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
main.py
from tkinter import * from PIL import Image, ImageTk from mandelbrot import * from julia_set import * class App(object): def __init__(self, master): # CANVAS self.ulx, self.uly, self.drx, self.dry, self.def_width = default_settings()[ :5] self.image = ImageTk.PhotoImage(make_f...
(self, event): self.sx, self.sy = event.x, event.y def release(self, event): self.ex, self.ey = event.x, event.y if self.ex == self.sx or self.ey == self.sy: return self.sx, self.ex = sorted([self.ex, self.sx]) self.sy, self.ey = sorted([self.ey, self.sy]) ...
press
identifier_name
main.py
from tkinter import * from PIL import Image, ImageTk from mandelbrot import * from julia_set import * class App(object): def __init__(self, master): # CANVAS self.ulx, self.uly, self.drx, self.dry, self.def_width = default_settings()[ :5] self.image = ImageTk.PhotoImage(make_f...
ex, ey = event.x, event.y try: self.canvas.delete(self.rect) except: pass finally: self.rect = self.canvas.create_rectangle((self.sx, self.sy, ex, ey), fill='', outline='white') def update_imag...
return
conditional_block
main.py
from tkinter import * from PIL import Image, ImageTk from mandelbrot import * from julia_set import * class App(object): def __init__(self, master): # CANVAS self.ulx, self.uly, self.drx, self.dry, self.def_width = default_settings()[ :5] self.image = ImageTk.PhotoImage(make_f...
root = Tk() root.wm_title("Fractal Explorer") app = App(root) root.mainloop()
img = make_fractal(self.ulx, self.uly, self.drx, self.dry, self.def_width, self.iterval.get()) self.image = ImageTk.PhotoImage(img) self.canvas.config(width=self.image.width(), height=self.image.height()) self.canvas.create_image(0, 0, image=...
identifier_body
util.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 layout::box::Box; use layout::construct::{ConstructionResult, NoConstructionResult}; use layout::wrapper::Layo...
{ priv entries: ~[NodeRange], } impl ElementMapping { pub fn new() -> ElementMapping { ElementMapping { entries: ~[], } } pub fn add_mapping(&mut self, node: OpaqueNode, range: &Range) { self.entries.push(NodeRange::new(node, range)) } pub fn each(&self, c...
ElementMapping
identifier_name
util.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 layout::box::Box; use layout::construct::{ConstructionResult, NoConstructionResult}; use layout::wrapper::Layo...
} true } pub fn eachi<'a>(&'a self) -> Enumerate<VecIterator<'a, NodeRange>> { self.entries.iter().enumerate() } pub fn repair_for_box_changes(&mut self, old_boxes: &[Box], new_boxes: &[Box]) { let entries = &mut self.entries; debug!("--- Old boxes: ---"); ...
{ break }
conditional_block
util.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 layout::box::Box; use layout::construct::{ConstructionResult, NoConstructionResult}; use layout::wrapper::Layo...
old_i += 1; // possibly pop several items while repair_stack.len() > 0 && old_i == entries[repair_stack.last().entry_idx].range.end() { let item = repair_stack.pop(); debug!("repair_for_box_changes: Set range for {:u} to {}", ...
while new_j < new_boxes.len() && old_boxes[old_i].node != new_boxes[new_j].node { debug!("repair_for_box_changes: Slide through new box {:u}", new_j); new_j += 1; }
random_line_split
util.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 layout::box::Box; use layout::construct::{ConstructionResult, NoConstructionResult}; use layout::wrapper::Layo...
/// Converts a DOM node (script view) to an `OpaqueNode`. pub fn from_script_node(node: &AbstractNode) -> OpaqueNode { unsafe { OpaqueNode(cast::transmute_copy(node)) } } /// Unsafely converts an `OpaqueNode` to a DOM node (script view). Use this only if you /// absolu...
{ unsafe { OpaqueNode(cast::transmute_copy(node)) } }
identifier_body
statstring.py
#The Diablo II statstring parsing within this module makes use of findings by #iago, DarkMinion, and RealityRipple, among others from pbuffer import debug_output long_name = {'SSHR': 'Starcraft Shareware', 'JSTR': 'Starcraft Japanese', 'STAR': 'Starcraft', 'SEXP': 'Starcraft Bro...
def str_reverse(string): rev = reversed(string) build = '' for char in rev: build += char return build def statstring(text): product = str_reverse(text[:4]) results = {'product': product, 'statstring': text} try: results['display'] = long_name[p...
if (flags & 0x01) == 0x01: build = 'public' else: build = 'private' for k, v in chan_flags.iteritems(): if (flags & k) == k: build += ', ' + v return build
identifier_body
statstring.py
#iago, DarkMinion, and RealityRipple, among others from pbuffer import debug_output long_name = {'SSHR': 'Starcraft Shareware', 'JSTR': 'Starcraft Japanese', 'STAR': 'Starcraft', 'SEXP': 'Starcraft Broodwar', 'DSHR': 'Diablo Shareware', 'DRTL': 'Diablo ...
#The Diablo II statstring parsing within this module makes use of findings by
random_line_split
statstring.py
#The Diablo II statstring parsing within this module makes use of findings by #iago, DarkMinion, and RealityRipple, among others from pbuffer import debug_output long_name = {'SSHR': 'Starcraft Shareware', 'JSTR': 'Starcraft Japanese', 'STAR': 'Starcraft', 'SEXP': 'Starcraft Bro...
(string): rev = reversed(string) build = '' for char in rev: build += char return build def statstring(text): product = str_reverse(text[:4]) results = {'product': product, 'statstring': text} try: results['display'] = long_name[product] except Key...
str_reverse
identifier_name
statstring.py
#The Diablo II statstring parsing within this module makes use of findings by #iago, DarkMinion, and RealityRipple, among others from pbuffer import debug_output long_name = {'SSHR': 'Starcraft Shareware', 'JSTR': 'Starcraft Japanese', 'STAR': 'Starcraft', 'SEXP': 'Starcraft Bro...
return res def stats_diablo2(product, text): if text == '': return {'open': True} field = text.split(',', 2) if len(field) < 3: return {'open': True} realm = field[0] char_name = field[1] text = field[2][2:] if len(text) < 29: return {'open': True...
res['clan'] = clan
conditional_block
factor_int.rs
// Implements http://rosettacode.org/wiki/Factors_of_an_integer #[cfg(not(test))] fn main()
// Compute the factors of an integer // This method uses a simple check on each value between 1 and sqrt(x) to find // pairs of factors fn factor_int(x: i32) -> Vec<i32> { let mut factors: Vec<i32> = Vec::new(); let bound: i32 = (x as f64).sqrt().floor() as i32; for i in (1i32..bound) { if x % i...
{ let target = 78i32; println!("Factors of integer {}:", target); let factors = factor_int(target); for f in factors { println!("{}", f); } }
identifier_body
factor_int.rs
// Implements http://rosettacode.org/wiki/Factors_of_an_integer #[cfg(not(test))] fn main() { let target = 78i32; println!("Factors of integer {}:", target); let factors = factor_int(target); for f in factors { println!("{}", f); } } // Compute the factors of an integer // This method use...
} factors } #[test] fn test() { let result = factor_int(78i32); assert_eq!(result, vec![1i32, 78, 2, 39, 3, 26, 6, 13]); }
{ factors.push(i); factors.push(x/i); }
conditional_block
factor_int.rs
// Implements http://rosettacode.org/wiki/Factors_of_an_integer #[cfg(not(test))] fn main() { let target = 78i32; println!("Factors of integer {}:", target); let factors = factor_int(target); for f in factors { println!("{}", f); } } // Compute the factors of an integer // This method use...
() { let result = factor_int(78i32); assert_eq!(result, vec![1i32, 78, 2, 39, 3, 26, 6, 13]); }
test
identifier_name
factor_int.rs
// Implements http://rosettacode.org/wiki/Factors_of_an_integer #[cfg(not(test))] fn main() { let target = 78i32; println!("Factors of integer {}:", target); let factors = factor_int(target); for f in factors { println!("{}", f); } } // Compute the factors of an integer // This method use...
factors.push(i); factors.push(x/i); } } factors } #[test] fn test() { let result = factor_int(78i32); assert_eq!(result, vec![1i32, 78, 2, 39, 3, 26, 6, 13]); }
for i in (1i32..bound) { if x % i == 0 {
random_line_split
QuickViewUtils-dbg.js
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides sap.ui.define(['jquery.sap.global', 'sap/ui/core/Control', 'sap/ui/core/Element'], function(jQuery, Control, Element) {...
} oMLRow.addCell(oMLCell); oML.addRow(oMLRow); } this._oML = oML; return oML; }, _sortItems: function(oControl) { if (!oControl._sorted) { var aItems = oControl.removeAllAggregation("items", true); aItems.sort(function(a, b) { return (parseInt(a.getOrder(), 10) - parseInt(b....
oLink = new sap.ui.commons.Link({text:aItems[i].getValue(), href:aItems[i].getLink()}); oMLCell.addContent(oLink); } else { oTxtView = new sap.ui.commons.TextView({text:aItems[i].getValue()}); oMLCell.addContent(oTxtView);
random_line_split
QuickViewUtils-dbg.js
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides sap.ui.define(['jquery.sap.global', 'sap/ui/core/Control', 'sap/ui/core/Element'], function(jQuery, Control, Element) {...
} }); return QuickViewUtils; }, /* bExport= */ true);
{ var aItems = oControl.removeAllAggregation("items", true); aItems.sort(function(a, b) { return (parseInt(a.getOrder(), 10) - parseInt(b.getOrder(), 10)); }); jQuery.each(aItems, function(i,oItem) {oControl.addAggregation("items",oItem,false);}); oControl._sorted = true; }
conditional_block
querystring.d.ts
/** * The `querystring` module provides utilities for parsing and formatting URL * query strings. It can be accessed using: * * ```js * const querystring = require('querystring'); * ``` * * The `querystring` API is considered Legacy. While it is still maintained, * new code should use the `<URLSearchParams>` A...
interface ParsedUrlQuery extends NodeJS.Dict<string | string[]> {} interface ParsedUrlQueryInput extends NodeJS.Dict<string | number | boolean | ReadonlyArray<string> | ReadonlyArray<number> | ReadonlyArray<boolean> | null> {} /** * The `querystring.stringify()` method produces a URL query string from ...
interface ParseOptions { maxKeys?: number | undefined; decodeURIComponent?: ((str: string) => string) | undefined; }
random_line_split
GroupTest.ts
import { Assert, UnitTest } from '@ephox/bedrock-client'; import { Gene, TestUniverse, TextGene } from '@ephox/boss'; import { Arr } from '@ephox/katamari'; import * as Group from 'ephox/phoenix/family/Group'; import * as Finder from 'ephox/phoenix/test/Finder'; import * as TestRenders from 'ephox/phoenix/test/TestRen...
Gene('1.2.4', 'em', [ TextGene('1.2.4.1', 'Inside em') ]), TextGene('1.2.5', 'Last piece of text') ]) ]) ]) ); const check = (expected: string[][], ids: string[]) => { const items = Arr.map(ids, (id) => { return Finder.get(doc, id); }); ...
Gene('1.2.2', 'span', [ TextGene('1.2.2.1', 'inside a span') ]), TextGene('1.2.3', 'More text'),
random_line_split
authentification.component.ts
import { Component } from '@angular/core'; import { Http, RequestOptions, Headers } from '@angular/http'; import 'rxjs/add/operator/toPromise'; import { Router } from '@angular/router'; const API_BASE_URL = "https://imie-api-mock.cleverapps.io"; @Component({ selector: 'app-root', templateUrl: './authentification....
{ constructor(private http: Http, private router: Router){} title = 'Authentification'; email = null; password = null; errorMessage = ""; onSubmit() { this.login(); } login() { const headers = new Headers({ 'Content-Type': 'application/json' }); const requestOptions = new RequestOptions(...
AuthentificationComponent
identifier_name
authentification.component.ts
import { Component } from '@angular/core'; import { Http, RequestOptions, Headers } from '@angular/http'; import 'rxjs/add/operator/toPromise'; import { Router } from '@angular/router'; const API_BASE_URL = "https://imie-api-mock.cleverapps.io"; @Component({
export class AuthentificationComponent { constructor(private http: Http, private router: Router){} title = 'Authentification'; email = null; password = null; errorMessage = ""; onSubmit() { this.login(); } login() { const headers = new Headers({ 'Content-Type': 'application/json' }); cons...
selector: 'app-root', templateUrl: './authentification.component.html', styleUrls: ['./app.component.css'] })
random_line_split
authentification.component.ts
import { Component } from '@angular/core'; import { Http, RequestOptions, Headers } from '@angular/http'; import 'rxjs/add/operator/toPromise'; import { Router } from '@angular/router'; const API_BASE_URL = "https://imie-api-mock.cleverapps.io"; @Component({ selector: 'app-root', templateUrl: './authentification....
login() { const headers = new Headers({ 'Content-Type': 'application/json' }); const requestOptions = new RequestOptions({ headers: headers }); this .http .post(`${API_BASE_URL}/connect`, { email: this.email, password: this.password }, requestOptions) .toPromise() .then(res => r...
{ this.login(); }
identifier_body
moment_curve.py
#!/usr/bin/python2.3 # This is the short name of the plugin, used as the menu item # for the plugin. # If not specified, the name of the file will be used. shortname = "Moment Curve layout (Cohen et al. 1995)" # This is the long name of the plugin, used as the menu note # for the plugin. # If not specified, the short ...
def moment(C, compact=False): """ Run moment curve layout (Cohen, Eades, Lin, Ruskey 1995). """ G = C.graph from math import sqrt, ceil, floor from graph import DummyVertex, GraphError import colorsys vertices = [x for x in G.vertices if not isinstance(x, DummyVertex)] n = len(v...
""" k_n (C, n) -> void Create a complete graph on n vertices in context C. """ from graph import Vertex, DummyVertex G = C.graph G.clear() # Add n vertices for i in range(n): G.addVertex(Vertex(id='%d' % i, name='v%d' % i)) # For every pair of vertices (u, v): for u in ...
identifier_body
moment_curve.py
#!/usr/bin/python2.3 # This is the short name of the plugin, used as the menu item # for the plugin. # If not specified, the name of the file will be used. shortname = "Moment Curve layout (Cohen et al. 1995)" # This is the long name of the plugin, used as the menu note # for the plugin. # If not specified, the short ...
(context, UI): """ Run this plugin. """ if len(context.graph.vertices) < 1: generate = True else: res = UI.prYesNo("Use current graph?", "Would you like to apply the layout to the current graph? If not, a complete graph will be generated and the current grap...
run
identifier_name
moment_curve.py
#!/usr/bin/python2.3 # This is the short name of the plugin, used as the menu item # for the plugin. # If not specified, the name of the file will be used. shortname = "Moment Curve layout (Cohen et al. 1995)" # This is the long name of the plugin, used as the menu note # for the plugin. # If not specified, the short ...
else: generate = True if generate: N = UI.prType("Number of Vertices", "Input number of vertices to generate complete graph:", int, 4) if N == None: return True while N < 0: N = UI.prType("Number of Vertices", "Please inp...
random_line_split
moment_curve.py
#!/usr/bin/python2.3 # This is the short name of the plugin, used as the menu item # for the plugin. # If not specified, the name of the file will be used. shortname = "Moment Curve layout (Cohen et al. 1995)" # This is the long name of the plugin, used as the menu note # for the plugin. # If not specified, the short ...
else: res = UI.prYesNo("Use current graph?", "Would you like to apply the layout to the current graph? If not, a complete graph will be generated and the current graph cleared.") if res: generate = False # Go through and eliminate any existing bend p...
generate = True
conditional_block
net.py
#!/usr/bin/env Python import time import sys if len(sys.argv) > 1: INTERFACE = sys.argv[1] else: INTERFACE = 'eth1' STATS = [] print 'Interface:',INTERFACE def rx():
def tx(): ifstat = open('/proc/net/dev').readlines() for interface in ifstat: if INTERFACE in interface: stat = float(interface.split()[9]) STATS[1:] = [stat] print 'In Out' rx() tx() while True: time.sleep(1) rxstat_o = list(STATS) rx() tx() ...
ifstat = open('/proc/net/dev').readlines() for interface in ifstat: #print '----', interface, '-----' if INTERFACE in interface: stat = float(interface.split()[1]) STATS[0:] = [stat]
identifier_body
net.py
#!/usr/bin/env Python import time import sys if len(sys.argv) > 1: INTERFACE = sys.argv[1] else: INTERFACE = 'eth1'
ifstat = open('/proc/net/dev').readlines() for interface in ifstat: #print '----', interface, '-----' if INTERFACE in interface: stat = float(interface.split()[1]) STATS[0:] = [stat] def tx(): ifstat = open('/proc/net/dev').readlines() for interface in ifstat: ...
STATS = [] print 'Interface:',INTERFACE def rx():
random_line_split
net.py
#!/usr/bin/env Python import time import sys if len(sys.argv) > 1: INTERFACE = sys.argv[1] else: INTERFACE = 'eth1' STATS = [] print 'Interface:',INTERFACE def rx(): ifstat = open('/proc/net/dev').readlines() for interface in ifstat: #print '----', interface, '-----' if INTERFACE in ...
print 'In Out' rx() tx() while True: time.sleep(1) rxstat_o = list(STATS) rx() tx() RX = float(STATS[0]) RX_O = rxstat_o[0] TX = float(STATS[1]) TX_O = rxstat_o[1] RX_RATE = round((RX - RX_O)/1024/1024,3) TX_RATE = round((TX - TX_O)/1024/1024,3) print RX_RATE ,...
if INTERFACE in interface: stat = float(interface.split()[9]) STATS[1:] = [stat]
conditional_block
net.py
#!/usr/bin/env Python import time import sys if len(sys.argv) > 1: INTERFACE = sys.argv[1] else: INTERFACE = 'eth1' STATS = [] print 'Interface:',INTERFACE def
(): ifstat = open('/proc/net/dev').readlines() for interface in ifstat: #print '----', interface, '-----' if INTERFACE in interface: stat = float(interface.split()[1]) STATS[0:] = [stat] def tx(): ifstat = open('/proc/net/dev').readlines() for interface in ifst...
rx
identifier_name
edit_distance_op_test.py
# Copyright 2015 Google Inc. 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 required by applicable law or a...
def testEditDistanceUnnormalized(self): hypothesis_indices = [[0, 0], [1, 0], [1, 1]] hypothesis_values = [10, 10, 11] hypothesis_shape = [2, 2] truth_indices = [[0, 0], [0, 1], [1, 0], [1, 1]] truth_values = [1, 2, ...
hypothesis_indices = [[0, 0], [0, 1], [1, 0], [1, 1]] hypothesis_values = [0, 1, 1, -1] hypothesis_shape = [2, 2] truth_indices = [[0, 0], [1, 0], [1, 1]] truth_values = [0, 1, 1] truth_shape = [2, 2] exp...
identifier_body
edit_distance_op_test.py
# Copyright 2015 Google Inc. 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 required by applicable law or a...
# limitations under the License. # ============================================================================== """Tests for tensorflow.kernels.edit_distance_op.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow.python.platform import ...
# distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and
random_line_split
edit_distance_op_test.py
# Copyright 2015 Google Inc. 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 required by applicable law or a...
tf.test.main()
conditional_block
edit_distance_op_test.py
# Copyright 2015 Google Inc. 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 required by applicable law or a...
(self): hypothesis_indices = [[0, 0], [1, 0], [1, 1]] hypothesis_values = [10, 10, 11] hypothesis_shape = [2, 2] truth_indices = [[0, 0], [0, 1], [1, 0], [1, 1]] truth_values = [1, 2, 1, -1] truth_shape =...
testEditDistanceUnnormalized
identifier_name
test_wheels_util.py
from __future__ import absolute_import, unicode_literals import pytest from virtualenv.seed.wheels.embed import MAX, get_embed_wheel from virtualenv.seed.wheels.util import Wheel def test_wheel_support_no_python_requires(mocker): wheel = get_embed_wheel("setuptools", for_py_version=None) zip_mock = mocker.M...
def test_wheel_repr(): wheel = get_embed_wheel("setuptools", MAX) assert str(wheel.path) in repr(wheel)
wheel = get_embed_wheel("setuptools", MAX) assert wheel.support_py("3.3") is False
identifier_body
test_wheels_util.py
from __future__ import absolute_import, unicode_literals import pytest from virtualenv.seed.wheels.embed import MAX, get_embed_wheel from virtualenv.seed.wheels.util import Wheel def test_wheel_support_no_python_requires(mocker): wheel = get_embed_wheel("setuptools", for_py_version=None) zip_mock = mocker.M...
(): wheel = get_embed_wheel("setuptools", MAX) assert str(wheel.path) in repr(wheel)
test_wheel_repr
identifier_name
test_wheels_util.py
from __future__ import absolute_import, unicode_literals import pytest from virtualenv.seed.wheels.embed import MAX, get_embed_wheel
wheel = get_embed_wheel("setuptools", for_py_version=None) zip_mock = mocker.MagicMock() mocker.patch("virtualenv.seed.wheels.util.ZipFile", new=zip_mock) zip_mock.return_value.__enter__.return_value.read = lambda name: b"" supports = wheel.support_py("3.8") assert supports is True def test_b...
from virtualenv.seed.wheels.util import Wheel def test_wheel_support_no_python_requires(mocker):
random_line_split
topic.rs
use std::fmt; use protocol::command::CMD_TOPIC; use protocol::message::{IrcMessage, RawMessage, ParseMessageError, ParseMessageErrorKind}; #[derive(Debug, Clone, Eq, PartialEq)] pub struct TopicCommand<'a> { channel: &'a str, topic: Option<&'a str>, } impl<'a> TopicCommand<'a> { pub fn new(channel: &'a s...
(&self) -> &'a str { self.channel } pub fn topic(&self) -> Option<&'a str> { self.topic } } impl<'a> fmt::Display for TopicCommand<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(write!(f, "{} {}", CMD_TOPIC, self.channel)); match self.topic { ...
channel
identifier_name
topic.rs
use std::fmt; use protocol::command::CMD_TOPIC; use protocol::message::{IrcMessage, RawMessage, ParseMessageError, ParseMessageErrorKind}; #[derive(Debug, Clone, Eq, PartialEq)]
impl<'a> TopicCommand<'a> { pub fn new(channel: &'a str, topic: Option<&'a str>) -> TopicCommand<'a> { TopicCommand { channel: channel, topic: topic, } } pub fn channel(&self) -> &'a str { self.channel } pub fn topic(&self) -> Option<&'a str> { ...
pub struct TopicCommand<'a> { channel: &'a str, topic: Option<&'a str>, }
random_line_split
scanner.py
#!/usr/bin/env python # encoding: utf-8 """A service to sync a local file tree to jottacloud. Copies and updates files in the cloud by comparing md5 hashes, like the official client. Run it from crontab at an appropriate interval. """ # This file is part of jottacloudclient. # # jottacloudclient is free software: you...
if len(bothplaces): for f in progress.bar(bothplaces, label="comparing %s existing files: " % len(bothplaces)): log.debug("checking whether file contents has changed: %s", f) if not dry_run: if saferun(jottacloud.replace_if_changed,...
ferun(jottacloud.delete, f.jottapath, jfs) is not False: _files += 1
conditional_block
scanner.py
#!/usr/bin/env python # encoding: utf-8 """A service to sync a local file tree to jottacloud. Copies and updates files in the cloud by comparing md5 hashes, like the official client. Run it from crontab at an appropriate interval. """ # This file is part of jottacloudclient. # # jottacloudclient is free software: you...
filescanner(topdir, jottapath, jfs, errorfile, exclude=None, dry_run=False, prune_files=True, prune_folders=True ): errors = {} def saferun(cmd, *args): log.debug('running %s with args %s', cmd, args) try: return apply(cmd, args) except Exception as e: puts(colo...
= abs(size) if (size==0): return "0B" units = ['B','KiB','MiB','GiB','TiB','PiB','EiB','ZiB','YiB'] p = math.floor(math.log(size, 2)/10) return "%.3f%s" % (size/math.pow(1024,p),units[int(p)]) def
identifier_body
scanner.py
#!/usr/bin/env python # encoding: utf-8 """A service to sync a local file tree to jottacloud. Copies and updates files in the cloud by comparing md5 hashes, like the official client. Run it from crontab at an appropriate interval. """ # This file is part of jottacloudclient. # # jottacloudclient is free software: you...
ir, jottapath, jfs, errorfile, exclude=None, dry_run=False, prune_files=True, prune_folders=True ): errors = {} def saferun(cmd, *args): log.debug('running %s with args %s', cmd, args) try: return apply(cmd, args) except Exception as e: puts(colored.red('Ouch. So...
canner(topd
identifier_name
scanner.py
#!/usr/bin/env python # encoding: utf-8 """A service to sync a local file tree to jottacloud. Copies and updates files in the cloud by comparing md5 hashes, like the official client. Run it from crontab at an appropriate interval. """ # This file is part of jottacloudclient. # # jottacloudclient is free software: you...
if prune_folders and len(onlyremotefolders): puts(colored.red("Deleting %s folders from JottaCloud because they no longer exist locally " % len(onlyremotefolders))) for f in onlyremotefolders: if not dry_run: if saferun(jottacloud.d...
log.debug("checking whether file contents has changed: %s", f) if not dry_run: if saferun(jottacloud.replace_if_changed, f.localpath, f.jottapath, jfs) is not False: _files += 1
random_line_split
regionmanip.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 ...
ty } fn fold_region(&mut self, r: ty::Region) -> ty::Region { self.relate(r); r } } impl<'a> RegionRelator<'a> { fn relate(&mut self, r_sub: ty::Region) { for &r in self.stack.iter() { if !r.is_bound() && !r_sub.i...
_ => { ty_fold::super_fold_ty(self, ty); } }
random_line_split
regionmanip.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 ...
} rr.fold_ty(ty); struct RegionRelator<'a> { tcx: &'a ty::ctxt, stack: Vec<ty::Region>, relate_op: |ty::Region, ty::Region|: 'a, } // FIXME(#10151) -- Define more precisely when a region is // considered "nested". Consider taking variance into account as // well. ...
{}
conditional_block
regionmanip.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 ...
(tcx: &ty::ctxt, opt_region: Option<ty::Region>, ty: ty::t, relate_op: |ty::Region, ty::Region|) { /*! * This rather specialized function walks each region `r` that appear * in `ty` and invokes `relate_op(r_encl, r)` fo...
relate_nested_regions
identifier_name
regionmanip.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 ...
{ /*! * This function populates the region map's `free_region_map`. * It walks over the transformed self type and argument types * for each function just before we check the body of that * function, looking for types where you have a borrowed * pointer to other borrowed data (e.g., `&'a &'b...
identifier_body
gh-cache-storage.spec.ts
import { CacheStorage, CacheEntry } from './gh-cache-storage'; import { InMemoryStorage } from './testing/in-memory-storage'; import { BrowserStorage } from './interface/storage'; describe('CacheStorage', () => { const url = 'https://api.github.com/repos/piotrl/github-profile-card/languages'; const cacheData: ...
// then expect(result).toEqual(cacheData); }); });
// when const result = cache.get(url);
random_line_split
post.service.ts
import { Injectable } from '@angular/core'; import { IPost } from './post-interface'; @Injectable() export class PostService { public posts : IPost[]; constructor() { this.posts = [ { id:1, content:"<b>Awesome framework!. </b><br> sada dhasjdasjdhasjdhas jdsahd j asdjhash dajhdjashdhas...
getSize(){ return this.posts.length; } }
{ this.posts.push( post ); }
identifier_body
post.service.ts
public posts : IPost[]; constructor() { this.posts = [ { id:1, content:"<b>Awesome framework!. </b><br> sada dhasjdasjdhasjdhas jdsahd j asdjhash dajhdjashdhasdg asjdh asdhasjdhjasdh ajsdhjash ajdhsaj dsjadhasj dhjasdh sajdhjsad ajsdh jadhajs dh ", comments:[{ id:1, ...
import { Injectable } from '@angular/core'; import { IPost } from './post-interface'; @Injectable() export class PostService {
random_line_split
post.service.ts
import { Injectable } from '@angular/core'; import { IPost } from './post-interface'; @Injectable() export class PostService { public posts : IPost[]; constructor() { this.posts = [ { id:1, content:"<b>Awesome framework!. </b><br> sada dhasjdasjdhasjdhas jdsahd j asdjhash dajhdjashdhas...
(){ return this.posts.length; } }
getSize
identifier_name
x86.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 ...
(target_triple: ~str, target_os: abi::Os) -> target_strs::t { return target_strs::t { module_asm: ~"", meta_sect_name: meta_section_name(sess_os_to_meta_os(target_os)).to_owned(), data_layout: match target_os { abi::OsMacos => { ~"e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16"...
get_target_strs
identifier_name
x86.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 ...
"-i32:32:32-i64:32:64" + "-f32:32:32-f64:32:64-v64:64:64" + "-v128:128:128-a0:0:64-f80:128:128" + "-n8:16:32" } abi::OsWin32 => { ~"e-p:32:32-f64:64:64-i64:64:64-f80:32:32-n8:16:32" } abi::OsLinux => { ~"e-...
data_layout: match target_os { abi::OsMacos => { ~"e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16" +
random_line_split
x86.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 ...
{ return target_strs::t { module_asm: ~"", meta_sect_name: meta_section_name(sess_os_to_meta_os(target_os)).to_owned(), data_layout: match target_os { abi::OsMacos => { ~"e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16" + "-i32:32:32-i64:32:64" + ...
identifier_body
x86.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 ...
abi::OsFreebsd => { ~"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32" } }, target_triple: target_triple, cc_args: ~[~"-m32"], }; }
{ ~"e-p:32:32-f64:32:64-i64:32:64-f80:32:32-n8:16:32" }
conditional_block
deriving-eq-ord-boxed-slice.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 ...
let a = Foo(box [0, 1, 2]); let b = Foo(box [0, 1, 2]); assert!(a == b); println!("{}", a != b); println!("{}", a < b); println!("{}", a <= b); println!("{}", a == b); println!("{}", a > b); println!("{}", a >= b); }
#[derive(PartialEq, PartialOrd, Eq, Ord)] struct Foo(Box<[u8]>); pub fn main() {
random_line_split
deriving-eq-ord-boxed-slice.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 ...
{ let a = Foo(box [0, 1, 2]); let b = Foo(box [0, 1, 2]); assert!(a == b); println!("{}", a != b); println!("{}", a < b); println!("{}", a <= b); println!("{}", a == b); println!("{}", a > b); println!("{}", a >= b); }
identifier_body
deriving-eq-ord-boxed-slice.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 ...
() { let a = Foo(box [0, 1, 2]); let b = Foo(box [0, 1, 2]); assert!(a == b); println!("{}", a != b); println!("{}", a < b); println!("{}", a <= b); println!("{}", a == b); println!("{}", a > b); println!("{}", a >= b); }
main
identifier_name
artifacts.py
#!/usr/bin/env python """End to end tests that run ArtifactCollectorFlow.""" from grr.endtoend_tests import base from grr.lib import aff4 from grr.lib.rdfvalues import client as rdf_client class TestDarwinPersistenceMechanisms(base.AutomatedTest): """Test DarwinPersistenceMechanisms.""" platforms = ["Darwin"] ...
# Make sure there are at least some results. self.assertEqual(len(volume_list), 1) self.assertEqual(volume_list[0].unixvolume.mount_point, "/") self.assertTrue(isinstance(volume_list[0].FreeSpacePercent(), float)) class TestParserDependency(base.AutomatedTest): """Test Artifacts complete when KB is ...
output_urn = self.client_id.Add(self.test_output_path) collection = aff4.FACTORY.Open(output_urn, mode="r", token=self.token) self.assertIsInstance(collection, aff4.RDFValueCollection) volume_list = list(collection)
random_line_split
artifacts.py
#!/usr/bin/env python """End to end tests that run ArtifactCollectorFlow.""" from grr.endtoend_tests import base from grr.lib import aff4 from grr.lib.rdfvalues import client as rdf_client class TestDarwinPersistenceMechanisms(base.AutomatedTest): """Test DarwinPersistenceMechanisms.""" platforms = ["Darwin"] ...
(self): # Set the KB to an empty object client = aff4.FACTORY.Open(self.client_id, mode="rw", token=self.token) self.old_kb = client.Get(client.Schema.KNOWLEDGE_BASE) client.Set(client.Schema.KNOWLEDGE_BASE, rdf_client.KnowledgeBase()) client.Flush() super(TestParserDependency, self).setUp() ...
setUp
identifier_name
artifacts.py
#!/usr/bin/env python """End to end tests that run ArtifactCollectorFlow.""" from grr.endtoend_tests import base from grr.lib import aff4 from grr.lib.rdfvalues import client as rdf_client class TestDarwinPersistenceMechanisms(base.AutomatedTest): """Test DarwinPersistenceMechanisms.""" platforms = ["Darwin"] ...
class TestParserDependencyUserShellFolders(TestParserDependency): test_output_path = "analysis/testing/TestParserDependencyUserShellFolders" args = {"artifact_list": ["UserShellFolders"], "dependencies": "FETCH_NOW", "output": test_output_path} def CheckFlow(self): super(TestParserDependencyUser...
test_output_path = "analysis/testing/TestParserDependencyTemp" args = {"artifact_list": ["TempEnvironmentVariable"], "dependencies": "FETCH_NOW", "output": test_output_path}
identifier_body
artifacts.py
#!/usr/bin/env python """End to end tests that run ArtifactCollectorFlow.""" from grr.endtoend_tests import base from grr.lib import aff4 from grr.lib.rdfvalues import client as rdf_client class TestDarwinPersistenceMechanisms(base.AutomatedTest): """Test DarwinPersistenceMechanisms.""" platforms = ["Darwin"] ...
self.assertTrue(userobj.appdata) self.assertTrue(userobj.temp)
conditional_block
pairtree_revlookup.py
#!/usr/bin/python # -*- coding: utf-8 -*- """ FS Pairtree storage - Reverse lookup ==================================== Conventions used: From http://www.cdlib.org/inside/diglib/pairtree/pairtreespec.html version 0.1 This is an implementation of a reverse lookup index, using the pairtree path spec to record the li...
[self._add_id(x) for x in args if not self._exists(x)] def __len__(self): return len(os.listdir(self._dirpath)) def __repr__(self): return "ID:'%s' -> ['%s']" % (self._id, "','".join(self._get_ids())) def __str__(self): return self.__repr__() def __iter__(self): for f in self._ge...
random_line_split
pairtree_revlookup.py
#!/usr/bin/python # -*- coding: utf-8 -*- """ FS Pairtree storage - Reverse lookup ==================================== Conventions used: From http://www.cdlib.org/inside/diglib/pairtree/pairtreespec.html version 0.1 This is an implementation of a reverse lookup index, using the pairtree path spec to record the li...
def __delitem__(self, id): dirpath = id_to_dirpath(id, self._rl_dir) if os.path.isdir(dirpath): for f in os.listdir(dirpath): os.remove(os.path.join(dirpath, f)) os.removedirs(dirpath) # will throw OSError if the dir cannot be removed. self._init_store() # just in case
id_c = PairtreeReverseLookup_list(self._rl_dir, id) if isinstance(list, value): id_c.append(*value) else: id_c.append(value)
identifier_body
pairtree_revlookup.py
#!/usr/bin/python # -*- coding: utf-8 -*- """ FS Pairtree storage - Reverse lookup ==================================== Conventions used: From http://www.cdlib.org/inside/diglib/pairtree/pairtreespec.html version 0.1 This is an implementation of a reverse lookup index, using the pairtree path spec to record the li...
def __delitem__(self, id): dirpath = id_to_dirpath(id, self._rl_dir) if os.path.isdir(dirpath): for f in os.listdir(dirpath): os.remove(os.path.join(dirpath, f)) os.removedirs(dirpath) # will throw OSError if the dir cannot be removed. self._init_store() # just in case
id_c.append(value)
conditional_block
pairtree_revlookup.py
#!/usr/bin/python # -*- coding: utf-8 -*- """ FS Pairtree storage - Reverse lookup ==================================== Conventions used: From http://www.cdlib.org/inside/diglib/pairtree/pairtreespec.html version 0.1 This is an implementation of a reverse lookup index, using the pairtree path spec to record the li...
(self): return self.__repr__() def __iter__(self): for f in self._get_ids(): yield id_decode(f) class PairtreeReverseLookup(object): def __init__(self, storage_dir="data"): self._storage_dir = storage_dir self._rl_dir = os.path.join(storage_dir, PAIRTREE_RL) self._init_store() ...
__str__
identifier_name
tests.py
from __future__ import absolute_import from six.moves.urllib.parse import urlparse, parse_qs
from sentry.plugins.bases.notify import NotificationPlugin from sentry.plugins.base.structs import Notification from sentry.testutils import TestCase class DummyNotificationPlugin(CorePluginMixin, NotificationPlugin): def is_configured(self, project): return True class NotifyPlugin(TestCase): def te...
from requests.exceptions import HTTPError, SSLError from sentry_plugins.base import CorePluginMixin from sentry.exceptions import PluginError from sentry.shared_integrations.exceptions import ApiError, ApiHostError, ApiUnauthorized
random_line_split
tests.py
from __future__ import absolute_import from six.moves.urllib.parse import urlparse, parse_qs from requests.exceptions import HTTPError, SSLError from sentry_plugins.base import CorePluginMixin from sentry.exceptions import PluginError from sentry.shared_integrations.exceptions import ApiError, ApiHostError, ApiUnauth...
(self): n = DummyNotificationPlugin() n.slug = "slack" url = "https://sentry.io/" assert n.add_notification_referrer_param(url) == url + "?referrer=" + n.slug url = "https://sentry.io/?referrer=notslack" assert n.add_notification_referrer_param(url) == "https://sentry.io...
test_add_notification_referrer_param
identifier_name
tests.py
from __future__ import absolute_import from six.moves.urllib.parse import urlparse, parse_qs from requests.exceptions import HTTPError, SSLError from sentry_plugins.base import CorePluginMixin from sentry.exceptions import PluginError from sentry.shared_integrations.exceptions import ApiError, ApiHostError, ApiUnauth...
else: message = err.text assert message assert message in n.test_configuration_and_get_test_results(self.project) class DummyNotificationPluginTest(TestCase): def setUp(self): self.event = self.store_event(data={}, project_id=self.project.id) se...
message = "your access token was invalid"
conditional_block
tests.py
from __future__ import absolute_import from six.moves.urllib.parse import urlparse, parse_qs from requests.exceptions import HTTPError, SSLError from sentry_plugins.base import CorePluginMixin from sentry.exceptions import PluginError from sentry.shared_integrations.exceptions import ApiError, ApiHostError, ApiUnauth...
def test_should_notify(self): assert self.plugin.should_notify(self.group, self.event)
self.event = self.store_event(data={}, project_id=self.project.id) self.group = self.event.group self.plugin = DummyNotificationPlugin()
identifier_body
reducer.jest.js
import produce from 'immer'; import homeReducer, { initialState } from '../reducer'; import { loadGalleries, galleriesLoadingSuccess, galleriesLoadingError, } from '../actions'; /* eslint-disable default-case, no-param-reassign */ describe('homeReducer', () => { let state; beforeEach(() => { state = ini...
expect(homeReducer(state, galleriesLoadingError(fixture, 'cdn'))).toEqual( expectedResult, ); }); });
draft.galleryErrors = fixture; draft.host = 'cdn'; });
random_line_split
Entity.js
//#include 'debug.js' //#include 'Image.js' //#include 'path/Ellipse.js' //#include 'path/Path.js' //#include 'path/Point.js' //#include 'path/Rect.js' //#include 'Tokenizer.js' var CanvizEntity = exports.CanvizEntity = function(defaultAttrHashName, name, canviz, rootGraph, parentGraph, immediateGraph) { this.defa...
if (tooltip) bbDiv.attr({title: tooltip}); } _.each(this.drawAttrs, _.bind(function(command) { // debug(command); var tokenizer = new CanvizTokenizer(command); var token = tokenizer.takeChars(); if (token) { var dashStyle = 'solid'; ctx.save(); while (token) { // ...
this.initBB(); var bbDiv = $('<div>'); bbDiv.addClass('entity'); this.canviz.elements.append(bbDiv); var tooltip = this.getAttr('tooltip');
random_line_split
Entity.js
//#include 'debug.js' //#include 'Image.js' //#include 'path/Ellipse.js' //#include 'path/Path.js' //#include 'path/Point.js' //#include 'path/Rect.js' //#include 'Tokenizer.js' var CanvizEntity = exports.CanvizEntity = function(defaultAttrHashName, name, canviz, rootGraph, parentGraph, immediateGraph) { this.defa...
colorName = matches[2]; } else { matches = color.match(/^\/(.*)$/); if (matches) { colorScheme = 'X11'; colorName = matches[1]; } } colorName = colorName.toLowerCase(); var colorSchemeName = colorScheme.toLowerCase(); var colorSchemeData = Canviz.prototype.colors[colorSchemeName]; if (c...
{ colorScheme = matches[1]; }
conditional_block
abstractworkerglobalscope.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::abstractworker::WorkerScriptMsg; use crate::dom::bindings::conversions::DerivedFrom; use crate::d...
(&self) -> Result<CommonScriptMsg, ()> { let common_msg = match self.recv() { Ok(DedicatedWorkerScriptMsg::CommonWorker(_worker, common_msg)) => common_msg, Err(_) => return Err(()), Ok(DedicatedWorkerScriptMsg::WakeUp) => panic!("unexpected worker event message!"), }...
recv
identifier_name
abstractworkerglobalscope.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::abstractworker::WorkerScriptMsg; use crate::dom::bindings::conversions::DerivedFrom; use crate::d...
fn clone(&self) -> Box<dyn ScriptChan + Send> { Box::new(WorkerThreadWorkerChan { sender: self.sender.clone(), worker: self.worker.clone(), }) } } impl ScriptPort for Receiver<DedicatedWorkerScriptMsg> { fn recv(&self) -> Result<CommonScriptMsg, ()> { let com...
self.sender.send(msg).map_err(|_| ()) }
random_line_split
abstractworkerglobalscope.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::abstractworker::WorkerScriptMsg; use crate::dom::bindings::conversions::DerivedFrom; use crate::d...
{ let scope = worker_scope.upcast::<WorkerGlobalScope>(); let timer_event_port = worker_scope.timer_event_port(); let devtools_port = match scope.from_devtools_sender() { Some(_) => Some(scope.from_devtools_receiver()), None => None, }; let task_queue = worker_scope.task_queue(); ...
identifier_body
connection.rs
use std::fmt::{self, Display}; use std::str::FromStr; use unicase::UniCase; pub use self::ConnectionOption::{KeepAlive, Close, ConnectionHeader}; const KEEP_ALIVE: UniCase<&'static str> = UniCase("keep-alive"); const CLOSE: UniCase<&'static str> = UniCase("close"); /// Values that can be in the `Connection` header. ...
fn parse_option(header: Vec<u8>) -> Connection { let val = vec![header]; let connection: Connection = Header::parse_header(&val[..]).unwrap(); connection } #[test] fn test_parse() { assert_eq!(Connection::close(),parse_option(b"close".to_vec())); assert_eq!(Conn...
use header::Header; use unicase::UniCase;
random_line_split
connection.rs
use std::fmt::{self, Display}; use std::str::FromStr; use unicase::UniCase; pub use self::ConnectionOption::{KeepAlive, Close, ConnectionHeader}; const KEEP_ALIVE: UniCase<&'static str> = UniCase("keep-alive"); const CLOSE: UniCase<&'static str> = UniCase("close"); /// Values that can be in the `Connection` header. ...
() { assert_eq!(Connection::close(),parse_option(b"close".to_vec())); assert_eq!(Connection::keep_alive(),parse_option(b"keep-alive".to_vec())); assert_eq!(Connection::keep_alive(),parse_option(b"Keep-Alive".to_vec())); assert_eq!(Connection(vec![ConnectionHeader(UniCase("upgrade".to_own...
test_parse
identifier_name
connection.rs
use std::fmt::{self, Display}; use std::str::FromStr; use unicase::UniCase; pub use self::ConnectionOption::{KeepAlive, Close, ConnectionHeader}; const KEEP_ALIVE: UniCase<&'static str> = UniCase("keep-alive"); const CLOSE: UniCase<&'static str> = UniCase("close"); /// Values that can be in the `Connection` header. ...
} impl Display for ConnectionOption { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(match *self { KeepAlive => "keep-alive", Close => "close", ConnectionHeader(UniCase(ref s)) => s.as_ref() }) } } header! { #[doc="`Connection` heade...
{ if UniCase(s) == KEEP_ALIVE { Ok(KeepAlive) } else if UniCase(s) == CLOSE { Ok(Close) } else { Ok(ConnectionHeader(UniCase(s.to_owned()))) } }
identifier_body
tree_layout.rs
use std::fmt::{Debug, Display}; use std::num::Float; use std::rc::Rc; use tree::Tree; use tree::Tree::{Node, Tip}; // Tree layout algorithm based on the following paper: // "FUNCTIONAL PEARLS - Drawing Trees by Andrew J. Kennedy (1996)" // (http://research.microsoft.com/en-us/um/people/akenn/fun/DrawingTrees.pdf) pu...
(es: Vec<Extent>, acc: Extent) -> Vec<f64> { match es.first() { Some(e) => { let x = fit(acc.clone(), e.clone()); let mut r = aux(es.tail().to_vec(), merge_extent(acc.clone(), move_extent(e.clone().to_vec(), x))); r.insert(0, x); r ...
aux
identifier_name
tree_layout.rs
use std::fmt::{Debug, Display}; use std::num::Float; use std::rc::Rc; use tree::Tree; use tree::Tree::{Node, Tip}; // Tree layout algorithm based on the following paper: // "FUNCTIONAL PEARLS - Drawing Trees by Andrew J. Kennedy (1996)" // (http://research.microsoft.com/en-us/um/people/akenn/fun/DrawingTrees.pdf) pu...
fn fit_list_left(es: Vec<Extent>) -> Vec<f64> { fn aux(es: Vec<Extent>, acc: Extent) -> Vec<f64> { match es.first() { Some(e) => { let x = fit(acc.clone(), e.clone()); let mut r = aux(es.tail().to_vec(), merge_extent(acc.clone(), move_extent(e.clone().to_vec(), ...
{ fn flip_extent(e: Extent) -> Extent { e.iter().map(|&x| { let (p, q) = x; (-q, -p) }).collect() } fit_list_left( es.iter().rev().map(|e| flip_extent((*e).clone())).collect()).iter() .map(|&f| -f).rev().collect() }
identifier_body
tree_layout.rs
use std::fmt::{Debug, Display}; use std::num::Float; use std::rc::Rc; use tree::Tree; use tree::Tree::{Node, Tip}; // Tree layout algorithm based on the following paper: // "FUNCTIONAL PEARLS - Drawing Trees by Andrew J. Kennedy (1996)" // (http://research.microsoft.com/en-us/um/people/akenn/fun/DrawingTrees.pdf) pu...
fit_list_right(es.clone()).iter()) .map(|x| mean(*x.0, *x.1)).collect() } fn fit_list_right(es: Vec<Extent>) -> Vec<f64> { fn flip_extent(e: Extent) -> Extent { e.iter().map(|&x| { let (p, q) = x; (-q, -p) }).collect() } fit_list_left( es.ite...
fn mean(x: f64, y: f64) -> f64 { (x + y) / 2.0 } fit_list_left(es.clone()).iter().zip(
random_line_split
signature.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity 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 lat...
(&self) -> bool { H256::from_slice(self.s()) <= "7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0".into() } /// Check if each component of the signature is in range. pub fn is_valid(&self) -> bool { self.v() <= 1 && H256::from_slice(self.r()) < "fffffffffffffffffffffffffffffffebaaedce6af48a03...
is_low_s
identifier_name
signature.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity 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 lat...
assert!(verify_address(&keypair.address(), &signature, &message).unwrap()); } }
random_line_split
signature.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity 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 lat...
#[cfg(test)] mod tests { use std::str::FromStr; use {Generator, Random, Message}; use super::{sign, verify_public, verify_address, recover, Signature}; #[test] fn vrs_conversion() { // given let keypair = Random.generate().unwrap(); let message = Message::default(); let signature = sign(keypair.secret()...
{ let context = &SECP256K1; let rsig = RecoverableSignature::from_compact(context, &signature[0..64], RecoveryId::from_i32(signature[64] as i32)?)?; let pubkey = context.recover(&SecpMessage::from_slice(&message[..])?, &rsig)?; let serialized = pubkey.serialize_vec(context, false); let mut public = Public::defaul...
identifier_body
by-value-non-immediate-argument.rs
// Copyright 2013-2014 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-MI...
(a: (int, uint, f64, f64)) { zzz(); // #break } struct Newtype(f64, f64, int, uint); fn new_type(a: Newtype) { zzz(); // #break } // The first element is to ensure proper alignment, irrespective of the machines word size. Since // the size of the discriminant value is machine dependent, this has be taken int...
tup
identifier_name
by-value-non-immediate-argument.rs
// Copyright 2013-2014 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-MI...
fn tup(a: (int, uint, f64, f64)) { zzz(); // #break } struct Newtype(f64, f64, int, uint); fn new_type(a: Newtype) { zzz(); // #break } // The first element is to ensure proper alignment, irrespective of the machines word size. Since // the size of the discriminant value is machine dependent, this has be t...
{ zzz(); // #break }
identifier_body
by-value-non-immediate-argument.rs
// Copyright 2013-2014 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-MI...
// === LLDB TESTS ================================================================================== // lldb-command:run // lldb-command:print s // lldb-check:[...]$0 = Struct { a: 1, b: 2.5 } // lldb-command:continue // lldb-command:print x // lldb-check:[...]$1 = Struct { a: 3, b: 4.5 } // lldb-command:print y /...
random_line_split
utils.js
window.Utils = (function() { const DIGITS = 6; function numberToFixed (number)
function arrayNumbersToFixed (array) { for (var i = 0; i < array.length; i++) { array[i] = numberToFixed(array[i]); } return array; } function getTooltips (controllerName) { var tooltips; var tooltipName; switch (controllerName) { ca...
{ return parseFloat(number.toFixed(DIGITS)); }
identifier_body
utils.js
window.Utils = (function() { const DIGITS = 6; function numberToFixed (number) { return parseFloat(number.toFixed(DIGITS)); } function arrayNumbersToFixed (array) { for (var i = 0; i < array.length; i++) { array[i] = numberToFixed(array[i]); } return array; ...
tooltipName = '.oculus-tooltips'; break; } case 'vive-controls': { tooltipName = '.vive-tooltips'; break; } default: { break; } } tooltips = Array.prototype.slice....
case 'windows-motion-controls': { tooltipName = '.windows-motion-tooltips'; break; } case 'oculus-touch-controls': {
random_line_split
utils.js
window.Utils = (function() { const DIGITS = 6; function
(number) { return parseFloat(number.toFixed(DIGITS)); } function arrayNumbersToFixed (array) { for (var i = 0; i < array.length; i++) { array[i] = numberToFixed(array[i]); } return array; } function getTooltips (controllerName) { var tooltips; ...
numberToFixed
identifier_name
72_Edit_Distance.py
class Solution(object): def minDistance(self, word1, word2): """ :type word1: str :type word2: str :rtype: int """ row = len(word1) + 1 col = len(word2) + 1 dp = [[0] * col for _ in range(row)] for i in range(col): dp[0][i] = i ...
dp[i][j] = min(dp[i][j], dp[i - 1][j] + 1, dp[i][j - 1] + 1) return dp[row - 1][col - 1]
dp[i][j] = dp[i - 1][j - 1] + 1
conditional_block
72_Edit_Distance.py
class Solution(object): def
(self, word1, word2): """ :type word1: str :type word2: str :rtype: int """ row = len(word1) + 1 col = len(word2) + 1 dp = [[0] * col for _ in range(row)] for i in range(col): dp[0][i] = i for i in range(row): dp[...
minDistance
identifier_name
72_Edit_Distance.py
class Solution(object): def minDistance(self, word1, word2): """ :type word1: str :type word2: str
dp = [[0] * col for _ in range(row)] for i in range(col): dp[0][i] = i for i in range(row): dp[i][0] = i for i in range(1, row): for j in range(1, col): if word1[i - 1] == word2[j - 1]: dp[i][j] = dp[i - 1][j - 1...
:rtype: int """ row = len(word1) + 1 col = len(word2) + 1
random_line_split
72_Edit_Distance.py
class Solution(object): def minDistance(self, word1, word2):
""" :type word1: str :type word2: str :rtype: int """ row = len(word1) + 1 col = len(word2) + 1 dp = [[0] * col for _ in range(row)] for i in range(col): dp[0][i] = i for i in range(row): dp[i][0] = i for i in ra...
identifier_body
Block.js
var IpWidget_Block = function () { this.init = function (widgetObject, data) { //store widgetObject variable to be accessible from other functions this.widgetObject = widgetObject; this.widgetObject.css('min-height', '30px'); //if widget is empty it could be impossible to click on. ...
// wrap fields in a div so accordion would work $popup.find('fieldset').each(function (index, fieldset) { var $fieldset = $(fieldset); var $legend = $fieldset.find('legend'); // if legend exist it means its option group ...
var $popup = $('#ipWidgetBlockPopup .ipsModal'); $popup.modal(); ipInitForms(); //This is standard ImpressPages function to initialize JS specific form fields
random_line_split
Block.js
var IpWidget_Block = function () { this.init = function (widgetObject, data) { //store widgetObject variable to be accessible from other functions this.widgetObject = widgetObject; this.widgetObject.css('min-height', '30px'); //if widget is empty it could be impossible to click on. ...
}); var $editScreen = $popup.find('.ipsEditScreen'); $editScreen.ipUploadImage('destroy'); $editScreen.ipUploadImage({ image: $popup.find('input[name="background_image"]').val(), windowHeight: 300, ...
{ // adding required attributes to make collapse() to work $legend .attr('data-toggle', 'collapse') .attr('data-target', '#blockPropertiesCollapse' + index) .addClass('collapsed'); ...
conditional_block
en-ie.js
//! moment.js locale configuration //! locale : Irish english (en-ie) //! author : Chris Cartlidge : https://github.com/chriscartlidge ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../moment')) : typeof defin...
dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); return en_ie; }));
week : {
random_line_split
highlight.js
var Highlight = function() { /* Utility functions */ function escape(value) { return value.replace(/&/gm, '&amp;').replace(/</gm, '&lt;').replace(/>/gm, '&gt;'); } function tag(node) { return node.nodeName.toLowerCase(); } function testRe(re, lexeme) { var match = re && re.exec(lexeme); ...
/* Core highlighting function. Accepts a language name, or an alias, and a string with the code to highlight. Returns an object with the following properties: - relevance (int) - value (an HTML string with highlighting markup) */ function highlight(name, value, ignore_illegals, continuation) { ...
{ function reStr(re) { return (re && re.source) || re; } function langRe(value, global) { return RegExp( reStr(value), 'm' + (language.case_insensitive ? 'i' : '') + (global ? 'g' : '') ); } function compileMode(mode, parent) { if (mode.compiled) ...
identifier_body
highlight.js
var Highlight = function() { /* Utility functions */ function escape(value) { return value.replace(/&/gm, '&amp;').replace(/</gm, '&lt;').replace(/>/gm, '&gt;'); } function tag(node) { return node.nodeName.toLowerCase(); } function testRe(re, lexeme) { var match = re && re.exec(lexeme); ...
result.value = fixMarkup(result.value); block.innerHTML = result.value; block.className += ' hljs ' + (!language && result.language || ''); block.result = { language: result.language, re: result.relevance }; if (result.second_best) { block.second_best = { language: re...
{ var resultNode = document.createElementNS('http://www.w3.org/1999/xhtml', 'div'); resultNode.innerHTML = result.value; result.value = mergeStreams(originalStream, nodeStream(resultNode), text); }
conditional_block