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
setup.py
#!/usr/bin/env python # vim: set filetype=python expandtab tabstop=4 shiftwidth=4 autoindent smartindent: #from distutils.core import setup import os import logging import setuptools import distutils.cmd import subprocess # TODO add check to make sure required libs are present (eg sqlite3) _PACKAGE_NAME = 'python...
name = _PACKAGE_NAME, version = _PACKAGE_VERSION, description = 'Python libraries for reading iBank files.', author = 'Craig Sebenik', author_email = 'craig5@users.noreply.github.com', url = 'https://github.com/craig5/python-ibank', scripts = [os.path...
setuptools.setup(
random_line_split
formidable-tests.ts
/// <reference path="./formidable.d.ts" /> import formidable = require('formidable'); import http = require('http'); import util = require('util'); http.createServer((req, res) => { if (req.url == '/upload' && req.method.toLowerCase() == 'post')
// show a file upload form res.writeHead(200, {'content-type': 'text/html'}); res.end( '<form action="/upload" enctype="multipart/form-data" method="post">'+ '<input type="text" name="title"><br>'+ '<input type="file" name="upload" multiple="multiple"><br>'+ '<input type="submit" value="Upload">...
{ // parse a file upload var form = new formidable.IncomingForm(); form.parse(req, (err, fields, files) => { res.writeHead(200, {'content-type': 'text/plain'}); res.write('received upload:\n\n'); res.end(util.inspect({fields: fields, files: files})); }); return; }
conditional_block
formidable-tests.ts
/// <reference path="./formidable.d.ts" /> import formidable = require('formidable'); import http = require('http'); import util = require('util');
http.createServer((req, res) => { if (req.url == '/upload' && req.method.toLowerCase() == 'post') { // parse a file upload var form = new formidable.IncomingForm(); form.parse(req, (err, fields, files) => { res.writeHead(200, {'content-type': 'text/plain'}); res.write('received upload:\n\n');...
random_line_split
influx_db.py
import logging from redash.query_runner import * from redash.utils import json_dumps logger = logging.getLogger(__name__) try: from influxdb import InfluxDBClusterClient enabled = True except ImportError: enabled = False def _transform_result(results): result_columns = [] result_rows = [] ...
return "influxdb" def run_query(self, query, user): client = InfluxDBClusterClient.from_DSN(self.configuration['url']) logger.debug("influxdb url: %s", self.configuration['url']) logger.debug("influxdb got query: %s", query) try: results = client.query(query) ...
random_line_split
influx_db.py
import logging from redash.query_runner import * from redash.utils import json_dumps logger = logging.getLogger(__name__) try: from influxdb import InfluxDBClusterClient enabled = True except ImportError: enabled = False def _transform_result(results): result_columns = [] result_rows = [] ...
@classmethod def enabled(cls): return enabled @classmethod def annotate_query(cls): return False @classmethod def type(cls): return "influxdb" def run_query(self, query, user): client = InfluxDBClusterClient.from_DSN(self.configuration['url']) lo...
return { 'type': 'object', 'properties': { 'url': { 'type': 'string' } }, 'required': ['url'] }
identifier_body
influx_db.py
import logging from redash.query_runner import * from redash.utils import json_dumps logger = logging.getLogger(__name__) try: from influxdb import InfluxDBClusterClient enabled = True except ImportError: enabled = False def _transform_result(results): result_columns = [] result_rows = [] ...
(cls): return enabled @classmethod def annotate_query(cls): return False @classmethod def type(cls): return "influxdb" def run_query(self, query, user): client = InfluxDBClusterClient.from_DSN(self.configuration['url']) logger.debug("influxdb url: %s", sel...
enabled
identifier_name
influx_db.py
import logging from redash.query_runner import * from redash.utils import json_dumps logger = logging.getLogger(__name__) try: from influxdb import InfluxDBClusterClient enabled = True except ImportError: enabled = False def _transform_result(results): result_columns = [] result_rows = [] ...
result_rows.append(result_row) return json_dumps({ "columns": [{'name': c} for c in result_columns], "rows": result_rows }) class InfluxDB(BaseQueryRunner): noop_query = "show measurements limit 1" @classmethod def configuration_schema(cls): return { ...
tags = series.get('tags', {}) if column in tags: result_row[column] = tags[column] elif column in series['columns']: index = series['columns'].index(column) value = point[index] result...
conditional_block
job.rs
use std::io::{self, BufRead, Read}; use std::marker::PhantomData; use std::ops::Deref; use std::ptr; use crate::{raw, Error}; pub struct JobDriver<R> { input: R, job: Job, input_ended: bool, } pub struct Job(pub *mut raw::rs_job_t); // Wrapper around rs_buffers_t. struct Buffers<'a> { inner: raw::rs...
next_out: out_buf.as_mut_ptr() as *mut i8, avail_out: out_buf.len(), }, _phantom: PhantomData, } } pub fn with_no_out(in_buf: &'a [u8], eof_in: bool) -> Self { Buffers { inner: raw::rs_buffers_t { next_in: in_bu...
eof_in: if eof_in { 1 } else { 0 },
random_line_split
job.rs
use std::io::{self, BufRead, Read}; use std::marker::PhantomData; use std::ops::Deref; use std::ptr; use crate::{raw, Error}; pub struct JobDriver<R> { input: R, job: Job, input_ended: bool, } pub struct Job(pub *mut raw::rs_job_t); // Wrapper around rs_buffers_t. struct Buffers<'a> { inner: raw::rs...
pub fn into_inner(self) -> R { self.input } /// Complete the job by working without an output buffer. /// /// If the job needs to write some data, an `ErrorKind::WouldBlock` error is returned. pub fn consume_input(&mut self) -> io::Result<()> { loop { let (res, rea...
{ JobDriver { input, job, input_ended: false, } }
identifier_body
job.rs
use std::io::{self, BufRead, Read}; use std::marker::PhantomData; use std::ops::Deref; use std::ptr; use crate::{raw, Error}; pub struct JobDriver<R> { input: R, job: Job, input_ended: bool, } pub struct Job(pub *mut raw::rs_job_t); // Wrapper around rs_buffers_t. struct Buffers<'a> { inner: raw::rs...
(&self) -> usize { self.inner.avail_out } }
available_output
identifier_name
bootstrap.js
//Declare app level module which depends on filters, and services var SFApplicationAuth = angular.module('SFApplicationAuth.Auth',[]); SFApplicationAuth.config( [ '$stateProvider', '$urlRouterProvider', function ( $stateProvider, $urlRouterProvider ) { console.log("inciando bootstrap auth"); $stateProvid...
}]);
$rootScope.$on('$viewContentLoaded', function(event, viewConfig){ $log.log('$viewContentLoaded'); });
random_line_split
bootstrap.js
//Declare app level module which depends on filters, and services var SFApplicationAuth = angular.module('SFApplicationAuth.Auth',[]); SFApplicationAuth.config( [ '$stateProvider', '$urlRouterProvider', function ( $stateProvider, $urlRouterProvider ) { console.log("inciando bootstrap auth"); $stateProvid...
} }); $rootScope.$on('$stateChangeSuccess', function(next, current) { $log.log('$stateChangeSuccess'); }); $rootScope.$on('$stateChangeError', function( event, toState, toParams, fromState, fromParams, rejection) { $log.log('$stateChangeError'); }); $rootScope.$on('$stateUp...
{ $log.error( 'You don\'t have permission to access this area.' ); /** * Prevent Default action. */ event.preventDefault(); $log.log( 'Fazendo loggof' ); /** * Redirect to login */ $state.go( 'auth.logout' ); }
conditional_block
website.py
# -*- coding: utf-8 -*- # © 2015 Elico corp (www.elico-corp.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import base64 import random import string from binascii import hexlify, unhexlify from openerp import api, fields, models try: from captcha.image import ImageCaptcha except ImportE...
return chars
hars += string.uppercase
conditional_block
website.py
# -*- coding: utf-8 -*- # © 2015 Elico corp (www.elico-corp.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import base64 import random import string from binascii import hexlify, unhexlify from openerp import api, fields, models try: from captcha.image import ImageCaptcha except ImportE...
self, chars, size): return ''.join(random.choice(chars) for _ in range(size)) def _default_salt(self): return self._generate_random_str( string.digits + string.letters + string.punctuation, 100) # generate a random salt def _captcha_length(self): return [(str(i), st...
generate_random_str(
identifier_name
website.py
# -*- coding: utf-8 -*- # © 2015 Elico corp (www.elico-corp.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import base64 import random import string from binascii import hexlify, unhexlify from openerp import api, fields, models try: from captcha.image import ImageCaptcha except ImportE...
return self._generate_random_str( string.digits + string.letters + string.punctuation, 100) # generate a random salt def _captcha_length(self): return [(str(i), str(i)) for i in range(1, 11)] def _captcha_chars(self): return [ ('digits', 'Digits only'), ...
def _generate_random_str(self, chars, size): return ''.join(random.choice(chars) for _ in range(size)) def _default_salt(self):
random_line_split
website.py
# -*- coding: utf-8 -*- # © 2015 Elico corp (www.elico-corp.com) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). import base64 import random import string from binascii import hexlify, unhexlify from openerp import api, fields, models try: from captcha.image import ImageCaptcha except ImportE...
def _get_captcha_chars(self): chars = string.digits if self.captcha_chars == 'hexadecimal': # do not use the default string.hexdigits because it contains # lowercase chars += 'ABCDEF' elif self.captcha_chars == 'all': chars += string.uppercase...
eturn [ ('digits', 'Digits only'), ('hexadecimal', 'Hexadecimal'), ('all', 'Letters and Digits')]
identifier_body
AggHelp.py
# # AggHelp.py -- help classes for the Agg drawing # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. import aggdraw as agg from ginga import colors class AggContext(o...
return (int(r*255), int(g*255), int(b*255)) def get_pen(self, color, linewidth=1): # if hasattr(self, 'linestyle'): # if self.linestyle == 'dash': # cr.set_dash([ 3.0, 4.0, 6.0, 4.0], 5.0) p = agg.Pen(self.get_color(color), width=linewidth)...
r, g, b = 1.0, 1.0, 1.0
conditional_block
AggHelp.py
# # AggHelp.py -- help classes for the Agg drawing # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. import aggdraw as agg from ginga import colors class AggContext(o...
def text_extents(self, text, font): wd, ht = self.canvas.textsize(text, font) return wd, ht #END
color = self.get_color(color) # TODO: what kind of lookup can we use for this? filename = '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf' f = agg.Font(color, filename, size=size) return f
identifier_body
AggHelp.py
# # AggHelp.py -- help classes for the Agg drawing # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details.
class AggContext(object): def __init__(self, canvas): self.canvas = canvas def set_canvas(self, canvas): self.canvas = canvas def get_color(self, color): if isinstance(color, str): r, g, b = colors.lookup_color(color) elif isinstance(color, tuple): ...
import aggdraw as agg from ginga import colors
random_line_split
AggHelp.py
# # AggHelp.py -- help classes for the Agg drawing # # Eric Jeschke (eric@naoj.org) # # Copyright (c) Eric R. Jeschke. All rights reserved. # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. import aggdraw as agg from ginga import colors class AggContext(o...
(self, color, linewidth=1): # if hasattr(self, 'linestyle'): # if self.linestyle == 'dash': # cr.set_dash([ 3.0, 4.0, 6.0, 4.0], 5.0) p = agg.Pen(self.get_color(color), width=linewidth) return p def get_brush(self, color): p = agg.Bru...
get_pen
identifier_name
main.rs
/* --- Day 2: Bathroom Security --- You arrive at Easter Bunny Headquarters under cover of darkness. However, you left in such a rush that you forgot to use the bathroom! Fancy office buildings like this one usually have keypad locks on their bathrooms, so you search the front desk for the code. "In order to improve ...
(c : char) -> Direction { match c { 'U' => Direction::Up, 'D' => Direction::Down, 'L' => Direction::Left, 'R' => Direction::Right, _ => Direction::Up, } } fn move_cursor(numpad : &Numpad, cursor: &Cursor, dir : &Direction) -> Cursor { // calculate new position of t...
char_to_direction
identifier_name
main.rs
/* --- Day 2: Bathroom Security --- You arrive at Easter Bunny Headquarters under cover of darkness. However, you left in such a rush that you forgot to use the bathroom! Fancy office buildings like this one usually have keypad locks on their bathrooms, so you search the front desk for the code. "In order to improve ...
None, Some('A'), Some('B'), Some('C'), None, None, None, Some('D'), None, None ]; // and lets create our cursor, starting at the Five key let mut cursor : Cursor = 10; // convert characters to directions for line in lines { let sequence : Vec...
{ // read input from the file let mut f = File::open("input.txt").unwrap(); let mut input = String::new(); f.read_to_string(&mut input).ok(); // split into lines let lines : Vec<&str> = input.split('\n').collect(); let mut digits : Vec<char> = Vec::new(); // recreate the keypad with t...
identifier_body
main.rs
/* --- Day 2: Bathroom Security --- You arrive at Easter Bunny Headquarters under cover of darkness. However, you left in such a rush that you forgot to use the bathroom! Fancy office buildings like this one usually have keypad locks on their bathrooms, so you search the front desk for the code. "In order to improve ...
else { *cursor } }, } } fn is_valid(numpad: &Numpad, cursor : &Cursor) -> bool { numpad.get(*cursor).unwrap().is_some() } fn digit_for_cursor(numpad : &Numpad, cursor : &Cursor) -> char { numpad.get(*cursor).unwrap().unwrap().to_owned() }
{ cursor + row_length }
conditional_block
main.rs
/* --- Day 2: Bathroom Security --- You arrive at Easter Bunny Headquarters under cover of darkness. However, you left in such a rush that you forgot to use the bathroom! Fancy office buildings like this one usually have keypad locks on their bathrooms, so you search the front desk for the code. "In order to improve ...
You still start at "5" and stop when you're at an edge, but given the same instructions as above, the outcome is very different: You start at "5" and don't move at all (up and left are both edges), ending at 5. Continuing from "5", you move right twice and down three times (through "6", "7", "B", "D", "D"), ending at ...
D
random_line_split
menuanchoredposition.js
// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed ...
};
{ goog.positioning.MenuAnchoredPosition.superClass_.reposition.call( this, movableElement, movableCorner, opt_margin, opt_preferredSize); }
conditional_block
menuanchoredposition.js
// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed ...
/** * Encapsulates a popup position where the popup is anchored at a corner of * an element. The positioning behavior changes based on the values of * opt_adjust and opt_resize. * * When using this positioning object it's recommended that the movable element * be absolutely positioned. * * @param {Element} an...
random_line_split
atcacert.py
atcab import get_cryptoauthlib from .atcaenum import AtcaEnum import binascii class atcacert_cert_type_t(AtcaEnum): """Types of certificates""" CERTTYPE_X509 = 0 # Standard X509 certificate CERTTYPE_CUSTOM = 1 # Custom format class atcacert_cert_sn_src_t(AtcaEnum): """Sources for the cert...
class atcacert_std_cert_element_t(AtcaEnum): """Standard dynamic certificate elements""" STDCERT_PUBLIC_KEY = 0 STDCERT_SIGNATURE = 1 STDCERT_ISSUE_DATE = 2 STDCERT_EXPIRE_DATE = 3 STDCERT_SIGNER_ID = 4 STDCERT_CERT_SN = 5 STDCERT_AUTH_KEY_ID = 6 STDCERT_SUBJ_KEY_ID = 7 def _atc...
DATEFMT_ISO8601_SEP = 0 # ISO8601 full date YYYY-MM-DDThh:mm:ssZ DATEFMT_RFC5280_UTC = 1 # RFC 5280 (X.509) 4.1.2.5.1 UTCTime format YYMMDDhhmmssZ DATEFMT_POSIX_UINT32_BE = 2 # POSIX (aka UNIX) date format. Seconds since Jan 1, 1970. 32 bit unsigned integer, big endian. DATEFMT_POSIX_UINT32_LE = 3 # POS...
identifier_body
atcacert.py
09 = 0 # Standard X509 certificate CERTTYPE_CUSTOM = 1 # Custom format class atcacert_cert_sn_src_t(AtcaEnum): """Sources for the certificate serial number""" SNSRC_STORED = 0x0 # Cert serial is stored on the device. SNSRC_STORED_DYNAMIC = 0x7 # Cert serial is stored on the device with the...
_atcacert_convert_array(kwargs, f[0], f[1])
conditional_block
atcacert.py
atcab import get_cryptoauthlib from .atcaenum import AtcaEnum import binascii class atcacert_cert_type_t(AtcaEnum): """Types of certificates""" CERTTYPE_X509 = 0 # Standard X509 certificate CERTTYPE_CUSTOM = 1 # Custom format class atcacert_cert_sn_src_t(AtcaEnum): """Sources for the cert...
class atcacert_std_cert_element_t(AtcaEnum): """Standard dynamic certificate elements""" STDCERT_PUBLIC_KEY = 0 STDCERT_SIGNATURE = 1 STDCERT_ISSUE_DATE = 2 STDCERT_EXPIRE_DATE = 3 STDCERT_SIGNER_ID = 4 STDCERT_CERT_SN = 5 STDCERT_AUTH_KEY_ID = 6 STDCERT_SUBJ_KEY_ID = 7 def _atcace...
DATEFMT_POSIX_UINT32_LE = 3 # POSIX (aka UNIX) date format. Seconds since Jan 1, 1970. 32 bit unsigned integer, little endian. DATEFMT_RFC5280_GEN = 4 # RFC 5280 (X.509) 4.1.2.5.2 GeneralizedTime format YYYYMMDDhhmmssZ
random_line_split
atcacert.py
cab import get_cryptoauthlib from .atcaenum import AtcaEnum import binascii class atcacert_cert_type_t(AtcaEnum): """Types of certificates""" CERTTYPE_X509 = 0 # Standard X509 certificate CERTTYPE_CUSTOM = 1 # Custom format class atcacert_cert_sn_src_t(AtcaEnum): """Sources for the certif...
(Structure): _fields_ = [ ('id', c_char * 16), # ID identifying this element. ('device_loc', atcacert_device_loc_t), # Location in the device for the element. ('cert_loc', atcacert_cert_loc_t) # Location in the certificate template for the element. ] class atcacert_def_t(Structure):...
atcacert_cert_element_t
identifier_name
mod.rs
use collections::{Set, set}; use lr1::core::*; use lr1::first::FirstSets; use lr1::state_graph::StateGraph; use grammar::repr::*; mod reduce; mod shift; mod trace_graph; pub struct
<'trace, 'grammar: 'trace> { states: &'trace [LR1State<'grammar>], first_sets: &'trace FirstSets, state_graph: StateGraph, trace_graph: TraceGraph<'grammar>, visited_set: Set<(StateIndex, NonterminalString)>, } impl<'trace, 'grammar> Tracer<'trace, 'grammar> { pub fn new(first_sets: &'trace Fir...
Tracer
identifier_name
mod.rs
use collections::{Set, set}; use lr1::core::*; use lr1::first::FirstSets; use lr1::state_graph::StateGraph; use grammar::repr::*; mod reduce; mod shift; mod trace_graph; pub struct Tracer<'trace, 'grammar: 'trace> { states: &'trace [LR1State<'grammar>], first_sets: &'trace FirstSets, state_graph: StateGra...
} pub use self::trace_graph::TraceGraph;
{ Tracer { states: states, first_sets: first_sets, state_graph: StateGraph::new(states), trace_graph: TraceGraph::new(), visited_set: set(), } }
identifier_body
mod.rs
use collections::{Set, set}; use lr1::core::*; use lr1::first::FirstSets; use lr1::state_graph::StateGraph;
use grammar::repr::*; mod reduce; mod shift; mod trace_graph; pub struct Tracer<'trace, 'grammar: 'trace> { states: &'trace [LR1State<'grammar>], first_sets: &'trace FirstSets, state_graph: StateGraph, trace_graph: TraceGraph<'grammar>, visited_set: Set<(StateIndex, NonterminalString)>, } impl<'t...
random_line_split
texgen_emboss.py
'''OpenGL extension NV.texgen_emboss This module customises the behaviour of the OpenGL.raw.GL.NV.texgen_emboss to provide a more Python-friendly API Overview (from the spec) This extension provides a new texture coordinate generation mode suitable for multitexture-based embossing (or bump mapping) effects. ...
(): '''Return boolean indicating whether this extension is available''' from OpenGL import extensions return extensions.hasGLExtension( _EXTENSION_NAME ) ### END AUTOGENERATED SECTION
glInitTexgenEmbossNV
identifier_name
texgen_emboss.py
'''OpenGL extension NV.texgen_emboss This module customises the behaviour of the OpenGL.raw.GL.NV.texgen_emboss to provide a more Python-friendly API Overview (from the spec) This extension provides a new texture coordinate generation mode suitable for multitexture-based embossing (or bump mapping) effects. ...
### END AUTOGENERATED SECTION
'''Return boolean indicating whether this extension is available''' from OpenGL import extensions return extensions.hasGLExtension( _EXTENSION_NAME )
identifier_body
texgen_emboss.py
'''OpenGL extension NV.texgen_emboss This module customises the behaviour of the
This extension provides a new texture coordinate generation mode suitable for multitexture-based embossing (or bump mapping) effects. Given two texture units, this extension generates the texture coordinates of a second texture unit (an odd-numbered texture unit) as a perturbation of a first texture unit (an e...
OpenGL.raw.GL.NV.texgen_emboss to provide a more Python-friendly API Overview (from the spec)
random_line_split
framework.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import os import socket import traceback from lineup.datastructures import Queue class Node(object): def __init__(self, *args, **kw): self.initialize(*args, **kw) def initialize(self, *args, **kw): pass ...
(self): class_name = self.__class__.__name__ module_name = self.__class__.__module__ return '.'.join([module_name, class_name]) def get_name(self): return getattr(self, 'name', None) or self.taxonomy def get_hostname(self): return socket.gethostname() def make_work...
taxonomy
identifier_name
framework.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import os import socket import traceback from lineup.datastructures import Queue class Node(object): def __init__(self, *args, **kw): self.initialize(*args, **kw) def initialize(self, *args, **kw): pass ...
def feed(self, item): self.input.put(item) def enqueue_error(self, source_class, instructions, exception): print exception, source_class, instructions def wait_and_get_work(self): return self.output.get() @property def running(self): return all([w.alive for w in ...
worker.start()
conditional_block
framework.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import os import socket import traceback from lineup.datastructures import Queue class Node(object): def __init__(self, *args, **kw): self.initialize(*args, **kw) def initialize(self, *args, **kw): pass ...
@property def input(self): return self.queues[0] @property def output(self): return self.queues[-1] def get_queues(self): steps = getattr(self, 'steps', None) or [] return [Queue() for _ in steps] + [Queue()] def make_worker(self, Worker, index): retu...
self.queues = self.get_queues(*args, **kw) self.workers = [self.make_worker(Worker, index) for index, Worker in enumerate(steps)]
identifier_body
framework.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import os import socket import traceback from lineup.datastructures import Queue class Node(object): def __init__(self, *args, **kw): self.initialize(*args, **kw) def initialize(self, *args, **kw): pass ...
def feed(self, item): self.input.put(item) def enqueue_error(self, source_class, instructions, exception): print exception, source_class, instructions def wait_and_get_work(self): return self.output.get() @property def running(self): return all([w.alive for w in s...
worker.start()
random_line_split
CommunistWorker.js
L.CommunistWorker = L.AbstractWorker.extend({ statics: { // number of web workers, not using web workers when falsy NUM_WORKERS: 2 }, initialize: function (workerFunc) { this.workerFunc = workerFunc; }, onAdd: function (map) { this._workers = L.CommunistWorker.crea...
L.CommunistWorker.workers = communist({ //data : L.TileLayer.Vector.parseData data : workerFunc }, L.CommunistWorker.NUM_WORKERS); } return L.CommunistWorker.workers; } });
random_line_split
CommunistWorker.js
L.CommunistWorker = L.AbstractWorker.extend({ statics: { // number of web workers, not using web workers when falsy NUM_WORKERS: 2 }, initialize: function (workerFunc) { this.workerFunc = workerFunc; }, onAdd: function (map) { this._workers = L.CommunistWorker.crea...
return L.CommunistWorker.workers; } });
{ L.CommunistWorker.workers = communist({ //data : L.TileLayer.Vector.parseData data : workerFunc }, L.CommunistWorker.NUM_WORKERS); }
conditional_block
state.js
var links = require('./links');
initialize: function(map, lrm_control, tools, default_options) { this._lrm = lrm_control; this._map = map; this._tools = tools; this.set(default_options); console.log(this.options); this._lrm.on('routeselected', function(e) { this.options.alternative = e.route.routesIndex; }, thi...
var State = L.Class.extend({ options: { },
random_line_split
dom.rs
} /// An iterator over the DOM children of a node. pub struct DomChildren<N>(Option<N>); impl<N> Iterator for DomChildren<N> where N: TNode, { type Item = N; fn next(&mut self) -> Option<N> { let n = self.0.take()?; self.0 = n.next_sibling(); Some(n) } } /// An iterator over ...
{ loop { let n = self.0.next()?; // Filter out nodes that layout should ignore. if n.is_text_node() || n.is_element() { return Some(n); } } }
identifier_body
dom.rs
#[cfg_attr(feature = "servo", derive(MallocSizeOf, Deserialize, Serialize))] pub struct OpaqueNode(pub usize); impl OpaqueNode { /// Returns the address of this node, for debugging purposes. #[inline] pub fn id(&self) -> usize { self.0 } } /// Simple trait to provide basic information about th...
/// Because the script task's GC does not trace layout, node data cannot be safely stored in layout /// data structures. Also, layout code tends to be faster when the DOM is not being accessed, for /// locality reasons. Using `OpaqueNode` enforces this invariant. #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
random_line_split
dom.rs
(&self) -> DomChildren<Self> { DomChildren(self.first_child()) } /// Returns whether the node is attached to a document. fn is_in_document(&self) -> bool; /// Iterate over the DOM children of a node, in preorder. fn dom_descendants(&self) -> DomDescendants<Self> { DomDescendants { ...
dom_children
identifier_name
main.rs
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright (C) 2015-2022 Christian Krause * * * * ...
() -> Result<()> { let args = cli::build().get_matches(); let config = Config::try_from(&args)?; let input = args.value_of("input").unwrap(); analysis::run(input, config) }
main
identifier_name
main.rs
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright (C) 2015-2022 Christian Krause * * * * ...
#![warn(clippy::pedantic, clippy::nursery, clippy::cargo)] mod analysis; mod cli; mod config; mod log; mod output; mod summary; use anyhow::Result; use crate::config::Config; fn main() -> Result<()> { let args = cli::build().get_matches(); let config = Config::try_from(&args)?; let input = args.value_o...
#![deny(clippy::all)]
random_line_split
main.rs
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright (C) 2015-2022 Christian Krause * * * * ...
{ let args = cli::build().get_matches(); let config = Config::try_from(&args)?; let input = args.value_of("input").unwrap(); analysis::run(input, config) }
identifier_body
meth.rs
"); // self is passed as an opaque box in the environment slot let self_ty = ty::mk_opaque_box(bcx.tcx()); trans_arg_expr(bcx, self_ty, mentry.self_mode, base, temp_cleanups, DontAutorefArg) } pub fn trans_metho...
(bcx: @mut Block, mth_did: ast::DefId, callee_id: ast::NodeId, rcvr_substs: &[ty::t], rcvr_origins: typeck::vtable_res) -> (~[ty::t], typeck...
combine_impl_and_methods_tps
identifier_name
meth.rs
use lib; use metadata::csearch; use middle::trans::base::*; use middle::trans::build::*; use middle::trans::callee::*; use middle::trans::callee; use middle::trans::common::*; use middle::trans::datum::*; use middle::trans::expr::{SaveIn, Ignore}; use middle::trans::expr; use middle::trans::glue; use middle::trans::mon...
use back::abi; use lib::llvm::llvm; use lib::llvm::ValueRef;
random_line_split
meth.rs
"); // self is passed as an opaque box in the environment slot let self_ty = ty::mk_opaque_box(bcx.tcx()); trans_arg_expr(bcx, self_ty, mentry.self_mode, base, temp_cleanups, DontAutorefArg) } pub fn trans_metho...
// // fn foo<T1...Tn,self: Trait<T1...Tn>,M1...Mn>(...) {...} // // So when we see a call to this function foo, we have to figure // out which impl the `Trait<T1...Tn>` bound on the type `self` was // bound to. let bound_index = ty::lookup_trait_def(bcx.tcx(), trait_id). generics.t...
{ let _icx = push_ctxt("impl::trans_static_method_callee"); let ccx = bcx.ccx(); debug!("trans_static_method_callee(method_id={:?}, trait_id={}, \ callee_id={:?})", method_id, ty::item_path_str(bcx.tcx(), trait_id), callee_id); let _indenter = indenter(); ...
identifier_body
rotate_turn.rs
use rune_vm::Rune; use game_state::GameState; use minion_card::UID; use ::tags_list::*; use runes::remove_tag::RemoveTag; use runes::set_base_mana::SetBaseMana; use runes::set_mana::SetMana; use runes::deal_card::DealCard; use controller::EControllerState; use hlua; #[derive(RustcDecodable, RustcEncodable, Clone)] pub...
game_state.set_on_turn_player(turn_index); let new_mana = game_state.get_controller_by_index(turn_index as usize).get_base_mana().clone() + 1; let sbm = SetBaseMana::new(game_state.get_controller_by_index(turn_index as usize) .get_uid() ...
{ turn_index = 0; }
conditional_block
rotate_turn.rs
use rune_vm::Rune; use game_state::GameState; use minion_card::UID; use ::tags_list::*; use runes::remove_tag::RemoveTag; use runes::set_base_mana::SetBaseMana; use runes::set_mana::SetMana; use runes::deal_card::DealCard; use controller::EControllerState; use hlua; #[derive(RustcDecodable, RustcEncodable, Clone)] pub...
} } implement_for_lua!(RotateTurn, |mut _metatable| {}); impl Rune for RotateTurn { fn execute_rune(&self, mut game_state: &mut GameState) { let mut turn_index = game_state.get_on_turn_player().clone(); let in_play = game_state.get_controller_by_index(turn_index as usize).get_copy_of_in_play(...
impl RotateTurn { pub fn new() -> RotateTurn { RotateTurn {}
random_line_split
rotate_turn.rs
use rune_vm::Rune; use game_state::GameState; use minion_card::UID; use ::tags_list::*; use runes::remove_tag::RemoveTag; use runes::set_base_mana::SetBaseMana; use runes::set_mana::SetMana; use runes::deal_card::DealCard; use controller::EControllerState; use hlua; #[derive(RustcDecodable, RustcEncodable, Clone)] pub...
(&self, _controller: UID, _game_state: &GameState) -> bool { return true; } fn to_json(&self) -> String { "{\"runeType\":\"RotateTurn\"}".to_string() } fn into_box(&self) -> Box<Rune> { Box::new(self.clone()) } }
can_see
identifier_name
round10.js
;(function(environment){ 'use strict'; environment['Round10'] = {
map :[0,1,1,1,2,2,2,0,0,0,1,3,3,3,2,0,0,0,2,3,3,1,0,0,0,0,0,4,0,4,0,0,0,0,5,4,4,5,0,0,0,6,6,7,4,7,8,6,8,6,7,4,4,7,2,6,0,6,2,4,0,4,6,8,0,6,8,0,0,6,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] } })(this);
size :{x:8, y:13}, special:['', 'gift', 'fixed'], range:['', 'Yellow', 'Lime', 'gift', 'fixed', 'DarkViolet', 'SteelBlue', 'white', 'Crimson'],
random_line_split
MaxCalesterChipotleGreedy.py
# MaxCalester Program - Chipotle # Developed By: Andy Han # Data Provided By: Ibrahima Dieye and Lang Li # April 26th, 2017 # Macalester College # COMP 221 - Algorithm Design and Analysis # Questions? Contact us at dhan@macalester.edu import csv chipotle_best_combo = {} chipotle_best_combo_price_calorie...
length = len(sorted_ratio_list) # The length of the ratio_list to determine the number of comparisons to make total_calorie_count = 0 # A running tally of the calorie count based on the items "purchased" total_price = 0 # A running tally of how much "spent" so far based on the items added for i in...
print("Your budget is not big enough to buy anything from the database. Tough luck!") return
conditional_block
MaxCalesterChipotleGreedy.py
# MaxCalester Program - Chipotle # Developed By: Andy Han # Data Provided By: Ibrahima Dieye and Lang Li # April 26th, 2017 # Macalester College # COMP 221 - Algorithm Design and Analysis # Questions? Contact us at dhan@macalester.edu import csv chipotle_best_combo = {} chipotle_best_combo_price_calorie...
(budget): """ This function creates a list of items that would make the best combo by using the greedy property.""" sorted_price = sorted(chipotle_price) if budget < sorted_price[0]: # Base Case: If the budget is less than the price of the cheapest item of the list. print("Your budget is not big e...
greedy_algorithm
identifier_name
MaxCalesterChipotleGreedy.py
# MaxCalester Program - Chipotle # Developed By: Andy Han # Data Provided By: Ibrahima Dieye and Lang Li # April 26th, 2017 # Macalester College # COMP 221 - Algorithm Design and Analysis # Questions? Contact us at dhan@macalester.edu import csv chipotle_best_combo = {} chipotle_best_combo_price_calorie...
return length = len(sorted_ratio_list) # The length of the ratio_list to determine the number of comparisons to make total_calorie_count = 0 # A running tally of the calorie count based on the items "purchased" total_price = 0 # A running tally of how much "spent" so far based on the items added...
print("Your budget is not big enough to buy anything from the database. Tough luck!")
random_line_split
MaxCalesterChipotleGreedy.py
# MaxCalester Program - Chipotle # Developed By: Andy Han # Data Provided By: Ibrahima Dieye and Lang Li # April 26th, 2017 # Macalester College # COMP 221 - Algorithm Design and Analysis # Questions? Contact us at dhan@macalester.edu import csv chipotle_best_combo = {} chipotle_best_combo_price_calorie...
# Above, add the desired item's caloric count to the total caloric tally chipotle_item_list.append("1 " + item_name + " for the price of $" + str(item_price) + " with a calorie count of " + str( name_calorie_dict.get(item_name))) # Ad...
""" This function creates a list of items that would make the best combo by using the greedy property.""" sorted_price = sorted(chipotle_price) if budget < sorted_price[0]: # Base Case: If the budget is less than the price of the cheapest item of the list. print("Your budget is not big enough to buy a...
identifier_body
dialog-config.d.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { ViewContainerRef } from '@angular/core'; import { Direction } from '@angular/cdk/bidi'; /** Valid ARIA roles ...
export declare class MatDialogConfig { /** * Where the attached component should live in Angular's *logical* component tree. * This affects what is available for injection and the change detection order for the * component instantiated inside of the dialog. This does not affect where the dialog ...
* Configuration for opening a modal dialog with the MatDialog service. */
random_line_split
dialog-config.d.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { ViewContainerRef } from '@angular/core'; import { Direction } from '@angular/cdk/bidi'; /** Valid ARIA roles ...
{ /** * Where the attached component should live in Angular's *logical* component tree. * This affects what is available for injection and the change detection order for the * component instantiated inside of the dialog. This does not affect where the dialog * content will be rendered. */ ...
MatDialogConfig
identifier_name
entities.reducer.ts
import * as Redux from "redux"; import { ActionTemplate, TraitTemplate } from "src/types"; import actionsReducer, * as fromActions from "./actions.reducer"; import monsterBuilderReducer, * as fromMonsterBuilder from "./monsterBuilder"; import traitsReducer, * as fromTraits from "./traits.reducer"; export interface E...
export const getAllTraits = (state: EntitiesState) => fromTraits.getAllTraits(state.traits); export const getAppliedTraitIds = (state: EntitiesState) => fromMonsterBuilder.getAppliedTraitIds(state.monsterBuilder); export const getTraitArgs = (state: EntitiesState, trait: TraitTemplate) => fromMonsterBuil...
export const getMonsterBuilderData = (state: EntitiesState) => state.monsterBuilder;
random_line_split
main.rs
extern crate log; extern crate env_logger; extern crate clap; extern crate ctrlc; extern crate gauc; extern crate iron; extern crate urlencoded; use clap::{App, Arg}; use gauc::cli; use gauc::web; use gauc::client::Client; use std::env; use std::process::exit; use std::sync::{Arc, Mutex}; use std::sync::atomic::{At...
} }
if let Ok(client) = Client::connect(matches.value_of("url").unwrap()) { web::start_web(&Arc::new(Mutex::new(client)), port); }
random_line_split
main.rs
extern crate log; extern crate env_logger; extern crate clap; extern crate ctrlc; extern crate gauc; extern crate iron; extern crate urlencoded; use clap::{App, Arg}; use gauc::cli; use gauc::web; use gauc::client::Client; use std::env; use std::process::exit; use std::sync::{Arc, Mutex}; use std::sync::atomic::{At...
/// Web Server Entrypoint fn main() { install_ctrl_c_handler(); let couchbase_uri = match env::var("COUCHBASE_URI") { Ok(uri) => uri, Err(_) => DEFAULT_URI.to_string() }; // Specify program options let matches = App::new(DESCRIPTION) .version(VERSION) .author("To...
{ let running = Arc::new(AtomicBool::new(true)); let r = Arc::clone(&running); let _ = ctrlc::set_handler(move || { println!(""); println!(""); println!("Received ctrl+c, exiting ..."); r.store(false, Ordering::SeqCst); exit(0); }); }
identifier_body
main.rs
extern crate log; extern crate env_logger; extern crate clap; extern crate ctrlc; extern crate gauc; extern crate iron; extern crate urlencoded; use clap::{App, Arg}; use gauc::cli; use gauc::web; use gauc::client::Client; use std::env; use std::process::exit; use std::sync::{Arc, Mutex}; use std::sync::atomic::{At...
let port: u16 = matches.value_of("rest-port").unwrap().to_string().parse::<u16>().unwrap(); if matches.is_present("rest") { if let Ok(client) = Client::connect(matches.value_of("url").unwrap()) { web::start_web(&Arc::new(Mutex::new(client)), port); } } }
{ if let Ok(mut client) = Client::connect(matches.value_of("url").unwrap()) { cli::main(&matches, &mut client); } }
conditional_block
main.rs
extern crate log; extern crate env_logger; extern crate clap; extern crate ctrlc; extern crate gauc; extern crate iron; extern crate urlencoded; use clap::{App, Arg}; use gauc::cli; use gauc::web; use gauc::client::Client; use std::env; use std::process::exit; use std::sync::{Arc, Mutex}; use std::sync::atomic::{At...
() { install_ctrl_c_handler(); let couchbase_uri = match env::var("COUCHBASE_URI") { Ok(uri) => uri, Err(_) => DEFAULT_URI.to_string() }; // Specify program options let matches = App::new(DESCRIPTION) .version(VERSION) .author("Tomas Korcak <korczis@gmail.com>") ...
main
identifier_name
MatrixView.tsx
import React from "react"; import cn from "classnames"; import { Scanned, Kind } from "../../../Models/Queue/Queue"; import Mission from "../../../Models/Queue/Mission"; import Recovery from "../../../Models/Queue/Recovery"; import Shipbuilding from "../../../Models/Queue/Shipbuilding"; import TimerDisplaySetting, { Di...
renderModal() { const { label, cell } = this.state.manual; return ( <div className="modal modal-sm active" id="modal-id"> <a className="modal-overlay" onClick={this.closeManualModal.bind(this)} /> <div className="modal-container"> <div className="modal-header"> {/* ...
} /** * マニュアル登録のモーダルダイアログ */
random_line_split
MatrixView.tsx
import React from "react"; import cn from "classnames"; import { Scanned, Kind } from "../../../Models/Queue/Queue"; import Mission from "../../../Models/Queue/Mission"; import Recovery from "../../../Models/Queue/Recovery"; import Shipbuilding from "../../../Models/Queue/Shipbuilding"; import TimerDisplaySetting, { Di...
isplayFormat) { return ( <div className={cn("container", "column", label)}> <div className="columns"> <div className="column col-3"></div> <div className="column col-9">{/* label */}</div> </div> {cells.map(cell => { const tooltip = cell.getTooltipAttribut...
getColumn(label: string, cells: CellModel[], format: D
identifier_body
MatrixView.tsx
import React from "react"; import cn from "classnames"; import { Scanned, Kind } from "../../../Models/Queue/Queue"; import Mission from "../../../Models/Queue/Mission"; import Recovery from "../../../Models/Queue/Recovery"; import Shipbuilding from "../../../Models/Queue/Shipbuilding"; import TimerDisplaySetting, { Di...
(":").map(s => parseInt(s, 10)); return (((hours * 60) + minutes) * 60 * 1000); } } export default class MatrixView extends React.Component<{ missions: Scanned<Mission>, recoveries: Scanned<Recovery>, shipbuildings: Scanned<Shipbuilding>, }, { manual: { label: string, cell: CellModel }, }> { ...
] = this.draft.split
identifier_name
reset.component.ts
import { Component, OnInit, ChangeDetectorRef, Output, EventEmitter } from '@angular/core'; import { FormGroup, FormControl, Validators } from '@angular/forms'; import { NewPasswordRequestDTO } from '@app/user/models/user.model'; @Component({ selector: 'fcl-reset', templateUrl: './reset.component.html', st...
(private changeRef: ChangeDetectorRef) { this.pwStrength = -1; } ngOnInit() { this.resetForm = new FormGroup({ password1: new FormControl(null, Validators.required), password2: new FormControl(null, [Validators.required, Validators.minLength(8)]) }, this.password...
constructor
identifier_name
reset.component.ts
import { Component, OnInit, ChangeDetectorRef, Output, EventEmitter } from '@angular/core'; import { FormGroup, FormControl, Validators } from '@angular/forms'; import { NewPasswordRequestDTO } from '@app/user/models/user.model'; @Component({ selector: 'fcl-reset', templateUrl: './reset.component.html', st...
doStrengthChange(pwStrength: number) { this.pwStrength = pwStrength; this.changeRef.detectChanges(); } onReset() { const password: NewPasswordRequestDTO = { password: this.resetForm.value.password1 }; this.reset.emit(password); } private passw...
{ return (this.pwStrength >= 0 && this.pwStrength < 2); }
identifier_body
reset.component.ts
import { Component, OnInit, ChangeDetectorRef, Output, EventEmitter } from '@angular/core'; import { FormGroup, FormControl, Validators } from '@angular/forms'; import { NewPasswordRequestDTO } from '@app/user/models/user.model'; @Component({ selector: 'fcl-reset', templateUrl: './reset.component.html', st...
return null; } }
}
random_line_split
reset.component.ts
import { Component, OnInit, ChangeDetectorRef, Output, EventEmitter } from '@angular/core'; import { FormGroup, FormControl, Validators } from '@angular/forms'; import { NewPasswordRequestDTO } from '@app/user/models/user.model'; @Component({ selector: 'fcl-reset', templateUrl: './reset.component.html', st...
else { pw2.setErrors(null); } return null; } }
{ pw2.setErrors({ validatePasswordConfirm: true }); }
conditional_block
player.py
#!/Users/harvey/Projects/face-hack/venv/face/bin/python # # The Python Imaging Library # $Id$ # from __future__ import print_function try: from tkinter import * except ImportError: from Tkinter import * from PIL import Image, ImageTk import sys # ------------------------------------------------------------...
except KeyError: duration = 100 self.after(duration, self.next) def next(self): if isinstance(self.im, list): try: im = self.im[0] del self.im[0] self.image.paste(im) except IndexError: ret...
def __init__(self, master, im): if isinstance(im, list): # list of images self.im = im[1:] im = self.im[0] else: # sequence self.im = im if im.mode == "1": self.image = ImageTk.BitmapImage(im, foreground="white") el...
identifier_body
player.py
#!/Users/harvey/Projects/face-hack/venv/face/bin/python # # The Python Imaging Library # $Id$ # from __future__ import print_function try: from tkinter import * except ImportError: from Tkinter import * from PIL import Image, ImageTk import sys # ------------------------------------------------------------...
else: # sequence im = Image.open(filename) UI(root, im).pack() root.mainloop()
im.append(Image.open(filename))
conditional_block
player.py
#!/Users/harvey/Projects/face-hack/venv/face/bin/python # # The Python Imaging Library # $Id$ # from __future__ import print_function try: from tkinter import * except ImportError: from Tkinter import * from PIL import Image, ImageTk import sys # ------------------------------------------------------------...
(self): if isinstance(self.im, list): try: im = self.im[0] del self.im[0] self.image.paste(im) except IndexError: return # end of list else: try: im = self.im im.seek(...
next
identifier_name
player.py
#!/Users/harvey/Projects/face-hack/venv/face/bin/python # # The Python Imaging Library # $Id$ # from __future__ import print_function try: from tkinter import * except ImportError: from Tkinter import * from PIL import Image, ImageTk import sys # ------------------------------------------------------------...
def next(self): if isinstance(self.im, list): try: im = self.im[0] del self.im[0] self.image.paste(im) except IndexError: return # end of list else: try: im = self.im ...
duration = 100 self.after(duration, self.next)
random_line_split
practica1.py
# encoding: latin1 import urllib2, re from Tkinter import * import tkMessageBox import sqlite3 def extraer_datos(): f = urllib2.urlopen("http://www.us.es/rss/feed/portada") s = f.read() l = re.findall(r'<item>\s*<title>(.*)</title>\s*<link>(.*)</link>\s*<description>.*</description>\s*<author>.*...
def imprimir_etiqueta(cursor): v = Toplevel() sc = Scrollbar(v) sc.pack(side=RIGHT, fill=Y) lb = Listbox(v, width=150, yscrollcommand=sc.set) for row in cursor: lb.insert(END,row[0]) lb.insert(END,row[1]) lb.insert(END,row[2]) lb.insert(END,'') l...
conn = sqlite3.connect('test.db') conn.text_factory = str cursor = conn.execute("SELECT TITULO,LINK, FECHA FROM NOTICIAS") imprimir_etiqueta(cursor) conn.close()
identifier_body
practica1.py
# encoding: latin1 import urllib2, re from Tkinter import * import tkMessageBox import sqlite3 def extraer_datos(): f = urllib2.urlopen("http://www.us.es/rss/feed/portada") s = f.read() l = re.findall(r'<item>\s*<title>(.*)</title>\s*<link>(.*)</link>\s*<description>.*</description>\s*<author>.*...
conn = sqlite3.connect('test.db') conn.text_factory = str s = "%"+en.get()+"%" cursor = conn.execute("""SELECT TITULO,LINK,FECHA FROM NOTICIAS WHERE FECHA LIKE ?""",(s,)) # al ser de tipo string, el ? le pone comillas simples imprimir_etiqueta(cursor) conn.close() ...
sc.config(command = lb.yview) def buscar_bd(): def listar_busqueda(event):
random_line_split
practica1.py
# encoding: latin1 import urllib2, re from Tkinter import * import tkMessageBox import sqlite3 def extraer_datos(): f = urllib2.urlopen("http://www.us.es/rss/feed/portada") s = f.read() l = re.findall(r'<item>\s*<title>(.*)</title>\s*<link>(.*)</link>\s*<description>.*</description>\s*<author>.*...
conn.commit() cursor = conn.execute("SELECT COUNT(*) FROM NOTICIAS") tkMessageBox.showinfo( "Base Datos", "Base de datos creada correctamente \nHay " + str(cursor.fetchone()[0]) + " registros") conn.close() def listar_bd(): conn = sqlite3.connect('test.db') conn.text_factory = str ...
conn.execute("""INSERT INTO NOTICIAS (TITULO, LINK, FECHA) VALUES (?,?,?)""",(i[0],i[1],i[3]))
conditional_block
practica1.py
# encoding: latin1 import urllib2, re from Tkinter import * import tkMessageBox import sqlite3 def extraer_datos(): f = urllib2.urlopen("http://www.us.es/rss/feed/portada") s = f.read() l = re.findall(r'<item>\s*<title>(.*)</title>\s*<link>(.*)</link>\s*<description>.*</description>\s*<author>.*...
(): def listar_busqueda(event): conn = sqlite3.connect('test.db') conn.text_factory = str s = "%"+en.get()+"%" cursor = conn.execute("""SELECT TITULO,LINK,FECHA FROM NOTICIAS WHERE FECHA LIKE ?""",(s,)) # al ser de tipo string, el ? le pone comillas simples imprimir_et...
buscar_bd
identifier_name
EndgamesPanel.py
import random from io import StringIO from gi.repository import Gtk from pychess.compat import create_task from pychess.System.prefix import addDataPrefix from pychess.Utils.const import WHITE, BLACK, LOCAL, NORMALCHESS, ARTIFICIAL, chr2Sign, chrU2Sign, FAN_PIECES, HINT, ENDGAME from pychess.Utils.LearnModel import L...
# 2 same color bishop is not ok if len(bishop_cords[color]) == 2 and bishop_colors_ok: b0, b1 = bishop_cords[color] b0_color = BLACK if RANK(b0) % 2 == FILE(b0) % 2 else WHITE b1_color = BLACK if RANK(b1) % 2 == FILE(b1) % 2 else WHITE ...
piece = chrU2Sign[char.upper()] attacked = True limit = 100 while attacked and limit > 0: cord = random.choice(pawn_cords if char == "p" else cords) attacked = isAttacked(lboard, cord, 1 - color) limit -= 1 ...
conditional_block
EndgamesPanel.py
import random from io import StringIO from gi.repository import Gtk from pychess.compat import create_task from pychess.System.prefix import addDataPrefix from pychess.Utils.const import WHITE, BLACK, LOCAL, NORMALCHESS, ARTIFICIAL, chr2Sign, chrU2Sign, FAN_PIECES, HINT, ENDGAME from pychess.Utils.LearnModel import L...
(gamemodel): perspective.activate_panel("annotationPanel") create_task(gamemodel.start_analyzer(HINT, force_engine=discoverer.getEngineLearn())) gamemodel.connect("game_started", on_game_started) perspective = perspective_manager.get_perspective("games") create_task(perspective.generalStart...
on_game_started
identifier_name
EndgamesPanel.py
import random from io import StringIO from gi.repository import Gtk from pychess.compat import create_task from pychess.System.prefix import addDataPrefix from pychess.Utils.const import WHITE, BLACK, LOCAL, NORMALCHESS, ARTIFICIAL, chr2Sign, chrU2Sign, FAN_PIECES, HINT, ENDGAME from pychess.Utils.LearnModel import L...
perspective.activate_panel("annotationPanel") create_task(gamemodel.start_analyzer(HINT, force_engine=discoverer.getEngineLearn())) gamemodel.connect("game_started", on_game_started) perspective = perspective_manager.get_perspective("games") create_task(perspective.generalStart(gamemodel, p...
fen = create_fen(pieces) timemodel = TimeModel(0, 0) gamemodel = LearnModel(timemodel) gamemodel.set_learn_data(ENDGAME, pieces) player_name = conf.get("firstName") p0 = (LOCAL, Human, (WHITE, player_name), player_name) engine = discoverer.getEngineByName(discoverer.getEngineLearn()) pond...
identifier_body
EndgamesPanel.py
import random
from gi.repository import Gtk from pychess.compat import create_task from pychess.System.prefix import addDataPrefix from pychess.Utils.const import WHITE, BLACK, LOCAL, NORMALCHESS, ARTIFICIAL, chr2Sign, chrU2Sign, FAN_PIECES, HINT, ENDGAME from pychess.Utils.LearnModel import LearnModel from pychess.Utils.TimeModel...
from io import StringIO
random_line_split
vz-chart-helpers.ts
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or a...
(digits: number): ((v: number) => string) { return (v: number) => { let absv = Math.abs(v); if (absv < 1E-15) { // Sometimes zero-like values get an annoying representation absv = 0; } let f: (x: number) => string; if (absv >= 1E4) { f = d3.format('.' + digits +...
multiscaleFormatter
identifier_name
vz-chart-helpers.ts
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or a...
// a very literal definition of NaN: true for NaN for a non-number type // or null, etc. False for Infinity or -Infinity export let isNaN = (x) => +x !== x; export function getXComponents(xType: string): XComponents { switch (xType) { case 'step': return stepX(); case 'wall_time': ...
{ let scale = new Plottable.Scales.Linear(); return { scale: scale, axis: new Plottable.Axes.Numeric(scale, 'bottom'), accessor: relativeAccessor, }; }
identifier_body
vz-chart-helpers.ts
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or a...
let hours = Math.floor(n); n -= hours; n *= 60; if (hours || days) { ret += hours + 'h '; } let minutes = Math.floor(n); n -= minutes; n *= 60; if (minutes || hours || days) { ret += minutes + 'm '; } let seconds = Math.floor(n); return ret + seconds + 's'; ...
{ ret += days + 'd '; }
conditional_block
vz-chart-helpers.ts
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or a...
export interface Point { x: number; // pixel space y: number; // pixel space datum: ScalarDatum; dataset: Plottable.Dataset; } /* Create a formatter function that will switch between exponential and * regular display depending on the scale of the number being formatted, * and show `digits...
export let Y_AXIS_FORMATTER_PRECISION = 3; export let TOOLTIP_Y_PIXEL_OFFSET = 20; export let TOOLTIP_CIRCLE_SIZE = 4; export let NAN_SYMBOL_SIZE = 6;
random_line_split
task.rs
use std::borrow::Borrow; use std::collections::BTreeMap; use std::str::FromStr; use chrono::NaiveDate; use todo_txt::Task as RawTask; /// A Task with its metadata #[derive(Clone, Debug, PartialEq)] pub struct Task { pub subject: String, pub priority: u8, pub creation_date: Option<NaiveDate>, pub statu...
; Task { subject: t.subject, priority: t.priority, creation_date: t.create_date, status, threshold_date: t.threshold_date, due_date: t.due_date, contexts: t.contexts, projects: t.projects, hashtags: t.ha...
{ Status::Started }
conditional_block
task.rs
use std::borrow::Borrow; use std::collections::BTreeMap; use std::str::FromStr; use chrono::NaiveDate; use todo_txt::Task as RawTask; /// A Task with its metadata #[derive(Clone, Debug, PartialEq)] pub struct Task { pub subject: String, pub priority: u8, pub creation_date: Option<NaiveDate>, pub statu...
due_date: self.due_date, contexts: self.contexts, projects: self.projects, hashtags: self.hashtags, tags: self.tags, } } }
create_date: self.creation_date, finished, finish_date, threshold_date: self.threshold_date,
random_line_split
task.rs
use std::borrow::Borrow; use std::collections::BTreeMap; use std::str::FromStr; use chrono::NaiveDate; use todo_txt::Task as RawTask; /// A Task with its metadata #[derive(Clone, Debug, PartialEq)] pub struct Task { pub subject: String, pub priority: u8, pub creation_date: Option<NaiveDate>, pub statu...
(txt: impl Borrow<str>) -> Task { // For this unwrap, see https://github.com/sanpii/todo-txt/issues/10 RawTask::from_str(txt.borrow()).unwrap().into() } /// Check if the task is done pub fn is_done(&self) -> bool { if let Status::Finished(_) = self.status { true ...
parse
identifier_name
task.rs
use std::borrow::Borrow; use std::collections::BTreeMap; use std::str::FromStr; use chrono::NaiveDate; use todo_txt::Task as RawTask; /// A Task with its metadata #[derive(Clone, Debug, PartialEq)] pub struct Task { pub subject: String, pub priority: u8, pub creation_date: Option<NaiveDate>, pub statu...
} } impl ::std::convert::Into<RawTask> for Task { fn into(self) -> RawTask { let (finished, finish_date) = match self.status { Status::Started => (false, None), Status::Finished(date) => (true, date), }; RawTask { subject: self.subject, p...
{ // compute status let status = if t.finished { Status::Finished(t.finish_date) } else { Status::Started }; Task { subject: t.subject, priority: t.priority, creation_date: t.create_date, status, ...
identifier_body
__manifest__.py
# -*- coding: utf-8 -*- # Copyright 2016 Onestein (<http://www.onestein.eu>) # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { 'name': "Absence Management", 'summary': """Create time based absence notifications""", 'author': 'Onestein', 'website': 'http://www.onestein.eu', 'ima...
'license': 'AGPL-3', 'depends': [ 'hr_holidays', ], 'data': [ 'security/ir.model.access.csv', 'views/hr_holidays_status.xml', 'views/hr_holidays.xml', 'data/hr_absenteeism_cron.xml', ], 'demo': [], 'installable': True, 'auto_install': False, 'a...
'category': 'Human Resources', 'version': '10.0.1.0.0',
random_line_split
Base.js
'use strict'; (function(exports, undefined) { function _emit(type, data) { var handlers = Util.slice.call(this._notifyHash[type]); for (var i = 0, l = handlers.length; i < l; i++) { var j = Util.extend({}, handlers[i]); var scope = (j.scope) ? j.scope : this; j.scope = scope; j.handl...
(type) { var handlers = this._notifyHash; if (type) { delete handlers[type]; } else { this._notifyHash = {}; } }; function _bind(key, handle) { var events = key.split(' '); for (var i = 0, l = events.length; i < l; i++) { var t = events[i]; if (!this._notifyHash[t]) ...
_detach
identifier_name
Base.js
'use strict'; (function(exports, undefined) { function _emit(type, data) { var handlers = Util.slice.call(this._notifyHash[type]); for (var i = 0, l = handlers.length; i < l; i++) { var j = Util.extend({}, handlers[i]); var scope = (j.scope) ? j.scope : this; j.scope = scope; j.handl...
; function _bind(key, handle) { var events = key.split(' '); for (var i = 0, l = events.length; i < l; i++) { var t = events[i]; if (!this._notifyHash[t]) { this._notifyHash[t] = []; } this._notifyHash[t].push({ 'handler': handle, 'type': t }); } } ...
{ var handlers = this._notifyHash; if (type) { delete handlers[type]; } else { this._notifyHash = {}; } }
identifier_body
Base.js
'use strict'; (function(exports, undefined) { function _emit(type, data) { var handlers = Util.slice.call(this._notifyHash[type]); for (var i = 0, l = handlers.length; i < l; i++) { var j = Util.extend({}, handlers[i]); var scope = (j.scope) ? j.scope : this; j.scope = scope; j.handl...
function Base() { this._dataHash = {}; this._notifyHash = {}; }; var proto = {}; proto.on = function(arg1, arg2) { if (Util.type(arg1) === 'object') { for (var j in arg1) { _bind.call(this, j, arg1[j]); } } else { _bind.call(this, arg1, arg2); } return this; ...
random_line_split
timeout.rs
#[macro_use] extern crate holmes; use holmes::simple::*; use std::time::{Duration, Instant}; // The whole point of this test is to take an excessively long execution // and make sure it terminates about on time if a limiter is provided #[test] pub fn infinity()
}
{ single(&|holmes: &mut Engine, core: &mut Core| { // Amount of time holmes gets let limit = Duration::new(2, 0); // Wiggle room to shut things down let wiggle = Duration::new(1, 0); holmes.limit_time(limit.clone()); let start = Instant::now(); try!(holmes_exe...
identifier_body
timeout.rs
#[macro_use] extern crate holmes; use holmes::simple::*; use std::time::{Duration, Instant}; // The whole point of this test is to take an excessively long execution // and make sure it terminates about on time if a limiter is provided #[test] pub fn infinity() { single(&|holmes: &mut Engine, core: &mut Core| { ...
holmes.limit_time(limit.clone()); let start = Instant::now(); try!(holmes_exec!(holmes, { predicate!(count(uint64)); fact!(count(0)); func!(let inc: uint64 -> uint64 = |i: &u64| *i + 1); rule!(inc: count(n_plus_one) <= count(n), { let n_plus_one = {inc([n])} ...
random_line_split