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
checks.py
import socket as sk from kivy.logger import Logger def getWebsite(): return "www.google.com" def getIpPort(): sock_info=sk.getaddrinfo(getWebsite(),80,proto=sk.IPPROTO_TCP) return sock_info[0][-1] def checkInternet(): sock=sk.socket() sock.settimeout(1) try: sock.connect(getIpPort()) ...
if readings[0] < 200 or readings[1] < 200: return False else: return True
init=[psutil.net_io_counters().bytes_sent,psutil.net_io_counters().bytes_recv] time.sleep(1) final=[psutil.net_io_counters().bytes_sent,psutil.net_io_counters().bytes_recv] readings=[(final[0]-init[0]),(final[1]-init[1])] print(readings)
random_line_split
checks.py
import socket as sk from kivy.logger import Logger def getWebsite(): return "www.google.com" def getIpPort(): sock_info=sk.getaddrinfo(getWebsite(),80,proto=sk.IPPROTO_TCP) return sock_info[0][-1] def checkInternet(): sock=sk.socket() sock.settimeout(1) try: sock.connect(getIpPort()) ...
else: return False except Exception as e: Logger.error(e) return False def checkSpeed(): import psutil import time init=[psutil.net_io_counters().bytes_sent,psutil.net_io_counters().bytes_recv] time.sleep(1) final=[psutil.net_io_counters().bytes_sent,psutil....
return True
conditional_block
TileContent-dbg.js
sap.suite.ui.commons", properties : { "footer" : {type : "string", group : "Appearance", defaultValue : null}, "size" : {type : "sap.suite.ui.commons.InfoTileSize", group : "Misc", defaultValue : "Auto"}, "unit" : {type : "string", group : "Misc", defaultValue : null}, "disabled" : {type : "boolean", group : "...
{ if (oContent.getAltText) { sAltText += oContent.getAltText(); bIsFirst = false; } else if (oContent.getTooltip_AsString()){ sAltText += oContent.getTooltip_AsString(); bIsFirst = false; } }
conditional_block
TileContent-dbg.js
* To override this automatic resolution, one of the prefixes "aggregation:", "association:" * or "event:" can be added to the name of the setting (such a prefixed name must be * enclosed in single or double quotes). * * The supported settings are: * <ul> * <li>Properties * <ul> * <li>{@link #getFooter footer}...
* Accepts an object literal <code>mSettings</code> that defines initial * property values, aggregated and associated objects as well as event handlers. * * If the name of a setting is ambiguous (e.g. a property has the same name as an event), * then the framework assumes property, aggregation, association, eve...
random_line_split
profit_and_loss_statement.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe import _ from frappe.utils import flt from erpnext.accounts.report.financial_statements import (get_period_list, get_columns, ...
(income, expense, period_list, company): if income and expense: net_profit_loss = { "account_name": "'" + _("Net Profit / Loss") + "'", "account": None, "warn_if_negative": True, "currency": frappe.db.get_value("Company", company, "default_currency") } for period in period_list: net_profit_loss[p...
get_net_profit_loss
identifier_name
profit_and_loss_statement.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe import _ from frappe.utils import flt from erpnext.accounts.report.financial_statements import (get_period_list, get_columns, ...
if income and expense: net_profit_loss = { "account_name": "'" + _("Net Profit / Loss") + "'", "account": None, "warn_if_negative": True, "currency": frappe.db.get_value("Company", company, "default_currency") } for period in period_list: net_profit_loss[period.key] = flt(income[-2][period.key] - ...
identifier_body
profit_and_loss_statement.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe import _ from frappe.utils import flt from erpnext.accounts.report.financial_statements import (get_period_list, get_columns, ...
return net_profit_loss
net_profit_loss[period.key] = flt(income[-2][period.key] - expense[-2][period.key], 3)
conditional_block
profit_and_loss_statement.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import unicode_literals import frappe from frappe import _ from frappe.utils import flt from erpnext.accounts.report.financial_statements import (get_period_list, get_columns, ...
return columns, data def get_net_profit_loss(income, expense, period_list, company): if income and expense: net_profit_loss = { "account_name": "'" + _("Net Profit / Loss") + "'", "account": None, "warn_if_negative": True, "currency": frappe.db.get_value("Company", company, "default_currency") } ...
data.append(net_profit_loss) columns = get_columns(period_list, filters.company)
random_line_split
dump_yaml.py
import sys import yaml def
(table_path): data_dict = {} with open(table_path) as table_to_load: # load headers headers = table_to_load.readline().strip('\n').split('\t') row_id = 0 for line in table_to_load.readlines(): # print(line) line_data = line.strip('\n').split('\t') ...
fetch_table_data
identifier_name
dump_yaml.py
import sys import yaml def fetch_table_data(table_path): data_dict = {} with open(table_path) as table_to_load: # load headers headers = table_to_load.readline().strip('\n').split('\t') row_id = 0 for line in table_to_load.readlines(): # print(line) lin...
table_data = fetch_table_data(experiments_table_path) all_data_dict['ENA_experiment'] = table_data runs_table_path = sys.argv[4] table_data = fetch_table_data(runs_table_path) all_data_dict['ENA_run'] = table_data # print(all_data_dict) print(yaml.dump(all_data_dict)) print('YAML -------------')
experiments_table_path = sys.argv[3]
random_line_split
dump_yaml.py
import sys import yaml def fetch_table_data(table_path):
all_data_dict = {} print('YAML -------------') studies_table_path = sys.argv[1] table_data = fetch_table_data(studies_table_path) all_data_dict['ENA_study'] = table_data samples_table_path = sys.argv[2] table_data = fetch_table_data(samples_table_path) all_data_dict['ENA_sample'] = table_data experiments_table_path ...
data_dict = {} with open(table_path) as table_to_load: # load headers headers = table_to_load.readline().strip('\n').split('\t') row_id = 0 for line in table_to_load.readlines(): # print(line) line_data = line.strip('\n').split('\t') row_dict = {} ...
identifier_body
dump_yaml.py
import sys import yaml def fetch_table_data(table_path): data_dict = {} with open(table_path) as table_to_load: # load headers headers = table_to_load.readline().strip('\n').split('\t') row_id = 0 for line in table_to_load.readlines(): # print(line) lin...
data_dict[row_id] = row_dict row_id += 1 return data_dict all_data_dict = {} print('YAML -------------') studies_table_path = sys.argv[1] table_data = fetch_table_data(studies_table_path) all_data_dict['ENA_study'] = table_data samples_table_path = sys.argv[2] table_data = fetch_table...
col_name = headers[col_num] row_dict[col_name] = line_data[col_num]
conditional_block
karma-dist-minified.conf.js
// Karma configuration // Generated on Thu Aug 21 2014 10:24:39 GMT+0200 (CEST) module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/...
], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/brow...
// list of files to exclude exclude: [
random_line_split
mod.rs
use byteorder::{BigEndian, WriteBytesExt}; use db; use std::cmp; use std::io::Cursor; pub mod bloomfilter; #[macro_export] macro_rules! retry_bound { ($k:expr) => { if $k < 9 { // special case since formula yields a very loose upper bound for k < 9 $k as u32 // we can always retrieve k element...
#[inline] pub fn tree_height(num: u64) -> u32 { ((num + 1) as f64).log2().ceil() as u32 } #[inline] pub fn get_index(labels: &[Vec<u8>], label: &[u8]) -> Option<u64> { match labels.binary_search_by(|probe| label_cmp(&probe[..], label)) { Ok(i) => Some(i as u64), Err(_) => None, } } #[i...
{ unsafe { (&*(l1 as *const [u8] as *const [u64; 4])).cmp(&*(l2 as *const [u8] as *const [u64; 4])) } }
identifier_body
mod.rs
use byteorder::{BigEndian, WriteBytesExt}; use db; use std::cmp; use std::io::Cursor; pub mod bloomfilter; #[macro_export] macro_rules! retry_bound { ($k:expr) => { if $k < 9 { // special case since formula yields a very loose upper bound for k < 9 $k as u32 // we can always retrieve k element...
} else if db::CIPHER_SIZE <= 1024 { if num < 8 { 1 } else if num < 32768 { 8 } else if num < 131072 { 16 } else { 32 } } else if num < 32768 { 1 } else { 8 } }
}
random_line_split
mod.rs
use byteorder::{BigEndian, WriteBytesExt}; use db; use std::cmp; use std::io::Cursor; pub mod bloomfilter; #[macro_export] macro_rules! retry_bound { ($k:expr) => { if $k < 9 { // special case since formula yields a very loose upper bound for k < 9 $k as u32 // we can always retrieve k element...
} else if db::CIPHER_SIZE <= 1024 { if num < 8 { 1 } else if num < 32768 { 8 } else if num < 131072 { 16 } else { 32 } } else if num < 32768 { 1 } else { 8 } }
{ 64 }
conditional_block
mod.rs
use byteorder::{BigEndian, WriteBytesExt}; use db; use std::cmp; use std::io::Cursor; pub mod bloomfilter; #[macro_export] macro_rules! retry_bound { ($k:expr) => { if $k < 9 { // special case since formula yields a very loose upper bound for k < 9 $k as u32 // we can always retrieve k element...
(bucket_len: u64, collection_idx: u32, num_collections: u32) -> u64 { if num_collections == 1 { bucket_len } else if num_collections == 2 { // hybrid 2 match collection_idx { 0 => (bucket_len as f64 / 2f64).ceil() as u64, 1 => bucket_len / 2, _ => pani...
collection_len
identifier_name
mod.rs
//! # Schemes //! A scheme is a primitive for handling filesystem syscalls in Redox. //! Schemes accept paths from the kernel for `open`, and file descriptors that they generate //! are then passed for operations like `close`, `read`, `write`, etc. //! //! The kernel validates paths and file descriptors before they are...
pub fn iter(&self) -> ::collections::btree_map::Iter<usize, Arc<Box<Scheme + Send + Sync>>> { self.map.iter() } pub fn iter_name(&self) -> ::collections::btree_map::Iter<Box<[u8]>, usize> { self.names.iter() } /// Get the nth scheme. pub fn get(&self, id: usize) -> Option<&Ar...
{ SchemeList { map: BTreeMap::new(), names: BTreeMap::new(), next_id: 1 } }
identifier_body
mod.rs
//! # Schemes //! A scheme is a primitive for handling filesystem syscalls in Redox. //! Schemes accept paths from the kernel for `open`, and file descriptors that they generate //! are then passed for operations like `close`, `read`, `write`, etc. //! //! The kernel validates paths and file descriptors before they are...
RwLock::new(list) } /// Get the global schemes list, const pub fn schemes() -> RwLockReadGuard<'static, SchemeList> { SCHEMES.call_once(init_schemes).read() } /// Get the global schemes list, mutable pub fn schemes_mut() -> RwLockWriteGuard<'static, SchemeList> { SCHEMES.call_once(init_schemes).write() }
list.insert(Box::new(*b"sys"), Arc::new(Box::new(SysScheme::new()))).expect("failed to insert sys scheme"); list.insert(Box::new(*b"zero"), Arc::new(Box::new(ZeroScheme))).expect("failed to insert zero scheme");
random_line_split
mod.rs
//! # Schemes //! A scheme is a primitive for handling filesystem syscalls in Redox. //! Schemes accept paths from the kernel for `open`, and file descriptors that they generate //! are then passed for operations like `close`, `read`, `write`, etc. //! //! The kernel validates paths and file descriptors before they are...
(&self, name: &[u8]) -> Option<(usize, &Arc<Box<Scheme + Send + Sync>>)> { if let Some(&id) = self.names.get(name) { self.get(id).map(|scheme| (id, scheme)) } else { None } } /// Create a new scheme. pub fn insert(&mut self, name: Box<[u8]>, scheme: Arc<Box<S...
get_name
identifier_name
mod.rs
//! # Schemes //! A scheme is a primitive for handling filesystem syscalls in Redox. //! Schemes accept paths from the kernel for `open`, and file descriptors that they generate //! are then passed for operations like `close`, `read`, `write`, etc. //! //! The kernel validates paths and file descriptors before they are...
if self.next_id >= SCHEME_MAX_SCHEMES { self.next_id = 1; } while self.map.contains_key(&self.next_id) { self.next_id += 1; } if self.next_id >= SCHEME_MAX_SCHEMES { return Err(Error::new(EAGAIN)); } let id = self.next_id; ...
{ return Err(Error::new(EEXIST)); }
conditional_block
lexer.py
""" `GrammarLexer` is compatible with Pygments lexers and can be used to highlight the input using a regular grammar with token annotations. """ from __future__ import unicode_literals from pygments.token import Token from prompt_toolkit.layout.lexers import Lexer from .compiler import _CompiledGrammar __all__ = ( ...
(self, cli, text): m = self.compiled_grammar.match_prefix(text) if m: characters = [[self.default_token, c] for c in text] for v in m.variables(): # If we have a `Lexer` instance for this part of the input. # Tokenize recursively and apply tokens...
get_tokens
identifier_name
lexer.py
""" `GrammarLexer` is compatible with Pygments lexers and can be used to highlight the input using a regular grammar with token annotations. """ from __future__ import unicode_literals from pygments.token import Token from prompt_toolkit.layout.lexers import Lexer from .compiler import _CompiledGrammar __all__ = ( ...
return [(Token, text)]
random_line_split
lexer.py
""" `GrammarLexer` is compatible with Pygments lexers and can be used to highlight the input using a regular grammar with token annotations. """ from __future__ import unicode_literals from pygments.token import Token from prompt_toolkit.layout.lexers import Lexer from .compiler import _CompiledGrammar __all__ = ( ...
# Highlight trailing input. trailing_input = m.trailing_input() if trailing_input: for i in range(trailing_input.start, trailing_input.stop): characters[i][0] = Token.TrailingInput return characters else: return [...
lexer_tokens = lexer.get_tokens(cli, text[v.start:v.stop]) i = v.start for t, s in lexer_tokens: for c in s: if characters[i][0] == self.default_token: characters[i][0] = t ...
conditional_block
lexer.py
""" `GrammarLexer` is compatible with Pygments lexers and can be used to highlight the input using a regular grammar with token annotations. """ from __future__ import unicode_literals from pygments.token import Token from prompt_toolkit.layout.lexers import Lexer from .compiler import _CompiledGrammar __all__ = ( ...
self.default_token = default_token or Token self.lexers = lexers or {} def get_tokens(self, cli, text): m = self.compiled_grammar.match_prefix(text) if m: characters = [[self.default_token, c] for c in text] for v in m.variables(): # If we h...
""" Lexer which can be used for highlighting of tokens according to variables in the grammar. (It does not actual lexing of the string, but it exposes an API, compatible with the Pygments lexer class.) :param compiled_grammar: Grammar as returned by the `compile()` function. :param lexers: Diction...
identifier_body
issue-60925.rs
// build-fail // revisions: legacy v0 //[legacy]compile-flags: -Z symbol-mangling-version=legacy //[v0]compile-flags: -Z symbol-mangling-version=v0 #![feature(rustc_attrs)] // This test is the same code as in ui/issue-53912.rs but this test checks that the symbol mangling // fix produces the correct result, where...
() {}
main
identifier_name
issue-60925.rs
// build-fail // revisions: legacy v0 //[legacy]compile-flags: -Z symbol-mangling-version=legacy //[v0]compile-flags: -Z symbol-mangling-version=v0 #![feature(rustc_attrs)] // This test is the same code as in ui/issue-53912.rs but this test checks that the symbol mangling // fix produces the correct result, where...
fn main() {}
{ foo::foo(); }
identifier_body
issue-60925.rs
// build-fail // revisions: legacy v0 //[legacy]compile-flags: -Z symbol-mangling-version=legacy
#![feature(rustc_attrs)] // This test is the same code as in ui/issue-53912.rs but this test checks that the symbol mangling // fix produces the correct result, whereas that test just checks that the reproduction compiles // successfully and doesn't crash LLVM fn dummy() {} mod llvm { pub(crate) struct Foo; } mo...
//[v0]compile-flags: -Z symbol-mangling-version=v0
random_line_split
test_memory.py
# @Author: dileep # @Last Modified by: dileep import random import pytest from microbial_ai.regulation import Event, Action, Memory @pytest.fixture def random_action(): return Action(type='fixed', phi={'rxn1': (random.random(), '+')}) @pytest.fixture def random_event(random_action): return Event(state=ra...
def test_sample(self, random_event): memory = Memory(1000) with pytest.raises(ValueError): memory.sample(100) for _ in range(400): memory.add_event(random_event) assert len(memory.sample(200)) == 200
memory = Memory(1000) memory.add_event(random_event) assert len(memory.memory) == 1 assert memory.idx == 1 for _ in range(1500): memory.add_event(random_event) assert len(memory.memory) == memory.capacity assert memory.idx == (1000 - 500 + 1)
identifier_body
test_memory.py
# @Author: dileep # @Last Modified by: dileep import random import pytest from microbial_ai.regulation import Event, Action, Memory @pytest.fixture def random_action(): return Action(type='fixed', phi={'rxn1': (random.random(), '+')}) @pytest.fixture def random_event(random_action): return Event(state=ra...
assert len(memory.sample(200)) == 200
memory.add_event(random_event)
conditional_block
test_memory.py
# @Author: dileep # @Last Modified by: dileep import random import pytest from microbial_ai.regulation import Event, Action, Memory @pytest.fixture def random_action(): return Action(type='fixed', phi={'rxn1': (random.random(), '+')}) @pytest.fixture def random_event(random_action): return Event(state=ra...
assert memory.capacity == 1000 assert memory.idx == 0 def test_add_event(self, random_event): memory = Memory(1000) memory.add_event(random_event) assert len(memory.memory) == 1 assert memory.idx == 1 for _ in range(1500): memory.add_event(random_...
""" def test_initialization(self): memory = Memory(1000)
random_line_split
test_memory.py
# @Author: dileep # @Last Modified by: dileep import random import pytest from microbial_ai.regulation import Event, Action, Memory @pytest.fixture def
(): return Action(type='fixed', phi={'rxn1': (random.random(), '+')}) @pytest.fixture def random_event(random_action): return Event(state=random.randint(0, 100), action=random_action, next_state=random.randint(0, 100), reward=random.random()) @pytest.mark.usefixtures("random_event") class T...
random_action
identifier_name
WebhookEventMiddleware.ts
import {Constant, Context, HeaderParams, Inject, Middleware, MiddlewareMethods, RawBodyParams} from "@tsed/common"; import {BadRequest, InternalServerError} from "@tsed/exceptions"; import {Stripe} from "stripe"; import {STRIPE_WEBHOOK_EVENT, STRIPE_WEBHOOK_SIGNATURE} from "../constants"; import "../services/StripeFact...
}
{ const {secret, tolerance}: WebhookEventOptions = { ...this.webhooks, ...ctx.endpoint.store.get(WebhookEventMiddleware) }; if (!secret) { throw new InternalServerError( "Missing Stripe webhooks secret key. You can get this in your dashboard. See: https://dashboard.stripe.com/webh...
identifier_body
WebhookEventMiddleware.ts
import {Constant, Context, HeaderParams, Inject, Middleware, MiddlewareMethods, RawBodyParams} from "@tsed/common"; import {BadRequest, InternalServerError} from "@tsed/exceptions"; import {Stripe} from "stripe"; import {STRIPE_WEBHOOK_EVENT, STRIPE_WEBHOOK_SIGNATURE} from "../constants"; import "../services/StripeFact...
try { ctx.set(STRIPE_WEBHOOK_SIGNATURE, signature); ctx.set(STRIPE_WEBHOOK_EVENT, this.stripe.webhooks.constructEvent(body, signature, secret, tolerance)); } catch (err) { throw new BadRequest(`Stripe webhook error: ${err.message}`, err); } } }
{ throw new InternalServerError( "Missing Stripe webhooks secret key. You can get this in your dashboard. See: https://dashboard.stripe.com/webhooks." ); }
conditional_block
WebhookEventMiddleware.ts
import {STRIPE_WEBHOOK_EVENT, STRIPE_WEBHOOK_SIGNATURE} from "../constants"; import "../services/StripeFactory"; export interface WebhookEventOptions { secret: string; tolerance: number; } @Middleware() export class WebhookEventMiddleware implements MiddlewareMethods { @Inject() protected stripe: Stripe; @...
import {Constant, Context, HeaderParams, Inject, Middleware, MiddlewareMethods, RawBodyParams} from "@tsed/common"; import {BadRequest, InternalServerError} from "@tsed/exceptions"; import {Stripe} from "stripe";
random_line_split
WebhookEventMiddleware.ts
import {Constant, Context, HeaderParams, Inject, Middleware, MiddlewareMethods, RawBodyParams} from "@tsed/common"; import {BadRequest, InternalServerError} from "@tsed/exceptions"; import {Stripe} from "stripe"; import {STRIPE_WEBHOOK_EVENT, STRIPE_WEBHOOK_SIGNATURE} from "../constants"; import "../services/StripeFact...
implements MiddlewareMethods { @Inject() protected stripe: Stripe; @Constant("stripe.webhooks") protected webhooks: WebhookEventOptions; use(@HeaderParams("stripe-signature") signature: string, @RawBodyParams() body: Buffer, @Context() ctx: Context): any { const {secret, tolerance}: WebhookEventOptions...
WebhookEventMiddleware
identifier_name
firebase-plugin-service.ts
import {Injectable} from '@angular/core' import { AdminService, AuthSubject } from '@tangential/authorization-service' import { FirebaseProvider, FireBlanket } from '@tangential/firebase-util' import {TangentialPlugin} from '../plugin' import {PluginService} from './plugin-service' export const PluginsFirebase...
(subject:AuthSubject, plugin: TangentialPlugin): Promise<void> { let ref = PluginFirebaseRef(this.db, plugin.configuration.id) let cfg = plugin.configuration return FireBlanket.set(ref, {name: cfg.name, id: cfg.id, installing:true}) } }
savePluginState
identifier_name
firebase-plugin-service.ts
import {Injectable} from '@angular/core' import { AdminService, AuthSubject } from '@tangential/authorization-service' import { FirebaseProvider, FireBlanket
export const PluginsFirebaseRef = function(db: firebase.database.Database):firebase.database.Reference { return db.ref('/plugins') } export const PluginFirebaseRef = function(db: firebase.database.Database, pluginKey:string):firebase.database.Reference { return PluginsFirebaseRef(db).child(pluginKey) } @Injectab...
} from '@tangential/firebase-util' import {TangentialPlugin} from '../plugin' import {PluginService} from './plugin-service'
random_line_split
firebase-plugin-service.ts
import {Injectable} from '@angular/core' import { AdminService, AuthSubject } from '@tangential/authorization-service' import { FirebaseProvider, FireBlanket } from '@tangential/firebase-util' import {TangentialPlugin} from '../plugin' import {PluginService} from './plugin-service' export const PluginsFirebase...
}
{ let ref = PluginFirebaseRef(this.db, plugin.configuration.id) let cfg = plugin.configuration return FireBlanket.set(ref, {name: cfg.name, id: cfg.id, installing:true}) }
identifier_body
settings.py
""" Django settings for expense_tracker project. Generated by 'django-admin startproject' using Django 1.10.2. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ i...
ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'tracker.apps.TrackerConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.midd...
# SECURITY WARNING: don't run with debug turned on in production! DEBUG = True
random_line_split
collectforbuild.py
from blessings import Terminal from django.conf import settings from django.contrib.staticfiles import finders, storage as djstorage from django.core.exceptions import ImproperlyConfigured from django.core.management.base import BaseCommand from django.core.management import call_command from django.utils.encoding impo...
def find_all(self, storage, dir=''): """ Find all files in the specified directory, recursively. """ all_dirs = set() all_files = set() with patched_settings(STATICBUILDER_COLLECT_BUILT=True): dirs, files = storage.listdir(dir) all_dirs.upda...
self.clean_built(storage)
conditional_block
collectforbuild.py
from blessings import Terminal from django.conf import settings from django.contrib.staticfiles import finders, storage as djstorage from django.core.exceptions import ImproperlyConfigured from django.core.management.base import BaseCommand from django.core.management import call_command from django.utils.encoding impo...
""" Log helper; from Django's collectstatic command. """ msg = smart_text(msg) if not msg.endswith("\n"): msg += "\n" if level > 1: msg = t.bright_black(msg) if self.verbosity >= level: self.stdout.write(msg)
identifier_body
collectforbuild.py
from blessings import Terminal from django.conf import settings from django.contrib.staticfiles import finders, storage as djstorage from django.core.exceptions import ImproperlyConfigured from django.core.management.base import BaseCommand from django.core.management import call_command from django.utils.encoding impo...
def call_command_func(self, func, *args, **kwargs): print(t.bright_black) try: result = func(*args, **kwargs) finally: print(t.normal) return result def collect_for_build(self, build_dir): with patched_finders(): with patched_settings(...
# Copy the static assets to a the build directory. self.log(t.bold('Collecting static assets for building...')) self.call_command_func(self.collect_for_build, build_dir)
random_line_split
collectforbuild.py
from blessings import Terminal from django.conf import settings from django.contrib.staticfiles import finders, storage as djstorage from django.core.exceptions import ImproperlyConfigured from django.core.management.base import BaseCommand from django.core.management import call_command from django.utils.encoding impo...
(self, func, *args, **kwargs): print(t.bright_black) try: result = func(*args, **kwargs) finally: print(t.normal) return result def collect_for_build(self, build_dir): with patched_finders(): with patched_settings(STATICBUILDER_COLLECT_BUI...
call_command_func
identifier_name
library.ts
import types from '../constants/action-types'; import { config } from '../lib/app'; import * as utils from '../utils/utils'; import { Action, TrackModel, SortBy, SortOrder } from '../../shared/types/interfaces'; export interface LibrarySort { by: SortBy; order: SortOrder; } export interface LibraryState { trac...
// let musicFolders = app.config.get('musicFolders'); // // Check if we received folders // if (folders !== undefined) { // musicFolders = musicFolders.concat(folders); // // Remove duplicates, useless children, ect... // musicFolders = utils.removeUselessFolders(musicFolders...
// case (types.LIBRARY_ADD_FOLDERS): { // TODO Redux -> move to a thunk // const { folders } = action.payload;
random_line_split
incoming.rs
/// Holds the state for data going from API -> turtl (incoming sync data), /// including tracking which sync item's we've seen and which we haven't. pub struct SyncIncoming { /// Holds our sync config. Note that this is shared between the sync system /// and the `Turtl` object in the main thread. config: ...
{ match jedi::get_opt::<Vec<i64>>(&["sync_ids"], val_with_sync_ids) { Some(x) => { let mut db_guard = lock!(turtl.db); if db_guard.is_some() { match SyncIncoming::ignore_on_next(db_guard.as_mut().expect("turtl::sync_incoming::ignore_syncs_maybe() -- db is None"), &x) ...
identifier_body
incoming.rs
// ignore it. ErrorKind::WouldBlock => return Ok(()), _ => { info!("SyncIncoming.sync_from_api() -- unknown IO error kind: {:?}", io.kind()); self.set_connected(false); ...
turtl.find_model_key(&mut model)?; model.deserialize()?; }
random_line_split
incoming.rs
fn get_ignored_impl(db: &mut Storage) -> TResult<Vec<String>> { let ignored = match db.kv_get(SYNC_IGNORE_KEY)? { Some(x) => jedi::parse(&x)?, None => Vec::new(), }; Ok(ignored) } /// Static handler for ignoring sync items. /// /// Tracks which sync ...
set_run_version
identifier_name
renderGovernance.js
var mongoose = require('mongoose'); var Governance = mongoose.model('Governance'); var modelClass = require('../modelClass'); var renderModel = new modelClass.RenderModel( Governance, 'governance/governance.tex', 'governance/na.tex'); var is = require('is-js'); var defaultData = require('../default.json'); var _ = ...
'use strict';
random_line_split
whistle-transform.js
var Transform = require('pipestream').Transform; var util = require('util'); var iconv = require('iconv-lite'); var LT_RE = /^\s*</; var JSON_RE = /^\s*[\[\{]/; function WhistleTransform(options) { Transform.call(this); options = options || {}; var value = parseInt((options.speed * 1000) / 8); if (value > 0) ...
return this._strictHtml ? LT_RE.test(chunk.toString()) : !JSON_RE.test(chunk.toString()); }; WhistleTransform.prototype._transform = function (chunk, encoding, callback) { var self = this; var cb = function () { if (self._allowInject && self._ended && self._bottom) { chunk = chunk ? Buffer.conc...
random_line_split
whistle-transform.js
var Transform = require('pipestream').Transform; var util = require('util'); var iconv = require('iconv-lite'); var LT_RE = /^\s*</; var JSON_RE = /^\s*[\[\{]/; function WhistleTransform(options) { Transform.call(this); options = options || {}; var value = parseInt((options.speed * 1000) / 8); if (value > 0) ...
return this._strictHtml ? LT_RE.test(chunk.toString()) : !JSON_RE.test(chunk.toString()); }; WhistleTransform.prototype._transform = function (chunk, encoding, callback) { var self = this; var cb = function () { if (self._allowInject && self._ended && self._bottom) { chunk = chunk ? Buffer.con...
{ return true; }
conditional_block
whistle-transform.js
var Transform = require('pipestream').Transform; var util = require('util'); var iconv = require('iconv-lite'); var LT_RE = /^\s*</; var JSON_RE = /^\s*[\[\{]/; function
(options) { Transform.call(this); options = options || {}; var value = parseInt((options.speed * 1000) / 8); if (value > 0) { this._speed = value; } if ((value = parseInt(options.delay)) > 0) { this._delay = value; } var charset = options.charset && String(options.charset); if (!iconv.encodin...
WhistleTransform
identifier_name
whistle-transform.js
var Transform = require('pipestream').Transform; var util = require('util'); var iconv = require('iconv-lite'); var LT_RE = /^\s*</; var JSON_RE = /^\s*[\[\{]/; function WhistleTransform(options) { Transform.call(this); options = options || {}; var value = parseInt((options.speed * 1000) / 8); if (value > 0) ...
util.inherits(WhistleTransform, Transform); WhistleTransform.prototype.allowInject = function (chunk) { if (!chunk || (!this._strictHtml && !this._safeHtml)) { return true; } return this._strictHtml ? LT_RE.test(chunk.toString()) : !JSON_RE.test(chunk.toString()); }; WhistleTransform.prototype._tr...
{ var buf = options[name]; return buf == null || Buffer.isBuffer(buf) ? buf : iconv.encode(buf + '', charset); }
identifier_body
gulpfile.js
const gulp = require('gulp'); const HubRegistry = require('gulp-hub'); const browserSync = require('browser-sync'); const conf = require('./conf/gulp.conf'); // Load some files into the registry const hub = new HubRegistry([conf.path.tasks('*.js')]); // Tell gulp to use the tasks just loaded gulp.registry(hub); <% ...
-%> gulp.task('build', <%- buildTask %>); gulp.task('test', <%- testTask %>); gulp.task('test:auto', <%- testAutoTask %>); gulp.task('serve', <%- serveTask %>); gulp.task('serve:dist', gulp.series('default', 'browsersync:dist')); gulp.task('default', gulp.series('clean', 'build')); gulp.task('watch', watch); function...
{ -%> gulp.task('inject', gulp.series(gulp.parallel('styles', 'scripts'), 'inject')); <% }
conditional_block
gulpfile.js
const gulp = require('gulp'); const HubRegistry = require('gulp-hub'); const browserSync = require('browser-sync'); const conf = require('./conf/gulp.conf'); // Load some files into the registry const hub = new HubRegistry([conf.path.tasks('*.js')]); // Tell gulp to use the tasks just loaded gulp.registry(hub); <% ...
function watch(done) { <% if (modules === 'inject') { -%> gulp.watch([ conf.path.src('index.html'), 'bower.json' ], gulp.parallel('inject')); <% } -%> <% if (framework !== 'react' && modules !== 'webpack') { -%> <% if (modules !== 'systemjs') { -%> gulp.watch(conf.path.src('app/**/*.html'), gulp.seri...
{ browserSync.reload(); cb(); }
identifier_body
gulpfile.js
const gulp = require('gulp'); const HubRegistry = require('gulp-hub'); const browserSync = require('browser-sync'); const conf = require('./conf/gulp.conf'); // Load some files into the registry const hub = new HubRegistry([conf.path.tasks('*.js')]); // Tell gulp to use the tasks just loaded gulp.registry(hub); <% ...
<% } -%> done(); }
random_line_split
gulpfile.js
const gulp = require('gulp'); const HubRegistry = require('gulp-hub'); const browserSync = require('browser-sync'); const conf = require('./conf/gulp.conf'); // Load some files into the registry const hub = new HubRegistry([conf.path.tasks('*.js')]); // Tell gulp to use the tasks just loaded gulp.registry(hub); <% ...
(done) { <% if (modules === 'inject') { -%> gulp.watch([ conf.path.src('index.html'), 'bower.json' ], gulp.parallel('inject')); <% } -%> <% if (framework !== 'react' && modules !== 'webpack') { -%> <% if (modules !== 'systemjs') { -%> gulp.watch(conf.path.src('app/**/*.html'), gulp.series('partials', r...
watch
identifier_name
extern-call-deep2.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 ...
; }
{ // Make sure we're on a task with small Rust stacks (main currently // has a large stack) do task::spawn { let result = count(1000u); info!("result = %?", result); assert_eq!(result, 1000u); }
identifier_body
extern-call-deep2.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 ...
} #[fixed_stack_segment] #[inline(never)] fn count(n: uint) -> uint { unsafe { info!("n = %?", n); rustrt::rust_dbg_call(cb, n) } } pub fn main() { // Make sure we're on a task with small Rust stacks (main currently // has a large stack) do task::spawn { let result = count...
{ count(data - 1u) + 1u }
conditional_block
extern-call-deep2.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 ...
(n: uint) -> uint { unsafe { info!("n = %?", n); rustrt::rust_dbg_call(cb, n) } } pub fn main() { // Make sure we're on a task with small Rust stacks (main currently // has a large stack) do task::spawn { let result = count(1000u); info!("result = %?", result); ...
count
identifier_name
extern-call-deep2.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 ...
#[fixed_stack_segment] #[inline(never)] fn count(n: uint) -> uint { unsafe { info!("n = %?", n); rustrt::rust_dbg_call(cb, n) } } pub fn main() { // Make sure we're on a task with small Rust stacks (main currently // has a large stack) do task::spawn { let result = count(100...
} }
random_line_split
__init__.py
structured import dict2xml # Zato from zato.common import DATA_FORMAT, PUB_SUB, ZATO_ERROR, ZATO_NONE, ZATO_OK from zato.common.pubsub import ItemFull, PermissionDenied from zato.common.util import get_basic_auth_credentials from zato.server.connection.http_soap import BadRequest, Forbidden, TooManyRequests, Unauthori...
# ################################################################################################################################ class StoreOverflownMessages(AdminService): """ Stores on filesystem messages that were above a consumer's max backlog and marks them as rejected by the consumer. """ def han...
interval = float(self.server.fs_server_config.pubsub.move_to_target_queues_interval) while True: self.logger.debug('Moving messages to target queues, interval %rs', interval) spawn(self._move_to_target_queues) sleep(interval)
identifier_body
__init__.py
structured import dict2xml # Zato from zato.common import DATA_FORMAT, PUB_SUB, ZATO_ERROR, ZATO_NONE, ZATO_OK from zato.common.pubsub import ItemFull, PermissionDenied from zato.common.util import get_basic_auth_credentials from zato.server.connection.http_soap import BadRequest, Forbidden, TooManyRequests, Unauthori...
def handle(self): # TODO: self.logger's name should be 'zato_pubsub' so it got logged to the same location # the rest of pub/sub does. interval = float(self.server.fs_server_config.pubsub.invoke_callbacks_interval) while True: self.logger.debug('Invoking pub/sub callb...
outconn = self.outgoing.plain_http[consumer.callback_name] if outconn.config['data_format'] == DATA_FORMAT.XML: out = dict2xml(out) content_type = 'application/xml' else: out = dumps(out) ...
conditional_block
__init__.py
structured import dict2xml # Zato from zato.common import DATA_FORMAT, PUB_SUB, ZATO_ERROR, ZATO_NONE, ZATO_OK from zato.common.pubsub import ItemFull, PermissionDenied from zato.common.util import get_basic_auth_credentials from zato.server.connection.http_soap import BadRequest, Forbidden, TooManyRequests, Unauthori...
(AdminService): """ Invoked when a server is starting - periodically spawns a greenlet invoking consumer URL callbacks. """ def _reject(self, msg_ids, sub_key, consumer, reason): self.pubsub.reject(sub_key, msg_ids) self.logger.error('Could not deliver messages `%s`, sub_key `%s` to `%s`, re...
InvokeCallbacks
identifier_name
__init__.py
.structured import dict2xml # Zato from zato.common import DATA_FORMAT, PUB_SUB, ZATO_ERROR, ZATO_NONE, ZATO_OK from zato.common.pubsub import ItemFull, PermissionDenied from zato.common.util import get_basic_auth_credentials from zato.server.connection.http_soap import BadRequest, Forbidden, TooManyRequests, Unauthor...
# ################################################################################################################################ class DeleteExpired(AdminService): """ Invoked when a server is starting - periodically spawns a greenlet deleting expired messages. """ def _delete_expired(self): self...
from zato.server.service.internal import AdminService logger_overflown = getLogger('zato_pubsub_overflown')
random_line_split
ui_role_list_item.py
#!/usr/bin/python """Test to verify presentation of selectable list items.""" from macaroon.playback import * import utils sequence = MacroSequence() sequence.append(KeyComboAction("<Control><Shift>n")) sequence.append(KeyComboAction("Tab")) sequence.append(utils.StartRecordingAction()) sequence.append(KeyComboAct...
sequence.append(KeyComboAction("Left")) sequence.append(utils.AssertPresentationAction( "3. Left to previous list item", ["BRAILLE LINE: 'soffice application Template Manager frame Template Manager dialog Drawings page tab list My Templates list item'", " VISIBLE: 'My Templates list item', cursor=1",...
["BRAILLE LINE: 'soffice application Template Manager frame Template Manager dialog Drawings page tab list Presentation Backgrounds list item'", " VISIBLE: 'Presentation Backgrounds list it', cursor=1", "SPEECH OUTPUT: 'Presentation Backgrounds'"])) sequence.append(utils.StartRecordingAction())
random_line_split
pic.py
# _*_ coding: utf-8 _*_ # filename: pic.py import csv import numpy import matplotlib.pyplot as plt # 读取 house.csv 文件中价格和面积列
print price print size plt.figure() plt.subplot(211) # plt.title("price") plt.title("/ 10000RMB") plt.hist(price, bins=20) plt.subplot(212) # plt.title("area") plt.xlabel("/ m**2") plt.hist(size, bins=20) plt.figure(2) plt.title("price") plt.plot(price) plt.show() # 求价格和面积的平均值 price_mean = numpy.mean(price) size_m...
price, size = numpy.loadtxt('house.csv', delimiter='|', usecols=(1, 2), unpack=True)
random_line_split
binPackerAlgorithm.ts
class BinPackerNode { x: number; y: number; width: number; height: number; leftChild?: BinPackerNode; rightChild?: BinPackerNode; used: boolean; constructor(x: number, y: number, width: number, height: number) { this.x = x; this.y = y; this.width = width; this.height = height; this....
// if it fits perfectly then use this gap if (width === node.width && height === node.height) { node.used = true; return { x: node.x, y: node.y }; } // checks if we partition in vertical or horizontal if (node.width - width > node.height - height) { node.leftChild = new BinPacke...
{ return null; }
conditional_block
binPackerAlgorithm.ts
class BinPackerNode { x: number; y: number; width: number; height: number; leftChild?: BinPackerNode; rightChild?: BinPackerNode; used: boolean; constructor(x: number, y: number, width: number, height: number) { this.x = x; this.y = y; this.width = width; this.height = height; this....
); } if (node.used || width > node.width || height > node.height) { return null; } // if it fits perfectly then use this gap if (width === node.width && height === node.height) { node.used = true; return { x: node.x, y: node.y }; } // checks if we partition in vert...
return ( BinPacker._recursiveFindPlace(node.leftChild, width, height) || BinPacker._recursiveFindPlace(node.rightChild, width, height)
random_line_split
binPackerAlgorithm.ts
class BinPackerNode { x: number; y: number; width: number; height: number; leftChild?: BinPackerNode; rightChild?: BinPackerNode; used: boolean; constructor(x: number, y: number, width: number, height: number) { this.x = x; this.y = y; this.width = width; this.height = height; this....
}
{ width = BinPacker._makeDivisibleBy(width, this._divisibleBy) + this._paddingX; height = BinPacker._makeDivisibleBy(height, this._divisibleBy) + this._paddingY; return BinPacker._recursiveFindPlace(this._rootNode, width, height); }
identifier_body
binPackerAlgorithm.ts
class BinPackerNode { x: number; y: number; width: number; height: number; leftChild?: BinPackerNode; rightChild?: BinPackerNode; used: boolean; constructor(x: number, y: number, width: number, height: number) { this.x = x; this.y = y; this.width = width; this.height = height; this....
(width: number, height: number) { width = BinPacker._makeDivisibleBy(width, this._divisibleBy) + this._paddingX; height = BinPacker._makeDivisibleBy(height, this._divisibleBy) + this._paddingY; return BinPacker._recursiveFindPlace(this._rootNode, width, height); } }
placeNextRectangle
identifier_name
historypack.rs
} impl HistoryPackVersion { fn new(value: u8) -> Result<Self> { match value { 0 => Ok(HistoryPackVersion::Zero), 1 => Ok(HistoryPackVersion::One), _ => Err(HistoryPackError(format!( "invalid history pack version number '{:?}'", value ...
HistoryPackIterator
identifier_name
historypack.rs
} impl HgIdHistoryStore for HistoryPack { fn get_node_info(&self, key: &Key) -> Result<Option<NodeInfo>> { let hgid_location = match self.index.get_hgid_entry(key)? { None => return Ok(None), Some(location) => location, }; self.read_node_info(key, hgid_location.offse...
let path = &mutpack.flush().unwrap().unwrap()[0]; let pack_path = path.with_extension("histpack");
random_line_split
historypack.rs
, Write}, mem::{drop, take}, path::{Path, PathBuf}, sync::Arc, }; use anyhow::{format_err, Result}; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use memmap::{Mmap, MmapOptions}; use thiserror::Error; use types::{HgId, Key, NodeInfo, RepoPath, RepoPathBuf}; use util::path::remove_file; use cra...
mmap, version, index: HistoryIndex::new(&index_path)?, base_path: Arc::new(base_path), pack_path, index_path, }) } pub fn len(&self) -> usize { self.mmap.len() } pub fn base_path(&self) -> &Path { &self.ba...
{ let base_path = PathBuf::from(path); let pack_path = path.with_extension("histpack"); let file = File::open(&pack_path)?; let len = file.metadata()?.len(); if len < 1 { return Err(format_err!( "empty histpack '{:?}' is invalid", path....
identifier_body
dojox.widget.DataPresentation.d.ts
/// <reference path="Object.d.ts" /> module dojox.widget{ export class DataPresentation{
legendHorizontal : bool; url : Object; urlContent : Object; refreshInterval : Object; refreshIntervalPending : Object; data : Object; preparedstore : Object; query : Object; queryOptions : Object; chartWidget : Object; legendWidget : Object; gridWidget : Object; domNode : Object; theme : Object; setURL (url?:String,url...
type : String; chartType : String; reverse : bool; animate : Object; labelMod : number;
random_line_split
dojox.widget.DataPresentation.d.ts
/// <reference path="Object.d.ts" /> module dojox.widget{ export class
{ type : String; chartType : String; reverse : bool; animate : Object; labelMod : number; legendHorizontal : bool; url : Object; urlContent : Object; refreshInterval : Object; refreshIntervalPending : Object; data : Object; preparedstore : Object; query : Object; queryOptions : Object; chartWidget : Object; legendWidge...
DataPresentation
identifier_name
tabview.d.ts
import { ElementRef, EventEmitter, AfterContentInit, QueryList } from '@angular/core'; import { BlockableUI } from '../common/api'; export declare class TabViewNav { tabs: TabPanel[]; orientation: string; onTabClick: EventEmitter<any>; onTabCloseClick: EventEmitter<any>; getDefaultHeaderClass(tab: T...
styleClass: string; controlClose: boolean; lazy: boolean; tabPanels: QueryList<TabPanel>; onChange: EventEmitter<any>; onClose: EventEmitter<any>; initialized: boolean; tabs: TabPanel[]; constructor(el: ElementRef); ngAfterContentInit(): void; initTabs(): void; open(event...
el: ElementRef; orientation: string; style: any;
random_line_split
tabview.d.ts
import { ElementRef, EventEmitter, AfterContentInit, QueryList } from '@angular/core'; import { BlockableUI } from '../common/api'; export declare class
{ tabs: TabPanel[]; orientation: string; onTabClick: EventEmitter<any>; onTabCloseClick: EventEmitter<any>; getDefaultHeaderClass(tab: TabPanel): string; clickTab(event: any, tab: TabPanel): void; clickClose(event: any, tab: TabPanel): void; } export declare class TabPanel { header: str...
TabViewNav
identifier_name
ccputils.py
# the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # 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 # ...
if useFilesOnly: return None # try lp first, then cups lpgrp = None try: lpgrp = grp.getgrnam(default) except Exception: try: lpgrp = grp.getgrnam(alternative) except Exception: pass if lpg...
if os.path.exists(cupsConfigFile): configGid = os.stat(cupsConfigFile).st_gid if configGid not in blacklistedGroupIds: return configGid else: logging.debug( "Group " + ...
conditional_block
ccputils.py
# the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # 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 # ...
(data, jobtype): """Convert a file to a base64 encoded file. Args: pathname: data to base64 encode jobtype: job type being encoded - pdf, jpg etc Returns: string, base64 encoded string. For more info on data urls, see: http://en.wikipedia.org/wiki...
Base64Encode
identifier_name
ccputils.py
# the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # 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 # ...
@staticmethod def is_exe(fpath): return os.path.exists(fpath) and os.access(fpath, os.X_OK) @staticmethod def which(program): for path in os.environ["PATH"].split(os.pathsep): exe_file = os.path.join(path, program) if Utils.is_exe(exe_file): ret...
"""Check if a file is or isnt a PDF Args: filename: string, name of the file to check Returns: boolean: True = is a PDF, False = not a PDF. """ p = subprocess.Popen(["file", '-'], stdout=subprocess.PIPE, stdin=subprocess.PIPE) output = p.communicate(filedata)[0] ...
identifier_body
ccputils.py
# the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # 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 # ...
Args: pathname: string, (path)name of file. Returns: string: contents of file. """ try: f = open(pathname, 'rb') s = f.read() return s except IOError as e: print 'ERROR: Error opening %s\n%s', pathname, e ...
random_line_split
PartType.ts
import { FieldPresence, FieldProcessorAdt, FieldSchema, Processor, ValueSchema } from '@ephox/boulder'; import { Adt, Fun, Id, Optional } from '@ephox/katamari'; import { SimpleOrSketchSpec } from '../api/component/SpecTypes'; import { CompositeSketchDetail } from '../api/ui/Sketcher'; type DeepPartial<T> = { [P in...
// Groups cannot choose their schema. const fGroupSchema = FieldSchema.state('schema', () => [ FieldSchema.option('preprocess') ]); const fDefaults = FieldSchema.defaulted('defaults', Fun.constant({ })); const fOverrides = FieldSchema.defaulted('overrides', Fun.constant({ })); const requiredSpec = ValueSchema.objO...
'pname', FieldPresence.defaultedThunk((typeSpec: PartSpec<any, any>) => '<alloy.' + Id.generate(typeSpec.name) + '>'), ValueSchema.anyValue() );
random_line_split
widgets.py
# -*- coding: utf-8 -*- import re from django.utils.safestring import mark_safe from django.contrib.admin.widgets import AdminFileWidget from django.template.defaultfilters import slugify from django.utils.encoding import smart_text from unidecode import unidecode from django.forms.widgets import FILE_INPUT_CONT...
ext = u"" if '.' in filename: ext = u"." + filename.rpartition('.')[2] filename = filename.rpartition('.')[0] filename = re.sub(r'[_.,:;@#$%^&?*|()\[\]]', '-', filename) filename = slugify(unidecode(smart_text(filename))) + ext ...
random_line_split
widgets.py
# -*- coding: utf-8 -*- import re from django.utils.safestring import mark_safe from django.contrib.admin.widgets import AdminFileWidget from django.template.defaultfilters import slugify from django.utils.encoding import smart_text from unidecode import unidecode from django.forms.widgets import FILE_INPUT_CONT...
(ImagePreviewWidget): template_name = 'admin/attachment/widgets/preview_image_input_vertical.html' class FileWidget(ClearableFileInput): def value_from_datadict(self, data, files, name): for key, file in files.items(): filename = file._get_name() ext = u"" ...
ImagePreviewWidgetVertical
identifier_name
widgets.py
# -*- coding: utf-8 -*- import re from django.utils.safestring import mark_safe from django.contrib.admin.widgets import AdminFileWidget from django.template.defaultfilters import slugify from django.utils.encoding import smart_text from unidecode import unidecode from django.forms.widgets import FILE_INPUT_CONT...
def value_from_datadict(self, data, files, name): for key, file in files.items(): filename = file._get_name() ext = u"" if '.' in filename: ext = u"." + filename.rpartition('.')[2] filename = filename.rpartition('.')[0] ...
output = [] output.append(super(AdminFileWidget, self).render(name, value, attrs)) # really for AdminFileWidget instance = getattr(value, 'instance', None) if instance is not None and value: output = ['<a target="_blank" href="%s"><img src="%s" alt="%s"/></a>' % \ ...
identifier_body
widgets.py
# -*- coding: utf-8 -*- import re from django.utils.safestring import mark_safe from django.contrib.admin.widgets import AdminFileWidget from django.template.defaultfilters import slugify from django.utils.encoding import smart_text from unidecode import unidecode from django.forms.widgets import FILE_INPUT_CONT...
return upload class ImagePreviewWidgetHorizontal(ImagePreviewWidget): template_name = 'admin/attachment/widgets/preview_image_input_horizontal.html' class ImagePreviewWidgetVertical(ImagePreviewWidget): template_name = 'admin/attachment/widgets/preview_image_input_vertical.html' c...
if upload: # If the user contradicts themselves (uploads a new file AND # checks the "clear" checkbox), we return a unique marker # object that FileField will turn into a ValidationError. return FILE_INPUT_CONTRADICTION # False signals to ...
conditional_block
tempsense.js
module.exports = function(HAPnode, config, functions) { var Accessory = HAPnode.Accessory; var Service = HAPnode.Service; var Characteristic = HAPnode.Characteristic; var uuid = HAPnode.uuid;
module.newDevice = function(device, tempDisplayUnit) { var temperatureDisplayUnit = tempDisplayUnit; var Sensor = { getTemperature: function() { temperature = functions.getVariable(device.id, 'temperature','number'); if (this.veraIsUsingFahrenheit()){ ...
var debug = HAPnode.debug; var module = {};
random_line_split
tempsense.js
module.exports = function(HAPnode, config, functions) { var Accessory = HAPnode.Accessory; var Service = HAPnode.Service; var Characteristic = HAPnode.Characteristic; var uuid = HAPnode.uuid; var debug = HAPnode.debug; var module = {}; module.newDevice ...
return temperature; }, veraIsUsingFahrenheit: function(){ return this.getTemperatureDisplayUnits() == Characteristic.TemperatureDisplayUnits.FAHRENHEIT }, fahrenheitToCelsius: function(temperature) { return (temperature - ...
{ temperature = this.fahrenheitToCelsius(temperature); }
conditional_block
webglprogram.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ // https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl use dom::bindings::codegen::Bindings::WebGLPr...
(self) { if !self.is_deleted.get() { self.is_deleted.set(true); self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::DeleteProgram(self.id))).unwrap(); } } /// glLinkProgram fn link(self) { self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::LinkProgram(self.i...
delete
identifier_name
webglprogram.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ // https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl use dom::bindings::codegen::Bindings::WebGLPr...
let (sender, receiver) = channel(); self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::GetAttribLocation(self.id, name, sender))).unwrap(); Ok(receiver.recv().unwrap()) } /// glGetUniformLocation fn get_uniform_location(self, name: String) -> WebGLResult<Option<i32>> { if...
{ return Ok(None); }
conditional_block
webglprogram.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ // https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl use dom::bindings::codegen::Bindings::WebGLPr...
/// glUseProgram fn use_program(self) { self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::UseProgram(self.id))).unwrap(); } /// glAttachShader fn attach_shader(self, shader: &WebGLShader) -> WebGLResult<()> { let shader_slot = match shader.gl_type() { constants::FRAG...
{ self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::LinkProgram(self.id))).unwrap(); }
identifier_body
webglprogram.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ // https://www.khronos.org/registry/webgl/specs/latest/1.0/webgl.idl use dom::bindings::codegen::Bindings::WebGLPr...
/// glDeleteProgram fn delete(self) { if !self.is_deleted.get() { self.is_deleted.set(true); self.renderer.send(CanvasMsg::WebGL(CanvasWebGLMsg::DeleteProgram(self.id))).unwrap(); } } /// glLinkProgram fn link(self) { self.renderer.send(CanvasMsg::Web...
fn get_uniform_location(self, name: String) -> WebGLResult<Option<i32>>; } impl<'a> WebGLProgramHelpers for &'a WebGLProgram {
random_line_split
t_ClaytonCopulaFactory_std.py
#! /usr/bin/env python from openturns import * TESTPREAMBLE() RandomGenerator.SetSeed(0) try: distribution = ClaytonCopula(1.5) size = 1000 sample = distribution.getSample(size) factory = ClaytonCopulaFactory() estimatedDistribution = factory.build(sample) print "distribution=", repr(distribu...
except: import sys print "t_ClaytonCopulaFactory_std.py", sys.exc_type, sys.exc_value
random_line_split
problem.py
import sys reload(sys) sys.setdefaultencoding("utf8") from urllib import urlencode from flask import jsonify, redirect, url_for, abort, request, render_template from syzoj import oj, controller from syzoj.models import User, Problem, File, FileParser from syzoj.controller import Paginate, Tools from .common import n...
if not problem: abort(404) if problem.is_allowed_use(user) == False: return not_have_permission() return render_template("problem.html", tool=Tools, tab="problem_set", problem=problem) @oj.route("/problem/<int:problem_id>/edit", methods=["GET", "POST"]) def edit_problem(problem_id): ...
problem = Problem.query.filter_by(id=problem_id).first()
random_line_split
problem.py
import sys reload(sys) sys.setdefaultencoding("utf8") from urllib import urlencode from flask import jsonify, redirect, url_for, abort, request, render_template from syzoj import oj, controller from syzoj.models import User, Problem, File, FileParser from syzoj.controller import Paginate, Tools from .common import n...
(problem_id): session_id = request.args.get('session_id') user = User.get_cur_user(session_id=session_id) problem = Problem.query.filter_by(id=problem_id).first() if problem and user and user.have_privilege(2): if request.method == "POST": problem.is_public = True elif reques...
change_public_attr
identifier_name
problem.py
import sys reload(sys) sys.setdefaultencoding("utf8") from urllib import urlencode from flask import jsonify, redirect, url_for, abort, request, render_template from syzoj import oj, controller from syzoj.models import User, Problem, File, FileParser from syzoj.controller import Paginate, Tools from .common import n...
session_id = request.args.get('session_id') user = User.get_cur_user(session_id=session_id) problem = Problem.query.filter_by(id=problem_id).first() if problem and user and user.have_privilege(2): if request.method == "POST": problem.is_public = True elif request.method == "DELET...
identifier_body
problem.py
import sys reload(sys) sys.setdefaultencoding("utf8") from urllib import urlencode from flask import jsonify, redirect, url_for, abort, request, render_template from syzoj import oj, controller from syzoj.models import User, Problem, File, FileParser from syzoj.controller import Paginate, Tools from .common import n...
if problem.is_allowed_use(user) == False: return not_have_permission() return render_template("problem.html", tool=Tools, tab="problem_set", problem=problem) @oj.route("/problem/<int:problem_id>/edit", methods=["GET", "POST"]) def edit_problem(problem_id): user = User.get_cur_user() if not ...
abort(404)
conditional_block
hash.rs
// Copyright 2015, 2016 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 la...
}
{ assert_eq!(hash::H256::from(0), H256(hash::H256::from(0)).into()); }
identifier_body
hash.rs
// Copyright 2015, 2016 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 la...
let mut hex = "0x".to_owned(); hex.push_str(&self.0.to_hex()); serializer.serialize_str(&hex) } } } } impl_hash!(H64, Hash64); impl_hash!(Address, Hash160); impl_hash!(H256, Hash256); impl_hash!(H520, Hash520); impl_hash!(Bloom, Hash2048); #[cfg(test)] mod test { use std::str::FromStr; use serde_j...
impl Serialize for $name { fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error> where S: Serializer {
random_line_split