file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
configurable_validator_signer.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{Error, PersistentSafetyStorage}; use diem_crypto::{ ed25519::{Ed25519PrivateKey, Ed25519PublicKey, Ed25519Signature}, hash::CryptoHash, }; use diem_global_constants::CONSENSUS_KEY; use diem_types::{account_address::A...
<T: Serialize + CryptoHash>( &self, message: &T, storage: &PersistentSafetyStorage, ) -> Result<Ed25519Signature, Error> { match self { ConfigurableValidatorSigner::Signer(signer) => Ok(signer.sign(message)), ConfigurableValidatorSigner::Handle(handle) => hand...
sign
identifier_name
configurable_validator_signer.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{Error, PersistentSafetyStorage}; use diem_crypto::{ ed25519::{Ed25519PrivateKey, Ed25519PublicKey, Ed25519Signature}, hash::CryptoHash, }; use diem_global_constants::CONSENSUS_KEY; use diem_types::{account_address::A...
/// Returns the author associated with this handle. pub fn author(&self) -> AccountAddress { self.author } /// Returns the public key version associated with this handle. pub fn key_version(&self) -> Ed25519PublicKey { self.key_version.clone() } /// Signs a given message ...
{ ValidatorHandle { author, key_version, } }
identifier_body
configurable_validator_signer.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{Error, PersistentSafetyStorage}; use diem_crypto::{ ed25519::{Ed25519PrivateKey, Ed25519PublicKey, Ed25519Signature}, hash::CryptoHash, }; use diem_global_constants::CONSENSUS_KEY; use diem_types::{account_address::A...
} /// Returns the public key version associated with this handle. pub fn key_version(&self) -> Ed25519PublicKey { self.key_version.clone() } /// Signs a given message using this handle and a given secure storage backend. pub fn sign<T: Serialize + CryptoHash>( &self, me...
} /// Returns the author associated with this handle. pub fn author(&self) -> AccountAddress { self.author
random_line_split
calculateTransform.js
import { Transform } from './transform.js'; /** * Calculate the transform for a Cornerstone enabled element * * @param {EnabledElement} enabledElement The Cornerstone Enabled Element * @param {Number} [scale] The viewport scale * @return {Transform} The current transform */ export default function (enabledElemen...
} if (enabledElement.viewport.vflip) { transform.scale(1, -1); } // Translate the origin back to the corner of the image so the event handlers can draw in image coordinate system transform.translate(-enabledElement.image.width / 2, -enabledElement.image.height / 2); return transform; }
} // Apply Flip if required if (enabledElement.viewport.hflip) { transform.scale(-1, 1);
random_line_split
calculateTransform.js
import { Transform } from './transform.js'; /** * Calculate the transform for a Cornerstone enabled element * * @param {EnabledElement} enabledElement The Cornerstone Enabled Element * @param {Number} [scale] The viewport scale * @return {Transform} The current transform */ export default function (enabledElemen...
// Translate the origin back to the corner of the image so the event handlers can draw in image coordinate system transform.translate(-enabledElement.image.width / 2, -enabledElement.image.height / 2); return transform; }
{ transform.scale(1, -1); }
conditional_block
layout.js
import * as React from "react" import loadable from "@loadable/component" import PropTypes from "prop-types" import { useStaticQuery, graphql } from "gatsby" import "./layout.css" const Header = loadable(() => import("./header")) const Layout = ({ children }) => { const data = useStaticQuery(graphql` query Sit...
marginTop: `2rem`, }} > © {new Date().getFullYear()}, Built with {` `} <a href="https://www.gatsbyjs.com">Gatsby</a> </footer> </div> </> ) } Layout.propTypes = { children: PropTypes.node.isRequired, } export default Layout
}} > <main>{children}</main> <footer style={{
random_line_split
labels.js
var inText = {top: "2.75rem", left: "0.75rem"}; var outText = {top: "0.5rem", left: 0}; function check()
$(document).ready(function() { // console.log("test2") check(); $(".login-form").on("change", ".login", check); $(".login-form").on("focus", ".login", function() { $(this).parent().children("label").animate(outText, 250); }); $(".login-form").on("focusout", ".login", function() { ...
{ $(".login").each(function() { if ($(this).val() != "") { $(this).parent().children("label").animate(outText, 250); } else { $(this).parent().children("label").animate(inText, 250); } }) }
identifier_body
labels.js
var inText = {top: "2.75rem", left: "0.75rem"}; var outText = {top: "0.5rem", left: 0}; function
() { $(".login").each(function() { if ($(this).val() != "") { $(this).parent().children("label").animate(outText, 250); } else { $(this).parent().children("label").animate(inText, 250); } }) } $(document).ready(function() { // console.log("test2") check(...
check
identifier_name
labels.js
var inText = {top: "2.75rem", left: "0.75rem"}; var outText = {top: "0.5rem", left: 0}; function check() { $(".login").each(function() { if ($(this).val() != "") { $(this).parent().children("label").animate(outText, 250); } else { $(this).parent().children("label").animate(i...
// console.log("test2") check(); $(".login-form").on("change", ".login", check); $(".login-form").on("focus", ".login", function() { $(this).parent().children("label").animate(outText, 250); }); $(".login-form").on("focusout", ".login", function() { if ($(this).val() == "") { ...
} $(document).ready(function() {
random_line_split
labels.js
var inText = {top: "2.75rem", left: "0.75rem"}; var outText = {top: "0.5rem", left: 0}; function check() { $(".login").each(function() { if ($(this).val() != "") { $(this).parent().children("label").animate(outText, 250); } else { $(this).parent().children("label").animate(i...
}); });
{ $(this).parent().children("label").animate(inText, 250); }
conditional_block
bfi.rs
use crate::core::bits::Bits; use crate::core::instruction::{BfiParams, Instruction}; use crate::core::register::Reg; #[allow(non_snake_case)] pub fn decode_BFI_t1(opcode: u32) -> Instruction { let rn: u8 = opcode.get_bits(16..20) as u8; let rd: u8 = opcode.get_bits(8..12) as u8; let imm3: u8 = opcode.get_...
// msbit = lsbit + width -1 <=> // width = msbit - lsbit + 1 let width = msbit - lsbit + 1; Instruction::BFI { params: BfiParams { rd: Reg::from(rd), rn: Reg::from(rn), lsbit: lsbit as usize, width: width as usize, }, } }
let imm2: u8 = opcode.get_bits(6..8) as u8; let lsbit = u32::from((imm3 << 2) + imm2); let msbit = opcode.get_bits(0..5);
random_line_split
bfi.rs
use crate::core::bits::Bits; use crate::core::instruction::{BfiParams, Instruction}; use crate::core::register::Reg; #[allow(non_snake_case)] pub fn decode_BFI_t1(opcode: u32) -> Instruction
{ let rn: u8 = opcode.get_bits(16..20) as u8; let rd: u8 = opcode.get_bits(8..12) as u8; let imm3: u8 = opcode.get_bits(12..15) as u8; let imm2: u8 = opcode.get_bits(6..8) as u8; let lsbit = u32::from((imm3 << 2) + imm2); let msbit = opcode.get_bits(0..5); // msbit = lsbit + width -1 <=...
identifier_body
bfi.rs
use crate::core::bits::Bits; use crate::core::instruction::{BfiParams, Instruction}; use crate::core::register::Reg; #[allow(non_snake_case)] pub fn
(opcode: u32) -> Instruction { let rn: u8 = opcode.get_bits(16..20) as u8; let rd: u8 = opcode.get_bits(8..12) as u8; let imm3: u8 = opcode.get_bits(12..15) as u8; let imm2: u8 = opcode.get_bits(6..8) as u8; let lsbit = u32::from((imm3 << 2) + imm2); let msbit = opcode.get_bits(0..5); // ...
decode_BFI_t1
identifier_name
helpers.rs
use errors::*; use crypto::digest::Digest; use crypto::blake2b::Blake2b; /// Helper to calculate a discovery key from a public key. 'key' should be 32 bytes; the returned /// array will also be 32 bytes long. /// /// dat discovery keys are calculated as a BLAKE2b "keyed hash" (using the passed key) of the string /// ...
(key: &[u8]) -> Vec<u8> { let mut discovery_key = [0; 32]; let mut hash = Blake2b::new_keyed(32, key); hash.input(&"hypercore".as_bytes()); hash.result(&mut discovery_key); discovery_key.to_vec() } /// Helper to parse a dat address (aka, public key) in string format. /// /// Address can start with ...
make_discovery_key
identifier_name
helpers.rs
use errors::*; use crypto::digest::Digest; use crypto::blake2b::Blake2b; /// Helper to calculate a discovery key from a public key. 'key' should be 32 bytes; the returned /// array will also be 32 bytes long. /// /// dat discovery keys are calculated as a BLAKE2b "keyed hash" (using the passed key) of the string /// "...
Ok(key_bytes) } #[test] fn test_parse_dat_address() { assert!(parse_dat_address( "c7638882870abd4044d6467b0738f15e3a36f57c3a7f7f3417fd7e4e0841d597").is_ok()); assert!(parse_dat_address( "C7638882870ABD4044D6467B0738F15E3A36F57C3A7F7F3417FD7E4E0841D597").is_ok()); assert!(parse_dat_addr...
random_line_split
helpers.rs
use errors::*; use crypto::digest::Digest; use crypto::blake2b::Blake2b; /// Helper to calculate a discovery key from a public key. 'key' should be 32 bytes; the returned /// array will also be 32 bytes long. /// /// dat discovery keys are calculated as a BLAKE2b "keyed hash" (using the passed key) of the string /// ...
#[test] fn test_parse_dat_address() { assert!(parse_dat_address( "c7638882870abd4044d6467b0738f15e3a36f57c3a7f7f3417fd7e4e0841d597").is_ok()); assert!(parse_dat_address( "C7638882870ABD4044D6467B0738F15E3A36F57C3A7F7F3417FD7E4E0841D597").is_ok()); assert!(parse_dat_address( "dat:/...
{ let raw_key = if input.starts_with("dat://") { &input[6..] } else { input }; if raw_key.len() != 32 * 2 { bail!("dat key not correct length"); } let mut key_bytes = vec![]; for i in 0..32 { let r = u8::from_str_radix(&raw_key[2 * i..2 * i + 2], 16); ...
identifier_body
img.rs
use std::iter::Iterator; use std::path; use image; use image::{DynamicImage, GenericImageView}; pub struct Image { pub width: u32, pub height: u32, img_buf: DynamicImage, } impl Image { pub fn new<P: AsRef<path::Path> + ToString>(path: P) -> Image { let img_buf = image::open(&path).unwrap(); ...
(img_buf: DynamicImage) -> Image { let (width, height) = img_buf.dimensions(); Image { width, height, img_buf, } } #[cfg(feature = "qrcode_builder")] pub fn from_qr(code: &str, width: u32) -> Image { use image::ImageBuffer; use qrc...
from
identifier_name
img.rs
use std::iter::Iterator; use std::path; use image; use image::{DynamicImage, GenericImageView}; pub struct Image { pub width: u32, pub height: u32, img_buf: DynamicImage, } impl Image { pub fn new<P: AsRef<path::Path> + ToString>(path: P) -> Image { let img_buf = image::open(&path).unwrap(); ...
else { image::Rgb([0, 0, 0]) } }); Image { width, height: width, img_buf: DynamicImage::ImageRgb8(img_buf), } } pub fn is_blank_pixel(&self, x: u32, y: u32) -> bool { let pixel = self.img_buf.get_pixel(x, y); ...
{ image::Rgb([0xFF, 0xFF, 0xFF]) }
conditional_block
img.rs
use std::iter::Iterator; use std::path; use image; use image::{DynamicImage, GenericImageView}; pub struct Image { pub width: u32, pub height: u32, img_buf: DynamicImage, } impl Image { pub fn new<P: AsRef<path::Path> + ToString>(path: P) -> Image { let img_buf = image::open(&path).unwrap(); ...
}
random_line_split
msg_log.py
import sys import os PACKAGE_PARENT = '../..' SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__)))) sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT))) from proxy.repr_to_bytes import repr_bytes_to_bytes_gen class Message(): def __init__(...
return log
line = b''.join(repr_bytes_to_bytes_gen(line)) if line[0:len(pattern['c'])] == pattern['c']: log.append({"C": line[pattern['start']:pattern['end']]}) elif line[0:len(pattern['s'])] == pattern['s']: log.append({"S": line[pattern['start']:pattern['en...
conditional_block
msg_log.py
import sys import os PACKAGE_PARENT = '../..' SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__)))) sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT))) from proxy.repr_to_bytes import repr_bytes_to_bytes_gen class Message(): def __init__(...
@staticmethod def get_log_from_file(f, pattern): log = [] with open(f, 'rb') as f: for line in f: line = b''.join(repr_bytes_to_bytes_gen(line)) if line[0:len(pattern['c'])] == pattern['c']: log.append({"C": line[pattern['start']:...
_log = [] _side_log = {'client': [], 'server': []} i = 0 while log: if log and log[0].get('C') != None: _side_log['client'].append(i) _log.append(log.pop(0)['C']) elif log and log[0].get('S') != None: _side_log['server'].app...
identifier_body
msg_log.py
import sys import os PACKAGE_PARENT = '../..' SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__)))) sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT))) from proxy.repr_to_bytes import repr_bytes_to_bytes_gen class Message(): def __init__(...
def __call__(self, msg=b''): self.msg = b''.join([self.msg, msg]) if self.msg in self.pin_pong: yield self.pin_pong[self.msg] self.msg = b'' @staticmethod def game_log_from_import(log): _log = [] _side_log = {'client': [], 'server': []} i = 0...
random_line_split
msg_log.py
import sys import os PACKAGE_PARENT = '../..' SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__)))) sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT))) from proxy.repr_to_bytes import repr_bytes_to_bytes_gen class Message(): def __init__(...
(self, _log, _side_log): log = {'client' : [], 'server' : [], } last_string = b'' last_side = 'client' for i in range(len(_log)): if i == 0: last_string = _log[i] last_side = 'client' elif i in _side_log[last_side]: ...
pin_pong_f
identifier_name
json-crud.d.ts
export = JsonDB; declare function JsonDB(path?: string; options?: Options): Promise<JsonDBInstance>; declare namespace JsonDB { export type Id = string | number; export type IdOrError = Id | Error; export type Results = { [key: Id]: any }; export type Data = { [key: Id]: any } | any[]; export type Fiel...
* @returns A promise that will resolve to an object containing the * key/values of the values matched */ read: (filter?: Filter) => Promise<Results>; /** * Updates data in the JSON database. Data can either be given as * key-value parameter pairs, OR if the key field has been specifie...
* * @param [filter] Filter to use to match the values to return. If not * given, all values will be returned *
random_line_split
index.d.ts
// Type definitions for geojson 7946.0 // Project: https://geojson.org/ // Definitions by: Jacob Bruun <https://github.com/cobster> // Arne Schubert <https://github.com/atd-schubert> // Jeff Jacobson <https://github.com/JeffJacobson> // Ilia Choly <https://github.com/icho...
// [key: string]: any; /** * Specifies the type of GeoJSON object. */ type: GeoJsonTypes; /** * Bounding box of the coordinate range of the object's Geometries, Features, or Feature Collections. * https://tools.ietf.org/html/rfc7946#section-5 */ bbox?: BBox; } /** * Union ...
export interface GeoJsonObject { // Don't include foreign members directly into this type def. // in order to preserve type safety.
random_line_split
chrome_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use net::chrome_loader::resolve_chrome_url; use url::Url; #[test] fn test_relative() { let url = Url::parse("...
fn test_absolute_2() { let url = Url::parse("chrome://C:\\Windows").unwrap(); assert!(resolve_chrome_url(&url).is_err()); } #[test] #[cfg(target_os = "windows")] fn test_absolute_3() { let url = Url::parse("chrome://\\\\server/C$").unwrap(); assert!(resolve_chrome_url(&url).is_err()); } #[test] fn tes...
#[test] #[cfg(target_os = "windows")]
random_line_split
chrome_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use net::chrome_loader::resolve_chrome_url; use url::Url; #[test] fn test_relative() { let url = Url::parse("...
#[test] #[cfg(target_os = "windows")] fn test_absolute_3() { let url = Url::parse("chrome://\\\\server/C$").unwrap(); assert!(resolve_chrome_url(&url).is_err()); } #[test] fn test_valid() { let url = Url::parse("chrome://badcert.jpg").unwrap(); let resolved = resolve_chrome_url(&url).unwrap(); as...
{ let url = Url::parse("chrome://C:\\Windows").unwrap(); assert!(resolve_chrome_url(&url).is_err()); }
identifier_body
chrome_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use net::chrome_loader::resolve_chrome_url; use url::Url; #[test] fn test_relative() { let url = Url::parse("...
() { let url = Url::parse("chrome:///etc/passwd").unwrap(); assert!(resolve_chrome_url(&url).is_err()); } #[test] #[cfg(target_os = "windows")] fn test_absolute_2() { let url = Url::parse("chrome://C:\\Windows").unwrap(); assert!(resolve_chrome_url(&url).is_err()); } #[test] #[cfg(target_os = "windows...
test_absolute
identifier_name
defaulter-list-resource.service.spec.ts
import { TestBed, async, inject, fakeAsync } from '@angular/core/testing'; import { LocalStorageService } from '../utils/local-storage.service'; import { AppSettingsService } from '../app-settings/app-settings.service'; import { DefaulterListResourceService } from './defaulter-list-resource.service'; import { CacheModu...
} const expectedResults = { startIndex: 0, size: 3, result: [ { patient_uuid: 'patient-uuid', person_id: 102322, encounter_id: 636033226, location_id: 1, location_uuid: '08feae7c-1352-11df-a1f1-0026b9348838', days_since_rtc: 30, encounter_datetime: '2016-09-19T21:00:...
{ return true; }
identifier_body
defaulter-list-resource.service.spec.ts
import { TestBed, async, inject, fakeAsync } from '@angular/core/testing'; import { LocalStorageService } from '../utils/local-storage.service'; import { AppSettingsService } from '../app-settings/app-settings.service'; import { DefaulterListResourceService } from './defaulter-list-resource.service'; import { CacheModu...
date_changed: '2013-08-05T09:02:05.000Z', voided: 0, voided_by: null, date_voided: null, void_reason: null, uuid: '2f8213c6-5c26-4889-ba28-7f28dadd237e', deathdate_estimated: 0, birthtime: null, age: 41 } ] }; describe('DefaulterListResourceService Tests', () ...
changed_by: 165060,
random_line_split
defaulter-list-resource.service.spec.ts
import { TestBed, async, inject, fakeAsync } from '@angular/core/testing'; import { LocalStorageService } from '../utils/local-storage.service'; import { AppSettingsService } from '../app-settings/app-settings.service'; import { DefaulterListResourceService } from './defaulter-list-resource.service'; import { CacheModu...
() { return true; } } const expectedResults = { startIndex: 0, size: 3, result: [ { patient_uuid: 'patient-uuid', person_id: 102322, encounter_id: 636033226, location_id: 1, location_uuid: '08feae7c-1352-11df-a1f1-0026b9348838', days_since_rtc: 30, encounter_dat...
ready
identifier_name
config-file.ts
import { promises as fs } from "fs" import * as tr from "text-runner-core" import * as YAML from "yamljs" import * as config from "./configuration" /** provides the config file content as a Configuration instance */ export async function load(cmdLineArgs: config.Data): Promise<config.Data> { return parse(await read...
# To exclude the "vendor" folder: '{,!(vendor)/**/}*.md' files: "**/*.md" # black-list of files not to test # This is applied after the white-list above. exclude: [] # the formatter to use (detailed, dot, progress, summary) format: detailed # Define which folders of your Markdown source get compiled to HTML # and pu...
await fs.writeFile( cmdLineArgs.configFileName || "text-run.yml", `# white-list for files to test # This is a glob expression, see https://github.com/isaacs/node-glob#glob-primer # The folder "node_modules" is already excluded.
random_line_split
config-file.ts
import { promises as fs } from "fs" import * as tr from "text-runner-core" import * as YAML from "yamljs" import * as config from "./configuration" /** provides the config file content as a Configuration instance */ export async function load(cmdLineArgs: config.Data): Promise<config.Data> { return parse(await read...
(fileContent: string): config.Data { if (fileContent === "") { return new config.Data({}) } const fileData = YAML.parse(fileContent) return new config.Data({ regionMarker: fileData.regionMarker, defaultFile: fileData.defaultFile, emptyWorkspace: fileData.emptyWorkspace, exclude: fileData.exc...
parse
identifier_name
config-file.ts
import { promises as fs } from "fs" import * as tr from "text-runner-core" import * as YAML from "yamljs" import * as config from "./configuration" /** provides the config file content as a Configuration instance */ export async function load(cmdLineArgs: config.Data): Promise<config.Data> { return parse(await read...
const fileData = YAML.parse(fileContent) return new config.Data({ regionMarker: fileData.regionMarker, defaultFile: fileData.defaultFile, emptyWorkspace: fileData.emptyWorkspace, exclude: fileData.exclude, files: fileData.files, formatterName: fileData.format, online: fileData.online, ...
{ return new config.Data({}) }
conditional_block
config-file.ts
import { promises as fs } from "fs" import * as tr from "text-runner-core" import * as YAML from "yamljs" import * as config from "./configuration" /** provides the config file content as a Configuration instance */ export async function load(cmdLineArgs: config.Data): Promise<config.Data> { return parse(await read...
/** provides the textual config file content */ async function read(cmdLineArgs: config.Data): Promise<string> { if (cmdLineArgs.configFileName) { try { const result = await fs.readFile(cmdLineArgs.configFileName, "utf8") return result } catch (e) { throw new tr.UserError(`cannot read conf...
{ await fs.writeFile( cmdLineArgs.configFileName || "text-run.yml", `# white-list for files to test # This is a glob expression, see https://github.com/isaacs/node-glob#glob-primer # The folder "node_modules" is already excluded. # To exclude the "vendor" folder: '{,!(vendor)/**/}*.md' files: "**/*.md" # bla...
identifier_body
InformationLabel.tsx
import React, { FC, useContext } from 'react'; import ReactiveFormControl from '../form-controls/ReactiveFormControl'; import { Label, Link, Icon } from 'office-ui-fabric-react'; import { style } from 'typestyle'; import { ThemeContext } from '../../ThemeContext'; import { ThemeExtended } from '../../theme/SemanticColo...
)} </ReactiveFormControl> ); }; export default InformationLabel;
{labelProps && labelProps.icon && <Icon iconName={labelProps.icon} className={labelIconStyle} />} <span>{value}</span> </Label>
random_line_split
InformationLabel.tsx
import React, { FC, useContext } from 'react'; import ReactiveFormControl from '../form-controls/ReactiveFormControl'; import { Label, Link, Icon } from 'office-ui-fabric-react'; import { style } from 'typestyle'; import { ThemeContext } from '../../ThemeContext'; import { ThemeExtended } from '../../theme/SemanticColo...
}; const defaultLabelStyle = (theme: ThemeExtended) => style({ color: theme.semanticColors.textColor, }); const getLabelStyle = (labelProps: any, theme: ThemeExtended) => { return labelProps && labelProps.type ? style({ color: getLabelColor(labelProps.type, theme), }) : defaultLabelSt...
{ return theme.semanticColors.textColor; }
conditional_block
main.rs
#![feature(slice_position_elem, iter_arith)] #[macro_use] extern crate libeuler; /// 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. /// /// What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? fn main() { solut...
else { factor += 1; } } retval } fn prime_factors_less_than(max: &i64) -> Vec<Vec<i64>> { let mut retval = Vec::new(); for i in 1..*max { retval.push(factors(&i)); } retval }
{ retval.push(factor); v /= factor; }
conditional_block
main.rs
#![feature(slice_position_elem, iter_arith)] #[macro_use] extern crate libeuler; /// 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. /// /// What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? fn main()
fn factors(value: &i64) -> Vec<i64> { let mut factor = 2; let mut v = value.clone(); let mut retval = Vec::new(); while v > 1 { if v % factor == 0 { retval.push(factor); v /= factor; } else { factor += 1; } } retval } fn prime_fact...
{ solutions!{ inputs: (max_factor: i64 = 20) sol naive { let primes = prime_factors_less_than(&max_factor); let mut needed_factors = Vec::new(); for factors in primes.iter() { let mut f = needed_factors.clone(); let still_needed: ...
identifier_body
main.rs
#![feature(slice_position_elem, iter_arith)] #[macro_use] extern crate libeuler; /// 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. /// /// What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? fn main() { solut...
(value: &i64) -> Vec<i64> { let mut factor = 2; let mut v = value.clone(); let mut retval = Vec::new(); while v > 1 { if v % factor == 0 { retval.push(factor); v /= factor; } else { factor += 1; } } retval } fn prime_factors_less_tha...
factors
identifier_name
main.rs
#![feature(slice_position_elem, iter_arith)] #[macro_use] extern crate libeuler; /// 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. /// /// What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? fn main() { solut...
needed_factors.iter().map(|&i| i).product::<i64>() } }; } fn factors(value: &i64) -> Vec<i64> { let mut factor = 2; let mut v = value.clone(); let mut retval = Vec::new(); while v > 1 { if v % factor == 0 { retval.push(factor); v /= factor; ...
needed_factors.push(v.clone()); } }
random_line_split
modelling.py
from gensim import corpora,models,utils import numpy as np from pymongo import MongoClient from preprocess_text import clean from corpus_dictionary import custom_corpus, CompleteCorpus client = MongoClient() db = client['crawled_news'] collection = db['crawled_news'] def tagged_docs(): for d in collection.find():...
corpus.dictionary.save("dictionary/temp_complete_dictionary.dict") dictionary = corpora.dictionary.Dictionary.load("dictionary/temp_complete_dictionary.dict") c = corpora.mmcorpus.MmCorpus("corpus/temp_complete_corpus.mm") lda = update_lda_model(c,model_path,size) save_lda_topics_to_db(model_path,di...
# topic_probabilities.append(topic_probability) def compute_complete_lda_topics(model_path,size=100): corpus = CompleteCorpus() corpora.MmCorpus.serialize("corpus/temp_complete_corpus.mm", corpus)
random_line_split
modelling.py
from gensim import corpora,models,utils import numpy as np from pymongo import MongoClient from preprocess_text import clean from corpus_dictionary import custom_corpus, CompleteCorpus client = MongoClient() db = client['crawled_news'] collection = db['crawled_news'] def tagged_docs(): for d in collection.find():...
def update_doc2vec_model(model_path="model/doc2vec.model",size=400,min_count=5): doc2vec = models.doc2vec.Doc2Vec(tagged_docs(), size=size, window=8, min_count=min_count, workers=6) doc2vec.save(model_path) return doc2vec def update_lda_model(corpus,model_path="model/lda.model",size=100): print("LDA ...
cleaned = clean(d["content"]) doc_id = str(d["_id"]) yield models.doc2vec.TaggedDocument(cleaned.split(),[doc_id])
conditional_block
modelling.py
from gensim import corpora,models,utils import numpy as np from pymongo import MongoClient from preprocess_text import clean from corpus_dictionary import custom_corpus, CompleteCorpus client = MongoClient() db = client['crawled_news'] collection = db['crawled_news'] def tagged_docs(): for d in collection.find():...
def save_lda_topics_to_db(lda_model_path,dictionary): lda = models.ldamulticore.LdaMulticore.load(lda_model_path) i = 1 for document in collection.find(): if i%100 == 0: print(i) i += 1 document_id = document["_id"] cleaned = clean(document["content"]) d...
doc2vec = models.doc2vec.Doc2Vec(min_count=10) doc2vec.load_word2vec_format(model_source_path,binary=True) # doc2vec.init_sims(replace=False) doc2vec.save(model_target_path) return doc2vec
identifier_body
modelling.py
from gensim import corpora,models,utils import numpy as np from pymongo import MongoClient from preprocess_text import clean from corpus_dictionary import custom_corpus, CompleteCorpus client = MongoClient() db = client['crawled_news'] collection = db['crawled_news'] def tagged_docs(): for d in collection.find():...
(model_path,size=100): corpus = CompleteCorpus() corpora.MmCorpus.serialize("corpus/temp_complete_corpus.mm", corpus) corpus.dictionary.save("dictionary/temp_complete_dictionary.dict") dictionary = corpora.dictionary.Dictionary.load("dictionary/temp_complete_dictionary.dict") c = corpora.mmcorpus.Mm...
compute_complete_lda_topics
identifier_name
editSelect.js
/* * 此方法用于 图书搜索页面 的 搜索结果中的 “编辑” 按钮进去 编辑页面后 三个 下拉框的默认选择。 * 分别是 “图书类型” “书架” “出版社” */
function selectOption( name ) { nameVal = $('.' + name).find('select').attr('value'); nameElm = $('.' + name); nameElm.find('li').each(function(){ if ( $(this).attr('data-raw-value') == nameVal) { text = $(this).text(); // 显示层 select 改变值 trigger = nameElm.find('div[class=trigger]'); trigger.te...
random_line_split
editSelect.js
/* * 此方法用于 图书搜索页面 的 搜索结果中的 “编辑” 按钮进去 编辑页面后 三个 下拉框的默认选择。 * 分别是 “图书类型” “书架” “出版社” */ function selectOption( name ) { nameVal = $('.' + name).find('select').attr('value'); nameElm = $('.' + name); nameElm.find(
unction(){ if ( $(this).attr('data-raw-value') == nameVal) { text = $(this).text(); // 显示层 select 改变值 trigger = nameElm.find('div[class=trigger]'); trigger.text( text ); } }); nameElm.find('option').each(function(){ if ( $(this).val() == nameVal ){ // 实际的 <option> 也要改变 $(this).attr...
'li').each(f
identifier_name
editSelect.js
/* * 此方法用于 图书搜索页面 的 搜索结果中的 “编辑” 按钮进去 编辑页面后 三个 下拉框的默认选择。 * 分别是 “图书类型” “书架” “出版社” */ function selectOption( name ) { nameVal = $('.' + name).find('select').attr('value'); nameElm = $('.' + name); nameElm.find('li').each(function(){ if ( $(this).attr('data-raw-value') == nameVal) { text = $(this).text(...
cted', 'selected'); } }); }
text ); } }); nameElm.find('option').each(function(){ if ( $(this).val() == nameVal ){ // 实际的 <option> 也要改变 $(this).attr('sele
conditional_block
editSelect.js
/* * 此方法用于 图书搜索页面 的 搜索结果中的 “编辑” 按钮进去 编辑页面后 三个 下拉框的默认选择。 * 分别是 “图书类型” “书架” “出版社” */ function selectOption( name ) { nameVal = $('.' + name).find('select').attr('value'); nameElm = $('.' + name); nameElm.find('li').each(function()
{ if ( $(this).attr('data-raw-value') == nameVal) { text = $(this).text(); // 显示层 select 改变值 trigger = nameElm.find('div[class=trigger]'); trigger.text( text ); } }); nameElm.find('option').each(function(){ if ( $(this).val() == nameVal ){ // 实际的 <option> 也要改变 $(this).attr('selecte...
identifier_body
usage.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
(Model): """Describes Storage Resource Usage. :param unit: The unit of measurement. Possible values include: 'Count', 'Bytes', 'Seconds', 'Percent', 'CountsPerSecond', 'BytesPerSecond' :type unit: str or :class:`UsageUnit <azure.mgmt.storage.v2015_06_15.models.UsageUnit>` :param current_value...
Usage
identifier_name
usage.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
self.unit = unit self.current_value = current_value self.limit = limit self.name = name
identifier_body
usage.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
'unit': {'key': 'unit', 'type': 'UsageUnit'}, 'current_value': {'key': 'currentValue', 'type': 'int'}, 'limit': {'key': 'limit', 'type': 'int'}, 'name': {'key': 'name', 'type': 'UsageName'}, } def __init__(self, unit, current_value, limit, name): self.unit = unit ...
} _attribute_map = {
random_line_split
components.ts
import styled, { css } from "styled-components"; import { Colors } from "../../util/constants"; export const InspectorContainer = styled.div<{ visible?: boolean }>` background: ${Colors.Inspector.Background}; box-shadow: inset 1px 1px 0 0 hsla(0, 0%, 100%, 0.1); display: ${({ visible }) => (visible ? "flex" : "n...
export const Separator = styled.div` height: 1px; background-color: hsla(0, 0%, 0%, 0.25); `; export const Text = styled.p<{ bold?: boolean }>` color: #fff; margin: 0 0.8em; ${({ bold }) => bold && css` font-weight: bold; `}; `; export const Tabs = styled.nav` background: ${Colors.App.Ba...
padding: 0 0.8em; margin-bottom: 1em; `;
random_line_split
MeetingControllerTests.ts
///ts:import=MeetingController import MeetingController = require('../../Client/MeetingController'); ///ts:import:generated ///ts:import=IMeetingSvc import IMeetingSvc = require('../../Client/IMeetingSvc'); ///ts:import:generated ///ts:import=MeetingData import MeetingData = require('../../Common/MeetingData'); ///ts:...
$rootScope = _$rootScope_.$new(); meetingSvc = <IMeetingSvc>{ createMeeting: function () {}}; mockMeetingSvc = sinon.mock(meetingSvc); mockUserSvc = sinon.mock(userSvc); })); afterEach(function () { $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.veri...
$httpBackend = _$httpBackend_; $http = _$http_; $routeParams = { id: 3 };
random_line_split
ligature-subdivision.js
description('Test that the caret is positioned correctly when its offset occurrs in the middle of a ligature,\ and that hit-testing in the middle of a ligature works correctly.'); var latin = document.createElement("div"); latin.innerHTML = "office"; latin.style.fontSize = "72px"; latin.style.textRendering = "opti...
shouldBe('document.caretRangeFromPoint(x - 90, y).startOffset', '3'); range.setStart(arabic.firstChild, 0); range.setEnd(arabic.firstChild, 2); var w = range.getBoundingClientRect().width; // Widths vary between Mac OS X Leopard, Snow Leopard, and current Mac OS X. shouldBeTrue('w === 66 || w === 65 || w === 61'); do...
random_line_split
truncate_reverse_primer.py
#!/usr/bin/env python # File created February 29, 2012 from __future__ import division __author__ = "William Walters" __copyright__ = "Copyright 2011, The QIIME Project" __credits__ = ["William Walters", "Emily TerAvest"] __license__ = "GPL" __version__ = "1.8.0-dev" __maintainer__ = "William Walters" __email__ = "Wil...
def get_output_filepaths(output_dir, fasta_fp): """ Returns output fasta filepath and log filepath fasta_fp: fasta filepath output_dir: output directory """ fasta_extensions = ['.fa', '.fasta', '.fna'] curr_fasta_out = basename(fasta_fp) for fasta_extension in f...
""" Parses mapping file to get dictionary of SampleID:Rev primer mapping_fp: mapping filepath """ hds, mapping_data, run_description, errors, warnings = \ process_id_map(mapping_fp, has_barcodes=False, disable_primer_check=True) if errors: for curr_err in errors:...
identifier_body
truncate_reverse_primer.py
#!/usr/bin/env python # File created February 29, 2012 from __future__ import division __author__ = "William Walters" __copyright__ = "Copyright 2011, The QIIME Project" __credits__ = ["William Walters", "Emily TerAvest"] __license__ = "GPL" __version__ = "1.8.0-dev" __maintainer__ = "William Walters" __email__ = "Wil...
""" Returns output fasta filepath and log filepath fasta_fp: fasta filepath output_dir: output directory """ fasta_extensions = ['.fa', '.fasta', '.fna'] curr_fasta_out = basename(fasta_fp) for fasta_extension in fasta_extensions: curr_fasta_out = curr_fasta_out.replace(fasta_exten...
fasta_fp):
random_line_split
truncate_reverse_primer.py
#!/usr/bin/env python # File created February 29, 2012 from __future__ import division __author__ = "William Walters" __copyright__ = "Copyright 2011, The QIIME Project" __credits__ = ["William Walters", "Emily TerAvest"] __license__ = "GPL" __version__ = "1.8.0-dev" __maintainer__ = "William Walters" __email__ = "Wil...
(mapping_fp): """ Parses mapping file to get dictionary of SampleID:Rev primer mapping_fp: mapping filepath """ hds, mapping_data, run_description, errors, warnings = \ process_id_map(mapping_fp, has_barcodes=False, disable_primer_check=True) if errors: for c...
get_rev_primer_seqs
identifier_name
truncate_reverse_primer.py
#!/usr/bin/env python # File created February 29, 2012 from __future__ import division __author__ = "William Walters" __copyright__ = "Copyright 2011, The QIIME Project" __credits__ = ["William Walters", "Emily TerAvest"] __license__ = "GPL" __version__ = "1.8.0-dev" __maintainer__ = "William Walters" __email__ = "Wil...
for header in range(len(hds)): for curr_data in mapping_data: id_map[curr_data[0]][hds[header]] = curr_data[header] reverse_primers = {} for curr_id in id_map.keys(): try: reverse_primers[curr_id] =\ [str(DNA(curr_rev_primer).rc()) for curr_rev_pri...
id_map[curr_data[0]] = {}
conditional_block
SupervisorJob.py
from jinja2 import Template class SupervisorJob(object): """docstring for SupervisorJob""" def
(self, config): """ Specify the configuration options for a job. 'config' must be a dictionary containing the following keys: - env_vars: dict containing the key/value pairs to be specified as environment variables e.g. {"ES_HOME" : "/home/es"} ...
__init__
identifier_name
SupervisorJob.py
from jinja2 import Template class SupervisorJob(object): """docstring for SupervisorJob""" def __init__(self, config): """ Specify the configuration options for a job. 'config' must be a dictionary containing the following keys: - env_vars: dict containing the key/value pairs ...
return res def get_env_str(self): return ", ".join([k + "=\"" + str(v) + "\"" for k,v in self['env_vars'].items()])
res += "export %s=%s\n" % (k, v)
conditional_block
SupervisorJob.py
from jinja2 import Template class SupervisorJob(object): """docstring for SupervisorJob""" def __init__(self, config): """ Specify the configuration options for a job. 'config' must be a dictionary containing the following keys: - env_vars: dict containing the key/value pairs ...
env = Template(config) return env.render({ "program_name" : self.config['name'], "base_dir" : self.config['base_dir'], "env" : self.get_env_str(), "cmd" : self.config['cmd'], "stdout" : self.config['stdout_file'], ...
"""
random_line_split
SupervisorJob.py
from jinja2 import Template class SupervisorJob(object): """docstring for SupervisorJob""" def __init__(self, config): """ Specify the configuration options for a job. 'config' must be a dictionary containing the following keys: - env_vars: dict containing the key/value pairs ...
def __getitem__(self, k): return self.config[k] def __setitem__(self, k, v): self.config[k] = v def __contains__(self, k): return k in self.config def add_env(self, k, v): self['env_vars'][k] = v def as_supervisor_program(self): config = """[program:{{pr...
raise NotImplementedError("base class")
identifier_body
mqtt_helper.py
import uuid from paho.mqtt import publish from paho.mqtt.client import MQTTv31 from conf.mqttconf import * def
(msg, user_list, qos=2, retain=False): """ 发布mqtt消息 :param msg:消息内容,可以是字符串、int、bytearray :param user_list: 用户列表数组(不带前缀的),例如:["zhangsan","lilei"] :param qos: 消息质量(0:至多一次,1:至少一次,2:只有一次) :param retain:设置是否保存消息,为True时当订阅者不在线时发送的消息等上线后会得到通知,否则只发送给在线的设备 :return: """ auth = {"username": MOS...
send
identifier_name
mqtt_helper.py
import uuid from paho.mqtt import publish from paho.mqtt.client import MQTTv31 from conf.mqttconf import * def send(msg, user_list, qos=2, retain=False):
""" 发布mqtt消息 :param msg:消息内容,可以是字符串、int、bytearray :param user_list: 用户列表数组(不带前缀的),例如:["zhangsan","lilei"] :param qos: 消息质量(0:至多一次,1:至少一次,2:只有一次) :param retain:设置是否保存消息,为True时当订阅者不在线时发送的消息等上线后会得到通知,否则只发送给在线的设备 :return: """ auth = {"username": MOSQUITTO_PUB_USER, "password": MOSQUITTO_PUB_...
identifier_body
mqtt_helper.py
import uuid from paho.mqtt import publish from paho.mqtt.client import MQTTv31 from conf.mqttconf import * def send(msg, user_list, qos=2, retain=False): """ 发布mqtt消息 :param msg:消息内容,可以是字符串、int、bytearray :param user_list: 用户列表数组(不带前缀的),例如:["zhangsan","lilei"] :param qos: 消息质量(0:至多一次,1:至少一次,2:只有一...
conditional_block
mqtt_helper.py
import uuid from paho.mqtt import publish from paho.mqtt.client import MQTTv31 from conf.mqttconf import * def send(msg, user_list, qos=2, retain=False): """
:param user_list: 用户列表数组(不带前缀的),例如:["zhangsan","lilei"] :param qos: 消息质量(0:至多一次,1:至少一次,2:只有一次) :param retain:设置是否保存消息,为True时当订阅者不在线时发送的消息等上线后会得到通知,否则只发送给在线的设备 :return: """ auth = {"username": MOSQUITTO_PUB_USER, "password": MOSQUITTO_PUB_PWD} client_id = MOSQUITTO_PREFIX + str(uuid.uuid1()) ...
发布mqtt消息 :param msg:消息内容,可以是字符串、int、bytearray
random_line_split
index.d.ts
// Type definitions for minilog 2.0 // Project: https://github.com/mixu/minilog // Definitions by: Guido <http://guido.io> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped //These type definitions are not complete, although basic usage should be typed. interface Minilog { debug(...msg: any[]): Mi...
{ write(name: any, level: any, args: any): void; pipe(dest: any): any; unpipe(from: any): Transform; mixin(dest: any): void; } } export = Minilog; export as namespace Minilog;
Transform
identifier_name
index.d.ts
// Type definitions for minilog 2.0 // Project: https://github.com/mixu/minilog // Definitions by: Guido <http://guido.io> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped //These type definitions are not complete, although basic usage should be typed. interface Minilog { debug(...msg: any[]): Mi...
export var suggest: Filter; export var backends: Minilog.MinilogBackends; export var defaultBackend: any; export var defaultFormatter: string; export class Filter extends Transform{ /** * Adds an entry to the whitelist * Returns this filter */ allow(name: ...
export function enable(): Minilog; export function disable() : Minilog; export function pipe(dest: any): Transform;
random_line_split
analyzer.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be
import * as ts from 'typescript'; import {ModuleResolver} from '../../imports'; import {PartialEvaluator} from '../../partial_evaluator'; import {scanForRouteEntryPoints} from './lazy'; import {RouterEntryPointManager} from './route'; export interface NgModuleRawRouteData { sourceFile: ts.SourceFile; moduleName...
* found in the LICENSE file at https://angular.io/license */
random_line_split
analyzer.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import * as ts from 'typescript'; import {ModuleResolver} from '../../imports'; import {PartialEvaluator} from '../...
add(sourceFile: ts.SourceFile, moduleName: string, imports: ts.Expression|null, exports: ts.Expression|null, providers: ts.Expression|null): void { const key = `${sourceFile.fileName}#${moduleName}`; if (this.modules.has(key)) { throw new Error(`Double route analyzing ${key}`); } this.mo...
{ this.entryPointManager = new RouterEntryPointManager(moduleResolver); }
identifier_body
analyzer.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import * as ts from 'typescript'; import {ModuleResolver} from '../../imports'; import {PartialEvaluator} from '../...
this.modules.set( key, { sourceFile, moduleName, imports, exports, providers, }); } listLazyRoutes(): LazyRoute[] { const routes: LazyRoute[] = []; for (const key of Array.from(this.modules.keys())) { const data = this.modules.get(key) !; const entryPo...
{ throw new Error(`Double route analyzing ${key}`); }
conditional_block
analyzer.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import * as ts from 'typescript'; import {ModuleResolver} from '../../imports'; import {PartialEvaluator} from '../...
(moduleResolver: ModuleResolver, private evaluator: PartialEvaluator) { this.entryPointManager = new RouterEntryPointManager(moduleResolver); } add(sourceFile: ts.SourceFile, moduleName: string, imports: ts.Expression|null, exports: ts.Expression|null, providers: ts.Expression|null): void { const key...
constructor
identifier_name
single-book.js
jQuery( document ).ready(function() { // hide the bottom buy links if the excerpt is closed if (jQuery('.mbm-book-excerpt-read-more').is(":visible"))
// handle the editions hide/show jQuery('.mbm-book-editions-toggle').on('click', function() { jQuery(this).siblings('.mbm-book-editions-subinfo').toggle(); jQuery(this).toggleClass('mbm-book-editions-open'); }); // open the excerpt jQuery('.mbm-book-excerpt-read-more').on( 'click', function() { jQuery(th...
{ jQuery('#mbm-book-links2').hide(); }
conditional_block
single-book.js
jQuery( document ).ready(function() { // hide the bottom buy links if the excerpt is closed if (jQuery('.mbm-book-excerpt-read-more').is(":visible")) { jQuery('#mbm-book-links2').hide(); } // handle the editions hide/show jQuery('.mbm-book-editions-toggle').on('click', function() { jQuery(this).siblings('.mbm...
jQuery(this).parent().toggle(); jQuery(this).parent().siblings('.mbm-book-excerpt-read-more').toggle(); jQuery('#mbm-book-links2').hide(); jQuery('html, body').animate({ scrollTop: (jQuery('.mbm-book-excerpt-read-more').offset().top - 100) },500); }); }); // ready
jQuery('.mbm-book-excerpt-collapse').on( 'click', function() {
random_line_split
lib.rs
#[macro_use] extern crate bitflags; extern crate nix; extern crate libc; mod itimer_spec; mod sys; use std::mem; use std::ptr; use std::os::unix::io::{RawFd, AsRawFd}; use nix::{Errno, Error}; use nix::unistd; use libc::{c_int, clockid_t}; pub use self::itimer_spec::*; #[doc(hidden)] const TIMERFD_DATA_SIZE: usize ...
(&mut self) { let _ = unistd::close(self.0); } } #[cfg(test)] mod tests { use super::*; use std::{time, thread}; use nix::sys::time::{TimeSpec, TimeValLike}; #[test] fn test_read_timerfd() { let mut timer = TimerFd::with_flags(ClockId::Monotonic, TFD_NONBLOCK).expec...
drop
identifier_name
lib.rs
#[macro_use] extern crate bitflags; extern crate nix; extern crate libc; mod itimer_spec; mod sys; use std::mem; use std::ptr; use std::os::unix::io::{RawFd, AsRawFd}; use nix::{Errno, Error}; use nix::unistd; use libc::{c_int, clockid_t}; pub use self::itimer_spec::*; #[doc(hidden)] const TIMERFD_DATA_SIZE: usize ...
#[inline] pub fn timerfd_settime( fd: RawFd, flags: TFDTimerFlags, utmr: &ITimerSpec, otmr: Option<&mut ITimerSpec>, ) -> nix::Result<()> { let res = unsafe { sys::timerfd_settime( fd, flags.bits(), utmr as *const ITimerSpec, otmr.map(|x| x a...
{ unsafe { Errno::result(sys::timerfd_create(clock_id, flags.bits())) } }
identifier_body
lib.rs
#[macro_use] extern crate bitflags; extern crate nix; extern crate libc; mod itimer_spec; mod sys; use std::mem; use std::ptr; use std::os::unix::io::{RawFd, AsRawFd}; use nix::{Errno, Error}; use nix::unistd; use libc::{c_int, clockid_t}; pub use self::itimer_spec::*; #[doc(hidden)] const TIMERFD_DATA_SIZE: usize ...
assert!(timer.read_time().unwrap().is_some()); } }
random_line_split
opening.rs
use std::io::prelude::*; use std::path::Path; use std::fs::File; use std::io::Result; use bitboard::Board; use bitboard::Move; use bitboard::Turn; /// ///Opening book file format: ///(16 bytes: hash table array size (n)) ///n * (20 bytes: (1 byte used)(16 bytes: board position, normalized)(1 byte: white best move)(...
{ file : File, } impl Opening { pub fn new(filename : String) -> Result<Opening> { let open_file = File::open(&filename)?; Ok(Opening { file : open_file, }) } pub fn get_move(&mut self, bb : Board, t : Turn) -> Result<Move> { Ok(Move::null()) ...
Opening
identifier_name
opening.rs
use std::io::prelude::*; use std::path::Path; use std::fs::File; use std::io::Result; use bitboard::Board; use bitboard::Move; use bitboard::Turn; ///
/// struct OpeningNode { hash_val_1 : u32, hash_val_2 : u32, black_minimax : i16, white_minimax : i16, best_alt_move : u16, alt_score : i16, flags : u16, } pub struct Opening { file : File, } impl Opening { pub fn new(filename : String) -> Resul...
///Opening book file format: ///(16 bytes: hash table array size (n)) ///n * (20 bytes: (1 byte used)(16 bytes: board position, normalized)(1 byte: white best move)(1 byte: black best move))
random_line_split
unix-sockets.js
'use strict'; const assert = require('assert'); let http = require('http'); let https = require('https'); const os = require('os'); const fs = require('fs'); const express = require('../support/express'); const request = require('../support/client'); const app = express(); const key = fs.readFileSync(`${__dirname}/f...
if (fs.existsSync(httpSockPath) === true) { // try unlink if sock file exists fs.unlinkSync(httpSockPath); } httpServer = http.createServer(app); httpServer.listen(httpSockPath, done); }); const base = `http+unix://${httpSockPath.replace(/\//g, '%2F')}`; describe('request', () => { ...
random_line_split
unix-sockets.js
'use strict'; const assert = require('assert'); let http = require('http'); let https = require('https'); const os = require('os'); const fs = require('fs'); const express = require('../support/express'); const request = require('../support/client'); const app = express(); const key = fs.readFileSync(`${__dirname}/f...
else { httpsServer = https.createServer({ key, cert }, app); } httpsServer.listen(httpsSockPath, done); }); const base = `https+unix://${httpsSockPath.replace(/\//g, '%2F')}`; describe('request', () => { it('path: / (root)', done => { request .get(`${base}/`) .ca(cacert...
{ httpsServer = https.createSecureServer({ key, cert }, app); }
conditional_block
block_device_mapping_v1.py
# Copyright 2013 OpenStack Foundation # All Rights Reserved. # # 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 # # Unless requ...
"""Block device mapping boot support.""" name = "BlockDeviceMappingV1" alias = ALIAS version = 1 def get_resources(self): return [] def get_controller_extensions(self): return [] # use nova.api.extensions.server.extensions entry point to modify # server create kwargs ...
identifier_body
block_device_mapping_v1.py
# Copyright 2013 OpenStack Foundation # All Rights Reserved. # # 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 # # Unless requ...
(extensions.V3APIExtensionBase): """Block device mapping boot support.""" name = "BlockDeviceMappingV1" alias = ALIAS version = 1 def get_resources(self): return [] def get_controller_extensions(self): return [] # use nova.api.extensions.server.extensions entry point to m...
BlockDeviceMappingV1
identifier_name
block_device_mapping_v1.py
# Copyright 2013 OpenStack Foundation # All Rights Reserved. # # 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 # # Unless requ...
create_kwargs['block_device_mapping'] = block_device_mapping # Sets the legacy_bdm flag if we got a legacy block device mapping. create_kwargs['legacy_bdm'] = True
conditional_block
block_device_mapping_v1.py
# Copyright 2013 OpenStack Foundation # All Rights Reserved. # # 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 # # Unless requ...
ATTRIBUTE_NAME_V2 = "block_device_mapping_v2" class BlockDeviceMappingV1(extensions.V3APIExtensionBase): """Block device mapping boot support.""" name = "BlockDeviceMappingV1" alias = ALIAS version = 1 def get_resources(self): return [] def get_controller_extensions(self): r...
from nova.i18n import _ from nova.openstack.common import strutils ALIAS = "os-block-device-mapping-v1" ATTRIBUTE_NAME = "block_device_mapping"
random_line_split
carmen.py
#!/usr/bin/python # Copyright 2013 Sumana Harihareswara # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This progra...
class Game(): def __init__(self): self.player = Hero() self.nemesis = Villain() def __repr__(self): return """A session of the game, with a hero and villain set up with names and locations.""" def wincondition(self): """The player wins when s/he is in the same Cit...
def __init__(self): self.location = ind self.name = raw_input("Detective at keyboard, identify yourself: ")
identifier_body
carmen.py
#!/usr/bin/python # Copyright 2013 Sumana Harihareswara # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This progra...
# along with this program. If not, see <http://www.gnu.org/licenses/>. """ A silly game in Python. See the README. """ import sys import random import textwrap import mock def anykey(): x = raw_input("Press Return to continue. ") + "a" class City(object): """Each City has a name, a set of destinations one ...
random_line_split
carmen.py
#!/usr/bin/python # Copyright 2013 Sumana Harihareswara # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This progra...
(object): """Each City has a name, a set of destinations one step away, and a clue.""" def __init__(self, n, c): self.dests = [] self.name = n self.clue = c class Villain(object): def __init__(self): self.name = random.choice(["Carmen", "Waldo", "Edward Snowden", "Lyra"]) ...
City
identifier_name
carmen.py
#!/usr/bin/python # Copyright 2013 Sumana Harihareswara # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # This progra...
def choose(self, path): try: path = int(path) except ValueError: print "That doesn't make sense, %s, because it's not the number for one of your possible destinations." % self.player.name print "So you stay in %s." % self.player.location.name return ...
print "%d. %s" % (i+1, x.name)
conditional_block
use_sax.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from xml.parsers.expat import ParserCreate class DefaultSaxHandler(object): def start_element(self, name, attrs): print('sax:start_element: %s, attrs: %s' % (name, str(attrs))) def
(self, name): print('sax:end_element: %s' % name) def char_data(self, text): print('sax:char_data: %s' % text) xml = r'''<?xml version="1.0"?> <ol> <li><a href="/python">Python</a></li> <li><a href="/ruby">Ruby</a></li> </ol> ''' handler = DefaultSaxHandler() parser = ParserCreate() pars...
end_element
identifier_name
use_sax.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from xml.parsers.expat import ParserCreate class DefaultSaxHandler(object): def start_element(self, name, attrs):
def end_element(self, name): print('sax:end_element: %s' % name) def char_data(self, text): print('sax:char_data: %s' % text) xml = r'''<?xml version="1.0"?> <ol> <li><a href="/python">Python</a></li> <li><a href="/ruby">Ruby</a></li> </ol> ''' handler = DefaultSaxHandler() parser ...
print('sax:start_element: %s, attrs: %s' % (name, str(attrs)))
identifier_body
use_sax.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from xml.parsers.expat import ParserCreate class DefaultSaxHandler(object): def start_element(self, name, attrs): print('sax:start_element: %s, attrs: %s' % (name, str(attrs))) def end_element(self, name): print('sax:end_element: %s' % name) ...
xml = r'''<?xml version="1.0"?> <ol> <li><a href="/python">Python</a></li> <li><a href="/ruby">Ruby</a></li> </ol> ''' handler = DefaultSaxHandler() parser = ParserCreate() parser.StartElementHandler = handler.start_element parser.EndElementHandler = handler.end_element parser.CharacterDataHandler = handler.ch...
print('sax:char_data: %s' % text)
random_line_split
screenbuffer-rect-test.js
/* Terminal Kit Copyright (c) 2009 - 2021 Cédric Ronvel The MIT License (MIT) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights ...
} ) ;
srcRect.clip( dstRect , 0 , -21 , true ) ; expect( dstRect.isNull ).to.be( true ) ; expect( srcRect.isNull ).to.be( true ) ; } ) ;
random_line_split
app.js
'use strict'; angular.module('plankApp', [ 'ngCookies', 'ngResource', 'ngSanitize', 'ui.router', 'ui.bootstrap' ]) .config(function ($stateProvider, $urlRouterProvider, $locationProvider, $httpProvider) { $urlRouterProvider.otherwise('/'); $locationProvider.html5Mode(true); // true mean drop the # ...
config.headers = config.headers || {}; if ($cookieStore.get('token')) { config.headers.Authorization = 'Bearer ' + $cookieStore.get('token'); } return config; }, // Intercept 401s and redirect you to login responseError: function(response) { if(respon...
random_line_split
app.js
'use strict'; angular.module('plankApp', [ 'ngCookies', 'ngResource', 'ngSanitize', 'ui.router', 'ui.bootstrap' ]) .config(function ($stateProvider, $urlRouterProvider, $locationProvider, $httpProvider) { $urlRouterProvider.otherwise('/'); $locationProvider.html5Mode(true); // true mean drop the # ...
} }; }) .run(function ($rootScope, $location, Auth, $state) { // Redirect to login if route requires auth and you're not logged in $rootScope.$on('$stateChangeStart', function (event, next) { Auth.isLoggedInAsync(function(loggedIn) { if (next.authenticate && !loggedIn) { ...
{ return $q.reject(response); }
conditional_block
dir_68267d1309a1af8e8297ef4c3efbcdba.js
] ], [ "BeagleGooP.cpp", "_beagle_goo_p_8cpp.html", "_beagle_goo_p_8cpp" ], [ "GPIOoo.cpp", "_g_p_i_ooo_8cpp.html", null ], [ "gpiotest.c", "gpiotest_8c.html", "gpiotest_8c" ], [ "HD44780.cpp", "_h_d44780_8cpp.html", null ], [ "HD44780gpioPhy.cpp", "_h_d44780gpio_phy_8cpp.html", "_h_d44780gpio_p...
var dir_68267d1309a1af8e8297ef4c3efbcdba = [ [ "BeagleGoo.cpp", "_beagle_goo_8cpp.html", [ [ "BeagleGoo", "struct_beagle_goo.html", "struct_beagle_goo" ]
random_line_split
timestamp.ts
import { OperatorFunction, Timestamp as TimestampInterface, TimestampProvider, Timestamp } from '../types'; import { map } from './map'; /** * Attaches a timestamp to each item emitted by an observable indicating when it was emitted * * The `timestamp` operator maps the *source* observable stream to an object of ty...
{ return map((value: T) => ({ value, timestamp: timestampProvider.now()})); }
identifier_body
timestamp.ts
import { OperatorFunction, Timestamp as TimestampInterface, TimestampProvider, Timestamp } from '../types'; import { map } from './map'; /** * Attaches a timestamp to each item emitted by an observable indicating when it was emitted * * The `timestamp` operator maps the *source* observable stream to an object of ty...
<T>(timestampProvider: TimestampProvider = Date): OperatorFunction<T, Timestamp<T>> { return map((value: T) => ({ value, timestamp: timestampProvider.now()})); }
timestamp
identifier_name
timestamp.ts
import { OperatorFunction, Timestamp as TimestampInterface, TimestampProvider, Timestamp } from '../types'; import { map } from './map'; /** * Attaches a timestamp to each item emitted by an observable indicating when it was emitted * * The `timestamp` operator maps the *source* observable stream to an object of ty...
}
return map((value: T) => ({ value, timestamp: timestampProvider.now()}));
random_line_split