file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
Luup.ts
export module Query { export const OK:string = "OK"; export module ParamNames { export const ACTION:string = "action"; // String export const DEVICE:string = "device"; // Integer export const DEVICE_NUM:string = "DeviceNum"; // Integer export const ID:string = "id"; // String export const NAME:string = "n...
export function translateParamNames(from:IUriComponentMap):IUriComponentMap { var result:IUriComponentMap = {}; for(var key of Object.keys(from)) { result[translateParamName(key)] = from[key]; } return result; } export module IDs { export const USER_DATA:string = "user_data"; export const US...
{ var fromLC = from.toLowerCase(); for(var key of Object.keys(ParamNames)) { if(key.toLowerCase()==fromLC) return key; } return from; }
identifier_body
naming-conventions.ts
import pluralize = require("pluralize"); /** * Takes a json-api type name, assumed to be using the dasherized, pluralized * conventions that are recommended for the json-api `type` key, and returns * a singularized, PascalCase version of that name, per the naming conventions * of Mongoose models. * * @param {str...
( modelName: string, pluralizer: typeof pluralize.plural = pluralize.plural.bind(pluralize) ) { return pluralizer( modelName .replace(/([A-Z])/g, "-$1") .slice(1) .toLowerCase() ); }
getTypeName
identifier_name
naming-conventions.ts
import pluralize = require("pluralize"); /** * Takes a json-api type name, assumed to be using the dasherized, pluralized * conventions that are recommended for the json-api `type` key, and returns * a singularized, PascalCase version of that name, per the naming conventions * of Mongoose models. * * @param {str...
{ return pluralizer( modelName .replace(/([A-Z])/g, "-$1") .slice(1) .toLowerCase() ); }
identifier_body
naming-conventions.ts
import pluralize = require("pluralize"); /** * Takes a json-api type name, assumed to be using the dasherized, pluralized * conventions that are recommended for the json-api `type` key, and returns * a singularized, PascalCase version of that name, per the naming conventions * of Mongoose models. * * @param {str...
}
random_line_split
servo.py
from __future__ import division from .module import Module, interact class Servo(Module): def __init__(self, id, alias, device): Module.__init__(self, 'Servo', id, alias, device) self._max_angle = 180.0 self._min_pulse = 0.0005 self._max_pulse = 0.0015 self._angle = 0.0 ...
(self): def move(position): self.position = position return interact(move, position=(0, 180, 1))
control
identifier_name
servo.py
from __future__ import division from .module import Module, interact class Servo(Module): def __init__(self, id, alias, device): Module.__init__(self, 'Servo', id, alias, device) self._max_angle = 180.0 self._min_pulse = 0.0005 self._max_pulse = 0.0015 self._angle = 0.0 ...
return interact(move, position=(0, 180, 1))
self.position = position
random_line_split
servo.py
from __future__ import division from .module import Module, interact class Servo(Module):
def __init__(self, id, alias, device): Module.__init__(self, 'Servo', id, alias, device) self._max_angle = 180.0 self._min_pulse = 0.0005 self._max_pulse = 0.0015 self._angle = 0.0 @property def rot_position(self): return self._angle @rot_position.setter ...
identifier_body
index.ts
"use strict"; import * as http from "http"; import { euglena_template } from "euglena.template"; import { euglena } from "euglena"; import Particle = euglena.being.Particle; import * as io from "socket.io-client"; import Exception = euglena.sys.type.Exception; let OrganelleName = euglena_template.being.alive.constant...
private throwImpact(to: euglena_template.being.alive.particle.EuglenaInfo, impact: euglena.being.interaction.Impact): void { let server = this.servers[to.data.name]; if (server) { server.emit("impact", impact); } else { var post_options = { host: to.d...
{ addAction(euglena_template.being.alive.constants.particles.ConnectToEuglena, (particle) => { this_.connectToEuglena(particle.data); }); addAction(euglena_template.being.alive.constants.particles.ThrowImpact, (particle) => { this_.throwImpact(particle.data.to, particle.d...
identifier_body
index.ts
"use strict"; import * as http from "http"; import { euglena_template } from "euglena.template"; import { euglena } from "euglena"; import Particle = euglena.being.Particle; import * as io from "socket.io-client"; import Exception = euglena.sys.type.Exception; let OrganelleName = euglena_template.being.alive.constants...
} else { var post_options = { host: to.data.url, port: Number(to.data.port), path: "/", method: 'POST', headers: { 'Content-Type': 'application/json' } }; let h...
let server = this.servers[to.data.name]; if (server) { server.emit("impact", impact);
random_line_split
index.ts
"use strict"; import * as http from "http"; import { euglena_template } from "euglena.template"; import { euglena } from "euglena"; import Particle = euglena.being.Particle; import * as io from "socket.io-client"; import Exception = euglena.sys.type.Exception; let OrganelleName = euglena_template.being.alive.constant...
} private connectToEuglena(euglenaInfo: euglena_template.being.alive.particle.EuglenaInfo) { var post_options: http.RequestOptions = {}; post_options.host = euglenaInfo.data.url; post_options.port = Number(euglenaInfo.data.port); post_options.path = "/"; post_options.met...
{ var post_options = { host: to.data.url, port: Number(to.data.port), path: "/", method: 'POST', headers: { 'Content-Type': 'application/json' } }; let httpConnector = ...
conditional_block
index.ts
"use strict"; import * as http from "http"; import { euglena_template } from "euglena.template"; import { euglena } from "euglena"; import Particle = euglena.being.Particle; import * as io from "socket.io-client"; import Exception = euglena.sys.type.Exception; let OrganelleName = euglena_template.being.alive.constant...
(addAction: (particleName: string, action: (particle: Particle) => void) => void): void { addAction(euglena_template.being.alive.constants.particles.ConnectToEuglena, (particle) => { this_.connectToEuglena(particle.data); }); addAction(euglena_template.being.alive.constants.particles...
bindActions
identifier_name
setup.py
DESCRIPTION = """\ ACQ4 is a python-based platform for experimental neurophysiology. It includes support for standard electrophysiology, multiphoton imaging, scanning laser photostimulation, and many other experimental techniques. ACQ4 is highly modular and extensible, allowing support to be added for new types of d...
# Find last tag matching "acq4-.*" tagNames = check_output(['git', 'tag'], universal_newlines=True).strip().split('\n') while True: if len(tagNames) == 0: raise Exception("Could not determine last tagged version.") lastTagName = tagNames.pop() ...
commit = check_output(['git', 'show', name], universal_newlines=True).split('\n')[0] assert commit[:7] == 'commit ' return commit[7:]
identifier_body
setup.py
DESCRIPTION = """\ ACQ4 is a python-based platform for experimental neurophysiology. It includes support for standard electrophysiology, multiphoton imaging, scanning laser photostimulation, and many other experimental techniques. ACQ4 is highly modular and extensible, allowing support to be added for new types of d...
(distutils.command.build.build): def run(self): ret = distutils.command.build.build.run(self) # If the version in __init__ is different from the automatically-generated # version string, then we will update __init__ in the build directory global path, version, initVersion ...
Build
identifier_name
setup.py
DESCRIPTION = """\ ACQ4 is a python-based platform for experimental neurophysiology. It includes support for standard electrophysiology, multiphoton imaging, scanning laser photostimulation, and many other experimental techniques. ACQ4 is highly modular and extensible, allowing support to be added for new types of d...
if sys.platform == 'win32': scripts = ['bin/acq4.bat'] else: scripts = ['bin/acq4'] setup( version=version, cmdclass={'build': Build}, packages=allPackages, package_dir={}, package_data={'acq4': packageData}, data_files=dataFiles, classifiers = [ "Programming Language :: Py...
if f.endswith(ext): packageData.append(os.path.join(subpath, f)[len(pkgRoot):].lstrip(os.path.sep))
random_line_split
setup.py
DESCRIPTION = """\ ACQ4 is a python-based platform for experimental neurophysiology. It includes support for standard electrophysiology, multiphoton imaging, scanning laser photostimulation, and many other experimental techniques. ACQ4 is highly modular and extensible, allowing support to be added for new types of d...
version = m.group(1).strip('\'\"') initVersion = version # If this is a git checkout, try to generate a more decriptive version string try: if os.path.isdir(os.path.join(path, '.git')): def gitCommit(name): commit = check_output(['git', 'show', name], universal_newlines=True).split('\n')[0] ...
raise Exception("Cannot determine __version__ from init file: '%s'!" % initfile)
conditional_block
__init__.py
""" The OpenMP package does contain all code templates required for the openMP code generation in ANNarchy. BaseTemplates: defines the basic defintions common to all sparse matrix formates, e. g. projection header [FORMAT]_SingleThread: defines the format specific defintions for the currently available form...
__all__ = ["BaseTemplates", "LIL_OpenMP", "LIL_Sliced_OpenMP", "COO_OpenMP", "CSR_OpenMP", "CSR_T_OpenMP", "CSR_T_Sliced_OpenMP", "ELL_OpenMP", "ELLR_OpenMP", "Dense_OpenMP"]
random_line_split
marimo.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from pwn import * import time host = "10.211.55.6" port = 8888 host = "ch41l3ng3s.codegate.kr" port = 3333 r = remote(host,port) def sell(idx): r.recvuntil(">>") r.sendline("S") r.recvuntil(">>") r.sendline(str(idx)) r.recvuntil("?") r.sendline("...
if profile : r.sendline("M") r.recvuntil(">>") r.sendline(profile) return data else : r.sendline("B") return data puts_got = 0x603018 r.recvuntil(">>") r.sendline("show me the marimo") r.recvuntil(">>") r.sendline("Aa") r.recvuntil(">>") r.sendline("orange") tim...
r.sendline(str(idx)) data = r.recvuntil(">>")
random_line_split
marimo.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from pwn import * import time host = "10.211.55.6" port = 8888 host = "ch41l3ng3s.codegate.kr" port = 3333 r = remote(host,port) def sell(idx): r.recvuntil(">>") r.sendline("S") r.recvuntil(">>") r.sendline(str(idx)) r.recvuntil("?") r.sendline("...
(idx,profile=None): r.recvuntil(">>") r.sendline("V") r.recvuntil(">>") r.sendline(str(idx)) data = r.recvuntil(">>") if profile : r.sendline("M") r.recvuntil(">>") r.sendline(profile) return data else : r.sendline("B") return data puts_got = ...
view
identifier_name
marimo.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from pwn import * import time host = "10.211.55.6" port = 8888 host = "ch41l3ng3s.codegate.kr" port = 3333 r = remote(host,port) def sell(idx): r.recvuntil(">>") r.sendline("S") r.recvuntil(">>") r.sendline(str(idx)) r.recvuntil("?") r.sendline("...
else : r.sendline("B") return data puts_got = 0x603018 r.recvuntil(">>") r.sendline("show me the marimo") r.recvuntil(">>") r.sendline("Aa") r.recvuntil(">>") r.sendline("orange") time.sleep(1) sell(0) buy(1,"danogg","fuck") buy(1,"orange","fuck") time.sleep(3) data = view(0) ctime = int(data.spl...
r.sendline("M") r.recvuntil(">>") r.sendline(profile) return data
conditional_block
marimo.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from pwn import * import time host = "10.211.55.6" port = 8888 host = "ch41l3ng3s.codegate.kr" port = 3333 r = remote(host,port) def sell(idx):
def buy(size,name,pr): r.recvuntil(">>") r.sendline("B") r.recvuntil(">>") r.sendline(str(size)) r.recvuntil(">>") r.sendline("P") r.recvuntil(">>") r.sendline(name) r.recvuntil(">>") r.sendline(pr) def view(idx,profile=None): r.recvuntil(">>") r.sendline("V") r.re...
r.recvuntil(">>") r.sendline("S") r.recvuntil(">>") r.sendline(str(idx)) r.recvuntil("?") r.sendline("S")
identifier_body
mcdonalds_il.py
# -*- coding: utf-8 -*- import scrapy import json import re from locations.items import GeojsonPointItem class McDonalsILSpider(scrapy.Spider): name = "mcdonalds_il" allowed_domains = ["www.mcdonalds.co.il"] start_urls = ( 'https://www.mcdonalds.co.il/%D7%90%D7%99%D7%AA%D7%95%D7%A8_%D7%9E%D7%A1%D...
(self, data): lat = lon = '' data = data.xpath('//div[@id="map"]') lat = data.xpath('//@data-lat').extract_first() lon = data.xpath('//@data-lng').extract_first() return lat, lon def parse_phone(self, phone): phone = phone.xpath('//div[@class="padding_hf_v sp_padding...
parse_latlon
identifier_name
mcdonalds_il.py
# -*- coding: utf-8 -*- import scrapy import json import re from locations.items import GeojsonPointItem class McDonalsILSpider(scrapy.Spider): name = "mcdonalds_il" allowed_domains = ["www.mcdonalds.co.il"] start_urls = ( 'https://www.mcdonalds.co.il/%D7%90%D7%99%D7%AA%D7%95%D7%A8_%D7%9E%D7%A1%D...
'phone': phone, 'lon': lon, 'lat': lat, 'name': name, 'addr_full': address } yield GeojsonPointItem(**properties) def parse(self, response): stores = response.xpath('//div[@class="store_wrap link"]/a/@href').extract() for ...
phone = self.parse_phone(response) lat, lon = self.parse_latlon(response) properties = { 'ref': response.meta['ref'],
random_line_split
mcdonalds_il.py
# -*- coding: utf-8 -*- import scrapy import json import re from locations.items import GeojsonPointItem class McDonalsILSpider(scrapy.Spider): name = "mcdonalds_il" allowed_domains = ["www.mcdonalds.co.il"] start_urls = ( 'https://www.mcdonalds.co.il/%D7%90%D7%99%D7%AA%D7%95%D7%A8_%D7%9E%D7%A1%D...
def parse_phone(self, phone): phone = phone.xpath('//div[@class="padding_hf_v sp_padding_qt_v"]/a/text()').extract_first() if not phone: return "" return phone.strip() def parse_address(self, address): address = address.xpath('//h2/strong/text()').extract_fi...
lat = lon = '' data = data.xpath('//div[@id="map"]') lat = data.xpath('//@data-lat').extract_first() lon = data.xpath('//@data-lng').extract_first() return lat, lon
identifier_body
mcdonalds_il.py
# -*- coding: utf-8 -*- import scrapy import json import re from locations.items import GeojsonPointItem class McDonalsILSpider(scrapy.Spider): name = "mcdonalds_il" allowed_domains = ["www.mcdonalds.co.il"] start_urls = ( 'https://www.mcdonalds.co.il/%D7%90%D7%99%D7%AA%D7%95%D7%A8_%D7%9E%D7%A1%D...
ref = self.parse_Ref(store) yield scrapy.Request('https:' + store, meta={'ref': ref}, callback=self.parse_store)
conditional_block
qr-scanner.ts
import { Component } from '@angular/core'; import { ModalController, } from '@ionic/angular'; import { QRScanner, QRScannerStatus } from '@ionic-native/qr-scanner/ngx'; import { Vibration } from '@ionic-native/vibration/ngx'; import { EmitService } from '@services/emit.service'; @Component({ selector: 'modal-qr-s...
() { this.emitservice.qrcodeEmit.emit('qrScanner:show'); this.qrScanner.show(); } private hideCamera() { this.emitservice.qrcodeEmit.emit('qrScanner:hide'); this.qrScanner.hide(); } public dismiss(qrCode: object = null) { this.qrScanner.getStatus().then((status: QRScannerStatus) => { ...
showCamera
identifier_name
qr-scanner.ts
import { Component } from '@angular/core'; import { ModalController, } from '@ionic/angular'; import { QRScanner, QRScannerStatus } from '@ionic-native/qr-scanner/ngx'; import { Vibration } from '@ionic-native/vibration/ngx'; import { EmitService } from '@services/emit.service'; @Component({ selector: 'modal-qr-s...
ionViewDidLeave() { this.hideCamera(); this.qrScanner.destroy(); } }
if (this.ionApp) { this.ionApp.classList.remove('transparent'); } this.modalCtrl.dismiss(qrCode); }
random_line_split
qr-scanner.ts
import { Component } from '@angular/core'; import { ModalController, } from '@ionic/angular'; import { QRScanner, QRScannerStatus } from '@ionic-native/qr-scanner/ngx'; import { Vibration } from '@ionic-native/vibration/ngx'; import { EmitService } from '@services/emit.service'; @Component({ selector: 'modal-qr-s...
}); if (this.ionApp) { this.ionApp.classList.remove('transparent'); } this.modalCtrl.dismiss(qrCode); } ionViewDidLeave() { this.hideCamera(); this.qrScanner.destroy(); } }
{ this.hideCamera(); }
conditional_block
qr-scanner.ts
import { Component } from '@angular/core'; import { ModalController, } from '@ionic/angular'; import { QRScanner, QRScannerStatus } from '@ionic-native/qr-scanner/ngx'; import { Vibration } from '@ionic-native/vibration/ngx'; import { EmitService } from '@services/emit.service'; @Component({ selector: 'modal-qr-s...
public dismiss(qrCode: object = null) { this.qrScanner.getStatus().then((status: QRScannerStatus) => { if (status.showing) { this.hideCamera(); } }); if (this.ionApp) { this.ionApp.classList.remove('transparent'); } this.modalCtrl.dismiss(qrCode); } ionViewDidLeave...
{ this.emitservice.qrcodeEmit.emit('qrScanner:hide'); this.qrScanner.hide(); }
identifier_body
angular-locale_nd.js
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n...
"Mvulo", "Sibili", "Sithathu", "Sine", "Sihlanu", "Mgqibelo" ], "ERANAMES": [ "UKristo angakabuyi", "Ukristo ebuyile" ], "ERAS": [ "BC", "AD" ], "FIRSTDAYOFWEEK": 6, "MONTH": [ "Zibandlela", "Nhlolanja"...
"DAY": [ "Sonto",
random_line_split
angular-locale_nd.js
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n...
var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "AM", "PM" ], "DAY": [ "Sonto", "Mvulo", "Sibili", "Sithathu", "Sine", "Sihlanu", ...
{ v = Math.min(getDecimals(n), 3); }
conditional_block
angular-locale_nd.js
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function
(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f...
getDecimals
identifier_name
angular-locale_nd.js
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n)
function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "AM", ...
{ n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; }
identifier_body
track.py
#!/usr/bin/python # -*- coding: utf-8 -*- # mingus - Music theory Python package, track module. # Copyright (C) 2008-2009, Bart Spaans # # 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 Found...
(self): """Diminish all the bars in the Track.""" for bar in self.bars: bar.diminish() return self def __add__(self, value): """Enable the '+' operator for Tracks. Notes, notes as string, NoteContainers and Bars accepted. """ if hasattr(value, 'b...
diminish
identifier_name
track.py
#!/usr/bin/python # -*- coding: utf-8 -*- # mingus - Music theory Python package, track module. # Copyright (C) 2008-2009, Bart Spaans # # 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 Found...
Each sublist divides the value by 2. If a tuning is set, chords will be expanded so they have a proper fingering. Example: >>> t = Track().from_chords(['C', ['Am', 'Dm'], 'G7', 'C#'], 1) """ tun = self.get_tuning() def add_chord(chord, duration): ...
def from_chords(self, chords, duration=1): """Add chords to the Track. The given chords should be a list of shorthand strings or list of list of shorthand strings, etc.
random_line_split
track.py
#!/usr/bin/python # -*- coding: utf-8 -*- # mingus - Music theory Python package, track module. # Copyright (C) 2008-2009, Bart Spaans # # 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 Found...
def test_integrity(self): """Test whether all but the last Bars contained in this track are full.""" for b in self.bars[:-1]: if not b.is_full(): return False return True def __eq__(self, other): """Enable the '==' operator for tracks.""" ...
return self.add_notes(value)
conditional_block
track.py
#!/usr/bin/python # -*- coding: utf-8 -*- # mingus - Music theory Python package, track module. # Copyright (C) 2008-2009, Bart Spaans # # 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 Found...
def augment(self): """Augment all the bars in the Track.""" for bar in self.bars: bar.augment() return self def diminish(self): """Diminish all the bars in the Track.""" for bar in self.bars: bar.diminish() return self def __add__(s...
"""Transpose all the notes in the track up or down the interval. Call transpose() on every Bar. """ for bar in self.bars: bar.transpose(interval, up) return self
identifier_body
005reset.py
#!/usr/bin/env python import atexit import argparse import getpass import sys import textwrap import time from pyVim import connect from pyVmomi import vim import requests requests.packages.urllib3.disable_warnings() import ssl try: _create_unverified_https_context = ssl._create_unverified_context except Att...
def answer_vm_question(virtual_machine): print "\n" choices = virtual_machine.runtime.question.choice.choiceInfo default_option = None if virtual_machine.runtime.question.choice.defaultIndex is not None: ii = virtual_machine.runtime.question.choice.defaultIndex default_option = choice...
"""Prints label with a spinner. When called repeatedly from inside a loop this prints a one line CLI spinner. """ sys.stdout.write("\r\t%s %s" % (label, _spinner.next())) sys.stdout.flush()
identifier_body
005reset.py
#!/usr/bin/env python import atexit import argparse import getpass import sys import textwrap import time from pyVim import connect from pyVmomi import vim import requests requests.packages.urllib3.disable_warnings() import ssl try: _create_unverified_https_context = ssl._create_unverified_context except Att...
print "Found VirtualMachine: %s Name: %s" % (vm, vm.name) if vm.runtime.powerState == vim.VirtualMachinePowerState.poweredOn: # using time.sleep we just wait until the power off action # is complete. Nothing fancy here. print "reset the vm" task = vm.ResetVM_Task() while task.info.state not in [v...
print "could not find a virtual machine with the name %s" % args.name sys.exit(-1)
conditional_block
005reset.py
#!/usr/bin/env python import atexit import argparse import getpass import sys import textwrap import time from pyVim import connect from pyVmomi import vim import requests requests.packages.urllib3.disable_warnings() import ssl try: _create_unverified_https_context = ssl._create_unverified_context except Att...
(): """Creates a generator yielding a char based spinner. """ while True: for c in '|/-\\': yield c _spinner = _create_char_spinner() def spinner(label=''): """Prints label with a spinner. When called repeatedly from inside a loop this prints a one line CLI spinner. ...
_create_char_spinner
identifier_name
005reset.py
#!/usr/bin/env python
import argparse import getpass import sys import textwrap import time from pyVim import connect from pyVmomi import vim import requests requests.packages.urllib3.disable_warnings() import ssl try: _create_unverified_https_context = ssl._create_unverified_context except AttributeError: # Legacy Python that ...
import atexit
random_line_split
sortpal.js
function unique(a) { var r = new Array(); o:for(var i = 0, n = a.length; i < n; i++) { for(var x = 0, y = r.length; x < y; x++) { if((r[x][0]==a[i][0]) && (r[x][1]==a[i][1]) && (r[x][2]==a[i][2])) { // console.log("dupe" + r[x][0] + " " + a[x][0] + " " + r[x][1] + " " + a[x][1]); continue o; } } ...
function rgb_to_xyz(rgb) { red = rgb[0]; green = rgb[1]; blue = rgb[2]; x = ((0.412453 * red) + (0.357580 * green) + (0.180423 * blue)); y = ((0.212671 * red) + (0.715160 * green) + (0.072169 * blue)); z = ((0.019334 * red) + (0.119193 * green) + (0.950227 * blue)); xyz = [x,y,z]; return xyz; } function f...
{ // Ey = 0.299R + 0.587G + 0.114B // U = Ecr = 0.713(R - Ey) = 0.500R - 0.419G - 0.081B // V = Ecb = 0.564(B - Er) = -0.169R - 0.331G + 0.500B // (Gregory Smith points out that Er here should read Ey - equations above were corrected) // http://www.compuphase.com/cmetric.htm references // from gamma correc...
identifier_body
sortpal.js
function unique(a) { var r = new Array(); o:for(var i = 0, n = a.length; i < n; i++) { for(var x = 0, y = r.length; x < y; x++) { if((r[x][0]==a[i][0]) && (r[x][1]==a[i][1]) && (r[x][2]==a[i][2])) { // console.log("dupe" + r[x][0] + " " + a[x][0] + " " + r[x][1] + " " + a[x][1]); continue o; } } ...
this.uu = luv[1]; this.vvv = luv[2]; // lab is supposed to map euclidian 3d distance to perceptive color // more or less CIE 1976 Delta E this.lab3d = distFrom0(this.l, this.a, this.b); this.luv3d = distFrom0(this.ll, this.uu, this.vvv); //this.luv3dunsquared = unsquaredDistFrom0(this.ll, t...
random_line_split
sortpal.js
function unique(a) { var r = new Array(); o:for(var i = 0, n = a.length; i < n; i++) { for(var x = 0, y = r.length; x < y; x++) { if((r[x][0]==a[i][0]) && (r[x][1]==a[i][1]) && (r[x][2]==a[i][2])) { // console.log("dupe" + r[x][0] + " " + a[x][0] + " " + r[x][1] + " " + a[x][1]); continue o; } } ...
(rgb) { var min = Math.min(rgb[0], rgb[1], rgb[2]); var max = Math.max(rgb[0], rgb[1], rgb[2]); var v = max; var w = min; b = 255 -v; // dont really need hue here, just stub it and return w/b color = [0,w,b]; return color; } // from http://www.kourbatov.com/faq/rgb2cmyk.htm function rgb_to_cmyk (rgb) ...
rgb_to_hwb
identifier_name
vendor.browser.ts
// For vendors for example jQuery, Lodash, angular2-jwt just import them here unless you plan on // chunking vendors files for async loading. You would need to import the async loaded vendors // at the entry point of the async loaded file. Also see custom-typings.d.ts as you also need to // run `typings install x` wher...
import 'bootstrap-loader';
{ // Development require('angular2-hmr'); }
conditional_block
vendor.browser.ts
// For vendors for example jQuery, Lodash, angular2-jwt just import them here unless you plan on // chunking vendors files for async loading. You would need to import the async loaded vendors // at the entry point of the async loaded file. Also see custom-typings.d.ts as you also need to // run `typings install x` wher...
import '@angular/http'; import '@angular/router'; // AngularClass import '@angularclass/webpack-toolkit'; import '@angularclass/request-idle-callback'; // RxJS import 'rxjs/add/operator/map'; import 'rxjs/add/operator/mergeMap'; if ('production' === ENV) { // Production } else { // Development require('angul...
import '@angular/platform-browser'; import '@angular/platform-browser-dynamic'; import '@angular/core'; import '@angular/common'; import '@angular/forms';
random_line_split
generator.rs
#![feature(generators, generator_trait)] use std::ops::{Generator, GeneratorState}; use std::pin::Pin; // The following implementation of a function called from a `yield` statement // (apparently requiring the Result and the `String` type or constructor) // creates conditions where the `generator::StateTransform` MIR...
{ let is_true = std::env::args().len() == 1; let mut generator = || { yield get_u32(is_true); return "foo"; }; match Pin::new(&mut generator).resume(()) { GeneratorState::Yielded(Ok(1)) => {} _ => panic!("unexpected return from resume"), } match Pin::new(&mut gen...
identifier_body
generator.rs
#![feature(generators, generator_trait)] use std::ops::{Generator, GeneratorState}; use std::pin::Pin; // The following implementation of a function called from a `yield` statement // (apparently requiring the Result and the `String` type or constructor) // creates conditions where the `generator::StateTransform` MIR...
() { let is_true = std::env::args().len() == 1; let mut generator = || { yield get_u32(is_true); return "foo"; }; match Pin::new(&mut generator).resume(()) { GeneratorState::Yielded(Ok(1)) => {} _ => panic!("unexpected return from resume"), } match Pin::new(&mut ...
main
identifier_name
generator.rs
#![feature(generators, generator_trait)] use std::ops::{Generator, GeneratorState}; use std::pin::Pin;
// creates conditions where the `generator::StateTransform` MIR transform will // drop all `Counter` `Coverage` statements from a MIR. `simplify.rs` has logic // to handle this condition, and still report dead block coverage. fn get_u32(val: bool) -> Result<u32, String> { if val { Ok(1) } else { Err(String::from("s...
// The following implementation of a function called from a `yield` statement // (apparently requiring the Result and the `String` type or constructor)
random_line_split
array.ts
import { DataEntity, get, set } from '@terascope/utils'; import { PostProcessConfig, InputOutputCardinality } from '../../../interfaces'; import TransformOpBase from './base'; export default class MakeArray extends TransformOpBase { private fields!: string[]; static cardinality: InputOutputCardinality = 'many...
} }); if (results.length > 0) set(doc, this.target, results); return doc; } }
{ results.push(data); }
conditional_block
array.ts
import { DataEntity, get, set } from '@terascope/utils'; import { PostProcessConfig, InputOutputCardinality } from '../../../interfaces'; import TransformOpBase from './base'; export default class MakeArray extends TransformOpBase { private fields!: string[]; static cardinality: InputOutputCardinality = 'many...
(doc: DataEntity): DataEntity { const results: any[] = []; this.fields.forEach((field) => { const data = get(doc, field); if (data !== undefined) { if (Array.isArray(data)) { results.push(...data); } else { r...
run
identifier_name
array.ts
import { DataEntity, get, set } from '@terascope/utils'; import { PostProcessConfig, InputOutputCardinality } from '../../../interfaces'; import TransformOpBase from './base'; export default class MakeArray extends TransformOpBase { private fields!: string[]; static cardinality: InputOutputCardinality = 'many...
}
{ const results: any[] = []; this.fields.forEach((field) => { const data = get(doc, field); if (data !== undefined) { if (Array.isArray(data)) { results.push(...data); } else { results.push(data); ...
identifier_body
array.ts
import { DataEntity, get, set } from '@terascope/utils'; import { PostProcessConfig, InputOutputCardinality } from '../../../interfaces'; import TransformOpBase from './base'; export default class MakeArray extends TransformOpBase { private fields!: string[]; static cardinality: InputOutputCardinality = 'many...
throw new Error(`array creation configuration is misconfigured, could not determine fields to join ${JSON.stringify(config)}`); } this.fields = fields; this.target = tField; } run(doc: DataEntity): DataEntity { const results: any[] = []; this.fields.forEach((...
); } if (!fields || !Array.isArray(fields) || fields.length === 0) {
random_line_split
babylon.convolutionPostProcess.ts
module BABYLON { export class ConvolutionPostProcess extends PostProcess{ co
ame: string, public kernel: number[], options: number | PostProcessOptions, camera: Camera, samplingMode?: number, engine?: Engine, reusable?: boolean) { super(name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable); this.onApply = (effect: Effec...
nstructor(n
identifier_name
babylon.convolutionPostProcess.ts
module BABYLON { export class ConvolutionPostProcess extends PostProcess{ constructor(name: string, public kernel: number[], options: number | PostProcessOptions, camera: Camera, samplingMode?: number, engine?: Engine, reusable?: boolean) { super(name, "convolution", ["kernel", "screenSize"]...
this.onApply = (effect: Effect) => { effect.setFloat2("screenSize", this.width, this.height); effect.setArray("kernel", this.kernel); }; } // Statics // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing) public static Edge...
random_line_split
NetworkTimer.ts
/** * NetworkedTimer.js * * License: Apache 2.0 * author: Ciarán McCann * url: http://www.ciaranmccann.me/ */ ///<reference path="../system/Timer.ts"/> ///<reference path="Events.ts"/> ///<reference path="Client.ts"/> class NetworkTimer extends Timer { currentServerTime : number; // When last checked ...
{ this.packetRateTimer.update(); super.update(); if (this.packetRateTimer.hasTimePeriodPassed()) { Client.socket.emit(Events.client.GET_GAME_TIME, '',function (data) => { this.currentServerTime = data; }); } } ...
random_line_split
NetworkTimer.ts
/** * NetworkedTimer.js * * License: Apache 2.0 * author: Ciarán McCann * url: http://www.ciaranmccann.me/ */ ///<reference path="../system/Timer.ts"/> ///<reference path="Events.ts"/> ///<reference path="Client.ts"/> class NetworkTimer extends Timer { currentServerTime : number; // When last checked ...
//override getTimeNow() { return this.currentServerTime; } }
this.packetRateTimer.update(); super.update(); if (this.packetRateTimer.hasTimePeriodPassed()) { Client.socket.emit(Events.client.GET_GAME_TIME, '',function (data) => { this.currentServerTime = data; }); } }
identifier_body
NetworkTimer.ts
/** * NetworkedTimer.js * * License: Apache 2.0 * author: Ciarán McCann * url: http://www.ciaranmccann.me/ */ ///<reference path="../system/Timer.ts"/> ///<reference path="Events.ts"/> ///<reference path="Client.ts"/> class N
extends Timer { currentServerTime : number; // When last checked packetRateTimer: Timer; constructor(gameTurnTimeDuraction) { super(gameTurnTimeDuraction); this.packetRateTimer = new Timer(1000); this.currentServerTime = Date.now(); } update() { this.packet...
etworkTimer
identifier_name
NetworkTimer.ts
/** * NetworkedTimer.js * * License: Apache 2.0 * author: Ciarán McCann * url: http://www.ciaranmccann.me/ */ ///<reference path="../system/Timer.ts"/> ///<reference path="Events.ts"/> ///<reference path="Client.ts"/> class NetworkTimer extends Timer { currentServerTime : number; // When last checked ...
} //override getTimeNow() { return this.currentServerTime; } }
Client.socket.emit(Events.client.GET_GAME_TIME, '',function (data) => { this.currentServerTime = data; }); }
conditional_block
__init__.py
""" Study Project Copyright (C) 2015 Study Project Authors and Contributors This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Th...
VERSION = (1, 0, 0, 'alpha') __version__ = "1.0.0alpha"
]
random_line_split
map3d_population3.js
$.ajax({ url: './data/population.json', success: function (data) { var max = -Infinity; data = data.map(function (item) {
geoCoord: item.slice(0, 2), value: item[2] } }); data.forEach(function (item) { item.barHeight = item.value / max * 50 + 0.1 }); myChart.setOption({ title : { text: 'Gridded Population of the World (2000...
max = Math.max(item[2], max); return {
random_line_split
_6_2_coordinate_systems_depth.rs
#![allow(non_upper_case_globals)] extern crate glfw; use self::glfw::{Context, Key, Action}; extern crate gl; use self::gl::types::*; use std::sync::mpsc::Receiver; use std::ptr; use std::mem; use std::os::raw::c_void; use std::path::Path; use std::ffi::CStr; use shader::Shader; use image; use image::GenericImage; ...
fn process_events(window: &mut glfw::Window, events: &Receiver<(f64, glfw::WindowEvent)>) { for (_, event) in glfw::flush_messages(events) { match event { glfw::WindowEvent::FramebufferSize(width, height) => { // make sure the viewport matches the new window dimensions; note th...
{ // glfw: initialize and configure // ------------------------------ let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap(); glfw.window_hint(glfw::WindowHint::ContextVersion(3, 3)); glfw.window_hint(glfw::WindowHint::OpenGlProfile(glfw::OpenGlProfileHint::Core)); #[cfg(target_os = "macos")] ...
identifier_body
_6_2_coordinate_systems_depth.rs
#![allow(non_upper_case_globals)] extern crate glfw; use self::glfw::{Context, Key, Action}; extern crate gl; use self::gl::types::*; use std::sync::mpsc::Receiver; use std::ptr; use std::mem; use std::os::raw::c_void; use std::path::Path; use std::ffi::CStr; use shader::Shader; use image; use image::GenericImage; ...
} } }
{}
conditional_block
_6_2_coordinate_systems_depth.rs
#![allow(non_upper_case_globals)] extern crate glfw; use self::glfw::{Context, Key, Action}; extern crate gl;
use std::sync::mpsc::Receiver; use std::ptr; use std::mem; use std::os::raw::c_void; use std::path::Path; use std::ffi::CStr; use shader::Shader; use image; use image::GenericImage; use cgmath::{Matrix4, vec3, Deg, Rad, perspective}; use cgmath::prelude::*; // settings const SCR_WIDTH: u32 = 800; const SCR_HEIGHT:...
use self::gl::types::*;
random_line_split
_6_2_coordinate_systems_depth.rs
#![allow(non_upper_case_globals)] extern crate glfw; use self::glfw::{Context, Key, Action}; extern crate gl; use self::gl::types::*; use std::sync::mpsc::Receiver; use std::ptr; use std::mem; use std::os::raw::c_void; use std::path::Path; use std::ffi::CStr; use shader::Shader; use image; use image::GenericImage; ...
() { // glfw: initialize and configure // ------------------------------ let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).unwrap(); glfw.window_hint(glfw::WindowHint::ContextVersion(3, 3)); glfw.window_hint(glfw::WindowHint::OpenGlProfile(glfw::OpenGlProfileHint::Core)); #[cfg(target_os = "macos"...
main_1_6_2
identifier_name
french.py
import sys from .space_delimited import SpaceDelimited try: from nltk.stem.snowball import SnowballStemmer stemmer = SnowballStemmer("french") except ValueError: raise ImportError("Could not load stemmer for {0}. ".format(__name__)) try: from nltk.corpus import stopwords as nltk_stopwords stopwor...
"You may need to install the nltk 'stopwords' " + "corpora. See http://www.nltk.org/data.html") try: import enchant dictionary = enchant.Dict("fr") except enchant.errors.DictNotFoundError: raise ImportError("No enchant-compatible dictionary found for 'fr'. " + ...
except LookupError: raise ImportError("Could not load stopwords for {0}. ".format(__name__) +
random_line_split
index.ts
import type { FormatRelativeFn } from '../../../types' const formatRelativeLocale = { lastWeek: (date: Date): string => { const day = date.getUTCDay() switch (day) { case 0: return "'prejšnjo nedeljo ob' p" case 3: return "'prejšnjo sredo ob' p" case 6: return "'pre...
eturn format } export default formatRelative
return format(date) } r
conditional_block
index.ts
import type { FormatRelativeFn } from '../../../types' const formatRelativeLocale = { lastWeek: (date: Date): string => { const day = date.getUTCDay() switch (day) { case 0: return "'prejšnjo nedeljo ob' p" case 3: return "'prejšnjo sredo ob' p" case 6: return "'pre...
export default formatRelative
} return format }
random_line_split
mnist_mlp.py
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('data', one_hot=True) mnist_train = mnist.train mnist_val = mnist.validation p = 28 * 28 n = 10 h1 = 300 func_act = tf.nn.sigmoid x_pl = tf.placeholder(dtype=tf.float32, shape=[None, p]) y_pl = tf.pl...
acc = sess.run(accuracy, feed_dict=val_fd) print(f'Validation Acc: {acc:.4f}')
print(f'Loss: {loss_value:.4f}')
conditional_block
mnist_mlp.py
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('data', one_hot=True) mnist_train = mnist.train mnist_val = mnist.validation
p = 28 * 28 n = 10 h1 = 300 func_act = tf.nn.sigmoid x_pl = tf.placeholder(dtype=tf.float32, shape=[None, p]) y_pl = tf.placeholder(dtype=tf.float32, shape=[None, n]) w1 = tf.Variable(tf.truncated_normal(shape=[p, h1], stddev=0.1)) b1 = tf.Variable(tf.zeros(shape=[h1])) w2 = tf.Variable(tf.truncated_normal(shape=[...
random_line_split
accordion.d.ts
import { ElementRef, EventEmitter, QueryList } from '@angular/core'; import { BlockableUI } from '../common/api'; export declare class
implements BlockableUI { el: ElementRef; multiple: boolean; onClose: EventEmitter<any>; onOpen: EventEmitter<any>; style: any; styleClass: string; lazy: boolean; tabs: AccordionTab[]; constructor(el: ElementRef); addTab(tab: AccordionTab): void; getBlockableElement(): HTMLEl...
Accordion
identifier_name
accordion.d.ts
import { ElementRef, EventEmitter, QueryList } from '@angular/core'; import { BlockableUI } from '../common/api'; export declare class Accordion implements BlockableUI { el: ElementRef; multiple: boolean; onClose: EventEmitter<any>; onOpen: EventEmitter<any>; style: any; styleClass: string; ...
readonly hasHeaderFacet: boolean; onToggleDone(event: Event): void; } export declare class AccordionModule { }
constructor(accordion: Accordion); toggle(event: any): boolean; findTabIndex(): number; readonly lazy: boolean;
random_line_split
sujet.py
# -*-coding:Utf-8 -* # Copyright (c) 2010 LE GOFF Vincent # 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 # lis...
y def str_mots_cles(self): return ", ".join(self.mots_cles) or "aucun mot-clé" def _get_str_groupe(self): return self._str_groupe or "aucun" def _set_str_groupe(self, nom_groupe): self._str_groupe = nom_groupe str_groupe = property(_get_str_groupe, _set_str_groupe) @propert...
+ self.titre @propert
identifier_body
sujet.py
# -*-coding:Utf-8 -* # Copyright (c) 2010 LE GOFF Vincent # 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 # lis...
return ("", ) def __str__(self): return "aide:" + self.titre @property def str_mots_cles(self): return ", ".join(self.mots_cles) or "aucun mot-clé" def _get_str_groupe(self): return self._str_groupe or "aucun" def _set_str_groupe(self, nom_groupe): self._str_grou...
(self):
identifier_name
sujet.py
# -*-coding:Utf-8 -* # Copyright (c) 2010 LE GOFF Vincent # 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 # lis...
her_contenu(personnage, ident=ident + "{}.".format(i + 1), sp="\n\n") return ret
+ str(i + 1) + ". " + \ s.titre.capitalize() + "|ff|" ret += "\n\n" + s.affic
conditional_block
sujet.py
# -*-coding:Utf-8 -* # Copyright (c) 2010 LE GOFF Vincent # 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 # lis...
# POSSIBILITY OF SUCH DAMAGE. """Fichier contenant la classe SujetAide, détaillée plus bas.""" from abstraits.obase import BaseObj from primaires.format.description import Description from primaires.format.fonctions import supprimer_accents, couper_phrase class SujetAide(BaseObj): """Classe représentant un suj...
random_line_split
turtle.rs
// Copyright (c) 2015-2019 William (B.J.) Snow Orvis // // 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...
} impl TurtleAnimation { /// Build a TurtleAnimation from a canvas element and a boxed turtle program. /// /// The TurtleProgram is copied and boxed (via its `turtle_program_iter`) to to avoid /// TurtleAnimation being generic. pub fn new(ctx: CanvasRenderingContext2d, program: &dyn TurtleProgram) ...
/// that program. pub struct TurtleAnimation { turtle: CanvasTurtle, iter: TurtleCollectToNextForwardIterator,
random_line_split
turtle.rs
// Copyright (c) 2015-2019 William (B.J.) Snow Orvis // // 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...
(&mut self, _x1: f64, _y1: f64, _x2: f64, _y2: f64) -> bool { false } }
zoom
identifier_name
turtle.rs
// Copyright (c) 2015-2019 William (B.J.) Snow Orvis // // 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...
else { log::debug!("No more moves"); self.turtle.up(); false } } /// Translates a pixel-coordinate on the Canvas into the coordinate system used by the turtle /// curves. /// /// See turtle::turtle_vat for more information on the coordinate system for tu...
{ log::debug!("Rendering one move"); for action in one_move { self.turtle.perform(action); } true }
conditional_block
turtle.rs
// Copyright (c) 2015-2019 William (B.J.) Snow Orvis // // 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...
fn up(&mut self) { self.state.down = false; } } /// Represents everything needed to render a turtle a piece at a time to a canvas. /// /// It holds onto a turtle program, which is then used to eventually initialize an iterator over /// that program. pub struct TurtleAnimation { turtle: CanvasTurt...
{ self.state.down = true; }
identifier_body
my-app.js
// Initialize your app var myApp = new Framework7(); // Export selectors engine var $$ = Dom7; var mainView = myApp.addView('.view-main', { domCache: true //enable inline pages }); var mainVieww = myApp.addView('.view-mainn', { domCache: true //enable inline pages }); // Pull to refresh content insta ...
setTimeout(function () { $( "#front" ).empty(); $.getJSON("http://www.allpilotunion.com/wp-json/wp/v2/categories", function(result){ $.each(result, function(i, cat){ $("#front").append('<li><a href="#'+cat.slug+'" class="item-link"><div class="item-content...
var frontContent = $$('.front-cont'); // Add 'refresh' listener on it frontContent.on('refresh', function (e) { // Emulate 2s loading
random_line_split
RecognizeCleanerML.py
# vim: ts=4:sw=4:expandtab # BleachBit # Copyright (C) 2008-2017 Andrew Ziem # https://www.bleachbit.org # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # ...
(self, pathname): """Is pathname recognized?""" with open(pathname) as f: body = f.read() new_hash = hashdigest(self.salt + body) try: known_hash = options.get_hashpath(pathname) except bleachbit.NoOptionError: return NEW, new_hash if n...
__recognized
identifier_name
RecognizeCleanerML.py
# vim: ts=4:sw=4:expandtab # BleachBit # Copyright (C) 2008-2017 Andrew Ziem # https://www.bleachbit.org # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # ...
return CHANGED, new_hash def __scan(self): """Look for files and act accordingly""" changes = [] for pathname in sorted(list_cleanerml_files(local_only=True)): pathname = os.path.abspath(pathname) (status, myhash) = self.__recognized(pathname) if...
return KNOWN, new_hash
conditional_block
RecognizeCleanerML.py
# vim: ts=4:sw=4:expandtab # BleachBit # Copyright (C) 2008-2017 Andrew Ziem # https://www.bleachbit.org # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # ...
pathname = change[0] myhash = change[2] logger.info("remembering CleanerML file '%s'", pathname) if os.path.exists(pathname): options.set_hashpath(pathname, myhash)
for change in changes:
random_line_split
RecognizeCleanerML.py
# vim: ts=4:sw=4:expandtab # BleachBit # Copyright (C) 2008-2017 Andrew Ziem # https://www.bleachbit.org # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # ...
def __scan(self): """Look for files and act accordingly""" changes = [] for pathname in sorted(list_cleanerml_files(local_only=True)): pathname = os.path.abspath(pathname) (status, myhash) = self.__recognized(pathname) if NEW == status or CHANGED == stat...
"""Is pathname recognized?""" with open(pathname) as f: body = f.read() new_hash = hashdigest(self.salt + body) try: known_hash = options.get_hashpath(pathname) except bleachbit.NoOptionError: return NEW, new_hash if new_hash == known_hash: ...
identifier_body
index.d.ts
// Type definitions for @feathersjs/authentication 2.1 // Project: https://feathersjs.com // Definitions by: Abraao Alves <https://github.com/AbraaoAlves> // Jan Lohage <https://github.com/j2L4e> // Nick Bolles <https://github.com/NickBolles> // Definitions: https://github.com/Definit...
<T = any> { constructor(app: Application) create(data: Partial<T>, params: Params): Promise<{ accessToken: string }>; remove(id: null | string, params: Params): Promise<{ accessToken: string }>; } } export namespace AuthHooks { interface HashPassOptions { passwordField: string; ...
Service
identifier_name
index.d.ts
// Type definitions for @feathersjs/authentication 2.1 // Project: https://feathersjs.com // Definitions by: Abraao Alves <https://github.com/AbraaoAlves> // Jan Lohage <https://github.com/j2L4e> // Nick Bolles <https://github.com/NickBolles> // Definitions: https://github.com/Definit...
* Typically the entity id associated with the JWT */ subject?: string | undefined; /** * The issuing server, application or resource */ issuer?: string | undefined; algorithm?: string | undefined; expiresIn?: string | undefined; } | undefi...
* The resource server where the token is processed */ audience?: string | undefined; /**
random_line_split
network.py
# This code is part of Ansible, but is an independent component. # This particular file snippet, and this file snippet only, is BSD licensed. # Modules you write using this snippet, which is embedded dynamically by Ansible # still belong to the author of the module, and may assign their own license # to the complete wo...
def disconnect(self): try: if self.connected: self.connection.disconnect() self.log('disconnected from %s' % self.params['host']) except NetworkError as exc: self.fail_json(msg=to_native(exc), exception=traceback.format_exc()) def register_tran...
try: if not self.connected: self.connection.connect(self.params) if self.params['authorize']: self.connection.authorize(self.params) self.log('connected to %s:%s using %s' % (self.params['host'], self.params['port']...
identifier_body
network.py
# This code is part of Ansible, but is an independent component. # This particular file snippet, and this file snippet only, is BSD licensed. # Modules you write using this snippet, which is embedded dynamically by Ansible # still belong to the author of the module, and may assign their own license # to the complete wo...
def register_transport(transport, default=False): def register(cls): NET_CONNECTIONS[transport] = cls if default: NET_CONNECTIONS['__default__'] = cls return cls return register def add_argument(key, value): NET_CONNECTION_ARGS[key] = value def get_resource_connecti...
self.log('disconnected from %s' % self.params['host']) except NetworkError as exc: self.fail_json(msg=to_native(exc), exception=traceback.format_exc())
random_line_split
network.py
# This code is part of Ansible, but is an independent component. # This particular file snippet, and this file snippet only, is BSD licensed. # Modules you write using this snippet, which is embedded dynamically by Ansible # still belong to the author of the module, and may assign their own license # to the complete wo...
(cls): NET_CONNECTIONS[transport] = cls if default: NET_CONNECTIONS['__default__'] = cls return cls return register def add_argument(key, value): NET_CONNECTION_ARGS[key] = value def get_resource_connection(module): if hasattr(module, '_connection'): return mo...
register
identifier_name
network.py
# This code is part of Ansible, but is an independent component. # This particular file snippet, and this file snippet only, is BSD licensed. # Modules you write using this snippet, which is embedded dynamically by Ansible # still belong to the author of the module, and may assign their own license # to the complete wo...
elif val is not None: return [val] else: return list() class ModuleStub(object): def __init__(self, argument_spec, fail_json): self.params = dict() for key, value in argument_spec.items(): self.params[key] = value.get('default') self.fail_json = fail_js...
return list(val)
conditional_block
metastore.py
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
""" Retrieves Connection object from airflow metastore database. """ # pylint: disable=missing-docstring @provide_session def get_connections(self, conn_id, session=None) -> List[Connection]: conn_list = session.query(Connection).filter(Connection.conn_id == conn_id).all() session.e...
identifier_body
metastore.py
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
return None
return var_value.val
conditional_block
metastore.py
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
session.expunge_all() return conn_list @provide_session def get_variable(self, key: str, session=None): """ Get Airflow Variable from Metadata DB :param key: Variable Key :return: Variable Value """ from airflow.models.variable import Variable ...
random_line_split
metastore.py
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
(self, key: str, session=None): """ Get Airflow Variable from Metadata DB :param key: Variable Key :return: Variable Value """ from airflow.models.variable import Variable var_value = session.query(Variable).filter(Variable.key == key).first() session.exp...
get_variable
identifier_name
buffertools.js
if (!Buffer.concat) { Buffer.concat = function(buffers) { const buffersCount = buffers.length; let length = 0; for (let i = 0; i < buffersCount; i++) { const buffer = buffers[i]; length += buffer.length; } const result = new Buffer(length); let position = 0; for (let i = 0; i...
for (let i = 0, len = this.length; i < len; i++) { if (this[i] !== other[i]) { return false; } } return true; };
{ return false; }
conditional_block
buffertools.js
if (!Buffer.concat) { Buffer.concat = function(buffers) { const buffersCount = buffers.length;
length += buffer.length; } const result = new Buffer(length); let position = 0; for (let i = 0; i < buffersCount; i++) { const buffer = buffers[i]; buffer.copy(result, position, 0); position += buffer.length; } return result; }; } Buffer.prototype.toByteArray = funct...
let length = 0; for (let i = 0; i < buffersCount; i++) { const buffer = buffers[i];
random_line_split
test_life_1_05.rs
extern crate game_of_life_parsers; use std::fs::File; use game_of_life_parsers::GameDescriptor; use game_of_life_parsers::Coord; use game_of_life_parsers::Parser; use game_of_life_parsers::Life105Parser; #[test] fn
() { let file = File::open("tests/life_1_05/glider.life").unwrap(); let mut parser = Life105Parser::new(); let gd: Box<GameDescriptor> = parser.parse(Box::new(file)).unwrap(); assert_eq!(&[2, 3], gd.survival()); assert_eq!(&[1], gd.birth()); assert_eq!(&[ // block 1 Coord { x: 0, y: -1 }, Coord { x: 1, y...
parse_file
identifier_name
test_life_1_05.rs
extern crate game_of_life_parsers; use std::fs::File; use game_of_life_parsers::GameDescriptor; use game_of_life_parsers::Coord; use game_of_life_parsers::Parser; use game_of_life_parsers::Life105Parser; #[test] fn parse_file()
{ let file = File::open("tests/life_1_05/glider.life").unwrap(); let mut parser = Life105Parser::new(); let gd: Box<GameDescriptor> = parser.parse(Box::new(file)).unwrap(); assert_eq!(&[2, 3], gd.survival()); assert_eq!(&[1], gd.birth()); assert_eq!(&[ // block 1 Coord { x: 0, y: -1 }, Coord { x: 1, y: 0...
identifier_body
test_life_1_05.rs
extern crate game_of_life_parsers; use std::fs::File; use game_of_life_parsers::GameDescriptor; use game_of_life_parsers::Coord; use game_of_life_parsers::Parser; use game_of_life_parsers::Life105Parser;
let gd: Box<GameDescriptor> = parser.parse(Box::new(file)).unwrap(); assert_eq!(&[2, 3], gd.survival()); assert_eq!(&[1], gd.birth()); assert_eq!(&[ // block 1 Coord { x: 0, y: -1 }, Coord { x: 1, y: 0 }, Coord { x: -1, y: 1 }, Coord { x: 0, y: 1 }, Coord { x: 1, y: 1 }, // block 2 Coord { x: 3, y: 2...
#[test] fn parse_file() { let file = File::open("tests/life_1_05/glider.life").unwrap(); let mut parser = Life105Parser::new();
random_line_split
socket.rs
use chan; use chan::Sender; use rustc_serialize::{Encodable, json}; use std::io::{BufReader, Read, Write}; use std::net::Shutdown; use std::sync::{Arc, Mutex}; use std::{fs, thread}; use datatype::{Command, DownloadFailed, Error, Event}; use super::{Gateway, Interpret}; use unix_socket::{UnixListener, UnixStream}; /...
_ => return }; let _ = UnixStream::connect(&self.events_path).map(|mut stream| { stream.write_all(&output.into_bytes()) .unwrap_or_else(|err| error!("couldn't write to events socket: {}", err)); stream.shutdown(Shutdown::Write) .unwr...
{ json::encode(&EventWrapper { version: "0.1".to_string(), event: "DownloadFailed".to_string(), data: DownloadFailed { update_id: id, reason: reason } }).expect("couldn't encode DownloadFailed event") }
conditional_block