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
member.component.spec.ts
import { SocialSharingComponent } from './social-sharing/social-sharing.component'; import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { MemberComponent } from './member.component'; import { MaterialModule } from '../material/material.module'; import { NO_ERRORS_SCHEMA } from '@angular/co...
component = fixture.componentInstance; component.member = { name: 'ben lesh', role: 'lead', githubUrl: '', avatar: '', twitterUrl: '', webpageUrl: '' }; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
beforeEach(() => { fixture = TestBed.createComponent(MemberComponent);
random_line_split
close-method.window.js
function assert_closed_opener(w, closed, opener)
async_test(t => { const openee = window.open(); assert_closed_opener(openee, false, self); openee.onunload = t.step_func(() => { assert_closed_opener(openee, true, self); t.step_timeout(() => { assert_closed_opener(openee, true, null); t.done(); }, 0); }); openee.close(); assert_cl...
{ assert_equals(w.closed, closed); assert_equals(w.opener, opener); }
identifier_body
close-method.window.js
function assert_closed_opener(w, closed, opener) { assert_equals(w.closed, closed); assert_equals(w.opener, opener); } async_test(t => { const openee = window.open(); assert_closed_opener(openee, false, self); openee.onunload = t.step_func(() => { assert_closed_opener(openee, true, self); t.step_time...
assert_closed_opener(openee, true, self); }, "window.close() queues a task to discard, but window.closed knows immediately"); async_test(t => { const openee = window.open("", "greatname"); assert_closed_opener(openee, false, self); openee.close(); assert_closed_opener(openee, true, self); const openee2 = w...
}); openee.close();
random_line_split
close-method.window.js
function
(w, closed, opener) { assert_equals(w.closed, closed); assert_equals(w.opener, opener); } async_test(t => { const openee = window.open(); assert_closed_opener(openee, false, self); openee.onunload = t.step_func(() => { assert_closed_opener(openee, true, self); t.step_timeout(() => { assert_clos...
assert_closed_opener
identifier_name
mona.rs
extern crate mon_artist; use mon_artist::render::svg::{SvgRender}; use mon_artist::render::{RenderS}; use mon_artist::grid::{Grid, ParseError}; use mon_artist::{SceneOpts}; use std::convert::From; use std::env; use std::fs::File; use std::io::{self, BufRead, BufReader, Read, Write}; fn main() { let mut args = en...
Parse(ParseError), } impl From<io::Error> for Error { fn from(e: io::Error) -> Self { Error::IO(e) } } impl From<ParseError> for Error { fn from(e: ParseError) -> Self { Error::Parse(e) } } use mon_artist::format::Table; fn get_table(table: &str) -> Table { match File::open(table) { Ok(input) => Tabl...
IO(io::Error),
random_line_split
mona.rs
extern crate mon_artist; use mon_artist::render::svg::{SvgRender}; use mon_artist::render::{RenderS}; use mon_artist::grid::{Grid, ParseError}; use mon_artist::{SceneOpts}; use std::convert::From; use std::env; use std::fs::File; use std::io::{self, BufRead, BufReader, Read, Write}; fn main() { let mut args = en...
(table: &str) -> Table { match File::open(table) { Ok(input) => Table::from_lines(BufReader::new(input).lines()), Err(err) => match table { "default" => Table::default(), "demo" => Table::demo(), _ => panic!("Unknown table name: {}, file err: {:?}", table, err)...
get_table
identifier_name
mona.rs
extern crate mon_artist; use mon_artist::render::svg::{SvgRender}; use mon_artist::render::{RenderS}; use mon_artist::grid::{Grid, ParseError}; use mon_artist::{SceneOpts}; use std::convert::From; use std::env; use std::fs::File; use std::io::{self, BufRead, BufReader, Read, Write}; fn main() { let mut args = en...
else { break; }; let in_file = if let Some(arg) = args.next() { arg } else { break; }; let out_file = if let Some(arg) = args.next() { arg } else { break; }; println!("processing {} to {} via {}", in_file, out_file, table); process(&table, &in_file, &out_file).unwrap(); } // d...
{ arg }
conditional_block
util.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the ...
let content = matches.name("content").map(|r| r.as_str()).unwrap_or(""); Ok((Value::parse(header.as_str())?, String::from(content))) }
random_line_split
util.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the ...
(buf: &str) -> Result<(Value, String)> { debug!("Building entry from string"); lazy_static! { static ref RE: Regex = Regex::new(r"(?smx) ^---$ (?P<header>.*) # Header ^---$\n (?P<content>.*) # Content ").unwrap(); } let matches = match RE....
entry_buffer_to_header_content
identifier_name
util.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the ...
{ debug!("Building entry from string"); lazy_static! { static ref RE: Regex = Regex::new(r"(?smx) ^---$ (?P<header>.*) # Header ^---$\n (?P<content>.*) # Content ").unwrap(); } let matches = match RE.captures(buf) { None => retu...
identifier_body
dbscanplot.py
import requests import time import dblayer from sklearn.cluster import DBSCAN import plotly import plotly.graph_objs as go import pandas as pd import numpy as np import random import testfile # Create random colors in list color_list = [] def generate_color(ncluster): for i in range(ncluster): color = '...
start_time = time.time() #### sess = requests.Session() dbobj=dblayer.classDBLayer() projection = [{"$project": {"_id": 0, "mag": "$properties.mag", "depth": {"$arrayElemAt": ["$geometry.coordinates", 2]}, "longitude": {"$arrayElemAt": ["$geometr...
identifier_body
dbscanplot.py
import requests import time import dblayer from sklearn.cluster import DBSCAN import plotly import plotly.graph_objs as go import pandas as pd import numpy as np import random import testfile # Create random colors in list color_list = [] def generate_color(ncluster): for i in range(ncluster):
def showLatLongInCluster(data): # Run the DBSCAN from sklearn dbscan = DBSCAN(eps=2, min_samples=5, metric='euclidean', algorithm='auto').fit(data) cluster_labels = dbscan.labels_ n_clusters = len(set(cluster_labels)) - (1 if -1 in cluster_labels else 0) generate_color(n_clusters) plot_data...
color = '#{:02x}{:02x}{:02x}'.format(*map(lambda x: random.randint(0, 255), range(ncluster))) color_list.append(color)
conditional_block
dbscanplot.py
import requests import time import dblayer from sklearn.cluster import DBSCAN import plotly import plotly.graph_objs as go import pandas as pd import numpy as np import random import testfile # Create random colors in list color_list = [] def
(ncluster): for i in range(ncluster): color = '#{:02x}{:02x}{:02x}'.format(*map(lambda x: random.randint(0, 255), range(ncluster))) color_list.append(color) def showLatLongInCluster(data): # Run the DBSCAN from sklearn dbscan = DBSCAN(eps=2, min_samples=5, metric='euclidean', algorithm='au...
generate_color
identifier_name
dbscanplot.py
import requests import time import dblayer from sklearn.cluster import DBSCAN import plotly import plotly.graph_objs as go import pandas as pd import numpy as np import random import testfile # Create random colors in list color_list = []
color = '#{:02x}{:02x}{:02x}'.format(*map(lambda x: random.randint(0, 255), range(ncluster))) color_list.append(color) def showLatLongInCluster(data): # Run the DBSCAN from sklearn dbscan = DBSCAN(eps=2, min_samples=5, metric='euclidean', algorithm='auto').fit(data) cluster_labels = dbsca...
def generate_color(ncluster): for i in range(ncluster):
random_line_split
ContestEditor.tsx
/* 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/. * * Copyright (c) 2016 Jacob Peddicord <jacob@peddicord.net> */ import * as React from 'react'; import { connect }...
extends React.Component<Props, {}> { static formatTimestamp(stamp) { if (stamp == null || !stamp.isValid()) { return ''; } return stamp.format('YYYY-MM-DD HH:mm:ss Z'); } saveContest = e => { const { dispatch, active } = this.props; const fields = e.target.elements; e.preventDefau...
ContestEditor
identifier_name
ContestEditor.tsx
/* 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/. * * Copyright (c) 2016 Jacob Peddicord <jacob@peddicord.net> */ import * as React from 'react'; import { connect }...
<div className="form-group row"> <label htmlFor="contest_problems" className="col-3 col-form-label col-form-label-sm">Problems</label> <div className="col-9"> <textarea id="contest_problems" defaultValue={active.problems.join('\n')} rows={6} className="form-control form-c...
</div> </div>
random_line_split
ContestEditor.tsx
/* 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/. * * Copyright (c) 2016 Jacob Peddicord <jacob@peddicord.net> */ import * as React from 'react'; import { connect }...
return v; } dispatch(updateContest(active.id, { title: nully(fields.contest_title.value), start_time: nully(fields.contest_start_time.value), end_time: nully(fields.contest_end_time.value), mode: fields.contest_mode.value, code: nully(fields.contest_code.value), probl...
{ return null; }
conditional_block
ContestEditor.tsx
/* 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/. * * Copyright (c) 2016 Jacob Peddicord <jacob@peddicord.net> */ import * as React from 'react'; import { connect }...
} export default connect(state => { return { active: state.contests.active, }; })(ContestEditor) as React.ComponentClass<{}>;
{ const { active } = this.props; const startTime = ContestEditor.formatTimestamp(active.start_time); const endTime = ContestEditor.formatTimestamp(active.end_time); return ( <SafetyBox> <form onSubmit={this.saveContest} className="container"> <div className="form-group row"> ...
identifier_body
LogService.js
module.exports = { login: function(user, req) { // Parse detailed information from user-agent string var r = require('ua-parser').parse(req.headers['user-agent']); // Create new UserLogin row to database sails.models.loglogin.create({ ip: req.ip, host: req.host, agent: req.headers...
request: function(log, req, resp) { //var userId = -1; // if (req.token) { // userId = req.token; // } else { // userId = -1; // } sails.models.logrequest.create({ ip: log.ip, protocol: log.protocol, method: log.method, url: log.diagnostic.url, headers...
created.user = user; sails.models.loglogin.publishCreate(created); }); },
random_line_split
upgrade042.py
self.description = "Backup file relocation" lp1 = pmpkg("bash") lp1.files = ["etc/profile*"] lp1.backup = ["etc/profile"] self.addpkg2db("local", lp1) p1 = pmpkg("bash", "1.0-2") self.addpkg(p1) lp2 = pmpkg("filesystem") self.addpkg2db("local", lp2) p2 = pmpkg("filesystem", "1.0-2") p2.files = ["etc/profile**"] p2....
self.addpkg(p2) self.args = "-U %s" % " ".join([p.filename() for p in (p1, p2)]) self.filesystem = ["etc/profile"] self.addrule("PACMAN_RETCODE=0") self.addrule("PKG_VERSION=bash|1.0-2") self.addrule("PKG_VERSION=filesystem|1.0-2") self.addrule("!FILE_PACSAVE=etc/profile") self.addrule("FILE_PACNEW=etc/profile") sel...
p2.depends = [ "bash" ]
random_line_split
helpper.js
//Init var CANVAS_WIDTH = 512; var CANVAS_HEIGHT = 512; var MOVABLE = "movable"; //jiglib body types in strings var BODY_TYPES = ["SPHERE", "BOX","CAPSULE", "PLANE"]; //enums for indexing BODY_TYPES var BodyValues = {"SPHERE":0, "BOX":1, "CAPSULE":2, "PLANE":3}; var SCORE_LOC_X = 130; var SCORE_LOC_Y = 475;
var SCORE_TEXT_CONTENT = "score:"; //Factors for the ray xyz-values. Used in initStatusScene() var RAY_FACTOR_X = -5; var RAY_FACTOR_Y = 5; var RAY_FACTOR_Z = -5; //Start and end message constants var GAME_OVER_TEXT = "Game over!"; var START_GAME_TEXT = "Press 'enter' to start!"; var START_OFFSET_X = 0; var START_OFF...
var SCORETEXT_LOC_X = 70; var SCORETEXT_LOC_Y = 478;
random_line_split
helpper.js
//Init var CANVAS_WIDTH = 512; var CANVAS_HEIGHT = 512; var MOVABLE = "movable"; //jiglib body types in strings var BODY_TYPES = ["SPHERE", "BOX","CAPSULE", "PLANE"]; //enums for indexing BODY_TYPES var BodyValues = {"SPHERE":0, "BOX":1, "CAPSULE":2, "PLANE":3}; var SCORE_LOC_X = 130; var SCORE_LOC_Y = 475; var SC...
else if(side1 >= 0.0 && side2 >= 0.0 && side2 > side1){ return(side2-side1); } else if(side1 < 0.0 && side2 < 0.0 && Math.abs(side1) > Math.abs(side2)){ return(Math.abs(side1)-Math.abs(side2)); } else if(side1 < 0.0 && side2 < 0.0 && Math.abs(side2) > Math.abs(side1)){ return(Math.abs(side2)-Math.a...
return(side1-side2); }
conditional_block
theming-tests.tsx
import * as React from "react"; import { channel, ContextWithTheme, Theme, themeListener, ThemeProvider, withTheme } from "theming"; // Typings currently accept non-plain-objects while they get rejected at runtime. // There exists currently no typing for plain objects. const runtimeErrorTheme: Theme = []; ...
primary: "red", secondary: "blue" } }; type CustomTheme = typeof customTheme; interface DemoBoxProps { text: string; theme: CustomTheme; } const DemoBox = ({ text, theme }: DemoBoxProps) => { return <div style={{ color: theme.color.primary }}>{text}</div>; }; const ThemedDemoBox = withTheme(DemoBox); c...
color: {
random_line_split
theming-tests.tsx
import * as React from "react"; import { channel, ContextWithTheme, Theme, themeListener, ThemeProvider, withTheme } from "theming"; // Typings currently accept non-plain-objects while they get rejected at runtime. // There exists currently no typing for plain objects. const runtimeErrorTheme: Theme = []; ...
componentDidMount() { this.subscription = themeListener.subscribe(this.context, this.setTheme); } componentWillUnmount() { const { subscription } = this; if (subscription != null) { themeListener.unsubscribe(this.context, subscription); } } render() { const { t...
{ super(props, context); this.state = { theme: themeListener.initial(context) }; }
identifier_body
theming-tests.tsx
import * as React from "react"; import { channel, ContextWithTheme, Theme, themeListener, ThemeProvider, withTheme } from "theming"; // Typings currently accept non-plain-objects while they get rejected at runtime. // There exists currently no typing for plain objects. const runtimeErrorTheme: Theme = []; ...
() { const { subscription } = this; if (subscription != null) { themeListener.unsubscribe(this.context, subscription); } } render() { const { theme } = this.state; return <Component theme={theme} {...this.props} />; } }; }
componentWillUnmount
identifier_name
theming-tests.tsx
import * as React from "react"; import { channel, ContextWithTheme, Theme, themeListener, ThemeProvider, withTheme } from "theming"; // Typings currently accept non-plain-objects while they get rejected at runtime. // There exists currently no typing for plain objects. const runtimeErrorTheme: Theme = []; ...
} render() { const { theme } = this.state; return <Component theme={theme} {...this.props} />; } }; }
{ themeListener.unsubscribe(this.context, subscription); }
conditional_block
setup.py
#!/usr/bin/env python # This file is part of Py6S. # # Copyright 2012 Robin Wilson and contributors listed in the CONTRIBUTORS file. # # Py6S is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either versi...
PROJECT_ROOT = os.path.dirname(__file__) def read_file(filepath, root=PROJECT_ROOT): """ Return the contents of the specified `filepath`. * `root` is the base path and it defaults to the `PROJECT_ROOT` directory. * `filepath` should be a relative path, starting from `root`. """ with open(os....
# along with Py6S. If not, see <http://www.gnu.org/licenses/>. import os from setuptools import setup
random_line_split
setup.py
#!/usr/bin/env python # This file is part of Py6S. # # Copyright 2012 Robin Wilson and contributors listed in the CONTRIBUTORS file. # # Py6S is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either versi...
LONG_DESCRIPTION = read_file("README.rst") SHORT_DESCRIPTION = "A wrapper for the 6S Radiative Transfer Model to make it easy to run simulations with a variety of input parameters, and to produce outputs in an easily processable form." REQS = [ 'pysolar==0.6', 'matplotlib', 'scipy' ] setup( name ...
""" Return the contents of the specified `filepath`. * `root` is the base path and it defaults to the `PROJECT_ROOT` directory. * `filepath` should be a relative path, starting from `root`. """ with open(os.path.join(root, filepath)) as fd: text = fd.read() return text
identifier_body
setup.py
#!/usr/bin/env python # This file is part of Py6S. # # Copyright 2012 Robin Wilson and contributors listed in the CONTRIBUTORS file. # # Py6S is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either versi...
(filepath, root=PROJECT_ROOT): """ Return the contents of the specified `filepath`. * `root` is the base path and it defaults to the `PROJECT_ROOT` directory. * `filepath` should be a relative path, starting from `root`. """ with open(os.path.join(root, filepath)) as fd: text = fd.read(...
read_file
identifier_name
elem.js
module.exports = { dom(element,type){ let DOM = document.createElement(element); if(type){ for(let key in type){ DOM.setAttribute(key,type[key]) } } return DOM }, // 添加类 addClass(element,newclass){ if(element.className){ var oldClass=element.className; element.cl...
, removeClass(element, a_class){ var obj_class = ' '+element.className+' ';//获取 class 内容, 并在首尾各加一个空格. ex) 'abc bcd' -> ' abc bcd ' obj_class = obj_class.replace(/(\s+)/gi, ' ');//将多余的空字符替换成一个空格. ex) ' abc bcd ' -> ' abc bcd ' var removed = obj_class.replace(' '+a_class+' ', ' ');...
element.className=newclass; } }
conditional_block
elem.js
module.exports = { dom(element,type){ let DOM = document.createElement(element); if(type){ for(let key in type){ DOM.setAttribute(key,type[key]) } } return DOM }, // 添加类
}else{ element.className=newclass; } }, removeClass(element, a_class){ var obj_class = ' '+element.className+' ';//获取 class 内容, 并在首尾各加一个空格. ex) 'abc bcd' -> ' abc bcd ' obj_class = obj_class.replace(/(\s+)/gi, ' ');//将多余的空字符替换成一个空格. ex) ' abc bcd ' -> ' ab...
addClass(element,newclass){ if(element.className){ var oldClass=element.className; element.className=oldClass+" "+newclass;
random_line_split
elem.js
module.exports = { dom(element,type){ let DOM = document.createElement(element); if(type){ for(let key in type){ DOM.setAttribute(key,type[key]) } } return DOM }, // 添加类 addCla
nt,newclass){ if(element.className){ var oldClass=element.className; element.className=oldClass+" "+newclass; }else{ element.className=newclass; } }, removeClass(element, a_class){ var obj_class = ' '+element.className+' ';//获取 class 内容, 并在首...
ss(eleme
identifier_name
elem.js
module.exports = { dom(element,type){ let DOM = document.createElement(element); if(type){ for(let key in type){ DOM.setAttribute(key,type[key]) } } return DOM }, // 添加类 addClass(element,newclass){
removeClass(element, a_class){ var obj_class = ' '+element.className+' ';//获取 class 内容, 并在首尾各加一个空格. ex) 'abc bcd' -> ' abc bcd ' obj_class = obj_class.replace(/(\s+)/gi, ' ');//将多余的空字符替换成一个空格. ex) ' abc bcd ' -> ' abc bcd ' var removed = obj_class.replace(' '+a_class+' ', ' ');//在原来的...
if(element.className){ var oldClass=element.className; element.className=oldClass+" "+newclass; }else{ element.className=newclass; } },
identifier_body
index.js
/** * Return an array of valid extensions, eg. ['.js','.json','.node'] * * @api public */ function require_extensions() { return Object.keys(require.extensions); } module.exports = require_extensions; /** * return a glob pattern for `require.extensions` * * @api public */ function glob() { return '.{'+ ...
(group) { return new RegExp(regexp_string(group)+'$'); } module.exports.regexp = regexp; /** * return a new `String` regular expression that matches `require.extensions` * * @api public */ function regexp_string(group) { return '(' + (group ? '' : '?:') + (require_extensions() .map(function(ext){...
regexp
identifier_name
index.js
/** * Return an array of valid extensions, eg. ['.js','.json','.node'] * * @api public */ function require_extensions()
module.exports = require_extensions; /** * return a glob pattern for `require.extensions` * * @api public */ function glob() { return '.{'+ require_extensions() .map(function(ext) { return ext.substr(1) }) .join(',') +'}'; } module.exports.glob = glob; /** * return a new `RegExp` obje...
{ return Object.keys(require.extensions); }
identifier_body
index.js
/** * Return an array of valid extensions, eg. ['.js','.json','.node'] * * @api public */ function require_extensions() { return Object.keys(require.extensions); } module.exports = require_extensions; /** * return a glob pattern for `require.extensions` * * @api public */ function glob() { return '.{'+ ...
* @api public */ function regexp(group) { return new RegExp(regexp_string(group)+'$'); } module.exports.regexp = regexp; /** * return a new `String` regular expression that matches `require.extensions` * * @api public */ function regexp_string(group) { return '(' + (group ? '' : '?:') + (require_extensions...
*
random_line_split
lib.rs
/* * Exopticon - A free video surveillance system. * Copyright (C) 2020 David Matthew Mattli <dmm@mattli.us> * * This file is part of Exopticon. * * Exopticon 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 Founda...
let iso_begin_time = { assert!(!iso_begin_time.is_null()); CStr::from_ptr(iso_begin_time) .to_string_lossy() .into_owned() }; let message = CaptureMessage::NewFile { filename, begin_time: iso_begin_time, }; print_message(message); } /// Sen...
CStr::from_ptr(filename).to_string_lossy().into_owned() };
random_line_split
lib.rs
/* * Exopticon - A free video surveillance system. * Copyright (C) 2020 David Matthew Mattli <dmm@mattli.us> * * This file is part of Exopticon. * * Exopticon 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 Founda...
/// Send a message signaling the closing of a file. /// /// # Safety /// /// filename and iso_end_time must be null-terminated character arrays. /// #[no_mangle] pub unsafe extern "C" fn send_end_file_message( filename: *const c_char, iso_end_time: *const c_char, ) { let filename = { assert!(!file...
{ let filename = { assert!(!filename.is_null()); CStr::from_ptr(filename).to_string_lossy().into_owned() }; let iso_begin_time = { assert!(!iso_begin_time.is_null()); CStr::from_ptr(iso_begin_time) .to_string_lossy() .into_owned() }; let me...
identifier_body
lib.rs
/* * Exopticon - A free video surveillance system. * Copyright (C) 2020 David Matthew Mattli <dmm@mattli.us> * * This file is part of Exopticon. * * Exopticon 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 Founda...
(_level: i32, message: *const c_char) { let message = { assert!(!message.is_null()); CStr::from_ptr(message).to_string_lossy().into_owned() }; let capture_message = CaptureMessage::Log { message }; print_message(capture_message); } #[cfg(test)] mod tests { #[test] fn it_works...
send_log_message
identifier_name
module.ts
import {AnimationAnnotation, registerAnimation} from "./animation"; import {ComponentAnnotation, publishComponent} from "./component"; import {ConstantWrapper, publishConstant} from "./constant"; import {DecoratorAnnotation, publishDecorator} from "./decorator"; import {DirectiveAnnotation, publishDirective} from "./di...
else if (hasAnnotation(dep, DecoratorAnnotation)) { decorators.push(dep); } else if (hasAnnotation(dep, FilterAnnotation)) { filters.push(dep); } else if (hasAnnotation(dep, AnimationAnnotation)) { animations.push(dep); } else ...
{ services.push(dep); }
conditional_block
module.ts
import {AnimationAnnotation, registerAnimation} from "./animation"; import {ComponentAnnotation, publishComponent} from "./component"; import {ConstantWrapper, publishConstant} from "./constant"; import {DecoratorAnnotation, publishDecorator} from "./decorator"; import {DirectiveAnnotation, publishDirective} from "./di...
{ name: string = void 0; dependencies: DependenciesArray = void 0; config: Function|Function[] = void 0; run: Function|Function[] = void 0; // modules: (string|Function)[] = void 0; // components: Function[] = void 0; // services: Function[] = void 0; // filters: Function[] = void 0; ...
ModuleAnnotation
identifier_name
module.ts
import {AnimationAnnotation, registerAnimation} from "./animation"; import {ComponentAnnotation, publishComponent} from "./component"; import {ConstantWrapper, publishConstant} from "./constant"; import {DecoratorAnnotation, publishDecorator} from "./decorator"; import {DirectiveAnnotation, publishDirective} from "./di...
let _config = isArray(module.config) ? module.config : [module.config]; for (let config of _config) { (<Function[]> mergedArrays.config).push(config); } } } aux.push(mergedArrays); } let annotation = mergeAnnotatio...
random_line_split
module.ts
import {AnimationAnnotation, registerAnimation} from "./animation"; import {ComponentAnnotation, publishComponent} from "./component"; import {ConstantWrapper, publishConstant} from "./constant"; import {DecoratorAnnotation, publishDecorator} from "./decorator"; import {DirectiveAnnotation, publishDirective} from "./di...
/** * @internal */ export function publishModule(moduleClass: ModuleConstructor, name?: string, dependencies?: DependenciesArray, constructorParameters?: any[]): ng.IModule { let aux: ModuleAnnotation[] = getAnnotations(moduleClass, ModuleAnnotation);...
{ return `tng_generated_module#${++moduleCount}`; }
identifier_body
websocket.py
# versione 0.5 import socket import threading import hashlib import base64 import json class BadWSRequest(Exception): pass class BadWSFrame(Exception): pass class BadCmdCall(Exception): pass class BadCmdParam(Exception): pass class Client(threading.Thread): _MAGIC_STRING = '258EAFA5-E914-47...
(self): #FIN bit and opcode 0x8 (0x88 is 10001000 binary sequence) #Mask and length bits are zero self.socket.send(b'\x88\x00') #Empty the remote buffer self.socket.recv(100) def run(self): print('[+] Connection established with ' + self.ip + ':' + str(self.port), "...
_sndClose
identifier_name
websocket.py
# versione 0.5 import socket import threading import hashlib import base64 import json class BadWSRequest(Exception): pass class BadWSFrame(Exception): pass class BadCmdCall(Exception): pass class BadCmdParam(Exception): pass class Client(threading.Thread): _MAGIC_STRING = '258EAFA5-E914-47...
def _sndResponse(self, data): data = json.dumps(data).encode('utf-8') length = len(data) #FIN bit and opcode 0x1 (0x81 is 10000001 binary sequence) payload = b'\x81' if length >= 65535: #Over the maximum length allowed by 16bit addressing raise Ba...
raise BadWSFrame('Unknown OpCode')
conditional_block
websocket.py
# versione 0.5 import socket import threading import hashlib import base64 import json class BadWSRequest(Exception): pass class BadWSFrame(Exception): pass class BadCmdCall(Exception): pass class BadCmdParam(Exception): pass class Client(threading.Thread): _MAGIC_STRING = '258EAFA5-E914-47...
print('FIN: ' + str( rcvBuffer[0] >> 7 )) #0x0f is 00001111 binary sequence opcode = rcvBuffer[0] & 0x0f print('opcode: ' + hex( opcode )) maskBit = rcvBuffer[1] >> 7 print('mask: ' + str( maskBit )) if maskBit != 1: raise BadWSFrame('Unmasked data')...
#2nd byte: MASKED, PAYLOAD_LENGTH (7 bit) rcvBuffer = self.socket.recv(2)
random_line_split
websocket.py
# versione 0.5 import socket import threading import hashlib import base64 import json class BadWSRequest(Exception): pass class BadWSFrame(Exception): pass class BadCmdCall(Exception): pass class BadCmdParam(Exception): pass class Client(threading.Thread): _MAGIC_STRING = '258EAFA5-E914-47...
def executeAction(self, clientInstance, request): #Array of two element is expected function, parameters = request if function in self.actionDict: try: return self.actionDict[function](*parameters) except TypeError: raise BadCmdPara...
self.actionDict.update({ functionName: function })
identifier_body
gruntfile.js
var $path = require('path'); module.exports = function(grunt) { grunt.initConfig({ localBase : $path.resolve(__dirname), pkg: grunt.file.readJSON('package.json'), litheConcat : { options : { cwd: '<%=localBase%>' }, publish : { src : 'public/js/', dest : 'public/js/dist/', ...
litheCompress : { options : { cwd: '<%=localBase%>' }, publish : { src : 'public/js/dist/', dest : 'public/js/dist/' } } }); grunt.loadTasks('tasks/lithe'); grunt.registerTask( 'publish', '[COMMON] pack and compress files, then distribute', [ 'litheConcat:publi...
], target : 'conf/' } },
random_line_split
setup.py
Overlays on map tiles in Python. """ from setuptools import setup setup( name='pymapplot', version='0.0.1', url='https://github.com/HengfengLi/pymapplot', license='MIT', author='Hengfeng Li', author_email='hengf.li@gmail.com', description=('Overlays on map tiles in Python. '), long_des...
""" PyMapPlot --------------
random_line_split
lib.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(bytes: &[u8], flags: c_int) -> Option<CVec<u8>> { unsafe { let mut outsz : size_t = 0; let res = tdefl_compress_mem_to_heap(bytes.as_ptr() as *c_void, bytes.len() as size_t, &mut outsz, ...
deflate_bytes_internal
identifier_name
lib.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
else { None } } } /// Compress a buffer, without writing any sort of header on the output. pub fn deflate_bytes(bytes: &[u8]) -> Option<CVec<u8>> { deflate_bytes_internal(bytes, LZ_NORM) } /// Compress a buffer, using a header that zlib can understand. pub fn deflate_bytes_zlib(bytes: &[u...
{ Some(CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res))) }
conditional_block
lib.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn deflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<CVec<u8>> { unsafe { let mut outsz : size_t = 0; let res = tdefl_compress_mem_to_heap(bytes.as_ptr() as *c_void, bytes.len() as size_t, ...
static TINFL_FLAG_PARSE_ZLIB_HEADER : c_int = 0x1; // parse zlib header and adler32 checksum static TDEFL_WRITE_ZLIB_HEADER : c_int = 0x01000; // write zlib header and adler32 checksum
random_line_split
lib.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
/// Decompress a buffer that starts with a zlib header. pub fn inflate_bytes_zlib(bytes: &[u8]) -> Option<CVec<u8>> { inflate_bytes_internal(bytes, TINFL_FLAG_PARSE_ZLIB_HEADER) } #[cfg(test)] mod tests { use super::{inflate_bytes, deflate_bytes}; use std::rand; use std::rand::Rng; #[test] #...
{ inflate_bytes_internal(bytes, 0) }
identifier_body
PracticeQuestions.py
"""Chapter 22 Practice Questions Answers Chapter 22 Practice Questions via Python code.
def main(): # 1. How many prime numbers are there? # Hint: Check page 322 message = "Iymdi ah rv urxxeqfi fjdjqv gu gzuqw clunijh." # Encrypted with key "PRIMES" #print(decryptMessage(blank, blank)) # Fill in the blanks # 2. What are integers that are not prime called? # Hint: Check page 323...
""" from pythontutorials.books.CrackingCodes.Ch18.vigenereCipher import decryptMessage
random_line_split
PracticeQuestions.py
"""Chapter 22 Practice Questions Answers Chapter 22 Practice Questions via Python code. """ from pythontutorials.books.CrackingCodes.Ch18.vigenereCipher import decryptMessage def main(): # 1. How many prime numbers are there? # Hint: Check page 322
# If PracticeQuestions.py is run (instead of imported as a module), call # the main() function: if __name__ == '__main__': main()
message = "Iymdi ah rv urxxeqfi fjdjqv gu gzuqw clunijh." # Encrypted with key "PRIMES" #print(decryptMessage(blank, blank)) # Fill in the blanks # 2. What are integers that are not prime called? # Hint: Check page 323 message = "Vbmggpcw wlvx njr bhv pctqh emi psyzxf czxtrwdxr fhaugrd." # Encrypted...
identifier_body
PracticeQuestions.py
"""Chapter 22 Practice Questions Answers Chapter 22 Practice Questions via Python code. """ from pythontutorials.books.CrackingCodes.Ch18.vigenereCipher import decryptMessage def main(): # 1. How many prime numbers are there? # Hint: Check page 322 message = "Iymdi ah rv urxxeqfi fjdjqv gu gzuqw clunijh...
main()
conditional_block
PracticeQuestions.py
"""Chapter 22 Practice Questions Answers Chapter 22 Practice Questions via Python code. """ from pythontutorials.books.CrackingCodes.Ch18.vigenereCipher import decryptMessage def
(): # 1. How many prime numbers are there? # Hint: Check page 322 message = "Iymdi ah rv urxxeqfi fjdjqv gu gzuqw clunijh." # Encrypted with key "PRIMES" #print(decryptMessage(blank, blank)) # Fill in the blanks # 2. What are integers that are not prime called? # Hint: Check page 323 mess...
main
identifier_name
mutable.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use crate::*; pub trait SyncMutable { fn put(&self, key: &[u8], value: &[u8]) -> Result<()>; fn put_cf(&self, cf: &str, key: &[u8], value: &[u8]) -> Result<()>; fn delete(&self, key: &[u8]) -> Result<()>; fn delete_cf(&self, cf: &st...
}
{ self.put_cf(cf, key, &m.write_to_bytes()?) }
identifier_body
mutable.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use crate::*; pub trait SyncMutable { fn put(&self, key: &[u8], value: &[u8]) -> Result<()>; fn put_cf(&self, cf: &str, key: &[u8], value: &[u8]) -> Result<()>; fn delete(&self, key: &[u8]) -> Result<()>; fn delete_cf(&self, cf: &st...
<M: protobuf::Message>(&self, key: &[u8], m: &M) -> Result<()> { self.put(key, &m.write_to_bytes()?) } fn put_msg_cf<M: protobuf::Message>(&self, cf: &str, key: &[u8], m: &M) -> Result<()> { self.put_cf(cf, key, &m.write_to_bytes()?) } }
put_msg
identifier_name
mutable.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use crate::*; pub trait SyncMutable { fn put(&self, key: &[u8], value: &[u8]) -> Result<()>; fn put_cf(&self, cf: &str, key: &[u8], value: &[u8]) -> Result<()>; fn delete(&self, key: &[u8]) -> Result<()>; fn delete_cf(&self, cf: &st...
} fn put_msg_cf<M: protobuf::Message>(&self, cf: &str, key: &[u8], m: &M) -> Result<()> { self.put_cf(cf, key, &m.write_to_bytes()?) } }
fn put_msg<M: protobuf::Message>(&self, key: &[u8], m: &M) -> Result<()> { self.put(key, &m.write_to_bytes()?)
random_line_split
wsgi.py
""" WSGI config for server project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` s...
middleware here, or combine a Django application with an application of another framework. """ import os # We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks # if running multiple sites in the same mod_wsgi process. To fix this, use # mod_wsgi daemon mode with each site in its own daemon pro...
might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI
random_line_split
elf_arch-i386.rs
pub const ELF_CLASS: u8 = 1; pub type ElfAddr = u32; pub type ElfHalf = u16; pub type ElfOff = u32; pub type ElfWord = u32; /// An ELF header #[repr(packed)] pub struct ElfHeader { /// The "magic number" (4 bytes) pub magic: [u8; 4], /// 64 or 32 bit? pub class: u8, /// Little (1) or big endianness...
pub ver_2: ElfWord, /// The ELF entry pub entry: ElfAddr, /// The program header table offset pub ph_off: ElfOff, /// The section header table offset pub sh_off: ElfOff, /// The flags set pub flags: ElfWord, /// The header table length pub h_len: ElfHalf, /// The program ...
/// Second version
random_line_split
elf_arch-i386.rs
pub const ELF_CLASS: u8 = 1; pub type ElfAddr = u32; pub type ElfHalf = u16; pub type ElfOff = u32; pub type ElfWord = u32; /// An ELF header #[repr(packed)] pub struct ElfHeader { /// The "magic number" (4 bytes) pub magic: [u8; 4], /// 64 or 32 bit? pub class: u8, /// Little (1) or big endianness...
{ pub _type: ElfWord, pub off: ElfOff, pub vaddr: ElfAddr, pub paddr: ElfAddr, pub file_len: ElfWord, pub mem_len: ElfWord, pub flags: ElfWord, pub align: ElfWord, } /// An ELF section #[repr(packed)] pub struct ElfSection { pub name: ElfWord, pub _type: ElfWord, pub flags:...
ElfSegment
identifier_name
test_despike.py
import numpy as np from apvisitproc import despike import pytest import os DATAPATH = os.path.dirname(__file__) FILELIST1 = os.path.join(DATAPATH, 'list_of_txt_spectra.txt') FILELIST2 = os.path.join(DATAPATH, 'list_of_fits_spectra.txt') @pytest.fixture def wave_spec_generate(): ''' Read in three small chunks...
def test_simpledespike(wave_spec_generate): ''' spike condition is met at pixels 15, 16, 17 and 18 so indices 9 through 24, inclusive, should be removed ''' wave, spec = wave_spec_generate[0], wave_spec_generate[1] newwave, newspec = despike.simpledespike(wave, spec, delwindow=6, ...
assert all(value >= 0 for value in wave) assert list(np.sort(wave)) == list(wave) assert all(np.equal(np.sort(wave), wave))
conditional_block
test_despike.py
import numpy as np from apvisitproc import despike import pytest import os DATAPATH = os.path.dirname(__file__) FILELIST1 = os.path.join(DATAPATH, 'list_of_txt_spectra.txt') FILELIST2 = os.path.join(DATAPATH, 'list_of_fits_spectra.txt') @pytest.fixture def wave_spec_generate(): ''' Read in three small chunks...
''' wavelist, speclist = wave_spec_generate[2], wave_spec_generate[3] newwavelist, newspeclist = despike.despike_spectra(wavelist, speclist, type='simple', plot=False) assert len(newwavelist) == len(wavelist) assert len(newspeclist) == len(speclist)
Test that new spectra are shorter than the original because the outliers are gone
random_line_split
test_despike.py
import numpy as np from apvisitproc import despike import pytest import os DATAPATH = os.path.dirname(__file__) FILELIST1 = os.path.join(DATAPATH, 'list_of_txt_spectra.txt') FILELIST2 = os.path.join(DATAPATH, 'list_of_fits_spectra.txt') @pytest.fixture def wave_spec_generate(): ''' Read in three small chunks...
''' Test that new spectra are shorter than the original because the outliers are gone ''' wavelist, speclist = wave_spec_generate[2], wave_spec_generate[3] newwavelist, newspeclist = despike.despike_spectra(wavelist, speclist, type='simple', plot=False) assert len(newwavelist) == len(wavelist) a...
identifier_body
test_despike.py
import numpy as np from apvisitproc import despike import pytest import os DATAPATH = os.path.dirname(__file__) FILELIST1 = os.path.join(DATAPATH, 'list_of_txt_spectra.txt') FILELIST2 = os.path.join(DATAPATH, 'list_of_fits_spectra.txt') @pytest.fixture def wave_spec_generate(): ''' Read in three small chunks...
(wave_spec_generate): ''' Test that new spectra are shorter than the original because the outliers are gone ''' wavelist, speclist = wave_spec_generate[2], wave_spec_generate[3] newwavelist, newspeclist = despike.despike_spectra(wavelist, speclist, type='simple', plot=False) assert len(newwaveli...
test_despike_spectra
identifier_name
cp861.py
""" Python Character Mapping Codec generated from 'CP861.TXT' with gencodec.py.
(c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,errors='strict'): return codecs.charmap_encode(input,errors,encoding_map) def decode(self,input,errors='strict'):...
Written by Marc-Andre Lemburg (mal@lemburg.com).
random_line_split
cp861.py
""" Python Character Mapping Codec generated from 'CP861.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,error...
(): return (Codec().encode,Codec().decode,StreamReader,StreamWriter) ### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA 0x0081: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS 0x0082: 0x00e9, # LATIN SMALL LETTER E WI...
getregentry
identifier_name
cp861.py
""" Python Character Mapping Codec generated from 'CP861.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,error...
encoding_map[v] = k
conditional_block
cp861.py
""" Python Character Mapping Codec generated from 'CP861.TXT' with gencodec.py. Written by Marc-Andre Lemburg (mal@lemburg.com). (c) Copyright CNRI, All Rights Reserved. NO WARRANTY. (c) Copyright 2000 Guido van Rossum. """#" import codecs ### Codec APIs class Codec(codecs.Codec): def encode(self,input,error...
### Decoding Map decoding_map = codecs.make_identity_dict(range(256)) decoding_map.update({ 0x0080: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA 0x0081: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS 0x0082: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE 0x0083: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX 0x0084:...
return (Codec().encode,Codec().decode,StreamReader,StreamWriter)
identifier_body
sleeptimer.py
#!/usr/bin/env python ################################################## ## DEPENDENCIES import sys import os import os.path try: import builtins as builtin except ImportError: import __builtin__ as builtin from os.path import getmtime, exists import time import types from Cheetah.Version import MinCompatib...
import Cheetah.Filters as Filters import Cheetah.ErrorCatchers as ErrorCatchers ################################################## ## MODULE CONSTANTS VFFSL=valueFromFrameOrSearchList VFSL=valueFromSearchList VFN=valueForName currentTime=time.time __CHEETAH_version__ = '2.4.4' __CHEETAH_versionTuple__ = (2, 4, 4, 'dev...
random_line_split
sleeptimer.py
#!/usr/bin/env python ################################################## ## DEPENDENCIES import sys import os import os.path try: import builtins as builtin except ImportError: import __builtin__ as builtin from os.path import getmtime, exists import time import types from Cheetah.Version import MinCompatib...
################################################## ## CHEETAH GENERATED ATTRIBUTES _CHEETAH__instanceInitialized = False _CHEETAH_version = __CHEETAH_version__ _CHEETAH_versionTuple = __CHEETAH_versionTuple__ _CHEETAH_genTime = __CHEETAH_genTime__ _CHEETAH_genTimestamp = __CH...
if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)): trans = self.transaction # is None unless self.awake() was called if not trans: trans = DummyTransaction() _dummyTrans = True else: _dummyTrans = False write = trans.response...
identifier_body
sleeptimer.py
#!/usr/bin/env python ################################################## ## DEPENDENCIES import sys import os import os.path try: import builtins as builtin except ImportError: import __builtin__ as builtin from os.path import getmtime, exists import time import types from Cheetah.Version import MinCompatib...
write = trans.response().write SL = self._CHEETAH__searchList _filter = self._CHEETAH__currentFilter ######################################## ## START - generated method body _orig_filter_51193055 = _filter filterName = u'WebSafe' if sel...
_dummyTrans = False
conditional_block
sleeptimer.py
#!/usr/bin/env python ################################################## ## DEPENDENCIES import sys import os import os.path try: import builtins as builtin except ImportError: import __builtin__ as builtin from os.path import getmtime, exists import time import types from Cheetah.Version import MinCompatib...
(Template): ################################################## ## CHEETAH GENERATED METHODS def __init__(self, *args, **KWs): super(sleeptimer, self).__init__(*args, **KWs) if not self._CHEETAH__instanceInitialized: cheetahKWArgs = {} allowedKWs = 'searchList name...
sleeptimer
identifier_name
Affix.test.tsx
import React from 'react'; import { mount, ReactWrapper, HTMLAttributes } from 'enzyme'; import ResizeObserverImpl from 'rc-resize-observer'; import Affix, { AffixProps, AffixState } from '..'; import { getObserverEntities } from '../utils'; import Button from '../../button'; import rtlTest from '../../../tests/shared/...
await movePlaceholder(-100); expect(onChange).toHaveBeenLastCalledWith(true); expect(affixMounterWrapper.instance().affix.state.affixStyle?.top).toBe(0); affixMounterWrapper.setProps({ offsetTop: 10, }); await sleep(20); expect(affixMounterWrapper.instance().affix.state.affixStyle?.top...
random_line_split
Affix.test.tsx
import React from 'react'; import { mount, ReactWrapper, HTMLAttributes } from 'enzyme'; import ResizeObserverImpl from 'rc-resize-observer'; import Affix, { AffixProps, AffixState } from '..'; import { getObserverEntities } from '../utils'; import Button from '../../button'; import rtlTest from '../../../tests/shared/...
events.scroll({ type: 'scroll', }); await sleep(20); }; it('Anchor render perfectly', async () => { document.body.innerHTML = '<div id="mounter" />'; affixMounterWrapper = mount(<AffixMounter />, { attachTo: document.getElementById('mounter') }); await sleep(20); await movePlac...
{ throw new Error('scroll should be set'); }
conditional_block
Affix.test.tsx
import React from 'react'; import { mount, ReactWrapper, HTMLAttributes } from 'enzyme'; import ResizeObserverImpl from 'rc-resize-observer'; import Affix, { AffixProps, AffixState } from '..'; import { getObserverEntities } from '../utils'; import Button from '../../button'; import rtlTest from '../../../tests/shared/...
() { this.container.addEventListener = jest .fn() .mockImplementation((event: keyof HTMLElementEventMap, cb: (ev: Partial<Event>) => void) => { events[event] = cb; }); } getTarget = () => this.container; render() { return ( <div ref={node => { this.conta...
componentDidMount
identifier_name
Affix.test.tsx
import React from 'react'; import { mount, ReactWrapper, HTMLAttributes } from 'enzyme'; import ResizeObserverImpl from 'rc-resize-observer'; import Affix, { AffixProps, AffixState } from '..'; import { getObserverEntities } from '../utils'; import Button from '../../button'; import rtlTest from '../../../tests/shared/...
} className="container" > <Affix className="fixed" target={this.getTarget} ref={ele => { this.affix = ele!; }} {...this.props} > <Button type="primary">Fixed at the top of container</Button> </Affix> </di...
{ return ( <div ref={node => { this.container = node!; }
identifier_body
test_timeout2.js
var http = require("http"); var querystring = require("querystring"); // 核心模块 var SBuffer=require("../tools/SBuffer"); var common=require("../tools/common"); var zlib=require("zlib"); var redis_pool=require("../tools/connection_pool"); var events = require('events'); var util = require('util'); function ProxyAgent(...
获取服务配置信息 * @param 服务名 * @return object */ ProxyAgent.prototype.getReqConfig = function(logName){ var _self=this; var Obj={}; Obj=Config[logName]; Obj.logger=Analysis.getLogger(logName); Obj.name=logName; return Obj; } ProxyAgent.prototype.doRequest=function(_req,_res){ var _self=this; _self.reqConf=_self...
headNeeds = preHeaders||""; this.preAnalysisFields = preAnalysisFields||""; this.AnalysisFields = {}; this.logName=logName||""; this.response=null; this.reqConf={}; this.retData=[]; this.redis =null; // redis {} redis_key events.EventEmitter.call(this); } /** *
identifier_body
test_timeout2.js
var http = require("http"); var querystring = require("querystring"); // 核心模块 var SBuffer=require("../tools/SBuffer"); var common=require("../tools/common"); var zlib=require("zlib"); var redis_pool=require("../tools/connection_pool"); var events = require('events'); var util = require('util'); function ProxyAge
ers,preAnalysisFields,logName){ this.headNeeds = preHeaders||""; this.preAnalysisFields = preAnalysisFields||""; this.AnalysisFields = {}; this.logName=logName||""; this.response=null; this.reqConf={}; this.retData=[]; this.redis =null; // redis {} redis_key events.EventEmitter.call(this); } /** * 获取服务配置信息 ...
nt(preHead
identifier_name
test_timeout2.js
var http = require("http"); var querystring = require("querystring"); // 核心模块 var SBuffer=require("../tools/SBuffer"); var common=require("../tools/common"); var zlib=require("zlib"); var redis_pool=require("../tools/connection_pool"); var events = require('events'); var util = require('util'); function ProxyAgent(...
conditional_block
test_timeout2.js
var http = require("http"); var querystring = require("querystring"); // 核心模块 var SBuffer=require("../tools/SBuffer"); var common=require("../tools/common"); var zlib=require("zlib"); var redis_pool=require("../tools/connection_pool"); var events = require('events'); var util = require('util'); function ProxyAgent(...
* @param resultBuffer */ ProxyAgent.prototype.setRedis = function (redis_key, redis_time, resultBuffer) { redis_pool.acquire(function(err, client) { if (!err) { client.setex(redis_key, redis_time, resultBuffer, function(err, repliy) { redis_pool.release(client); // 链接使用完毕释放链接 }); logger.debug(red...
random_line_split
char.js
import { Primitive } from './primitive.js'; /** * A single Unicode character. * Value type semantics, immutable and final. * * The parameter type signatures in this class and file are enforced * by RacketScript when called from RacketScript. * * No checks are performed here, allowing us to use it internally * ...
() { if (this._nativeString === null) { this._nativeString = String.fromCodePoint(this.codepoint); } return this._nativeString; } /** * @return {!number} a non-negative integer. * @override */ hashForEqual() { return this.codepoint; } /** ...
toString
identifier_name
char.js
import { Primitive } from './primitive.js'; /** * A single Unicode character. * Value type semantics, immutable and final. * * The parameter type signatures in this class and file are enforced * by RacketScript when called from RacketScript. * * No checks are performed here, allowing us to use it internally * ...
} } /** * @param {!Ports.NativeStringOutputPort} out */ printNativeString(out) { this.writeNativeString(out); } // displayUstring is defined in unicode_string.js to avoid a circular dependency. /** * @param {!Ports.UStringOutputPort} out */ printUStrin...
{ out.consume(c > 0xFFFF ? `#\\U${c.toString(16).toUpperCase().padStart(8, '0')}` : `#\\u${c.toString(16).toUpperCase().padStart(4, '0')}`); }
conditional_block
char.js
import { Primitive } from './primitive.js'; /** * A single Unicode character. * Value type semantics, immutable and final. * * The parameter type signatures in this class and file are enforced * by RacketScript when called from RacketScript. * * No checks are performed here, allowing us to use it internally * ...
*/ export function isUpperCase(c) { return IS_UPPER_CASE.test(c.toString()); } /** * @param {!Char} c * @return {!boolean} */ export function isTitleCase(c) { return IS_TITLE_CASE.test(c.toString()); } /** * @param {!Char} c * @return {!boolean} */ export function isNumeric(c) { return IS_NUMERIC.test(c.t...
* @param {!Char} c * @return {!boolean}
random_line_split
char.js
import { Primitive } from './primitive.js'; /** * A single Unicode character. * Value type semantics, immutable and final. * * The parameter type signatures in this class and file are enforced * by RacketScript when called from RacketScript. * * No checks are performed here, allowing us to use it internally * ...
/** * @param {!Char} c * @return {!Char} */ export function upcase(c) { const upper = c.toString().toUpperCase(); if (!isSingleCodePoint(upper)) return c; return charFromNativeString(upper); } /** * @param {!Char} c * @return {!Char} */ export function downcase(c) { const lower = c.toString().toLower...
{ return str.length === 1 || (str.length === 2 && str.codePointAt(0) > 0xFFFF); }
identifier_body
interrupt_pause_script.py
#!/usr/bin/python from __future__ import print_function
#GPIO pins Taster1 = 24 Taster2 = 27 # GPIO-Nummer als Pinreferenz waehlen GPIO.setmode(GPIO.BCM) # GPIO vom SoC als Input deklarieren und Pull-Down Widerstand aktivieren #PULL = GPIO.PUD_DOWN #GPIO -> GND PULL = GPIO.PUD_UP #GPIO -> 3V3 GPIO.setup(Taster1, GPIO.IN, pull_up_down=PULL) GPIO.setup(Taster2, ...
import RPi.GPIO as GPIO import time import Queue # https://pymotw.com/2/Queue/
random_line_split
interrupt_pause_script.py
#!/usr/bin/python from __future__ import print_function import RPi.GPIO as GPIO import time import Queue # https://pymotw.com/2/Queue/ #GPIO pins Taster1 = 24 Taster2 = 27 # GPIO-Nummer als Pinreferenz waehlen GPIO.setmode(GPIO.BCM) # GPIO vom SoC als Input deklarieren und Pull-Down Widerstand aktivieren #PULL = G...
# ISR def interrupt_event(pin): if pin == Taster1: queue.put(pin) if pin == Taster2: print("Führe Script weiter aus") dictionary['pause'] = False try: # Interrupt Event hinzufuegen. Auf steigende Flanke reagieren und ISR "Interrupt" deklarieren sowie Pin entprellen GPI...
while dictionary['pause'] == True: time.sleep(1)
identifier_body
interrupt_pause_script.py
#!/usr/bin/python from __future__ import print_function import RPi.GPIO as GPIO import time import Queue # https://pymotw.com/2/Queue/ #GPIO pins Taster1 = 24 Taster2 = 27 # GPIO-Nummer als Pinreferenz waehlen GPIO.setmode(GPIO.BCM) # GPIO vom SoC als Input deklarieren und Pull-Down Widerstand aktivieren #PULL = G...
# ISR def interrupt_event(pin): if pin == Taster1: queue.put(pin) if pin == Taster2: print("Führe Script weiter aus") dictionary['pause'] = False try: # Interrupt Event hinzufuegen. Auf steigende Flanke reagieren und ISR "Interrupt" deklarieren sowie Pin entprellen GPI...
time.sleep(1)
conditional_block
interrupt_pause_script.py
#!/usr/bin/python from __future__ import print_function import RPi.GPIO as GPIO import time import Queue # https://pymotw.com/2/Queue/ #GPIO pins Taster1 = 24 Taster2 = 27 # GPIO-Nummer als Pinreferenz waehlen GPIO.setmode(GPIO.BCM) # GPIO vom SoC als Input deklarieren und Pull-Down Widerstand aktivieren #PULL = G...
(pin): if pin == Taster1: queue.put(pin) if pin == Taster2: print("Führe Script weiter aus") dictionary['pause'] = False try: # Interrupt Event hinzufuegen. Auf steigende Flanke reagieren und ISR "Interrupt" deklarieren sowie Pin entprellen GPIO.add_event_detect(Taster1,...
interrupt_event
identifier_name
index.d.ts
/* * @license Apache-2.0 * * Copyright (c) 2019 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 * * Unless required by ap...
// EXPORTS // export = keysIn;
random_line_split
search-notifications.js
/*jslint browser */ /*globals window, settings, searchTerm, locales, pageLanguage, getQueryVariable */ // display a 'Searching' progress placeholder function ebSearchShowSearchingNotice() { 'use strict'; var searchProgressPlaceholder = document.querySelector('.search-progress-placeholder'); if (searchProg...
} // Load the search index and the script for showing results. // We load these here so that they don't block the main thread. // This does not seem to work in file:///'s, only on a webserver. function ebSearchLoadIndexAndResults() { 'use strict'; [ 'assets/js/search-index-' + settings.site.output + ...
{ searchProgressPlaceholder.classList.add('visuallyhidden'); }
conditional_block
search-notifications.js
/*jslint browser */ /*globals window, settings, searchTerm, locales, pageLanguage, getQueryVariable */ // display a 'Searching' progress placeholder function ebSearchShowSearchingNotice() { 'use strict'; var searchProgressPlaceholder = document.querySelector('.search-progress-placeholder'); if (searchProg...
() { 'use strict'; var query = getQueryVariable('query'); if (query && query !== '') { ebSearchResultsProcess(); } } ebSearchCheckForSearchString();
ebSearchCheckForSearchString
identifier_name
search-notifications.js
/*jslint browser */ /*globals window, settings, searchTerm, locales, pageLanguage, getQueryVariable */ // display a 'Searching' progress placeholder function ebSearchShowSearchingNotice() { 'use strict'; var searchProgressPlaceholder = document.querySelector('.search-progress-placeholder'); if (searchProg...
// Hide the search-progress placeholder function ebSearchHideSearchingNotice() { 'use strict'; var searchProgressPlaceholder = document.querySelector('.search-progress-placeholder'); if (searchProgressPlaceholder) { searchProgressPlaceholder.classList.add('visuallyhidden'); } } // Load the sea...
searchProgressPlaceholder.innerHTML = '<p>' + locales[pageLanguage].search['placeholder-searching'] + '</p>'; var searchForm = document.querySelector("form.search"); searchForm.insertAdjacentElement('afterend', searchProgressPlaceholder); } }
random_line_split
search-notifications.js
/*jslint browser */ /*globals window, settings, searchTerm, locales, pageLanguage, getQueryVariable */ // display a 'Searching' progress placeholder function ebSearchShowSearchingNotice()
// Hide the search-progress placeholder function ebSearchHideSearchingNotice() { 'use strict'; var searchProgressPlaceholder = document.querySelector('.search-progress-placeholder'); if (searchProgressPlaceholder) { searchProgressPlaceholder.classList.add('visuallyhidden'); } } // Load the se...
{ 'use strict'; var searchProgressPlaceholder = document.querySelector('.search-progress-placeholder'); if (searchProgressPlaceholder) { searchProgressPlaceholder.classList.remove('visuallyhidden'); } else { searchProgressPlaceholder = document.createElement('div'); searchProgre...
identifier_body
magnific.js
// Inline popups $('#inline-popups').magnificPopup({ delegate: 'a', removalDelay: 500, //delay removal by X to allow out-animation callbacks: { beforeOpen: function() { this.st.mainClass = this.st.el.attr('data-effect'); } }, midClick: true // allow opening popup on middle mouse click....
// Image popups $('.lightbox').magnificPopup({ // delegate: 'a', type: 'image', mainClass: 'mfp-3d-unfold', removalDelay: 500, //delay removal by X to allow out-animation callbacks: { beforeOpen: function() { // just a hack that adds mfp-anim class to markup this.st.image.markup = t...
random_line_split
webpack.config.js
/* to package "eslint": "^1.7.3", "eslint-config-rackt": "^1.1.0", "eslint-plugin-react": "^3.6.3", */ require('es6-promise').polyfill(); // old node 0.10 var path = require('path'); var webpack = require('webpack'); module.exports = { externals: { jquery: "jQuery", autobahn: "autobahn" }, ...
"$": "jquery", "_": "underscore", }) */ ], resolve: { alias: { "lodash": path.resolve("./node_modules/lodash"), "react": path.resolve("./node_modules/react/react.js"), "react-dom": path.resolve("./node_modules/react/lib/ReactDOM.js"), "react-router": path....
random_line_split
Button.js
/** * @file san-mui/Button * @author leon <ludafa@outlook.com> */ import {create} from '../common/util/cx'; import {TouchRipple} from '../Ripple'; import BaseButton from './Base'; import {DataTypes} from 'san'; const cx = create('button'); export default class Button extends BaseButton { static components = ...
() { return cx(this).build(); } }; static dataTypes = { type: DataTypes.string, disabled: DataTypes.bool }; initData() { return { type: 'button', disabled: false }; }; attached() { // save the original href in...
computedClassName
identifier_name
Button.js
/** * @file san-mui/Button * @author leon <ludafa@outlook.com> */ import {create} from '../common/util/cx'; import {TouchRipple} from '../Ripple'; import BaseButton from './Base'; import {DataTypes} from 'san'; const cx = create('button'); export default class Button extends BaseButton { static components = ...
}
{ if (!this.data.get('disabled')) { this.fire('click', e); } }
identifier_body