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
portal-directives.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 { ComponentFactoryResolver, ComponentRef, Directive, EmbeddedViewRef, EventEmitter, NgModule, On...
*/ @Directive({ selector: '[cdkPortal]', exportAs: 'cdkPortal', }) export class CdkPortal extends TemplatePortal { constructor(templateRef: TemplateRef<any>, viewContainerRef: ViewContainerRef) { super(templateRef, viewContainerRef); } } /** * @deprecated Use `CdkPortal` instead. * @breaking-change 9.0....
* the directive instance itself can be attached to a host, enabling declarative use of portals.
random_line_split
portal-directives.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 { ComponentFactoryResolver, ComponentRef, Directive, EmbeddedViewRef, EventEmitter, NgModule, On...
extends BasePortalOutlet implements OnInit, OnDestroy { private _document: Document; /** Whether the portal component is initialized. */ private _isInitialized = false; /** Reference to the currently-attached component/view ref. */ private _attachedRef: CdkPortalOutletAttachedRef; constructor( pri...
CdkPortalOutlet
identifier_name
upload.js
(function(win) { var dataType = { form: getFormData, json: getJsonData, data: getData }; function genUId() { var date = new Date().getTime(); var uuid = 'xxxxxx4xxxyxxxxxxx'.replace(/[xy]/g, function(c) { var r = (date + Math.random() * 16) % 16 | 0; date = Math.floor(date / 16); return (c == 'x...
var options = { domain: '', method: 'POST', file_data_name: 'file', unique_key: 'key', base64_size: 4 * 1024 * 1024, chunk_size: 4 * 1024 * 1024, headers: {}, multi_parmas: {}, query: {}, support_options: true, data: dataType.form, genUId: genUId }; if (!opts || !opts.domain) {...
return uuid; }; function mergeOption(opts) {
random_line_split
upload.js
(function(win) { var dataType = { form: getFormData, json: getJsonData, data: getData }; function genUId() { var date = new Date().getTime(); var uuid = 'xxxxxx4xxxyxxxxxxx'.replace(/[xy]/g, function(c) { var r = (date + Math.random() * 16) % 16 | 0; date = Math.floor(date / 16); return (c == 'x...
(m, callback) { for (var key in m) { callback(key, m[key]); } } function getFormData(file, opts) { var form = new FormData(); if (opts.unique_key) { var suffix = file.name.substr(file.name.lastIndexOf('.')); var unique_value = genUId() + suffix; form.append(opts.unique_key, unique_value); opts...
mEach
identifier_name
upload.js
(function(win) { var dataType = { form: getFormData, json: getJsonData, data: getData }; function genUId() { var date = new Date().getTime(); var uuid = 'xxxxxx4xxxyxxxxxxx'.replace(/[xy]/g, function(c) { var r = (date + Math.random() * 16) % 16 | 0; date = Math.floor(date / 16); return (c == 'x...
var oHeight = imageInfo.height; var maxHeight = config.maxHeight || 0; if(maxHeight > 0 && oHeight > maxHeight){ var ratioHeight = maxHeight/oHeight; ratio = Math.min(ratio,ratioHeight); } var maxSize = config.maxSize || 0; var oSize = Math.ceil(imageInfo.size/1000); //K,Math.ceil(0.3) = 1; if(o...
{ ratio = maxWidth/oWidth; }
conditional_block
upload.js
(function(win) { var dataType = { form: getFormData, json: getJsonData, data: getData }; function genUId() { var date = new Date().getTime(); var uuid = 'xxxxxx4xxxyxxxxxxx'.replace(/[xy]/g, function(c) { var r = (date + Math.random() * 16) % 16 | 0; date = Math.floor(date / 16); return (c == 'x...
function getResizeRatio(imageInfo,config){ //hasOwnProperty? var ratio = 1; var oWidth = imageInfo.width; var maxWidth = config.maxWidth || 0; if(maxWidth > 0 && oWidth > maxWidth){ ratio = maxWidth/oWidth; } var oHeight = imageInfo.height; var maxHeight = config.maxHeight || 0; if(maxHeight...
{ return new Upload(options); }
identifier_body
poke-catalog.component.ts
import { OnInit, Component, Input, EventEmitter } from "@angular/core"; import { Pokemon } from "./pokemon.model"; import { ExternalImageURLPipe } from "./../pipes/external-image-url.pipe"; import { PokeCatalogService } from "./poke-catalog.service"; @Component({ selector: "poke-catalog", pipes: [ExternalImageURLP...
() { this.pokemonList = this.originalPokemonList.filter((pokemon, index)=> { // If the value to search is a substring of the pokemon name; then the pokemonList will have the current pokemon return pokemon.name.includes(this.searchValue); }); } public ngOnInit() { this._pokeCatalogService.ge...
filterPokemon
identifier_name
poke-catalog.component.ts
import { OnInit, Component, Input, EventEmitter } from "@angular/core"; import { Pokemon } from "./pokemon.model"; import { ExternalImageURLPipe } from "./../pipes/external-image-url.pipe"; import { PokeCatalogService } from "./poke-catalog.service"; @Component({ selector: "poke-catalog", pipes: [ExternalImageURLP...
public ngOnInit() { this._pokeCatalogService.getPokemonList().then((pokemonList: Pokemon[]) => { this.pokemonList = pokemonList; this.originalPokemonList = pokemonList; }); } }
{ this.pokemonList = this.originalPokemonList.filter((pokemon, index)=> { // If the value to search is a substring of the pokemon name; then the pokemonList will have the current pokemon return pokemon.name.includes(this.searchValue); }); }
identifier_body
poke-catalog.component.ts
import { OnInit, Component, Input, EventEmitter } from "@angular/core"; import { Pokemon } from "./pokemon.model"; import { ExternalImageURLPipe } from "./../pipes/external-image-url.pipe"; import { PokeCatalogService } from "./poke-catalog.service"; @Component({ selector: "poke-catalog",
styleUrls: ["app/poke-catalog/poke-catalog.component.css"] }) export class PokeCatalogComponent implements OnInit { originalPokemonList: Array<Pokemon> = []; pokemonList: Array<Pokemon> = []; searchValue: string = ""; @Input() set searchValueInput(value: string) { this.searchValue = value; this.filte...
pipes: [ExternalImageURLPipe], providers: [PokeCatalogService], templateUrl: "app/poke-catalog/poke-catalog.component.html",
random_line_split
log.rs
// This Source Code Form is subject to the terms of // the Mozilla Public License, v. 2.0. If a copy of // the MPL was not distributed with this file, You // can obtain one at http://mozilla.org/MPL/2.0/. use std::error::Error; pub fn error(e: &Error) { target::error(e) }
// ANDROID ////////////////////////////////////////////////////////////////// #[cfg(target_os = "android")] mod target { use libc::*; use std::error::Error; use std::ffi::*; const TAG: &'static [u8] = b"CryptoBox"; const LEVEL_ERROR: c_int = 6; pub fn error(e: &Error) { log(&format!("...
random_line_split
log.rs
// This Source Code Form is subject to the terms of // the Mozilla Public License, v. 2.0. If a copy of // the MPL was not distributed with this file, You // can obtain one at http://mozilla.org/MPL/2.0/. use std::error::Error; pub fn error(e: &Error) { target::error(e) } // ANDROID /////////////////////////////...
(e: &Error) { log(&format!("{}", e), LEVEL_ERROR) } fn log(msg: &str, lvl: c_int) { let tag = CString::new(TAG).unwrap(); let msg = CString::new(msg.as_bytes()).unwrap_or(CString::new("<malformed log message>").unwrap()); unsafe { __android_log_write(lvl, tag.as_ptr(...
error
identifier_name
log.rs
// This Source Code Form is subject to the terms of // the Mozilla Public License, v. 2.0. If a copy of // the MPL was not distributed with this file, You // can obtain one at http://mozilla.org/MPL/2.0/. use std::error::Error; pub fn error(e: &Error) { target::error(e) } // ANDROID /////////////////////////////...
}
{ writeln!(&mut stderr(), "ERROR: {}", e).unwrap(); }
identifier_body
main.py
import json import random import requests from plugin import create_plugin from message import SteelyMessage HELP_STR = """ Request your favourite bible quotes, right to the chat. Usage: /bible - Random quote /bible Genesis 1:3 - Specific verse /bible help - This help text Verses are specified in th...
(bot, message: SteelyMessage, **kwargs): bot.sendMessage( HELP_STR, thread_id=message.thread_id, thread_type=message.thread_type) def is_valid_quote(book, chapter, verse): return (0 <= book < len(bible) and 0 <= chapter < len(bible[book]['chapters']) and 0 <= ve...
help_command
identifier_name
main.py
import json import random import requests from plugin import create_plugin from message import SteelyMessage HELP_STR = """ Request your favourite bible quotes, right to the chat. Usage: /bible - Random quote /bible Genesis 1:3 - Specific verse /bible help - This help text Verses are specified in th...
verse_i = int(verse) - 1 if not is_valid_quote(book_i, chapter_i, verse_i): return "Verse or chapter out of range" return get_quote(book_i, chapter_i, verse_i) @plugin.listen(command='bible [book] [passage]') def passage_command(bot, message: SteelyMessage, **kwargs): if 'passage' not in kwar...
return "Passage must be an int"
conditional_block
main.py
import json import random import requests from plugin import create_plugin from message import SteelyMessage HELP_STR = """ Request your favourite bible quotes, right to the chat. Usage: /bible - Random quote /bible Genesis 1:3 - Specific verse /bible help - This help text Verses are specified in th...
return "{}\n - {} {}:{}".format( bible[book]["chapters"][chapter][verse], bible[book]["name"], chapter + 1, verse + 1) def get_quote_from_ref(book_name, ref): if book_name.lower() not in book_to_index: return "Could not find book name: " + book_name book_i = book_to_index[b...
random_line_split
main.py
import json import random import requests from plugin import create_plugin from message import SteelyMessage HELP_STR = """ Request your favourite bible quotes, right to the chat. Usage: /bible - Random quote /bible Genesis 1:3 - Specific verse /bible help - This help text Verses are specified in th...
def get_quote(book, chapter, verse): return "{}\n - {} {}:{}".format( bible[book]["chapters"][chapter][verse], bible[book]["name"], chapter + 1, verse + 1) def get_quote_from_ref(book_name, ref): if book_name.lower() not in book_to_index: return "Could not find book name: " ...
return (0 <= book < len(bible) and 0 <= chapter < len(bible[book]['chapters']) and 0 <= verse < len(bible[book]['chapters'][chapter]))
identifier_body
CompareVersionsDialog.tsx
/* eslint-disable i18next/no-literal-string */ import {css, cx} from "@emotion/css" import {WindowContentProps} from "@touk/window-manager" import _ from "lodash" import React from "react" import {connect} from "react-redux" import {formatAbsolutely} from "../../common/DateUtils" import * as JsonUtils from "../../commo...
} isRemote(versionId: string) { return versionId.startsWith(this.remotePrefix) } versionToPass(versionId: string) { return versionId.replace(this.remotePrefix, "") } versionDisplayString(versionId: string) { return this.isRemote(versionId) ? `${this.versionToPass(versionId)} on ${this.props...
{ this.setState(this.initState) }
conditional_block
CompareVersionsDialog.tsx
/* eslint-disable i18next/no-literal-string */ import {css, cx} from "@emotion/css" import {WindowContentProps} from "@touk/window-manager" import _ from "lodash" import React from "react" import {connect} from "react-redux" import {formatAbsolutely} from "../../common/DateUtils" import * as JsonUtils from "../../commo...
<div className="versionHeader">Version {this.versionDisplayString(this.state.otherVersion)}</div> {printElement(otherElement, [])} </div> </div> ) } differentPathsForObjects(currentNode, otherNode) { const diffObject = JsonUtils.objectDiff(currentNode, otherNode) const...
<div className="versionHeader">Current version</div> {printElement(currentElement, differentPaths)} </div> <div>
random_line_split
CompareVersionsDialog.tsx
/* eslint-disable i18next/no-literal-string */ import {css, cx} from "@emotion/css" import {WindowContentProps} from "@touk/window-manager" import _ from "lodash" import React from "react" import {connect} from "react-redux" import {formatAbsolutely} from "../../common/DateUtils" import * as JsonUtils from "../../commo...
( <div> <div className="esp-form-row"> <p>Difference to pick</p> <SelectWithFocus id="otherVersion" className="node-input" value={this.state.currentDiffId || ""} ...
{ return ( <> <div className="esp-form-row"> <p>Version to compare</p> <SelectWithFocus autoFocus={true} id="otherVersion" className="node-input" value={this.state.otherVersion || ""} onChange={(e) => this.loadVersion(e.ta...
identifier_body
CompareVersionsDialog.tsx
/* eslint-disable i18next/no-literal-string */ import {css, cx} from "@emotion/css" import {WindowContentProps} from "@touk/window-manager" import _ from "lodash" import React from "react" import {connect} from "react-redux" import {formatAbsolutely} from "../../common/DateUtils" import * as JsonUtils from "../../commo...
(version: ProcessVersionType, versionPrefix = "") { const versionId = versionPrefix + version.processVersionId return ( <option key={versionId} value={versionId}> {this.versionDisplayString(versionId)} - created by {version.user} &nbsp; {formatAbsolutely(version.createDate)}</option> ) } ...
createVersionElement
identifier_name
p3starscreen.py
#!/usr/bin/env python import os import sys import argparse import pat3dem.star as p3s def main():
for i in args_def: if args.__dict__[i] == None: args.__dict__[i] = args_def[i] # preprocess -sf if args.sfile != '0': lines_sf = open(args.sfile).readlines() lines_sfile = [] for line in lines_sf: line = line.strip() if line != '': lines_sfile += [line] # get the star file star = args.star[0] ...
progname = os.path.basename(sys.argv[0]) usage = progname + """ [options] <a star file> Write two star files after screening by an item and a cutoff in the star file. Write one star file after screening by a file containing blacklist/whitelist (either keyword or item). """ args_def = {'screen':'0', 'cutoff':'00'...
identifier_body
p3starscreen.py
#!/usr/bin/env python import os import sys import argparse import pat3dem.star as p3s def
(): progname = os.path.basename(sys.argv[0]) usage = progname + """ [options] <a star file> Write two star files after screening by an item and a cutoff in the star file. Write one star file after screening by a file containing blacklist/whitelist (either keyword or item). """ args_def = {'screen':'0', 'cutoff'...
main
identifier_name
p3starscreen.py
#!/usr/bin/env python import os import sys import argparse import pat3dem.star as p3s def main(): progname = os.path.basename(sys.argv[0]) usage = progname + """ [options] <a star file> Write two star files after screening by an item and a cutoff in the star file. Write one star file after screening by a file con...
write_screen.write(' \n') elif args.sfile != '0': with open('{}_screened.star'.format(basename), 'w') as write_screen: write_screen.write(''.join(header)) if args.white == 0: for line in lines: skip = 0 for key in lines_sfile: if key in line: skip = 1 print 'Skip {}.'.for...
print 'Include {}.'.format(key) write_screen.write(line)
conditional_block
p3starscreen.py
#!/usr/bin/env python import os import sys import argparse import pat3dem.star as p3s def main(): progname = os.path.basename(sys.argv[0]) usage = progname + """ [options] <a star file> Write two star files after screening by an item and a cutoff in the star file. Write one star file after screening by a file con...
if args.white == 0: for line in lines: skip = 0 for key in lines_sfile: if key in line: skip = 1 print 'Skip {}.'.format(key) break if skip == 0: write_screen.write(line) else: for line in lines: for key in lines_sfile: if key in line: prin...
elif args.sfile != '0': with open('{}_screened.star'.format(basename), 'w') as write_screen: write_screen.write(''.join(header))
random_line_split
mod.rs
pub use self::mouse_joint::{MouseJointConfig, MouseJoint}; use std::rc::{Rc, Weak}; use std::cell::RefCell; use std::mem; use std::ptr; use super::{Body, BodyHandleWeak}; use super::island::{Position, Velocity}; use ::dynamics::world::TimeStep; mod mouse_joint; pub type JointHandle<'a> = Rc<RefCell<Joint<'a>>>; pub ...
self.get_joint_data_mut().is_island = is_island; } pub fn is_island(&self) -> bool { self.get_joint_data().is_island } pub fn initialize_velocity_constraints(&mut self, step: TimeStep, positions: &Vec<Position>, velocities: &mut Vec<Velocity>) { match self { &mut Jo...
pub fn set_island(&mut self, is_island: bool) {
random_line_split
mod.rs
pub use self::mouse_joint::{MouseJointConfig, MouseJoint}; use std::rc::{Rc, Weak}; use std::cell::RefCell; use std::mem; use std::ptr; use super::{Body, BodyHandleWeak}; use super::island::{Position, Velocity}; use ::dynamics::world::TimeStep; mod mouse_joint; pub type JointHandle<'a> = Rc<RefCell<Joint<'a>>>; pub ...
(&self) -> bool { self.get_joint_data().is_island } pub fn initialize_velocity_constraints(&mut self, step: TimeStep, positions: &Vec<Position>, velocities: &mut Vec<Velocity>) { match self { &mut Joint::Mouse(ref mut joint) => joint.initialize_velocity_constraints(step, positions, ...
is_island
identifier_name
lib.rs
HashSet, sync::Arc}; use subscription_service::ReconfigSubscription; pub mod builder; /// Histogram of idle time of spent in event processing loop pub static EVENT_PROCESSING_LOOP_IDLE_DURATION_S: Lazy<DurationHistogram> = Lazy::new(|| { DurationHistogram::new( register_histogram!( "simple_onc...
self.process_payload(payload).await; } warn!( NetworkSchema::new(&self.network_context), "{} OnChain Discovery actor terminated", self.network_context, ); } } #[cfg(test)] mod tests { use super::*; use diem_config::config::HANDSHAKE_VERSION; ...
while let Some(payload) = self.next_reconfig_event().await {
random_line_split
lib.rs
(), vec![]) } /// Extracts a set of ConnectivityRequests from a ValidatorSet which are appropriate for a network with type role. fn extract_updates( network_context: Arc<NetworkContext>, encryptor: &Encryptor, node_set: ValidatorSet, ) -> Vec<ConnectivityRequest> { let is_validator = network_context.ne...
test_pubkey
identifier_name
lib.rs
HashSet, sync::Arc}; use subscription_service::ReconfigSubscription; pub mod builder; /// Histogram of idle time of spent in event processing loop pub static EVENT_PROCESSING_LOOP_IDLE_DURATION_S: Lazy<DurationHistogram> = Lazy::new(|| { DurationHistogram::new( register_histogram!( "simple_onc...
]) .set(mismatch); } /// Processes a received OnChainConfigPayload. Depending on role (Validator or FullNode), parses /// the appropriate configuration changes and passes it to the ConnectionManager channel. async fn process_payload(&mut self, payload: OnChainConfigPayload) { ...
{ let mismatch = onchain_keys.map_or(0, |pubkeys| { if !pubkeys.contains(&self.expected_pubkey) { error!( NetworkSchema::new(&self.network_context), "Onchain pubkey {:?} differs from local pubkey {}", pubkeys, ...
identifier_body
lib.rs
HashSet, sync::Arc}; use subscription_service::ReconfigSubscription; pub mod builder; /// Histogram of idle time of spent in event processing loop pub static EVENT_PROCESSING_LOOP_IDLE_DURATION_S: Lazy<DurationHistogram> = Lazy::new(|| { DurationHistogram::new( register_histogram!( "simple_onc...
else { PeerRole::ValidatorFullNode }; (peer_id, Peer::from_addrs(peer_role, addrs)) }) .collect(); vec![ConnectivityRequest::UpdateDiscoveredPeers( DiscoverySource::OnChain, discovered_peers, )] } impl ConfigurationChangeListener { /...
{ PeerRole::Validator }
conditional_block
gcal.js
/*! * FullCalendar v1.6.1 Google Calendar Plugin * Docs & License: http://arshaw.com/fullcalendar/ * (c) 2013 Adam Shaw */ (function($) { var fc = $.fullCalendar; var formatDate = fc.formatDate; var parseISO8601 = fc.parseISO8601; var addDays = fc.addDays; var applyAll = fc.applyAll; fc.source...
(sourceOptions, start, end) { var success = sourceOptions.success; var data = $.extend({}, sourceOptions.data || {}, { 'start-min': formatDate(start, 'u'), 'start-max': formatDate(end, 'u'), 'singleevents': true, 'max-results': 9999 }); var ctz = sourceOptions.currentTimezone; if (ctz) { d...
transformOptions
identifier_name
gcal.js
/*! * FullCalendar v1.6.1 Google Calendar Plugin * Docs & License: http://arshaw.com/fullcalendar/ * (c) 2013 Adam Shaw */ (function($) { var fc = $.fullCalendar; var formatDate = fc.formatDate; var parseISO8601 = fc.parseISO8601; var addDays = fc.addDays; var applyAll = fc.applyAll; fc.source...
sourceOptions.editable = false; } } }); fc.sourceFetchers.push(function(sourceOptions, start, end) { if (sourceOptions.dataType == 'gcal') { return transformOptions(sourceOptions, start, end); } }); function transformOptions(sourceOptions, start, end) { var success = sourceOptions.succ...
sourceOptions.dataType = 'gcal'; if (sourceOptions.editable === undefined) {
random_line_split
gcal.js
/*! * FullCalendar v1.6.1 Google Calendar Plugin * Docs & License: http://arshaw.com/fullcalendar/ * (c) 2013 Adam Shaw */ (function($) { var fc = $.fullCalendar; var formatDate = fc.formatDate; var parseISO8601 = fc.parseISO8601; var addDays = fc.addDays; var applyAll = fc.applyAll; fc.source...
endParam: false, success: function(data) { var events = []; if (data.feed.entry) { $.each(data.feed.entry, function(i, entry) { var startStr = entry['gd$when'][0]['startTime']; var start = parseISO8601(startStr, true); var end = parseISO8601(entry['gd$when'][0]['endTime'], true); ...
{ var success = sourceOptions.success; var data = $.extend({}, sourceOptions.data || {}, { 'start-min': formatDate(start, 'u'), 'start-max': formatDate(end, 'u'), 'singleevents': true, 'max-results': 9999 }); var ctz = sourceOptions.currentTimezone; if (ctz) { data.ctz = ctz = ctz.replace(...
identifier_body
gcal.js
/*! * FullCalendar v1.6.1 Google Calendar Plugin * Docs & License: http://arshaw.com/fullcalendar/ * (c) 2013 Adam Shaw */ (function($) { var fc = $.fullCalendar; var formatDate = fc.formatDate; var parseISO8601 = fc.parseISO8601; var addDays = fc.addDays; var applyAll = fc.applyAll; fc.source...
return events; } }); } // legacy fc.gcalFeed = function(url, sourceOptions) { return $.extend({}, sourceOptions, { url: url, dataType: 'gcal' }); }; })(jQuery);
{ return res; }
conditional_block
ext.py
import json import logging from foxglove import glove from httpx import Response from .settings import Settings logger = logging.getLogger('ext') def lenient_json(v): if isinstance(v, (str, bytes)): try: return json.loads(v) except (ValueError, TypeError): pass return...
r = await glove.http.request(method, url, json=data or None, **kwargs) if isinstance(allowed_statuses, int): allowed_statuses = (allowed_statuses,) if allowed_statuses != '*' and r.status_code not in allowed_statuses: data = { 'request_real_url': str(r.re...
kwargs['timeout'] = timeout
conditional_block
ext.py
import json import logging from foxglove import glove from httpx import Response from .settings import Settings
logger = logging.getLogger('ext') def lenient_json(v): if isinstance(v, (str, bytes)): try: return json.loads(v) except (ValueError, TypeError): pass return v class ApiError(RuntimeError): def __init__(self, method, url, status, response_text): self.method...
random_line_split
ext.py
import json import logging from foxglove import glove from httpx import Response from .settings import Settings logger = logging.getLogger('ext') def lenient_json(v): if isinstance(v, (str, bytes)): try: return json.loads(v) except (ValueError, TypeError): pass return...
: def __init__(self, root_url, settings: Settings): self.settings = settings self.root = root_url.rstrip('/') + '/' async def get(self, uri, *, allowed_statuses=(200,), **data) -> Response: return await self._request('GET', uri, allowed_statuses=allowed_statuses, **data) async def ...
ApiSession
identifier_name
ext.py
import json import logging from foxglove import glove from httpx import Response from .settings import Settings logger = logging.getLogger('ext') def lenient_json(v): if isinstance(v, (str, bytes)): try: return json.loads(v) except (ValueError, TypeError): pass return...
async def post(self, uri, *, allowed_statuses=(200, 201), **data) -> Response: return await self._request('POST', uri, allowed_statuses=allowed_statuses, **data) async def put(self, uri, *, allowed_statuses=(200, 201), **data) -> Response: return await self._request('PUT', uri, allowed_status...
return await self._request('DELETE', uri, allowed_statuses=allowed_statuses, **data)
identifier_body
main.rs
use std::io::BufReader; use std::fs::File; use std::str::FromStr; use std::io; use std::io::prelude::*; use std::collections::HashSet; use std::cmp::Reverse; fn has_distinct_pair(set:&HashSet<i64>, sum: i64) -> bool { for k in set.iter() { let v = sum - k; if *k != v && set.contains(&v) { ...
{ for arg in std::env::args().skip(1) { let value = print_medians(&arg).expect("failed to read"); println!("answer = {}", value); } }
identifier_body
main.rs
use std::io::BufReader; use std::fs::File; use std::str::FromStr; use std::io; use std::io::prelude::*; use std::collections::HashSet; use std::cmp::Reverse; fn has_distinct_pair(set:&HashSet<i64>, sum: i64) -> bool { for k in set.iter() { let v = sum - k; if *k != v && set.contains(&v) { ...
} Ok(result) } fn main() { for arg in std::env::args().skip(1) { let value = print_medians(&arg).expect("failed to read"); println!("answer = {}", value); } }
{ result = result + 1; }
conditional_block
main.rs
use std::io::BufReader; use std::fs::File; use std::str::FromStr; use std::io; use std::io::prelude::*; use std::collections::HashSet; use std::cmp::Reverse; fn has_distinct_pair(set:&HashSet<i64>, sum: i64) -> bool { for k in set.iter() { let v = sum - k; if *k != v && set.contains(&v) { ...
let mut result = 0; for s in -10000..10001 { if has_distinct_pair(&set, s) { result = result + 1; } } Ok(result) } fn main() { for arg in std::env::args().skip(1) { let value = print_medians(&arg).expect("failed to read"); println!("answer = {}", value);...
random_line_split
main.rs
use std::io::BufReader; use std::fs::File; use std::str::FromStr; use std::io; use std::io::prelude::*; use std::collections::HashSet; use std::cmp::Reverse; fn
(set:&HashSet<i64>, sum: i64) -> bool { for k in set.iter() { let v = sum - k; if *k != v && set.contains(&v) { return true; } } false } fn print_medians(file_name: &str) -> io::Result<u64> { let f = File::open(file_name)?; let reader = BufReader::new(f); ...
has_distinct_pair
identifier_name
index.js
'use strict'; const basicAuth = require('basic-auth'); function unauthorized(res, realm) { const _realm = realm || 'Authorization Required'; res.set('WWW-Authenticate', `Basic realm=${_realm}`); return res.sendStatus(401); }; function isPromiseLike(obj)
function isValidUser(user, username, password) { return !(!user || user.name !== username || user.pass !== password); } function createMiddleware(username, password, realm) { const _realm = typeof username === 'function' ? password : realm; return function basicAuthMiddleware(req, res, next) { con...
{ return obj && typeof obj.then === 'function'; }
identifier_body
index.js
'use strict'; const basicAuth = require('basic-auth'); function unauthorized(res, realm) { const _realm = realm || 'Authorization Required'; res.set('WWW-Authenticate', `Basic realm=${_realm}`); return res.sendStatus(401); }; function isPromiseLike(obj) { return obj && typeof obj.then === 'function'; } fun...
} let authorized = null; if (typeof username === 'function') { const checkFn = username; try { authorized = checkFn(user.name, user.pass, function checkFnCallback(err, authentified) { if (err) { return next(err); } if (authentified) { ...
return function basicAuthMiddleware(req, res, next) { const user = basicAuth(req); if (!user) { return unauthorized(res, realm);
random_line_split
index.js
'use strict'; const basicAuth = require('basic-auth'); function unauthorized(res, realm) { const _realm = realm || 'Authorization Required'; res.set('WWW-Authenticate', `Basic realm=${_realm}`); return res.sendStatus(401); }; function
(obj) { return obj && typeof obj.then === 'function'; } function isValidUser(user, username, password) { return !(!user || user.name !== username || user.pass !== password); } function createMiddleware(username, password, realm) { const _realm = typeof username === 'function' ? password : realm; retu...
isPromiseLike
identifier_name
index.js
'use strict'; const basicAuth = require('basic-auth'); function unauthorized(res, realm) { const _realm = realm || 'Authorization Required'; res.set('WWW-Authenticate', `Basic realm=${_realm}`); return res.sendStatus(401); }; function isPromiseLike(obj) { return obj && typeof obj.then === 'function'; } fun...
else { authorized = isValidUser(user, username, password); } if (isPromiseLike(authorized)) { return authorized .then(function(authorized) { if (authorized === true) { return next(); } return unauthorized(res, _realm); }) .catch(ne...
{ authorized = username.some(([username, password]) => isValidUser(user, username, password)); }
conditional_block
gtkshortcutgen.py
#!/usr/bin/python3 # vim:fileencoding=utf-8:sw=4:et """ GtkShortcutsWindow helper for generating GtkBuilder XML file. ``` shortcuts1 = [ shortcut_entry("Quit", gesture="gesture-two-finger-swipe-left"), ] shortcuts2 = [ shortcut_entry("Import channels from file", "<ctrl>o"), shortcu...
set_stdio_encoding() log_level = log.INFO log.basicConfig(format="%(levelname)s>> %(message)s", level=log_level) shortcuts1 = [ shortcut_entry("Quit", gesture="gesture-two-finger-swipe-left"), ] shortcuts2 = [ shortcut_entry("Import channels from file", "<ctrl>o"), sh...
import codecs; stdio = ["stdin", "stdout", "stderr"] for x in stdio: obj = getattr(sys, x) if not obj.encoding: setattr(sys, x, codecs.getwriter(enc)(obj))
identifier_body
gtkshortcutgen.py
#!/usr/bin/python3 # vim:fileencoding=utf-8:sw=4:et """ GtkShortcutsWindow helper for generating GtkBuilder XML file. ``` shortcuts1 = [ shortcut_entry("Quit", gesture="gesture-two-finger-swipe-left"), ] shortcuts2 = [ shortcut_entry("Import channels from file", "<ctrl>o"), shortcu...
(base_entry): def objnode(adict): prefix = "GtkShortcuts" if not adict["klass"].startswith(prefix): adict["klass"] = prefix + adict["klass"] if "attrib" not in adict: adict["attrib"]= {} aobj = etree.Element ("object", attrib=adict["attrib"]) aobj.attr...
create_object_tree
identifier_name
gtkshortcutgen.py
#!/usr/bin/python3 # vim:fileencoding=utf-8:sw=4:et """ GtkShortcutsWindow helper for generating GtkBuilder XML file. ``` shortcuts1 = [ shortcut_entry("Quit", gesture="gesture-two-finger-swipe-left"), ] shortcuts2 = [ shortcut_entry("Import channels from file", "<ctrl>o"), shortcu...
entry = { "klass": "Section", "properties": { "visible": 1, "section-name": name, }, "childs": groups, } entry["properties"].update(kwargs) return entry def shortcut_window_entry(id_, sections, **kwargs): en...
return entry def section_entry(name, groups, **kwargs):
random_line_split
gtkshortcutgen.py
#!/usr/bin/python3 # vim:fileencoding=utf-8:sw=4:et """ GtkShortcutsWindow helper for generating GtkBuilder XML file. ``` shortcuts1 = [ shortcut_entry("Quit", gesture="gesture-two-finger-swipe-left"), ] shortcuts2 = [ shortcut_entry("Import channels from file", "<ctrl>o"), shortcu...
if "attrib" not in adict: adict["attrib"]= {} aobj = etree.Element ("object", attrib=adict["attrib"]) aobj.attrib["class"] = adict["klass"] return aobj def propnode(name, value): aobj = etree.Element ("property", attrib={"name": name}) if name == "title"...
adict["klass"] = prefix + adict["klass"]
conditional_block
form_builder_spec.ts
/** * @license * Copyright Google Inc. 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 {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_intern...
expect(g.controls['password'].value).toEqual('some value'); expect(g.controls['password'].validator).toEqual(syncValidator); expect(g.controls['password'].asyncValidator).toEqual(asyncValidator); }); it('should use controls', () => { var g = b.group({'login': b.control('some value', syn...
{ function syncValidator(_: any /** TODO #9100 */): any /** TODO #9100 */ { return null; } function asyncValidator(_: any /** TODO #9100 */) { return PromiseWrapper.resolve(null); } describe('Form Builder', () => { var b: any /** TODO #9100 */; beforeEach(() => { b = new FormBuilder(); }); it('shou...
identifier_body
form_builder_spec.ts
/** * @license * Copyright Google Inc. 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 {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_intern...
(_: any /** TODO #9100 */) { return PromiseWrapper.resolve(null); } describe('Form Builder', () => { var b: any /** TODO #9100 */; beforeEach(() => { b = new FormBuilder(); }); it('should create controls from a value', () => { var g = b.group({'login': 'some value'}); expect(g.controls['lo...
asyncValidator
identifier_name
form_builder_spec.ts
/** * @license * Copyright Google Inc. 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 {afterEach, beforeEach, ddescribe, describe, expect, iit, it, xit} from '@angular/core/testing/testing_intern...
var b: any /** TODO #9100 */; beforeEach(() => { b = new FormBuilder(); }); it('should create controls from a value', () => { var g = b.group({'login': 'some value'}); expect(g.controls['login'].value).toEqual('some value'); }); it('should create controls from an array', () => { ...
function syncValidator(_: any /** TODO #9100 */): any /** TODO #9100 */ { return null; } function asyncValidator(_: any /** TODO #9100 */) { return PromiseWrapper.resolve(null); } describe('Form Builder', () => {
random_line_split
test_dolfin_linear_solver.py
# Copyright (C) 2015-2022 by the RBniCS authors # # This file is part of RBniCS. # # SPDX-License-Identifier: LGPL-3.0-or-later import pytest from numpy import isclose from dolfin import (assemble, dx, Function, FunctionSpace, grad, inner, solve, TestFunction, TrialFunction, UnitSquareMesh) from rb...
print("Testing " + test_type + " backend" + ", callback_type = " + callback_type) global LinearSolver LinearSolver = AllLinearSolver[test_type] benchmark(data.evaluate_backend, setup=data.generate_random, teardown=data.assert_backend)
conditional_block
test_dolfin_linear_solver.py
# Copyright (C) 2015-2022 by the RBniCS authors # # This file is part of RBniCS. # # SPDX-License-Identifier: LGPL-3.0-or-later import pytest from numpy import isclose from dolfin import (assemble, dx, Function, FunctionSpace, grad, inner, solve, TestFunction, TrialFunction, UnitSquareMesh) from rb...
(arg): return arg elif callback_type == "tensor callbacks": def callback(arg): return assemble(arg) self.callback_type = callback_type self.callback = callback def generate_random(self): # Generate random rhs g = RandomDolfinFuncti...
callback
identifier_name
test_dolfin_linear_solver.py
# Copyright (C) 2015-2022 by the RBniCS authors # # This file is part of RBniCS. # # SPDX-License-Identifier: LGPL-3.0-or-later import pytest from numpy import isclose from dolfin import (assemble, dx, Function, FunctionSpace, grad, inner, solve, TestFunction, TrialFunction, UnitSquareMesh) from rb...
def assert_backend(self, a, f, result_backend): result_builtin = self.evaluate_builtin(a, f) error = Function(self.V) error.vector().add_local(+ result_backend.vector().get_local()) error.vector().add_local(- result_builtin.vector().get_local()) error.vector().apply("add") ...
a = self.callback(a) f = self.callback(f) result_backend = Function(self.V) solver = LinearSolver(a, result_backend, f) solver.set_parameters({ "linear_solver": "mumps" }) solver.solve() return result_backend
identifier_body
test_dolfin_linear_solver.py
# Copyright (C) 2015-2022 by the RBniCS authors
# SPDX-License-Identifier: LGPL-3.0-or-later import pytest from numpy import isclose from dolfin import (assemble, dx, Function, FunctionSpace, grad, inner, solve, TestFunction, TrialFunction, UnitSquareMesh) from rbnics.backends import LinearSolver as FactoryLinearSolver from rbnics.backends.dolfi...
# # This file is part of RBniCS. #
random_line_split
ToolRegistry.ts
/** * Copyright © 2021 Rémi Pace. * This file is part of Abc-Map. * * Abc-Map is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later vers...
: AbstractTool[] { const history = getServices().history; const modals = getServices().modals; return [ new NoneTool(mainStore, history), new PointTool(mainStore, history), new LineStringTool(mainStore, history), new PolygonTool(mainStore, history), new TextTool(mainStore, hist...
tAll()
identifier_name
ToolRegistry.ts
/** * Copyright © 2021 Rémi Pace. * This file is part of Abc-Map. * * Abc-Map is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later vers...
return result; } }
throw new Error(`Tool not found: ${id}`); }
conditional_block
ToolRegistry.ts
/** * Copyright © 2021 Rémi Pace. * This file is part of Abc-Map. * * Abc-Map is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as
* the License, or (at your option) any later version. * * Abc-Map is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You shou...
* published by the Free Software Foundation, either version 3 of
random_line_split
20160112212733-create-workout.js
/* jshint node: true */ /* jshint esversion: 6 */ 'use strict'; module.exports = {
allowNull: false, autoIncrement: true, primaryKey: true, type: Sequelize.INTEGER }, workout_date: { type: Sequelize.DATEONLY }, UserId: { allowNull: false, references: { model: 'Users', key: 'id' }, type:...
up: function(queryInterface, Sequelize) { return queryInterface.createTable('Workouts', { id: {
random_line_split
get_event_authorization.rs
//! `GET /_matrix/federation/*/event_auth/{roomId}/{eventId}` //! //! Endpoint to retrieve the complete auth chain for a given event. pub mod v1 { //! `/v1/` ([spec]) //! //! [spec]: https://spec.matrix.org/v1.2/server-server-api/#get_matrixfederationv1event_authroomideventid use ruma_common::{api::ru...
} }
{ Self { auth_chain } }
identifier_body
get_event_authorization.rs
//! `GET /_matrix/federation/*/event_auth/{roomId}/{eventId}` //! //! Endpoint to retrieve the complete auth chain for a given event. pub mod v1 { //! `/v1/` ([spec]) //! //! [spec]: https://spec.matrix.org/v1.2/server-server-api/#get_matrixfederationv1event_authroomideventid use ruma_common::{api::ru...
(auth_chain: Vec<Box<RawJsonValue>>) -> Self { Self { auth_chain } } } }
new
identifier_name
mod.rs
// Copyright 2017 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
CallTag::Batch(prom) => prom.resolve(success), CallTag::Request(cb) => cb.resolve(cq, success), CallTag::UnaryRequest(cb) => cb.resolve(cq, success), CallTag::Abort(_) => {} CallTag::Shutdown(prom) => prom.resolve(success), CallTag::Spawn(notify) =...
} /// Resolve the CallTag with given status. pub fn resolve(self, cq: &CompletionQueue, success: bool) { match self {
random_line_split
mod.rs
// Copyright 2017 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
(&mut self) -> Poll<T, Error> { let mut guard = self.inner.lock(); if guard.stale { panic!("Resolved future is not supposed to be polled again."); } if let Some(res) = guard.result.take() { guard.stale = true; return Ok(Async::Ready(res?)); } ...
poll
identifier_name
mod.rs
// Copyright 2017 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to i...
} #[cfg(test)] mod tests { use std::sync::mpsc::*; use std::sync::*; use std::thread; use super::*; use crate::env::Environment; #[test] fn test_resolve() { let env = Environment::new(1); let (cq_f1, tag1) = CallTag::shutdown_pair(); let (cq_f2, tag2) = CallTag::...
{ match *self { CallTag::Batch(ref ctx) => write!(f, "CallTag::Batch({:?})", ctx), CallTag::Request(_) => write!(f, "CallTag::Request(..)"), CallTag::UnaryRequest(_) => write!(f, "CallTag::UnaryRequest(..)"), CallTag::Abort(_) => write!(f, "CallTag::Abort(..)"), ...
identifier_body
utm.py
80.0 * pi) def UTMCentralMeridian(zone): """Calculates the central meridian for the given UTM-zone.""" return deg_to_rad(-183.0 + (zone * 6.0)) def ArcLengthOfMeridian(phi):
# Precalculate delta delta = ((-35.0 * n**3.0 / 48.0) + (105.0 * n**5.0 / 256.0)) # Precalculate epsilon epsilon = (315.0 * n**4.0 / 512.0) # Now calculate the sum of the series and return result = (alpha * (phi + (beta * sin(2.0 * phi)) + (gamma * sin(4.0 * phi)) ...
"""Computes the ellipsoidal distance from the equator to a point at a given latitude. Reference: Hoffmann-Wellenhof, B., Lichtenegger, H., and Collins, J., GPS: Theory and Practice, 3rd ed. New York: Springer-Verlag Wien, 1994.""" # Precalculate n n = (sm_a - sm_b) / (sm_a + sm_b) ...
identifier_body
utm.py
(deg): """Converts degrees to radians.""" return (deg / 180.0 * pi) def UTMCentralMeridian(zone): """Calculates the central meridian for the given UTM-zone.""" return deg_to_rad(-183.0 + (zone * 6.0)) def ArcLengthOfMeridian(phi): """Computes the ellipsoidal distance from the equator to a point ...
deg_to_rad
identifier_name
utm.py
80.0 * pi) def UTMCentralMeridian(zone): """Calculates the central meridian for the given UTM-zone.""" return deg_to_rad(-183.0 + (zone * 6.0)) def ArcLengthOfMeridian(phi): """Computes the ellipsoidal distance from the equator to a point at a given latitude. Reference: Hoffmann-Wellenhof...
xy = [0, 0] MapLatLonToXY(deg_to_rad(lat), deg_to_rad(lon), UTMCentralMeridian(zone), xy) xy[0] = xy[0] * UTMScaleFactor + 500000.0 xy[1] = xy[1] * UTMScaleFactor if xy[1] < 0.0: xy[1] = xy[1] + 10000000.0 return [round(coord, 2) for coord in xy] def FootpointLatitude(y): ...
zone = long_to_zone(lon)
conditional_block
utm.py
180.0 * pi) def UTMCentralMeridian(zone): """Calculates the central meridian for the given UTM-zone.""" return deg_to_rad(-183.0 + (zone * 6.0)) def ArcLengthOfMeridian(phi): """Computes the ellipsoidal distance from the equator to a point at a given latitude. Reference: Hoffmann-Wellenho...
if zone is None: zone = long_to_zone(lon) xy = [0, 0] MapLatLonToXY(deg_to_rad(lat), deg_to_rad(lon), UTMCentralMeridian(zone), xy) xy[0] = xy[0] * UTMScaleFactor + 500000.0 xy[1] = xy[1] * UTMScaleFactor if xy[1] < 0.0: xy[1] = xy[1] + 10000000.0 return [rou...
def latlong_to_utm(lon, lat, zone = None): """Converts a latitude/longitude pair to x and y coordinates in the Universal Transverse Mercator projection."""
random_line_split
wechatService.py
# -*- coding:utf-8 -*- """ # Author: Pegasus Wang (pegasuswang@qq.com, http://ningning.today) # Created Time : Fri Feb 20 21:38:57 2015 # File Name: wechatService.py # Description: # :copyright: (c) 2015 by Pegasus Wang. # :license: MIT, see LICENSE for more details. """ import json import time import urllib import ...
(req_info): query = {'key': RobotService.KEY, 'info': req_info.encode('utf-8')} headers = {'Content-type': 'text/html', 'charset': 'utf-8'} data = urllib.urlencode(query) req = urllib2.Request(RobotService.url, data) f = urllib2.urlopen(req).read() return json.loads(f).ge...
auto_reply
identifier_name
wechatService.py
# -*- coding:utf-8 -*- """ # Author: Pegasus Wang (pegasuswang@qq.com, http://ningning.today) # Created Time : Fri Feb 20 21:38:57 2015 # File Name: wechatService.py # Description: # :copyright: (c) 2015 by Pegasus Wang. # :license: MIT, see LICENSE for more details. """ import json import time import urllib import ...
eventType = requestMap.get(u'Event') if eventType == MessageUtil.EVENT_TYPE_SUBSCRIBE: respContent = u'^_^谢谢您的关注,本公众号由王宁宁开发(python2.7+django1.4),如果你有兴趣继续开发,' \ u'可以联系我,就当打发时间了.' elif eventType == MessageUtil.EVENT_TYPE_UNSUBSCRIBE: ...
respContent = u'您发送的是地理位置消息!' elif msgType == MessageUtil.REQ_MESSAGE_TYPE_LINK: respContent = u'您发送的是链接消息!' elif msgType == MessageUtil.REQ_MESSAGE_TYPE_EVENT:
random_line_split
wechatService.py
# -*- coding:utf-8 -*- """ # Author: Pegasus Wang (pegasuswang@qq.com, http://ningning.today) # Created Time : Fri Feb 20 21:38:57 2015 # File Name: wechatService.py # Description: # :copyright: (c) 2015 by Pegasus Wang. # :license: MIT, see LICENSE for more details. """ import json import time import urllib import ...
if msgType == MessageUtil.REQ_MESSAGE_TYPE_TEXT: content = requestMap.get('Content').decode('utf-8') # note: decode first #respContent = u'您发送的是文本消息:' + content respContent = RobotService.auto_reply(content) elif msgType == MessageUtil.REQ_MESSAGE_TYPE_IMAGE: ...
"""process request""" @staticmethod def processRequest(request): """process different message types. :param request: post request message :return: None """ requestMap = MessageUtil.parseXml(request) fromUserName = requestMap.get(u'FromUserName') toUserNam...
identifier_body
wechatService.py
# -*- coding:utf-8 -*- """ # Author: Pegasus Wang (pegasuswang@qq.com, http://ningning.today) # Created Time : Fri Feb 20 21:38:57 2015 # File Name: wechatService.py # Description: # :copyright: (c) 2015 by Pegasus Wang. # :license: MIT, see LICENSE for more details. """ import json import time import urllib import ...
return respXml """ if msgType == 'text': content = requestMap.get('Content') # TODO elif msgType == 'image': picUrl = requestMap.get('PicUrl') # TODO elif msgType == 'voice': mediaId = requestMap.get('MediaId') ...
conditional_block
generate_playlist.py
""" Playlist Generation """ from os import path from random import choice import string import pafy from .. import content, g, playlists, screen, util, listview from ..playlist import Playlist from . import command, search, album_search @command(r'mkp\s*(.{1,100})') def generate_playlist(sourcefile): """Gene...
def description_generator(text): """ Fetches a videos description and parses it for <artist> - <track> combinations """ if not isinstance(g.model, Playlist): g.message = util.F("mkp desc unknown") return # Use only the first result, for now num = text.replace("--descripti...
"""Generates a random alphanumeric string of 6 characters""" n_chars = 6 return ''.join(choice(string.ascii_lowercase + string.digits) for _ in range(n_chars))
identifier_body
generate_playlist.py
""" Playlist Generation """ from os import path from random import choice import string import pafy from .. import content, g, playlists, screen, util, listview from ..playlist import Playlist from . import command, search, album_search @command(r'mkp\s*(.{1,100})') def generate_playlist(sourcefile): """Gene...
(filename): """Check if filename exists and has a non-zero size""" return path.isfile(filename) and path.getsize(filename) > 0 def create_playlist(queries, title=None): """Add a new playlist Create playlist with a random name, get the first match for each title in queries and append it to the pla...
check_sourcefile
identifier_name
generate_playlist.py
""" Playlist Generation """ from os import path from random import choice import string import pafy from .. import content, g, playlists, screen, util, listview from ..playlist import Playlist from . import command, search, album_search @command(r'mkp\s*(.{1,100})') def generate_playlist(sourcefile): """Gene...
else: plname=random_plname() if not g.userpl.get(plname): g.userpl[plname] = Playlist(plname) for query in queries: g.message = util.F('mkp finding') % query screen.update() qresult = find_best_match(query) if qresult: g.userpl[plname].songs.app...
plname=title.replace(" ", "-")
conditional_block
generate_playlist.py
""" Playlist Generation """ from os import path from random import choice import string import pafy from .. import content, g, playlists, screen, util, listview from ..playlist import Playlist from . import command, search, album_search @command(r'mkp\s*(.{1,100})') def generate_playlist(sourcefile): """Gene...
if not isinstance(g.model, Playlist): g.message = util.F("mkp desc unknown") return # Use only the first result, for now num = text.replace("--description", "") num = num.replace("-d", "") num = util.number_string_to_list(num)[0] query = {} query['id'] = g.model[num].ytid ...
<artist> - <track> combinations """
random_line_split
history.py
import collections import functools import re import wrappers class History(object): """ Tracking of operations provenance. >>> h = History("some_op") >>> print str(h) some_op() >>> h.add_args(["w1", "w2"]) >>> print str(h) some_op( w1, w2, ) >>> h.add_kws({"a...
string = "" if self.args: def arg_str(arg): if ( isinstance(arg, list) and arg and isinstance(arg[0], History) ): return '[\n ' + ",\n ".join( ...
self.op = str(operation) self.args = None self.kws = None def __str__(self):
random_line_split
history.py
import collections import functools import re import wrappers class History(object): """ Tracking of operations provenance. >>> h = History("some_op") >>> print str(h) some_op() >>> h.add_args(["w1", "w2"]) >>> print str(h) some_op( w1, w2, ) >>> h.add_kws({"a...
def __repr__(self): pat = re.compile(r'\s+') return pat.sub('', str(self)) def add_args(self, args): self.args = args def add_kws(self, kws): self.kws = kws def _gen_catch_history(wrps, list_of_histories): for wrp in wrps: if hasattr(wrp, "history"): ...
return self.op + "()"
conditional_block
history.py
import collections import functools import re import wrappers class History(object): """ Tracking of operations provenance. >>> h = History("some_op") >>> print str(h) some_op() >>> h.add_args(["w1", "w2"]) >>> print str(h) some_op( w1, w2, ) >>> h.add_kws({"a...
def __str__(self): string = "" if self.args: def arg_str(arg): if ( isinstance(arg, list) and arg and isinstance(arg[0], History) ): return '[\n ' + ",\n ".join...
self.op = str(operation) self.args = None self.kws = None
identifier_body
history.py
import collections import functools import re import wrappers class History(object): """ Tracking of operations provenance. >>> h = History("some_op") >>> print str(h) some_op() >>> h.add_args(["w1", "w2"]) >>> print str(h) some_op( w1, w2, ) >>> h.add_kws({"a...
(self, kws): self.kws = kws def _gen_catch_history(wrps, list_of_histories): for wrp in wrps: if hasattr(wrp, "history"): list_of_histories.append(wrp.history) yield wrp def track_history(func): """ Python decorator for Wrapper operations. >>> @track_history ...
add_kws
identifier_name
wall.rs
use glium; use types; use camera; use shaders; use texture; #[derive(Copy, Clone)] struct Vertex { position: [f32; 3], normal: [f32; 3], tex_coords: [f32; 2] } implement_vertex!(Vertex, position, normal, tex_coords); pub struct Wall { matrix: types::Mat, buffer: glium::VertexBuffer<Vertex>, d...
normal: [0.0, 0.0, -1.0], tex_coords: [1.0, 1.0] }, Vertex { position: [-1.0, -1.0, 0.0], normal: [0.0, 0.0, -1.0], tex_coords: [0.0, 0.0] }, Vertex { position: [ 1.0, -1.0, 0.0], normal: [0....
let buffer = glium::vertex::VertexBuffer::new(window, &[ Vertex { position: [-1.0, 1.0, 0.0], normal: [0.0, 0.0, -1.0], tex_coords: [0.0, 1.0] }, Vertex { position: [ 1.0, 1.0, 0.0],
random_line_split
wall.rs
use glium; use types; use camera; use shaders; use texture; #[derive(Copy, Clone)] struct
{ position: [f32; 3], normal: [f32; 3], tex_coords: [f32; 2] } implement_vertex!(Vertex, position, normal, tex_coords); pub struct Wall { matrix: types::Mat, buffer: glium::VertexBuffer<Vertex>, diffuse_texture: glium::texture::SrgbTexture2d, normal_map: glium::texture::texture2d::Texture...
Vertex
identifier_name
wall.rs
use glium; use types; use camera; use shaders; use texture; #[derive(Copy, Clone)] struct Vertex { position: [f32; 3], normal: [f32; 3], tex_coords: [f32; 2] } implement_vertex!(Vertex, position, normal, tex_coords); pub struct Wall { matrix: types::Mat, buffer: glium::VertexBuffer<Vertex>, d...
u_light: light, diffuse_tex: &self.diffuse_texture, normal_tex: &self.normal_map }; frame_buffer.draw(&self.buffer, &glium::index::NoIndices(strip), &library.lit_texture, &uniforms, &params).unwrap(); } }
{ use glium::Surface; use glium::DrawParameters; let strip = glium::index::PrimitiveType::TriangleStrip; let params = glium::DrawParameters { depth: glium::Depth { test: glium::draw_parameters::DepthTest::IfLess, write: true, ....
identifier_body
json_pipe_spec.ts
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, inject,} from '@angular/core/testing/testing_internal'; import {AsyncTestCompleter} from '@angular/core/testing/testing_internal'; import {TestComponentBuilder} from '@angular/compiler/testing'; import {Json, StringWrapper} from '../../src/facade...
beforeEach(() => { inceptionObj = {dream: {dream: {dream: 'Limbo'}}}; inceptionObjString = '{\n' + ' "dream": {\n' + ' "dream": {\n' + ' "dream": "Limbo"\n' + ' }\n' + ' }\n' + '}'; pipe = new JsonPipe(); }); des...
{ return StringWrapper.replace(obj, regNewLine, ''); }
identifier_body
json_pipe_spec.ts
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, inject,} from '@angular/core/testing/testing_internal'; import {AsyncTestCompleter} from '@angular/core/testing/testing_internal'; import {TestComponentBuilder} from '@angular/compiler/testing'; import {Json, StringWrapper} from '../../src/facade...
{ data: any; }
TestComp
identifier_name
json_pipe_spec.ts
import {ddescribe, describe, it, iit, xit, expect, beforeEach, afterEach, inject,} from '@angular/core/testing/testing_internal'; import {AsyncTestCompleter} from '@angular/core/testing/testing_internal'; import {TestComponentBuilder} from '@angular/compiler/testing'; import {Json, StringWrapper} from '../../src/facade...
describe('transform', () => { it('should return JSON-formatted string', () => { expect(pipe.transform(inceptionObj)).toEqual(inceptionObjString); }); it('should return JSON-formatted string even when normalized', () => { var dream1 = normalize(pipe.transform(inceptionObj)); va...
pipe = new JsonPipe(); });
random_line_split
test_worker_bigrams.py
# coding: utf-8 # # Copyright 2012 NAMD-EMAP-FGV # # This file is part of PyPLN. You can get more information at: http://pypln.org/. # # PyPLN 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 o...
expected_chi_sq = 2.0 self.assertEqual(result, expected_chi_sq)
random_line_split
test_worker_bigrams.py
# coding: utf-8 # # Copyright 2012 NAMD-EMAP-FGV # # This file is part of PyPLN. You can get more information at: http://pypln.org/. # # PyPLN 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 o...
doc_id = self.collection.insert({'tokens': tokens}, w=1) Bigrams().delay(doc_id) refreshed_document = self.collection.find_one({'_id': doc_id}) bigram_rank = refreshed_document['bigram_rank'] result = bigram_rank[0][1][0] # 2.0 is the value of the chi_sq measure for this...
def test_bigrams_should_return_correct_score(self): # We need this list comprehension because we need to save the word list # in mongo (thus, it needs to be json serializable). Also, a list is # what will be available to the worker in real situations. tokens = [w for w in ...
identifier_body
test_worker_bigrams.py
# coding: utf-8 # # Copyright 2012 NAMD-EMAP-FGV # # This file is part of PyPLN. You can get more information at: http://pypln.org/. # # PyPLN 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 o...
(self): # We need this list comprehension because we need to save the word list # in mongo (thus, it needs to be json serializable). Also, a list is # what will be available to the worker in real situations. tokens = [w for w in nltk.corpus.genesis.words('english-web.txt'...
test_bigrams_should_return_correct_score
identifier_name
ActionMap.py
from enigma import eActionMap class ActionMap: def __init__(self, contexts = [ ], actions = { }, prio=0): self.actions = actions self.contexts = contexts self.prio = prio self.p = eActionMap.getInstance() self.bound = False self.exec_active = False self.enabled = True def setEnabled(self, enabled): ...
return 1 else: print "unknown action %s/%s! typo in keymap?" % (context, action) return 0 def destroy(self): pass class NumberActionMap(ActionMap): def action(self, contexts, action): numbers = ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9") if (action in numbers and self.actions.has_key(action...
return res
conditional_block
ActionMap.py
from enigma import eActionMap class ActionMap: def __init__(self, contexts = [ ], actions = { }, prio=0): self.actions = actions self.contexts = contexts self.prio = prio self.p = eActionMap.getInstance() self.bound = False self.exec_active = False self.enabled = True def setEnabled(self, enabled): ...
(self): pass class NumberActionMap(ActionMap): def action(self, contexts, action): numbers = ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9") if (action in numbers and self.actions.has_key(action)): res = self.actions[action](int(action)) if res is not None: return res return 1 else: return ...
destroy
identifier_name
ActionMap.py
from enigma import eActionMap class ActionMap: def __init__(self, contexts = [ ], actions = { }, prio=0): self.actions = actions self.contexts = contexts self.prio = prio self.p = eActionMap.getInstance() self.bound = False self.exec_active = False self.enabled = True def setEnabled(self, enabled): ...
# sorry for this complicated code. # it's not more than converting a "documented" actionmap # (where the values are possibly (function, help)-tuples) # into a "classic" actionmap, where values are just functions. # the classic actionmap is then passed to the ActionMap constructor, # the collected helpstrings (wi...
class HelpableActionMap(ActionMap): """An Actionmap which automatically puts the actions into the helpList. Note that you can only use ONE context here!"""
random_line_split
ActionMap.py
from enigma import eActionMap class ActionMap: def __init__(self, contexts = [ ], actions = { }, prio=0): self.actions = actions self.contexts = contexts self.prio = prio self.p = eActionMap.getInstance() self.bound = False self.exec_active = False self.enabled = True def setEnabled(self, enabled): ...
def destroy(self): pass class NumberActionMap(ActionMap): def action(self, contexts, action): numbers = ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9") if (action in numbers and self.actions.has_key(action)): res = self.actions[action](int(action)) if res is not None: return res return 1 el...
print " ".join(("action -> ", context, action)) if action in self.actions: res = self.actions[action]() if res is not None: return res return 1 else: print "unknown action %s/%s! typo in keymap?" % (context, action) return 0
identifier_body
htmlsourceelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLSourceElementBinding; use dom::bindings::codegen::InheritTypes::HTMLSour...
} impl HTMLSourceElement { pub fn new_inherited(localName: DOMString, document: &JSRef<Document>) -> HTMLSourceElement { HTMLSourceElement { htmlelement: HTMLElement::new_inherited(HTMLSourceElementTypeId, localName, document) } } pub fn new(localName: DOMString, document: &JS...
{ self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLSourceElementTypeId)) }
identifier_body
htmlsourceelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLSourceElementBinding; use dom::bindings::codegen::InheritTypes::HTMLSour...
<'a>(&'a self) -> &'a Reflector { self.htmlelement.reflector() } }
reflector
identifier_name
htmlsourceelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLSourceElementBinding; use dom::bindings::codegen::InheritTypes::HTMLSour...
} impl HTMLSourceElementDerived for EventTarget { fn is_htmlsourceelement(&self) -> bool { self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLSourceElementTypeId)) } } impl HTMLSourceElement { pub fn new_inherited(localName: DOMString, document: &JSRef<Document>) -> HTMLSourceElement { ...
use servo_util::str::DOMString; #[deriving(Encodable)] pub struct HTMLSourceElement { pub htmlelement: HTMLElement
random_line_split
cat.js
var shell = require('..'); var assert = require('assert'), path = require('path'), fs = require('fs'); // Node shims for < v0.7 fs.existsSync = fs.existsSync || path.existsSync; shell.silent(); function numLines(str) { return typeof str === 'string' ? str.match(/\n/g).length : 0; } // save current dir va...
// Valids // // simple var result = shell.cat('resources/file1'); assert.equal(shell.error(), null); assert.equal(result, 'test1'); // multiple files var result = shell.cat('resources/file2', 'resources/file1'); assert.equal(shell.error(), null); assert.equal(result, 'test2\ntest1'); // multiple files, array syntax ...
shell.cat('/adsfasdf'); // file does not exist assert.ok(shell.error()); //
random_line_split
cat.js
var shell = require('..'); var assert = require('assert'), path = require('path'), fs = require('fs'); // Node shims for < v0.7 fs.existsSync = fs.existsSync || path.existsSync; shell.silent(); function
(str) { return typeof str === 'string' ? str.match(/\n/g).length : 0; } // save current dir var cur = shell.pwd(); shell.rm('-rf', 'tmp'); shell.mkdir('tmp') // // Invalids // shell.cat(); assert.ok(shell.error()); assert.equal(fs.existsSync('/asdfasdf'), false); // sanity check shell.cat('/adsfasdf'); // file d...
numLines
identifier_name