file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
editor-gtk.py
#! /usr/bin/env python import sys import os import gtk from arithmetic import Parser class Editor(object): 'A minimal editor' def __init__(self): # path to UI file scriptPath = os.path.split( sys.argv[0] )[0] uiFilePath = os.path.join( scriptPath,'editor.ui' ) self.builder = ...
parser.parse( textbuffer ) if __name__ == '__main__': editor = Editor() editor.run()
parser = ParserGTK()
random_line_split
editor-gtk.py
#! /usr/bin/env python import sys import os import gtk from arithmetic import Parser class Editor(object): 'A minimal editor' def __init__(self): # path to UI file scriptPath = os.path.split( sys.argv[0] )[0] uiFilePath = os.path.join( scriptPath,'editor.ui' ) self.builder = ...
( self, i, textBuffer, start, end, text ): 'Write text in line i of lines from start to end offset.' # Delete if end > start: # handle start at end of line or beyond iter_line = textBuffer.get_iter_at_line( i ) nchars = iter_line.get_chars_in_line() ...
writeResult
identifier_name
editor-gtk.py
#! /usr/bin/env python import sys import os import gtk from arithmetic import Parser class Editor(object): 'A minimal editor' def __init__(self): # path to UI file scriptPath = os.path.split( sys.argv[0] )[0] uiFilePath = os.path.join( scriptPath,'editor.ui' ) self.builder = ...
if __name__ == '__main__': editor = Editor() editor.run()
'Perform arithmetic operations' if event.keyval == gtk.keysyms.F5: parser = ParserGTK() parser.parse( textbuffer )
identifier_body
LinkingManager.js
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow */...
/** * Get the original URL that the page was opened to. * Returns a Promise that is resolved with the string of the initial URL. * @param success - ID of success callback */ $getInitialURL(success: number, fail: number) { this._rnctx.invokeCallback(success, [initialURL]); } }
{ this._rnctx.invokeCallback(success, [true]); }
identifier_body
LinkingManager.js
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow */...
(url: string, success: number, fail: number) { this._rnctx.invokeCallback(success, [true]); } /** * Get the original URL that the page was opened to. * Returns a Promise that is resolved with the string of the initial URL. * @param success - ID of success callback */ $getInitialURL(success: numbe...
$canOpenURL
identifier_name
LinkingManager.js
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow */...
} /** * Get the original URL that the page was opened to. * Returns a Promise that is resolved with the string of the initial URL. * @param success - ID of success callback */ $getInitialURL(success: number, fail: number) { this._rnctx.invokeCallback(success, [initialURL]); } }
* @param fail - ID of fail call back */ $canOpenURL(url: string, success: number, fail: number) { this._rnctx.invokeCallback(success, [true]);
random_line_split
packet.rs
//! SIMD intersection result use crate::geometry::{f32xN, m32xN, V3DxN}; use crate::intersection::Isect; /// Intersection result #[derive(Copy, Clone, Debug)] pub struct IsectxN { pub t: f32xN, pub p: V3DxN, pub n: V3DxN, pub hit: m32xN, } impl Default for IsectxN { #[inline] fn
() -> Self { Self { t: f32xN::splat(1e17), hit: m32xN::splat(false), p: V3DxN::default(), n: V3DxN::default(), } } } impl IsectxN { pub fn get(&self, idx: usize) -> Isect { Isect { t: self.t.extract(idx), p: self.p....
default
identifier_name
packet.rs
//! SIMD intersection result use crate::geometry::{f32xN, m32xN, V3DxN}; use crate::intersection::Isect; /// Intersection result #[derive(Copy, Clone, Debug)] pub struct IsectxN { pub t: f32xN, pub p: V3DxN, pub n: V3DxN, pub hit: m32xN, }
impl Default for IsectxN { #[inline] fn default() -> Self { Self { t: f32xN::splat(1e17), hit: m32xN::splat(false), p: V3DxN::default(), n: V3DxN::default(), } } } impl IsectxN { pub fn get(&self, idx: usize) -> Isect { Isect { ...
random_line_split
packet.rs
//! SIMD intersection result use crate::geometry::{f32xN, m32xN, V3DxN}; use crate::intersection::Isect; /// Intersection result #[derive(Copy, Clone, Debug)] pub struct IsectxN { pub t: f32xN, pub p: V3DxN, pub n: V3DxN, pub hit: m32xN, } impl Default for IsectxN { #[inline] fn default() -> ...
} impl IsectxN { pub fn get(&self, idx: usize) -> Isect { Isect { t: self.t.extract(idx), p: self.p.get(idx), n: self.n.get(idx), hit: self.hit.extract(idx), } } }
{ Self { t: f32xN::splat(1e17), hit: m32xN::splat(false), p: V3DxN::default(), n: V3DxN::default(), } }
identifier_body
index.tsx
import * as React from 'react'; import { Button, ButtonProps, Label, Progress } from 'semantic-ui-react'; import { Enchantment, ItemStack, PotionEffect } from '../../fetch'; import { formatRange } from '../Util'; const getRoman: (num: number) => string = (num: number) => { if (num === 1) { return 'I'; } if (num ...
}; const getAmplifier: (effect: PotionEffect) => string = (effect: PotionEffect) => getRoman(effect.amplifier + 1); const itemStackStyle = { display: 'inline-block', verticalAlign: 'top', margin: '0.1em', padding: '0.2em', border: '1px solid rgba(34,36,38,.1)', borderRadius: '.28571429rem' }; export interface ...
} if (num === 5) { return 'V'; } return '';
random_line_split
index.tsx
import * as React from 'react'; import { Button, ButtonProps, Label, Progress } from 'semantic-ui-react'; import { Enchantment, ItemStack, PotionEffect } from '../../fetch'; import { formatRange } from '../Util'; const getRoman: (num: number) => string = (num: number) => { if (num === 1) { return 'I'; } if (num ...
() { const { item } = this.props; if (item.quantity <= 1) { return null; } return ( <Label size="tiny" color="blue"> x{item.quantity} </Label> ); } private renderEnchantments() { const { item } = this.props; if (!item.enchantments) { return null; } const renderEnchant = (enchant:...
renderQuantity
identifier_name
index.tsx
import * as React from 'react'; import { Button, ButtonProps, Label, Progress } from 'semantic-ui-react'; import { Enchantment, ItemStack, PotionEffect } from '../../fetch'; import { formatRange } from '../Util'; const getRoman: (num: number) => string = (num: number) => { if (num === 1) { return 'I'; } if (num ...
percent={percent} style={{ margin: '0 0 .5em 0' }} /> ); } private renderQuantity() { const { item } = this.props; if (item.quantity <= 1) { return null; } return ( <Label size="tiny" color="blue"> x{item.quantity} </Label> ); } private renderEnchantments() { const { item ...
{ const { item } = this.props; if (!item.durability) { return null; } if (item.durability.unbreakable) { return <Label size="tiny">Unbreakable</Label>; } const percent = formatRange( item.durability.durability, item.useLimit ? item.useLimit : 0 ); return ( <Progress progress s...
identifier_body
index.tsx
import * as React from 'react'; import { Button, ButtonProps, Label, Progress } from 'semantic-ui-react'; import { Enchantment, ItemStack, PotionEffect } from '../../fetch'; import { formatRange } from '../Util'; const getRoman: (num: number) => string = (num: number) => { if (num === 1) { return 'I'; } if (num ...
return ( <Label size="tiny" color="blue"> x{item.quantity} </Label> ); } private renderEnchantments() { const { item } = this.props; if (!item.enchantments) { return null; } const renderEnchant = (enchant: Enchantment) => ( <Label color="purple" size="tiny" key={enchant.id}> {encha...
{ return null; }
conditional_block
test_tasks_base.py
# Copyright (c) 2014 Mirantis Inc. # # 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, ...
@base.task(before=[tenant.delete]) def delete(self): self.env.cloud.nova.servers.delete(self.data) class TenantWorkload(base.Resource): @Tenant() def tenant(self): return self.data @base.Collection(Server) def servers(self): return self.env.cloud.nova.servers.list(se...
server = self.data.copy() server.pop("tenant") server["tenant_id"] = self.tenant["id"] self.data = self.env.cloud.nova.servers.create(server)
identifier_body
test_tasks_base.py
# Copyright (c) 2014 Mirantis Inc. # # 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, ...
(cls, data): try: tenant_id = data["tenant_id"] except KeyError: tenant_id = Tenant.get_id_for(data["tenant"]) return (tenant_id, super(Server, cls).get_id_for(data)) @Tenant() def tenant(self): if "tenant_id" in self.data: return {"id": self....
get_id_for
identifier_name
test_tasks_base.py
# Copyright (c) 2014 Mirantis Inc. # # 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, ...
elif "tenant" in self.data: return self.data["tenant"] else: assert False @base.task(requires=[tenant.create]) def create(self): server = self.data.copy() server.pop("tenant") server["tenant_id"] = self.tenant["id"] self.data = self.env.c...
return {"id": self.data["tenant_id"]}
conditional_block
test_tasks_base.py
# Copyright (c) 2014 Mirantis Inc. # # 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, ...
from pumphouse.tasks import base class Tenant(base.Resource): @base.task def create(self): self.data = self.env.cloud.keystone.tenants.create(self.data) @base.task def delete(self): self.env.cloud.keystone.tenants.delete(self.data["id"]) class Server(base.Resource): @classmethod...
random_line_split
defaultsettings.js
/** * "Language Key" : { * "languageDirection": "rtl or ltr" // for example english is left to right but arabic is right to left * "servicesUrl": // where we pull the services data from. This can be a local (ex. js/a.json) or an external url (ex. http://my-website/a.json) * "languageName": // The la...
services.factory('DefaultSettings', [function () { return { version: 'v0.21.0', defaultLanguage: "EN", mapTileAPI: null, includePolygons: false, defaultLogo: "images/logo.png", feedbackEndpoint: false, analyticsId: false, languages: {}, fields:...
var services = angular.module('services');
random_line_split
home.component.ts
import { Component } from '@angular/core'; import { DemoSources, DemoSourceType, MyItem } from '../shared/interfaces'; import { globalScope as scopes, demoList as demos } from '../routes'; import { Datasource, IAdapter } from '../../../public_api'; // from 'ngx-ui-scroll'; @Component({ selector: 'app-home', temp...
() { this.datasource.adapter.reload(this.reloadIndex); } }
doReload
identifier_name
home.component.ts
import { Component } from '@angular/core'; import { DemoSources, DemoSourceType, MyItem } from '../shared/interfaces'; import { globalScope as scopes, demoList as demos } from '../routes'; import { Datasource, IAdapter } from '../../../public_api'; // from 'ngx-ui-scroll'; @Component({ selector: 'app-home', temp...
if (this.delay) { setTimeout(() => success(data), this.delay); } else { success(data); } }, settings: { padding: 0.5, bufferSize: 15, itemSize: 25, startIndex: 1 }, devSettings: { debug: false } }); sources: DemoSources = [{ na...
for (let i = index; i <= index + count - 1; i++) { data.push({ id: i, text: 'item #' + i }); }
random_line_split
home.component.ts
import { Component } from '@angular/core'; import { DemoSources, DemoSourceType, MyItem } from '../shared/interfaces'; import { globalScope as scopes, demoList as demos } from '../routes'; import { Datasource, IAdapter } from '../../../public_api'; // from 'ngx-ui-scroll'; @Component({ selector: 'app-home', temp...
doReload() { this.datasource.adapter.reload(this.reloadIndex); } }
{ this.scopes = scopes; this.demos = demos; }
identifier_body
home.component.ts
import { Component } from '@angular/core'; import { DemoSources, DemoSourceType, MyItem } from '../shared/interfaces'; import { globalScope as scopes, demoList as demos } from '../routes'; import { Datasource, IAdapter } from '../../../public_api'; // from 'ngx-ui-scroll'; @Component({ selector: 'app-home', temp...
if (this.delay) { setTimeout(() => success(data), this.delay); } else { success(data); } }, settings: { padding: 0.5, bufferSize: 15, itemSize: 25, startIndex: 1 }, devSettings: { debug: false } }); sources: DemoSources = [{ n...
{ data.push({ id: i, text: 'item #' + i }); }
conditional_block
select.js
import Ember from 'ember'; const { A, Route } = Ember; export default Route.extend({ model()
id: 4, name: 'Bear', longName: 'Hungry Bear', })); animalOptions.push(this.store.createRecord('animal', { id: 5, name: 'Rabbit', longName: 'Great Rabbit', })); animalOptions.push(this.store.createRecord('animal', { id: 6, name: 'Tiger', longName: 'Wi...
{ var animalOptions = A(); animalOptions.push(this.store.createRecord('animal', { id: 1, name: 'Dog', longName: 'Big Dog', })); animalOptions.push(this.store.createRecord('animal', { id: 2, name: 'Cat', longName: 'Shit Cat', })); animalOptions.push(this.stor...
identifier_body
select.js
import Ember from 'ember'; const { A, Route } = Ember; export default Route.extend({ model() { var animalOptions = A(); animalOptions.push(this.store.createRecord('animal', { id: 1, name: 'Dog', longName: 'Big Dog', })); animalOptions.push(this.store.createRecord('animal', { ...
id: 5, name: 'Rabbit', longName: 'Great Rabbit', })); animalOptions.push(this.store.createRecord('animal', { id: 6, name: 'Tiger', longName: 'Wimpy Tiger', })); let colorOptions = A([ 'Red', 'Green', 'Blue', 'Yellow', ]), n...
})); animalOptions.push(this.store.createRecord('animal', {
random_line_split
select.js
import Ember from 'ember'; const { A, Route } = Ember; export default Route.extend({
() { var animalOptions = A(); animalOptions.push(this.store.createRecord('animal', { id: 1, name: 'Dog', longName: 'Big Dog', })); animalOptions.push(this.store.createRecord('animal', { id: 2, name: 'Cat', longName: 'Shit Cat', })); animalOptions.push(this.s...
model
identifier_name
client.py
import socket import argparse import sys import magic_ping import os import settings import signal import logging import struct logging.basicConfig(format=u'%(levelname)-8s [%(asctime)s] %(message)s', level=logging.DEBUG, filename=u'client.log') # Обработка CTRL+C def signal_handler(signal, frame): print("\nSTOP...
while True: data = file.read(settings.DATA_SIZE) if arguments.cypher: data = [a ^ b for (a, b) in zip(data, settings.KEY)] # шифруем XORом с ключом data = bytes(data) if not data: break already_sent += len(data) packet_number += 1 ...
p.parse_args(sys.argv[1:]) file = arguments.file file_name = file.name file_size = os.stat(file_name).st_size address = arguments.address ID = 1 s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) packet_number = 1 data = file_name.encode() if arguments.cypher: ...
conditional_block
client.py
import socket import argparse import sys import magic_ping import os import settings import signal import logging import struct logging.basicConfig(format=u'%(levelname)-8s [%(asctime)s] %(message)s', level=logging.DEBUG, filename=u'client.log') # Обработка CTRL+C def signal_handler(signal, frame): print("\nSTOP...
signal.signal(signal.SIGINT, signal_handler) if __name__ == '__main__': p = create_cmd_parser() arguments = p.parse_args(sys.argv[1:]) file = arguments.file file_name = file.name file_size = os.stat(file_name).st_size address = arguments.address ID = 1 s = socket.socket(socket.AF_INET, ...
parser.add_argument('-c', '--cypher', action='store_const', const=True) return parser
random_line_split
client.py
import socket import argparse import sys import magic_ping import os import settings import signal import logging import struct logging.basicConfig(format=u'%(levelname)-8s [%(asctime)s] %(message)s', level=logging.DEBUG, filename=u'client.log') # Обработка CTRL+C def signal_ha
frame): print("\nSTOP CLIENT.") logging.info("STOP CLIENT.") exit(0) # Парсер аргументов командной строки def create_cmd_parser(): parser = argparse.ArgumentParser() parser.add_argument('-f', '--file', required=True, type=argparse.FileType(mode='rb')) parser.add_argument('-a', '--address', req...
ndler(signal,
identifier_name
client.py
import socket import argparse import sys import magic_ping import os import settings import signal import logging import struct logging.basicConfig(format=u'%(levelname)-8s [%(asctime)s] %(message)s', level=logging.DEBUG, filename=u'client.log') # Обработка CTRL+C def signal_handler(signal, frame): print("\nSTOP...
ndler) if __name__ == '__main__': p = create_cmd_parser() arguments = p.parse_args(sys.argv[1:]) file = arguments.file file_name = file.name file_size = os.stat(file_name).st_size address = arguments.address ID = 1 s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) ...
arser.add_argument('-f', '--file', required=True, type=argparse.FileType(mode='rb')) parser.add_argument('-a', '--address', required=True) parser.add_argument('-c', '--cypher', action='store_const', const=True) return parser signal.signal(signal.SIGINT, signal_ha
identifier_body
__init__.py
############################################################################### # This file is part of openWNS (open Wireless Network Simulator) # _____________________________________________________________________________ # # Copyright (C) 2004-2007 # Chair of Communication Networks (ComNets) # Kopernikusstr. 16, D-...
############################################################################## #from Cleanup import * #from Documentation import * #from ForEach import * #from Install import * #from Lint import * #from Missing import * #from Replay import * #from SanityCheck import *# #f#rom Testing import * #f#rom Update import * #f...
# details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. #
random_line_split
stats.rs
// Copyright (c) 2014 Richard Diamond & contributors. // // This file is part of Rust Rocket. // // Rust Rocket is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (...
use std::collections::HashMap; use address::Address; enum Message { } #[deriving(Clone, Encodable, Decodable)] pub struct Router { /// Every train yard has its own entry here: time: Vec<u64>, } #[deriving(Encodable, Decodable)] struct Session { times: HashMap<Address, u64>, } #[deriving(Clone)] pub...
use std::comm::Sender;
random_line_split
stats.rs
// Copyright (c) 2014 Richard Diamond & contributors. // // This file is part of Rust Rocket. // // Rust Rocket is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (...
{ times: HashMap<Address, u64>, } #[deriving(Clone)] pub struct SessionIf { chan: Sender<Message>, }
Session
identifier_name
tests.py
#!/usr/bin/python # This script generates a list of testsuites that should be run as part of # the Samba test suite. # The output of this script is parsed by selftest.pl, which then decides # which of the tests to actually run. It will, for example, skip all tests # listed in selftest/skip or only run a subset during ...
planpythontestsuite("none", "samba.tests.graph_utils") planpythontestsuite("none", "samba.tests.ldif_utils") plantestsuite("wafsamba.duplicate_symbols", "none", [os.path.join(srcdir(), "buildtools/wafsamba/test_duplicate_symbol.sh")])
random_line_split
tests.py
#!/usr/bin/python # This script generates a list of testsuites that should be run as part of # the Samba test suite. # The output of this script is parsed by selftest.pl, which then decides # which of the tests to actually run. It will, for example, skip all tests # listed in selftest/skip or only run a subset during ...
planpythontestsuite("none", "selftest.tests.test_suite", extra_path=[srcdir()]) try: import testscenarios except ImportError: skiptestsuite("subunit", "testscenarios not available") else: planpythontestsuite("none", "subunit.tests.test_suite") planpythontestsuite("none", "samba.tests.blackbox.ndrdump") pl...
planpythontestsuite("none", "samba.tests.docs")
conditional_block
dict.py
# python-modeled # # Copyright (C) 2014 Stefan Zimmermann <zimmermann.code@gmail.com> # # python-modeled is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your op...
return member.type.__getitem__(cls, modeled.dict[mtypes]) @property def itemtype(cls): return cls.mtype.mtype @property def keytype(cls): return cls.mtype.mtype.mtypes[0] @property def valuetype(cls): return cls.mtype.mtype.mtypes[1] meta.__name__ = 'member.di...
def __getitem__(cls, mtypes):
random_line_split
dict.py
# python-modeled # # Copyright (C) 2014 Stefan Zimmermann <zimmermann.code@gmail.com> # # python-modeled is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your op...
else: self.valuename = 'value' Dict.__name__ = 'member.dict'
self.valuename = decamelize(self.valuetype.__name__)
conditional_block
dict.py
# python-modeled # # Copyright (C) 2014 Stefan Zimmermann <zimmermann.code@gmail.com> # # python-modeled is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your op...
(self): return self.mtype.mtype.mtypes[1] def __init__(self, items=None, **options): if items is None: items = {} try: assert(issubclass(self.mtype, modeled.dict)) except AttributeError: items = modeled.dict(items) self.__class__ = typ...
valuetype
identifier_name
dict.py
# python-modeled # # Copyright (C) 2014 Stefan Zimmermann <zimmermann.code@gmail.com> # # python-modeled is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your op...
meta.__name__ = 'member.dict.meta' class Dict(with_metaclass(meta, member)): __module__ = 'modeled' @property def itemtype(self): return self.mtype.mtype @property def keytype(self): return self.mtype.mtype.mtypes[0] @property def valuetype(self): return self.m...
@cached def __getitem__(cls, mtypes): return member.type.__getitem__(cls, modeled.dict[mtypes]) @property def itemtype(cls): return cls.mtype.mtype @property def keytype(cls): return cls.mtype.mtype.mtypes[0] @property def valuetype(cls): return cls.mtype.m...
identifier_body
pilfile.py
#!/Users/tiradoe/Projects/Giflocker/bin/python3 # # The Python Imaging Library. # $Id$ # # a utility to identify image files # # this script identifies image files, extracting size and # pixel mode information for known file formats. Note that # you don't need the PIL C extension to use this module. # # History: # 0.0...
print() if verify: try: im.verify() except: if not quiet: print("failed to verify image", end=' ') print("(%s:%s)" % (sys.exc_info()[0], sys.exc_info()[1])) except IOError as v: if not quiet: ...
print(im.info, im.tile, end=' ')
conditional_block
pilfile.py
#!/Users/tiradoe/Projects/Giflocker/bin/python3 # # The Python Imaging Library. # $Id$ # # a utility to identify image files # # this script identifies image files, extracting size and # pixel mode information for known file formats. Note that # you don't need the PIL C extension to use this module. # # History: # 0.0...
(files): # expand wildcards where necessary if sys.platform == "win32": out = [] for file in files: if glob.has_magic(file): out.extend(glob.glob(file)) else: out.append(file) return out return files for file in globfix(args): ...
globfix
identifier_name
pilfile.py
#!/Users/tiradoe/Projects/Giflocker/bin/python3 # # The Python Imaging Library. # $Id$ # # a utility to identify image files # # this script identifies image files, extracting size and # pixel mode information for known file formats. Note that # you don't need the PIL C extension to use this module. # # History: # 0.0...
from PIL import Image if len(sys.argv) == 1: print("PIL File 0.4/2003-09-30 -- identify image files") print("Usage: pilfile [option] files...") print("Options:") print(" -f list supported file formats") print(" -i show associated info and tile data") print(" -v verify file headers") ...
import sys
random_line_split
pilfile.py
#!/Users/tiradoe/Projects/Giflocker/bin/python3 # # The Python Imaging Library. # $Id$ # # a utility to identify image files # # this script identifies image files, extracting size and # pixel mode information for known file formats. Note that # you don't need the PIL C extension to use this module. # # History: # 0.0...
for file in globfix(args): try: im = Image.open(file) print("%s:" % file, im.format, "%dx%d" % im.size, im.mode, end=' ') if verbose: print(im.info, im.tile, end=' ') print() if verify: try: im.verify() except: ...
if sys.platform == "win32": out = [] for file in files: if glob.has_magic(file): out.extend(glob.glob(file)) else: out.append(file) return out return files
identifier_body
analysis.py
""" Utilities for structure analysis. """ from . import measure from .atoms import Selection __all__ = ['hydrogen_bonds', 'HydrogenBond']
Represents hydrogen bond. @ivar: Hydrogen donor atom @ivar: Hydrogen atom @ivar: Hydrogen acceptor atom """ def __init__(self, donor, hydrogen, acceptor): self.donor = donor self.hydrogen = hydrogen self.acceptor = acceptor def __repr__(self): return '<%s: %...
class HydrogenBond(object): """
random_line_split
analysis.py
""" Utilities for structure analysis. """ from . import measure from .atoms import Selection __all__ = ['hydrogen_bonds', 'HydrogenBond'] class HydrogenBond(object): """ Represents hydrogen bond. @ivar: Hydrogen donor atom @ivar: Hydrogen atom @ivar: Hydrogen acceptor atom """ def __init...
def hydrogen_bonds(donors, acceptors=None, distance=3.0, angle=135): """ Returns iterator of hydrogen bonds between the selections. @param donors: Hydrogen donors selection @type donors: Selection @param acceptors: Hydrogen acceptors selection @type donors: Selection or None @param dista...
yield HydrogenBond(donor, hydrogen, acceptor)
conditional_block
analysis.py
""" Utilities for structure analysis. """ from . import measure from .atoms import Selection __all__ = ['hydrogen_bonds', 'HydrogenBond'] class HydrogenBond(object): """ Represents hydrogen bond. @ivar: Hydrogen donor atom @ivar: Hydrogen atom @ivar: Hydrogen acceptor atom """ def __init...
def _get_bonds(donor, acceptor, donor_hydrogens, angle): # Utility function which finds hydrogen bonds between donor atom and acceptor atom hydrogens = (a for a in donor.bonded if a in donor_hydrogens) for hydrogen in hydrogens: # Check the angle. If it's big enough, then it is a hydrogen bond ...
return not self.__eq__(other)
identifier_body
analysis.py
""" Utilities for structure analysis. """ from . import measure from .atoms import Selection __all__ = ['hydrogen_bonds', 'HydrogenBond'] class HydrogenBond(object): """ Represents hydrogen bond. @ivar: Hydrogen donor atom @ivar: Hydrogen atom @ivar: Hydrogen acceptor atom """ def __init...
(self): return '<%s: %s--%s..%s>' % (type(self).__name__, self.donor, self.hydrogen, self.acceptor) def __eq__(self, other): return type(self) == type(other) and self.donor == other.donor and self.hydrogen == other.hydrogen and \ self.acceptor == other.acceptor def __ne__(self, oth...
__repr__
identifier_name
common.py
""" Django settings for accountant project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ import os import sys from decimal import Decimal import accounting V...
# Emailing DEFAULT_FROM_EMAIL = 'noreply@accountant.fr' # Templates # https://docs.djangoproject.com/en/1.7/ref/settings/#template-context-processors from accounting import ACCOUNTING_TEMPLATE_CONTEXT_PROCESSORS TEMPLATE_CONTEXT_PROCESSORS = ( 'django.contrib.auth.context_processors.auth', 'allauth.account....
WSGI_APPLICATION = 'wsgi.application'
random_line_split
Arabic-Presentation-Forms-B-code-points.js
// All code points in the Arabic Presentation Forms-B block as per Unicode v5.1.0: [ 0xFE70, 0xFE71, 0xFE72, 0xFE73, 0xFE74, 0xFE75, 0xFE76, 0xFE77, 0xFE78, 0xFE79, 0xFE7A, 0xFE7B, 0xFE7C, 0xFE7D, 0xFE7E, 0xFE7F, 0xFE80, 0xFE81, 0xFE82, 0xFE83, 0xFE84, 0xFE85, 0xFE86, 0xFE87, 0xFE88, 0xFE89, ...
];
random_line_split
pseudo.py
# -*- coding: utf-8 -*- import random as rand class PrimeTester(object): def solovay_strassen(self, primo, acuracidade=5): nro_tentativas = 0 if primo == 2 or primo == 3: return (nro_tentativas, True) if primo < 2: raise ValueError('Entrada < 2') if primo %...
# https://en.wikipedia.org/wiki/Mersenne_Twister self.mersenne_twister[i] %= self.__magic__
self.mersenne_twister[i] = self.mersenne_twister[(i + 397) % self.N] ^ (y >> 1) if y % 2 != 0: # Original : MT[i] := MT[i] xor (2567483615) // 0x9908b0df # Hacked : MT[i] := MT[i] mod (2567483615) // 0x9908b0df
random_line_split
pseudo.py
# -*- coding: utf-8 -*- import random as rand class PrimeTester(object): def solovay_strassen(self, primo, acuracidade=5): nro_tentativas = 0 if primo == 2 or primo == 3: return (nro_tentativas, True) if primo < 2: raise ValueError('Entrada < 2') if primo %...
(self, bits): if bits in [64, 128, 256, 512, 1024, 2048, 4096]: self.__magic__ = rand.getrandbits(bits) else: raise 'Precisa ser algum desses valores: {64, 128, 256, 512, 1024, 2048, 4096}' if self.index == 0: self.gerar() y = self.mersenne_twister[s...
extrair
identifier_name
pseudo.py
# -*- coding: utf-8 -*- import random as rand class PrimeTester(object): def solovay_strassen(self, primo, acuracidade=5): nro_tentativas = 0 if primo == 2 or primo == 3: return (nro_tentativas, True) if primo < 2: raise ValueError('Entrada < 2') if primo %...
def alimentar(self, seed): self.index = 0 self.mersenne_twister[0] = seed for i in range(1, self.N): self.mersenne_twister[i] = ( 1812433253 * (self.mersenne_twister[i - 1] ^ (self.mersenne_twister[i - 1] >> 30)) + i) def extrair(self, bits): if bi...
self.N = 624 self.M = 397 self.mersenne_twister = [x for x in range(624)] self.index = 0 self.index_tamanho = 64 self.__magic__ = rand.getrandbits(64)
identifier_body
pseudo.py
# -*- coding: utf-8 -*- import random as rand class PrimeTester(object): def solovay_strassen(self, primo, acuracidade=5): nro_tentativas = 0 if primo == 2 or primo == 3: return (nro_tentativas, True) if primo < 2: raise ValueError('Entrada < 2') if primo %...
for _ in range(acuracidade): nro_tentativas += 1 a = rand.randint(2, primo - 1) res = self.adrien_legendre(a, primo) potencia = self.potencia(a, (primo - 1) // 2, primo) if res == 0 or potencia != res % primo: return (nro_tentativa...
raise ValueError('Entrada % 2 == 0')
conditional_block
disadvantaged_group_views.py
from django.views.generic import ListView, DetailView, CreateView, \ DeleteView, UpdateView from baseapp.models import Disadvantaged_group from django.contrib import auth, messages class Disadvantaged_groupView(object): model = Disadvantaged_group def get_template_names(sel...
(self): from django.core.urlresolvers import reverse return reverse('baseapp_disadvantaged_group_list')
get_success_url
identifier_name
disadvantaged_group_views.py
from django.views.generic import ListView, DetailView, CreateView, \ DeleteView, UpdateView from baseapp.models import Disadvantaged_group from django.contrib import auth, messages class Disadvantaged_groupView(object): model = Disadvantaged_group def get_template_names(sel...
def get_success_url(self): from django.core.urlresolvers import reverse return reverse('baseapp_disadvantaged_group_list')
random_line_split
disadvantaged_group_views.py
from django.views.generic import ListView, DetailView, CreateView, \ DeleteView, UpdateView from baseapp.models import Disadvantaged_group from django.contrib import auth, messages class Disadvantaged_groupView(object): model = Disadvantaged_group def get_template_names(sel...
class Disadvantaged_groupDetailView(Disadvantaged_groupView, DetailView): def get_success_url(self): from django.core.urlresolvers import reverse return reverse('baseapp_disadvantaged_group_list') class Disadvantaged_groupListView(Disadvantaged_groupBaseListView, ListView): def get_success_...
def get_success_url(self): from django.core.urlresolvers import reverse return reverse('baseapp_disadvantaged_group_list')
identifier_body
properties.ts
export function
(Prism: any) { // https://github.com/PrismJS/prism/blob/e0ee93f138b7da294a28db50b97c22977fdfc8ed/components/prism-properties.js Prism.languages.properties = { comment: /^[ \t]*[#!].*$/m, 'attr-value': { pattern: /(^[ \t]*(?:\\(?:\r\n|[\s\S])|[^\\\s:=])+?(?: *[=:] *(?! )| ))(?:\\(?:\r\n|[\s\S])...
installProperties
identifier_name
properties.ts
export function installProperties(Prism: any) { // https://github.com/PrismJS/prism/blob/e0ee93f138b7da294a28db50b97c22977fdfc8ed/components/prism-properties.js Prism.languages.properties = { comment: /^[ \t]*[#!].*$/m, 'attr-value': { pattern: /(^[ \t]*(?:\\(?:\r\n|[\s\S])|[^\\\s:=])+?(?: *[=...
}; }
lookbehind: true, }, 'attr-name': /^[ \t]*(?:\\(?:\r\n|[\s\S])|[^\\\s:=])+?(?= *[=:] *| )/m, punctuation: /[=:]/,
random_line_split
properties.ts
export function installProperties(Prism: any)
{ // https://github.com/PrismJS/prism/blob/e0ee93f138b7da294a28db50b97c22977fdfc8ed/components/prism-properties.js Prism.languages.properties = { comment: /^[ \t]*[#!].*$/m, 'attr-value': { pattern: /(^[ \t]*(?:\\(?:\r\n|[\s\S])|[^\\\s:=])+?(?: *[=:] *(?! )| ))(?:\\(?:\r\n|[\s\S])|[^\\\r\n])+/...
identifier_body
bounds.rs
// 这个 trait 实现了打印标记:`{:?}`。 use std::fmt::Debug; trait HasArea { fn area(&self) -> f64; } impl HasArea for Rectangle { fn area(&self) -> f64 { self.length * self.height } } #[derive(Debug)] struct Rectangle { length: f64, height: f64 } #[allow(dead_code)] struct Triangle { length: f64, height: f64 } // 泛型 ...
t: 4.0 }; print_debug(&rectangle); println!("Area: {}", area(&rectangle)); //print_debug(&_triangle); //println!("Area: {}", area(&_triangle)); // ^ 试一试:将上述语句的注释去掉。 // | 报错:未实现 `Debug` 或 `HasArea`。 }
identifier_body
bounds.rs
// 这个 trait 实现了打印标记:`{:?}`。 use std::fmt::Debug; trait HasArea { fn area(&self) -> f64; } impl HasArea for Rectangle { fn area(&self) -> f64 { self.length * self.height } } #[derive(Debug)] struct Rectangle { length: f64, height: f64 } #[allow(dead_code)] struct Triangle { length: f6
t: f64 } // 泛型 `T` 必须实现 `Debug`。不管什么类型,都可以正常工作。 fn print_debug<T: Debug>(t: &T) { println!("{:?}", t); } // `T` 必须实现 `HasArea`。任意符合限定的函数都可以访问 // `HasArea` 的 `area` 函数。 fn area<T: HasArea>(t: &T) -> f64 { t.area() } fn main() { let rectangle = Rectangle { length: 3.0, height: 4.0 }; let _triangle = Triang...
4, heigh
identifier_name
bounds.rs
// 这个 trait 实现了打印标记:`{:?}`。 use std::fmt::Debug; trait HasArea { fn area(&self) -> f64; } impl HasArea for Rectangle { fn area(&self) -> f64 { self.length * self.height } } #[derive(Debug)] struct Rectangle { length: f64, height: f64 } #[allow(dead_code)]
// 泛型 `T` 必须实现 `Debug`。不管什么类型,都可以正常工作。 fn print_debug<T: Debug>(t: &T) { println!("{:?}", t); } // `T` 必须实现 `HasArea`。任意符合限定的函数都可以访问 // `HasArea` 的 `area` 函数。 fn area<T: HasArea>(t: &T) -> f64 { t.area() } fn main() { let rectangle = Rectangle { length: 3.0, height: 4.0 }; let _triangle = Triangle { leng...
struct Triangle { length: f64, height: f64 }
random_line_split
BarLineChart.js
/*! * Copyright 2010 - 2015 Pentaho Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by ap...
}, _configure: function() { this.base(); this._configureAxisRange(/*isPrimary*/false, 'ortho2'); this._configureAxisTitle('ortho2',""); this.options.plot2OrthoAxis = 2; // Plot2 uses same color scale ...
{ options.pointDotsVisible = true; options.extensionPoints.pointDot_shape = shape; }
conditional_block
BarLineChart.js
/*! * Copyright 2010 - 2015 Pentaho Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by ap...
this.base.apply(this, arguments); // Plot2 var lineLabelsAnchor = drawSpec.lineLabelsOption; if(lineLabelsAnchor && lineLabelsAnchor !== 'none') { options.plot2ValuesVisible = true; options.plot2ValuesAnchor = line...
// options.color2AxisTransform = null; }, _configureLabels: function(options, drawSpec) {
random_line_split
is_ascii.rs
use super::{LONG, MEDIUM, SHORT}; use test::black_box; use test::Bencher; macro_rules! benches { ($( fn $name: ident($arg: ident: &[u8]) $body: block )+) => { benches!(mod short SHORT[..] $($name $arg $body)+); benches!(mod medium MEDIUM[..] $($name $arg $body)+); benches!(mod long LONG[..]...
return bytes.iter().all(|b| b.is_ascii()); } // SAFETY: transmuting a sequence of `u8` to `usize` is always fine let (head, body, tail) = unsafe { bytes.align_to::<usize>() }; head.iter().all(|b| b.is_ascii()) && body.iter().all(|w| !contains_nonascii(*w)) && tail.iter().all(|b| ...
// These are separate since it's easier to debug errors if they don't go through // macro expansion first. fn is_ascii_align_to(bytes: &[u8]) -> bool { if bytes.len() < core::mem::size_of::<usize>() {
random_line_split
is_ascii.rs
use super::{LONG, MEDIUM, SHORT}; use test::black_box; use test::Bencher; macro_rules! benches { ($( fn $name: ident($arg: ident: &[u8]) $body: block )+) => { benches!(mod short SHORT[..] $($name $arg $body)+); benches!(mod medium MEDIUM[..] $($name $arg $body)+); benches!(mod long LONG[..]...
// SAFETY: transmuting a sequence of `u8` to `usize` is always fine let (head, body, tail) = unsafe { bytes.align_to::<usize>() }; head.iter().all(|b| b.is_ascii()) && body.iter().all(|w| !contains_nonascii(*w)) && tail.iter().all(|b| b.is_ascii()) } fn is_ascii_align_to_unrolled(bytes: &[...
{ return bytes.iter().all(|b| b.is_ascii()); }
conditional_block
is_ascii.rs
use super::{LONG, MEDIUM, SHORT}; use test::black_box; use test::Bencher; macro_rules! benches { ($( fn $name: ident($arg: ident: &[u8]) $body: block )+) => { benches!(mod short SHORT[..] $($name $arg $body)+); benches!(mod medium MEDIUM[..] $($name $arg $body)+); benches!(mod long LONG[..]...
(bytes: &[u8]) -> bool { if bytes.len() < core::mem::size_of::<usize>() { return bytes.iter().all(|b| b.is_ascii()); } // SAFETY: transmuting a sequence of `u8` to `usize` is always fine let (head, body, tail) = unsafe { bytes.align_to::<usize>() }; head.iter().all(|b| b.is_ascii()) ...
is_ascii_align_to
identifier_name
is_ascii.rs
use super::{LONG, MEDIUM, SHORT}; use test::black_box; use test::Bencher; macro_rules! benches { ($( fn $name: ident($arg: ident: &[u8]) $body: block )+) => { benches!(mod short SHORT[..] $($name $arg $body)+); benches!(mod medium MEDIUM[..] $($name $arg $body)+); benches!(mod long LONG[..]...
fn is_ascii_align_to_unrolled(bytes: &[u8]) -> bool { if bytes.len() < core::mem::size_of::<usize>() { return bytes.iter().all(|b| b.is_ascii()); } // SAFETY: transmuting a sequence of `u8` to `[usize; 2]` is always fine let (head, body, tail) = unsafe { bytes.align_to::<[usize; 2]>() }; h...
{ if bytes.len() < core::mem::size_of::<usize>() { return bytes.iter().all(|b| b.is_ascii()); } // SAFETY: transmuting a sequence of `u8` to `usize` is always fine let (head, body, tail) = unsafe { bytes.align_to::<usize>() }; head.iter().all(|b| b.is_ascii()) && body.iter().all(|w| ...
identifier_body
ntp_client.py
#!/bin/env python """ ####################################################################### # # # Copyright (c) 2012, Prateek Sureka. All Rights Reserved. # # This module provides an idempotent mechanism to remotely configure # # ntp sync...
print run("ntpdc -p")
random_line_split
ntp_client.py
#!/bin/env python """ ####################################################################### # # # Copyright (c) 2012, Prateek Sureka. All Rights Reserved. # # This module provides an idempotent mechanism to remotely configure # # ntp sync...
(server=config.get("ntp_client", {}).get("ntp_server", "")): """ Install, configure and start ntp sync and timezone. """ if not is_debian_or_ubuntu(): print red("Cannot deploy to non-debian/ubuntu host: %s" % env.host) return import apt, service packages = {"ntp":"latest", "ntpd...
deploy
identifier_name
ntp_client.py
#!/bin/env python """ ####################################################################### # # # Copyright (c) 2012, Prateek Sureka. All Rights Reserved. # # This module provides an idempotent mechanism to remotely configure # # ntp sync...
import apt apt.ensure(tzdata="latest") return run("cp -f /usr/share/zoneinfo/%s /etc/localtime" % timezone) @task def configure(server=config.get("ntp_client", {}).get("ntp_server", "")): """ Configure NTP sync to server. """ if not is_debian_or_ubuntu(): print red("Cannot deploy...
print red("Cannot deploy to non-debian/ubuntu host: %s" % env.host) return
conditional_block
ntp_client.py
#!/bin/env python """ ####################################################################### # # # Copyright (c) 2012, Prateek Sureka. All Rights Reserved. # # This module provides an idempotent mechanism to remotely configure # # ntp sync...
@task def deploy(server=config.get("ntp_client", {}).get("ntp_server", "")): """ Install, configure and start ntp sync and timezone. """ if not is_debian_or_ubuntu(): print red("Cannot deploy to non-debian/ubuntu host: %s" % env.host) return import apt, service packages = {"nt...
""" Configure NTP sync to server. """ if not is_debian_or_ubuntu(): print red("Cannot deploy to non-debian/ubuntu host: %s" % env.host) return # Upload configuration params = {'server':server} reconfigure("ntp_client.conf.template", params, NTP_CONF_PATH)
identifier_body
game_state.rs
// See LICENSE file for copyright and license details. use crate::core::core::{Event, ObjectTypes, Unit}; use crate::core::types::{MapPos, PlayerId, UnitId}; use std::collections::HashMap; pub struct GameState { pub units: HashMap<UnitId, Unit>, } impl<'a> GameState { pub fn new() -> GameState { Game...
unit.pos = pos; assert!(unit.move_points > 0); unit.move_points = 0; } Event::EventEndTurn(_, new_player_id) => { self.refresh_units(object_types, new_player_id.clone()); } Event::EventCreateUnit(id, pos, typ...
let unit = self.units.get_mut(&id).unwrap();
random_line_split
game_state.rs
// See LICENSE file for copyright and license details. use crate::core::core::{Event, ObjectTypes, Unit}; use crate::core::types::{MapPos, PlayerId, UnitId}; use std::collections::HashMap; pub struct GameState { pub units: HashMap<UnitId, Unit>, } impl<'a> GameState { pub fn new() -> GameState { Game...
(&mut self, object_types: &ObjectTypes, player_id: PlayerId) { for (_, unit) in self.units.iter_mut() { if unit.player_id == player_id { unit.move_points = object_types.get_unit_type(unit.type_id).move_points; unit.attacked = false; } } } ...
refresh_units
identifier_name
game_state.rs
// See LICENSE file for copyright and license details. use crate::core::core::{Event, ObjectTypes, Unit}; use crate::core::types::{MapPos, PlayerId, UnitId}; use std::collections::HashMap; pub struct GameState { pub units: HashMap<UnitId, Unit>, } impl<'a> GameState { pub fn new() -> GameState { Game...
} } pub fn apply_event(&mut self, object_types: &ObjectTypes, event: &Event) { match event { Event::EventMove(id, ref path) => { let pos = *path.last().unwrap(); let unit = self.units.get_mut(&id).unwrap(); unit.pos = pos; ...
{ unit.move_points = object_types.get_unit_type(unit.type_id).move_points; unit.attacked = false; }
conditional_block
game_state.rs
// See LICENSE file for copyright and license details. use crate::core::core::{Event, ObjectTypes, Unit}; use crate::core::types::{MapPos, PlayerId, UnitId}; use std::collections::HashMap; pub struct GameState { pub units: HashMap<UnitId, Unit>, } impl<'a> GameState { pub fn new() -> GameState { Game...
fn refresh_units(&mut self, object_types: &ObjectTypes, player_id: PlayerId) { for (_, unit) in self.units.iter_mut() { if unit.player_id == player_id { unit.move_points = object_types.get_unit_type(unit.type_id).move_points; unit.attacked = false; }...
{ let mut units = Vec::new(); for (_, unit) in self.units.iter() { if unit.pos == pos { units.push(unit); } } units }
identifier_body
syntax_definition.rs
this data structure? use std::collections::{BTreeMap, HashMap}; use std::hash::Hash; use super::scope::*; use super::regex::{Regex, Region}; use regex_syntax::escape; use serde::{Serialize, Serializer}; use crate::parsing::syntax_set::SyntaxSet; pub type CaptureMapping = Vec<(usize, Vec<Scope>)>; /// An opaque ID f...
{ pub meta_scope: Vec<Scope>, pub meta_content_scope: Vec<Scope>, /// This being set false in the syntax file implies this field being set false, /// but it can also be set falso for contexts that don't include the prototype for other reasons pub meta_include_prototype: bool, pub clear_scopes: ...
Context
identifier_name
syntax_definition.rs
this data structure? use std::collections::{BTreeMap, HashMap}; use std::hash::Hash; use super::scope::*; use super::regex::{Regex, Region}; use regex_syntax::escape; use serde::{Serialize, Serializer}; use crate::parsing::syntax_set::SyntaxSet; pub type CaptureMapping = Vec<(usize, Vec<Scope>)>; /// An opaque ID f...
Pattern::Match(ref match_pat) => match_pat, _ => panic!("bad index to match_at"), } } } impl ContextReference { /// find the pointed to context, panics if ref is not linked pub fn resolve<'a>(&self, syntax_set: &'a SyntaxSet) -> &'a Context { match *self { ...
random_line_split
__main__.py
# -*- coding: utf-8 -*- from __future__ import print_function import sys from ipa_auto import ipa_auto if __name__ == "__main__": label = "" pub = False con = False # url = "http://192.168.0.33/publish/ipapub/" # url = "http://127.0.0.1:8000/ipapub/" url = '' cfg = 'auto.cfg' if len(sys...
if any(a in sys.argv for a in ['-con', '-continue']): con = True cfgs = [s for s in sys.argv if s.startswith('_')] if len(cfgs) > 0: #只取第一个 cfg = 'auto'+cfgs[0]+'.cfg' print("请输入标签(无标签的包可能被删除,无需标签直接按回车):".decode('utf-8')) label = raw_input() ipa_auto(label, ...
url = sys.argv[sys.argv.index('-url') + 1]
conditional_block
__main__.py
# -*- coding: utf-8 -*- from __future__ import print_function import sys from ipa_auto import ipa_auto if __name__ == "__main__": label = "" pub = False con = False
if '-publish' in sys.argv: pub = True if '-url' in sys.argv: url = sys.argv[sys.argv.index('-url') + 1] if any(a in sys.argv for a in ['-con', '-continue']): con = True cfgs = [s for s in sys.argv if s.startswith('_')] if len(cfgs) > 0: #只取第一个 ...
# url = "http://192.168.0.33/publish/ipapub/" # url = "http://127.0.0.1:8000/ipapub/" url = '' cfg = 'auto.cfg' if len(sys.argv) > 1:
random_line_split
2_variables_and_types.py
#!/usr/bin/python # Code is executed top-to-bottom on load. # Variables are defined at the first assignment a = 2 # defines `a` b = 2 # 'print' operator, simple form: just prints out human-readable representation # of the argument. NOTE: no \n! print a + b # Types in Python are dynamic! v = 42 # `v` is an integer...
# 'print' operator, full form. print "%d %.1f %s" % (42, 4.2, "forty two") # non-optimal equivalent: print str(42) + " " + str(4.2) + " forty two"
random_line_split
edit.js
angular .module('cocktailApp') .controller('CocktailEditCtrl', ['$location', '$routeParams', 'navigator', 'cocktailCollection', function($location, $routeParams, navigator, cocktailCollection) { var self = this; self.isDisabled = true; if (!$routeParams.id) { self.cocktail = {}; ...
self.addEquipment = function() { if (!self.cocktail.equipment) { self.cocktail.equipment = []; } self.cocktail.equipment.push(null); }; self.removeEquipment = function(index) { self.cocktail.equipment.splice(index, 1); }; self.addIngredient = f...
{ cocktailCollection.get($routeParams.id) .then(function(cocktail) { self.cocktail = cocktail; self.isDisabled = false; }, function(err) { self.errorMessage = "Failed to find id: " + id; }); }
conditional_block
app.ts
// source: app.ts /// <reference path="typings/mithriljs/mithril.d.ts" /> /// <reference path="pages/navigation.ts" /> /// <reference path="pages/graph.ts" /> /// <reference path="pages/log.ts" /> /// <reference path="pages/monitor.ts" /> /// <reference path="pages/nodes.ts" /> /// <reference path="pages/stores.ts" />...
"/node/:node_id": AdminViews.Nodes.NodePage, "/nodes/:node_id": AdminViews.Nodes.NodePage, "/store": AdminViews.Stores.StorePage, "/stores": AdminViews.Stores.StoresPage, "/store/:store_id": AdminViews.Stores.StorePage, "/stores/:store_id": AdminViews.Stores.StorePage });
"/logs": AdminViews.Log.Page, "/logs/:node_id": AdminViews.Log.Page, "/monitor": AdminViews.Monitor.Page, "/node": AdminViews.Nodes.NodesPage, "/nodes": AdminViews.Nodes.NodesPage,
random_line_split
compat.py
#------------------------------------------------------------------------------------------ # # Copyright 2017 Robert Pengelly. # # This file is part of ppa-helper. # # 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 # ...
(fallback=(80, 24)): columns = compat_getenv('COLUMNS') if columns: columns = int(columns) else: columns = None lines = compat_getenv('LINES') if lines: lines = int(lines) else: lines = None if columns is None or li...
compat_get_terminal_size
identifier_name
compat.py
#------------------------------------------------------------------------------------------ # # Copyright 2017 Robert Pengelly. # # This file is part of ppa-helper. # # 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 # ...
else: compat_kwargs = lambda kwargs: kwargs if hasattr(shutil, 'get_terminal_size'): # Python >= 3.3 compat_get_terminal_size = shutil.get_terminal_size else: _terminal_size = collections.namedtuple('terminal_size', ['columns', 'lines']) def compat_get_terminal_size(fallback=(80, 24)): colum...
return dict((bytes(k), v) for k, v in kwargs.items())
identifier_body
compat.py
#------------------------------------------------------------------------------------------ # # Copyright 2017 Robert Pengelly. # # This file is part of ppa-helper. # # 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 # ...
else: _terminal_size = collections.namedtuple('terminal_size', ['columns', 'lines']) def compat_get_terminal_size(fallback=(80, 24)): columns = compat_getenv('COLUMNS') if columns: columns = int(columns) else: columns = None lines = compat_getenv('LINES'...
compat_get_terminal_size = shutil.get_terminal_size
conditional_block
compat.py
#------------------------------------------------------------------------------------------ # # Copyright 2017 Robert Pengelly. # # This file is part of ppa-helper. # # 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 # ...
else: compat_kwargs = lambda kwargs: kwargs if hasattr(shutil, 'get_terminal_size'): # Python >= 3.3 compat_get_terminal_size = shutil.get_terminal_size else: _terminal_size = collections.namedtuple('terminal_size', ['columns', 'lines']) def compat_get_terminal_size(fallback=(80, 24)): column...
random_line_split
validation_utils.py
import gzip import logging import os import shutil import uuid from PIL import Image from zipfile import ZipFile import pandas as pd import numpy as np import pyresample as pr from trollvalidation.validations import configuration as cfg LOG = logging.getLogger(__name__) # logging.basicConfig(level=logging.DEBUG, # ...
try: z.extract(name, temporary_files_folder) except Exception, e: LOG.exception(e) LOG.error('Could not uncompress {0}'.format(name)) return unpacked_shapefile, [temporary_files_folder] else: ...
unpacked_shapefile = os.path.join( temporary_files_folder, name)
conditional_block
validation_utils.py
import gzip import logging import os import shutil import uuid from PIL import Image from zipfile import ZipFile import pandas as pd import numpy as np import pyresample as pr from trollvalidation.validations import configuration as cfg LOG = logging.getLogger(__name__) # logging.basicConfig(level=logging.DEBUG, # ...
def cleanup(self): map(os.remove, self.files) def cleanup(_, tmp_files): # Delete files first and the remove directories for tmp_file in tmp_files: if os.path.isfile(tmp_file): LOG.info("Cleaning up... {0}".format(tmp_file)) os.remove(tmp_file) for tmp_folder in...
self.tmpfiles += files else: self.tmpfiles.append(files)
random_line_split
validation_utils.py
import gzip import logging import os import shutil import uuid from PIL import Image from zipfile import ZipFile import pandas as pd import numpy as np import pyresample as pr from trollvalidation.validations import configuration as cfg LOG = logging.getLogger(__name__) # logging.basicConfig(level=logging.DEBUG, # ...
(self): map(os.remove, self.files) def cleanup(_, tmp_files): # Delete files first and the remove directories for tmp_file in tmp_files: if os.path.isfile(tmp_file): LOG.info("Cleaning up... {0}".format(tmp_file)) os.remove(tmp_file) for tmp_folder in tmp_files: ...
cleanup
identifier_name
validation_utils.py
import gzip import logging import os import shutil import uuid from PIL import Image from zipfile import ZipFile import pandas as pd import numpy as np import pyresample as pr from trollvalidation.validations import configuration as cfg LOG = logging.getLogger(__name__) # logging.basicConfig(level=logging.DEBUG, # ...
elif 'nh_ease2-250' in file_name: cfg_id = 'EASE2_NH' elif 'sh_ease2-250' in file_name: cfg_id = 'EASE2_SH' elif 'nic_weekly_' in file_name: cfg_id = 'NIC_EASE_NH' elif 'nh_polstere-100' in file_name: cfg_id = 'OSISAF_NH' elif 'sh_polstere-100' in file_name: c...
""" This function is a utility function to read the area definition of corresponding to an ice concentration product. :param file_handle: str Path to an ice concentration product in NetCDF product. :return: AreaDefinition The parsed area definition corresponding to the projection ...
identifier_body
ChildProcessWorker.js
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports.default = void 0; function _child_process() { const data = require('child_process'); _child_process = function () { return data; }; return data; } function _stream() { const data = require('stream'); _stream = f...
() { return this._stderr; } _getFakeStream() { if (!this._fakeStream) { this._fakeStream = new (_stream().PassThrough)(); } return this._fakeStream; } } exports.default = ChildProcessWorker;
getStderr
identifier_name
ChildProcessWorker.js
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports.default = void 0; function _child_process() { const data = require('child_process'); _child_process = function () { return data; }; return data; } function _stream() { const data = require('stream'); _stream = f...
send(request, onProcessStart, onProcessEnd, onCustomMessage) { onProcessStart(this); this._onProcessEnd = (...args) => { // Clean the request to avoid sending past requests to workers that fail // while waiting for a new request (timers, unhandled rejections...) this._request = null; ...
{ if ( exitCode !== 0 && exitCode !== SIGTERM_EXIT_CODE && exitCode !== SIGKILL_EXIT_CODE ) { this.initialize(); if (this._request) { this._child.send(this._request); } } else { this._shutdown(); } }
identifier_body
ChildProcessWorker.js
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports.default = void 0; function _child_process() { const data = require('child_process'); _child_process = function () { return data; }; return data; } function _stream() { const data = require('stream'); _stream = f...
else { obj[key] = value; } return obj; } const SIGNAL_BASE_EXIT_CODE = 128; const SIGKILL_EXIT_CODE = SIGNAL_BASE_EXIT_CODE + 9; const SIGTERM_EXIT_CODE = SIGNAL_BASE_EXIT_CODE + 15; // How long to wait after SIGTERM before sending SIGKILL const SIGKILL_DELAY = 500; /** * This class wraps the child process ...
{ Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); }
conditional_block
ChildProcessWorker.js
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports.default = void 0; function _child_process() { const data = require('child_process'); _child_process = function () { return data; }; return data; } function _stream() { const data = require('stream'); _stream = f...
error.name, error.message, error.stack, { type: 'WorkerError' } ]); } } _shutdown() { // End the temporary streams so the merged streams end too if (this._fakeStream) { this._fakeStream.end(); this._fakeStream = null; } this....
if (this._retries > this._options.maxRetries) { const error = new Error('Call retries were exceeded'); this._onMessage([ _types().PARENT_MESSAGE_CLIENT_ERROR,
random_line_split
roerrorapi.rs
// Copyright © 2017 winapi-rs developers
// Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option. // All files in the project carrying such notice may not be copied, modified, or distributed // except according ...
random_line_split
xmldocument.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use document_loader::DocumentLoader; use dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods; use d...
} doc } } impl XMLDocumentMethods for XMLDocument { // https://html.spec.whatwg.org/multipage/#dom-document-location fn GetLocation(&self) -> Option<DomRoot<Location>> { self.upcast::<Document>().GetLocation() } // https://html.spec.whatwg.org/multipage/#dom-tree-accessors...
{ let doc = reflect_dom_object( Box::new(XMLDocument::new_inherited( window, has_browsing_context, url, origin, doctype, content_type, last_modified, activity, ...
identifier_body
xmldocument.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use document_loader::DocumentLoader; use dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods; use d...
(window: &Window, has_browsing_context: HasBrowsingContext, url: Option<ServoUrl>, origin: MutableOrigin, is_html_document: IsHTMLDocument, content_type: Option<DOMString>, last_modified: Option...
new_inherited
identifier_name
xmldocument.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use document_loader::DocumentLoader; use dom::bindings::codegen::Bindings::DocumentBinding::DocumentMethods; use d...
// https://html.spec.whatwg.org/multipage/#dom-document-location fn GetLocation(&self) -> Option<DomRoot<Location>> { self.upcast::<Document>().GetLocation() } // https://html.spec.whatwg.org/multipage/#dom-tree-accessors:supported-property-names fn SupportedPropertyNames(&self) -> Vec<DOMS...
impl XMLDocumentMethods for XMLDocument {
random_line_split
build.js
function load(/*String*/fileName)
function readFile(/*String*/path, /*String?*/encoding){ //summary: reads a file and returns a string encoding = encoding || "utf-8"; var file = new java.io.File(path); var lineSeparator = "\n"; var input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(file), encoding)); tr...
{ //summary: opens the file at fileName and evals the contents as JavaScript. //Read the file var fileContents = readFile(fileName); //Eval the contents. var Context = Packages.org.mozilla.javascript.Context; var context = Context.enter(); try{ return context.evaluateString(this, fileContents, fileName, 1, ...
identifier_body
build.js
function load(/*String*/fileName){ //summary: opens the file at fileName and evals the contents as JavaScript. //Read the file var fileContents = readFile(fileName); //Eval the contents. var Context = Packages.org.mozilla.javascript.Context; var context = Context.enter(); try{ return context.evaluateString(...
//Build the layer contents. var depResult = buildUtil.makeDojoJs(buildUtil.loadDependencyList(kwArgs.profileProperties, null, buildscriptDir), kwArgs.version, kwArgs); //Grab the content from the "dojo.xd.js" layer. var layerName = depResult[1].layerName; var layerContents = depResult[1].contents; ...
dependencies.loader = kwArgs.loader;
random_line_split