file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
list_and_dump.py
# Copyright 2015 Spotify AB # # 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 agreed to in writing, so...
(out_file): """ Connects to the ssh agent on localhost and requests a key listing, dumping what gets sent as a response to a file. Useful for constructing test data :param out_file: the filename to write to """ with open(out_file, "w") as f: s = socket.socket(socket.AF_UNIX) s...
list_keys_dump_raw_data
identifier_name
hash.py
''' Copyright (C) 2016-2019 Vanessa Sochat. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distribute...
if os.path.exists(file_obj): os.remove(file_obj) return hashes def get_image_hash(image_path, level=None, level_filter=None, include_files=None, skip_files=None, version=None, file_ob...
'''get_image_hashes returns the hash for an image across all levels. This is the quickest, easiest way to define a container's reproducibility on each level. ''' if levels is None: levels = get_levels(version=version) hashes = dict() # use a cached object for all file_obj, tar = get_ima...
identifier_body
hash.py
''' Copyright (C) 2016-2019 Vanessa Sochat. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distribute...
(image_path, version=None, levels=None): '''get_image_hashes returns the hash for an image across all levels. This is the quickest, easiest way to define a container's reproducibility on each level. ''' if levels is None: levels = get_levels(version=version) hashes = dict() # use a cach...
get_image_hashes
identifier_name
hash.py
''' Copyright (C) 2016-2019 Vanessa Sochat. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distribute...
try: file_obj.close() except: tar.close() if os.path.exists(file_obj): os.remove(file_obj) return hashes def get_image_hash(image_path, level=None, level_filter=None, include_files=None, skip_file...
hashes[level_name] = get_image_hash(image_path, level_filter=level_filter, file_obj=file_obj, tar=tar)
conditional_block
hash.py
''' Copyright (C) 2016-2019 Vanessa Sochat. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distribute...
the user can also provide a level_filter manually with level_filter (for custom levels) :param level: the level of reproducibility to use, which maps to a set regular expression to match particular files/folders in the image. Choices are in notes. :param skip_files: an optional list of files to skip ...
'''get_image_hash will generate a sha1 hash of an image, depending on a level of reproducibility specified by the user. (see function get_levels for descriptions)
random_line_split
actualSDN.py
OFPPortStatsReply, MAIN_DISPATCHER) def _port_stats_reply_handler(self, ev): body = ev.msg.body parser = ev.msg.datapath.ofproto_parser self.logger.info('datapath port ' 'rx-pkts rx-bytes ' 'tx-pkts tx-bytes bandwidth') ...
if self.host_enter == self.host_num: self.default_path_install(ev)
random_line_split
actualSDN.py
3 self.logger.info('%016x %8x %8d %8d %8d %8d %8d\n', ev.msg.datapath.id, stat.port_no, stat.rx_packets, stat.rx_bytes, stat.tx_packets, stat.tx_bytes, speed) self.bandwidth[index] = transfer_bytes def add_flow(self, datap...
if in_port != self.mac_to_port.get(dpid).get(src): #Delete the wrong flow self.ShortestPathDeleteFlow(datapath, src) #Update mac_to_port table for key, value in self.mac_to_port.items(): if value.has_key(src): ...
conditional_block
actualSDN.py
# self.path_db = [] # store shortest path # monitor init self.datapaths={} # all datapaths self.monitor_thread = hub.spawn(self._monitor) self.bandwidth = {} #networkx init self.topology_api_app = self self.directed_Topo = nx.DiGraph() ...
(self, ev): #Topo information of switch self.switch_enter += 1 #Get Switch List switch_list = get_switch(self.topology_api_app, None) self.switches = [switch.dp.id for switch in switch_list] self.switches_dp = [switch.dp for switch in switch_list] #Add switch dpid ...
get_topology_data
identifier_name
actualSDN.py
# self.path_db = [] # store shortest path # monitor init self.datapaths={} # all datapaths self.monitor_thread = hub.spawn(self._monitor) self.bandwidth = {} #networkx init self.topology_api_app = self self.directed_Topo = nx.DiGraph() ...
# the main function @
ofproto =datapath.ofproto parser = datapath.ofproto_parser pkt.serialize() data = pkt.data actions = [parser.OFPActionOutput(port=in_port)] out = parser.OFPPacketOut(datapath=datapath, buffer_id=ofproto.OFP_NO_BUFFER, ...
identifier_body
singleslnConfigFile.ts
import ma = require('azure-pipelines-task-lib/mock-answer'); import tmrm = require('azure-pipelines-task-lib/mock-run'); import path = require('path'); import util = require('./NugetMockHelper'); let taskPath = path.join(__dirname, '..', 'nugetinstaller.js'); let tmr: tmrm.TaskMockRunner = new tmrm.TaskMockRunner(task...
tmr.run();
nmh.registerToolRunnerMock();
random_line_split
base.rs
action_module: String, /// custom fields for the specific kind of codegenerator /// (recursive ascent, table-driven, etc) pub custom: C, pub repeatable: bool, } impl<'codegen, 'grammar, W: Write, C> CodeGenerator<'codegen, 'grammar, W, C> { pub fn new( grammar: &'grammar Grammar, ...
<F>(&mut self, body: F) -> io::Result<()> where F: FnOnce(&mut Self) -> io::Result<()>, { rust!(self.out, ""); rust!(self.out, "#[cfg_attr(rustfmt, rustfmt_skip)]"); rust!(self.out, "mod {}parse{} {{", self.prefix, self.start_symbol); // these stylistic lints are annoyin...
write_parse_mod
identifier_name
base.rs
need to carry generic parameters from /// the grammar, since the nonterminals may include generic /// parameters -- but we don't want them to carry *all* the /// generic parameters, since that can be unnecessarily /// restrictive. /// /// In particular, consider something like this: /// ...
{ // otherwise, convert one from the `IntoIterator` // supplied, using the `ToTriple` trait which inserts // errors/locations etc if none are given let clone_call = if self.repeatable { ".clone()" } else { "" }; rust!( self.out, ...
conditional_block
base.rs
action_module: String, /// custom fields for the specific kind of codegenerator /// (recursive ascent, table-driven, etc) pub custom: C, pub repeatable: bool, } impl<'codegen, 'grammar, W: Write, C> CodeGenerator<'codegen, 'grammar, W, C> { pub fn new( grammar: &'grammar Grammar, ...
{ rust!(self.out, ""); rust!(self.out, "#[cfg_attr(rustfmt, rustfmt_skip)]"); rust!(self.out, "mod {}parse{} {{", self.prefix, self.start_symbol); // these stylistic lints are annoying for the generated code, // which doesn't follow conventions: rust!( se...
random_line_split
base.rs
action_module: String, /// custom fields for the specific kind of codegenerator /// (recursive ascent, table-driven, etc) pub custom: C, pub repeatable: bool, } impl<'codegen, 'grammar, W: Write, C> CodeGenerator<'codegen, 'grammar, W, C> { pub fn new( grammar: &'grammar Grammar, ...
// **and** `'a` are referenced -- same with bounds like `T: // Foo<U>`. If those were needed, then `'a` or `U` would also // have to appear in the types. debug!("filtered_type_params = {:?}", filtered_type_params); let filtered_where_clauses: Vec<_> = grammar .where_c...
{ let referenced_ty_params: Set<_> = tys .into_iter() .flat_map(|t| t.free_variables(&grammar.type_parameters)) .collect(); let filtered_type_params: Vec<_> = grammar .type_parameters .iter() .filter(|t| referenced_ty_params.contai...
identifier_body
mindbreaker.ts
<!DOCTYPE TS><TS> <context> <name>MindBreaker</name> <message> <source>New Game</source> <translation>Новая игра</translation> </message> <message>
<translation>Быки и коровы</translation> </message> </context> <context> <name>MindBreakerBoard</name> <message> <source>Reset Statistics</source> <translation>Сбросить статистику</translation> </message> <message> <source>Reset the win ratio?</source> <transl...
<source>win avg: %1 turns (%2 games)</source> <translation>средний выигыш: %1 ходов (%2 игр)</translation> </message> <message> <source>Mind Breaker</source>
random_line_split
gtfs-update.js
var http = require("http"); var path = require('path'); var fs = require('fs'); var mkdirp = require('mkdirp'); var pg = require('pg'); var exec = require('child_process').exec; var sh = require("execSync") var util = require('util'); var info = {"good_load":0,"bad_load":0,"no_data":0}; var password="transit"; var op...
http_res.on("end", function () { parseAgencies(JSON.parse(data).data); }); }) .on('error', function(e) { console.log(e); console.log("Got error: " + e); }); var parseAgencies = function(agencyList){ var validAgencyCount = 0; var conString = "postgres://postgres:"+password+"@localhost:...
random_line_split
gtfs-update.js
var http = require("http"); var path = require('path'); var fs = require('fs'); var mkdirp = require('mkdirp'); var pg = require('pg'); var exec = require('child_process').exec; var sh = require("execSync") var util = require('util'); var info = {"good_load":0,"bad_load":0,"no_data":0}; var password="transit"; var op...
}else{ //client.query('DROP SCHEMA "'+schemaName+'"'); //console.log(schemaName+": No Rows"); info.bad_load++; //gtfsdbLoad(schemaName,destinationStream) } //console.log(util.inspect(info,false,null)); }) } var parseAgent = function(agent,a...
{ //client.query('DROP SCHEMA "'+schemaName+'"'); //console.log(schemaName+": No Geometry"); info.bad_load++; //gtfsdbLoad(schemaName,destinationStream) }
conditional_block
eventlet_backdoor.py
# Copyright (c) 2012 OpenStack Foundation. # Administrator of the National Aeronautics and Space Administration. # 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 a...
import pprint import socket import sys import traceback import eventlet.backdoor import greenlet from oslo_config import cfg from neutron.openstack.common._i18n import _LI help_for_backdoor_port = ( "Acceptable values are 0, <port>, and <start>:<end>, where 0 results " "in listening on a random tcp port numb...
import gc import logging import os
random_line_split
eventlet_backdoor.py
# Copyright (c) 2012 OpenStack Foundation. # Administrator of the National Aeronautics and Space Administration. # 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 a...
(val): if val is not None: pprint.pprint(val) sys.displayhook = displayhook sock = _listen('localhost', start_port, end_port, eventlet.listen) # In the case of backdoor port being zero, a port number is assigned by # listen(). In any case, pull the port number out here. port =...
displayhook
identifier_name
eventlet_backdoor.py
# Copyright (c) 2012 OpenStack Foundation. # Administrator of the National Aeronautics and Space Administration. # 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 a...
def initialize_if_enabled(): backdoor_locals = { 'exit': _dont_use_this, # So we don't exit the entire process 'quit': _dont_use_this, # So we don't exit the entire process 'fo': _find_objects, 'pgt': _print_greenthreads, 'pnt': _print_nativethreads, } i...
try_port = start_port while True: try: return listen_func((host, try_port)) except socket.error as exc: if (exc.errno != errno.EADDRINUSE or try_port >= end_port): raise try_port += 1
identifier_body
eventlet_backdoor.py
# Copyright (c) 2012 OpenStack Foundation. # Administrator of the National Aeronautics and Space Administration. # 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 a...
else: start, end = port_range.split(':', 1) try: start, end = int(start), int(end) if end < start: raise ValueError return start, end except ValueError as ex: raise EventletBackdoorConfigValueError(port_range, ex, ...
start, end = port_range, port_range
conditional_block
index.d.ts
// Type definitions for auth0-lock 10.9 // Project: http://auth0.com // Definitions by: Brian Caruso <https://github.com/carusology> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// <reference types="auth0-js/v7" /> interface Auth0LockAdditionalSignUpFieldOption { value: string; label: strin...
socialButtonStyle?: "big" | "small"; theme?: Auth0LockThemeOptions; usernameStyle?: string; } interface Auth0LockFlashMessageOptions { type: "success" | "error"; text: string; } interface Auth0LockShowOptions { allowedConnections?: string[]; allowForgotPassword?: boolean; allowLogin?: ...
prefill?: { email?: string, username?: string}; rememberLastLogin?: boolean; signupLink?: string;
random_line_split
controller_rendering.js
Ember.TEMPLATES["unit-controllers"] = Ember.Handlebars.compile( '<div class="unit-controllers">{{render "rendered" someModel className="asd"}}</div>' ); //-------------------------------------------------------------------------- module("templates - controllers - full environment", { setup: function() { var c...
}); } }); test("template renders correctly", function() { equal(Ember.$("#qunit-fixture .unit-controllers").text(), "controller stub"); });
view.appendTo("#qunit-fixture");
random_line_split
bluetoothremotegattserver.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 dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding; use dom::bindings::codegen::Bindings::Blue...
Root::from_ref(self) } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-disconnect fn Disconnect(&self) { self.connected.set(false); } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-getprimaryservice fn GetPrima...
{ self.connected.set(true); }
conditional_block
bluetoothremotegattserver.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 dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding; use dom::bindings::codegen::Bindings::Blue...
(&self) -> Root<BluetoothDevice> { self.device.get() } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-connected fn Connected(&self) -> bool { self.connected.get() } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-co...
Device
identifier_name
bluetoothremotegattserver.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 dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding; use dom::bindings::codegen::Bindings::Blue...
} // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-connected fn Connected(&self) -> bool { self.connected.get() } // https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-connect fn Connect(&self) -> Root<BluetoothRemoteGATTServer...
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattserver-device fn Device(&self) -> Root<BluetoothDevice> { self.device.get()
random_line_split
bluetoothremotegattserver.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 dom::bindings::codegen::Bindings::BluetoothRemoteGATTServerBinding; use dom::bindings::codegen::Bindings::Blue...
}
{ //UNIMPLEMENTED None }
identifier_body
test_case.py
def mock_now(test, now, seconds): """Mocks utcnow() and ndb properties. In particular handles when auto_now and auto_now_add are used. """ now = now + datetime.timedelta(seconds=seconds) test.mock(utils, 'utcnow', lambda: now) test.mock(ndb.DateTimeProperty, '_now', lambda _: now) test.mock(ndb.DateProp...
from depot_tools import auto_stub # W0212: Access to a protected member XXX of a client class # pylint: disable=W0212
random_line_split
test_case.py
now) test.mock(ndb.DateTimeProperty, '_now', lambda _: now) test.mock(ndb.DateProperty, '_now', lambda _: now.date()) return now class TestCase(auto_stub.TestCase): """Support class to enable more unit testing in GAE. Adds support for: - google.appengine.api.mail.send_mail_to_admins(). - Running t...
(self, task, **kwargs): # Not 100% sure why the Content-Length hack is needed, nor why the # stub returns unicode values that break webtest's assertions. body = base64.b64decode(task['body']) headers = {k: str(v) for k, v in task['headers']} headers['Content-Length'] = str(len(body)) try: ...
_post_task
identifier_name
test_case.py
now) test.mock(ndb.DateTimeProperty, '_now', lambda _: now) test.mock(ndb.DateProperty, '_now', lambda _: now.date()) return now class TestCase(auto_stub.TestCase): """Support class to enable more unit testing in GAE. Adds support for: - google.appengine.api.mail.send_mail_to_admins(). - Running t...
def _SendToAdmins(self, request, *args, **kwargs): """Make sure the request is logged. See google_appengine/google/appengine/api/mail_stub.py around line 299, MailServiceStub._SendToAdmins(). """ self.mail_stub._CacheMessage(request) return self.old_send_to_admins(request, *args, **kwargs) ...
self.mock(utils, "milliseconds_since_epoch", lambda: milliseconds)
identifier_body
test_case.py
now) test.mock(ndb.DateTimeProperty, '_now', lambda _: now) test.mock(ndb.DateProperty, '_now', lambda _: now.date()) return now class TestCase(auto_stub.TestCase): """Support class to enable more unit testing in GAE. Adds support for: - google.appengine.api.mail.send_mail_to_admins(). - Running t...
if base64.b64decode(t['body']) != payload: continue return t return None class Endpoints(object): """Handles endpoints API calls.""" def __init__(self, api_service_cls, regex=None, source_ip='127.0.0.1'): super(Endpoints, self).__init__() self._api_service_cls = api_service_cls ...
continue
conditional_block
ex6.py
#Pizza please import pyaudiogame from pyaudiogame import storage spk = pyaudiogame.speak MyApp = pyaudiogame.App("Pizza Please") storage.screen = ["start"] storage.toppings = ["cheese", "olives", "mushrooms", "Pepperoni", "french fries"] storage.your_toppings = ["cheese"] storage.did_run = False def is_number(number,...
(key): """Removes toppings from the pizza""" number = is_number(key, storage.your_toppings) if number or number == 0: t = storage.your_toppings.pop(number) if t == "cheese": spk("You can't remove cheese, what are you, Italian?") storage.your_toppings.insert(0, "cheese") else: spk("You removed %s from ...
remove_topping
identifier_name
ex6.py
#Pizza please import pyaudiogame from pyaudiogame import storage spk = pyaudiogame.speak MyApp = pyaudiogame.App("Pizza Please") storage.screen = ["start"] storage.toppings = ["cheese", "olives", "mushrooms", "Pepperoni", "french fries"] storage.your_toppings = ["cheese"] storage.did_run = False def is_number(number,...
elif key == "space": spk("You sit down to enjoy a yummy pizza. You eat... eat... eat... eat... and are finally done. That was good! Now it's time for another!") storage.your_toppings = ['cheese'] storage.did_run = False elif storage.screen[0] == "start": spk("Welcom to pizza madness! Here you can build your ...
spk("Press a number to add a topping to your pizza. Press d to remove a topping you don't like") storage.screen[0] = "add" storage.did_run = False
conditional_block
ex6.py
#Pizza please import pyaudiogame from pyaudiogame import storage spk = pyaudiogame.speak MyApp = pyaudiogame.App("Pizza Please") storage.screen = ["start"] storage.toppings = ["cheese", "olives", "mushrooms", "Pepperoni", "french fries"] storage.your_toppings = ["cheese"] storage.did_run = False def is_number(number,...
def logic(actions): """Press a and d to switch from adding and removing toppings, press 0-9 to deal with the toppings and press space to eat the pizza""" key = actions['key'] if key == "d": spk("Press a number to remove a topping from your pizza, press a to add toppings again") storage.screen[0] = "remove" st...
storage.your_toppings.insert(0, "cheese") else: spk("You removed %s from your pizza. Now your pizza has %s on top" % (t, storage.your_toppings))
random_line_split
ex6.py
#Pizza please import pyaudiogame from pyaudiogame import storage spk = pyaudiogame.speak MyApp = pyaudiogame.App("Pizza Please") storage.screen = ["start"] storage.toppings = ["cheese", "olives", "mushrooms", "Pepperoni", "french fries"] storage.your_toppings = ["cheese"] storage.did_run = False def is_number(number,...
def remove_topping(key): """Removes toppings from the pizza""" number = is_number(key, storage.your_toppings) if number or number == 0: t = storage.your_toppings.pop(number) if t == "cheese": spk("You can't remove cheese, what are you, Italian?") storage.your_toppings.insert(0, "cheese") else: spk("...
"""Will add a topping to your pizza""" number = is_number(key, storage.toppings) if number or number == 0: storage.your_toppings.append(storage.toppings[number]) spk("You added %s to your pizza. Your pizza currently has %s on top" % (storage.toppings[number], storage.your_toppings))
identifier_body
fabricGlobals.ts
/// <reference path="../../baseIncludes.ts"/> module Fabric { export var log:Logging.Logger = Logger.get("Fabric"); export var jmxDomain = 'io.fabric8'; export var managerMBean = Fabric.jmxDomain + ":type=Fabric"; export var clusterManagerMBean = Fabric.jmxDomain + ":type=ClusterServiceManager"; export var ...
export var DEFAULT_REST_API = "/api/fabric8"; }
export var currentContainerId = ''; export var currentContainer = {};
random_line_split
generate.py
import resume.models as rmod import random import logging from django.http import HttpResponse from datetime import date logger = logging.getLogger('default') def generate(request): cs_objs = rmod.Department.objects.filter(shortname='cs') if len(cs_objs) == 0: logger.info('created cs dept') cs = rmod.Depa...
c_objs = rmod.Component.objects.filter(applicant=a) if len(c_objs) == 0: logger.info('created component') c = rmod.Component(applicant=a, type=ct, value='component 1', lastSubmitted=0,\ department=cs) c.save() else: logger.info('used existing component') c = c_objs[0] reviewer_objs =...
else: logger.info('used existing applicant') a = a_objs[0]
random_line_split
generate.py
import resume.models as rmod import random import logging from django.http import HttpResponse from datetime import date logger = logging.getLogger('default') def generate(request):
ct_objs = rmod.ComponentType.objects.filter(short='stmt') if len(ct_objs) == 0: logger.info('created component type') ct = rmod.ComponentType(type='statement', name='Research Statement', short='stmt', department=cs) ct.save() else: logger.info('used existing component type') ct = ct_objs[0] ...
cs_objs = rmod.Department.objects.filter(shortname='cs') if len(cs_objs) == 0: logger.info('created cs dept') cs = rmod.Department(name='Computer Science', shortname='cs', lastChange=0,\ headerImage='', logoImage='', resumeImage='', headerBgImage='',\ brandColor='blue', contactName='Donald Knuth',...
identifier_body
generate.py
import resume.models as rmod import random import logging from django.http import HttpResponse from datetime import date logger = logging.getLogger('default') def
(request): cs_objs = rmod.Department.objects.filter(shortname='cs') if len(cs_objs) == 0: logger.info('created cs dept') cs = rmod.Department(name='Computer Science', shortname='cs', lastChange=0,\ headerImage='', logoImage='', resumeImage='', headerBgImage='',\ brandColor='blue', contactName='D...
generate
identifier_name
generate.py
import resume.models as rmod import random import logging from django.http import HttpResponse from datetime import date logger = logging.getLogger('default') def generate(request): cs_objs = rmod.Department.objects.filter(shortname='cs') if len(cs_objs) == 0: logger.info('created cs dept') cs = rmod.Depa...
auth_objs = rmod.AuthInfo.objects.all() if len(auth_objs) == 0: return HttpResponse("No auth_info objects to use") auth = auth_objs[0] pos_objs = rmod.ApplicantPosition.objects.filter(name='pos1') if len(pos_objs) == 0: logger.info('created app position') pos = rmod.ApplicantPosition(department...
logger.info('used existing component type') ct = ct_objs[0]
conditional_block
Install.py
# Install.py -- File system installation commands # Copyright (C) 2007-2013 CEA # # This file is part of shine # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License...
(Command): """ shine install -m /path/to/model.lmf """ NAME = "install" DESCRIPTION = "Install a new file system." def execute(self): # Option sanity check self.forbidden(self.options.fsnames, "-f, see -m") self.forbidden(self.options.labels, "-l") self.forbidd...
Install
identifier_name
Install.py
# Install.py -- File system installation commands # Copyright (C) 2007-2013 CEA # # This file is part of shine # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License...
else: rc = self.register_fs(fs_conf) if rc: msg = "Error: failed to register FS to backend (rc=%d)" % rc print(msg, file=sys.stderr) else: print("Filesystem %s registered." % fs.fs_name) # Helper message. # If user specified nodes...
rc = 0
conditional_block
Install.py
# Install.py -- File system installation commands # Copyright (C) 2007-2013 CEA # # This file is part of shine # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License...
eh = FSGlobalEventHandler(self) # Use this Shine.FSUtils convenience function. lmf = self.get_lmf_path() if lmf: print("Using Lustre model file %s" % lmf) else: raise CommandHelpException("Lustre model file for ``%s'' not found:" ...
""" shine install -m /path/to/model.lmf """ NAME = "install" DESCRIPTION = "Install a new file system." def execute(self): # Option sanity check self.forbidden(self.options.fsnames, "-f, see -m") self.forbidden(self.options.labels, "-l") self.forbidden(self.options...
identifier_body
Install.py
# Install.py -- File system installation commands # Copyright (C) 2007-2013 CEA # # This file is part of shine # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License...
# # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # from __future__ import print_function import sys from Shine.Configuration.Globals import Globals from Sh...
# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details.
random_line_split
AnimatedNode.js
import ReanimatedModule from '../../ReanimatedModule'; import { Platform } from 'react-native'; const UPDATED_NODES = []; let loopID = 1; let propUpdatesEnqueued = null; let nodeCount = 0; let callID = ''; export function getCallID() { return callID; } export function setCallID(nextCallID) { callID = nextCallID...
__addChild(child) { if (this.__children.length === 0) { this.__attach(); } this.__children.push(child); child.__nativeInitialize(); if (ReanimatedModule.connectNodes) { ReanimatedModule.connectNodes(this.__nodeID, child.__nodeID); } else { child.__dangerouslyRescheduleEval...
{ return this.__children; }
identifier_body
AnimatedNode.js
import ReanimatedModule from '../../ReanimatedModule'; import { Platform } from 'react-native'; const UPDATED_NODES = []; let loopID = 1; let propUpdatesEnqueued = null; let nodeCount = 0; let callID = ''; export function getCallID() { return callID; } export function setCallID(nextCallID) { callID = nextCallID...
nodes[i].__removeChild(this); } } this.__nativeTearDown(); } __getValue() { if (!(callID in this.__lastLoopID) || this.__lastLoopID[callID] < loopID) { this.__lastLoopID[callID] = loopID; const result = this.__onEvaluate(); this.__memoizedValue[callID] = result; r...
if (nodes) { for (let i = 0, l = nodes.length; i < l; i++) {
random_line_split
AnimatedNode.js
import ReanimatedModule from '../../ReanimatedModule'; import { Platform } from 'react-native'; const UPDATED_NODES = []; let loopID = 1; let propUpdatesEnqueued = null; let nodeCount = 0; let callID = ''; export function getCallID() { return callID; } export function setCallID(nextCallID) { callID = nextCallID...
() { if (!this.__initialized) { ReanimatedModule.createNode(this.__nodeID, { ...this.__nodeConfig }); this.__initialized = true; } } __nativeTearDown() { if (this.__initialized) { ReanimatedModule.dropNode(this.__nodeID); this.__initialized = false; } } isNativelyInitia...
__nativeInitialize
identifier_name
AnimatedNode.js
import ReanimatedModule from '../../ReanimatedModule'; import { Platform } from 'react-native'; const UPDATED_NODES = []; let loopID = 1; let propUpdatesEnqueued = null; let nodeCount = 0; let callID = ''; export function getCallID() { return callID; } export function setCallID(nextCallID) { callID = nextCallID...
if (ReanimatedModule.disconnectNodes) { ReanimatedModule.disconnectNodes(this.__nodeID, child.__nodeID); } this.__children.splice(index, 1); if (this.__children.length === 0) { this.__detach(); } } _connectAnimatedView(nativeViewTag) { if (ReanimatedModule.connectNodeToView) ...
{ console.warn("Trying to remove a child that doesn't exist"); return; }
conditional_block
node.service.ts
import { Injectable, NgZone } from '@angular/core'; import { Observable, Observer } from "rxjs"; import { ICmdOutput } from "../interfaces"; const electron = window['require']('electron'); const spawn = window['require']("child_process").spawn; const path = window['require']("path"); const fs = window['require']('fs')...
appendToFile(filepath: string, content: string) { fs.appendFileSync(filepath, content); } }
{ this.saveFile(filepath, JSON.stringify(content, null, 2)); }
identifier_body
node.service.ts
import { Injectable, NgZone } from '@angular/core'; import { Observable, Observer } from "rxjs"; import { ICmdOutput } from "../interfaces"; const electron = window['require']('electron'); const spawn = window['require']("child_process").spawn; const path = window['require']("path"); const fs = window['require']('fs')...
saveFile(filepath: string, content: string) { fs.writeFileSync(filepath, content); } saveJsonFile(filepath: string, content: any) { this.saveFile(filepath, JSON.stringify(content, null, 2)); } appendToFile(filepath: string, content: string) { fs.appendFileSync(filepath, content); } }
readJSONFile(filepath: string): string { return JSON.parse(this.readFile(filepath)); }
random_line_split
node.service.ts
import { Injectable, NgZone } from '@angular/core'; import { Observable, Observer } from "rxjs"; import { ICmdOutput } from "../interfaces"; const electron = window['require']('electron'); const spawn = window['require']("child_process").spawn; const path = window['require']("path"); const fs = window['require']('fs')...
(filepath: string): string { return fs.readFileSync(filepath, 'utf-8'); } readJSONFile(filepath: string): string { return JSON.parse(this.readFile(filepath)); } saveFile(filepath: string, content: string) { fs.writeFileSync(filepath, content); } saveJsonFile(filepath: string, content: any) { ...
readFile
identifier_name
arrayPacket.ts
import { PacketBase } from './packetBase'; import { PacketType } from './packetType'; import { ArrayStruct } from './arrayElement'; import { BufferHelper } from '../bufferHelper'; export class ArrayPacket extends PacketBase { private _tokenName: string; private _data: ArrayStruct; constructor(tokenName: s...
(): Buffer { const buf = Buffer.allocUnsafe(this.size); let offset = buf.writeUInt8(PacketType.array, 0); offset = BufferHelper.writeAsciiString(buf, offset, this._tokenName); const bytes = this._data.getBytes(); bytes.copy(buf, offset); return buf; } }
bytes
identifier_name
arrayPacket.ts
import { PacketBase } from './packetBase'; import { PacketType } from './packetType'; import { ArrayStruct } from './arrayElement'; import { BufferHelper } from '../bufferHelper'; export class ArrayPacket extends PacketBase {
constructor(tokenName: string, data: ArrayStruct) { super(); this._tokenName = tokenName; this._data = data; } get size(): number { return 1//packet type byte + Buffer.byteLength(this._tokenName) + 1//class name + 0-terminator + this._data.size; ...
private _tokenName: string; private _data: ArrayStruct;
random_line_split
arrayPacket.ts
import { PacketBase } from './packetBase'; import { PacketType } from './packetType'; import { ArrayStruct } from './arrayElement'; import { BufferHelper } from '../bufferHelper'; export class ArrayPacket extends PacketBase { private _tokenName: string; private _data: ArrayStruct; constructor(tokenName: s...
bytes(): Buffer { const buf = Buffer.allocUnsafe(this.size); let offset = buf.writeUInt8(PacketType.array, 0); offset = BufferHelper.writeAsciiString(buf, offset, this._tokenName); const bytes = this._data.getBytes(); bytes.copy(buf, offset); return buf; } }
{ return 1//packet type byte + Buffer.byteLength(this._tokenName) + 1//class name + 0-terminator + this._data.size; }
identifier_body
test_tf_nn_moments.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Author: violinsolo # Created on 08/03/2018 import tensorflow as tf import numpy as np x_shape = [5, 3, 3, 2] x = np.arange(reduce(lambda t, s: t*s, list(x_shape), 1))
print x x = x.reshape([5, 3, 3, -1]) print x.shape X = tf.Variable(x) with tf.Session() as sess: m = tf.nn.moments(X, axes=[0]) # m = tf.nn.moments(X, axes=[0,1]) # m = tf.nn.moments(X, axes=np.arange(len(x_shape)-1)) mean, variance = m print(sess.run(m, feed_dict={X: x})) # print(sess.ru...
random_line_split
slice-panic-1.rs
// Copyright 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-MIT or ...
() { let x: &[_] = &[Foo, Foo]; x[3..4]; } fn main() { let _ = task::try(proc() foo()); unsafe { assert!(DTOR_COUNT == 2); } }
foo
identifier_name
slice-panic-1.rs
// Copyright 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-MIT or ...
unsafe { assert!(DTOR_COUNT == 2); } }
random_line_split
slice-panic-1.rs
// Copyright 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-MIT or ...
{ let _ = task::try(proc() foo()); unsafe { assert!(DTOR_COUNT == 2); } }
identifier_body
asha-workers-details.service_20170217014428.ts
import { Injectable } from '@angular/core'; import { Headers, Http } from '@angular/http';
import { AshaWorkersList, DummyAshaWorkerDetails } from './temporary/temp-data'; @Injectable() export class AshaWorkersDetailsService{ private url: string = "http://www.ashavizianagaram.in:81/ashaservices/webapi/getdetails/get_asha_worker_details"; constructor(private http: Http){} getAshaWorkersList()...
import 'rxjs/add/operator/toPromise'; import { AshaWorkerBasicDetailsModel } from '../model/asha-worker-basic-details-model';
random_line_split
asha-workers-details.service_20170217014428.ts
import { Injectable } from '@angular/core'; import { Headers, Http } from '@angular/http'; import 'rxjs/add/operator/toPromise'; import { AshaWorkerBasicDetailsModel } from '../model/asha-worker-basic-details-model'; import { AshaWorkersList, DummyAshaWorkerDetails } from './temporary/temp-data'; @Injectable() expo...
private handleError(error: any):Promise<any>{ console.error('An error occured', error); return Promise.reject(error.message || error); } }
{ return Promise.resolve(DummyAshaWorkerDetails); }
identifier_body
asha-workers-details.service_20170217014428.ts
import { Injectable } from '@angular/core'; import { Headers, Http } from '@angular/http'; import 'rxjs/add/operator/toPromise'; import { AshaWorkerBasicDetailsModel } from '../model/asha-worker-basic-details-model'; import { AshaWorkersList, DummyAshaWorkerDetails } from './temporary/temp-data'; @Injectable() expo...
(private http: Http){} getAshaWorkersList(): Promise<AshaWorkerBasicDetailsModel[]>{ //return Promise.resolve(AshaWorkersList); return this.http.get(this.url) .toPromise() .then(response => response.json().awAshaDetailsModel as ) ...
constructor
identifier_name
ember-chart.js
// Idea and initial code from https://github.com/aomra015/ember-cli-chart import Ember from 'ember'; export default Ember.Component.extend({ tagName: 'canvas', attributeBindings: ['width', 'height'], onlyValues: false, chartData: {}, didInsertElement: function(){ var context = this.get('element').getCo...
while (chart.scale.xLabels.length && chart.scale.xLabels[0] !== this.get("chartData.labels")[0]) { chart.removeData(); } this.get("chartData.labels").forEach((label, i) => { if (i < chart.scale.xLabels.length) { this.get("chartData.datasets").forEach((ds, j) => { if (this.get...
var chart = this.get("chart");
random_line_split
ember-chart.js
// Idea and initial code from https://github.com/aomra015/ember-cli-chart import Ember from 'ember'; export default Ember.Component.extend({ tagName: 'canvas', attributeBindings: ['width', 'height'], onlyValues: false, chartData: {}, didInsertElement: function(){ var context = this.get('element').getCo...
else { var base = { max: "203,46,255", up: "46,255,203", avg: "46,203,255", min: "46,98,255", sum: "98,56,255", }[label] || "151,187,205"; return { fillColor: "rgba(" + base + ",0.03)", strokeColor: "rgba(" + base + ",0.5)", pointColor: ...
{ return { fillColor: "rgba(151,187,205,1)", strokeColor: "rgba(151,187,205,1)" }; }
conditional_block
bench.py
# -*- coding: utf-8 -*- import pack_command import pack_command_python import timeit import cProfile import pstats import pycallgraph def format_time(seconds): v = seconds if v * 1000 * 1000 * 1000 < 1000: scale = u'ns' v = int(round(v*1000*1000*1000)) elif v * 1000 * 1000 < 1000: ...
if profile: pr.disable() ps = pstats.Stats(pr) sort_by = 'cumulative' ps.strip_dirs().sort_stats(sort_by).print_stats(20)
runit() if graph: pycallgraph.make_dot_graph('example.png')
random_line_split
bench.py
# -*- coding: utf-8 -*- import pack_command import pack_command_python import timeit import cProfile import pstats import pycallgraph def format_time(seconds): v = seconds if v * 1000 * 1000 * 1000 < 1000: scale = u'ns' v = int(round(v*1000*1000*1000)) elif v * 1000 * 1000 < 1000: ...
elif v * 1000 < 1000: scale = u'ms' v = round(v*1000, 4) else: scale = u'sec' v = int(v) return u'{} {}'.format(v, scale) # profiler size number = 100000 sample = 7 # profiler type profile = False graph = False timer = True def runit(): pack_command.pack_command("ZADD...
scale = u'μs' v = int(round(v*1000*1000))
conditional_block
bench.py
# -*- coding: utf-8 -*- import pack_command import pack_command_python import timeit import cProfile import pstats import pycallgraph def
(seconds): v = seconds if v * 1000 * 1000 * 1000 < 1000: scale = u'ns' v = int(round(v*1000*1000*1000)) elif v * 1000 * 1000 < 1000: scale = u'μs' v = int(round(v*1000*1000)) elif v * 1000 < 1000: scale = u'ms' v = round(v*1000, 4) else: scale...
format_time
identifier_name
bench.py
# -*- coding: utf-8 -*- import pack_command import pack_command_python import timeit import cProfile import pstats import pycallgraph def format_time(seconds):
# profiler size number = 100000 sample = 7 # profiler type profile = False graph = False timer = True def runit(): pack_command.pack_command("ZADD", "foo", 1369198341, 10000) def runitp(): pack_command_python.pack_command("ZADD", "foo", 1369198341, 10000) if profile: pr = cProfile.Profile() pr.enab...
v = seconds if v * 1000 * 1000 * 1000 < 1000: scale = u'ns' v = int(round(v*1000*1000*1000)) elif v * 1000 * 1000 < 1000: scale = u'μs' v = int(round(v*1000*1000)) elif v * 1000 < 1000: scale = u'ms' v = round(v*1000, 4) else: scale = u'sec' ...
identifier_body
base_convert.py
#! /usr/bin/env python """ Convert arbitrary numbers between integer bases from 2 to 64. """ import string import sys from decimal import Decimal ALL_DIGITS = ''.join(map(str, range(10))) + string.ascii_letters + '+/' DIGIT_MAP = dict(enumerate(ALL_DIGITS)) DIGIT_RMAP = dict(zip(DIGIT_MAP.values(), DIGIT_MAP.keys()))...
(e): pass def digit_error(digit, base): """ Report an invalid digit in the given base. """ message = '%s is not a valid digit in base %s.' % (digit, base) handle_error(message) raise ValueError(message) def convert(number, from_base=10, to_base=10, round_to=5): """ Convert number...
handle_error
identifier_name
base_convert.py
#! /usr/bin/env python """ Convert arbitrary numbers between integer bases from 2 to 64. """ import string import sys from decimal import Decimal ALL_DIGITS = ''.join(map(str, range(10))) + string.ascii_letters + '+/' DIGIT_MAP = dict(enumerate(ALL_DIGITS)) DIGIT_RMAP = dict(zip(DIGIT_MAP.values(), DIGIT_MAP.keys()))...
def digit_error(digit, base): """ Report an invalid digit in the given base. """ message = '%s is not a valid digit in base %s.' % (digit, base) handle_error(message) raise ValueError(message) def convert(number, from_base=10, to_base=10, round_to=5): """ Convert number between spec...
pass
identifier_body
base_convert.py
#! /usr/bin/env python """ Convert arbitrary numbers between integer bases from 2 to 64. """ import string import sys from decimal import Decimal ALL_DIGITS = ''.join(map(str, range(10))) + string.ascii_letters + '+/' DIGIT_MAP = dict(enumerate(ALL_DIGITS)) DIGIT_RMAP = dict(zip(DIGIT_MAP.values(), DIGIT_MAP.keys()))...
fraction += d_value * from_base ** -(i+1) frac_digits = [] product = fraction while product > 0 and len(frac_digits) < round_to: product *= to_base frac_digits.append(int(product)) product -= int(product) if frac_digits: result += '.' + ''.join(map(str, frac_digi...
digit_error(d, from_base)
conditional_block
base_convert.py
#! /usr/bin/env python """ Convert arbitrary numbers between integer bases from 2 to 64. """ import string import sys from decimal import Decimal ALL_DIGITS = ''.join(map(str, range(10))) + string.ascii_letters + '+/' DIGIT_MAP = dict(enumerate(ALL_DIGITS)) DIGIT_RMAP = dict(zip(DIGIT_MAP.values(), DIGIT_MAP.keys()))...
product = fraction while product > 0 and len(frac_digits) < round_to: product *= to_base frac_digits.append(int(product)) product -= int(product) if frac_digits: result += '.' + ''.join(map(str, frac_digits)) return result if result else '0' if __name__ == '__main__': ...
fraction += d_value * from_base ** -(i+1) frac_digits = []
random_line_split
FunctionHypothesis.py
""" A special type of hypothesis whose value is a function. The function is automatically eval-ed when we set_value, and is automatically hidden and unhidden when we pickle This can also be called like a function, as in fh(data)! """ from Hypothesis import Hypothesis from copy import copy clas...
elif value is None: self.fvalue = None else: self.fvalue = self.compile_function() # now that the value is set def force_function(self, f): """ Sets the function to f, ignoring value. :param f: - a python function (object) :return: "...
self.fvalue = f
conditional_block
FunctionHypothesis.py
""" A special type of hypothesis whose value is a function. The function is automatically eval-ed when we set_value, and is automatically hidden and unhidden when we pickle This can also be called like a function, as in fh(data)! """ from Hypothesis import Hypothesis from copy import copy clas...
def __call__(self, *vals): # The below assertions are useful but VERY slow #assert not any([isinstance(x, FunctionData) for x in vals]), "*** Probably you mean to pass FunctionData.input instead of FunctionData?" #assert callable(self.fvalue) return self.fvalue(*vals) def co...
""" A special type of hypothesis whose value is a function. The function is automatically eval-ed when we set_value, and is automatically hidden and unhidden when we pickle This can also be called like a function, as in fh(data)! """ def __init__(self, value=None, f=None, di...
identifier_body
FunctionHypothesis.py
""" A special type of hypothesis whose value is a function. The function is automatically eval-ed when we set_value, and is automatically hidden and unhidden when we pickle This can also be called like a function, as in fh(data)! """ from Hypothesis import Hypothesis from copy import copy clas...
def compile_function(self): """ Takes my value and returns what function I compute. Internally cached by set_value NOTE: This must be overwritten by subclasses to something useful--see LOTHypothesis """ raise NotImplementedError def set_value(self, value, f=None): ...
#assert callable(self.fvalue) return self.fvalue(*vals)
random_line_split
FunctionHypothesis.py
""" A special type of hypothesis whose value is a function. The function is automatically eval-ed when we set_value, and is automatically hidden and unhidden when we pickle This can also be called like a function, as in fh(data)! """ from Hypothesis import Hypothesis from copy import copy clas...
(self, *vals): # The below assertions are useful but VERY slow #assert not any([isinstance(x, FunctionData) for x in vals]), "*** Probably you mean to pass FunctionData.input instead of FunctionData?" #assert callable(self.fvalue) return self.fvalue(*vals) def compile_function(se...
__call__
identifier_name
controllers.py
# This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from datetime import timedelta from flask import flash, redirect, request, session from indico.core.db i...
def _process(self): return WPNews.render_template('news_item.html', item=self.item) class RHManageNewsBase(RHAdminBase): pass class RHManageNews(RHManageNewsBase): def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPManageNews.render_te...
self.item = NewsItem.get_or_404(request.view_args['news_id'])
identifier_body
controllers.py
# This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from datetime import timedelta from flask import flash, redirect, request, session from indico.core.db i...
return jsonify_form(form) class RHDeleteNews(RHManageNewsItemBase): def _process(self): db.session.delete(self.item) get_recent_news.clear_cached() flash(_("News '{title}' has been deleted").format(title=self.item.title), 'success') logger.info('News %r deleted by %r', sel...
old_title = self.item.title form.populate_obj(self.item) db.session.flush() get_recent_news.clear_cached() logger.info('News %r modified by %s', self.item, session.user) flash(_("News '{title}' has been updated").format(title=old_title), 'success') ...
conditional_block
controllers.py
# This file is part of Indico.
# modify it under the terms of the MIT License; see the # LICENSE file for more details. from datetime import timedelta from flask import flash, redirect, request, session from indico.core.db import db from indico.modules.admin import RHAdminBase from indico.modules.news import logger, news_settings from indico.modu...
# Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or
random_line_split
controllers.py
# This file is part of Indico. # Copyright (C) 2002 - 2021 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from datetime import timedelta from flask import flash, redirect, request, session from indico.core.db i...
(RHManageNewsBase): def _process(self): news = NewsItem.query.order_by(NewsItem.created_dt.desc()).all() return WPManageNews.render_template('admin/news.html', 'news', news=news) class RHNewsSettings(RHManageNewsBase): def _process(self): form = NewsSettingsForm(obj=FormDefaults(**news...
RHManageNews
identifier_name
c_str.rs
another location. /// /// Note that this structure is **not** `repr(C)` and is not recommended to be /// placed in the signatures of FFI functions. Instead safe wrappers of FFI /// functions may leverage the unsafe `from_ptr` constructor to provide a safe /// interface to other consumers. /// /// # Examples /// /// In...
as_ptr
identifier_name
c_str.rs
use slice; use string::String; use vec::Vec; /// A type representing an owned C-compatible string /// /// This type serves the primary purpose of being able to safely generate a /// C-compatible string from a Rust byte slice or vector. An instance of this /// type is a static guarantee that the underlying bytes contai...
use ops::Deref; use option::Option::{self, Some, None}; use result::Result::{self, Ok, Err};
random_line_split
c_str.rs
the nul byte. #[stable(feature = "rust1", since = "1.0.0")] pub fn new<T: Into<Vec<u8>>>(t: T) -> Result<CString, NulError> { let bytes = t.into(); match bytes.iter().position(|x| *x == 0) { Some(i) => Err(NulError(i, bytes)), None => Ok(unsafe { CString::from_vec_unchec...
{ let data = b"123\0"; let ptr = data.as_ptr() as *const libc::c_char; unsafe { assert_eq!(CStr::from_ptr(ptr).to_bytes(), b"123"); assert_eq!(CStr::from_ptr(ptr).to_bytes_with_nul(), b"123\0"); } }
identifier_body
PreviewMenu.js
import React from 'react'; import { withState } from 'recompose'; import styled from 'styled-components'; import MenuWrapper from './MenuWrapper'; import Layer from './Layer'; import { play as Play, pause as Pause } from './Icons'; import { mergePixels, debounce } from '../utils'; class Debounce extends React.Componen...
() { clearTimeout(this.timer); } render() { const { setFPS, setFrame, setPaused } = this; const { sources, width, height, children, style } = this.props; const { paused, fps } = this.state; const index = this.state.frame % sources.length; return ( <div style={style}> <PreviewIm...
componentWillUnmount
identifier_name
PreviewMenu.js
import React from 'react'; import { withState } from 'recompose'; import styled from 'styled-components'; import MenuWrapper from './MenuWrapper'; import Layer from './Layer'; import { play as Play, pause as Pause } from './Icons'; import { mergePixels, debounce } from '../utils'; class Debounce extends React.Componen...
margin: 0, width: 24, height: 24, border: '1px solid #fff', borderRadius: 24, background: 'none', outline: 'none' }} onClick={() => setFPS(fps <= 1 ? 0 : fps - 1)} > - </button> </div>...
color: '#fff',
random_line_split
nb.js
/* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'link', 'nb', { acccessKey: 'Aksessknapp', advanced: 'Avansert', advisoryContentType: 'Type', advisoryTitle: 'Tittel', anchor: { toolbar: 'Sett ...
popupLocationBar: 'Adresselinje', popupMenuBar: 'Menylinje', popupResizable: 'Skalerbar', popupScrollBars: 'Scrollbar', popupStatusBar: 'Statuslinje', popupToolbar: 'Verktøylinje', popupTop: 'Topp-posisjon', rel: 'Relasjon (rel)', selectAnchor: 'Velg et anker', styles: 'Stil', tabIndex: 'Tabindeks', target:...
popupDependent: 'Avhenging (Netscape)', popupFeatures: 'Egenskaper for popup-vindu', popupFullScreen: 'Fullskjerm (IE)', popupLeft: 'Venstre posisjon',
random_line_split
create.ts
import Rails from '@rails/ujs'; import { showNotification, showErrorNotification } from 'utilities/notifications'; import I18n from 'retrospring/i18n'; export function createListHandler(event: Event): void { const button = event.target as HTMLButtonElement; const input = document.querySelector<HTMLInputElement>('i...
type: 'POST', data: new URLSearchParams({ name: input.value, user: button.dataset.user }).toString(), success: (data) => { if (data.success) { document.querySelector('#lists-list ul.list-group').insertAdjacentHTML('beforeend', data.render); } showNotification...
Rails.ajax({ url: '/ajax/create_list',
random_line_split
create.ts
import Rails from '@rails/ujs'; import { showNotification, showErrorNotification } from 'utilities/notifications'; import I18n from 'retrospring/i18n'; export function createListHandler(event: Event): void { const button = event.target as HTMLButtonElement; const input = document.querySelector<HTMLInputElement>('i...
}
{ event.preventDefault(); document.querySelector<HTMLButtonElement>('button#create-list').click(); }
conditional_block
create.ts
import Rails from '@rails/ujs'; import { showNotification, showErrorNotification } from 'utilities/notifications'; import I18n from 'retrospring/i18n'; export function createListHandler(event: Event): void { const button = event.target as HTMLButtonElement; const input = document.querySelector<HTMLInputElement>('i...
{ // Return key if (event.which === 13) { event.preventDefault(); document.querySelector<HTMLButtonElement>('button#create-list').click(); } }
identifier_body
create.ts
import Rails from '@rails/ujs'; import { showNotification, showErrorNotification } from 'utilities/notifications'; import I18n from 'retrospring/i18n'; export function createListHandler(event: Event): void { const button = event.target as HTMLButtonElement; const input = document.querySelector<HTMLInputElement>('i...
(event: KeyboardEvent): void { // Return key if (event.which === 13) { event.preventDefault(); document.querySelector<HTMLButtonElement>('button#create-list').click(); } }
createListInputHandler
identifier_name
suggestion-modal-for-exploration-player.service.ts
// Copyright 2019 The Oppia Authors. 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 ap...
} }; } ]);
{ _showEditStateContentSuggestionModal(); }
conditional_block
suggestion-modal-for-exploration-player.service.ts
// Copyright 2019 The Oppia Authors. 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 ap...
]);
random_line_split
get.ts
import { suite } from 'uvu'; import assert from 'uvu/assert'; import { beforeEach, prepES, } from '../helpers'; let test = suite('es/sqlite - get'); test.before.each( beforeEach ); test('retrieve all components on an entity', async () => { let [, es] = await prepES(undefined, 'todo'); let e = awa...
assert.equal( e.components.size, 0 ); }); test('retrieve some components on an entity', async () => { let [, es] = await prepES(undefined, 'todo'); const bf = es.resolveComponentDefIds(['/component/title']); let e = await es.getEntity( 102, bf ); assert.equal( e.components.size, 1 ); }); test...
random_line_split
fan.py
"""Support for Tasmota fans.""" from hatasmota import const as tasmota_const from homeassistant.components import fan from homeassistant.components.fan import FanEntity from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.util.percentage impo...
(tasmota_entity, discovery_hash): """Discover and add a Tasmota fan.""" async_add_entities( [TasmotaFan(tasmota_entity=tasmota_entity, discovery_hash=discovery_hash)] ) hass.data[ DATA_REMOVE_DISCOVER_COMPONENT.format(fan.DOMAIN) ] = async_dispatcher_connect( ...
async_discover
identifier_name
fan.py
"""Support for Tasmota fans.""" from hatasmota import const as tasmota_const from homeassistant.components import fan from homeassistant.components.fan import FanEntity from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.util.percentage impo...
self._tasmota_entity.set_speed(tasmota_const.FAN_SPEED_OFF)
random_line_split
fan.py
"""Support for Tasmota fans.""" from hatasmota import const as tasmota_const from homeassistant.components import fan from homeassistant.components.fan import FanEntity from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.util.percentage impo...
@property def speed_count(self) -> int: """Return the number of speeds the fan supports.""" return len(ORDERED_NAMED_FAN_SPEEDS) @property def percentage(self): """Return the current speed percentage.""" if self._state is None: return None if self._...
"""Initialize the Tasmota fan.""" self._state = None super().__init__( **kwds, )
identifier_body
fan.py
"""Support for Tasmota fans.""" from hatasmota import const as tasmota_const from homeassistant.components import fan from homeassistant.components.fan import FanEntity from homeassistant.core import callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.util.percentage impo...
return ordered_list_item_to_percentage(ORDERED_NAMED_FAN_SPEEDS, self._state) @property def supported_features(self): """Flag supported features.""" return fan.SUPPORT_SET_SPEED async def async_set_percentage(self, percentage): """Set the speed of the fan.""" if pe...
return 0
conditional_block
data_processing.py
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
dataset = dataset.batch(batch_size, drop_remainder=True) return dataset def count_dataset(dataset): cnt = 0 for _ in iter(dataset): cnt = cnt + 1 return int(cnt) def get_local_y_dist(client_dataset): dist = np.zeros((1, NUM_EMNIST_CLASSES)) for x in client_dataset: y = x['label'].numpy() ...
dataset = dataset.shuffle(SHUFFLE_SIZE)
conditional_block
data_processing.py
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
(data_tuple, mode, batch_size=256, with_dist=False): """Packs the arrays into tf.data.Dataset. Args: data_tuple: tuples of numpy array return from parse_data() as inputs. It follows the orders: For with_dist is True: Input images, client ids, label distributions, labels For with_dist ...
pack_dataset
identifier_name
data_processing.py
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
if split_size < 1: split_num = int(len(y)*split_size) ids = np.random.choice(np.arange(len(y)), split_num) y = tf.gather(y, ids) x = tf.gather(x, ids) num = len(y) idx = np.array([client_id]*num) train_x[cnt:cnt+num] = x train_y[cnt:cnt+n...
train_x, train_id, train_y = np.zeros((MAX_DATA_SIZE, 28, 28, 1)), np.zeros( (MAX_DATA_SIZE)), np.zeros((MAX_DATA_SIZE)) cnt = 0 if with_dist: train_dist = np.zeros((MAX_DATA_SIZE, NUM_EMNIST_CLASSES)) client_num_list = [] for client_id in client_ids: ds = emnist.create_tf_dataset_...
identifier_body
data_processing.py
# coding=utf-8 # Copyright 2022 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
return int(cnt) def get_local_y_dist(client_dataset): dist = np.zeros((1, NUM_EMNIST_CLASSES)) for x in client_dataset: y = x['label'].numpy() dist[y] += 1 return np.array(dist).reshape((1, -1)) / np.sum(dist) def parse_data(emnist_train, emnist_test, client_ids, ...
def count_dataset(dataset): cnt = 0 for _ in iter(dataset): cnt = cnt + 1
random_line_split