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
simple.rs
pub fn
() { let a = true; let b = false; if a { print!("a"); } else if b { print!("b"); } else { print!("c") } let mut a: int = 0; let b: bool = true; let c: bool = false; let _numbers = [1, 2, 3]; let t = _numbers[a..]; // As a naked if if b || c ...
main
identifier_name
simple.rs
pub fn main() { let a = true; let b = false; if a { print!("a"); } else if b { print!("b"); } else { print!("c") } let mut a: int = 0; let b: bool = true; let c: bool = false; let _numbers = [1, 2, 3]; let t = _numbers[a..]; // As a naked if ...
// Tuple expressions. They are not at all ambiguious. (0,); (0.0, 4.5); ("a", 4u, true); // Tuple destructuring let with a statement block! let (_cap, _cap_name, _oldflags) = { (1, 2, 3) }; }
} println!("{}", a);
random_line_split
simple.rs
pub fn main()
a = 1; } a << 32 > a << 16; a >> 32 < a >> 16; a >>= 1; println!("{}", a); // As an expression a = if !c { 10 } else { 20 }; 'foo: loop { println!("{}", a); break 'foo; } println!("{}", a); // Tuple expressions. They are ...
{ let a = true; let b = false; if a { print!("a"); } else if b { print!("b"); } else { print!("c") } let mut a: int = 0; let b: bool = true; let c: bool = false; let _numbers = [1, 2, 3]; let t = _numbers[a..]; // As a naked if if b || c {
identifier_body
simple.rs
pub fn main() { let a = true; let b = false; if a { print!("a"); } else if b
else { print!("c") } let mut a: int = 0; let b: bool = true; let c: bool = false; let _numbers = [1, 2, 3]; let t = _numbers[a..]; // As a naked if if b || c { a = 1; } a << 32 > a << 16; a >> 32 < a >> 16; a >>= 1; println!("{}", a); // As ...
{ print!("b"); }
conditional_block
AutofillStore.d.ts
export = AutofillStore; declare function AutofillStore(): void; declare class
{ private ds_; private logger_; private modified_; isModified(): boolean; setAsModified(): void; private formatFilePath_; load(): DataSet; save(): void; findEntry(entry: AutofillRecordKey): AutofillRecord; newEntry(entry: AutofillRecord): void; updateEntry(entry: AutofillRec...
AutofillStore
identifier_name
AutofillStore.d.ts
export = AutofillStore; declare function AutofillStore(): void; declare class AutofillStore { private ds_; private logger_; private modified_; isModified(): boolean; setAsModified(): void; private formatFilePath_; load(): DataSet; save(): void; findEntry(entry: AutofillRecordKey): Au...
findEntry_(entry: AutofillRecordKey): boolean; } declare namespace AutofillStore { export { instance_, getInstance, AutofillRecordKey, AutofillRecord }; } import DataSet = require('@nginstack/engine/lib/dataset/DataSet.js'); interface AutofillRecordKey { processKey: number; interactionName: string; ...
deleteEntry(entry: AutofillRecordKey): void;
random_line_split
graphs2b.py
# # This file is part of DF. # # DF is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public # License as published by the Free Software Foundation; # either version 3 of the License, or (at your option) any # later version.
# # Latassan is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR # PURPOSE. See the GNU General Public License for more # details. # # You should have received a copy of the GNU General Public # License along ...
random_line_split
graphs2b.py
# # This file is part of DF. # # DF is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public # License as published by the Free Software Foundation; # either version 3 of the License, or (at your option) any # later version. # # Latassan is distributed in the hope that it ...
log.basicConfig(level=log.DEBUG, format='%(asctime)s:%(levelname)s:%(message)s') matrix_file_name = sys.argv[1] graph_file_name = sys.argv[2] density = float(sys.argv[3]) iw = False umat = pickle.load(open(matrix_file_name, 'rb')) g = GraphUtils.get_graph_from_matrix(umat,density,ignore_weigh...
conditional_block
assignments.js
import {all, call, put, select, takeEvery} from 'redux-saga/effects'; import { createClassroomAssignment, getCourses, } from '../clients/googleClassroom'; import {createProjectSnapshot} from '../clients/firebase'; import {assignmentCreated, assignmentNotCreated} from '../actions/assignments'; import {coursesFullyL...
yield put(coursesLoaded(courses)); pageToken = nextPageToken; } while (pageToken); yield put(coursesFullyLoaded()); } export function* createAssignment({ payload: {selectedCourseId, dueDate, assignmentState}, }) { const project = yield select(getCurrentProject); const snapshotKey = yield call(createP...
export function* openAssignmentCreator() { let pageToken; do { const {courses, nextPageToken} = yield call(getCourses, pageToken);
random_line_split
assignments.js
import {all, call, put, select, takeEvery} from 'redux-saga/effects'; import { createClassroomAssignment, getCourses, } from '../clients/googleClassroom'; import {createProjectSnapshot} from '../clients/firebase'; import {assignmentCreated, assignmentNotCreated} from '../actions/assignments'; import {coursesFullyL...
} catch (e) { yield put(assignmentNotCreated()); } } export default function* assignments() { yield all([ takeEvery('OPEN_ASSIGNMENT_CREATOR', openAssignmentCreator), takeEvery('CREATE_ASSIGNMENT', createAssignment), ]); }
{ const course = yield select(getCourse, selectedCourseId); yield put( assignmentCreated({ url: course.alternateLink, exportType: 'assignment-draft', }), ); }
conditional_block
sync-rwlock-write-mode-shouldnt-escape.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn main() { let x = ~sync::RWLock::new(); let mut y = None; do x.write_downgrade |write_mode| { y = Some(write_mode); } // Adding this line causes a method unification failure instead // do (&option::unwrap(y)).write { } }
// error-pattern: lifetime of variable does not enclose its declaration extern mod extra; use extra::sync;
random_line_split
sync-rwlock-write-mode-shouldnt-escape.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let x = ~sync::RWLock::new(); let mut y = None; do x.write_downgrade |write_mode| { y = Some(write_mode); } // Adding this line causes a method unification failure instead // do (&option::unwrap(y)).write { } }
identifier_body
sync-rwlock-write-mode-shouldnt-escape.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let x = ~sync::RWLock::new(); let mut y = None; do x.write_downgrade |write_mode| { y = Some(write_mode); } // Adding this line causes a method unification failure instead // do (&option::unwrap(y)).write { } }
main
identifier_name
file_organizer.py
self.get_prop('nbytes', cand_idxs), }) # print(ut.repr4(ut.group_items(fpaths, nbytes))) data.ignore = ['full_path', 'dname'] data.print(ignore=['full_path', 'dname']) data['hash'] = self.get_prop('md5', data['idx']) data.print(ignore=['full_path', 'hash']) data....
random_line_split
file_organizer.py
% fpath)['out'] for fpath in fpaths) def _abs(self, rel_paths): for rel_path in rel_paths: yield join(self.dpath, rel_path) def get_prop(self, attrname, idxs=None): """ Caching getter """ if attrname not in self.attrs:
prop_list = self.attrs[attrname] if idxs is None: idxs = list(range(len(prop_list))) props = prop_list else: props = ut.take(prop_list, idxs) miss_flags = ut.flag_None_items(props) if any(miss_flags): miss_idxs = ut.compress(idxs, ...
self.attrs[attrname] = [None for _ in range(len(self))]
conditional_block
file_organizer.py
def index(self): fpaths = self.fpaths() prog = ut.ProgIter(fpaths, length=len(self), label='building uuid') self.uuids = self._md5(prog) def _nbytes(self, fpaths): return (ut.get_file_nBytes(fpath) for fpath in fpaths) def _full_path(self, fpaths): return fpaths ...
def __init__(self, dpath): self.dpath = dpath self.rel_fpath_list = None def populate(self): self.rel_fpath_list = ut.glob(self.dpath, '*', recursive=True, fullpath=False, with_dirs=False) self.attrs = { # 'nbytes': list(map(ut.get_...
identifier_body
file_organizer.py
% fpath)['out'] for fpath in fpaths) def _abs(self, rel_paths): for rel_path in rel_paths: yield join(self.dpath, rel_path) def get_prop(self, attrname, idxs=None): """ Caching getter """ if attrname not in self.attrs: self.attrs[attrname] = [No...
(src, dst): try: shutil.move(src, dst) except OSError: return 1 return 0 error_list = [ trymove(src, dst) for (src, dst) in ut.ProgIter(move_tasks, lbl='moving') ] assert not any(error_list), 'error merg...
trymove
identifier_name
test_interruptible.py
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Getting Things GNOME! - a personal organizer for the GNOME desktop # Copyright (c) 2008-2013 - Lionel Dricot & Bertrand Rousseau # # This program is free software: you can redistribute it and/or modify it under # t...
thread = Thread(target=never_ending, args=(cancellation_point, )) thread.start() self.thread_started.wait() self.quit_condition = True countdown = 10 while thread.is_alive() and countdown > 0: time.sleep(0.1) countdown -= 1 self.assertFals...
time.sleep(0.1) cancellation_point()
conditional_block
test_interruptible.py
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Getting Things GNOME! - a personal organizer for the GNOME desktop # Copyright (c) 2008-2013 - Lionel Dricot & Bertrand Rousseau # # This program is free software: you can redistribute it and/or modify it under # t...
self.thread_started.set() while True: time.sleep(0.1) cancellation_point() thread = Thread(target=never_ending, args=(cancellation_point, )) thread.start() self.thread_started.wait() self.quit_condition = True countdown = 10...
random_line_split
test_interruptible.py
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Getting Things GNOME! - a personal organizer for the GNOME desktop # Copyright (c) 2008-2013 - Lionel Dricot & Bertrand Rousseau # # This program is free software: you can redistribute it and/or modify it under # t...
thread = Thread(target=never_ending, args=(cancellation_point, )) thread.start() self.thread_started.wait() self.quit_condition = True countdown = 10 while thread.is_alive() and countdown > 0: time.sleep(0.1) countdown -= 1 self.assertFals...
self.thread_started.set() while True: time.sleep(0.1) cancellation_point()
identifier_body
test_interruptible.py
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Getting Things GNOME! - a personal organizer for the GNOME desktop # Copyright (c) 2008-2013 - Lionel Dricot & Bertrand Rousseau # # This program is free software: you can redistribute it and/or modify it under # t...
(): return unittest.TestLoader().loadTestsFromTestCase(TestInterruptible)
test_suite
identifier_name
vector.py
from victor.exceptions import ( FieldValidationException, FieldTypeConversionError, FieldRequiredError, VectorInputTypeError ) class Field(object): required = True """Field is required and an exception will be raised if missing""" missing_value = None """Value to use when field is mis...
class Vector(object): def __init__(self): self.input_data = {} self._fields = {} self._map = {} self._required = [] self._setup_fields() def get_name(self): return self.__class__.__name__ def __call__(self, data): return self.input(data) def...
if not isinstance(value, (list, tuple)): raise FieldValidationException('ListField requires data ' 'to be a sequence type') for x in value: self.cls.set_data(value) self.data = value return True
identifier_body
vector.py
from victor.exceptions import ( FieldValidationException, FieldTypeConversionError, FieldRequiredError, VectorInputTypeError ) class Field(object): required = True """Field is required and an exception will be raised if missing""" missing_value = None """Value to use when field is mis...
self._setup_fields() def get_name(self): return self.__class__.__name__ def __call__(self, data): return self.input(data) def input(self, data): self._map = {} if not isinstance(data, dict): raise VectorInputTypeError('Vector input not a dictionary') ...
self._fields = {} self._map = {} self._required = []
random_line_split
vector.py
from victor.exceptions import ( FieldValidationException, FieldTypeConversionError, FieldRequiredError, VectorInputTypeError ) class Field(object): required = True """Field is required and an exception will be raised if missing""" missing_value = None """Value to use when field is mis...
(self, value): return self.cast_cls(value) def set_data(self, value): if self.strict: if not self._validate(value): raise FieldValidationException('%s does not ' 'except this value' ...
_cast_type
identifier_name
vector.py
from victor.exceptions import ( FieldValidationException, FieldTypeConversionError, FieldRequiredError, VectorInputTypeError ) class Field(object): required = True """Field is required and an exception will be raised if missing""" missing_value = None """Value to use when field is mis...
return True class IntField(Field): cast_cls = int _cast_fallback_value = 0 def __init__(self, *args, **kwargs): super(IntField, self).__init__(*args, **kwargs) if self.missing_value is None: self.missing_value = self._cast_fallback_value def _cast_type(self, va...
return False
conditional_block
sk1.js
window._skel_config = { prefix: 'css/style', preloadStyleSheets: true, resetCSS: true, boxModel: 'border', grid: { gutters: 30 }, breakpoints: { wide: { range: '1200-', containers: 1140, grid: { gutters: 50 } }, narrow: { range: '481-1199', containers: 960 }, mobile: { r...
$("#resultID").val(process(selected, opOne,opTwo)); // puts the convertion into the correct dom element on the page. }).change(); }); function process(selected, opOne,opTwo) { switch (selected) { case "+": return Calc.AddNo(opOne,opTwo); break; case "-"...
// console.log($('#conversion :selected').val()); //write it out to the console to verify what was
random_line_split
sk1.js
window._skel_config = { prefix: 'css/style', preloadStyleSheets: true, resetCSS: true, boxModel: 'border', grid: { gutters: 30 }, breakpoints: { wide: { range: '1200-', containers: 1140, grid: { gutters: 50 } }, narrow: { range: '481-1199', containers: 960 }, mobile: { r...
}); $("#clear").click(function () { $("#opOneID").val(''); $("#opTwoID").val(''); $("#resultID").val(''); }); $("#pnlRemove").click(function () { /* this function remove the fron panelof the cube so you can see inside and changes the bottom image which is the mancheste...
$("#resultID").val(process(selected, opOne, opTwo)); // puts the result into the correct dom element resultID on the page. }
conditional_block
sk1.js
window._skel_config = { prefix: 'css/style', preloadStyleSheets: true, resetCSS: true, boxModel: 'border', grid: { gutters: 30 }, breakpoints: { wide: { range: '1200-', containers: 1140, grid: { gutters: 50 } }, narrow: { range: '481-1199', containers: 960 }, mobile: { r...
elected, opOne,opTwo) { switch (selected) { case "+": return Calc.AddNo(opOne,opTwo); break; case "-": return Calc.SubNo(opOne, opTwo); break; case "/": return Calc.DivideNo(opOne, opTwo); break; case "*": ...
ocess(s
identifier_name
sk1.js
window._skel_config = { prefix: 'css/style', preloadStyleSheets: true, resetCSS: true, boxModel: 'border', grid: { gutters: 30 }, breakpoints: { wide: { range: '1200-', containers: 1140, grid: { gutters: 50 } }, narrow: { range: '481-1199', containers: 960 }, mobile: { r...
return "Error ! "; // code to be executed if n is different from case 1 and 2 } }
switch (selected) { case "+": return Calc.AddNo(opOne,opTwo); break; case "-": return Calc.SubNo(opOne, opTwo); break; case "/": return Calc.DivideNo(opOne, opTwo); break; case "*": return Calc.Mul...
identifier_body
config.py
#!/usr/bin/env python # -*- coding:utf-8 -*- """ read the config file ,parse config """ import os import ConfigParser import re # get config file def get_config(section, key):
# database config dbhost = get_config("database", "dbhost") dbport = int(get_config("database", "dbport")) dbuser = get_config("database", "dbuser") dbpass = get_config("database", "dbpass") dbname = get_config("database", "dbname") # server config port = get_config("server", "port") address = get_config("server", "...
config = ConfigParser.ConfigParser() path = os.path.split(os.path.split(os.path.realpath(__file__))[0])[0] + '/conf/oms_test.conf' config.read(path) return config.get(section, key)
identifier_body
config.py
#!/usr/bin/env python # -*- coding:utf-8 -*- """ read the config file ,parse config """ import os import ConfigParser import re # get config file def get_config(section, key): config = ConfigParser.ConfigParser() path = os.path.split(os.path.split(os.path.realpath(__file__))[0])[0] + '/conf/oms_test.co...
# mail config mail_open = get_config("mail", "mail_open") mail_host = get_config("mail", "mail_host") mail_user = get_config("mail", "mail_user") mail_pass = get_config("mail", "mail_pass") mail_postfix = get_config("mail", "mail_postfix")
random_line_split
config.py
#!/usr/bin/env python # -*- coding:utf-8 -*- """ read the config file ,parse config """ import os import ConfigParser import re # get config file def
(section, key): config = ConfigParser.ConfigParser() path = os.path.split(os.path.split(os.path.realpath(__file__))[0])[0] + '/conf/oms_test.conf' config.read(path) return config.get(section, key) # database config dbhost = get_config("database", "dbhost") dbport = int(get_config("database", "dbport"))...
get_config
identifier_name
config.py
#!/usr/bin/env python # -*- coding:utf-8 -*- """ read the config file ,parse config """ import os import ConfigParser import re # get config file def get_config(section, key): config = ConfigParser.ConfigParser() path = os.path.split(os.path.split(os.path.realpath(__file__))[0])[0] + '/conf/oms_test.co...
elif re.match("^[0-9]*m$", expire_time): expire_second = int(expire_time.replace('m', '')) * 60 elif re.match("^[0-9]*s$", expire_time): expire_second = int(expire_time.replace('s', '')) # mail config mail_open = get_config("mail", "mail_open") mail_host = get_config("mail", "mail_host") mail_user = get_confi...
expire_second = int(expire_time.replace('h', '')) * 3600
conditional_block
OscillatorTests.js
define(["helper/OutputAudio", "Tone/source/Oscillator", "helper/Offline", "Test", "helper/Meter"], function (OutputAudio, Oscillator, Offline, Test, Meter) { return function(Constr, args){ context("Oscillator Tests", function(){ it ("extends Tone.Oscillator", function(){ var instance = new Constr(args); ...
}); meter.after(function(){ osc.dispose(); done(); }); meter.run(); }); }); }; });
{ throw new Error("audio clipped with level "+level); }
conditional_block
OscillatorTests.js
define(["helper/OutputAudio", "Tone/source/Oscillator", "helper/Offline", "Test", "helper/Meter"], function (OutputAudio, Oscillator, Offline, Test, Meter) { return function(Constr, args){ context("Oscillator Tests", function(){ it ("extends Tone.Oscillator", function(){ var instance = new Constr(args); ...
it("can set/set the frequency", function(){ var instance = new Constr(args); instance.frequency.value = 110; expect(instance.frequency.value).to.equal(110); instance.start(); instance.frequency.value = 220; expect(instance.frequency.value).to.equal(220); instance.dispose(); }); it...
expect(instance.frequency.value).to.equal(200); expect(instance.detune.value).to.equal(-20); instance.dispose(); });
random_line_split
TextAreaAdapter.test.js
import React from "react"; import { mount } from "enzyme"; import { TextArea as VanillaTextArea } from "hig-vanilla"; import TextAreaAdapter from "./TextAreaAdapter"; describe("TextAreaAdapter", () => { it("implements the hig interface", () => { expect(spiedInstance => { mount( <TextAreaAdapter ...
required="" /> ); }).toImplementHIGInterfaceOf(VanillaTextArea); }); });
random_line_split
adrive.py
"""audio driver subsystem""" from os.path import exists
from subprocess import check_call from functools import partial from .drive import Driver import click DRIVE_QUEUE = 'a.drive' CTL_PATH = '{}/.config/pianobar/ctl'.format(environ['HOME']) COMMANDS = {'p', 'n', '^', '(', ')'} def callback(ctl:'file_t', cmd:str) -> "IO ()": """writes command to ctl pipe""" if ...
from os import environ
random_line_split
adrive.py
"""audio driver subsystem""" from os.path import exists from os import environ from subprocess import check_call from functools import partial from .drive import Driver import click DRIVE_QUEUE = 'a.drive' CTL_PATH = '{}/.config/pianobar/ctl'.format(environ['HOME']) COMMANDS = {'p', 'n', '^', '(', ')'} def callback...
@click.command() @click.option('--ctl_path', default=CTL_PATH) @click.option('--queue', default=DRIVE_QUEUE) def main(ctl_path:str, queue:str) -> "IO ()": """daemon for a.drive queue consumption""" if not exists(ctl_path): with open('/dev/null', 'w') as null: check_call(['pianoctl'], stdo...
"""writes command to ctl pipe""" if cmd not in COMMANDS: return ctl.write(cmd) ctl.flush()
identifier_body
adrive.py
"""audio driver subsystem""" from os.path import exists from os import environ from subprocess import check_call from functools import partial from .drive import Driver import click DRIVE_QUEUE = 'a.drive' CTL_PATH = '{}/.config/pianobar/ctl'.format(environ['HOME']) COMMANDS = {'p', 'n', '^', '(', ')'} def callback...
with open(ctl_path, 'w') as ctl: Driver(callback=partial(callback, ctl), queue=queue).drive()
with open('/dev/null', 'w') as null: check_call(['pianoctl'], stdout=null)
conditional_block
adrive.py
"""audio driver subsystem""" from os.path import exists from os import environ from subprocess import check_call from functools import partial from .drive import Driver import click DRIVE_QUEUE = 'a.drive' CTL_PATH = '{}/.config/pianobar/ctl'.format(environ['HOME']) COMMANDS = {'p', 'n', '^', '(', ')'} def callback...
(ctl_path:str, queue:str) -> "IO ()": """daemon for a.drive queue consumption""" if not exists(ctl_path): with open('/dev/null', 'w') as null: check_call(['pianoctl'], stdout=null) with open(ctl_path, 'w') as ctl: Driver(callback=partial(callback, ctl), queue=queue).drive()
main
identifier_name
log.py
# Copyright 2014 Xinyu, He <legendmohe@foxmail.com> # # 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 o...
debug_logger.propagate = False # now if you use logger it will not log to console. comm_name = 'log/home.log' comm_logger = logging.getLogger('CommonLog') handler = logging.handlers.RotatingFileHandler(comm_name, maxBytes=20*1024*1024) formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s [%(filenam...
handler.setFormatter(formatter) debug_logger.setLevel(logging.DEBUG) debug_logger.addHandler(handler)
random_line_split
main.rs
#![feature(slice_concat_ext)] extern crate ramp; extern crate bufstream; extern crate regex; use std::sync::mpsc::channel; use std::thread; use std::sync::{RwLock, Arc}; use std::net::{TcpListener, TcpStream}; use std::io::{Read, BufRead, Write}; use regex::Regex; use std::slice::SliceConcatExt; #[macro_use] extern c...
, None => { stream.write("NOT FOUND\n".as_bytes()); } }; } continue } } }
{ let d = version.dependencies.join(","); let response = format!("{} {} {}\n", version.value, version.timestamp, d); ...
conditional_block
main.rs
#![feature(slice_concat_ext)] extern crate ramp; extern crate bufstream; extern crate regex; use std::sync::mpsc::channel; use std::thread; use std::sync::{RwLock, Arc}; use std::net::{TcpListener, TcpStream}; use std::io::{Read, BufRead, Write}; use regex::Regex; use std::slice::SliceConcatExt; #[macro_use] extern c...
() { /* Logger notes: RUST_LOG=error ./main RUST_LOG=info http://rust-lang.github.io/log/env_logger/ */ info!("Starting up RAMP socket server!"); let db = Arc::new(RwLock::new(Database::new())); let listener = TcpListener::bind("127.0.0.1:6000").unwrap(); info!("Socket bound");...
main
identifier_name
main.rs
#![feature(slice_concat_ext)] extern crate ramp; extern crate bufstream; extern crate regex; use std::sync::mpsc::channel; use std::thread; use std::sync::{RwLock, Arc}; use std::net::{TcpListener, TcpStream}; use std::io::{Read, BufRead, Write}; use regex::Regex; use std::slice::SliceConcatExt; #[macro_use] extern c...
handle_client(stream, db2) }); }, Err(e) => {} } } info!("Goodbye forever."); } fn handle_client(mut stream: TcpStream, mut db: DB ) { info!("Starting new client thread, creating regexes"); let prepare = Regex::new(r"prepare\s+(...
{ /* Logger notes: RUST_LOG=error ./main RUST_LOG=info http://rust-lang.github.io/log/env_logger/ */ info!("Starting up RAMP socket server!"); let db = Arc::new(RwLock::new(Database::new())); let listener = TcpListener::bind("127.0.0.1:6000").unwrap(); info!("Socket bound"); ...
identifier_body
main.rs
#![feature(slice_concat_ext)] extern crate ramp; extern crate bufstream; extern crate regex; use std::sync::mpsc::channel; use std::thread; use std::sync::{RwLock, Arc}; use std::net::{TcpListener, TcpStream}; use std::io::{Read, BufRead, Write}; use regex::Regex; use std::slice::SliceConcatExt; #[macro_use] extern c...
d); stream.write(response.as_bytes()); }, None => { stream.write("NOT FOUND\n".as_bytes()); } }; } continue } ...
random_line_split
__init__.py
# The contents of this file are subject to the BitTorrent Open Source License # Version 1.1 (the License). You may not copy or use this file, in either # source code or executable form, except in compliance with the License. You # may obtain a copy of the License at http://www.bittorrent.com/license/. # # Software di...
'BTFailure', 'Bencached', 'BencodeDecodeError', 'bencode', 'bdecode', 'bread', 'bwrite', 'encode', 'decode' ) DEFAULT = Bencode( encoding='utf-8', encoding_fallback='value', dict_ordered=True, dict_ordered_sort=True ) bdecode = DEFAULT.decode bencode = DEFAULT.enco...
__all__ = (
random_line_split
0006_auto_20161209_0108.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2016-12-09 01:08 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration):
INTO non_zero FROM hordak_leg WHERE transaction_id = tx_id GROUP BY amount_currency HAVING ABS(SUM(amount)) > 0 LIMIT 1; IF FOUND THEN ...
dependencies = [("hordak", "0005_account_currencies")] operations = [ migrations.RunSQL( """ CREATE OR REPLACE FUNCTION check_leg() RETURNS trigger AS $$ DECLARE tx_id INT; non_zero RECOR...
identifier_body
0006_auto_20161209_0108.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2016-12-09 01:08 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [("hordak", "0005_account_currencies")] operations = [ migrations.RunSQL( """ ...
non_zero RECORD; BEGIN IF (TG_OP = 'DELETE') THEN tx_id := OLD.transaction_id; ELSE tx_id := NEW.transaction_id; END IF; SELECT ABS(SUM(amount)) AS total,...
RETURNS trigger AS $$ DECLARE tx_id INT;
random_line_split
0006_auto_20161209_0108.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2016-12-09 01:08 from __future__ import unicode_literals from django.db import migrations class
(migrations.Migration): dependencies = [("hordak", "0005_account_currencies")] operations = [ migrations.RunSQL( """ CREATE OR REPLACE FUNCTION check_leg() RETURNS trigger AS $$ DECLARE tx_id INT; ...
Migration
identifier_name
relationshipAttribute.model.ts
import * as mongoose from 'mongoose'; import {RelationshipModel} from './relationship.model'; import {IRelationshipAttributeName, RelationshipAttributeNameModel} from './relationshipAttributeName.model'; import {IRelationshipAttributeNameUsage} from './relationshipAttributeNameUsage.model'; import {IRelationshipAttribu...
} // concrete model ..................................................................................................... RelationshipAttributeMongooseModel = Model( 'RelationshipAttribute', RelationshipAttributeSchema, RelationshipAttribute ) as mongoose.Model<IRelationshipAttributeDocument>;
{ return await RelationshipAttributeMongooseModel.create({ value: value, attributeName: attributeName }); }
identifier_body
relationshipAttribute.model.ts
import * as mongoose from 'mongoose'; import {RelationshipModel} from './relationship.model'; import {IRelationshipAttributeName, RelationshipAttributeNameModel} from './relationshipAttributeName.model'; import {IRelationshipAttributeNameUsage} from './relationshipAttributeNameUsage.model'; import {IRelationshipAttribu...
(): Promise<DTO> { const dto: DTO = { value: this.value, attributeName: await this.attributeName.toHrefValue(true) }; return dto; } } interface IRelationshipAttributeDocument extends IRelationshipAttribute, mongoose.Document { } // static ............................
toDTO
identifier_name
relationshipAttribute.model.ts
import * as mongoose from 'mongoose'; import {RelationshipModel} from './relationship.model'; import {IRelationshipAttributeName, RelationshipAttributeNameModel} from './relationshipAttributeName.model'; import {IRelationshipAttributeNameUsage} from './relationshipAttributeNameUsage.model'; import {IRelationshipAttribu...
import {PermissionTemplates} from '../../../commons/permissions/allPermission.templates'; import {PermissionEnforcers} from '../permissions/allPermission.enforcers'; // force schema to load first (see https://github.com/atogov/RAM/pull/220#discussion_r65115456) /* tslint:disable:no-unused-variable */ const _Relationsh...
random_line_split
enterSecondDH.js
/* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero Genera...
}
{ return false; }
conditional_block
enterSecondDH.js
/* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero Genera...
(pi) { var maps = [108000600, 108000601, 108000602]; if(pi.isQuestStarted(20201) || pi.isQuestStarted(20202) || pi.isQuestStarted(20203) || pi.isQuestStarted(20204) || pi.isQuestStarted(20205)) { pi.removeAll(4032096); pi.removeAll(4032097); pi.removeAll(4032098); pi.removeAll(40...
enter
identifier_name
enterSecondDH.js
/* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de>
this program under any other version of the GNU Affero General Public License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public L...
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation version 3 as published by the Free Software Foundation. You may not use, modify or distribute
random_line_split
enterSecondDH.js
/* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero Genera...
{ var maps = [108000600, 108000601, 108000602]; if(pi.isQuestStarted(20201) || pi.isQuestStarted(20202) || pi.isQuestStarted(20203) || pi.isQuestStarted(20204) || pi.isQuestStarted(20205)) { pi.removeAll(4032096); pi.removeAll(4032097); pi.removeAll(4032098); pi.removeAll(4032099...
identifier_body
app.ts
var shaderRepo: ShaderRepository = null; // global for debugging var environmentMap: CubeMap = null; var irradianceMap: CubeMap = null; interface AppParams { vp : HTMLCanvasElement; orbitCenter: gml.Vec4; orbitDistance: number; } class CubemapFilterApp { renderer: Renderer; camera: Camera; // camera buil...
} } var app: CubemapFilterApp = null; function StartApp() { if ( app == null ) { var params : AppParams = { vp : <HTMLCanvasElement> document.getElementById( "big-viewport" ), orbitCenter: new gml.Vec4( 0, 0, 0, 1 ), orbitDistance: 10 }; shaderRepo = new ShaderRepository( ( repo ) ...
{ if ( this.dirty ) { // rebuild camera let baseAim = new gml.Vec4( 0, 0, -1, 0 ); let rotY = gml.Mat4.rotateY( this.yaw ); let rotRight = rotY.transform( gml.Vec4.right ); let rotX = gml.Mat4.rotate( rotRight, this.pitch ); let rotAim = rotX.transform( rotY.transform( baseAim ...
identifier_body
app.ts
var shaderRepo: ShaderRepository = null; // global for debugging var environmentMap: CubeMap = null; var irradianceMap: CubeMap = null; interface AppParams { vp : HTMLCanvasElement; orbitCenter: gml.Vec4; orbitDistance: number; } class CubemapFilterApp { renderer: Renderer; camera: Camera; // camera buil...
} } var app: CubemapFilterApp = null; function StartApp() { if ( app == null ) { var params : AppParams = { vp : <HTMLCanvasElement> document.getElementById( "big-viewport" ), orbitCenter: new gml.Vec4( 0, 0, 0, 1 ), orbitDistance: 10 }; shaderRepo = new ShaderRepository( ( repo ) ...
{ // rebuild camera let baseAim = new gml.Vec4( 0, 0, -1, 0 ); let rotY = gml.Mat4.rotateY( this.yaw ); let rotRight = rotY.transform( gml.Vec4.right ); let rotX = gml.Mat4.rotate( rotRight, this.pitch ); let rotAim = rotX.transform( rotY.transform( baseAim ) ).normalized; le...
conditional_block
app.ts
var shaderRepo: ShaderRepository = null; // global for debugging var environmentMap: CubeMap = null; var irradianceMap: CubeMap = null; interface AppParams { vp : HTMLCanvasElement; orbitCenter: gml.Vec4; orbitDistance: number; } class CubemapFilterApp { renderer: Renderer; camera: Camera; // camera buil...
( params: AppParams, shaderRepo: ShaderRepository ) { this.renderer = new Renderer( params.vp, shaderRepo, new gml.Vec4( 0.8, 0.8, 0.8, 1 ) ); this.orbitCenter = params.orbitCenter; this.orbitDistance = params.orbitDistance; this.yaw = gml.fromDegrees( 180 ); this.pitch = gml.fromDegrees( 0 ); t...
constructor
identifier_name
app.ts
var shaderRepo: ShaderRepository = null; // global for debugging var environmentMap: CubeMap = null; var irradianceMap: CubeMap = null; interface AppParams { vp : HTMLCanvasElement; orbitCenter: gml.Vec4; orbitDistance: number; } class CubemapFilterApp { renderer: Renderer; camera: Camera; // camera buil...
let rotPos = this.orbitCenter.add( rotAim.negate().multiply( this.orbitDistance ) ); this.camera = new Camera( rotPos, rotAim, rotUp, rotRight ); this.renderer.setCamera( this.camera ); this.renderer.update(); this.renderer.renderIrradiance(); this.dirty = false; } } } var a...
let rotAim = rotX.transform( rotY.transform( baseAim ) ).normalized; let rotUp = rotRight.cross( rotAim );
random_line_split
getblocktemplate_proposals.py
#!/usr/bin/env python2 # Copyright (c) 2014-2015 The Aureus Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.test_framework import AureusTestFramework from test_framework.util import * from bina...
(b): return sha256(sha256(b).digest()).digest() def genmrklroot(leaflist): cur = leaflist while len(cur) > 1: n = [] if len(cur) & 1: cur.append(cur[-1]) for i in range(0, len(cur), 2): n.append(dblsha(cur[i] + cur[i+1])) cur = n return cur[0] de...
dblsha
identifier_name
getblocktemplate_proposals.py
#!/usr/bin/env python2 # Copyright (c) 2014-2015 The Aureus Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.test_framework import AureusTestFramework from test_framework.util import * from bina...
tmpl['bits'] = '1c0000ff' # impossible in the real world assert_template(node, tmpl, txlist, 'bad-diffbits') tmpl['bits'] = realbits # Test 9: Bad merkle root rawtmpl = template_to_bytes(tmpl, txlist) rawtmpl[4+32] = (rawtmpl[4+32] + 1) % 0x100 rsp = node.getblo...
pass # Expected txlist.pop() # Test 8: Bad bits realbits = tmpl['bits']
random_line_split
getblocktemplate_proposals.py
#!/usr/bin/env python2 # Copyright (c) 2014-2015 The Aureus Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.test_framework import AureusTestFramework from test_framework.util import * from bina...
def dblsha(b): return sha256(sha256(b).digest()).digest() def genmrklroot(leaflist): cur = leaflist while len(cur) > 1: n = [] if len(cur) & 1: cur.append(cur[-1]) for i in range(0, len(cur), 2): n.append(dblsha(cur[i] + cur[i+1])) cur = n retur...
if n < 0xfd: return pack('<B', n) if n <= 0xffff: return b'\xfd' + pack('<H', n) if n <= 0xffffffff: return b'\xfe' + pack('<L', n) return b'\xff' + pack('<Q', n)
identifier_body
getblocktemplate_proposals.py
#!/usr/bin/env python2 # Copyright (c) 2014-2015 The Aureus Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. from test_framework.test_framework import AureusTestFramework from test_framework.util import * from bina...
num_matched = num_matched+1 if num_matched == 0: raise AssertionError("No objects matched %s"%(str(to_match))) def b2x(b): return b2a_hex(b).decode('ascii') # NOTE: This does not work for signed numbers (set the high bit) or zero (use b'\0') def encodeUNum(n): s = bytearray(b'\1') ...
raise AssertionError("%s : expected %s=%s"%(str(item), str(key), str(value)))
conditional_block
lib.rs
// This file is part of rust-web/twig // // For the copyright and license information, please view the LICENSE // file that was distributed with this source code. //! Twig library for rust. //! //! # Examples //! //! ``` //! use twig::engine::Setup; //! use twig::loader; //! use twig::runtime::Runtime; //! use twig::t...
//! let compiled = engine.load_template("greetings", None).unwrap(); //! assert_eq!(&compiled.render(&runtime).unwrap(), "Hello world!") //! ``` extern crate regex; #[macro_use]pub mod api; pub mod engine; pub mod runtime; pub mod loader; pub mod template; pub mod extension; pub use engine::Engine; pub use engine::S...
//! runtime.set("name", "world"); //!
random_line_split
disney.py
# ex:ts=4:sw=4:sts=4:et # -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- from __future__ import absolute_import import json import re import copy import os from svtplay_dl.service import Service, OpenGraphThumbMixin from svtplay_dl.utils import get_http_data, check_redirect, filenamify from svtplay_dl...
(Service, OpenGraphThumbMixin): supported_domains = ['disney.se', 'video.disney.se'] def get(self, options): parse = urlparse(self.url) if parse.hostname == "video.disney.se": error, data = self.get_urldata() if error: log.error("Can't get the page") ...
Disney
identifier_name
disney.py
# ex:ts=4:sw=4:sts=4:et # -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- from __future__ import absolute_import import json import re import copy import os from svtplay_dl.service import Service, OpenGraphThumbMixin from svtplay_dl.utils import get_http_data, check_redirect, filenamify from svtplay_dl...
for x in n["data"]: if "flavors" in x: for i in x["flavors"]: if i["format"] == "mp4": yield HTTP(copy.copy(options), i["url"], i["bitrate"]) else: error, data ...
supported_domains = ['disney.se', 'video.disney.se'] def get(self, options): parse = urlparse(self.url) if parse.hostname == "video.disney.se": error, data = self.get_urldata() if error: log.error("Can't get the page") return if s...
identifier_body
disney.py
# ex:ts=4:sw=4:sts=4:et # -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- from __future__ import absolute_import import json import re import copy import os from svtplay_dl.service import Service, OpenGraphThumbMixin from svtplay_dl.utils import get_http_data, check_redirect, filenamify from svtplay_dl...
redirect = check_redirect(url) streams = hlsparse(redirect) for n in list(streams.keys()): yield HLS(copy.copy(options), streams[n], n)
else: options.output = title url = "http://cdnapi.kaltura.com/p/%s/sp/%s00/playManifest/entryId/%s/format/applehttp/protocol/http/a.m3u8?ks=%s&referrer=aHR0cDovL3d3dy5kaXNuZXkuc2U=&" % (partnerid[1:], partnerid[1:], entryid, ks)
random_line_split
disney.py
# ex:ts=4:sw=4:sts=4:et # -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- from __future__ import absolute_import import json import re import copy import os from svtplay_dl.service import Service, OpenGraphThumbMixin from svtplay_dl.utils import get_http_data, check_redirect, filenamify from svtplay_dl...
else: error, data = self.get_urldata() if error: log.error("Cant get the page") return match = re.search(r"uniqueId : '([^']+)'", data) if not match: log.error("Can't find video info") return ...
yield HTTP(copy.copy(options), i["url"], i["bitrate"])
conditional_block
msgsend-ring-mutex-arcs.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
let mut futures = Vec::new(); for i in range(1u, num_tasks) { //println!("spawning %?", i); let (new_chan, num_port) = init(); let num_chan_2 = num_chan.clone(); let new_future = Future::spawn(move|| { thread_ring(i, msg_per_task, num_chan...
{ let args = os::args(); let args = if os::getenv("RUST_BENCH").is_some() { vec!("".to_string(), "100".to_string(), "10000".to_string()) } else if args.len() <= 1u { vec!("".to_string(), "10".to_string(), "100".to_string()) } else { args.clone().into_iter().collect() }; ...
identifier_body
msgsend-ring-mutex-arcs.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let args = os::args(); let args = if os::getenv("RUST_BENCH").is_some() { vec!("".to_string(), "100".to_string(), "10000".to_string()) } else if args.len() <= 1u { vec!("".to_string(), "10".to_string(), "100".to_string()) } else { args.clone().into_iter().collect() }; ...
main
identifier_name
msgsend-ring-mutex-arcs.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
}); futures.push(new_future); num_chan = new_chan; }; // do our iteration thread_ring(0, msg_per_task, num_chan, num_port); // synchronize for f in futures.iter_mut() { f.get() } }); // all done, report stats. ...
let (new_chan, num_port) = init(); let num_chan_2 = num_chan.clone(); let new_future = Future::spawn(move|| { thread_ring(i, msg_per_task, num_chan_2, num_port)
random_line_split
e966a3afd100_separate_patreon_user_table.py
revision = 'e966a3afd100' down_revision = '954c3c4caf32' branch_labels = None depends_on = None import alembic import sqlalchemy import requests import pytz import dateutil.parser import datetime def upgrade(): patreon_users = alembic.op.create_table("patreon_users", sqlalchemy.Column("id", sqlalchemy.Integer, pri...
alembic.op.add_column("users", sqlalchemy.Column("patreon_access_token", sqlalchemy.Text)) alembic.op.add_column("users", sqlalchemy.Column("patreon_refresh_token", sqlalchemy.Text)) alembic.op.add_column("users", sqlalchemy.Column("patreon_token_expires", sqlalchemy.DateTime(timezone=True))) conn = alembic.op.get_...
identifier_body
e966a3afd100_separate_patreon_user_table.py
revision = 'e966a3afd100' down_revision = '954c3c4caf32' branch_labels = None depends_on = None import alembic import sqlalchemy import requests import pytz import dateutil.parser import datetime def upgrade(): patreon_users = alembic.op.create_table("patreon_users", sqlalchemy.Column("id", sqlalchemy.Integer, pri...
meta.reflect() users = meta.tables["users"] existing_accounts = conn.execute(sqlalchemy.select([users.c.id, users.c.patreon_access_token, users.c.patreon_refresh_token, users.c.patreon_token_expires]) .where(users.c.patreon_access_token.isnot(None))) all_patreon_users = [] all_users = [] clientid = alembic.cont...
) # TODO: migrate conn = alembic.op.get_bind() meta = sqlalchemy.MetaData(bind=conn)
random_line_split
e966a3afd100_separate_patreon_user_table.py
revision = 'e966a3afd100' down_revision = '954c3c4caf32' branch_labels = None depends_on = None import alembic import sqlalchemy import requests import pytz import dateutil.parser import datetime def upgrade(): patreon_users = alembic.op.create_table("patreon_users", sqlalchemy.Column("id", sqlalchemy.Integer, pri...
all_patreon_users.append(user) all_users.append((user_id, data["data"]["id"])) alembic.op.bulk_insert(patreon_users, all_patreon_users) for user_id, patreon_id in all_users: conn.execute(users.update() .values(patreon_user=patreon_users.c.id) .where(users.c.id == user_id) .where(patreon_users.c.pat...
for pledge in data["data"]["relationships"]["pledges"]["data"]: for obj in data["included"]: if obj["id"] == pledge["id"] and obj["type"] == pledge["type"]: user["pledge_start"] = dateutil.parser.parse(obj["attributes"]["created_at"])
conditional_block
e966a3afd100_separate_patreon_user_table.py
revision = 'e966a3afd100' down_revision = '954c3c4caf32' branch_labels = None depends_on = None import alembic import sqlalchemy import requests import pytz import dateutil.parser import datetime def upgrade(): patreon_users = alembic.op.create_table("patreon_users", sqlalchemy.Column("id", sqlalchemy.Integer, pri...
(): alembic.op.add_column("users", sqlalchemy.Column("patreon_access_token", sqlalchemy.Text)) alembic.op.add_column("users", sqlalchemy.Column("patreon_refresh_token", sqlalchemy.Text)) alembic.op.add_column("users", sqlalchemy.Column("patreon_token_expires", sqlalchemy.DateTime(timezone=True))) conn = alembic.op...
downgrade
identifier_name
partner-alias-selection.js
$(function() { /* ------------ 合作伙伴信息 ------------ */ $( "#partner_id" ).combobox( { url : ksa.buildUrl( "/data/combo", "bd-partner-all" ), onSelect : function( record ) { $grid.datagrid( "load", { id : record.id } ); } } ); // 确认选择 ...
sager.confirm( "确定删除所选抬头吗?", function( ok ){ if( ok ) { $.ajax({ url: ksa.buildUrl( "/component/bd", "partner-alias-delete" ), data: { "partner.id" : $("#partner_id").combobox("getValue"), extra : $grid.datagrid("getSelected") }, ...
$.mes
identifier_name
partner-alias-selection.js
$(function() { /* ------------ 合作伙伴信息 ------------ */ $( "#partner_id" ).combobox( { url : ksa.buildUrl( "/data/combo", "bd-partner-all" ), onSelect : function( record ) { $grid.datagrid( "load", { id : record.id } ); } } ); // 确认选择 ...
success: function( result ) { try { if (result.status == "success") { // 添加成功 parent.$.close( extra ); return false; } else { $.messager.error( resul...
$.ajax({ url: ksa.buildUrl( "/component/bd", "partner-alias-insert" ), data: { "partner.id" : $("#partner_id").combobox("getValue"), extra : extra },
random_line_split
partner-alias-selection.js
$(function() { /* ------------ 合作伙伴信息 ------------ */ $( "#partner_id" ).combobox( { url : ksa.buildUrl( "/data/combo", "bd-partner-all" ), onSelect : function( record ) { $grid.datagrid( "load", { id : record.id } ); } } ); // 确认选择 ...
er.confirm( "确定删除所选抬头吗?", function( ok ){ if( ok ) { $.ajax({ url: ksa.buildUrl( "/component/bd", "partner-alias-delete" ), data: { "partner.id" : $("#partner_id").combobox("getValue"), extra : $grid.datagrid("getSelected") }, ...
identifier_body
partner-alias-selection.js
$(function() { /* ------------ 合作伙伴信息 ------------ */ $( "#partner_id" ).combobox( { url : ksa.buildUrl( "/data/combo", "bd-partner-all" ), onSelect : function( record ) { $grid.datagrid( "load", { id : record.id } ); } } ); // 确认选择 ...
sage ); $("#btn_extra_ok").attr("disabled", null ); } } catch (e) { $("#btn_extra_ok").attr("disabled", null ); } } }); } } ); // 添加关闭 $("#btn_extra_close").click( function() { $("#extra_window").window("close"); } ); /...
extra ); return false; } else { $.messager.error( result.mes
conditional_block
lib.rs
//! A very simple HTTP server which responds with the plain text "Hello, World!" to every request. #![crate_name = "ruster"] extern crate time; extern crate http; use std::io::net::ip::{SocketAddr, Ipv4Addr}; use std::io::Writer; use http::server::{Config, Server, Request, ResponseWriter}; use http::headers::conten...
impl Server for HelloWorldServer { fn get_config(&self) -> Config { Config { bind_address: SocketAddr { ip: Ipv4Addr(127, 0, 0, 1), port: 8001 } } } fn handle_request(&self, _r: Request, w: &mut ResponseWriter) { w.headers.date = Some(time::now_utc()); w.headers.content_length = Some(14); w.heade...
random_line_split
lib.rs
//! A very simple HTTP server which responds with the plain text "Hello, World!" to every request. #![crate_name = "ruster"] extern crate time; extern crate http; use std::io::net::ip::{SocketAddr, Ipv4Addr}; use std::io::Writer; use http::server::{Config, Server, Request, ResponseWriter}; use http::headers::conten...
}
{ w.headers.date = Some(time::now_utc()); w.headers.content_length = Some(14); w.headers.content_type = Some(MediaType { type_: String::from_str("text"), subtype: String::from_str("plain"), parameters: vec!((String::from_str("charset"), String::from_str("UTF-8"))) }); w.headers.ser...
identifier_body
lib.rs
//! A very simple HTTP server which responds with the plain text "Hello, World!" to every request. #![crate_name = "ruster"] extern crate time; extern crate http; use std::io::net::ip::{SocketAddr, Ipv4Addr}; use std::io::Writer; use http::server::{Config, Server, Request, ResponseWriter}; use http::headers::conten...
(&self) -> Config { Config { bind_address: SocketAddr { ip: Ipv4Addr(127, 0, 0, 1), port: 8001 } } } fn handle_request(&self, _r: Request, w: &mut ResponseWriter) { w.headers.date = Some(time::now_utc()); w.headers.content_length = Some(14); w.headers.content_type = Some(MediaType { type_: St...
get_config
identifier_name
deadline.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
} #[cfg(test)] mod tests { use std::io; use std::time::Duration; use futures::{Future, empty, done}; use tokio_core::reactor::Core; use super::{deadline, DeadlineStatus}; //#[test] TODO: not working fn _deadline_timeout_works() { let mut core = Core::new().unwrap(); let deadline = deadline(Duration::from_m...
Ok(Async::NotReady) => Ok(Async::NotReady), Err((err, _other)) => Err(err), } }
random_line_split
deadline.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
/// Deadline future completion status. #[derive(Debug, PartialEq)] pub enum DeadlineStatus<T> { /// Completed a future. Meet(T), /// Faled with timeout. Timeout, } /// Future, which waits for passed future completion within given period, or fails with timeout. pub struct Deadline<F> where F: Future { future: Se...
{ let timeout: DeadlineBox<F> = Box::new(Timeout::new(duration, handle)?.map(|_| DeadlineStatus::Timeout)); let future: DeadlineBox<F> = Box::new(future.map(DeadlineStatus::Meet)); let deadline = Deadline { future: timeout.select(future), }; Ok(deadline) }
identifier_body
deadline.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
<F, T>(duration: Duration, handle: &Handle, future: F) -> Result<Deadline<F>, io::Error> where F: Future<Item = T, Error = io::Error> + Send + 'static, T: 'static { let timeout: DeadlineBox<F> = Box::new(Timeout::new(duration, handle)?.map(|_| DeadlineStatus::Timeout)); let future: DeadlineBox<F> = Box::new(future.m...
deadline
identifier_name
java.io.ObjectStreamField.d.ts
declare namespace java { namespace io { class ObjectStreamField implements java.lang.Comparable<java.lang.Object> { public constructor(arg0: java.lang.String | string, arg1: java.lang.Class<unknown>) public constructor(arg0: java.lang.String | string, arg1: java.lang.Class<unknown>, arg2: boolean | j...
getSignature(): java.lang.String } } }
getField(): java.lang.reflect.Field
random_line_split
java.io.ObjectStreamField.d.ts
declare namespace java { namespace io { class
implements java.lang.Comparable<java.lang.Object> { public constructor(arg0: java.lang.String | string, arg1: java.lang.Class<unknown>) public constructor(arg0: java.lang.String | string, arg1: java.lang.Class<unknown>, arg2: boolean | java.lang.Boolean) constructor(arg0: java.lang.String | string, a...
ObjectStreamField
identifier_name
_helpers.py
# Copyright 2016 Google 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, ...
'Expected "projects/{proj}/configs/{cfg}"') return result def variable_name_from_full_name(full_name): """Extract the variable name from a full resource name. >>> variable_name_from_full_name( 'projects/my-proj/configs/my-config/variables/var-name') "var-name" >>> ...
'Unexpected format of resource', full_name,
random_line_split
_helpers.py
# Copyright 2016 Google 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, ...
(full_name): """Extract the config name from a full resource name. >>> config_name_from_full_name('projects/my-proj/configs/my-config') "my-config" :type full_name: str :param full_name: The full resource name of a config. The full resource name looks like ``projects/project-na...
config_name_from_full_name
identifier_name
_helpers.py
# Copyright 2016 Google 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, ...
return result def variable_name_from_full_name(full_name): """Extract the variable name from a full resource name. >>> variable_name_from_full_name( 'projects/my-proj/configs/my-config/variables/var-name') "var-name" >>> variable_name_from_full_name( 'projects/m...
raise ValueError( 'Unexpected format of resource', full_name, 'Expected "projects/{proj}/configs/{cfg}"')
conditional_block
_helpers.py
# Copyright 2016 Google 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, ...
projects, _, configs, _, variables, result = full_name.split('/', 5) if (projects != 'projects' or configs != 'configs' or variables != 'variables'): raise ValueError( 'Unexpected format of resource', full_name, 'Expected "projects/{proj}/configs/{cfg}/variables/..."'...
"""Extract the variable name from a full resource name. >>> variable_name_from_full_name( 'projects/my-proj/configs/my-config/variables/var-name') "var-name" >>> variable_name_from_full_name( 'projects/my-proj/configs/my-config/variables/another/var/name') "another/v...
identifier_body
Chart.tsx
import * as React from "react"; import * as d3 from "d3"; import * as nv from "nvd3"; import { GreetingChartData } from "./types"; interface ChartProps { data: GreetingChartData; onSegmentSelected: (segment: string) => any; } export default class Chart extends React.Component<ChartProps> { _d3selection: any; /...
this._nvd3chart = chart; if (onSegmentSelected) { chart.pie.dispatch.on("elementClick", e => onSegmentSelected(e.data.label)); } return chart; }); } render() { const svgStyle = { height: "500px", width: "600px" }; return ( <div> <svg style=...
const { data, onSegmentSelected } = this.props; this._d3selection = d3.select(this._chart); this._d3selection.datum(data).call(chart);
random_line_split
Chart.tsx
import * as React from "react"; import * as d3 from "d3"; import * as nv from "nvd3"; import { GreetingChartData } from "./types"; interface ChartProps { data: GreetingChartData; onSegmentSelected: (segment: string) => any; } export default class Chart extends React.Component<ChartProps> { _d3selection: any; /...
() { const svgStyle = { height: "500px", width: "600px" }; return ( <div> <svg style={svgStyle} className="with-3d-shadow with-transitions" ref={c => (this._chart = c)} /> </div> ); } }
render
identifier_name
Chart.tsx
import * as React from "react"; import * as d3 from "d3"; import * as nv from "nvd3"; import { GreetingChartData } from "./types"; interface ChartProps { data: GreetingChartData; onSegmentSelected: (segment: string) => any; } export default class Chart extends React.Component<ChartProps> { _d3selection: any; /...
componentDidMount() { // http://nvd3.org/examples/pie.html nv.addGraph(() => { const chart = nv.models .pieChart() .x(d => d.label) .y(d => d.value) .showLabels(true); chart.legend.updateState(false); const { data, onSegmentSelected } = this.props; th...
{ console.log("Component will unmount"); this._d3selection.remove(); }
identifier_body
Chart.tsx
import * as React from "react"; import * as d3 from "d3"; import * as nv from "nvd3"; import { GreetingChartData } from "./types"; interface ChartProps { data: GreetingChartData; onSegmentSelected: (segment: string) => any; } export default class Chart extends React.Component<ChartProps> { _d3selection: any; /...
return chart; }); } render() { const svgStyle = { height: "500px", width: "600px" }; return ( <div> <svg style={svgStyle} className="with-3d-shadow with-transitions" ref={c => (this._chart = c)} /> </div> ); } }
{ chart.pie.dispatch.on("elementClick", e => onSegmentSelected(e.data.label)); }
conditional_block
film_sorter.py
#!/usr/bin/env python ''' Files and renames your films according to genre using IMDb API supert-is-taken 2015 ''' from imdb import IMDb import sys import re import os import errno import codecs db=IMDb() def
(argv): for filename in sys.argv[1:]: print filename movie_list=db.search_movie( cleanup_movie_string(filename) ) while len(movie_list) == 0: search_string = raw_input('No results, alternative search string: ') movie_list = db.search_movie( cleanup_movie_string(searc...
main
identifier_name
film_sorter.py
#!/usr/bin/env python ''' Files and renames your films according to genre using IMDb API supert-is-taken 2015 ''' from imdb import IMDb import sys import re import os import errno import codecs db=IMDb() def main(argv): for filename in sys.argv[1:]: print filename movie_list=db.search_movie( c...
if __name__=="__main__": sys.exit(main(sys.argv))
if os.path.isfile(filename): try: os.unlink(filename) except: pass
identifier_body
film_sorter.py
#!/usr/bin/env python ''' Files and renames your films according to genre using IMDb API supert-is-taken 2015 ''' from imdb import IMDb import sys import re import os import errno import codecs db=IMDb() def main(argv): for filename in sys.argv[1:]: print filename movie_list=db.search_movie( c...
return int(raw_input("choice: ")) def cleanup_movie_string(s): s = s.replace("WEB-DL", "") s = re.sub(r'-.*$', "", s) s = s.replace(".1.", " ") s = s.replace(".0.", " ") s = s.replace(".H.", " ") s = s.replace(".", " ") s = s.replace("mkv", "") s = s.replace("X264", "") s = s....
prompt = '%d: ' + movie['long imdb title'] print(prompt % i) i+=1
conditional_block
film_sorter.py
#!/usr/bin/env python ''' Files and renames your films according to genre using IMDb API supert-is-taken 2015 ''' from imdb import IMDb import sys import re import os import errno import codecs db=IMDb() def main(argv): for filename in sys.argv[1:]: print filename movie_list=db.search_movie( c...
except: pass def __unlink(filename): if os.path.isfile(filename): try: os.unlink(filename) except: pass if __name__=="__main__": sys.exit(main(sys.argv))
random_line_split