file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
color.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/. */ //! Resolved color values. use super::{Context, ToResolvedValue}; use crate::values::computed; use crate::value...
(self, context: &Context) -> Self::ResolvedValue { context.style.resolve_color(self) } #[inline] fn from_resolved_value(resolved: Self::ResolvedValue) -> Self { generics::Color::Numeric(resolved) } } impl ToResolvedValue for computed::ColorOrAuto { // A resolved caret-color value i...
to_resolved_value
identifier_name
color.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/. */ //! Resolved color values. use super::{Context, ToResolvedValue}; use crate::values::computed; use crate::value...
#[inline] fn from_resolved_value(resolved: Self::ResolvedValue) -> Self { generics::ColorOrAuto::Color(computed::Color::from_resolved_value(resolved)) } }
{ let color = match self { generics::ColorOrAuto::Color(color) => color, generics::ColorOrAuto::Auto => generics::Color::CurrentColor, }; color.to_resolved_value(context) }
identifier_body
controller.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core'; import { FormControl } from '@angular/forms'; import { Observable } from 'rxjs/Observable'; import { Subscription } from 'rxjs/Subscription'; import 'rxjs/add/observable/interval'; import { LifeService } from '../life.service'; import { FileService } from ...
upload() { this.fileService.upload(config.cols, config.rows); } }
{ if (this.playing) { this.handler.unsubscribe(); this.playing = false; } }
identifier_body
controller.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core'; import { FormControl } from '@angular/forms'; import { Observable } from 'rxjs/Observable'; import { Subscription } from 'rxjs/Subscription'; import 'rxjs/add/observable/interval'; import { LifeService } from '../life.service'; import { FileService } from ...
} upload() { this.fileService.upload(config.cols, config.rows); } }
{ this.handler.unsubscribe(); this.playing = false; }
conditional_block
controller.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core'; import { FormControl } from '@angular/forms'; import { Observable } from 'rxjs/Observable'; import { Subscription } from 'rxjs/Subscription'; import 'rxjs/add/observable/interval'; import { LifeService } from '../life.service'; import { FileService } from ...
() { if (this.playing) { return; } this.playing = true; this.handler = Observable.interval(config.interval) .subscribe(() => this.service.nextGeneration()); } stop() { if (this.playing) { this.handler.unsubscribe(); this.playing = false; } } upload() { this...
play
identifier_name
controller.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core'; import { FormControl } from '@angular/forms'; import { Observable } from 'rxjs/Observable'; import { Subscription } from 'rxjs/Subscription'; import 'rxjs/add/observable/interval'; import { LifeService } from '../life.service'; import { FileService } from ...
* interaction with the application. Also it calls the proper * service methods. */ @Component({ selector: 'app-controller', templateUrl: './controller.component.html' }) export class ControllerComponent implements OnInit, OnDestroy { private handler: Subscription; private playing = false; private hasFile =...
random_line_split
structCS__AUDIODEVICE.js
var structCS__AUDIODEVICE = [ [ "device_id", "structCS__AUDIODEVICE.html#acaaaa3af3e56f33d6c83612eecc5af5b", null ], [ "device_name", "structCS__AUDIODEVICE.html#a0bc59d45f53cad0863859f38e573c9a2", null ], [ "isOutput", "structCS__AUDIODEVICE.html#abe34361d001528d150f4c5976d195d41", null ],
[ "rt_module", "structCS__AUDIODEVICE.html#a2f6742e5f4b735f67adb0a61a0548ed2", null ] ];
[ "max_nchnls", "structCS__AUDIODEVICE.html#ad290a89b60a4119d913ca98b765e3a2c", null ],
random_line_split
command.js
(c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview A command is an abstraction of an action a user can do in the * UI. * * When the focus changes in the document for each command a canExecu...
this.mods_ = mods; } KeyboardShortcut.prototype = { /** * Whether the keyboard shortcut object matches a keyboard event. * @param {!Event} e The keyboard event object. * @return {boolean} Whether we found a match or not. */ matchesEvent: function(e) { if (e.keyIdentifier == t...
{ var mods = {}; var ident = ''; shortcut.split('-').forEach(function(part) { var partLc = part.toLowerCase(); switch (partLc) { case 'alt': case 'ctrl': case 'meta': case 'shift': mods[partLc + 'Key'] = true; break; default: ...
identifier_body
command.js
(c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview A command is an abstraction of an action a user can do in the * UI. * * When the focus changes in the document for each command a canExecu...
(shortcut) { var mods = {}; var ident = ''; shortcut.split('-').forEach(function(part) { var partLc = part.toLowerCase(); switch (partLc) { case 'alt': case 'ctrl': case 'meta': case 'shift': mods[partLc + 'Key'] = true; break; default:...
KeyboardShortcut
identifier_name
command.js
Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview A command is an abstraction of an action a user can do in the * UI. * * When the focus changes in the document for each command ...
* Whether the command is disabled or not. * @type {boolean} */ cr.defineProperty(Command, 'disabled', cr.PropertyKind.BOOL_ATTR); /** * Whether the command is hidden or not. * @type {boolean} */ cr.defineProperty(Command, 'hidden', cr.PropertyKind.BOOL_ATTR); /** * Whether the command is ...
* @type {string} */ cr.defineProperty(Command, 'label', cr.PropertyKind.ATTR); /**
random_line_split
drawer.js
/** ******************************************************************************************************************** * * drawer with left navigation * @exports {function} initializeDrawer * ********************************************************************************************************************...
if (response.data.status === "success") { DEBUG && console.log("saved drawer setting in db."); } else { DEBUG && console.error(`error while saving to database: ${response}`); } }) ...
isLoggedIn() && !isSmallViewPort() && axios .post("/api/user/opendrawer") .then(response => {
random_line_split
drawer.js
/** ******************************************************************************************************************** * * drawer with left navigation * @exports {function} initializeDrawer * ********************************************************************************************************************...
else { openDrawer(drawer, button); } }); }; /* * public export */ export {initDrawer};
{ closeDrawer(drawer, button); }
conditional_block
oozie_api.js
var request = require('request'); var q = require('q'); var _ = require('underscore'); module.exports = { createOozieClient: function (options) { var _options = options; return { // Get oozie status // return {systemMode: ''} getStatus: getStatus, // Get oozie jobs // return: { // total: 0...
}); } function _get(uri) { var deferred = q.defer(); request.get(uri, { 'auth': { 'user': _options.user, 'pass': _options.pass, 'sendImmediately': false } }, responseFunc); function responseFunc(error, response, body) { if (!error && response.statusCode == 200) { ...
random_line_split
oozie_api.js
var request = require('request'); var q = require('q'); var _ = require('underscore'); module.exports = { createOozieClient: function (options) { var _options = options; return { // Get oozie status // return {systemMode: ''} getStatus: getStatus, // Get oozie jobs // return: { // total: ...
else { deferred.reject(error); } } return deferred.promise; } } };
{ deferred.resolve(body); }
conditional_block
oozie_api.js
var request = require('request'); var q = require('q'); var _ = require('underscore'); module.exports = { createOozieClient: function (options) { var _options = options; return { // Get oozie status // return {systemMode: ''} getStatus: getStatus, // Get oozie jobs // return: { // total: ...
function getJobs(params) { var uri = _options.uri + '/oozie/v2/jobs'; return _get(uri) .then(function (response) { return JSON.parse(response); }, function (err) { return err; }); } function getStatus() { var uri = _options.uri + '/oozie/v2/admin/status'; return _get(uri) ...
{ var uri = _options.uri + '/oozie/v2/jobs?action=start'; var xmlParams = _.reduce(_.keys(jobParamsJson), function (context, key) { return context + '<property><name>' + key + '</name><value>' + jobParamsJson[key] + '</value></property>'; }, ''); var oozieParamsXml = '<?xml version="1.0" encoding="UTF...
identifier_body
oozie_api.js
var request = require('request'); var q = require('q'); var _ = require('underscore'); module.exports = { createOozieClient: function (options) { var _options = options; return { // Get oozie status // return {systemMode: ''} getStatus: getStatus, // Get oozie jobs // return: { // total: ...
(error, response, body) { if (!error && response.statusCode == 201) { deferred.resolve(body); } else { deferred.reject(error); } } return deferred.promise; } } };
responseFunc
identifier_name
k-clustering-hamming.py
import operator import time # Only the vertex (and its hamming distance is given) # Need to find all vertices which are within a hamming distance of 2 # That means for each vertex, generate a list of 300 other vertices (24 bits + 23 + 22 + ... + 1) # which are with hamming distance of 2 (generate vertices with 2 bit...
#end = time.clock() #print end - start # Error was happening because here the key is something like "1001000" # Earlier program it was something like 1:2, 2:3, 3:3, so we could say that the root # is the root when the key is same as parent. so in the case above 3=3, so it is the root # Here we cannot do the sa...
if root(vert_union1[x]) != root(vert_union1[v]): # not required for algo. Just counting down the clusters clusters = clusters - 1 #print clusters #start = time.clock() #print x union(vert_union1[x],vert_union1[v]) #print "after ", root(vert_union1[x]), ",", root(vert_union1[v]) #end ...
conditional_block
k-clustering-hamming.py
import operator import time # Only the vertex (and its hamming distance is given) # Need to find all vertices which are within a hamming distance of 2 # That means for each vertex, generate a list of 300 other vertices (24 bits + 23 + 22 + ... + 1) # which are with hamming distance of 2 (generate vertices with 2 bit...
(key): while (vert_union_parent[key] != key): key = parent(key) return vert_union_parent[key] def union(key1, key2): root_key2 = root(key2) vert_union_parent[root_key2] = root(key1) # Put the root of the first one as the parent of the second one's root # this avoids the issue of union of two vertices whose ...
root
identifier_name
k-clustering-hamming.py
import operator import time # Only the vertex (and its hamming distance is given) # Need to find all vertices which are within a hamming distance of 2 # That means for each vertex, generate a list of 300 other vertices (24 bits + 23 + 22 + ... + 1) # which are with hamming distance of 2 (generate vertices with 2 bit...
# then see if these 300 are also in the vertex list. # if they are, then union/cluster them together print vertices_done vertices_done = vertices_done + 1 # Not required. Just counting up the vertices #start = time.clock() h_list = return_hamming_1_2_distance(v) # convert this to do for all vertices #end...
print "Done input" for v in vert_list_set: # for all the vertices, find all its hamming sets (300 vertices)
random_line_split
k-clustering-hamming.py
import operator import time # Only the vertex (and its hamming distance is given) # Need to find all vertices which are within a hamming distance of 2 # That means for each vertex, generate a list of 300 other vertices (24 bits + 23 + 22 + ... + 1) # which are with hamming distance of 2 (generate vertices with 2 bit...
if __name__ == '__main__': i = 0 with open('clustering_big.txt') as f: no_v, bits = [int(x) for x in f.readline().split()] for line in f: # read rest of lines temp = [str(x) for x in line] temp = [num.strip() for num in temp] temp = filter(None, temp) temp = ''.join(map(str,temp)) # temp = temp.r...
root_key2 = root(key2) vert_union_parent[root_key2] = root(key1) # Put the root of the first one as the parent of the second one's root # this avoids the issue of union of two vertices whose parents are different from their roots # for example b is a's root and c is d's root. When we union a and c, we should not ...
identifier_body
main.rs
#![feature(plugin)] #![plugin(regex_macros)] extern crate itertools; extern crate regex; extern crate rustc_serialize; extern crate strsim; extern crate telegram_bot as telegram; extern crate term_painter; #[macro_use] mod log;
mod needed; use bot::MartiniBot; use log::LogLevel; use std::env; use std::path::Path; fn main() { // Fetch environment variable with bot token let token = match env::var("TELEGRAM_BOT_TOKEN") { Ok(tok) => tok, Err(e) => panic!("Environment variable 'TELEGRAM_BOT_TOKEN' missing! {...
mod bot; mod iter;
random_line_split
main.rs
#![feature(plugin)] #![plugin(regex_macros)] extern crate itertools; extern crate regex; extern crate rustc_serialize; extern crate strsim; extern crate telegram_bot as telegram; extern crate term_painter; #[macro_use] mod log; mod bot; mod iter; mod needed; use bot::MartiniBot; use log::LogLevel; use std::env; use...
{ // Fetch environment variable with bot token let token = match env::var("TELEGRAM_BOT_TOKEN") { Ok(tok) => tok, Err(e) => panic!("Environment variable 'TELEGRAM_BOT_TOKEN' missing! {}", e), }; // Create bot and print bot information, if it succeeded let mut bot = Marti...
identifier_body
main.rs
#![feature(plugin)] #![plugin(regex_macros)] extern crate itertools; extern crate regex; extern crate rustc_serialize; extern crate strsim; extern crate telegram_bot as telegram; extern crate term_painter; #[macro_use] mod log; mod bot; mod iter; mod needed; use bot::MartiniBot; use log::LogLevel; use std::env; use...
() { // Fetch environment variable with bot token let token = match env::var("TELEGRAM_BOT_TOKEN") { Ok(tok) => tok, Err(e) => panic!("Environment variable 'TELEGRAM_BOT_TOKEN' missing! {}", e), }; // Create bot and print bot information, if it succeeded let mut bot = Ma...
main
identifier_name
formatNumber.tsx
export default function
(rawNumber: number | undefined | null): string { if (!rawNumber) { return '0'; } if (rawNumber < 10000) { return rawNumber.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,'); } else if (rawNumber >= 10000 && rawNumber < 100000) { return `${Math.round(rawNumber / 100) / 10}k`; } else if (rawNumb...
formatNumber
identifier_name
formatNumber.tsx
export default function formatNumber(rawNumber: number | undefined | null): string { if (!rawNumber) { return '0'; } if (rawNumber < 10000) { return rawNumber.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,'); } else if (rawNumber >= 10000 && rawNumber < 100000) {
} else { return rawNumber.toString(); } }
return `${Math.round(rawNumber / 100) / 10}k`; } else if (rawNumber >= 100000 && rawNumber < 1000000) { return `${Math.round(rawNumber / 1000)}k`; } else if (rawNumber >= 1000000) { return `${Math.round(rawNumber / 100000) / 10}m`;
random_line_split
formatNumber.tsx
export default function formatNumber(rawNumber: number | undefined | null): string { if (!rawNumber) { return '0'; } if (rawNumber < 10000) { return rawNumber.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,'); } else if (rawNumber >= 10000 && rawNumber < 100000) { return `${Math.round(rawNumber ...
}
{ return rawNumber.toString(); }
conditional_block
formatNumber.tsx
export default function formatNumber(rawNumber: number | undefined | null): string
{ if (!rawNumber) { return '0'; } if (rawNumber < 10000) { return rawNumber.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,'); } else if (rawNumber >= 10000 && rawNumber < 100000) { return `${Math.round(rawNumber / 100) / 10}k`; } else if (rawNumber >= 100000 && rawNumber < 1000000) { retu...
identifier_body
index.js
/*! * list-item <https://github.com/jonschlinkert/list-item> * * Copyright (c) 2015-present, Jon Schlinkert. * Licensed under the MIT License. */ 'use strict'; const isNumber = require('is-number'); const fill = require('fill-range'); /** * Returns a function to generate a plain-text/markdown list-item, * all...
let res = ''; res += indent.repeat(lvl); res += prefix; res += suffix; return res; }; } /** * Create the array of characters to use as bullets. * * - http://spec.commonmark.org/0.19/#list-items * - https://daringfireball.net/projects/markdown/syntax#list * - https://help.github.com/article...
{ return fn(indent.repeat(lvl), bullet, index); }
conditional_block
index.js
/*! * list-item <https://github.com/jonschlinkert/list-item> * * Copyright (c) 2015-present, Jon Schlinkert. * Licensed under the MIT License. */ 'use strict'; const isNumber = require('is-number'); const fill = require('fill-range'); /** * Returns a function to generate a plain-text/markdown list-item, * all...
(options = {}, fn) { if (typeof options === 'function') { fn = options; options = {}; } let chars = character(options); let index = 0; return (lvl, suffix) => { if (!isNumber(lvl)) { throw new Error('expected level to be a number'); } // cast to number lvl = +lvl; index++;...
listitem
identifier_name
index.js
/*! * list-item <https://github.com/jonschlinkert/list-item> * * Copyright (c) 2015-present, Jon Schlinkert. * Licensed under the MIT License. */ 'use strict'; const isNumber = require('is-number'); const fill = require('fill-range'); /** * Returns a function to generate a plain-text/markdown list-item, * all...
/** * Expose `listitem` */ module.exports = listitem;
{ let chars = options.chars || ['-', '*', '+']; if (typeof chars === 'string') { return fill(...chars.split('..'), options); } return chars; }
identifier_body
index.js
/*! * list-item <https://github.com/jonschlinkert/list-item> * * Copyright (c) 2015-present, Jon Schlinkert. * Licensed under the MIT License. */ 'use strict'; const isNumber = require('is-number'); const fill = require('fill-range'); /** * Returns a function to generate a plain-text/markdown list-item, * all...
} let res = ''; res += indent.repeat(lvl); res += prefix; res += suffix; return res; }; } /** * Create the array of characters to use as bullets. * * - http://spec.commonmark.org/0.19/#list-items * - https://daringfireball.net/projects/markdown/syntax#list * - https://help.github.com/ar...
? bullet + ' ' : ''; if (typeof fn === 'function') { return fn(indent.repeat(lvl), bullet, index);
random_line_split
main.rs
use std::int; use std::comm::stream; use std::comm::Port; use std::comm::Chan; type MaybeInt = Option<int>; fn fib_generator(max: int, chan: &Chan<MaybeInt>) { let mut a = 0; let mut b = 1; loop { let next = a + b; if next > max { break; } b = a; a ...
} let mut accum: int = 0; loop { let next: MaybeInt = port.recv(); match next { Some(x) if x % 2 == 0 => accum += x, Some(_) => loop, None => break, }; } println(fmt!("%d", accum)); }
random_line_split
main.rs
use std::int; use std::comm::stream; use std::comm::Port; use std::comm::Chan; type MaybeInt = Option<int>; fn
(max: int, chan: &Chan<MaybeInt>) { let mut a = 0; let mut b = 1; loop { let next = a + b; if next > max { break; } b = a; a = next; chan.send(Some(next)); } chan.send(None); } fn main() { let (port, chan): (Port<MaybeInt>, Chan<...
fib_generator
identifier_name
main.rs
use std::int; use std::comm::stream; use std::comm::Port; use std::comm::Chan; type MaybeInt = Option<int>; fn fib_generator(max: int, chan: &Chan<MaybeInt>)
fn main() { let (port, chan): (Port<MaybeInt>, Chan<MaybeInt>) = stream(); do spawn { fib_generator(4000000, &chan); } let mut accum: int = 0; loop { let next: MaybeInt = port.recv(); match next { Some(x) if x % 2 == 0 => accum += x, Some(_) => ...
{ let mut a = 0; let mut b = 1; loop { let next = a + b; if next > max { break; } b = a; a = next; chan.send(Some(next)); } chan.send(None); }
identifier_body
ajax.js
function redrawFromSelection(obj, url, current_selection) { /* Create the selection */ var new_selection = {}; $.each(obj.exp_selection, function(ekey,evalue) { $.each(evalue.exp_data, function(dkey,dvalue) { if (dvalue.selected) { new_selection[ekey + "-" + dkey] = ...
(obj) { obj.exp_selection = {}; // Re-Initialize experiments object var exp = experiments; var exp_selection = obj.exp_selection; var exp_to_load = 0; var exp_loaded = 0; $.ajax({ type: 'GET', url: '/get_experiments', dataType: 'json', data:...
createExpSelection
identifier_name
ajax.js
function redrawFromSelection(obj, url, current_selection) { /* Create the selection */ var new_selection = {}; $.each(obj.exp_selection, function(ekey,evalue) { $.each(evalue.exp_data, function(dkey,dvalue) { if (dvalue.selected) { new_selection[ekey + "-" + dkey] = ...
/* Needed to update current_selection */ //current_selection[key] = value; }); /* Maybe nothing was selected ?! */ if (Object.keys(new_selection).length === 0) { obj.clearPlot(); return new_selection; } /* Nothing to reload, but we should trigger a redraw */ ...
{ sel_key = key.split('-'); load_selection.push([ parseInt(sel_key[0], 10), parseInt(sel_key[1], 10), parseInt(sel_key[2], 10) ]); }
conditional_block
ajax.js
function redrawFromSelection(obj, url, current_selection)
parseInt(sel_key[2], 10) ]); } /* Needed to update current_selection */ //current_selection[key] = value; }); /* Maybe nothing was selected ?! */ if (Object.keys(new_selection).length === 0) { obj.clearPlot(); return new_selectio...
{ /* Create the selection */ var new_selection = {}; $.each(obj.exp_selection, function(ekey,evalue) { $.each(evalue.exp_data, function(dkey,dvalue) { if (dvalue.selected) { new_selection[ekey + "-" + dkey] = true; } }); }); var load_sele...
identifier_body
ajax.js
function redrawFromSelection(obj, url, current_selection) { /* Create the selection */ var new_selection = {}; $.each(obj.exp_selection, function(ekey,evalue) { $.each(evalue.exp_data, function(dkey,dvalue) { if (dvalue.selected) { new_selection[ekey + "-" + dkey] = ...
if (!(key in current_selection)) { sel_key = key.split('-'); load_selection.push([ parseInt(sel_key[0], 10), parseInt(sel_key[1], 10), parseInt(sel_key[2], 10) ]); } /* Needed to update current_selection */...
}); }); var load_selection = []; $.each(new_selection, function(key,value) {
random_line_split
file_tools.py
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import unicode_literals import codecs import distutils.dir_util import os import shutil import sys def touch_file(file_path): """ Create a new empty file at file_path. """ parent_dir = os.path.abspath(os.path.join(file_path, os.pardir)) if...
def copy_tree(input_dir, output_dir, overwrite=False): """ Helper function to copy a directory tree that adds an overwrite parameter. """ if os.path.isdir(output_dir): if overwrite: print('Directory exists, overwriting') distutils.dir_util.copy_tree(input_dir, output_d...
""" Helper function to copy a file that adds an overwrite parameter. """ if os.path.isfile(output_file): if overwrite: print('File exists, overwriting') shutil.copyfile(input_file, output_file) else: sys.exit('File exists, unable to continue: %s' % output_...
identifier_body
file_tools.py
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import unicode_literals import codecs import distutils.dir_util import os import shutil import sys def touch_file(file_path): """ Create a new empty file at file_path. """ parent_dir = os.path.abspath(os.path.join(file_path, os.pardir)) if...
with codecs.open(file_path, 'a'): os.utime(file_path, None) def copy_file(input_file, output_file, overwrite=False): """ Helper function to copy a file that adds an overwrite parameter. """ if os.path.isfile(output_file): if overwrite: print('File exists, overwriting')...
os.makedirs(parent_dir)
conditional_block
file_tools.py
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import unicode_literals import codecs import distutils.dir_util import os import shutil import sys def touch_file(file_path): """ Create a new empty file at file_path. """ parent_dir = os.path.abspath(os.path.join(file_path, os.pardir)) if...
(dir_path): """ Walk a directory and create a list of all contained file_paths in all sub-directories. """ file_paths = [] for root, dirs, files in os.walk(dir_path): for f in files: file_paths.append(os.path.join(root, f)) return file_paths def clean_dsstore(dir_path): ...
get_file_paths_from_directory
identifier_name
file_tools.py
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import unicode_literals import codecs import distutils.dir_util import os import shutil import sys def touch_file(file_path): """ Create a new empty file at file_path. """ parent_dir = os.path.abspath(os.path.join(file_path, os.pardir)) if...
def copy_tree(input_dir, output_dir, overwrite=False): """ Helper function to copy a directory tree that adds an overwrite parameter. """ if os.path.isdir(output_dir): if overwrite: print('Directory exists, overwriting') distutils.dir_util.copy_tree(input_dir, output_dir...
random_line_split
test_Browser_logs.py
from termcolor import colored def test_Browser_logs(app): wd = app.wd sidebar = wd.find_element_by_xpath("//td[@id='sidebar']") sidebar.find_element_by_xpath(".//span[normalize-space(.)='Catalog']").click() wd.find_element_by_xpath("//i[@class='fa fa-folder']/../a").click() products_qty = len(wd.f...
wd.find_element_by_name("cancel").click()
print(colored("WARNING! LOG EXIST(S)", "red")) for entry in log: print(entry)
conditional_block
test_Browser_logs.py
from termcolor import colored def
(app): wd = app.wd sidebar = wd.find_element_by_xpath("//td[@id='sidebar']") sidebar.find_element_by_xpath(".//span[normalize-space(.)='Catalog']").click() wd.find_element_by_xpath("//i[@class='fa fa-folder']/../a").click() products_qty = len(wd.find_elements_by_xpath(("//input[contains(@name,'produ...
test_Browser_logs
identifier_name
test_Browser_logs.py
from termcolor import colored def test_Browser_logs(app):
wd = app.wd sidebar = wd.find_element_by_xpath("//td[@id='sidebar']") sidebar.find_element_by_xpath(".//span[normalize-space(.)='Catalog']").click() wd.find_element_by_xpath("//i[@class='fa fa-folder']/../a").click() products_qty = len(wd.find_elements_by_xpath(("//input[contains(@name,'products')]/../....
identifier_body
test_Browser_logs.py
from termcolor import colored def test_Browser_logs(app):
wd = app.wd sidebar = wd.find_element_by_xpath("//td[@id='sidebar']") sidebar.find_element_by_xpath(".//span[normalize-space(.)='Catalog']").click() wd.find_element_by_xpath("//i[@class='fa fa-folder']/../a").click() products_qty = len(wd.find_elements_by_xpath(("//input[contains(@name,'products')]/...
random_line_split
test_mon_network.py
import io import os import difflib import pytest from jinja2 import Template import testutils securedrop_test_vars = testutils.securedrop_test_vars testinfra_hosts = [securedrop_test_vars.monitor_hostname] @pytest.mark.skip_in_prod def test_mon_iptables_rules(host): local = host.get_host("local://") time_...
(host, ossec_service): """ Ensure the OSSEC-related services are listening on the expected sockets. Services to check include ossec-remoted and ossec-authd. Helper services such as postfix are checked separately. Note that the SSH check will fail if run against a prod host, due to the SSH-o...
test_listening_ports
identifier_name
test_mon_network.py
import io import os import difflib import pytest from jinja2 import Template import testutils securedrop_test_vars = testutils.securedrop_test_vars testinfra_hosts = [securedrop_test_vars.monitor_hostname] @pytest.mark.skip_in_prod def test_mon_iptables_rules(host): local = host.get_host("local://") time_...
# Conduct the string comparison of the expected and actual iptables # ruleset assert iptables_expected == iptables @pytest.mark.skip_in_prod @pytest.mark.parametrize('ossec_service', [ dict(host="0.0.0.0", proto="tcp", port=22, listening=True), dict(host="0.0.0.0", proto="udp", port=1...
print(iptablesdiff)
conditional_block
test_mon_network.py
import io import os import difflib import pytest from jinja2 import Template import testutils securedrop_test_vars = testutils.securedrop_test_vars testinfra_hosts = [securedrop_test_vars.monitor_hostname] @pytest.mark.skip_in_prod def test_mon_iptables_rules(host): local = host.get_host("local://") time_...
iptables = r"iptables-save | sed 's/ \[[0-9]*\:[0-9]*\]//g' | egrep -v '^#'" environment = os.environ.get("SECUREDROP_TESTINFRA_TARGET_HOST", "staging") iptables_file = "{}/iptables-mon-{}.j2".format( os.path.dirname(os.path.abspath(__file__)), environment) # template out a local iptabl...
if local.interface("eth0").exists: kwargs["ssh_ip"] = local.interface("eth0").addresses[0] # Build iptables scrape cmd, purge comments + counters
random_line_split
test_mon_network.py
import io import os import difflib import pytest from jinja2 import Template import testutils securedrop_test_vars = testutils.securedrop_test_vars testinfra_hosts = [securedrop_test_vars.monitor_hostname] @pytest.mark.skip_in_prod def test_mon_iptables_rules(host): local = host.get_host("local://") time_...
""" Ensure the OSSEC-related services are listening on the expected sockets. Services to check include ossec-remoted and ossec-authd. Helper services such as postfix are checked separately. Note that the SSH check will fail if run against a prod host, due to the SSH-over-Tor strategy. We can po...
identifier_body
typed_forms_spec.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */
import {dirname, join} from 'path'; import * as shx from 'shelljs'; import {Configuration, Linter} from 'tslint'; const anySymbolName = 'AnyForUntypedForms'; describe('Google3 typedForms TSLint rule', () => { const rulesDirectory = dirname(require.resolve('../../migrations/google3/typedFormsRule')); let tmpDir: ...
import {readFileSync, writeFileSync} from 'fs';
random_line_split
typed_forms_spec.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {readFileSync, writeFileSync} from 'fs'; import {dirname, join} from 'path'; import * as shx from 'shelljs'; i...
it('should migrate a complete example', () => { writeFile('/index.ts', ` import { Component } from '@angular/core'; import { AbstractControl, FormArray, FormBuilder, FormControl as FC, FormGroup } from '@angular/forms'; @Component({template: ''}) export class MyComponent { priva...
{ return readFileSync(join(tmpDir, fileName), 'utf8'); }
identifier_body
typed_forms_spec.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {readFileSync, writeFileSync} from 'fs'; import {dirname, join} from 'path'; import * as shx from 'shelljs'; i...
(fix: boolean) { const program = Linter.createProgram(join(tmpDir, 'tsconfig.json')); const linter = new Linter({fix, rulesDirectory: [rulesDirectory]}, program); const config = Configuration.parseConfigFile({rules: {'typedForms': true}}); program.getRootFileNames().forEach(fileName => { linter.l...
runTSLint
identifier_name
Pipeline.js
"use strict"; const {toPromise} = require("./promise"); const {interceptNode, registerGlobalInterceptor} = require("./interceptor"); // pipeline interceptor registerGlobalInterceptor(node => node instanceof Pipeline ? (payload => node.dispatch(payload)) : null); class Pipeline { constructor() { this.firstNode = n...
} get nodes() { const nodes = [].concat(this.eagerNodes, this.innerNodes, this.deferedNodes); if (this.firstNode != undefined) { nodes.unshift(this.firstNode); } if (this.lastNode != undefined) { nodes.push(this.lastNode); } return nodes; } report(errorHandler) { this.errorHandler = errorHa...
intercept(...interceptors) { this.interceptors = this.interceptors.concat(interceptors); return this;
random_line_split
Pipeline.js
"use strict"; const {toPromise} = require("./promise"); const {interceptNode, registerGlobalInterceptor} = require("./interceptor"); // pipeline interceptor registerGlobalInterceptor(node => node instanceof Pipeline ? (payload => node.dispatch(payload)) : null); class Pipeline { constructor() { this.firstNode = n...
defer(...nodes) { if (arguments.length === 0) { return [].concat(this.deferedNodes); } this.deferedNodes = this.deferedNodes.concat(nodes); return this; } intercept(...interceptors) { this.interceptors = this.interceptors.concat(interceptors); return this; } get nodes() { const nodes = [].con...
{ if (arguments.length === 0) { return [].concat(this.eagerNodes); } this.eagerNodes = this.eagerNodes.concat(nodes); return this; }
identifier_body
Pipeline.js
"use strict"; const {toPromise} = require("./promise"); const {interceptNode, registerGlobalInterceptor} = require("./interceptor"); // pipeline interceptor registerGlobalInterceptor(node => node instanceof Pipeline ? (payload => node.dispatch(payload)) : null); class Pipeline { constructor() { this.firstNode = n...
(...nodes) { if (arguments.length === 0) { return [].concat(this.innerNodes); } this.innerNodes = this.innerNodes.concat(nodes); return this; } eager(...nodes) { if (arguments.length === 0) { return [].concat(this.eagerNodes); } this.eagerNodes = this.eagerNodes.concat(nodes); return this; }...
through
identifier_name
Pipeline.js
"use strict"; const {toPromise} = require("./promise"); const {interceptNode, registerGlobalInterceptor} = require("./interceptor"); // pipeline interceptor registerGlobalInterceptor(node => node instanceof Pipeline ? (payload => node.dispatch(payload)) : null); class Pipeline { constructor() { this.firstNode = n...
} return response; } } // generator const createPipeline = () => new Pipeline(); module.exports = { Pipeline, createPipeline };
{ response = response.catch(callback); }
conditional_block
generateCategoriesForLuzzu.py
import rdflib from rdflib.plugin import register, Serializer, Parser from rdflib.namespace import DCTERMS, VOID, RDF, XSD from rdflib import Graph, Literal, BNode, Namespace, RDF, URIRef graph_dump = Graph() graph_dump.parse('observed_withCategories.ttl', format="turtle") graph = Graph() query = """SELECT * WHERE {...
graph.add((pld, URIRef(":hasDomain"), category)) if ("%s"%(row["cat"]).strip() in "user-generated content"): graph.add((pld, URIRef(":getFromLOV"), Literal(False, datatype=XSD.boolean))) elif("%s"%(row["cat"]).strip() in "cross domain"): graph.add((pld, URIRef(":getFromLOV"), Literal(False...
pld = URIRef("urn:"+row["source"])
conditional_block
generateCategoriesForLuzzu.py
import rdflib from rdflib.plugin import register, Serializer, Parser from rdflib.namespace import DCTERMS, VOID, RDF, XSD from rdflib import Graph, Literal, BNode, Namespace, RDF, URIRef graph_dump = Graph() graph_dump.parse('observed_withCategories.ttl', format="turtle") graph = Graph()
query = """SELECT * WHERE { ?x a <http://purl.org/obs#Dataset> . ?x <http://purl.org/obs#category> ?cat . OPTIONAL { ?x <http://purl.org/obs#payLevelDomain> ?pld . } ?x <http://purl.org/dc/terms/source> ?source . }""" for row in graph_dump.query(query): category = Literal(row["cat"], datatype=XS...
random_line_split
sanitycheck.py
# jhbuild - a build script for GNOME 1.x and 2.x # Copyright (C) 2001-2006 James Henstridge # # sanitycheck.py: check whether build environment is sane # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software F...
uprint(_('Could not find XML catalog')) else: for (item, name) in [('-//OASIS//DTD DocBook XML V4.1.2//EN', 'DocBook XML DTD V4.1.2'), ('http://docbook.sourceforge.net/release/xsl/current/html/chunk.xsl', ...
except CommandError, exc: uprint(str(exc)) # XML catalog sanity checks if not os.access('/etc/xml/catalog', os.R_OK):
random_line_split
sanitycheck.py
# jhbuild - a build script for GNOME 1.x and 2.x # Copyright (C) 2001-2006 James Henstridge # # sanitycheck.py: check whether build environment is sane # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software F...
(Command): doc = N_('Check that required support tools are available') name = 'sanitycheck' usage_args = '' def run(self, config, options, args, help=None): if args: raise UsageError(_('no extra arguments expected')) # check whether the checkout root and install prefix...
cmd_sanitycheck
identifier_name
sanitycheck.py
# jhbuild - a build script for GNOME 1.x and 2.x # Copyright (C) 2001-2006 James Henstridge # # sanitycheck.py: check whether build environment is sane # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software F...
def inpath(filename, path): for dir in path: if os.path.isfile(os.path.join(dir, filename)): return True # also check for filename.exe on Windows if sys.platform.startswith('win') and os.path.isfile(os.path.join(dir, filename + '.exe')): return True return False...
data = get_output(['aclocal', '--print-ac-dir']) path = [data[:-1]] env = os.environ.get('ACLOCAL_FLAGS', '').split() i = 0 while i < len(env): if env[i] == '-I': path.append(env[i+1]) i = i + 2 else: i = i + 1 return path
identifier_body
sanitycheck.py
# jhbuild - a build script for GNOME 1.x and 2.x # Copyright (C) 2001-2006 James Henstridge # # sanitycheck.py: check whether build environment is sane # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software F...
# check for flex/bison: if not inpath('flex', os.environ['PATH'].split(os.pathsep)): uprint(_('%s not found') % 'flex') if not inpath('bison', os.environ['PATH'].split(os.pathsep)): uprint(_('%s not found') % 'bison') if not inpath('xzcat', os.environ['PATH'].sp...
try: git_help = os.popen('git --help', 'r').read() if not 'clone' in git_help: uprint(_('Installed git program is not the right git')) else: if not check_version(['git', '--version'], r'git version (...
conditional_block
confirmation.component.ts
import { Component } from '@angular/core'; import { GooglemapService } from '../../services/googlemap/googlemap.service'; import { CheckoutComponent } from '../checkout/checkout.component'; import { CustomerService } from '../../services/customer/customer.service'; import {ProductService} from '../../services/product/p...
} print(): void { window.print(); } }
{ this._productService.getById(this.cart[i]).subscribe(posts => { this.posts.push(posts); this.total += posts.price; window.localStorage.setItem('total',String[this.total]); }); }
conditional_block
confirmation.component.ts
import { Component } from '@angular/core'; import { GooglemapService } from '../../services/googlemap/googlemap.service'; import { CheckoutComponent } from '../checkout/checkout.component'; import { CustomerService } from '../../services/customer/customer.service'; import {ProductService} from '../../services/product/p...
this.total += posts.price; window.localStorage.setItem('total',String[this.total]); }); } } print(): void { window.print(); } }
{ console.log(this.addressline1, this.city, this.state); console.log(window.sessionStorage.getItem('latestTransaction')); this._transactionService.getById(this.latestTransaction).subscribe(transaction => { this.fullname = transaction.transaction[0].shipping_name; this.addressline1=transaction.t...
identifier_body
confirmation.component.ts
import { Component } from '@angular/core'; import { GooglemapService } from '../../services/googlemap/googlemap.service'; import { CheckoutComponent } from '../checkout/checkout.component'; import { CustomerService } from '../../services/customer/customer.service'; import {ProductService} from '../../services/product/p...
this.state= transaction.transaction[0].shipping_state; this.link='https://www.google.com/maps/embed/v1/directions?origin=1+Washington+Sq+San+Jose+CA+USA&destination='+this.addressline1.replace(/\s+/g, '+')+'+'+this.city+'+'+this.state+'+USA&key=AIzaSyC8Y0-TP7HlFgSAyjPTIrgKqzL1_7Ro0qE'; console.log(thi...
this.city = transaction.transaction[0].shipping_city;
random_line_split
confirmation.component.ts
import { Component } from '@angular/core'; import { GooglemapService } from '../../services/googlemap/googlemap.service'; import { CheckoutComponent } from '../checkout/checkout.component'; import { CustomerService } from '../../services/customer/customer.service'; import {ProductService} from '../../services/product/p...
(private _mapService: GooglemapService, private _customerService: CustomerService, private _productService: ProductService, public sanitizer: DomSanitizer, private _transactionService: TransactionService) { console.log(this.addressline1, this.city, this.state); console.log(window.sessionStorage.getItem('latestT...
constructor
identifier_name
test_multipole.py
#!/usr/bin/env python import os import sys sys.path.insert(0, os.pardir) from testing_harness import TestHarness, PyAPITestHarness import openmc from openmc.stats import Box from openmc.source import Source class MultipoleTestHarness(PyAPITestHarness):
#################### c1 = openmc.Cell(cell_id=1, fill=moderator) mod_univ = openmc.Universe(universe_id=1, cells=(c1,)) r0 = openmc.ZCylinder(R=0.3) c11 = openmc.Cell(cell_id=11, fill=dense_fuel, region=-r0) c11.temperature = [500, 0, 700, 800] c12 = openmc.Cell...
def _build_inputs(self): #################### # Materials #################### moderator = openmc.Material(material_id=1) moderator.set_density('g/cc', 1.0) moderator.add_nuclide('H1', 2.0) moderator.add_nuclide('O16', 1.0) moderator.add_s_alpha_beta('c_H...
identifier_body
test_multipole.py
#!/usr/bin/env python import os import sys sys.path.insert(0, os.pardir) from testing_harness import TestHarness, PyAPITestHarness import openmc from openmc.stats import Box from openmc.source import Source class MultipoleTestHarness(PyAPITestHarness): def _build_inputs(self): #################### ...
(self): f = os.path.join(os.getcwd(), 'plots.xml') if os.path.exists(f): os.remove(f) super(MultipoleTestHarness, self)._cleanup() if __name__ == '__main__': harness = MultipoleTestHarness('statepoint.5.h5') harness.main()
_cleanup
identifier_name
test_multipole.py
#!/usr/bin/env python import os import sys sys.path.insert(0, os.pardir) from testing_harness import TestHarness, PyAPITestHarness import openmc from openmc.stats import Box from openmc.source import Source class MultipoleTestHarness(PyAPITestHarness): def _build_inputs(self): #################### ...
harness = MultipoleTestHarness('statepoint.5.h5') harness.main()
conditional_block
test_multipole.py
#!/usr/bin/env python import os import sys sys.path.insert(0, os.pardir) from testing_harness import TestHarness, PyAPITestHarness import openmc from openmc.stats import Box from openmc.source import Source class MultipoleTestHarness(PyAPITestHarness): def _build_inputs(self): #################### ...
super(MultipoleTestHarness, self)._cleanup() if __name__ == '__main__': harness = MultipoleTestHarness('statepoint.5.h5') harness.main()
f = os.path.join(os.getcwd(), 'plots.xml') if os.path.exists(f): os.remove(f)
random_line_split
hy-AM.js
(function (global, factory) { if (typeof define === "function" && define.amd) { define('element/locale/hy-AM', ['module', 'exports'], factory); } else if (typeof exports !== "undefined") { factory(module, exports); } else { var mod = { exports: {} }; factory(mod, mod.exports); global...
jun: 'Յուն', jul: 'Յուլ', aug: 'Օգ', sep: 'Սեպտ', oct: 'Յոկ', nov: 'Նոյ', dec: 'Դեկ' } }, select: { loading: 'Բեռնում', noMatch: 'Համապատասխան տուեալներ չկան', noData: 'Տվյալներ չկան', placeholder: ...
may: 'Մայ',
random_line_split
hy-AM.js
(function (global, factory) { if (typeof define === "function" && define.amd)
else if (typeof exports !== "undefined") { factory(module, exports); } else { var mod = { exports: {} }; factory(mod, mod.exports); global.ELEMENT.lang = global.ELEMENT.lang || {}; global.ELEMENT.lang.hyAM = mod.exports; } })(this, function (module, exports) { 'use strict'; expo...
{ define('element/locale/hy-AM', ['module', 'exports'], factory); }
conditional_block
bump_maven_version.py
#! /usr/bin/python # Script for increasing versions numbers across the code import sys import glob import re import argparse def check_version_format(version): """Check format of version number""" pattern = '^[0-9]+[\.][0-9]+[\.][0-9]+(\-.+)*$' return re.match(pattern, version) is not None BIO_FORMATS_...
(object): def __init__(self, old_group="ome", new_group="ome"): self.old_group = old_group self.new_group = new_group self.group_pattern = \ r"(<groupId>)%s(</groupId>)" % \ old_group self.artifact_pattern = BIO_FORMATS_ARTIFACT % old_group self.relea...
Replacer
identifier_name
bump_maven_version.py
#! /usr/bin/python # Script for increasing versions numbers across the code import sys import glob import re import argparse def check_version_format(version): """Check format of version number""" pattern = '^[0-9]+[\.][0-9]+[\.][0-9]+(\-.+)*$' return re.match(pattern, version) is not None BIO_FORMATS_...
output.write(new_content) output.close() infile.close() def bump_pom_versions(self, version): """Replace versions in pom.xml files""" # Replace versions in components pom.xml for pomfile in (glob.glob("*/*/pom.xml") + glob.glob("*/*/*/pom.xml")):...
def __init__(self, old_group="ome", new_group="ome"): self.old_group = old_group self.new_group = new_group self.group_pattern = \ r"(<groupId>)%s(</groupId>)" % \ old_group self.artifact_pattern = BIO_FORMATS_ARTIFACT % old_group self.release_version_patt...
identifier_body
bump_maven_version.py
#! /usr/bin/python # Script for increasing versions numbers across the code import sys import glob import re import argparse def check_version_format(version): """Check format of version number""" pattern = '^[0-9]+[\.][0-9]+[\.][0-9]+(\-.+)*$' return re.match(pattern, version) is not None BIO_FORMATS_...
replacer.bump_stable_version(ns.version)
conditional_block
bump_maven_version.py
#! /usr/bin/python # Script for increasing versions numbers across the code import sys import glob import re import argparse def check_version_format(version): """Check format of version number""" pattern = '^[0-9]+[\.][0-9]+[\.][0-9]+(\-.+)*$' return re.match(pattern, version) is not None BIO_FORMATS_...
self.upgradecheck, self.stableversion_pattern, version) if __name__ == "__main__": # Input check parser = argparse.ArgumentParser() parser.add_argument("--old-group", type=str, default="ome") parser.add_argument("--new-group", type=str, default="ome") parser.add_argument("version", typ...
self.replace_file(
random_line_split
group.py
#---------------------------------------------------------------------------- # Persistent element grouping support. # #---------------------------------------------------------------------------- # Copyright 2017, Martin Kolman # # This program is free software: you can redistribute it and/or modify # it under the ter...
def filter_messages(self, messages): for single_filter in self.members: messages = single_filter.filter_messages(messages) return list(messages) # make sure we return a list of messages
item_data) else: self._members.append(cls(self.db, item_data))
random_line_split
group.py
#---------------------------------------------------------------------------- # Persistent element grouping support. # #---------------------------------------------------------------------------- # Copyright 2017, Martin Kolman # # This program is free software: you can redistribute it and/or modify # it under the ter...
(cls, db): data = FilterGroupData(copy.deepcopy(cls.data_defaults)) return cls(db, data) def __init__(self, db, data): super(FilterGroup, self).__init__(db, data) with self._group_lock: self._load_members() def _load_members(self): for item_data in self.data...
new
identifier_name
group.py
#---------------------------------------------------------------------------- # Persistent element grouping support. # #---------------------------------------------------------------------------- # Copyright 2017, Martin Kolman # # This program is free software: you can redistribute it and/or modify # it under the ter...
class FilterGroupData(blitzdb.Document): pass class FilterGroup(Group): data_defaults = copy.deepcopy(Group.data_defaults) @classmethod def new(cls, db): data = FilterGroupData(copy.deepcopy(cls.data_defaults)) return cls(db, data) def __init__(self, db, data): super(...
return "%s containing %s" % (self.__class__.__name__, self.members)
identifier_body
group.py
#---------------------------------------------------------------------------- # Persistent element grouping support. # #---------------------------------------------------------------------------- # Copyright 2017, Martin Kolman # # This program is free software: you can redistribute it and/or modify # it under the ter...
else: self._members.append(cls(self.db, item_data)) def filter_messages(self, messages): for single_filter in self.members: messages = single_filter.filter_messages(messages) return list(messages) # make sure we return a list of messages
self.log.error("Filter class class not found for data: %s", item_data)
conditional_block
document_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Tracking of pending loads in a document. //! //! <https://html.spec.whatwg.org/multipage/#the-end> use crate...
// Associated fetches will be canceled when dropping the canceller. self.cancellers.clear(); canceled_any } /// Add a load to the list of blocking loads. fn add_blocking_load(&mut self, load: LoadType) { debug!( "Adding blocking load {:?} ({}).", load...
let canceled_any = !self.cancellers.is_empty();
random_line_split
document_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Tracking of pending loads in a document. //! //! <https://html.spec.whatwg.org/multipage/#the-end> use crate...
(&self) -> bool { // TODO: Ensure that we report blocked if parsing is still ongoing. !self.blocking_loads.is_empty() } pub fn is_only_blocked_by_iframes(&self) -> bool { self.blocking_loads.iter().all(|load| match *load { LoadType::Subframe(_) => true, _ => fals...
is_blocked
identifier_name
document_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Tracking of pending loads in a document. //! //! <https://html.spec.whatwg.org/multipage/#the-end> use crate...
} } #[derive(JSTraceable, MallocSizeOf)] pub struct DocumentLoader { resource_threads: ResourceThreads, blocking_loads: Vec<LoadType>, events_inhibited: bool, cancellers: Vec<FetchCanceller>, } impl DocumentLoader { pub fn new(existing: &DocumentLoader) -> DocumentLoader { DocumentLoa...
{ self.doc.finish_load(load); }
conditional_block
task-1.js
/* globals $ */ /* Create a function that takes an id or DOM element and: */ function solve(){ return function (selector) { var classBtn = document.querySelectorAll('.button'), classContent = document.querySelectorAll('.content'); if(selector == undefined){ throw new Error(); } if...
(){ var next = this.nextElementSibling; while(next.className !== 'button'){ if (next.className === 'content') { break; } next = next.nextElementSibling; } if (next.className === 'content' && next.style.display == '') { thi...
ShowHideFn
identifier_name
task-1.js
/* globals $ */ /* Create a function that takes an id or DOM element and: */ function solve()
if (next.className === 'content') { break; } next = next.nextElementSibling; } if (next.className === 'content' && next.style.display == '') { this.innerHTML = 'show'; next.style.display = "none"; } else { ...
{ return function (selector) { var classBtn = document.querySelectorAll('.button'), classContent = document.querySelectorAll('.content'); if(selector == undefined){ throw new Error(); } if(selector !== HTMLElement){ selector = document.getElementById(selector); } if(select...
identifier_body
task-1.js
/* globals $ */ /* Create a function that takes an id or DOM element and: */ function solve(){ return function (selector) { var classBtn = document.querySelectorAll('.button'), classContent = document.querySelectorAll('.content'); if(selector == undefined){ throw new Error(); } if...
} for(i = 0; i < len; i+=1) { classBtn[i].innerHTML = "hide"; classBtn[i].addEventListener('click', ShowHideFn, false); } }; } module.exports = solve;
{ this.innerHTML = "hide"; next.style.display = ''; }
conditional_block
task-1.js
/* globals $ */ /* Create a function that takes an id or DOM element and: */ function solve(){ return function (selector) { var classBtn = document.querySelectorAll('.button'), classContent = document.querySelectorAll('.content'); if(selector == undefined){ throw new Error(); } if...
if (next.className === 'content') { break; } next = next.nextElementSibling; } if (next.className === 'content' && next.style.display == '') { this.innerHTML = 'show'; next.style.display = "none"; } else { ...
while(next.className !== 'button'){
random_line_split
namespaces.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 std::hashmap::HashMap; use cssparser::*; use errors::log_css_error; pub struct NamespaceMap { default: Op...
url = Some(value); break }, _ => syntax_error!(), } } if iter.next().is_some() { syntax_error!() } match (prefix, url) { (Some(prefix), Some(url)) => { if namespaces.prefix_map.swap(prefix, url).is_some() { l...
{ let location = rule.location; macro_rules! syntax_error( () => {{ log_css_error(location, "Invalid @namespace rule"); return }}; ); if rule.block.is_some() { syntax_error!() } let mut prefix: Option<~str> = None; let mut url: Option<~str> = None; let...
identifier_body
namespaces.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 std::hashmap::HashMap; use cssparser::*; use errors::log_css_error; pub struct NamespaceMap { default: Op...
() -> NamespaceMap { NamespaceMap { default: None, prefix_map: HashMap::new() } } } pub fn parse_namespace_rule(rule: AtRule, namespaces: &mut NamespaceMap) { let location = rule.location; macro_rules! syntax_error( () => {{ log_css_error(location, "Invalid @namespace rule"); ...
new
identifier_name
namespaces.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 std::hashmap::HashMap; use cssparser::*; use errors::log_css_error; pub struct NamespaceMap { default: Op...
let mut prefix: Option<~str> = None; let mut url: Option<~str> = None; let mut iter = rule.prelude.move_skip_whitespace(); for component_value in iter { match component_value { Ident(value) => { if prefix.is_some() { syntax_error!() } prefix = Some(va...
{ syntax_error!() }
conditional_block
namespaces.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 std::hashmap::HashMap; use cssparser::*; use errors::log_css_error; pub struct NamespaceMap { default: Op...
let location = rule.location; macro_rules! syntax_error( () => {{ log_css_error(location, "Invalid @namespace rule"); return }}; ); if rule.block.is_some() { syntax_error!() } let mut prefix: Option<~str> = None; let mut url: Option<~str> = None; let m...
pub fn parse_namespace_rule(rule: AtRule, namespaces: &mut NamespaceMap) {
random_line_split
user.service.ts
import { Injectable } from '@angular/core'; import { Http, Headers } from '@angular/http'; import 'rxjs/add/operator/map'; import { environment } from '../../environments/environment'; import { AuthenticateService } from './authenticate.service'; @Injectable() export class
{ user: {email:String, role:String}; constructor( private http: Http, private authenticateService : AuthenticateService) { this.user = {email: null, role: null}; this.authenticateService.loadTokenAndData(); } getAllUsers() { let headers = new Headers(); headers.append('Content-Type',...
UserService
identifier_name
user.service.ts
import { Injectable } from '@angular/core'; import { Http, Headers } from '@angular/http'; import 'rxjs/add/operator/map'; import { environment } from '../../environments/environment';
user: {email:String, role:String}; constructor( private http: Http, private authenticateService : AuthenticateService) { this.user = {email: null, role: null}; this.authenticateService.loadTokenAndData(); } getAllUsers() { let headers = new Headers(); headers.append('Content-Type', '...
import { AuthenticateService } from './authenticate.service'; @Injectable() export class UserService{
random_line_split
user.service.ts
import { Injectable } from '@angular/core'; import { Http, Headers } from '@angular/http'; import 'rxjs/add/operator/map'; import { environment } from '../../environments/environment'; import { AuthenticateService } from './authenticate.service'; @Injectable() export class UserService{ user: {email:String, role:Str...
getUserCount() { let headers = new Headers(); headers.append('Content-Type', 'application/json'); return this.http.get(environment.baseUrl + '/api/users/count', {headers: headers}) .map(res => res.json()); } }
{ let headers = new Headers(); headers.append('Content-Type', 'application/json'); headers.append('x-access-token', this.authenticateService.token); return this.http.get(environment.baseUrl + '/api/users', {headers: headers}) .map(res => res.json()); }
identifier_body
browser_test_driver.py
# Copyright (C) 2014 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the ...
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERR...
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
random_line_split
browser_test_driver.py
# Copyright (C) 2014 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the ...
(self, pixel_tests, per_test_args, deadline): """Same as Driver.start() however, it has an extra step. It waits for a path to a file to be used for stdin to be printed by the browser test. If a path is found by the deadline test test will open the file and assign it to the stdin of the p...
start
identifier_name
browser_test_driver.py
# Copyright (C) 2014 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the ...
# Gets the path of the directory that the file for stdin communication is # in. Since the browser test cannot clean it up, the layout test framework # will. Everything the browser test uses is stored in the same directory as # the stdin file, so deleting that directory recursively will remove all the ...
"""Same as Driver.start() however, it has an extra step. It waits for a path to a file to be used for stdin to be printed by the browser test. If a path is found by the deadline test test will open the file and assign it to the stdin of the process that is owned by this driver's server p...
identifier_body
browser_test_driver.py
# Copyright (C) 2014 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the ...
super(BrowserTestDriver, self).stop(self._port.driver_stop_timeout())
self._server_process.write('QUIT')
conditional_block
speaker.py
import pygame import logging from tools.action import Action class Speaker(Action): def __init__(self, id, params): super(Speaker, self).__init__(id, params) try: self.path_to_audio = params["path_to_audio"] self.repetitions = int(params["repetitions"]) except ValueError as ve: # if repetitions can't be...
def cleanup(self): logging.debug("Speaker: No cleanup necessary at the moment")
if not self.corrupted: self.play_audio() else: logging.error("Speaker: Wasn't able to play sound because of an initialization error")
identifier_body