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
hud.js
(function (window) { 'use strict'; window.opspark = window.opspark || {}; var draw = window.opspark.draw, createjs = window.createjs; /* Create a heads-up display for our game showing a scoreand an "integrity meter" which indicates our health. The returned objec...
() { hud.x = canvas.width - hud.getBounds().width - 2; hud.y = 2; } hud.updateScore = function (value) { score += value; txtScore.text = 'score : ' + score + ' / ' + of; layout(); setPosition(); }; ...
setPosition
identifier_name
hud.js
(function (window) { 'use strict'; window.opspark = window.opspark || {}; var draw = window.opspark.draw, createjs = window.createjs; /* Create a heads-up display for our game showing a scoreand an "integrity meter" which indicates our health. The returned objec...
}; hud.kill = function () { createjs.Tween.get(integrityMeter).to({alpha:0}, 1000); }; return hud; }; }(window));
{ createjs.Tween.get(integrityMeter).to({scaleX:value}, 400); if (value === 0) hud.kill(); }
conditional_block
hud.js
(function (window) { 'use strict'; window.opspark = window.opspark || {}; var draw = window.opspark.draw, createjs = window.createjs; /* Create a heads-up display for our game showing a scoreand an "integrity meter" which indicates our health. The returned objec...
function layout() { integrityMeter.x = integrityMeter.y = 2; integrity.x = txtScore.getBounds().width + 4; } function setPosition() { hud.x = canvas.width - hud.getBounds().width - 2; hud.y = 2; } hud.upd...
{ setPosition(); }
identifier_body
three_d_earth.py
from webalchemy import config FREEZE_OUTPUT = 'webglearth.html' class Earth: def __init__(self): self.width = window.innerWidth self.height = window.innerHeight # Earth params self.radius = 0.5 self.segments = 64 self.rotation = 6 self.scene = new(THREE....
self.sphere.rotation.y += 0.0005 self.clouds.rotation.y += 0.0004 requestAnimationFrame(self.wrap(self, self.render)) self.renderer.render(self.scene, self.camera) def createSphere(self, radius, segments): geometry = new(THREE.SphereGeometry, radius, segments, segments) ...
self.angx -= self.mdx/5000 self.mdx -= self.mdx/20 if Math.abs(self.angy + self.mdy/5000) < 3.14/2: self.angy += self.mdy/10000 self.mdy -= self.mdy/20 self.camera.position.x = 1.5 *Math.sin(self.angx) *Math.cos(self.angy) self.camera.posit...
conditional_block
three_d_earth.py
from webalchemy import config FREEZE_OUTPUT = 'webglearth.html' class Earth: def __init__(self): self.width = window.innerWidth self.height = window.innerHeight # Earth params self.radius = 0.5 self.segments = 64 self.rotation = 6 self.scene = new(THREE....
self.mdy += e.screenY - self.my self.mx = e.screenX self.my = e.screenY def mouseup(self, e): self.renderer.domElement.onmousemove = None def mousedown(self, e): self.mx = e.screenX self.my = e.screenY self.renderer.domElement.onmousemove = self.wrap(sel...
def mousemove(self, e): self.mdx += e.screenX - self.mx
random_line_split
three_d_earth.py
from webalchemy import config FREEZE_OUTPUT = 'webglearth.html' class Earth: def __init__(self): self.width = window.innerWidth self.height = window.innerHeight # Earth params self.radius = 0.5 self.segments = 64 self.rotation = 6 self.scene = new(THREE....
(self, e): self.mdx += e.screenX - self.mx self.mdy += e.screenY - self.my self.mx = e.screenX self.my = e.screenY def mouseup(self, e): self.renderer.domElement.onmousemove = None def mousedown(self, e): self.mx = e.screenX self.my = e.screenY s...
mousemove
identifier_name
three_d_earth.py
from webalchemy import config FREEZE_OUTPUT = 'webglearth.html' class Earth: def __init__(self): self.width = window.innerWidth self.height = window.innerHeight # Earth params self.radius = 0.5 self.segments = 64 self.rotation = 6 self.scene = new(THREE....
return wrapper def render(self): if Math.abs(self.mdx) > 1.1 or Math.abs(self.mdy) > 1.1: self.angx -= self.mdx/5000 self.mdx -= self.mdx/20 if Math.abs(self.angy + self.mdy/5000) < 3.14/2: self.angy += self.mdy/10000 self.mdy -= ...
return method.apply(object, arguments)
identifier_body
SmoozedComHook.py
# -*- coding: utf-8 -*- from module.plugins.internal.MultiHook import MultiHook class SmoozedComHook(MultiHook): __name__ = "SmoozedComHook" __type__ = "hook" __version__ = "0.04" __status__ = "testing" __config__ = [("pluginmode" , "all;listed;unlisted", "Use for plugins" ...
__authors__ = [("", "")] def get_hosters(self): user, info = self.account.select() return self.account.get_data(user)['hosters']
("reload" , "bool" , "Reload plugin list" , True ), ("reloadinterval", "int" , "Reload interval in hours" , 12 )] __description__ = """Smoozed.com hook plugin""" __license__ = "GPLv3"
random_line_split
SmoozedComHook.py
# -*- coding: utf-8 -*- from module.plugins.internal.MultiHook import MultiHook class SmoozedComHook(MultiHook): __name__ = "SmoozedComHook" __type__ = "hook" __version__ = "0.04" __status__ = "testing" __config__ = [("pluginmode" , "all;listed;unlisted", "Use for plugins" ...
(self): user, info = self.account.select() return self.account.get_data(user)['hosters']
get_hosters
identifier_name
SmoozedComHook.py
# -*- coding: utf-8 -*- from module.plugins.internal.MultiHook import MultiHook class SmoozedComHook(MultiHook):
__name__ = "SmoozedComHook" __type__ = "hook" __version__ = "0.04" __status__ = "testing" __config__ = [("pluginmode" , "all;listed;unlisted", "Use for plugins" , "all"), ("pluginlist" , "str" , "Plugin list (comma separated)", "" ), ...
identifier_body
font-size.js
window.BOLDGRID = window.BOLDGRID || {}; BOLDGRID.EDITOR = BOLDGRID.EDITOR || {}; BOLDGRID.EDITOR.CONTROLS = BOLDGRID.EDITOR.CONTROLS || {}; BOLDGRID.EDITOR.CONTROLS.GENERIC = BOLDGRID.EDITOR.CONTROLS.GENERIC || {}; ( function( $ ) { 'use strict'; var self, BG = BOLDGRID.EDITOR; BOLDGRID.EDITOR.CONTROLS.GENERIC...
BG.Panel.$element .find( '.panel-body .customize' ) .find( '.section.size' ) .remove(); BG.Panel.$element.find( '.panel-body .customize' ).append( $control ); return $control; }, bind: function() { var $el = BG.Menu.getTarget( BG.Panel.currentControl ), elementSize = $el.css( 'font-size...
random_line_split
enroll_node_not_found.py
# 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, software # distributed under the...
try: node = ironic.node.create(**{'driver': 'fake'}) except exceptions.HttpError as exc: raise utils.Error(_("Can not create node in ironic for unknown" "node: %s") % exc) return node_cache.add_node(node.uuid, ironic=ironic)
from ironic_inspector import utils def hook(introspection_data, **kwargs): ironic = utils.get_client()
random_line_split
enroll_node_not_found.py
# 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, software # distributed under the...
(introspection_data, **kwargs): ironic = utils.get_client() try: node = ironic.node.create(**{'driver': 'fake'}) except exceptions.HttpError as exc: raise utils.Error(_("Can not create node in ironic for unknown" "node: %s") % exc) return node_cache.add_node(n...
hook
identifier_name
enroll_node_not_found.py
# 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, software # distributed under the...
ironic = utils.get_client() try: node = ironic.node.create(**{'driver': 'fake'}) except exceptions.HttpError as exc: raise utils.Error(_("Can not create node in ironic for unknown" "node: %s") % exc) return node_cache.add_node(node.uuid, ironic=ironic)
identifier_body
rangetouch.d.ts
/* * This file is part of 6502.ts, an emulator for 6502 based systems built * in Typescript * * Copyright (c) 2014 -- 2020 Christian Speckner and contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Sof...
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ declare module 'rangetouch' { export interface Options...
* * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
random_line_split
processTemplate.js
'use strict'; (function() { angular.module('openshiftConsole').component('processTemplate', { controller: [ '$filter', '$q', '$scope', '$uibModal', 'APIDiscovery', 'APIService', 'DataService', 'Navigate', 'NotificationsService', 'ProcessedTemplateServic...
} })();
value: ctrl.template.metadata.name }); } }
random_line_split
processTemplate.js
'use strict'; (function() { angular.module('openshiftConsole').component('processTemplate', { controller: [ '$filter', '$q', '$scope', '$uibModal', 'APIDiscovery', 'APIService', 'DataService', 'Navigate', 'NotificationsService', 'ProcessedTemplateServic...
}; var launchConfirmationDialog = function(alerts) { var modalInstance = $uibModal.open({ templateUrl: 'views/modals/confirm.html', controller: 'ConfirmModalController', resolve: { modalConfig: function() { return { alerts: alerts, ...
{ Navigate.toNextSteps(ctrl.templateDisplayName, ctrl.selectedProject.metadata.name); }
conditional_block
processTemplate.js
'use strict'; (function() { angular.module('openshiftConsole').component('processTemplate', { controller: [ '$filter', '$q', '$scope', '$uibModal', 'APIDiscovery', 'APIService', 'DataService', 'Navigate', 'NotificationsService', 'ProcessedTemplateServic...
($filter, $q, $scope, $uibModal, APIDiscovery, APIService, DataService, Navigate, NotificationsService, ...
ProcessTemplate
identifier_name
processTemplate.js
'use strict'; (function() { angular.module('openshiftConsole').component('processTemplate', { controller: [ '$filter', '$q', '$scope', '$uibModal', 'APIDiscovery', 'APIService', 'DataService', 'Navigate', 'NotificationsService', 'ProcessedTemplateServic...
} })();
{ if(ctrl.prefillParameters) { _.each(ctrl.template.parameters, function(parameter) { if (ctrl.prefillParameters[parameter.name]) { parameter.value = ctrl.prefillParameters[parameter.name]; } }); } ctrl.labels = _.map(ctrl.template.labels, function(valu...
identifier_body
simple.py
import math def area(a, b, c): A1 = ((4*math.pi)*a**2) A2 = ((4*math.pi)*b**2) A3 = ((4*math.pi)*c**2) Avg = (A1+A2+A3)/3 return Avg def output(a, b ,c , d, e):
def main(): Name = raw_input("Name: ") Area1 = raw_input("Area of 1st sphere: ") Area2 = raw_input("Area of 2nd sphere: ") Area3 = raw_input("Area of 3rd sphere: ") e = area(int(Area1), int(Area2), int(Area3)) print output(Name, Area1, Area2, Area3, e) main()
return """ Hello there, {}! equation: ((4*math.pi)*{}**2)((4*math.pi)*{}**2)((4*math.pi)*{}**2) Calculating average area of three spheres... the answer is: {} """.format(a, b, c, d, e)
identifier_body
simple.py
import math def area(a, b, c): A1 = ((4*math.pi)*a**2) A2 = ((4*math.pi)*b**2) A3 = ((4*math.pi)*c**2) Avg = (A1+A2+A3)/3 return Avg def output(a, b ,c , d, e): return """ Hello there, {}! equation: ((4*math.pi)*{}**2)((4*math.pi)*{}**2)((4*math.pi)*{}**2) Calculating average area of three spheres... the answer...
(): Name = raw_input("Name: ") Area1 = raw_input("Area of 1st sphere: ") Area2 = raw_input("Area of 2nd sphere: ") Area3 = raw_input("Area of 3rd sphere: ") e = area(int(Area1), int(Area2), int(Area3)) print output(Name, Area1, Area2, Area3, e) main()
main
identifier_name
simple.py
import math def area(a, b, c): A1 = ((4*math.pi)*a**2) A2 = ((4*math.pi)*b**2) A3 = ((4*math.pi)*c**2) Avg = (A1+A2+A3)/3 return Avg def output(a, b ,c , d, e): return """ Hello there, {}! equation: ((4*math.pi)*{}**2)((4*math.pi)*{}**2)((4*math.pi)*{}**2) Calculating average area of three spheres... the answer...
main()
print output(Name, Area1, Area2, Area3, e)
random_line_split
pull_request_file.py
# coding=utf-8 from __future__ import unicode_literals, print_function from flask import request, jsonify, url_for from flask_login import current_user import bugsnag from . import load from webhookdb.tasks.pull_request_file import spawn_page_tasks_for_pull_request_files @load.route('/repos/<owner>/<repo>/pulls/<int:...
bugsnag_ctx = {"owner": owner, "repo": repo, "number": number} bugsnag.configure_request(meta_data=bugsnag_ctx) children = bool(request.args.get("children", False)) result = spawn_page_tasks_for_pull_request_files.delay( owner, repo, number, children=children, requestor_id=current_user....
random_line_split
pull_request_file.py
# coding=utf-8 from __future__ import unicode_literals, print_function from flask import request, jsonify, url_for from flask_login import current_user import bugsnag from . import load from webhookdb.tasks.pull_request_file import spawn_page_tasks_for_pull_request_files @load.route('/repos/<owner>/<repo>/pulls/<int:...
(owner, repo, number): """ Queue tasks to load the pull request files (diffs) for a single pull request into WebhookDB. :statuscode 202: task successfully queued """ bugsnag_ctx = {"owner": owner, "repo": repo, "number": number} bugsnag.configure_request(meta_data=bugsnag_ctx) children ...
pull_request_files
identifier_name
pull_request_file.py
# coding=utf-8 from __future__ import unicode_literals, print_function from flask import request, jsonify, url_for from flask_login import current_user import bugsnag from . import load from webhookdb.tasks.pull_request_file import spawn_page_tasks_for_pull_request_files @load.route('/repos/<owner>/<repo>/pulls/<int:...
""" Queue tasks to load the pull request files (diffs) for a single pull request into WebhookDB. :statuscode 202: task successfully queued """ bugsnag_ctx = {"owner": owner, "repo": repo, "number": number} bugsnag.configure_request(meta_data=bugsnag_ctx) children = bool(request.args.get("ch...
identifier_body
compositor_task.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/. */ //! Communication with the compositor task. use CompositorMsg as ConstellationMsg; use compositor; use euclid::po...
self.send(Msg::GetNativeDisplay(chan)); // If the compositor is shutting down when a paint task // is being created, the compositor won't respond to // this message, resulting in an eventual panic. Instead, // just return None in this case, since the paint task // will ex...
/// Implementation of the abstract `PaintListener` interface. impl PaintListener for Box<CompositorProxy + 'static + Send> { fn native_display(&mut self) -> Option<NativeDisplay> { let (chan, port) = channel();
random_line_split
compositor_task.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/. */ //! Communication with the compositor task. use CompositorMsg as ConstellationMsg; use compositor; use euclid::po...
{ /// A channel to the compositor. pub sender: Box<CompositorProxy + Send>, /// A port on which messages inbound to the compositor can be received. pub receiver: Box<CompositorReceiver>, /// A channel to the constellation. pub constellation_chan: Sender<ConstellationMsg>, /// A channel to t...
InitialCompositorState
identifier_name
compositor_task.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/. */ //! Communication with the compositor task. use CompositorMsg as ConstellationMsg; use compositor; use euclid::po...
fn assign_painted_buffers(&mut self, pipeline_id: PipelineId, epoch: Epoch, replies: Vec<(LayerId, Box<LayerBufferSet>)>, frame_tree_id: FrameTreeId) { self.send(Msg::AssignPaintedBuffer...
{ let (chan, port) = channel(); self.send(Msg::GetNativeDisplay(chan)); // If the compositor is shutting down when a paint task // is being created, the compositor won't respond to // this message, resulting in an eventual panic. Instead, // just return None in this case,...
identifier_body
0001_initial.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings import bawebauth.apps.bawebauth.fields class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ]
operations = [ migrations.CreateModel( name='Device', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=100, verbose_name='name')), ('ident'...
random_line_split
0001_initial.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings import bawebauth.apps.bawebauth.fields class Migration(migrations.Migration):
dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Device', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ...
identifier_body
0001_initial.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings import bawebauth.apps.bawebauth.fields class
(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Device', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primar...
Migration
identifier_name
notify.py
"""Support for Matrix notifications.""" import voluptuous as vol from homeassistant.components.notify import ( ATTR_DATA, ATTR_MESSAGE, ATTR_TARGET, PLATFORM_SCHEMA, BaseNotificationService, ) import homeassistant.helpers.config_validation as cv from .const import DOMAIN, SERVICE_SEND_MESSAGE CON...
return self.hass.services.call( DOMAIN, SERVICE_SEND_MESSAGE, service_data=service_data )
service_data[ATTR_DATA] = data
conditional_block
notify.py
"""Support for Matrix notifications.""" import voluptuous as vol from homeassistant.components.notify import ( ATTR_DATA, ATTR_MESSAGE, ATTR_TARGET, PLATFORM_SCHEMA, BaseNotificationService, ) import homeassistant.helpers.config_validation as cv from .const import DOMAIN, SERVICE_SEND_MESSAGE CON...
(BaseNotificationService): """Send notifications to a Matrix room.""" def __init__(self, default_room): """Set up the Matrix notification service.""" self._default_room = default_room def send_message(self, message="", **kwargs): """Send the message to the Matrix server.""" ...
MatrixNotificationService
identifier_name
notify.py
"""Support for Matrix notifications.""" import voluptuous as vol from homeassistant.components.notify import ( ATTR_DATA, ATTR_MESSAGE, ATTR_TARGET, PLATFORM_SCHEMA, BaseNotificationService, ) import homeassistant.helpers.config_validation as cv from .const import DOMAIN, SERVICE_SEND_MESSAGE CON...
def send_message(self, message="", **kwargs): """Send the message to the Matrix server.""" target_rooms = kwargs.get(ATTR_TARGET) or [self._default_room] service_data = {ATTR_TARGET: target_rooms, ATTR_MESSAGE: message} if (data := kwargs.get(ATTR_DATA)) is not None: se...
"""Set up the Matrix notification service.""" self._default_room = default_room
identifier_body
notify.py
"""Support for Matrix notifications.""" import voluptuous as vol from homeassistant.components.notify import ( ATTR_DATA, ATTR_MESSAGE, ATTR_TARGET, PLATFORM_SCHEMA, BaseNotificationService, ) import homeassistant.helpers.config_validation as cv from .const import DOMAIN, SERVICE_SEND_MESSAGE CON...
def send_message(self, message="", **kwargs): """Send the message to the Matrix server.""" target_rooms = kwargs.get(ATTR_TARGET) or [self._default_room] service_data = {ATTR_TARGET: target_rooms, ATTR_MESSAGE: message} if (data := kwargs.get(ATTR_DATA)) is not None: ser...
def __init__(self, default_room): """Set up the Matrix notification service.""" self._default_room = default_room
random_line_split
sysinfo.rs
use libc::{self, SI_LOAD_SHIFT}; use std::{cmp, mem}; use std::time::Duration; use Result; use errno::Errno; /// System info structure returned by `sysinfo`. #[derive(Copy, Clone)] #[allow(missing_debug_implementations)] // libc::sysinfo doesn't impl Debug pub struct SysInfo(libc::sysinfo); impl SysInfo { /// Re...
/// Current number of processes. pub fn process_count(&self) -> u16 { self.0.procs } /// Returns the amount of swap memory in Bytes. pub fn swap_total(&self) -> u64 { self.scale_mem(self.0.totalswap) } /// Returns the amount of unused swap memory in Bytes. pub fn swap_...
// Truncate negative values to 0 Duration::from_secs(cmp::max(self.0.uptime, 0) as u64) }
random_line_split
sysinfo.rs
use libc::{self, SI_LOAD_SHIFT}; use std::{cmp, mem}; use std::time::Duration; use Result; use errno::Errno; /// System info structure returned by `sysinfo`. #[derive(Copy, Clone)] #[allow(missing_debug_implementations)] // libc::sysinfo doesn't impl Debug pub struct SysInfo(libc::sysinfo); impl SysInfo { /// Re...
(&self) -> u64 { self.scale_mem(self.0.totalram) } /// Returns the amount of completely unused RAM in Bytes. /// /// "Unused" in this context means that the RAM in neither actively used by /// programs, nor by the operating system as disk cache or buffer. It is /// "wasted" RAM since it...
ram_total
identifier_name
_deprecated_nilsimsa.py
# Copyright (C) MetaCarta, Incorporated. # # 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. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; ...
(self, a, b, c, n): """Get accumulator for a transition n between chars a, b, c.""" return (((TRAN[(a+n)&255]^TRAN[b]*(n+n+1))+TRAN[(c)^TRAN[n]])&255) def update(self, data): """Add data to running digest, increasing the accumulators for 0-8 triplets formed by this char and the...
tran3
identifier_name
_deprecated_nilsimsa.py
# Copyright (C) MetaCarta, Incorporated. # # 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. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; ...
if PY3: ch = character else: ch = ord(character) self.count += 1 # incr accumulators for triplets if self.lastch[1] > -1: self.acc[self.tran3(ch, self.lastch[0], self.lastch[1], 0)] +=1 if self.lastc...
triplets formed by this char and the previous 0-3 chars.""" for character in data:
random_line_split
_deprecated_nilsimsa.py
# Copyright (C) MetaCarta, Incorporated. # # 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. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; ...
self.update(data) f.close() def compare(self, otherdigest, ishex=False): """Compute difference in bits between own digest and another. returns -127 to 128; 128 is the same, -127 is different""" bits = 0 myd = self.digest() if ishex: # conv...
break
conditional_block
_deprecated_nilsimsa.py
# Copyright (C) MetaCarta, Incorporated. # # 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. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; ...
def tran3(self, a, b, c, n): """Get accumulator for a transition n between chars a, b, c.""" return (((TRAN[(a+n)&255]^TRAN[b]*(n+n+1))+TRAN[(c)^TRAN[n]])&255) def update(self, data): """Add data to running digest, increasing the accumulators for 0-8 triplets formed by th...
"""Nilsimsa calculator, w/optional list of initial data chunks.""" self.count = 0 # num characters seen self.acc = [0]*256 # accumulators for computing digest self.lastch = [-1]*4 # last four seen characters (-1 until set) if data: if is_iterable_non_string(d...
identifier_body
showdevices.py
#!/usr/bin/python3 """Run 'adb devices' and show results in friendly way. Runs 'adb devices' and integrates the results with environment variables DEVTAGS and ANDROID_SERIAL to show model numbers for connected devices. """ import getopt import os import re import sys import script_utils as u valid_dispositions = {...
(serial_to_tag, tag_to_serial) = read_devtags() lines = u.docmdlines("adb devices") rxd1 = re.compile(r"^\* daemon not running.+$") rxd2 = re.compile(r"^\* daemon started.+$") rx1 = re.compile(r"^\s*(\S+)\s+(\S+)\s*$") devices_found = {} for line in lines[1:]: if rxd1.match(line) or rxd2.match(line):...
andser = ""
conditional_block
showdevices.py
#!/usr/bin/python3 """Run 'adb devices' and show results in friendly way. Runs 'adb devices' and integrates the results with environment variables DEVTAGS and ANDROID_SERIAL to show model numbers for connected devices. """ import getopt import os import re import sys import script_utils as u valid_dispositions = {...
tagtoser = {} for chunk in chunks: (tag, ser) = chunk.split(":") if ser in sertotag: u.error("malformed DEVTAGS (more than one " "entry for serial number %s" % ser) if tag in tagtoser: u.warning("malformed DEVTAGS (more than one " "serial number for tag %s" % ta...
chunks = dt.split(" ") sertotag = {}
random_line_split
showdevices.py
#!/usr/bin/python3 """Run 'adb devices' and show results in friendly way. Runs 'adb devices' and integrates the results with environment variables DEVTAGS and ANDROID_SERIAL to show model numbers for connected devices. """ import getopt import os import re import sys import script_utils as u valid_dispositions = {...
def perform(): """Main driver routine.""" andser = os.getenv("ANDROID_SERIAL") if andser: andser = andser.strip() else: andser = "" (serial_to_tag, tag_to_serial) = read_devtags() lines = u.docmdlines("adb devices") rxd1 = re.compile(r"^\* daemon not running.+$") rxd2 = re.compile(r"^\* daemo...
"""Read and post-process DEVTAGS environment var.""" dt = os.getenv("DEVTAGS") chunks = dt.split(" ") sertotag = {} tagtoser = {} for chunk in chunks: (tag, ser) = chunk.split(":") if ser in sertotag: u.error("malformed DEVTAGS (more than one " "entry for serial number %s" % ser) ...
identifier_body
showdevices.py
#!/usr/bin/python3 """Run 'adb devices' and show results in friendly way. Runs 'adb devices' and integrates the results with environment variables DEVTAGS and ANDROID_SERIAL to show model numbers for connected devices. """ import getopt import os import re import sys import script_utils as u valid_dispositions = {...
(): """Main driver routine.""" andser = os.getenv("ANDROID_SERIAL") if andser: andser = andser.strip() else: andser = "" (serial_to_tag, tag_to_serial) = read_devtags() lines = u.docmdlines("adb devices") rxd1 = re.compile(r"^\* daemon not running.+$") rxd2 = re.compile(r"^\* daemon started.+$")...
perform
identifier_name
files_in_patch.py
#!/usr/bin/env python3 # Copyright 2020 Red Hat, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #...
sys.stderr.write( "Cannot open {}: {}\n".format(curr_input_name, e_str)) sys.exit(255) prune_unwanted_names() print_file_names()
for curr_input_name in sys.argv[1:]: try: with open(curr_input_name, 'r') as curr_input_file: parse_input(curr_input_file) except IOError as e_str:
random_line_split
files_in_patch.py
#!/usr/bin/env python3 # Copyright 2020 Red Hat, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #...
line_match = re.search(r"^\s*---\s+([^\s@]+)[\s@]+", line_buffer) if not line_match: line_match = re.search(r"^\s*\+\+\+\s+([^\s@]+)[\s@]+", line_buffer) if line_match: curr_file_name = line_match.group(1) # trim off 'a/' a...
break
conditional_block
files_in_patch.py
#!/usr/bin/env python3 # Copyright 2020 Red Hat, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #...
(): for name in sorted(file_names): print(name) if __name__ == '__main__': if len(sys.argv) == 1: parse_input(sys.stdin) else: for curr_input_name in sys.argv[1:]: try: with open(curr_input_name, 'r') as curr_input_file: parse_input(c...
print_file_names
identifier_name
files_in_patch.py
#!/usr/bin/env python3 # Copyright 2020 Red Hat, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #...
if __name__ == '__main__': if len(sys.argv) == 1: parse_input(sys.stdin) else: for curr_input_name in sys.argv[1:]: try: with open(curr_input_name, 'r') as curr_input_file: parse_input(curr_input_file) except IOError as e_str: ...
for name in sorted(file_names): print(name)
identifier_body
interfaces.ts
import { Class, IMetadata } from "oly"; /** * Add koa-bodyparser and koa-router to definitions. */ declare module "oly-http/lib/interfaces" { interface IKoaRequest { body: any; } interface IKoaContext { params: { [key: string]: any }; }
} /** * Definition of file used by multer. */ export interface IUploadedFile { fieldname: string; originalname: string; encoding: string; mimetype: string; size: number; buffer: Buffer; } /** * */ export type IMethods = "GET" | "POST" | "DEL" | "PUT" | "PATCH"; /** * */ export interface IRouterTarg...
random_line_split
outgoing_webhook.py
from __future__ import absolute_import from typing import Any, Iterable, Dict, Tuple, Callable, Text, Mapping import requests import json import sys import inspect import logging from six.moves import urllib from functools import reduce from requests import Response from django.utils.translation import ugettext as _ ...
def fail_with_message(event, failure_message): # type: (Dict[str, Any], Text) -> None failure_message = "Failure! " + failure_message send_response_message(event['user_profile_id'], event['message'], failure_message) def request_retry(event, failure_message): # type: (Dict[str, Any], Text) -> None ...
success_message = "Success! " + success_message send_response_message(event['user_profile_id'], event['message'], success_message)
identifier_body
outgoing_webhook.py
from __future__ import absolute_import from typing import Any, Iterable, Dict, Tuple, Callable, Text, Mapping import requests import json import sys import inspect import logging from six.moves import urllib from functools import reduce from requests import Response from django.utils.translation import ugettext as _ ...
# On 50x errors, try retry elif str(response.status_code).startswith('5'): request_retry(event, "unable to connect with the third party.") else: response_data = service_handler.process_failure(response, event) fail_with_message(event, response_data["response...
response_data = service_handler.process_success(response, event) succeed_with_message(event, response_data["response_message"])
conditional_block
outgoing_webhook.py
from __future__ import absolute_import from typing import Any, Iterable, Dict, Tuple, Callable, Text, Mapping import requests import json import sys import inspect import logging from six.moves import urllib from functools import reduce from requests import Response from django.utils.translation import ugettext as _ ...
except requests.exceptions.Timeout: logging.info("Trigger event %s on %s timed out. Retrying" % (event["command"], event['service_name'])) request_retry(event, 'unable to connect with the third party.') except requests.exceptions.RequestException as e: response_message = "An exception ...
response_data = service_handler.process_failure(response, event) fail_with_message(event, response_data["response_message"])
random_line_split
outgoing_webhook.py
from __future__ import absolute_import from typing import Any, Iterable, Dict, Tuple, Callable, Text, Mapping import requests import json import sys import inspect import logging from six.moves import urllib from functools import reduce from requests import Response from django.utils.translation import ugettext as _ ...
(rest_operation, request_data, event, service_handler, timeout=None): # type: (Dict[str, Any], Dict[str, Any], Dict[str, Any], Any, Any) -> None rest_operation_validator = check_dict([ ('method', check_string), ('relative_url_path', check_string), ('request_kwargs', check_dict([])), ...
do_rest_call
identifier_name
fill-in.js
import getElement from './-get-element'; import isFormControl from './-is-form-control'; import { __focus__ } from './focus'; import settled from '../settled'; import fireEvent from './fire-event'; import { nextTickPromise } from '../-utils'; /** Fill the provided text into the `value` property (or set `.innerHTML` ...
{ return nextTickPromise().then(() => { if (!target) { throw new Error('Must pass an element or selector to `fillIn`.'); } let element = getElement(target); if (!element) { throw new Error(`Element not found when calling \`fillIn('${target}')\`.`); } let isControl = isFormControl(...
identifier_body
fill-in.js
import getElement from './-get-element'; import isFormControl from './-is-form-control'; import { __focus__ } from './focus'; import settled from '../settled'; import fireEvent from './fire-event'; import { nextTickPromise } from '../-utils'; /** Fill the provided text into the `value` property (or set `.innerHTML` ...
(target, text) { return nextTickPromise().then(() => { if (!target) { throw new Error('Must pass an element or selector to `fillIn`.'); } let element = getElement(target); if (!element) { throw new Error(`Element not found when calling \`fillIn('${target}')\`.`); } let isControl =...
fillIn
identifier_name
fill-in.js
import getElement from './-get-element'; import isFormControl from './-is-form-control'; import { __focus__ } from './focus'; import settled from '../settled'; import fireEvent from './fire-event'; import { nextTickPromise } from '../-utils'; /** Fill the provided text into the `value` property (or set `.innerHTML` ...
return settled(); }); }
fireEvent(element, 'input'); fireEvent(element, 'change');
random_line_split
fill-in.js
import getElement from './-get-element'; import isFormControl from './-is-form-control'; import { __focus__ } from './focus'; import settled from '../settled'; import fireEvent from './fire-event'; import { nextTickPromise } from '../-utils'; /** Fill the provided text into the `value` property (or set `.innerHTML` ...
fireEvent(element, 'input'); fireEvent(element, 'change'); return settled(); }); }
{ element.innerHTML = text; }
conditional_block
GetMetadata.py
# -*- coding: utf-8 -*- # # Copyright (C) 2007 Johann Prieur <johann.prieur@gmail.com> # # 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, or # (at your option) an...
def soap_body(): """Returns the SOAP xml body""" return """ <GetMetadata xmlns="http://www.hotmail.msn.com/ws/2004/09/oim/rsi" />""" def process_response(soap_response): body = soap_response.body try: return body.find("./rsi:GetMetadataResponse") except AttributeError: r...
"""Returns the SOAPAction value to pass to the transport or None if no SOAPAction needs to be specified""" return "http://www.hotmail.msn.com/ws/2004/09/oim/rsi/GetMetadata"
identifier_body
GetMetadata.py
# -*- coding: utf-8 -*- # # Copyright (C) 2007 Johann Prieur <johann.prieur@gmail.com> # # 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, or # (at your option) an...
(soap_response): body = soap_response.body try: return body.find("./rsi:GetMetadataResponse") except AttributeError: return None
process_response
identifier_name
GetMetadata.py
# -*- coding: utf-8 -*- # # Copyright (C) 2007 Johann Prieur <johann.prieur@gmail.com> # # 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, or # (at your option) an...
# 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. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation...
# This program is distributed in the hope that it will be useful,
random_line_split
edge_outside.rs
use crate::mock_graph::{ arbitrary::{GuidedArbGraph, Limit, VertexOutside}, MockVertex, TestGraph, }; use graphene::{ core::{Ensure, Graph}, impl_ensurer, }; use quickcheck::{Arbitrary, Gen}; use std::collections::HashSet; /// An arbitrary graph and two vertices where at least one is not in the graph. #[derive(Clo...
<G>(pub G, pub MockVertex, pub MockVertex) where G: GuidedArbGraph, G::Graph: TestGraph; impl<G> Ensure for EdgeOutside<G> where G: GuidedArbGraph, G::Graph: TestGraph, { fn ensure_unvalidated(_c: Self::Ensured, _: ()) -> Self { unimplemented!() } fn validate(_c: &Self::Ensured, _: &()) -> bool { unimple...
EdgeOutside
identifier_name
edge_outside.rs
use crate::mock_graph::{ arbitrary::{GuidedArbGraph, Limit, VertexOutside}, MockVertex, TestGraph, }; use graphene::{ core::{Ensure, Graph}, impl_ensurer, }; use quickcheck::{Arbitrary, Gen}; use std::collections::HashSet; /// An arbitrary graph and two vertices where at least one is not in the graph. #[derive(Clo...
where G: GuidedArbGraph, G::Graph: TestGraph, { fn ensure_unvalidated(_c: Self::Ensured, _: ()) -> Self { unimplemented!() } fn validate(_c: &Self::Ensured, _: &()) -> bool { unimplemented!() } } impl_ensurer! { use<G> EdgeOutside<G>: Ensure as (self.0): G where G: GuidedArbGraph, G::Graph: TestGraph...
impl<G> Ensure for EdgeOutside<G>
random_line_split
edge_outside.rs
use crate::mock_graph::{ arbitrary::{GuidedArbGraph, Limit, VertexOutside}, MockVertex, TestGraph, }; use graphene::{ core::{Ensure, Graph}, impl_ensurer, }; use quickcheck::{Arbitrary, Gen}; use std::collections::HashSet; /// An arbitrary graph and two vertices where at least one is not in the graph. #[derive(Clo...
}
{ let mut result = Vec::new(); // Shrink the graph, keeping only the shrunk graphs where the edge is still // invalid. result.extend( self.0 .shrink_guided(limits.clone()) .filter(|g| { !g.graph().contains_vertex(self.1) || !g.graph().contains_vertex(self.2) }) .map(|g| Self(g, self.1, ...
identifier_body
base_app.py
""" base IPOL demo web app includes interaction and rendering """ # TODO add steps (cf amazon cart) import shutil from mako.lookup import TemplateLookup import traceback import cherrypy import os.path import math import copy import threading import time from mako.exceptions import RichTraceback from . import http fr...
(): """ Get an app pool singleton instance """ try: # Acquire lock AppPool.pool_lock.acquire() # Set singleton object instance if AppPool.instance is None: AppPool.instance = AppPool.__AppPool() finally: ...
get_instance
identifier_name
base_app.py
""" base IPOL demo web app includes interaction and rendering """ # TODO add steps (cf amazon cart) import shutil from mako.lookup import TemplateLookup import traceback import cherrypy import os.path import math import copy import threading import time from mako.exceptions import RichTraceback from . import http fr...
self2.init_cfg() # public_archive cookie setup # default value if not cherrypy.request.cookie.get('public_archive', '1') == '0': cherrypy.response.cookie['public_archive'] = '1' self2.cfg['meta']['public'] = True else: self2.cfg['meta']['publi...
random_line_split
base_app.py
""" base IPOL demo web app includes interaction and rendering """ # TODO add steps (cf amazon cart) import shutil from mako.lookup import TemplateLookup import traceback import cherrypy import os.path import math import copy import threading import time from mako.exceptions import RichTraceback from . import http fr...
# Singleton object instance instance = None @staticmethod def get_instance(): """ Get an app pool singleton instance """ try: # Acquire lock AppPool.pool_lock.acquire() # Set singleton object instance if AppPool.instanc...
""" Adds an app object and to the pool. The creation time is also stored """ # Remove stored old app objects self.pool_tidyup() # Add app_object and timestamp entry = {'app_object': app_object, 'timestamp': time.tim...
identifier_body
base_app.py
""" base IPOL demo web app includes interaction and rendering """ # TODO add steps (cf amazon cart) import shutil from mako.lookup import TemplateLookup import traceback import cherrypy import os.path import math import copy import threading import time from mako.exceptions import RichTraceback from . import http fr...
else: firstdate = 'never' limit = 20 nbpage = int(math.ceil(nbtotal / float(limit))) page = int(page) if page == -1: page = nbpage - 1 offset = limit * page buckets = [{'url' : self.archive_url + archiv...
firstdate = archive.index_first_date(self.archive_index, path=self.archive_dir)
conditional_block
setup.py
#!/usr/bin/python # -*- coding: utf-8 -*- import os import setuptools def
(): setuptools.setup( name = "media_editing", version = "2018.03.26.0007", description = "media editing", long_description = long_description(), url = "https://github.com/wdbm/media_editing", author = "Will Breaden Mad...
main
identifier_name
setup.py
#!/usr/bin/python # -*- coding: utf-8 -*- import os import setuptools def main(): setuptools.setup( name = "media_editing", version = "2018.03.26.0007", description = "media editing", long_description = long_description(), url = "htt...
media_editing = media_editing:media_editing """ ) def long_description( filename = "README.md" ): if os.path.isfile(os.path.expandvars(filename)): try: import pypandoc long_description = pypandoc.convert_file(filenam...
[console_scripts]
random_line_split
setup.py
#!/usr/bin/python # -*- coding: utf-8 -*- import os import setuptools def main(): setuptools.setup( name = "media_editing", version = "2018.03.26.0007", description = "media editing", long_description = long_description(), url = "htt...
if __name__ == "__main__": main()
if os.path.isfile(os.path.expandvars(filename)): try: import pypandoc long_description = pypandoc.convert_file(filename, "rst") except ImportError: long_description = open(filename).read() else: long_description = "" return long_description
identifier_body
setup.py
#!/usr/bin/python # -*- coding: utf-8 -*- import os import setuptools def main(): setuptools.setup( name = "media_editing", version = "2018.03.26.0007", description = "media editing", long_description = long_description(), url = "htt...
main()
conditional_block
gly19.py
#!/usr/bin/python # gly19.py -- protein glycosylator # 2016.10.05 -- first version -- John Saeger # gly19 -- 2017.5.27 # This version complains about incomplete sidechains. You must fix them up. # I use pymol's mutate wizard to mutate a residue to itself. # This version has a slightly more sophisticated solvent exp...
(fn, chain): # read selected chain in PDB file try: pdb = [] # clean it up a little for line in open(fn, 'r'): l = line.strip().split() if l[0] != 'ATOM' or l[4] != chain: continue pdb.append([l[0], l[1], l[2], l[3], l[4], l[5]]) except: print("Couldn't read {}".format(fn)) quit() return pdb...
read_pdb
identifier_name
gly19.py
#!/usr/bin/python # gly19.py -- protein glycosylator # 2016.10.05 -- first version -- John Saeger # gly19 -- 2017.5.27 # This version complains about incomplete sidechains. You must fix them up. # I use pymol's mutate wizard to mutate a residue to itself. # This version has a slightly more sophisticated solvent exp...
def helix_score(hydro, seq, n): score = 0 # score -= hydro[seq[n-2]] # hydrophilic # score -= hydro[seq[n-1]] # hydrophilic score -= hydro[seq[n]] # hydrophilic score -= hydro[seq[n+1]] # hydrophilic score -= hydro[seq[n+2]] # hydrophilic # score -= hydro[seq[n+3]] # hydrophilic return score def...
score = 0 score += hydro[seq[n-2]] # hydrophobic score += hydro[seq[n-1]] # hydrophobic score -= hydro[seq[n]] # hydrophilic score += hydro[seq[n+1]] # hydrophobic score -= hydro[seq[n+2]] # hydrophilic score += hydro[seq[n+3]] # hydrophobic return score
identifier_body
gly19.py
#!/usr/bin/python # gly19.py -- protein glycosylator # 2016.10.05 -- first version -- John Saeger # gly19 -- 2017.5.27 # This version complains about incomplete sidechains. You must fix them up. # I use pymol's mutate wizard to mutate a residue to itself. # This version has a slightly more sophisticated solvent exp...
return seq def get_singles(fn, chain): # get solvent exposed atoms from PDB file pdb = read_pdb(fn, chain) resnum = 0 atoms = 0 # we'll be counting sidechain atoms singles = [] for l in pdb: if resnum == 0 and atoms == 0: l=pdb[0] resname = l[3] if l[2] not in ['N', 'C', 'O'] and int(l[5...
oldresnum = resnum oldresname = resname oldatomnum = atomnum resname = l[3] atomnum = 0 if int(l[5]) != resnum+1: # see if there is a resnum skip while resnum < int(l[5])-1: resnum += 1 seq += 'Z' # set to 'Z' if there was a skip resnum += 1 try: seq += res_letters[l[3]...
conditional_block
gly19.py
#!/usr/bin/python # gly19.py -- protein glycosylator # 2016.10.05 -- first version -- John Saeger # gly19 -- 2017.5.27 # This version complains about incomplete sidechains. You must fix them up. # I use pymol's mutate wizard to mutate a residue to itself. # This version has a slightly more sophisticated solvent exp...
stotal_common = sorted(list(total_common)) print("\nThere are {} common potential glycosylation sites:".format(len(stotal_common))) print(stotal_common)
total_common = sheet_common + helix_common + coil_common
random_line_split
remove_concepts_after.py
# -*- coding: utf-8 -*- # An entirely untested jython script to delete all the concepts in the # CATMAID database for a particular project. # # Mark Longair 2010 # # flake8: noqa import os, re, sys, ij from jarray import array from java.sql import DriverManager, Connection, SQLException, Types # Set up the JDBC con...
print >> sys.stderr, 'delete from connector_class_instance'+where s.executeUpdate('delete from connector_class_instance'+where) s.close() ij.IJ.showStatus("Removing concepts from treenode_connector") s = c.createStatement() print >> sys.stderr, 'delete from treenode_connector'+where s.execu...
random_line_split
remove_concepts_after.py
# -*- coding: utf-8 -*- # An entirely untested jython script to delete all the concepts in the # CATMAID database for a particular project. # # Mark Longair 2010 # # flake8: noqa import os, re, sys, ij from jarray import array from java.sql import DriverManager, Connection, SQLException, Types # Set up the JDBC con...
fp.close() database_url = "jdbc:postgresql://%s/%s" % (conf['host'], conf['database']) c = DriverManager.getConnection(database_url, conf['username'], conf['password']) def run(project_id, last_untouched_id): where = ' where id > %d and project_id...
line = line.strip() if len(line) == 0: continue m = re.search('(\S*)\s*:\s*(\S*)', line) if m: conf[m.group(1)] = m.group(2)
conditional_block
remove_concepts_after.py
# -*- coding: utf-8 -*- # An entirely untested jython script to delete all the concepts in the # CATMAID database for a particular project. # # Mark Longair 2010 # # flake8: noqa import os, re, sys, ij from jarray import array from java.sql import DriverManager, Connection, SQLException, Types # Set up the JDBC con...
(project_id, last_untouched_id): where = ' where id > %d and project_id = %d' % (last_untouched_id, project_id) ij.IJ.showStatus("Removing concepts from treenode_class_instance") s = c.createStatement() s.executeUpdate('delete from treenode_class_instance') s.close() ij.IJ.showStatus("Removin...
run
identifier_name
remove_concepts_after.py
# -*- coding: utf-8 -*- # An entirely untested jython script to delete all the concepts in the # CATMAID database for a particular project. # # Mark Longair 2010 # # flake8: noqa import os, re, sys, ij from jarray import array from java.sql import DriverManager, Connection, SQLException, Types # Set up the JDBC con...
gd = ij.gui.GenericDialog('Remove CATMAID Concepts') gd.addNumericField("CATMAID Project ID:", 4, 0) gd.showDialog() if not gd.wasCanceled(): project_id = int(gd.getNextNumber()) s = c.createStatement() rs = s.executeQuery('SELECT id FROM concept WHERE project_id = %d ORDER BY id LIMIT 1' % (project_id,)) r...
where = ' where id > %d and project_id = %d' % (last_untouched_id, project_id) ij.IJ.showStatus("Removing concepts from treenode_class_instance") s = c.createStatement() s.executeUpdate('delete from treenode_class_instance') s.close() ij.IJ.showStatus("Removing concepts from connector_class_instan...
identifier_body
wrapping_square.rs
use malachite_base::num::basic::integers::PrimitiveInt; use malachite_base::num::basic::signeds::PrimitiveSigned; use malachite_base::num::basic::unsigneds::PrimitiveUnsigned; use malachite_base_test_util::generators::{signed_gen, unsigned_gen}; #[test] fn test_wrapping_square() { fn test<T: PrimitiveInt>(x: T, ou...
{ apply_fn_to_unsigneds!(wrapping_square_properties_helper_unsigned); apply_fn_to_signeds!(wrapping_square_properties_helper_signed); }
identifier_body
wrapping_square.rs
use malachite_base::num::basic::integers::PrimitiveInt; use malachite_base::num::basic::signeds::PrimitiveSigned; use malachite_base::num::basic::unsigneds::PrimitiveUnsigned; use malachite_base_test_util::generators::{signed_gen, unsigned_gen}; #[test] fn test_wrapping_square() { fn test<T: PrimitiveInt>(x: T, ou...
<T: PrimitiveUnsigned>() { unsigned_gen::<T>().test_properties(|x| { let mut square = x; square.wrapping_square_assign(); assert_eq!(square, x.wrapping_square()); assert_eq!(square, x.wrapping_pow(2)); }); } fn wrapping_square_properties_helper_signed<T: PrimitiveSigned>() { ...
wrapping_square_properties_helper_unsigned
identifier_name
wrapping_square.rs
use malachite_base::num::basic::integers::PrimitiveInt; use malachite_base::num::basic::signeds::PrimitiveSigned; use malachite_base::num::basic::unsigneds::PrimitiveUnsigned; use malachite_base_test_util::generators::{signed_gen, unsigned_gen}; #[test] fn test_wrapping_square() { fn test<T: PrimitiveInt>(x: T, ou...
}); } #[test] fn saturating_square_properties() { apply_fn_to_unsigneds!(wrapping_square_properties_helper_unsigned); apply_fn_to_signeds!(wrapping_square_properties_helper_signed); }
{ assert_eq!((-x).wrapping_square(), square); }
conditional_block
wrapping_square.rs
use malachite_base::num::basic::integers::PrimitiveInt; use malachite_base::num::basic::signeds::PrimitiveSigned; use malachite_base::num::basic::unsigneds::PrimitiveUnsigned; use malachite_base_test_util::generators::{signed_gen, unsigned_gen}; #[test] fn test_wrapping_square() { fn test<T: PrimitiveInt>(x: T, ou...
assert_eq!(square, x.wrapping_square()); assert_eq!(square, x.wrapping_pow(2)); }); } fn wrapping_square_properties_helper_signed<T: PrimitiveSigned>() { signed_gen::<T>().test_properties(|x| { let mut square = x; square.wrapping_square_assign(); assert_eq!(square, x.wra...
fn wrapping_square_properties_helper_unsigned<T: PrimitiveUnsigned>() { unsigned_gen::<T>().test_properties(|x| { let mut square = x; square.wrapping_square_assign();
random_line_split
wheel.py
"""Support functions for working with wheel files. """ from __future__ import absolute_import import logging from email.parser import Parser from zipfile import ZipFile from pip._vendor.packaging.utils import canonicalize_name from pip._vendor.pkg_resources import DistInfoDistribution from pip._vendor.six import PY2...
def check_compatibility(version, name): # type: (Tuple[int, ...], str) -> None """Raises errors or warns if called with an incompatible Wheel-Version. Pip should refuse to install a Wheel-Version that's a major series ahead of what it's compatible with (e.g 2.0 > 1.1); and warn when installing a...
"""Given WHEEL metadata, return the parsed Wheel-Version. Otherwise, raise UnsupportedWheel. """ version_text = wheel_data["Wheel-Version"] if version_text is None: raise UnsupportedWheel("WHEEL is missing Wheel-Version") version = version_text.strip() try: return tuple(map(int...
identifier_body
wheel.py
"""Support functions for working with wheel files. """ from __future__ import absolute_import import logging from email.parser import Parser from zipfile import ZipFile from pip._vendor.packaging.utils import canonicalize_name from pip._vendor.pkg_resources import DistInfoDistribution from pip._vendor.six import PY2...
if PY2: from zipfile import BadZipfile as BadZipFile else: from zipfile import BadZipFile VERSION_COMPATIBLE = (1, 0) logger = logging.getLogger(__name__) class WheelMetadata(DictMetadata): """Metadata provider that maps metadata decoding exceptions to our internal exception type. """ de...
from email.message import Message from typing import Dict, Tuple from pip._vendor.pkg_resources import Distribution
conditional_block
wheel.py
"""Support functions for working with wheel files. """ from __future__ import absolute_import import logging from email.parser import Parser from zipfile import ZipFile from pip._vendor.packaging.utils import canonicalize_name from pip._vendor.pkg_resources import DistInfoDistribution from pip._vendor.six import PY2...
subdirs = list(set(p.split("/")[0] for p in source.namelist())) info_dirs = [s for s in subdirs if s.endswith('.dist-info')] if not info_dirs: raise UnsupportedWheel(".dist-info directory not found") if len(info_dirs) > 1: raise UnsupportedWheel( "multiple .dist-info direc...
# Zip file path separators must be /
random_line_split
wheel.py
"""Support functions for working with wheel files. """ from __future__ import absolute_import import logging from email.parser import Parser from zipfile import ZipFile from pip._vendor.packaging.utils import canonicalize_name from pip._vendor.pkg_resources import DistInfoDistribution from pip._vendor.six import PY2...
(source, dist_info_dir): # type: (ZipFile, str) -> Message """Return the WHEEL metadata of an extracted wheel, if possible. Otherwise, raise UnsupportedWheel. """ path = "{}/WHEEL".format(dist_info_dir) # Zip file path separators must be / wheel_contents = read_wheel_metadata_file(source, pa...
wheel_metadata
identifier_name
eina_iterator.rs
#![allow(dead_code)] use eina_ffi::*; use libc::*; use std::ptr; pub struct EinaIterator { pub ptr: *mut Eina_Iterator, } impl EinaIterator { /// Return the container of an iterator pub fn get_container(&mut self) -> Option<&mut c_void> { unsafe { let container = eina_iterator_contain...
/// Unlock the container of the iterator /// /// Warning: None of the existing eina data structures are lockable pub fn unlock(&mut self) -> bool { unsafe { match eina_iterator_unlock(self.ptr) { EINA_TRUE => true, _ => false, } } ...
{ unsafe { match eina_iterator_lock(self.ptr) { EINA_TRUE => true, _ => false, } } }
identifier_body
eina_iterator.rs
#![allow(dead_code)] use eina_ffi::*; use libc::*; use std::ptr; pub struct EinaIterator { pub ptr: *mut Eina_Iterator, } impl EinaIterator { /// Return the container of an iterator pub fn get_container(&mut self) -> Option<&mut c_void> { unsafe { let container = eina_iterator_contain...
} }
random_line_split
eina_iterator.rs
#![allow(dead_code)] use eina_ffi::*; use libc::*; use std::ptr; pub struct EinaIterator { pub ptr: *mut Eina_Iterator, } impl EinaIterator { /// Return the container of an iterator pub fn get_container(&mut self) -> Option<&mut c_void> { unsafe { let container = eina_iterator_contain...
(&mut self) { unsafe { eina_iterator_free(self.ptr) } } }
drop
identifier_name
testUtils.js
export const getMockState = { withNoNotes: ()=>({ byId: {}, ids: [], openNoteId: null }), withOneNote: ()=>({ byId: { 'id-123': { id: 'id-123', content: 'Hello World', timestamp: 1 } }, ids: ['id-123'], openNoteId: 'id-123' }), withTwoNotes: ()=>...
withNoOpenNotes: ()=>({ byId: { 'id-123': { id: 'id-123', content: 'Hello World', timestamp: 1 } }, ids: ['id-123'], openNoteId: null }) };
}),
random_line_split
htype.rs
use super::{Result, Error}; #[derive(Debug, PartialEq)] #[allow(non_camel_case_types)] pub enum
{ Ethernet_10mb = 1, Experimental_Ethernet_3mb, Amateur_Radio_AX_25, Proteon_ProNET_Token_Ring, Chaos, IEEE_802_Networks, Arcnet, Hyperchannel, Lanstar, Autonet_Short_Address, LocalTalk, LocalNet, Ultra_link, SMDS, Frame_Relay, Asynchronous_Transmission_M...
Htype
identifier_name
htype.rs
use super::{Result, Error}; #[derive(Debug, PartialEq)] #[allow(non_camel_case_types)] pub enum Htype { Ethernet_10mb = 1, Experimental_Ethernet_3mb, Amateur_Radio_AX_25, Proteon_ProNET_Token_Ring, Chaos, IEEE_802_Networks, Arcnet, Hyperchannel, Lanstar, Autonet_Short_Address, ...
15u8 => Ok(Htype::Frame_Relay), 16u8 => Ok(Htype::Asynchronous_Transmission_Mode), _ => Err(Error::ParseError(format!("Unknown Htype {:?}", byte))) } } }
random_line_split
ChildAxis.tests.ts
import * as chai from 'chai'; import * as slimdom from 'slimdom'; import jsonMlMapper from 'test-helpers/jsonMlMapper'; import { evaluateXPathToFirstNode, evaluateXPathToNodes, getBucketForSelector, IDomFacade, } from 'fontoxpath'; let documentNode;
beforeEach(() => { documentNode = new slimdom.Document(); }); describe('child', () => { it('parses child::', () => { jsonMlMapper.parse(['someParentElement', ['someElement']], documentNode); chai.assert( evaluateXPathToFirstNode('child::someElement', documentNode.documentElement) === documentNode.document...
random_line_split
regress-474769.js
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* 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/. */ var gTestfile = 'regress-474769.js...
{ enterFunc ('test'); printBugNumber(BUGNUMBER); printStatus (summary); expect = 1; jit(true); for each (b in [1, 1, 1, 1.5, 1, 1]) { (function() { for each (let h in [0, 0, 1.4, ""]) {} })(); } actual = b; jit(false); reportCompare(expect, actual, summary); exitFunc ('test'); }
//----------------------------------------------------------------------------- function test()
random_line_split
regress-474769.js
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* 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/. */ var gTestfile = 'regress-474769.js...
{ enterFunc ('test'); printBugNumber(BUGNUMBER); printStatus (summary); expect = 1; jit(true); for each (b in [1, 1, 1, 1.5, 1, 1]) { (function() { for each (let h in [0, 0, 1.4, ""]) {} })(); } actual = b; jit(false); reportCompare(expect, actual, summary); exitFunc ('test'); }
identifier_body
regress-474769.js
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* 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/. */ var gTestfile = 'regress-474769.js...
() { enterFunc ('test'); printBugNumber(BUGNUMBER); printStatus (summary); expect = 1; jit(true); for each (b in [1, 1, 1, 1.5, 1, 1]) { (function() { for each (let h in [0, 0, 1.4, ""]) {} })(); } actual = b; jit(false); reportCompare(expect, actual, summary); exitFunc ('test'); }
test
identifier_name
test-signal-handler.js
// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modi...
}, 1); // Test addListener condition where a watcher for SIGNAL // has been previously registered, and `process.listeners(SIGNAL).length === 1` process.addListener('SIGHUP', function () {}); process.removeAllListeners('SIGHUP'); process.addListener('SIGHUP', function () { sighup = true }); process.kill(process.pid, '...
{ process.kill(process.pid, 'SIGUSR1'); }
conditional_block
test-signal-handler.js
// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modi...
}); process.addListener('SIGUSR1', function() { second += 1; setTimeout(function() { console.log('End.'); process.exit(0); }, 5); }); var i = 0; setInterval(function() { console.log('running process...' + ++i); if (i == 5) { process.kill(process.pid, 'SIGUSR1'); } }, 1); // Test addListener ...
random_line_split