file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
list.rs | /* Copyright 2016 Jordan Miner
*
* Licensed under the MIT license <LICENSE or
* http://opensource.org/licenses/MIT>. This file may not be copied,
* modified, or distributed except according to those terms.
*/
use super::control_prelude::*;
use attributes::set_attribute_ptr;
use std::ffi::CStr;
#[derive(Clone)]
p... | else { "NO\0" });
self
}
// An `index` of 0 is the first item.
pub fn item(&self, index: usize) -> String {
get_str_attribute(self.handle(), &format!("{}\0", index + 1))
}
// An `index` of 0 is the first item.
pub fn set_item(&self, index: usize, text: &str) -> &Self {
... | { "YES\0" } | conditional_block |
list.rs | /* Copyright 2016 Jordan Miner
*
* Licensed under the MIT license <LICENSE or
* http://opensource.org/licenses/MIT>. This file may not be copied,
* modified, or distributed except according to those terms.
*/
use super::control_prelude::*;
use attributes::set_attribute_ptr;
use std::ffi::CStr;
#[derive(Clone)]
p... | (&self, index: usize) -> String {
get_str_attribute(self.handle(), &format!("{}\0", index + 1))
}
// An `index` of 0 is the first item.
pub fn set_item(&self, index: usize, text: &str) -> &Self {
set_str_attribute(self.handle(), &format!("{}\0", index + 1), text);
self
}
pu... | item | identifier_name |
list.rs | /* Copyright 2016 Jordan Miner
*
* Licensed under the MIT license <LICENSE or
* http://opensource.org/licenses/MIT>. This file may not be copied,
* modified, or distributed except according to those terms.
*/
use super::control_prelude::*;
use attributes::set_attribute_ptr;
use std::ffi::CStr;
#[derive(Clone)]
p... |
pub fn set_dropdown(&self, dropdown: bool) -> &Self {
set_str_attribute(self.handle(), "DROPDOWN\0", if dropdown { "YES\0" } else { "NO\0" });
self
}
pub fn edit_box(&self) -> bool {
unsafe {
get_str_attribute_slice(self.handle(), "EDITBOX\0") == "YES"
}
}
... | {
unsafe {
get_str_attribute_slice(self.handle(), "DROPDOWN\0") == "YES"
}
} | identifier_body |
list.rs | /* Copyright 2016 Jordan Miner
*
* Licensed under the MIT license <LICENSE or
* http://opensource.org/licenses/MIT>. This file may not be copied,
* modified, or distributed except according to those terms.
*/
use super::control_prelude::*;
use attributes::set_attribute_ptr;
use std::ffi::CStr;
#[derive(Clone)]
p... | set_str_attribute(self.handle(), &format!("INSERTITEM{}\0", index + 1), text);
self
}
// An `index` of 0 is the first item.
pub fn remove_item(&self, index: usize) -> &Self {
set_str_attribute(self.handle(), "REMOVEITEM\0", &format!("{}\0", index + 1));
self
}
pub f... | pub fn insert_item(&self, index: usize, text: &str) -> &Self { | random_line_split |
csv_user_import_mappings.py | from knowledgebase.models import ArticleCategory
def transform_category(value):
try:
return ArticleCategory.objects.get(name=value)
except ArticleCategory.DoesNotExist:
raise ValueError("Could not find category with name: %s" % value)
def transform_preferred_signpost(value):
value_normal... |
return value_normalised == "true"
TELEPHONE_COLUMN_FIELD_MAPPING = [
[(19, "name"), (20, "number")],
[(21, "name"), (22, "number")],
[(23, "name"), (24, "number")],
[(25, "name"), (26, "number")],
]
ARTICLE_COLUMN_FIELD_MAPPING = [
(0, "pk"),
(1, "created"),
(2, "modified"),
(3, ... | raise ValueError("%s is an invalid value for Preferred signpost" % value) | conditional_block |
csv_user_import_mappings.py | from knowledgebase.models import ArticleCategory
def transform_category(value):
|
def transform_preferred_signpost(value):
value_normalised = value.lower()
if value_normalised not in ["true", "false"]:
raise ValueError("%s is an invalid value for Preferred signpost" % value)
return value_normalised == "true"
TELEPHONE_COLUMN_FIELD_MAPPING = [
[(19, "name"), (20, "number"... | try:
return ArticleCategory.objects.get(name=value)
except ArticleCategory.DoesNotExist:
raise ValueError("Could not find category with name: %s" % value) | identifier_body |
csv_user_import_mappings.py | from knowledgebase.models import ArticleCategory
| try:
return ArticleCategory.objects.get(name=value)
except ArticleCategory.DoesNotExist:
raise ValueError("Could not find category with name: %s" % value)
def transform_preferred_signpost(value):
value_normalised = value.lower()
if value_normalised not in ["true", "false"]:
rai... | def transform_category(value): | random_line_split |
csv_user_import_mappings.py | from knowledgebase.models import ArticleCategory
def | (value):
try:
return ArticleCategory.objects.get(name=value)
except ArticleCategory.DoesNotExist:
raise ValueError("Could not find category with name: %s" % value)
def transform_preferred_signpost(value):
value_normalised = value.lower()
if value_normalised not in ["true", "false"]:
... | transform_category | identifier_name |
config.rs | //! Create and define the main configuration through toml files and command line args
pub mod components;
pub mod styling;
use components::*;
use crate::common::Result;
use async_std::fs;
use async_std::os::unix::io::AsRawFd;
use async_std::sync::Arc;
use serde::Deserialize;
use std::fs::File;
use std::io::Read;
us... | (&self, file_path: &str) -> Result<String> {
let mut file = File::open(file_path)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
}
| read_file | identifier_name |
config.rs | //! Create and define the main configuration through toml files and command line args
pub mod components;
pub mod styling;
use components::*;
use crate::common::Result;
use async_std::fs;
use async_std::os::unix::io::AsRawFd;
use async_std::sync::Arc;
use serde::Deserialize;
use std::fs::File;
use std::io::Read;
us... |
Err(_) => log::trace!("Failed to load contents from $HOME/.config/scout.toml"),
};
};
};
self
}
/// Read configuration from the given path
pub fn from_file<'a>(&'a mut self, file_path: &str) -> &'a mut Self {
match self.read_file(fil... | {
self.from_toml(&contents);
} | conditional_block |
config.rs | //! Create and define the main configuration through toml files and command line args
pub mod components;
pub mod styling;
use components::*;
use crate::common::Result;
use async_std::fs;
use async_std::os::unix::io::AsRawFd;
use async_std::sync::Arc;
use serde::Deserialize;
use std::fs::File;
use std::io::Read;
us... |
fn read_file(&self, file_path: &str) -> Result<String> {
let mut file = File::open(file_path)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
}
| {
match self.config.take() {
Some(config) => Arc::new(config),
None => Default::default(),
}
} | identifier_body |
config.rs | //! Create and define the main configuration through toml files and command line args
pub mod components;
pub mod styling;
use components::*;
use crate::common::Result;
use async_std::fs;
use async_std::os::unix::io::AsRawFd;
use async_std::sync::Arc;
use serde::Deserialize;
use std::fs::File;
use std::io::Read; | #[derive(Debug, Default)]
pub struct Args {
// flags
pub full_screen: bool,
pub inline: bool,
// options
pub lines: Option<usize>,
pub config: Option<String>,
pub search: Option<String>,
}
/// Arc version of Cfg
pub type Config = Arc<Cfg>;
/// Main configuration structure
#[derive(Deseria... |
use crate::terminal_size::terminal_size;
| random_line_split |
cog_utils.py | from abc import ABC
from typing import Final
from base64 import b64decode
from io import BytesIO
import struct
from redbot import VersionInfo
from redbot.core import commands
from ..converters import get_lazy_converter, get_playlist_converter
__version__ = VersionInfo.from_json({"major": 2, "minor": 4, "micro": 0, "... |
self.write_unsigned_short(byte_len)
self._write(utf)
def finish(self):
with BytesIO() as track_buf:
byte_len = self._buf.getbuffer().nbytes
flags = byte_len | (1 << 30)
enc_flags = struct.pack(">i", flags)
track_buf.write(enc_flags)
... | raise OverflowError("UTF string may not exceed 65535 bytes!") | conditional_block |
cog_utils.py | from abc import ABC
from typing import Final
from base64 import b64decode
from io import BytesIO
import struct
from redbot import VersionInfo
from redbot.core import commands
from ..converters import get_lazy_converter, get_playlist_converter
__version__ = VersionInfo.from_json({"major": 2, "minor": 4, "micro": 0, "... | self.write_unsigned_short(byte_len)
self._write(utf)
def finish(self):
with BytesIO() as track_buf:
byte_len = self._buf.getbuffer().nbytes
flags = byte_len | (1 << 30)
enc_flags = struct.pack(">i", flags)
track_buf.write(enc_flags)
... |
if byte_len > 65535:
raise OverflowError("UTF string may not exceed 65535 bytes!")
| random_line_split |
cog_utils.py | from abc import ABC
from typing import Final
from base64 import b64decode
from io import BytesIO
import struct
from redbot import VersionInfo
from redbot.core import commands
from ..converters import get_lazy_converter, get_playlist_converter
__version__ = VersionInfo.from_json({"major": 2, "minor": 4, "micro": 0, "... | (self):
self._buf = BytesIO()
def _write(self, data):
self._buf.write(data)
def write_byte(self, byte):
self._buf.write(byte)
def write_boolean(self, b):
enc = struct.pack("B", 1 if b else 0)
self.write_byte(enc)
def write_unsigned_short(self, s):
enc ... | __init__ | identifier_name |
cog_utils.py | from abc import ABC
from typing import Final
from base64 import b64decode
from io import BytesIO
import struct
from redbot import VersionInfo
from redbot.core import commands
from ..converters import get_lazy_converter, get_playlist_converter
__version__ = VersionInfo.from_json({"major": 2, "minor": 4, "micro": 0, "... |
# Both DataReader and DataWriter are taken from https://github.com/Devoxin/Lavalink.py/blob/master/lavalink/datarw.py
# These are licenced under MIT, Thanks Devoxin for putting these together!
# The license can be found in https://github.com/Devoxin/Lavalink.py/blob/master/LICENSE
class DataReader:
def __init_... | """
This allows the metaclass used for proper type detection to
coexist with discord.py's metaclass
"""
pass | identifier_body |
utils.rs | use config::*;
use env_logger;
use std::io::{BufReader, BufWriter};
use std::sync::Arc; | use std::sync::atomic::AtomicBool;
use vm::VM;
use vm::memory::Memory;
macro_rules! to_hex {
($data:expr, Word) => {
format!("0x{:04x}", $data)
};
($data:expr) => {
format!("0x{:02x}", $data)
};
}
pub fn data_to_hex(data: DataSlice) -> String {
data.iter()
.map(|i| to_hex!(i))
... | random_line_split | |
utils.rs | use config::*;
use env_logger;
use std::io::{BufReader, BufWriter};
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use vm::VM;
use vm::memory::Memory;
macro_rules! to_hex {
($data:expr, Word) => {
format!("0x{:04x}", $data)
};
($data:expr) => {
format!("0x{:02x}", $data)
};
}
pub fn | (data: DataSlice) -> String {
data.iter()
.map(|i| to_hex!(i))
.collect::<Vec<String>>()
.join(" ")
}
pub fn test_run(input: DataSlice,
mut executable: Data,
data_size: Word)
-> (Data, VM<BufReader<DataSlice>, BufWriter<Data>>) {
let _ = e... | data_to_hex | identifier_name |
utils.rs | use config::*;
use env_logger;
use std::io::{BufReader, BufWriter};
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use vm::VM;
use vm::memory::Memory;
macro_rules! to_hex {
($data:expr, Word) => {
format!("0x{:04x}", $data)
};
($data:expr) => {
format!("0x{:02x}", $data)
};
}
pub fn ... | .collect::<Data>();
(output, vm)
}
| {
let _ = env_logger::init();
let code_size = executable.len() as Word - CODE_OFFSET - data_size;
Memory::write_word(&mut executable, 0, code_size);
let input = BufReader::new(input);
let output: Data = vec![];
let output = BufWriter::new(output);
let termination_scheduled = Arc::new(Ato... | identifier_body |
CustomBgStylesheet.js | define(['tantaman/web/css_manip/CssManip'],
function(CassManip) {
var el = CassManip.getStyleElem({
id: 'customBackgrounds',
create: true
});
/**
* This is essentially a view class that
* render the stylesheet of background classes whenever
* new background classes are created.
*
* @param {EditorModel... |
CustomBgStylesheet.prototype = {
/**
* render the stylesheet. Should never
* need to be called explicitly.
*/
render: function(m, customBgs) {
if (!customBgs) return;
el.innerHTML =
JST['strut.presentation_generator/CustomBgStylesheet'](customBgs.get('bgs'));
},
/**
* Unregister from... | {
this.model = editorModel;
editorModel.on('change:customBackgrounds', this.render, this);
} | identifier_body |
CustomBgStylesheet.js | define(['tantaman/web/css_manip/CssManip'],
function(CassManip) {
var el = CassManip.getStyleElem({
id: 'customBackgrounds',
create: true
});
/**
* This is essentially a view class that
* render the stylesheet of background classes whenever
* new background classes are created.
*
* @param {EditorModel... | (editorModel) {
this.model = editorModel;
editorModel.on('change:customBackgrounds', this.render, this);
}
CustomBgStylesheet.prototype = {
/**
* render the stylesheet. Should never
* need to be called explicitly.
*/
render: function(m, customBgs) {
if (!customBgs) return;
el.innerHTML =
... | CustomBgStylesheet | identifier_name |
CustomBgStylesheet.js | define(['tantaman/web/css_manip/CssManip'],
function(CassManip) {
var el = CassManip.getStyleElem({
id: 'customBackgrounds',
create: true
});
/**
* This is essentially a view class that
* render the stylesheet of background classes whenever
* new background classes are created.
*
* @param {EditorModel... | /**
* render the stylesheet. Should never
* need to be called explicitly.
*/
render: function(m, customBgs) {
if (!customBgs) return;
el.innerHTML =
JST['strut.presentation_generator/CustomBgStylesheet'](customBgs.get('bgs'));
},
/**
* Unregister from the model so this component
* ca... | }
CustomBgStylesheet.prototype = { | random_line_split |
index.d.ts | import { AbstractPlugin, Animation, ExtendedPosition, Viewer } from '../..';
import { Event } from 'uevent';
export type MarkerType =
'image'
| 'imageLayer'
| 'html'
| 'square'
| 'rect'
| 'circle'
| 'ellipse'
| 'path'
| 'polygonPx'
| 'polygonRad'
| 'polylinePx'
| 'polylineRad';
/**
* @summary... | /**
* @summary Triggered when a marker is selected from the side panel
*/
on(e: 'select-marker-list', cb: (e: Event, marker: Marker) => void): this;
/**
* @summary Triggered when a marker was selected and the user clicks elsewhere
*/
on(e: 'unselect-marker', cb: (e: Event, marker: Marker) => void):... | * with {@link MarkersPlugin.getCurrentMarker}
*/
on(e: 'select-marker', cb: (e: Event, marker: Marker, data: SelectMarkerData) => void): this;
| random_line_split |
index.d.ts | import { AbstractPlugin, Animation, ExtendedPosition, Viewer } from '../..';
import { Event } from 'uevent';
export type MarkerType =
'image'
| 'imageLayer'
| 'html'
| 'square'
| 'rect'
| 'circle'
| 'ellipse'
| 'path'
| 'polygonPx'
| 'polygonRad'
| 'polylinePx'
| 'polylineRad';
/**
* @summary... | extends AbstractPlugin {
constructor(psv: Viewer, options: MarkersPluginOptions);
/**
* @summary Toggles the visibility of all tooltips
*/
toggleAllTooltips();
/**
* @summary Displays all tooltips
*/
showAllTooltips();
/**
* @summary Hides all tooltips
*/
hideAllTooltips();
/**
... | MarkersPlugin | identifier_name |
configtest.py | #!/usr/bin/python
#
# Config file test app (together with test.cfg file)
#
import os, sys
| cfg = configfile.ConfigFile("test.cfg")
cfg.setCfgValue("name1", "value1")
cfg.setCfgValue("name2", "value2")
cfg.selectSection("user")
cfg.setCfgValue("username", "janis")
cfg.setCfgValue("acceptable_names", ["john", "janis"])
cfg.load()
print cfg.cfg.options("main")
print cfg.cfg.options("user")
print cfg.getCfgVal... | sys.path.append("..")
import configfile
| random_line_split |
scryptsalsa208sha256.rs | c_serialize;
pub const SALTBYTES: usize = ffi::crypto_pwhash_scryptsalsa208sha256_SALTBYTES;
pub const STRBYTES: usize = ffi::crypto_pwhash_scryptsalsa208sha256_STRBYTES;
pub const STRPREFIX: &'static str = ffi::crypto_pwhash_scryptsalsa208sha256_STRPREFIX;
pub const OPSLIMIT_INTERACTIVE: OpsLimit =
OpsLimit(ffi::... | else {
Err(())
}
}
/// The `pwhash()` returns a `HashedPassword` which
/// includes:
///
/// - the result of a memory-hard, CPU-intensive hash function applied to the password
/// `passwd`
/// - the automatically generated salt used for the
/// previous computation
/// - the other parameters required ... | {
Ok(key)
} | conditional_block |
scryptsalsa208sha256.rs | c_serialize;
pub const SALTBYTES: usize = ffi::crypto_pwhash_scryptsalsa208sha256_SALTBYTES;
pub const STRBYTES: usize = ffi::crypto_pwhash_scryptsalsa208sha256_STRBYTES;
pub const STRPREFIX: &'static str = ffi::crypto_pwhash_scryptsalsa208sha256_STRPREFIX;
pub const OPSLIMIT_INTERACTIVE: OpsLimit =
OpsLimit(ffi::... | () {
use randombytes::randombytes;
for i in (0..16usize) {
let mut pw = randombytes(i);
let pwh = pwhash(&pw, OPSLIMIT_INTERACTIVE, MEML | test_pwhash_verify_tamper | identifier_name |
scryptsalsa208sha256.rs | c_serialize;
pub const SALTBYTES: usize = ffi::crypto_pwhash_scryptsalsa208sha256_SALTBYTES;
pub const STRBYTES: usize = ffi::crypto_pwhash_scryptsalsa208sha256_STRBYTES;
pub const STRPREFIX: &'static str = ffi::crypto_pwhash_scryptsalsa208sha256_STRPREFIX;
pub const OPSLIMIT_INTERACTIVE: OpsLimit =
OpsLimit(ffi::... |
#[test]
fn test_pwhash_verify_tamper() {
use randombytes::randombytes;
for i in (0..16usize) {
let mut pw = randombytes(i);
let pwh = pwhash(&pw, OPSLIMIT_INTERACTIVE, ME | {
use randombytes::randombytes;
for i in (0..32usize) {
let pw = randombytes(i);
let pwh = pwhash(&pw, OPSLIMIT_INTERACTIVE, MEMLIMIT_INTERACTIVE).unwrap();
assert!(pwhash_verify(&pwh, &pw));
}
} | identifier_body |
scryptsalsa208sha256.rs | c_serialize;
pub const SALTBYTES: usize = ffi::crypto_pwhash_scryptsalsa208sha256_SALTBYTES;
pub const STRBYTES: usize = ffi::crypto_pwhash_scryptsalsa208sha256_STRBYTES;
pub const STRPREFIX: &'static str = ffi::crypto_pwhash_scryptsalsa208sha256_STRPREFIX;
pub const OPSLIMIT_INTERACTIVE: OpsLimit =
OpsLimit(ffi::... |
/// `pwhash_verify()` verifies that the password `str_` is a valid password
/// verification string (as generated by `pwhash()`) for `passwd`
///
/// It returns `true` if the verification succeeds, and `false` on error.
pub fn pwhash_verify(&HashedPassword(ref str_): &HashedPassword,
passwd: &[u8]... | random_line_split | |
PostCategory.ts | import {PrimaryGeneratedColumn, Column, Entity} from "../../../src/index";
import {Post} from "./Post";
import {ManyToMany} from "../../../src/decorator/relations/ManyToMany";
import {AfterRemove} from "../../../src/decorator/listeners/AfterRemove";
import {BeforeRemove} from "../../../src/decorator/listeners/BeforeRem... |
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@ManyToMany(type => Post, post => post.categories, {
cascadeInsert: true,
cascadeUpdate: true
})
posts: Post[] = [];
@BeforeInsert()
doSomethingBeforeInsertion() {
console.log(`event: PostCatego... | random_line_split | |
PostCategory.ts | import {PrimaryGeneratedColumn, Column, Entity} from "../../../src/index";
import {Post} from "./Post";
import {ManyToMany} from "../../../src/decorator/relations/ManyToMany";
import {AfterRemove} from "../../../src/decorator/listeners/AfterRemove";
import {BeforeRemove} from "../../../src/decorator/listeners/BeforeRem... | () {
console.log(`event: PostCategory "${this.name}" has been removed and callback executed`);
}
} | doSomethingAfterRemove | identifier_name |
PostCategory.ts | import {PrimaryGeneratedColumn, Column, Entity} from "../../../src/index";
import {Post} from "./Post";
import {ManyToMany} from "../../../src/decorator/relations/ManyToMany";
import {AfterRemove} from "../../../src/decorator/listeners/AfterRemove";
import {BeforeRemove} from "../../../src/decorator/listeners/BeforeRem... |
} | {
console.log(`event: PostCategory "${this.name}" has been removed and callback executed`);
} | identifier_body |
app.js | /*
The Quarry Desktop App
*/
angular
.module('quarrydesktop', ['quarry.core', 'quarry.ui', 'quarry.app.digger'])
.config(['$stateProvider', '$routeProvider', '$urlRouterProvider',
function ($stateProvider, $routeProvider, $urlRouterProvider) {
$urlRouterProvider
//.when('/c?id', '/cont... | THE MAIN CONTROLLER
*/
.controller('MainCtrl', ['$scope', '$warehouse', '$location', '$digger', function($scope, $warehouse, $location, $digger){
/*
warehouse and user
*/
var warehouse = $scope.warehouse = $warehouse;
var user = $scope.user = $warehouse.user;
$s... | random_line_split | |
app.js | /*
The Quarry Desktop App
*/
angular
.module('quarrydesktop', ['quarry.core', 'quarry.ui', 'quarry.app.digger'])
.config(['$stateProvider', '$routeProvider', '$urlRouterProvider',
function ($stateProvider, $routeProvider, $urlRouterProvider) {
$urlRouterProvider
//.when('/c?id', '/cont... |
done(container);
},
/*
the blueprints we have for the digger
*/
baseblueprints:baseblueprints
})
/*
get the user loaded then assign the warehouse an ting
*/
$scope.init(function(warehouse){
/*
get connecte... | {
alert('blueprint')
} | conditional_block |
leap.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2018 David Arroyo Menéndez
# Author: David Arroyo Menéndez <davidam@gnu.org>
# Maintainer: David Arroyo Menéndez <davidam@gnu.org>
# This file is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as p... | lse:
print("{0} is not a leap year".format(year))
| nt("{0} is a leap year".format(year))
e | conditional_block |
leap.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2018 David Arroyo Menéndez
# Author: David Arroyo Menéndez <davidam@gnu.org>
# Maintainer: David Arroyo Menéndez <davidam@gnu.org>
# This file is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as p... | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with GNU Emacs; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
# Bos... | random_line_split | |
NativeSelect.js | import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import * as React from 'react';
import clsx from 'clsx';
import PropTypes from 'prop-types';
import NativeSelectInput from './NativeSelectInput';
import formControlState ... |
/**
* The icon that displays the arrow.
* @default ArrowDropDownIcon
*/
IconComponent: PropTypes.elementType,
/**
* An `Input` element; does not have to be a material-ui specific `Input`.
* @default <Input />
*/
input: PropTypes.element,
/**
* <a href="https://developer.mozilla.org/en-... | * @ignore
*/
className: PropTypes.string, | random_line_split |
render_file.rs | extern crate env_logger;
extern crate handlebars;
extern crate rustc_serialize;
use std::io::prelude::*;
use std::io;
use std::fs::File;
use std::path::Path;
use std::collections::BTreeMap;
use handlebars::{Handlebars, RenderError, RenderContext, Helper, Context};
use rustc_serialize::json::{Json, ToJson};
struct Te... | () -> BTreeMap<String, Json> {
let mut data = BTreeMap::new();
data.insert("year".to_string(), "2015".to_json());
let teams = vec![ Team { name: "Jiangsu Sainty".to_string(),
pts: 43u16 },
Team { name: "Beijing Guoan".to_string(),
... | make_data | identifier_name |
render_file.rs | extern crate env_logger;
extern crate handlebars; | extern crate rustc_serialize;
use std::io::prelude::*;
use std::io;
use std::fs::File;
use std::path::Path;
use std::collections::BTreeMap;
use handlebars::{Handlebars, RenderError, RenderContext, Helper, Context};
use rustc_serialize::json::{Json, ToJson};
struct Team {
name: String,
pts: u16
}
impl ToJson... | random_line_split | |
render_file.rs | extern crate env_logger;
extern crate handlebars;
extern crate rustc_serialize;
use std::io::prelude::*;
use std::io;
use std::fs::File;
use std::path::Path;
use std::collections::BTreeMap;
use handlebars::{Handlebars, RenderError, RenderContext, Helper, Context};
use rustc_serialize::json::{Json, ToJson};
struct Te... |
}
| {
println!("Failed to create target/table.html");
} | conditional_block |
test.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use super::*;
// Ensure serialization of MessagingProtocolVersion enum takes 1 byte.
#[test]
fn net_protocol() -> bcs::Result<()> {
let protocol = MessagingProtocolVersion::V1;
assert_eq!(bcs::to_bytes(&protocol)?, vec![0x00]);... | MessagingProtocolVersion::V1,
[ProtocolId::ConsensusRpc, ProtocolId::MempoolDirectSend]
.iter()
.into(),
);
let h2 = HandshakeMsg {
chain_id,
network_id: network_id.clone(),
supported_protocols,
};
assert_eq!(
(
Messagi... | {
let network_id = NetworkId::default();
let chain_id = ChainId::default();
let mut supported_protocols = BTreeMap::new();
supported_protocols.insert(
MessagingProtocolVersion::V1,
[ProtocolId::ConsensusRpc, ProtocolId::DiscoveryDirectSend]
.iter()
.into(),
);... | identifier_body |
test.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use super::*;
// Ensure serialization of MessagingProtocolVersion enum takes 1 byte.
#[test]
fn net_protocol() -> bcs::Result<()> {
let protocol = MessagingProtocolVersion::V1;
assert_eq!(bcs::to_bytes(&protocol)?, vec![0x00]);... | h1.perform_handshake(&h2).unwrap()
);
} | random_line_split | |
test.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use super::*;
// Ensure serialization of MessagingProtocolVersion enum takes 1 byte.
#[test]
fn net_protocol() -> bcs::Result<()> {
let protocol = MessagingProtocolVersion::V1;
assert_eq!(bcs::to_bytes(&protocol)?, vec![0x00]);... | () {
let mut handshake_msg = HandshakeMsg::new_for_testing();
handshake_msg.network_id = NetworkId::vfn_network();
// succeeds: Positive case
let h1 = handshake_msg.clone();
let h2 = handshake_msg.clone();
h1.perform_handshake(&h2).unwrap();
// fails: another private network
let mut h2... | represents_same_network | identifier_name |
index.d.ts | .name(params). Must be unique.
*/
key: string,
/**
* The Component to be displayed. Not required when defining a nested Scene, see example. If it is defined for 'container' scene, it will be used as custom container renderer
*/
component?: React.ReactNode,
/**
* Set to true if this i... | export var Actions: RNRFActions;
// ActionsConst
interface RNRFActionConst {
JUMP: string,
PUSH: string,
PUSH_OR_POP: string,
REPLACE: string,
BACK: string,
BACK_ACTION: string,
POP_AND_REPLACE: string,
POP_TO: string,
REFRESH: string,
RESET: string,
FOCUS: string,
... | random_line_split | |
index.d.ts | (params). Must be unique.
*/
key: string,
/**
* The Component to be displayed. Not required when defining a nested Scene, see example. If it is defined for 'container' scene, it will be used as custom container renderer
*/
component?: React.ReactNode,
/**
* Set to true if this is the... | extends React.Component<ModalProps, {}>{ }
// navbar
interface NavBarProps extends React.Props<NavBar> {
navigationState?: Object,
backButtonImage?: number,
backButtonTextStyle?: ReactNative.TextStyle,
leftButtonStyle?: ReactNative.ViewStyle
leftButtonIconStyle?: ReactNative.ImageStyle,
g... | Modal | identifier_name |
zhttpto.rs | //
// zhttpto.rs
//
// Starting code for PS1
// Running on Rust 0.9
//
// Note that this code has serious security risks! You should not run it
// on any system with access to sensitive files.
//
// University of Virginia - cs4414 Spring 2014
// Weilin Xu and David Evans
// Version 0.3
#[feature(globs)];
use std::i... |
};
});
}
println!("Connection terminates.");
}
}
}
}
| {
println("File does not exist. 404!.");
let no_such_file_string: ~str =
~"HTTP/1.1 404 Not Found\r\nContent-Type: text/html; charset=UTF-8\r\n\r\n
<doctype !html><html><head><title>Hello, ... | conditional_block |
zhttpto.rs | //
// zhttpto.rs
//
// Starting code for PS1
// Running on Rust 0.9
//
// Note that this code has serious security risks! You should not run it
// on any system with access to sensitive files.
//
// University of Virginia - cs4414 Spring 2014
// Weilin Xu and David Evans
// Version 0.3
#[feature(globs)];
use std::i... | stream.write(message_bytes);
}
None => {
println("File does not exist. 404!.");
let no_such_file_string: ~str =
~"HTTP/1.1 404 Not Fou... | Some(mut file) => {
let message_bytes: ~[u8] = file.read_to_end(); | random_line_split |
ScrollableTabBar.js | const React = require('react');
const { ViewPropTypes } = ReactNative = require('react-native');
const {
View,
Animated,
StyleSheet,
ScrollView,
Text,
Platform,
Dimensions,
I18nManager
} = ReactNative;
const Button = require('./Button');
//import { PropTypes } from 'react'
const WINDOW_WIDTH = Dimensi... | this.updateView({value: this.props.scrollValue._value, });
},
onContainerLayout(e) {
this._containerMeasurements = e.nativeEvent.layout;
this.updateView({value: this.props.scrollValue._value, });
},
});
module.exports = ScrollableTabBar;
const styles = StyleSheet.create({
tab: {
height: 49,
... | this.setState({ _containerWidth: width, }); | random_line_split |
ScrollableTabBar.js | const React = require('react');
const { ViewPropTypes } = ReactNative = require('react-native');
const {
View,
Animated,
StyleSheet,
ScrollView,
Text,
Platform,
Dimensions,
I18nManager
} = ReactNative;
const Button = require('./Button');
//import { PropTypes } from 'react'
const WINDOW_WIDTH = Dimensi... | (page, event) {
console.log("measureTab="+page+"layout "+JSON.stringify(event.nativeEvent.layout));
const { x, width, height, } = event.nativeEvent.layout;
this._tabsMeasurements[page] = {left: x, right: x + width, width, height, };
this.updateView({value: this.props.scrollValue._value, });
},
rend... | measureTab | identifier_name |
ScrollableTabBar.js | const React = require('react');
const { ViewPropTypes } = ReactNative = require('react-native');
const {
View,
Animated,
StyleSheet,
ScrollView,
Text,
Platform,
Dimensions,
I18nManager
} = ReactNative;
const Button = require('./Button');
//import { PropTypes } from 'react'
const WINDOW_WIDTH = Dimensi... |
},
necessarilyMeasurementsCompleted(position, isLastTab) {
return this._tabsMeasurements[position] &&
(isLastTab || this._tabsMeasurements[position + 1]) &&
this._tabContainerMeasurements &&
this._containerMeasurements;
},
updateTabPanel(position, pageOffset) {
const containerWidth ... | {
this.updateTabPanel(position, pageOffset);
this.updateTabUnderline(position, pageOffset, tabCount);
} | conditional_block |
ScrollableTabBar.js | const React = require('react');
const { ViewPropTypes } = ReactNative = require('react-native');
const {
View,
Animated,
StyleSheet,
ScrollView,
Text,
Platform,
Dimensions,
I18nManager
} = ReactNative;
const Button = require('./Button');
//import { PropTypes } from 'react'
const WINDOW_WIDTH = Dimensi... | ,
});
module.exports = ScrollableTabBar;
const styles = StyleSheet.create({
tab: {
height: 49,
alignItems: 'center',
justifyContent: 'center',
paddingLeft: 20,
paddingRight: 20,
},
container: {
height: 50,
borderWidth: 1,
borderTopWidth: 0,
borderLeftWidth: 0,
borderRight... | {
this._containerMeasurements = e.nativeEvent.layout;
this.updateView({value: this.props.scrollValue._value, });
} | identifier_body |
FaceDetector.py | import cv2
import numpy as np
import os
from vilay.core.Descriptor import MediaTime, Shape
from vilay.detectors.IDetector import IDetector
from vilay.core.DescriptionScheme import DescriptionScheme
class FaceDetector(IDetector):
def getName(self):
return "Face Detector"
def initialize(self):... | [x,y,width,height] = faces[faceIdx,:]
ds = DescriptionScheme('RTI', 'Face Detector')
region = Shape('Face Detector','rect', np.array([[x, y], [x + width, y + height]]))
mediaTime = MediaTime('Face Detector', frameIdx, 1)
... | conditional_block | |
FaceDetector.py | import cv2
import numpy as np
import os
from vilay.core.Descriptor import MediaTime, Shape
from vilay.detectors.IDetector import IDetector
from vilay.core.DescriptionScheme import DescriptionScheme
class FaceDetector(IDetector):
| # create ds and add time and shape descriptor
for faceIdx in range(len(faces)):
[x,y,width,height] = faces[faceIdx,:]
ds = DescriptionScheme('RTI', 'Face Detector')
region = Shape('Face Detector','rect', np... | def getName(self):
return "Face Detector"
def initialize(self):
# define haar-detector file
print os.getcwd() + '/vilay/detectors/FaceDetector/haarcascade_frontalface_default.xml'
self.cascade = cv2.CascadeClassifier(os.getcwd() + '/vilay/detectors/FaceDetector/haarcascade_front... | identifier_body |
FaceDetector.py | import cv2
import numpy as np
import os
from vilay.core.Descriptor import MediaTime, Shape
from vilay.detectors.IDetector import IDetector
from vilay.core.DescriptionScheme import DescriptionScheme
class FaceDetector(IDetector):
def getName(self):
return "Face Detector"
def | (self):
# define haar-detector file
print os.getcwd() + '/vilay/detectors/FaceDetector/haarcascade_frontalface_default.xml'
self.cascade = cv2.CascadeClassifier(os.getcwd() + '/vilay/detectors/FaceDetector/haarcascade_frontalface_default.xml')
def detect(self, mediaTimes, tgtDS, film, r... | initialize | identifier_name |
FaceDetector.py | import cv2
import numpy as np
import os
from vilay.core.Descriptor import MediaTime, Shape
from vilay.detectors.IDetector import IDetector
from vilay.core.DescriptionScheme import DescriptionScheme
class FaceDetector(IDetector):
def getName(self):
return "Face Detector"
def initialize(self):... |
def detect(self, mediaTimes, tgtDS, film, rootDS, mainGUI):
for mediaTime in mediaTimes:
for frameIdx in range(mediaTime.startTime, mediaTime.startTime + mediaTime.duration):
actFrame = film.getFrame(frameIdx)
# preprocessing
... | print os.getcwd() + '/vilay/detectors/FaceDetector/haarcascade_frontalface_default.xml'
self.cascade = cv2.CascadeClassifier(os.getcwd() + '/vilay/detectors/FaceDetector/haarcascade_frontalface_default.xml') | random_line_split |
base.js | // Using jquery solution
// (function(){
// app.el['input_city'] = $('input[bs-typeahead="listCity"]'); | // app.mapped[object.city] = object;
// objects.push(object.city);
// });
// process(objects);
// },
// updater: function(item) {
// // $("ul.typeahead.dropdown-menu:visible").siblings("input[type='hidden']").val(app.mapped[item].id);
// this.$element.siblings... |
// app.el['input_city'].typeahead({
// source: function(query, process) {
// var objects = [], data = [{"id":1, "city":"London"},{"id":2, "city":"Madrid"},{"id":3, "city":"Paris"}]
// $.each(data, function(i, object) { | random_line_split |
DAQmxDO.py | """
DAQmxDO.py
Part of the AQuA Cesium Controller software package
author=Martin Lichtman
created=2013-10-19
modified>=2015-05-24
This file holds everything to model a National Instruments DAQmx pulse output. It communicated to LabView via the higher up LabView class.
"""
from __future__ import division
__author__ ... | if self.enable and (len(self.indices)>0):
waveformXML = ('<waveform>'+
'<name>'+self.name+'</name>'+
'<transitions>'+' '.join([str(time) for time in self.indices])+'</transitions>'+
'<states>'+'\n'.join([' '.join([str(sample) for sample in state]) for state in... | identifier_body | |
DAQmxDO.py | """
DAQmxDO.py
Part of the AQuA Cesium Controller software package
author=Martin Lichtman
created=2013-10-19
modified>=2015-05-24
This file holds everything to model a National Instruments DAQmx pulse output. It communicated to LabView via the higher up LabView class.
"""
from __future__ import division
__author__ ... |
def toHardware(self):
# Check that there is some DAQmx data to send, otherwise disable the instrument
if self.enable and (len(self.indices)>0):
waveformXML = ('<waveform>'+
'<name>'+self.name+'</name>'+
'<transitions>'+' '.join([str(time) for time in sel... | self.times = np.zeros(0, dtype=np.float64)
self.time_durations = np.zeros(0, dtype=np.float64)
self.indices = np.zeros(0, dtype=np.uint64)
self.states = np.zeros((0, self.numChannels), dtype=np.bool) | conditional_block |
DAQmxDO.py | """
DAQmxDO.py
Part of the AQuA Cesium Controller software package
author=Martin Lichtman
created=2013-10-19
modified>=2015-05-24
This file holds everything to model a National Instruments DAQmx pulse output. It communicated to LabView via the higher up LabView class.
"""
from __future__ import division
__author__ ... | (self):
if self.transition_list:
# put all the transitions that have been stored together into one big list
# convert the float time to an integer number of samples
indices = np.rint(np.array([i[0] for i in self.transition_list], dtype=np.float64)*self.clockRate.value*self.un... | parse_transition_list | identifier_name |
DAQmxDO.py | """
DAQmxDO.py
Part of the AQuA Cesium Controller software package
author=Martin Lichtman
created=2013-10-19
modified>=2015-05-24
This file holds everything to model a National Instruments DAQmx pulse output. It communicated to LabView via the higher up LabView class.
"""
from __future__ import division
__author__ ... | index_list = np.zeros(1, dtype=np.uint64)
state_list = np.zeros((1, self.numChannels), dtype=np.bool)
# sort the transitions time. If there is a tie, preserve the order.
# mergesort is slower than the default quicksort, but it is 'stable' which means items of the same v... | # These arrays will be appended to to increase their size as we go along. | random_line_split |
mail_utils.py | import smtplib
from email.mime.text import MIMEText
from django.core.mail import EmailMultiAlternatives
from django.conf import settings
def send_message(message):
"""
* desc 快捷发送邮件
* input 要发送的邮件信息
* output None
"""
mail_handler = SendMail()
mail_handler.send_mail(settings.REPORT_US... | print(to)
content_msg = EmailMultiAlternatives(
subject, text_content, from_email, to)
html_content = u'<b>' + msg + '</b>'
content_msg.attach_alternative(html_content, 'text/html')
content_msg.send()
return 0
except:
... | om" for user in to_user.split(',')]
| conditional_block |
mail_utils.py | import smtplib
from email.mime.text import MIMEText
from django.core.mail import EmailMultiAlternatives
from django.conf import settings
def send_message(message):
"""
* desc 快捷发送邮件
* input 要发送的邮件信息
* output None
"""
mail_handler = SendMail()
mail_handler.send_mail(settings.REPORT_US... | * output 0 发送成功 1 发送失败
"""
subject = settings.MSUBMAIL
if error:
text_content = 'Virtual Manager Error'
else:
text_content = 'Virtual Manager Warning'
from_email = settings.FMAIL
try:
to = [str(user) + "@hujiang.com" for user in ... | identifier_body | |
mail_utils.py | import smtplib
from email.mime.text import MIMEText
from django.core.mail import EmailMultiAlternatives
from django.conf import settings
def send_message(message):
"""
* desc 快捷发送邮件
* input 要发送的邮件信息
* output None
"""
mail_handler = SendMail()
mail_handler.send_mail(settings.REPORT_US... | t, file_info, file_name):
# 发送附件的方法
part = MIMEApplication(file_info)
part.add_header('Content-Disposition',
'attachment', filename=file_name)
msg.attach(part)
sender = self.mail_host_user
msg['Subject'] = subject
msg['From'] = sender
... | r_list, subjec | identifier_name |
mail_utils.py | import smtplib
from email.mime.text import MIMEText
from django.core.mail import EmailMultiAlternatives
from django.conf import settings
def send_message(message):
"""
* desc 快捷发送邮件
* input 要发送的邮件信息
* output None
"""
mail_handler = SendMail()
mail_handler.send_mail(settings.REPORT_US... | def smtp_login(self):
# login the host
self.smtp.connect(self.mail_host)
self.smtp.login(self.mail_host_user, self.mail_host_pwd)
def send_file_mail(self, receiver_list, subject, file_info, file_name):
# 发送附件的方法
part = MIMEApplication(file_info)
part.add_header('... | self.mail_host_pwd = settings.MAIL_HOST_PWD
self.smtp = smtplib.SMTP()
self.smtp_login()
| random_line_split |
views.py | from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.core.paginator import Paginator
from uwcs_website.choob.models import *
def quotes_page(request):
quoters = map(lambda q:q[0],QuoteObject.objects.all().values_list('quoter').distinct())
quoted = map(lambda... |
def all_quotes(request,page_num):
paginator = Paginator(QuoteObject.objects.all(),PER_PAGE)
return render_to_response('choob/quote_list.html',{
'breadcrumbs': [('/','home'),('/irc/','irc'),('/irc/all_quotes/1/','all')],
'user':request.user,
'page':paginator.page(page_num),
})
# th... | '''
Generic quotes controller for making lists of quotes
type(f) = String -> [QuoteObject]
'''
if request.method == 'POST':
val = request.POST['val']
paginator = Paginator(f(val),PER_PAGE)
return render_to_response('choob/quote_list.html',{
'breadcrumbs': [('/','home'... | identifier_body |
views.py | from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.core.paginator import Paginator
from uwcs_website.choob.models import *
def quotes_page(request):
quoters = map(lambda q:q[0],QuoteObject.objects.all().values_list('quoter').distinct())
quoted = map(lambda... |
else:
return HttpResponseRedirect('/irc/all_quotes/')
def all_quotes(request,page_num):
paginator = Paginator(QuoteObject.objects.all(),PER_PAGE)
return render_to_response('choob/quote_list.html',{
'breadcrumbs': [('/','home'),('/irc/','irc'),('/irc/all_quotes/1/','all')],
'user':r... | val = request.POST['val']
paginator = Paginator(f(val),PER_PAGE)
return render_to_response('choob/quote_list.html',{
'breadcrumbs': [('/','home'),('/irc/','irc')],
'user':request.user,
'page':paginator.page(page_num),
'value':val,
'url':url,
... | conditional_block |
views.py | from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.core.paginator import Paginator
from uwcs_website.choob.models import *
def quotes_page(request):
quoters = map(lambda q:q[0],QuoteObject.objects.all().values_list('quoter').distinct())
quoted = map(lambda... |
def all_quotes(request,page_num):
paginator = Paginator(QuoteObject.objects.all(),PER_PAGE)
return render_to_response('choob/quote_list.html',{
'breadcrumbs': [('/','home'),('/irc/','irc'),('/irc/all_quotes/1/','all')],
'user':request.user,
'page':paginator.page(page_num),
})
# thi... | 'value':val,
'url':url,
})
else:
return HttpResponseRedirect('/irc/all_quotes/') | random_line_split |
views.py | from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.core.paginator import Paginator
from uwcs_website.choob.models import *
def quotes_page(request):
quoters = map(lambda q:q[0],QuoteObject.objects.all().values_list('quoter').distinct())
quoted = map(lambda... | (request,page_num,url,f):
'''
Generic quotes controller for making lists of quotes
type(f) = String -> [QuoteObject]
'''
if request.method == 'POST':
val = request.POST['val']
paginator = Paginator(f(val),PER_PAGE)
return render_to_response('choob/quote_list.html',{
... | quotes_f | identifier_name |
tdf006_ranges.py | ## \file
## \ingroup tutorial_tdataframe
## \notebook -nodraw
## This tutorial shows how to express the concept of ranges when working with the TDataFrame.
## \macro_code
##
## \date March 2017
## \author Danilo Piparo
import ROOT
fill_tree_code = '''
void fill_tree(const char *filename, const char *treeName)
{
TF... | t.Branch("b2", &b2);
for (int i = 0; i < 100; ++i) {
b1 = i;
b2 = i * i;
t.Fill();
}
t.Write();
f.Close();
return;
}
'''
# We prepare an input tree to run on
fileName = "tdf006_ranges_py.root"
treeName = "myTree"
ROOT.gInterpreter.Declare(fill_tree_code)
ROOT.fill_tree(fileName, tre... | random_line_split | |
posts.js | import { createAction } from 'redux-actions';
export const getPosts = createAction('GET_POSTS', () => {
return {
promise: fetch('/api/posts', {
method: 'get'
})
};
});
export const getCategories = createAction('GET_CATEGORIES', () => {
return {
promise: fetch('/api/post... | promise: fetch('/api/posts', {
method: 'post'
})
};
});
export const createCategory = createAction('CREATE_CATEGORY', () => {
return {
promise: fetch('/api/posts/categories', {
method: 'post'
})
};
});
export const createAuthor = createAction('CREATE... | random_line_split | |
char.rs | .
///
/// # Panics
///
/// Panics if given a radix > 36.
///
/// # Examples
///
/// ```
/// let c = '1';
///
/// assert!(c.is_digit(10));
///
/// assert!('f'.is_digit(16));
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[inline]
pub fn is_digit... | nue(self) -> bo | identifier_name | |
char.rs | ///
/// ```
/// for c in '❤'.escape_unicode() {
/// print!("{}", c);
/// }
/// println!("");
/// ```
///
/// This prints:
///
/// ```text
/// \u{2764}
/// ```
///
/// Collecting into a `String`:
///
/// ```
/// let heart: String = '❤'.escape_unico... | lf.is_alphabetic() || self.is_numeric()
}
/// In | identifier_body | |
char.rs | /// let mut b = [0; 2];
///
/// let result = 'ß'.encode_utf8(&mut b);
///
/// assert_eq!(result, Some(2));
/// ```
///
/// A buffer that's too small:
///
/// ```
/// # #![feature(unicode)]
/// let mut b = [0; 1];
///
/// let result = 'ß'.encode_utf8(&mut b);
///
... | ///
/// # Examples
/// | random_line_split | |
CheckPartitioning.py | ###############################################################################
# #
# Copyright 2019. Triad National Security, LLC. All rights reserved. #
# This program was produced under U.S. Government contract 89233218CNA000001 #
... | self.guidance = ['CCE 14161-4', 'CCE 14777-7', 'CCE 14011-1',
'CCE 14171-3', 'CCE 14559-9']
self.applicable = {'type': 'black',
'family': ['darwin']}
self.hasrunalready = False
self.auditonly = True
def report(self):
"""Ch... | """
private method to initialize the module
:param config: configuration object instance
:param environ: environment object instance
:param logger: logdispatcher object instance
:param statechglogger: statechglogger object instance
"""
Rule.__init__(self, config... | identifier_body |
CheckPartitioning.py | ###############################################################################
# #
# Copyright 2019. Triad National Security, LLC. All rights reserved. #
# This program was produced under U.S. Government contract 89233218CNA000001 #
... | for line in fstabdata:
line = line.split()
self.logger.log(LogPriority.DEBUG, 'Processing: ' + str(line))
if len(line) > 0 and not re.search('^#', line[0]):
try:
# dev = line[0]
fsnode = line[... | random_line_split | |
CheckPartitioning.py | ###############################################################################
# #
# Copyright 2019. Triad National Security, LLC. All rights reserved. #
# This program was produced under U.S. Government contract 89233218CNA000001 #
... |
if not varlogauditcomp:
self.compliant = False
results = results + ' /var/log/audit'
if not vartmpcomp:
self.compliant = False
results = results + ' /var/tmp'
if not homecomp:
self.compliant = False
... | self.compliant = False
results = results + ' /var/log' | conditional_block |
CheckPartitioning.py | ###############################################################################
# #
# Copyright 2019. Triad National Security, LLC. All rights reserved. #
# This program was produced under U.S. Government contract 89233218CNA000001 #
... | (self):
"""CheckPartitioning.report(): produce a report on whether or not the
systems partitioning appears to follow best practices.
:return: self.compliant - True if compliant; False if not
:rtype: bool
"""
self.detailedresults = ""
self.compliant = True
... | report | identifier_name |
contact.py | from model.group_address import Address_data
import random
import string
import os.path
import jsonpickle
import getopt
import sys
try:
opts, args = getopt.getopt(sys.argv[1:], "n:f:", ["number of groups", "file"])
except getopt.GetoptError as err:
getopt.usage()
sys.exit(2)
n = 5
f = "data/contacts.json... | (maxlen):
numbers = string.digits + " "*2 + "(" + ")" + "-"
return "".join([random.choice(numbers) for x in range(maxlen)])
def random_mail(domen, maxlen):
value = string.ascii_letters + string.digits
return "".join([random.choice(value) for x in range(random.randrange(maxlen))]) + domen
testdata = ... | random_numbers | identifier_name |
contact.py | from model.group_address import Address_data
import random
import string
import os.path
import jsonpickle
import getopt
import sys
try:
opts, args = getopt.getopt(sys.argv[1:], "n:f:", ["number of groups", "file"])
except getopt.GetoptError as err:
getopt.usage()
sys.exit(2)
n = 5
f = "data/contacts.json... | ]
file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", f)
#with open(file, "w") as out:
# out.write(json.dumps(testdata, default=lambda x: x.__dict__, indent=2))
with open(file, "w") as out:
jsonpickle.set_encoder_options("json", indent=2)
out.write(jsonpickle.encode(testdata)) | random_line_split | |
contact.py | from model.group_address import Address_data
import random
import string
import os.path
import jsonpickle
import getopt
import sys
try:
opts, args = getopt.getopt(sys.argv[1:], "n:f:", ["number of groups", "file"])
except getopt.GetoptError as err:
getopt.usage()
sys.exit(2)
n = 5
f = "data/contacts.json... |
testdata = [
Address_data(firstname=random_string("firstname", 20), middlename=random_string("", 1),
lastname=random_string("lastname", 20), nickname=random_string("nickname", 20),
company=random_string("company", 20), address=random_string("address", 20),
home_... | value = string.ascii_letters + string.digits
return "".join([random.choice(value) for x in range(random.randrange(maxlen))]) + domen | identifier_body |
contact.py | from model.group_address import Address_data
import random
import string
import os.path
import jsonpickle
import getopt
import sys
try:
opts, args = getopt.getopt(sys.argv[1:], "n:f:", ["number of groups", "file"])
except getopt.GetoptError as err:
getopt.usage()
sys.exit(2)
n = 5
f = "data/contacts.json... |
elif o == "-f":
f = a
def random_string(prefix, maxlen):
symbols = string.ascii_letters + string.digits + " "*7
return prefix + "".join([random.choice(symbols) for x in range(random.randrange(maxlen))])
def random_numbers(maxlen):
numbers = string.digits + " "*2 + "(" + ")" + "-"
return... | n = int(a) | conditional_block |
index.js | import dude from 'debug-dude'
const { /*debug,*/ log, info /*, warn, error*/ } = dude('bot')
import { version } from '../package.json'
info(`jdnet bot v${version} starting`)
import config from '../config.json'
import { connect, message } from 'coffea'
const networks = connect(config)
import fs from 'fs'
import path... | networks.on('message', (evt, reply) => {
let video = evt.text.match(/#([a-zA-Z]+)/)
if (video && video.length > 1) {
reply({
type: 'sendVideo',
action: 'record_video',
id: evt.channel,
video: fs.createReadStream(path.join(__dirname, `video/${video[1]}.mp4`))
})}
})
networks.on('message', (evt,... | random_line_split | |
index.js | import dude from 'debug-dude'
const { /*debug,*/ log, info /*, warn, error*/ } = dude('bot')
import { version } from '../package.json'
info(`jdnet bot v${version} starting`)
import config from '../config.json'
import { connect, message } from 'coffea'
const networks = connect(config)
import fs from 'fs'
import path... |
})
networks.on('message', (evt, reply) => {
let pic = evt.text.match(/#([a-zA-Z]+)/)
if (pic && pic.length > 1) {
reply({
type: 'sendPhoto',
action: 'upload_photo',
id: evt.channel,
photo: fs.createReadStream(path.join(__dirname, `pic/etc/${pic[1]}.jpg`))
})}
})
| {
reply({
type: 'sendVideo',
action: 'record_video',
id: evt.channel,
video: fs.createReadStream(path.join(__dirname, `video/${video[1]}.mp4`))
})} | conditional_block |
mod.rs | //! Provides the trainers for the [Network][network].
//! [network]: ../network/index.html
//!
//! The optimal state of a neural network would be the one where
//! for any given input to the network, it would produce an output perfectly
//! matching the target function. In that state the loss function would have its
//... | // /// [1]: https://en.wikipedia.org/wiki/Backpropagation#Phase_2:_Weight_update
// ///
// /// Used by [step][2] to optimize the network.
// ///
// /// [2]: ./struct.Solver.html#method.step
// //
// // TODO: the actual update can probably be pulled out of this function,
// // since that ... | random_line_split | |
AuthPanel.js | import React from 'react'
import Button from './Button'
import { removeToken } from '../storages/SessionStorage'
export default (props) => {
const handleLogInClick = () => {
chrome.runtime.sendMessage({ action: 'vk_notification_auth' }, (response) => {
if (response.content == 'OK') {
if (props.afte... | {
button = <Button onClick={ handleLogInClick }>Войти</Button>
}
return props.hidden ? null : button
}
| {
button = <Button onClick={ handleLogOutClick }>Выйти</Button>
} else | conditional_block |
AuthPanel.js | import React from 'react'
import Button from './Button'
import { removeToken } from '../storages/SessionStorage'
| if (response.content == 'OK') {
if (props.afterLogInClick) {
props.afterLogInClick()
}
}
})
}
const handleLogOutClick = async () => {
try {
await removeToken()
if (props.afterLogOutClick) {
props.afterLogOutClick()
}
} catch (e) {
/*... | export default (props) => {
const handleLogInClick = () => {
chrome.runtime.sendMessage({ action: 'vk_notification_auth' }, (response) => { | random_line_split |
french.py | import re
"""Rules are based on Brunot & Bruneau (1949).
"""
estre_replace = [('^sereient$|^fussions$|^fussiens$|^sereies$|^sereiet$|^serïens$|^seriiez$|^fussiez$|^fussent$|^ierent$|^fustes$|^furent$|^ierent$|^sereie$|^seroie$|^sereit$|^seiens$|^seient$|^fusses$|^fussez$|^estant$|^seiens$|^somes$|^estes$|^ieres$|^ier... | :
return apply_rule(token)
| conditional_block | |
french.py | import re
"""Rules are based on Brunot & Bruneau (1949).
"""
estre_replace = [('^sereient$|^fussions$|^fussiens$|^sereies$|^sereiet$|^serïens$|^seriiez$|^fussiez$|^fussent$|^ierent$|^fustes$|^furent$|^ierent$|^sereie$|^seroie$|^sereit$|^seiens$|^seient$|^fusses$|^fussez$|^estant$|^seiens$|^somes$|^estes$|^ieres$|^ier... | rd):
return re.sub(pattern, replace, word)
return (matches_rule, apply_rule)
rules = [build_match_and_apply_functions(pattern, replace)
for (pattern, replace) in patterns]
def regex(token):
for matches_rule, apply_rule in rules:
if matches_rule(token):
return apply_rule... | rn, word)
def apply_rule(wo | identifier_body |
french.py | import re
"""Rules are based on Brunot & Bruneau (1949).
"""
estre_replace = [('^sereient$|^fussions$|^fussiens$|^sereies$|^sereiet$|^serïens$|^seriiez$|^fussiez$|^fussent$|^ierent$|^fustes$|^furent$|^ierent$|^sereie$|^seroie$|^sereit$|^seiens$|^seient$|^fusses$|^fussez$|^estant$|^seiens$|^somes$|^estes$|^ieres$|^ier... | ("m'", 'me'),
("t'", 'te'),
("l'", 'le'),
("qu'", "que")]
patterns = determiner_rules+misc_rules+auxiliary_rules+verbal_rules+french_nominal_rules+reduction_rules
def build_match_and_apply_functions(pattern, replace):
def matches_rule(w... | reduction_rules = [("d'", 'de'), | random_line_split |
french.py | import re
"""Rules are based on Brunot & Bruneau (1949).
"""
estre_replace = [('^sereient$|^fussions$|^fussiens$|^sereies$|^sereiet$|^serïens$|^seriiez$|^fussiez$|^fussent$|^ierent$|^fustes$|^furent$|^ierent$|^sereie$|^seroie$|^sereit$|^seiens$|^seient$|^fusses$|^fussez$|^estant$|^seiens$|^somes$|^estes$|^ieres$|^ier... | re.sub(pattern, replace, word)
return (matches_rule, apply_rule)
rules = [build_match_and_apply_functions(pattern, replace)
for (pattern, replace) in patterns]
def regex(token):
for matches_rule, apply_rule in rules:
if matches_rule(token):
return apply_rule(token)
| return | identifier_name |
octree.rs |
&& aabb2.min.y < aabb1.max.y
&& aabb2.min.z < aabb1.max.z
}
fn contains(aabb1: &Aabb3<f32>, aabb2: &Aabb3<f32>) -> bool {
true
&& aabb1.min.x <= aabb2.min.x
&& aabb1.min.y <= aabb2.min.y
&& aabb1.min.z <= aabb2.min.z
&& aabb2.max.x <= aabb1.max.x
&& aabb2.max.y <= aabb1.max.y
&& aabb2.max.z <= aabb1... | else {
unsafe {
assert!(!self.parent.is_null());
(*self.parent).on_mut_ancestor(bounds, f)
}
}
}
// Find whether there are objects overlapping the object & bounds provided in
// this/child trees. Uses equality comparison on V to ignore "same" objects.
// Returns the value assoc... | {
f(self)
} | conditional_block |
octree.rs |
&& aabb2.min.y < aabb1.max.y
&& aabb2.min.z < aabb1.max.z
}
fn contains(aabb1: &Aabb3<f32>, aabb2: &Aabb3<f32>) -> bool {
true
&& aabb1.min.x <= aabb2.min.x
&& aabb1.min.y <= aabb2.min.y
&& aabb1.min.z <= aabb2.min.z
&& aabb2.max.x <= aabb1.max.x
&& aabb2.max.y <= aabb1.max.y
&& aabb2.max.z <= aabb1... | (bounds: &Aabb3<f32>, d: Dimension) -> f32 {
get(d, &bounds.max) - get(d, &bounds.min)
}
fn middle(bounds: &Aabb3<f32>, d: Dimension) -> f32 {
(get(d, &bounds.max) + get(d, &bounds.min)) / 2.0
}
fn get(d: Dimension, p: &Point3<f32>) -> f32 {
match d {
Dimension::X => p.x,
Dimension::Y => p.y,
Dimens... | length | identifier_name |
octree.rs |
&& aabb2.min.y < aabb1.max.y
&& aabb2.min.z < aabb1.max.z
}
fn contains(aabb1: &Aabb3<f32>, aabb2: &Aabb3<f32>) -> bool {
true
&& aabb1.min.x <= aabb2.min.x
&& aabb1.min.y <= aabb2.min.y
&& aabb1.min.z <= aabb2.min.z
&& aabb2.max.x <= aabb1.max.x
&& aabb2.max.y <= aabb1.max.y
&& aabb2.max.z <= aabb1... |
pub fn insert(&mut self, bounds: &Aabb3<f32>, v: V) {
let this: *mut Octree<V> = self;
assert!(contains(&self.bounds, &bounds));
let contents = match self.contents {
OctreeContents::Leaf(ref mut vs) => {
vs.push((*bounds, v));
let d = self.dimension;
let avg_length =
... | random_line_split | |
octree.rs | match d {
Dimension::X => p.x = v,
Dimension::Y => p.y = v,
Dimension::Z => p.z = v,
}
}
fn split(mid: f32, d: Dimension, bounds: &Aabb3<f32>) -> (Option<Aabb3<f32>>, Option<Aabb3<f32>>) {
if get(d, &bounds.max) <= mid {
(Some(*bounds), None)
} else if get(d, &bounds.min) >= mid {
(None, So... | {
self.remove(bounds, v);
self.insert_from(new_bounds, v)
} | identifier_body | |
benchmark.scipy.py | #!/usr/bin/env python
#
# @license Apache-2.0
#
# Copyright (c) 2018 The Stdlib Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# ... | main() | conditional_block | |
benchmark.scipy.py | #!/usr/bin/env python
#
# @license Apache-2.0
#
# Copyright (c) 2018 The Stdlib Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# ... | # Examples
``` python
python> benchmark("random", "from random import random;", "y = random()", 1000000)
```
"""
t = timeit.Timer(stmt, setup=setup)
print_version()
i = 0
while i < REPEATS:
print("# python::" + name)
COUNT[0] += 1
elapsed = t.timeit(number=... | * `setup`: benchmark setup
* `stmt`: statement to benchmark
* `iterations`: number of iterations
| random_line_split |
benchmark.scipy.py | #!/usr/bin/env python
#
# @license Apache-2.0
#
# Copyright (c) 2018 The Stdlib Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# ... |
def benchmark(name, setup, stmt, iterations):
"""Run the benchmark and print benchmark results.
# Arguments
* `name`: benchmark name
* `setup`: benchmark setup
* `stmt`: statement to benchmark
* `iterations`: number of iterations
# Examples
``` python
python> benchmark("random... | """Print benchmark results.
# Arguments
* `iterations`: number of iterations
* `elapsed`: elapsed time (in seconds)
# Examples
``` python
python> print_results(1000000, 0.131009101868)
```
"""
rate = iterations / elapsed
print(" ---")
print(" iterations: " + str(iterat... | identifier_body |
benchmark.scipy.py | #!/usr/bin/env python
#
# @license Apache-2.0
#
# Copyright (c) 2018 The Stdlib Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# ... | ():
"""Run the benchmarks."""
name = "arcsine:entropy"
setup = "from scipy.stats import arcsine; from random import random; rv = arcsine(10.0, 20.0);"
stmt = "y = rv.entropy()"
iterations = 1000
benchmark(name, setup, stmt, iterations)
name = "arcsine:kurtosis"
setup = "from scipy.stats... | main | identifier_name |
favoritos.component.ts | import { Component, AfterViewInit } from "@angular/core";
import { Favorite } from "../favorite";
import { FavoriteService } from "../favorite.service";
import "rxjs/add/operator/map";
@Component({
selector: "app-favoritos",
templateUrl: "./favoritos.component.html",
styleUrls: ["./favoritos.component.scss... | });
}
}
| temparray = this.series.slice(i, i + chunk);
this.seriesView.push(temparray);
}
| conditional_block |
favoritos.component.ts | import { Component, AfterViewInit } from "@angular/core";
import { Favorite } from "../favorite";
import { FavoriteService } from "../favorite.service";
import "rxjs/add/operator/map";
@Component({
selector: "app-favoritos",
templateUrl: "./favoritos.component.html",
styleUrls: ["./favoritos.component.scss... | () {
this.pesquisarFavoritos();
}
pesquisarFavoritos(): void {
this.favoriteService.PesquisarFavoritos().subscribe(data => {
this.series = [];
this.seriesView = [null];
if (!data || Object.prototype.toString.call(data) !== "[object Array]") {
... | ngAfterViewInit | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.