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
Progress.py
import os from PodSix.Resource import * from PodSix.Concurrent import Concurrent class Progress(Concurrent): def __init__(self): Concurrent.__init__(self) self.sprite = Image(file=os.path.join("resources", "progress.png")) self.showing = False self.maximum = 1 self.value = 0 self.width = 142 self.heig...
(self, maximum=None): if not maximum is None: self.maximum = maximum self.showing = True def Hide(self): if self.showing: self.showing = False def Value(self, val, maximum=None): if not maximum is None: self.maximum = maximum self.value = val
Show
identifier_name
itemrt.rs
//! Item rare tables for GC/BB. The ItemRT.gsl is organized much in the same //! way as the ItemPT archive. use std::io::{Read, Write, Cursor}; use std::io; use psoserial::Serial; use psoserial::util::*; /// Parsed rare table entry. There are 101 Enemy entries and 30 Box entries in /// a full rare table file. #[deri...
{ pub enemy_rares: Vec<RtEntry>, pub box_rares: Vec<RtEntry> } impl Serial for RtSet { fn serialize(&self, dst: &mut Write) -> io::Result<()> { try!(write_array(&self.enemy_rares, 101, dst)); try!(write_array(&self.box_rares, 30, dst)); Ok(()) } fn deserialize(src: &mut Rea...
RtSet
identifier_name
itemrt.rs
//! Item rare tables for GC/BB. The ItemRT.gsl is organized much in the same //! way as the ItemPT archive. use std::io::{Read, Write, Cursor}; use std::io; use psoserial::Serial; use psoserial::util::*; /// Parsed rare table entry. There are 101 Enemy entries and 30 Box entries in /// a full rare table file. #[deri...
} /// Full rare drop table for a full episode. #[derive(Clone, Debug)] pub struct ItemRT { sections: Vec<RtSet> } impl ItemRT { pub fn load_from_buffers(files: &[&[u8]]) -> io::Result<ItemRT> { if files.len() != 10 { return Err(io::Error::new(io::ErrorKind::Other, "Not enough files, need ...
{ let enemy_rares = try!(read_array(101, src)); let box_rares = try!(read_array(30, src)); Ok(RtSet { enemy_rares: enemy_rares, box_rares: box_rares }) }
identifier_body
itemrt.rs
//! Item rare tables for GC/BB. The ItemRT.gsl is organized much in the same //! way as the ItemPT archive. use std::io::{Read, Write, Cursor}; use std::io; use psoserial::Serial; use psoserial::util::*; /// Parsed rare table entry. There are 101 Enemy entries and 30 Box entries in /// a full rare table file. #[deri...
Ok(()) } fn deserialize(src: &mut Read) -> io::Result<Self> { Ok(RtEntry { prob: try!(Serial::deserialize(src)), item_data: try!(Serial::deserialize(src)) }) } } impl RtEntry { /// Derive the drop probability from the encoded value. /// /// This ...
try!(self.item_data.serialize(dst));
random_line_split
tasks.client.controller.js
'use strict'; // Tasks controller angular.module('tasks').controller('TasksController', ['$scope', '$stateParams', '$location', 'Authentication', 'Tasks', function($scope, $stateParams, $location, Authentication, Tasks) { $scope.authentication = Authentication; $scope.bases = [ {name: 'Squat', lift: 'squat'}, ...
}); }; } ]);
$scope.task = Tasks.get({ taskId: $stateParams.taskId
random_line_split
tasks.client.controller.js
'use strict'; // Tasks controller angular.module('tasks').controller('TasksController', ['$scope', '$stateParams', '$location', 'Authentication', 'Tasks', function($scope, $stateParams, $location, Authentication, Tasks) { $scope.authentication = Authentication; $scope.bases = [ {name: 'Squat', lift: 'squat'}, ...
}; // Update existing Task $scope.update = function() { var task = $scope.task; task.$update(function() { $location.path('tasks/' + task._id); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; // Find a list of Tasks $scope.find = function() { $scope.t...
{ $scope.task.$remove(function() { $location.path('tasks'); }); }
conditional_block
init.js
/* * @brief wss file * * Copyright (C) 2006-2009 Jedox AG * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License (Version 2) as published * by the Free Software Foundation at http://www.gnu.org/copyleft/gpl.html. * * This program ...
}, collapse:function(){ this.body.dom.style.display = 'none'; var that = Ext.getCmp('ps-navigation-panel'); that.timer = setTimeout(function(){that.expandedFlag = false; that.setWelcomePanelActive();}, 0); var cts = Jedox.studio.app.containers; delete cts.connTB; delete ...
{ cts.connPan = Ext.getCmp('c-main-panel').tabPanel.getActiveTab(); cts.connSCbtn = Ext.getCmp('conn-saveCancel-tb'); }
conditional_block
init.js
/* * @brief wss file * * Copyright (C) 2006-2009 Jedox AG * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License (Version 2) as published * by the Free Software Foundation at http://www.gnu.org/copyleft/gpl.html. * * This program ...
cts.connPan = Ext.getCmp('c-main-panel').tabPanel.getActiveTab(); cts.connSCbtn = Ext.getCmp('conn-saveCancel-tb'); } }, collapse:function(){ this.body.dom.style.display = 'none'; var that = Ext.getCmp('ps-navigation-panel'); that.timer = setTimeout(function(){that.expande...
if (Ext.getCmp('c-main-panel').layout.activeItem.id != 'connempty'){
random_line_split
Int2IntHash.js
Clazz.declarePackage ("J.util"); c$ = Clazz.decorateAsClass (function () { this.entryCount = 0; this.entries = null; Clazz.instantialize (this, arguments); }, J.util, "Int2IntHash"); Clazz.makeConstructor (c$, function (initialCapacity) { this.entries = new Array (initialCapacity); }, "~N"); $_M(c$, "get", ...
entries = this.entries; hash = (key & 0x7FFFFFFF) % entries.length; entries[hash] = new J.util.Int2IntHash.Entry (key, value, entries[hash]); ++this.entryCount; }, "~N,~N"); $_M(c$, "rehash", ($fz = function () { var oldEntries = this.entries; var oldSize = oldEntries.length; var newSize = oldSize * 2 + 1; ...
return; } if (this.entryCount > entries.length) this.rehash ();
random_line_split
SettingsPurchasesRoute_me.graphql.ts
/* tslint:disable */ /* eslint-disable */ import { ReaderFragment } from "relay-runtime"; import { FragmentRefs } from "relay-runtime"; export type SettingsPurchasesRoute_me = { readonly name: string | null; readonly " $refType": "SettingsPurchasesRoute_me"; }; export type SettingsPurchasesRoute_me$data = Sett...
}; (node as any).hash = 'd0810f50c8abc162df5bb80601d2e746'; export default node;
random_line_split
TestSin.rs
/* * Copyright (C) 2014 The Android Open Source Project * * 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 app...
} float2 __attribute__((kernel)) testSinFloat2Float2(float2 in) { return sin(in); } float3 __attribute__((kernel)) testSinFloat3Float3(float3 in) { return sin(in); } float4 __attribute__((kernel)) testSinFloat4Float4(float4 in) { return sin(in); }
random_line_split
guestby1currentsnapshot.py
# -*- coding: utf-8 -*- # # This file is part of Karesansui. # # Copyright (C) 2009-2012 HDE, Inc. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without lim...
model = findbyguest1(self.orm, guest_id) kvs = KaresansuiVirtSnapshot(readonly=False) snapshot_list = [] try: domname = kvs.kvc.uuid_to_domname(model.uniq_key) if not domname: return web.notfound() self.view.is_creatable = kvs.isSupportedDomain(domna...
pass # ignore snapshots that is not in database. #return web.badrequest("Request data is invalid.")
random_line_split
guestby1currentsnapshot.py
# -*- coding: utf-8 -*- # # This file is part of Karesansui. # # Copyright (C) 2009-2012 HDE, Inc. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without lim...
self.view.is_creatable = kvs.isSupportedDomain(domname) try: snapshot_list = kvs.listNames(domname)[domname] except: pass finally: kvs.finish() if not snapshot_id in snapshot_list: self.logger.debug(_("The spe...
return web.notfound()
conditional_block
guestby1currentsnapshot.py
# -*- coding: utf-8 -*- # # This file is part of Karesansui. # # Copyright (C) 2009-2012 HDE, Inc. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without lim...
(self, *param, **params): (host_id, guest_id) = self.chk_guestby1(param) if guest_id is None: return web.notfound() if is_param(self.input, 'id') is False \ or is_int(self.input.id) is False: return web.badrequest("Request data is invalid.") snapshot_id = str(se...
_PUT
identifier_name
guestby1currentsnapshot.py
# -*- coding: utf-8 -*- # # This file is part of Karesansui. # # Copyright (C) 2009-2012 HDE, Inc. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without lim...
snapshot_list = [] try: domname = kvs.kvc.uuid_to_domname(model.uniq_key) if not domname: return web.notfound() self.view.is_creatable = kvs.isSupportedDomain(domname) try: snapshot_list = kvs.listNames(domname)[domname] except:...
@auth def _PUT(self, *param, **params): (host_id, guest_id) = self.chk_guestby1(param) if guest_id is None: return web.notfound() if is_param(self.input, 'id') is False \ or is_int(self.input.id) is False: return web.badrequest("Request data is invalid.") sn...
identifier_body
app.js
var canvas = require("./canvas"); var keysDown = require("./input").keysDown; var mainMenu = require("./menu/mainMenu"); var Player = require("./player"); var Confirmation = require("./confirmation"); var scoreTracker = require("./scoretracker"); var overlay = require("./ov...
break; case "complete": audio.queueAhead(); this.confirmation.update(this.keysDown, timer.delta); default: // no default } }; module.exports = app;
{ this.state = "complete"; scoreTracker.tabulate(this.scenario.name); this.confirmation = new Confirmation(() => { delete this.confirmation; scoreTracker.reset(); this.sceneLoader(this.currentScene + 1); ...
conditional_block
app.js
var canvas = require("./canvas"); var keysDown = require("./input").keysDown; var mainMenu = require("./menu/mainMenu"); var Player = require("./player"); var Confirmation = require("./confirmation"); var scoreTracker = require("./scoretracker"); var overlay = require("./ov...
}; app.update = function(tStamp) { "use strict"; timer.progress(tStamp); switch (this.state) { case "mainmenu": mainMenu.update(this.keysDown, timer.delta); break; case "game": this.player.update(this.keysDown, this.scenario.actors, ...
default: // no default }
random_line_split
context.rs
Key { pub pid: Option<ContextId>, pub pgid: Option<ContextId>, } impl Ord for WaitpidKey { fn cmp(&self, other: &WaitpidKey) -> Ordering { // If both have pid set, compare that if let Some(s_pid) = self.pid { if let Some(o_pid) = other.pid { return s_pid.cmp(&o_p...
pub image: Vec<SharedMemory>, /// User heap pub heap: Option<SharedMemory>, /// User stack pub stack: Option<Memory>, /// User signal stack pub sigstack: Option<Memory>, /// User Thread local storage pub tls: Option<Tls>, /// User grants pub grants: Arc<Mutex<Vec<Grant>>>, ...
/// Restore ksig context on next switch pub ksig_restore: bool, /// Executable image
random_line_split
context.rs
other.pgid { return s_pgid.cmp(&o_pgid); } } // If either has pid set, it is greater if self.pid.is_some() { return Ordering::Greater; } if other.pid.is_some() { return Ordering::Less; } // If either has pgid...
add_file_min
identifier_name
context.rs
} } // If both have pgid set, compare that if let Some(s_pgid) = self.pgid { if let Some(o_pgid) = other.pgid { return s_pgid.cmp(&o_pgid); } } // If either has pid set, it is greater if self.pid.is_some() { ...
{ self.add_file_min(file, 0) }
identifier_body
context.rs
pub euid: u32, /// The effective group id pub egid: u32, /// The effective namespace id pub ens: SchemeNamespace, /// Status of context pub status: Status, /// Context running or not pub running: bool, /// CPU ID, if locked pub cpu_id: Option<usize>, /// Current system ca...
{ None }
conditional_block
spidergram.py
from bs4 import BeautifulSoup import requests import re import os import codecs import unidecode import arrow import traceback # disable warning about HTTPS try: requests.packages.urllib3.disable_warnings() except: pass class instaLogger:
class instagram: def __init__(self, logobj): self.logger = logobj self.dest = os.path.join(os.getcwdu(), 'images') if not os.path.exists(self.dest): os.makedirs(self.dest) self.results = None self.resetResults() self.baseUrl = None def resetResults...
def __init__(self, logfile): self.logfile = logfile def logEntry(self, entry, level): with codecs.open(self.logfile, mode='a', encoding='utf-8') as log: log.write(entry + '\n') if 'progress' in level: print unidecode.unidecode(entry)
identifier_body
spidergram.py
from bs4 import BeautifulSoup import requests import re import os import codecs import unidecode import arrow import traceback # disable warning about HTTPS try: requests.packages.urllib3.disable_warnings() except: pass class instaLogger: def __init__(self, logfile): self.logfile = logfile d...
def getLinksForGalleryPage(self, url): """ Recursive function to traverse the script payload that apparently is used to load Instagram pages completely on the fly. Pulls each individual "page" - which is apparently 24 images by the user, delineated by the "start_cursor" and...
return each.string.split(' = ')[-1]
conditional_block
spidergram.py
from bs4 import BeautifulSoup import requests import re import os import codecs import unidecode import arrow import traceback # disable warning about HTTPS try: requests.packages.urllib3.disable_warnings() except: pass class
: def __init__(self, logfile): self.logfile = logfile def logEntry(self, entry, level): with codecs.open(self.logfile, mode='a', encoding='utf-8') as log: log.write(entry + '\n') if 'progress' in level: print unidecode.unidecode(entry) class instagram: def ...
instaLogger
identifier_name
spidergram.py
from bs4 import BeautifulSoup import requests import re import os import codecs import unidecode import arrow import traceback # disable warning about HTTPS try: requests.packages.urllib3.disable_warnings() except: pass class instaLogger: def __init__(self, logfile): self.logfile = logfile d...
def getHighResLink(self, code): pageurl = 'https://www.instagram.com/p/{0}/?hl=en'.format(code) payloadRaw = self.findWindowSharedData(pageurl) hrlink = re.findall( '(?<="display_src":").*?\?', payloadRaw)[0] hrlink = hrlink.replace('\\', '')[:-1] retu...
random_line_split
complex.rs
== [(a + i b) * (c - i d)] / (c*c + d*d) // == [(a*c + b*d) / (c*c + d*d)] + i [(b*c - a*d) / (c*c + d*d)] impl<T: Clone + Num> Div<Cmplx<T>, Cmplx<T>> for Cmplx<T> { #[inline] fn div(&self, other: &Cmplx<T>) -> Cmplx<T> { let norm_sqr = other.norm_sqr(); Cmplx::new((self.re*other.re + self.i...
assert_eq!(c * _1_0i, c); assert_eq!(_1_0i * c, c); } } #[test]
random_line_split
complex.rs
> { Cmplx::new(self.re.clone(), -self.im) } /// Multiplies `self` by the scalar `t`. #[inline] pub fn scale(&self, t: T) -> Cmplx<T> { Cmplx::new(self.re * t, self.im * t) } /// Divides `self` by the scalar `t`. #[inline] pub fn unscale(&self, t: T) -> Cmplx<T> { ...
() { for &c in all_consts.iter() { assert_eq!(c.conj(), Cmplx::new(c.re, -c.im)); assert_eq!(c.conj().conj(), c); } } #[test] fn test_inv() { assert_eq!(_1_1i.inv(), _
test_conj
identifier_name
complex.rs
> { Cmplx::new(self.re.clone(), -self.im) } /// Multiplies `self` by the scalar `t`. #[inline] pub fn scale(&self, t: T) -> Cmplx<T> { Cmplx::new(self.re * t, self.im * t) } /// Divides `self` by the scalar `t`. #[inline] pub fn unscale(&self, t: T) -> Cmplx<T> { ...
} impl<T: Clone + Real> Cmplx<T> { /// Calculate the principal Arg of self. #[inline] pub fn arg(&self) -> T { self.im.atan2(&self.re) } /// Convert to polar form (r, theta), such that `self = r * exp(i /// * theta)` #[inline] pub fn to_polar(&self) -> (T, T) { (self.no...
{ self.re.hypot(&self.im) }
identifier_body
complex.rs
> { Cmplx::new(self.re.clone(), -self.im) } /// Multiplies `self` by the scalar `t`. #[inline] pub fn scale(&self, t: T) -> Cmplx<T> { Cmplx::new(self.re * t, self.im * t) } /// Divides `self` by the scalar `t`. #[inline] pub fn unscale(&self, t: T) -> Cmplx<T> { ...
} } #[cfg(test)] mod test { #[allow(non_uppercase_statics)]; use super::*; use std::num::{Zero,One,Real}; pub static _0_0i : Complex64 = Cmplx { re: 0.0, im: 0.0 }; pub static _1_0i : Complex64 = Cmplx { re: 1.0, im: 0.0 }; pub static _1_1i : Complex64 = Cmplx { re: 1.0, im: 1.0 }; p...
{ format!("{}+{}i", self.re.to_str_radix(radix), self.im.to_str_radix(radix)) }
conditional_block
util.ts
import * as bcrypt from 'bcrypt-nodejs'; const StringIsNumber = value => isNaN(Number(value)) === false; export function
(enumme) { return Object.keys(enumme) .filter(StringIsNumber) .map(key => enumme[key]); } export function soNumeros(texto: string) { return texto.replace(/\D/g, ''); } export function bcryptHash(texto: string) { return new Promise((resolve, reject) => { bcrypt.hash(texto, null, null, (err, resultado...
EnumToArray
identifier_name
util.ts
import * as bcrypt from 'bcrypt-nodejs'; const StringIsNumber = value => isNaN(Number(value)) === false; export function EnumToArray(enumme)
export function soNumeros(texto: string) { return texto.replace(/\D/g, ''); } export function bcryptHash(texto: string) { return new Promise((resolve, reject) => { bcrypt.hash(texto, null, null, (err, resultado: string) => { if (err) { reject(err); } else { resolve(resultado); ...
{ return Object.keys(enumme) .filter(StringIsNumber) .map(key => enumme[key]); }
identifier_body
util.ts
import * as bcrypt from 'bcrypt-nodejs'; const StringIsNumber = value => isNaN(Number(value)) === false; export function EnumToArray(enumme) { return Object.keys(enumme) .filter(StringIsNumber) .map(key => enumme[key]); } export function soNumeros(texto: string) { return texto.replace(/\D/g, ''); } expo...
} export function bcryptCompare(data: string, hash: string) { return new Promise((resolve, reject) => { bcrypt.compare(data, hash, (err, resultado: boolean) => { if (err) { reject(err); } else { resolve(resultado); } }); }); } export function hexToRgb(hex): { r: number,...
} else { resolve(resultado); } }); });
random_line_split
util.ts
import * as bcrypt from 'bcrypt-nodejs'; const StringIsNumber = value => isNaN(Number(value)) === false; export function EnumToArray(enumme) { return Object.keys(enumme) .filter(StringIsNumber) .map(key => enumme[key]); } export function soNumeros(texto: string) { return texto.replace(/\D/g, ''); } expo...
else { resolve(resultado); } }); }); } export function bcryptCompare(data: string, hash: string) { return new Promise((resolve, reject) => { bcrypt.compare(data, hash, (err, resultado: boolean) => { if (err) { reject(err); } else { resolve(resultado); } ...
{ reject(err); }
conditional_block
helpers.js
/** * Copyright (C) 2011 Jacob Beard * Released under GNU GPL, read the file 'COPYING' for more information **/ define( function(){ function addPathRefToSegment(path,seg){ seg.pathRef = path; } return { mixin : function (from,to){ for(var p in from){ if(from.hasOwnProperty(p)) to[p] = from[p]; ...
y : propY }; }, getStartSegFromPath : function(path){ var segList = path.pathSegList; var numItems = segList.numberOfItems; var startSeg = segList.getItem(0); return startSeg; }, getEndSegFromPath : function(path){ var segList = path.pathSegList; var numItems = segL...
return { x : propX,
random_line_split
helpers.js
/** * Copyright (C) 2011 Jacob Beard * Released under GNU GPL, read the file 'COPYING' for more information **/ define( function(){ function addPathRefToSegment(path,seg)
return { mixin : function (from,to){ for(var p in from){ if(from.hasOwnProperty(p)) to[p] = from[p]; } }, removeFromList : function (element,list){ return list.splice(list.indexOf(element),1); }, propNumtoPropString : function (propNum){ var propStr = propNum || ""; var p...
{ seg.pathRef = path; }
identifier_body
helpers.js
/** * Copyright (C) 2011 Jacob Beard * Released under GNU GPL, read the file 'COPYING' for more information **/ define( function(){ function
(path,seg){ seg.pathRef = path; } return { mixin : function (from,to){ for(var p in from){ if(from.hasOwnProperty(p)) to[p] = from[p]; } }, removeFromList : function (element,list){ return list.splice(list.indexOf(element),1); }, propNumtoPropString : function (propNum){ ...
addPathRefToSegment
identifier_name
Notification.tsx
import { AnimationEvent, MouseEvent, ReactNode } from 'react'; import { classnames } from '../../helpers'; import { NotificationType } from './interfaces'; const TYPES_CLASS = { error: 'notification-danger', warning: 'notification-warning', info: 'notification-info', success: 'notification-success', };...
}; return ( <div aria-atomic="true" role="alert" className={classnames([ 'p1', 'mb0-5', 'text-break', CLASSES.NOTIFICATION, CLASSES.NOTIFICATION_IN, TYPES_CLASS[type] || ...
{ onExit(); }
conditional_block
Notification.tsx
import { AnimationEvent, MouseEvent, ReactNode } from 'react'; import { classnames } from '../../helpers'; import { NotificationType } from './interfaces'; const TYPES_CLASS = { error: 'notification-danger', warning: 'notification-warning', info: 'notification-info', success: 'notification-success', };...
'p1', 'mb0-5', 'text-break', CLASSES.NOTIFICATION, CLASSES.NOTIFICATION_IN, TYPES_CLASS[type] || TYPES_CLASS.success, isClosing && CLASSES.NOTIFICATION_OUT, ])} onClick={onClick} ...
className={classnames([
random_line_split
weather.py
#!/usr/bin/env python import sys import html5lib import urllib2 from numpy import median, array from xml_icd import parseICD from html5lib import treebuilders def salt(): wx = {} try: tcs = parseICD("http://icd.salt/xml/salt-tcs-icd.xml") time = tcs['tcs xml time info'] bms = tcs['bm...
wx["UT"] = tds[3].firstChild.nodeValue.strip() tds[31].normalize() wx["Status"] = tds[31].firstChild.nodeValue.strip() return wx except: return False def grav(): wx = {} p = html5lib.HTMLParser(tree=treebuilders.getTreeBuilder("dom")) kan11 = p.parse(urllib2.ur...
wx["Raining"] = True
conditional_block
weather.py
#!/usr/bin/env python import sys import html5lib import urllib2 from numpy import median, array from xml_icd import parseICD from html5lib import treebuilders def salt(): wx = {} try: tcs = parseICD("http://icd.salt/xml/salt-tcs-icd.xml") time = tcs['tcs xml time info'] bms = tcs['bm...
wx["Wind Speed"] = float(tds[5].firstChild.nodeValue) rain = tds[4].firstChild.nodeValue if rain == "DRY": wx["Raining"] = False else: wx["Raining"] = True wx["UT"] = tds[3].firstChild.nodeValue.strip() tds[31].normalize() wx["Status"] = td...
wx = {} try: p = html5lib.HTMLParser(tree=treebuilders.getTreeBuilder("dom")) doc = p.parse(urllib2.urlopen("http://swaspgateway.suth/", timeout=1).read()) t = doc.getElementsByTagName("table")[0] tds = t.getElementsByTagName("td") wx["Te...
identifier_body
weather.py
#!/usr/bin/env python import sys import html5lib import urllib2 from numpy import median, array from xml_icd import parseICD from html5lib import treebuilders def
(): wx = {} try: tcs = parseICD("http://icd.salt/xml/salt-tcs-icd.xml") time = tcs['tcs xml time info'] bms = tcs['bms external conditions'] temps = bms['Temperatures'] wx["Temp"] = median(array(temps.values())) wx["Temp 2m"] = temps["2m"] wx["Temp 30m"] ...
salt
identifier_name
weather.py
#!/usr/bin/env python import sys import html5lib import urllib2 from numpy import median, array from xml_icd import parseICD from html5lib import treebuilders def salt(): wx = {} try: tcs = parseICD("http://icd.salt/xml/salt-tcs-icd.xml") time = tcs['tcs xml time info'] bms = tcs['bm...
# set up other values of interest wx["Air Pressure"] = bms["Air pressure"] * 10.0 wx["Dewpoint"] = bms["Dewpoint"] wx["RH"] = bms["Rel Humidity"] wx["Wind Speed (30m)"] = bms["Wind mag 30m"] * 3.6 wx["Wind Speed"] = bms["Wind mag 10m"] * 3.6 wx["Wind Dir (30m)"] =...
# get time wx["SAST"] = time["SAST"].split()[1] wx["Date"] = time["SAST"].split()[0]
random_line_split
js.rs
} impl<T: DomObject> JS<T> { /// Create a JS<T> from a &T #[allow(unrooted_must_root)] pub fn from_ref(obj: &T) -> JS<T> { debug_assert!(thread_state::get().is_script()); JS { ptr: unsafe { NonZero::new(&*obj) }, } } } impl<'root, T: DomObject + 'root> RootedRefere...
{ debug_assert!(thread_state::get().is_layout()); LayoutJS { ptr: self.ptr.clone(), } }
identifier_body
js.rs
<'root, T: DomObject + 'root> RootedReference<'root> for JS<T> { type Ref = &'root T; fn r(&'root self) -> &'root T { &self } } impl<T: DomObject> Deref for JS<T> { type Target = T; fn deref(&self) -> &T { debug_assert!(thread_state::get().is_script()); // We can only have ...
pub fn new(initial: &T) -> MutJS<T> { debug_assert!(thread_state::get().is_script()); MutJS { val: UnsafeCell::new(JS::from_ref(initial)), } } /// Set this `MutJS` to the given value. pub fn set(&self, val: &T) { debug_assert!(thread_state::get().is_script())...
impl<T: DomObject> MutJS<T> { /// Create a new `MutJS`.
random_line_split
js.rs
ability for GC-managed values such as /// `JS<T>`. Essentially a `Cell<JS<T>>`, but safer. /// /// This should only be used as a field in other DOM objects; see warning /// on `JS<T>`. #[must_root] #[derive(JSTraceable)] pub struct MutJS<T: DomObject> { val: UnsafeCell<JS<T>>, } impl<T: DomObject> MutJS<T> { ...
trace_roots
identifier_name
natsort.py
# This file is part of Indico. # Copyright (C) 2002 - 2020 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from __future__ import unicode_literals from sqlalchemy import DDL, text SQL_FUNCTION_NATSORT = ''' ...
DDL(SQL_FUNCTION_NATSORT).execute_if(callable_=_should_create_function).execute(conn)
identifier_body
natsort.py
# This file is part of Indico. # Copyright (C) 2002 - 2020 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from __future__ import unicode_literals from sqlalchemy import DDL, text SQL_FUNCTION_NATSORT = ''' ...
(ddl, target, connection, **kw): sql = """ SELECT COUNT(*) FROM information_schema.routines WHERE routine_schema = 'indico' AND routine_name = 'natsort' """ count = connection.execute(text(sql)).scalar() return not count def create_natsort_function(conn): DDL(SQL_FUNCTION_N...
_should_create_function
identifier_name
natsort.py
# This file is part of Indico. # Copyright (C) 2002 - 2020 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from __future__ import unicode_literals from sqlalchemy import DDL, text SQL_FUNCTION_NATSORT = '''
SELECT string_agg( convert_to(coalesce(r[2], length(length(r[1])::text) || length(r[1])::text || r[1]), 'SQL_ASCII'), ' ' ) FROM regexp_matches(value, '0*([0-9]+)|([^0-9]+)', 'g') r; $$ LANGUAGE SQL IMMUTABLE STRICT; ''' def _should_create_function(ddl, target, connection, **kw): ...
CREATE FUNCTION indico.natsort(value TEXT) RETURNS bytea AS $$
random_line_split
DateUtilities.d.ts
export declare class
{ static locale: any; static loadLocale(locale: any): void; /** * Add zero before value if value.length < length */ static pad(value: string, length: number): string; /** * Clonning date */ static clone(date: Date): Date; /** * Format date */ static formatD...
DateUtilities
identifier_name
DateUtilities.d.ts
export declare class DateUtilities { static locale: any; static loadLocale(locale: any): void; /** * Add zero before value if value.length < length */ static pad(value: string, length: number): string; /** * Clonning date */ static clone(date: Date): Date;
/** * Format UTC date */ static formatDateUTC(date: Date): any; /** * Convert day of the date to String */ static toDayOfMonthString(date: Date): string; /** * Get month of the date */ static toMonthString(date: any): any; /** * Get year of the date */ ...
/** * Format date */ static formatDate(date: Date): any;
random_line_split
AudioMerger.py
from pydub import * class AudioMerger: voice_tags = ["one", "two", "three", "four", "five", "ten", "RUN", "relax", "completed"] def __init__(self, music): self.music = music self.additionalGain = 8 self.voices={} for voice in self.voice_tags:
def addCountdown(self, startTime, isRun = True): for i in range(1, 6): voice = self.voices[self.voice_tags[i - 1]] self.music = self.music.overlay(voice, position = (startTime - i) * 1000) self.music = self.music.overlay(self.voices["ten"], position = (startTime - 10) * 1000) voice = self.voices["RUN" if...
sound = AudioSegment.from_file('voices/' + voice + '.wav') sound += self.additionalGain self.voices[voice] = sound
conditional_block
AudioMerger.py
from pydub import * class AudioMerger: voice_tags = ["one", "two", "three", "four", "five", "ten", "RUN", "relax", "completed"] def __init__(self, music): self.music = music self.additionalGain = 8 self.voices={} for voice in self.voice_tags: sound = AudioSegment.from_file('voices/' + voice + '.wav') ...
(self, startTime, isRun = True): for i in range(1, 6): voice = self.voices[self.voice_tags[i - 1]] self.music = self.music.overlay(voice, position = (startTime - i) * 1000) self.music = self.music.overlay(self.voices["ten"], position = (startTime - 10) * 1000) voice = self.voices["RUN" if isRun else "relax"...
addCountdown
identifier_name
AudioMerger.py
from pydub import * class AudioMerger: voice_tags = ["one", "two", "three", "four", "five", "ten", "RUN", "relax", "completed"] def __init__(self, music):
def addCountdown(self, startTime, isRun = True): for i in range(1, 6): voice = self.voices[self.voice_tags[i - 1]] self.music = self.music.overlay(voice, position = (startTime - i) * 1000) self.music = self.music.overlay(self.voices["ten"], position = (startTime - 10) * 1000) voice = self.voices["RUN" if...
self.music = music self.additionalGain = 8 self.voices={} for voice in self.voice_tags: sound = AudioSegment.from_file('voices/' + voice + '.wav') sound += self.additionalGain self.voices[voice] = sound
identifier_body
AudioMerger.py
from pydub import * class AudioMerger: voice_tags = ["one", "two", "three", "four", "five", "ten", "RUN", "relax", "completed"] def __init__(self, music): self.music = music self.additionalGain = 8 self.voices={} for voice in self.voice_tags: sound = AudioSegment.from_file('voices/' + voice + '.wav') ...
voice = self.voices[self.voice_tags[i - 1]] self.music = self.music.overlay(voice, position = (startTime - i) * 1000) self.music = self.music.overlay(self.voices["ten"], position = (startTime - 10) * 1000) voice = self.voices["RUN" if isRun else "relax"] self.music = self.music.overlay(voice, position = sta...
self.voices[voice] = sound def addCountdown(self, startTime, isRun = True): for i in range(1, 6):
random_line_split
takeSnapshot.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @providesModule takeSnapshot * @flow */ 'use strict'; const UIManager = require('UIManager'); const findNumericNodeHandle = require...
(typeof view !== 'number' && view !== 'window') { view = findNumericNodeHandle(view) || 'window'; } // Call the hidden '__takeSnapshot' method; the main one throws an error to // prevent accidental backwards-incompatible usage. return UIManager.__takeSnapshot(view, options); } module.exports = takeSnapsh...
if
identifier_name
takeSnapshot.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @providesModule takeSnapshot * @flow */ 'use strict'; const UIManager = require('UIManager'); const findNumericNodeHandle = require...
// Call the hidden '__takeSnapshot' method; the main one throws an error to // prevent accidental backwards-incompatible usage. return UIManager.__takeSnapshot(view, options); } module.exports = takeSnapshot;
random_line_split
takeSnapshot.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @providesModule takeSnapshot * @flow */ 'use strict'; const UIManager = require('UIManager'); const findNumericNodeHandle = require...
// Call the hidden '__takeSnapshot' method; the main one throws an error to // prevent accidental backwards-incompatible usage. return UIManager.__takeSnapshot(view, options); } module.exports = takeSnapshot;
{ view = findNumericNodeHandle(view) || 'window'; }
identifier_body
lib.rs
::HashMap; use std::io; use std::io::prelude::*; use std::fs::{self, File}; use std::path::{PathBuf, Path}; use std::process; use syntax::ast; use syntax::codemap; use syntax::ext::base::{self, ExtCtxt, MacResult}; use syntax::fold::Folder; use syntax::parse::{self, token}; use rustc::plugin::Registry; use tempdir::T...
(reg: &Registry, name: String, expander: F) -> Result<base::SyntaxExtension, ()> { let dir = match TempDir::new(&format!("rustc_external_mixin_{}", name)) { Ok(d) => d, Err(e) => { reg.sess.span_err(reg.krate_span, &format...
new
identifier_name
lib.rs
::HashMap; use std::io; use std::io::prelude::*; use std::fs::{self, File}; use std::path::{PathBuf, Path}; use std::process; use syntax::ast; use syntax::codemap; use syntax::ext::base::{self, ExtCtxt, MacResult}; use syntax::fold::Folder; use syntax::parse::{self, token}; use rustc::plugin::Registry; use tempdir::T...
&Path, &Path) -> Result<Output, ()> { fn expand<'cx>(&self, cx: &'cx mut ExtCtxt, sp: codemap::Span, raw_tts: &[ast::TokenTree]) -> Box<MacResult+'cx> { macro_rules! mac_try {...
random_line_split
lib.rs
::HashMap; use std::io; use std::io::prelude::*; use std::fs::{self, File}; use std::path::{PathBuf, Path}; use std::process; use syntax::ast; use syntax::codemap; use syntax::ext::base::{self, ExtCtxt, MacResult}; use syntax::fold::Folder; use syntax::parse::{self, token}; use rustc::plugin::Registry; use tempdir::T...
args.connect("`, `"), e) }; cx.span_err(sp, &msg); Err(()) } } } /// The options passed to the macro. pub type Options = HashMap<String, Vec<(String, codemap::Span)>>; pub enum Output { Interpreted(process::Output), ...
{ let mut command = process::Command::new(&binary); command.current_dir(dir) .args(&args); if let Some(file) = file { command.arg(&file); } match command.output() { Ok(o) => Ok(o), Err(e) => { let msg = if args.is_empty() { format!("`{}!...
identifier_body
InfiniteScrollNewsArticle.tsx
import { data as sd } from "sharify" import moment from "moment" import styled from "styled-components" import React, { Component, Fragment } from "react" import { flatten, debounce, once } from "lodash" import Waypoint from "react-waypoint" import { positronql } from "desktop/lib/positronql" import { ModalOptions, ...
dismissAuthModal() { Cookies.set("editorial-signup-dismissed", 1, { expires: 864000 }) } fetchNextArticles = async () => { const { articles, following, offset, omit, relatedArticles } = this.state this.setState({ isLoading: true, }) try { const data = await positronql({ ...
{ setupFollowButtons(this.state.following) const editorialAuthDismissedCookie = Cookies.get( "editorial-signup-dismissed" ) if ( !sd.CURRENT_USER && !editorialAuthDismissedCookie && !this.props.isMobile ) { this.showAuthModal() } }
identifier_body
InfiniteScrollNewsArticle.tsx
import { data as sd } from "sharify" import moment from "moment" import styled from "styled-components" import React, { Component, Fragment } from "react" import { flatten, debounce, once } from "lodash" import Waypoint from "react-waypoint" import { positronql } from "desktop/lib/positronql" import { ModalOptions, ...
`
margin-top: ${props => (props.isMobile ? "100" : "200")}px;
random_line_split
InfiniteScrollNewsArticle.tsx
import { data as sd } from "sharify" import moment from "moment" import styled from "styled-components" import React, { Component, Fragment } from "react" import { flatten, debounce, once } from "lodash" import Waypoint from "react-waypoint" import { positronql } from "desktop/lib/positronql" import { ModalOptions, ...
() { setupFollowButtons(this.state.following) const editorialAuthDismissedCookie = Cookies.get( "editorial-signup-dismissed" ) if ( !sd.CURRENT_USER && !editorialAuthDismissedCookie && !this.props.isMobile ) { this.showAuthModal() } } dismissAuthModal() { ...
componentDidMount
identifier_name
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use anyhow::{anyhow, Error}; use async_trait::async_trait; use bookmarks::BookmarkTransactionError; use context::CoreContext; use mononoke_...
async fn into_transaction_hook( self: Box<Self>, _ctx: &CoreContext, rebased: &RebasedChangesets, ) -> Result<Box<dyn PushrebaseTransactionHook>, Error> { // Let's tie assigned git hashes to rebased Bonsai changesets: let entries = self .assignments ...
{ let git_sha1 = extract_git_sha1_from_bonsai_extra( bcs_new .extra .iter() .map(|(k, v)| (k.as_str(), v.as_slice())), )?; if let Some(git_sha1) = git_sha1 { self.assignments.insert(bcs_old, git_sha1); } Ok((...
identifier_body
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use anyhow::{anyhow, Error}; use async_trait::async_trait; use bookmarks::BookmarkTransactionError; use context::CoreContext; use mononoke_...
(&self) -> Result<Box<dyn PushrebaseCommitHook>, Error> { let hook = Box::new(GitMappingCommitHook { bonsai_git_mapping: self.bonsai_git_mapping.clone(), assignments: HashMap::new(), }) as Box<dyn PushrebaseCommitHook>; Ok(hook) } } struct GitMappingCommitHook { ...
prepushrebase
identifier_name
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use anyhow::{anyhow, Error}; use async_trait::async_trait; use bookmarks::BookmarkTransactionError; use context::CoreContext; use mononoke_...
} }
.await .map_err(|e| BookmarkTransactionError::Other(e.into()))?; Ok(txn)
random_line_split
lib.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use anyhow::{anyhow, Error}; use async_trait::async_trait; use bookmarks::BookmarkTransactionError; use context::CoreContext; use mononoke_...
Ok(Box::new(GitMappingTransactionHook { bonsai_git_mapping: self.bonsai_git_mapping, entries, }) as Box<dyn PushrebaseTransactionHook>) } } struct GitMappingTransactionHook { bonsai_git_mapping: Arc<dyn BonsaiGitMapping>, entries: Vec<BonsaiGitMappingEntry>, } #[a...
{ return Err(anyhow!( "Git mapping rebased set ({}) and assignments ({}) have different lengths!", rebased.len(), self.assignments.len(), )); }
conditional_block
test_wait.rs
use nix::unistd::*; use nix::unistd::ForkResult::*; use nix::sys::signal::*; use nix::sys::wait::*; use libc::exit; #[test] fn test_wait_signal()
#[test] fn test_wait_exit() { match fork() { Ok(Child) => unsafe { exit(12); }, Ok(Parent { child }) => { assert_eq!(waitpid(child, None), Ok(WaitStatus::Exited(child, 12))); }, // panic, fork should never fail unless there is a serious problem with the OS Err(_) => panic!(...
{ match fork() { Ok(Child) => pause().unwrap_or(()), Ok(Parent { child }) => { kill(child, SIGKILL).ok().expect("Error: Kill Failed"); assert_eq!(waitpid(child, None), Ok(WaitStatus::Signaled(child, SIGKILL, false))); }, // panic, fork should never fail unless there is a ...
identifier_body
test_wait.rs
use nix::unistd::*; use nix::unistd::ForkResult::*; use nix::sys::signal::*; use nix::sys::wait::*; use libc::exit; #[test] fn
() { match fork() { Ok(Child) => pause().unwrap_or(()), Ok(Parent { child }) => { kill(child, SIGKILL).ok().expect("Error: Kill Failed"); assert_eq!(waitpid(child, None), Ok(WaitStatus::Signaled(child, SIGKILL, false))); }, // panic, fork should never fail unless there is...
test_wait_signal
identifier_name
test_wait.rs
use nix::unistd::*; use nix::unistd::ForkResult::*; use nix::sys::signal::*; use nix::sys::wait::*; use libc::exit; #[test] fn test_wait_signal() { match fork() { Ok(Child) => pause().unwrap_or(()), Ok(Parent { child }) => { kill(child, SIGKILL).ok().expect("Error: Kill Failed"); as...
assert_eq!(waitpid(child, None), Ok(WaitStatus::Exited(child, 12))); }, // panic, fork should never fail unless there is a serious problem with the OS Err(_) => panic!("Error: Fork Failed") } }
Ok(Child) => unsafe { exit(12); }, Ok(Parent { child }) => {
random_line_split
424f18f4c1df_.py
"""empty message Revision ID: 424f18f4c1df Revises: 106e3631fe9 Create Date: 2015-06-23 11:31:08.548661 """ # revision identifiers, used by Alembic. revision = '424f18f4c1df' down_revision = '106e3631fe9' from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql from sqlalchemy.diale...
### commands auto generated by Alembic - please adjust! ### providers_list.create(op.get_bind(), checkfirst=False) op.create_table('auth_providers', sa.Column('id', sa.Integer(), nullable=False), sa.Column('provider', providers_list, nullable=True), ...
def upgrade():
random_line_split
424f18f4c1df_.py
"""empty message Revision ID: 424f18f4c1df Revises: 106e3631fe9 Create Date: 2015-06-23 11:31:08.548661 """ # revision identifiers, used by Alembic. revision = '424f18f4c1df' down_revision = '106e3631fe9' from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql from sqlalchemy.diale...
def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_table('auth_providers') providers_list.drop(op.get_bind(), checkfirst=False) ### end Alembic commands ###
providers_list.create(op.get_bind(), checkfirst=False) op.create_table('auth_providers', sa.Column('id', sa.Integer(), nullable=False), sa.Column('provider', providers_list, nullable=True), sa.Column('provider_id', sa.Integer(), nullable=True), ...
identifier_body
424f18f4c1df_.py
"""empty message Revision ID: 424f18f4c1df Revises: 106e3631fe9 Create Date: 2015-06-23 11:31:08.548661 """ # revision identifiers, used by Alembic. revision = '424f18f4c1df' down_revision = '106e3631fe9' from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql from sqlalchemy.diale...
(): ### commands auto generated by Alembic - please adjust! ### providers_list.create(op.get_bind(), checkfirst=False) op.create_table('auth_providers', sa.Column('id', sa.Integer(), nullable=False), sa.Column('provider', providers_list, nullable=True), ...
upgrade
identifier_name
ostriz.py
from artifactor import ArtifactorBasePlugin import requests import json def overall_test_status(statuses): # Handle some logic for when to count certain tests as which state for when, status in statuses.iteritems(): if when == "call" and status[1] and status[0] == "skipped": return "xfaile...
test_ident = "{}/{}".format(test_location, test_name) json_data = artifacts[test_ident] json_data['name'] = test_ident json_data['run'] = run_id json_data['slaveid'] = slaveid json_data['source'] = self.data['source'] json_data['version'] = version json_data['buil...
identifier_body
ostriz.py
from artifactor import ArtifactorBasePlugin import requests import json def overall_test_status(statuses): # Handle some logic for when to count certain tests as which state for when, status in statuses.iteritems(): if when == "call" and status[1] and status[0] == "skipped": return "xfaile...
return "skipped" elif when == "call" and status[0] == 'failed': return "failed" return "passed" class Ostriz(ArtifactorBasePlugin): def plugin_initialize(self): self.register_plugin_hook('ostriz_send', self.ostriz_send) def configure(self): self.url = self...
return "error" elif status[0] == "skipped":
random_line_split
ostriz.py
from artifactor import ArtifactorBasePlugin import requests import json def overall_test_status(statuses): # Handle some logic for when to count certain tests as which state for when, status in statuses.iteritems(): if when == "call" and status[1] and status[0] == "skipped": return "xfaile...
return "passed" class Ostriz(ArtifactorBasePlugin): def plugin_initialize(self): self.register_plugin_hook('ostriz_send', self.ostriz_send) def configure(self): self.url = self.data.get('url', None) self.configured = True @ArtifactorBasePlugin.check_configured def ostri...
return "failed"
conditional_block
ostriz.py
from artifactor import ArtifactorBasePlugin import requests import json def overall_test_status(statuses): # Handle some logic for when to count certain tests as which state for when, status in statuses.iteritems(): if when == "call" and status[1] and status[0] == "skipped": return "xfaile...
(self, artifacts, test_location, test_name, slaveid, run_id, version, build, stream): test_ident = "{}/{}".format(test_location, test_name) json_data = artifacts[test_ident] json_data['name'] = test_ident json_data['run'] = run_id json_data['slaveid'] = slaveid ...
ostriz_send
identifier_name
baps3-load.rs
#![feature(plugin)] extern crate baps3_protocol; #[macro_use] extern crate baps3_cli; extern crate "rustc-serialize" as rustc_serialize; extern crate docopt; #[plugin] #[no_link] extern crate docopt_macros; use std::borrow::ToOwned; use std::os; use std::path; use baps3_cli::{ Baps3, Baps3Error, Baps3Result, verbos...
))); try!(baps3.send(&Message::new("load").arg(&*ap))); if flag_play { try!(baps3.send(&Message::new("play"))); } Ok(()) } /// Converts a potentially-relative path string to an absolute path string. fn to_absolute_path_str(rel: &str) -> Baps3Result<String> { // This is a convoluted, enta...
{ vec!["FileLoad"] }
conditional_block
baps3-load.rs
#![feature(plugin)] extern crate baps3_protocol; #[macro_use] extern crate baps3_cli; extern crate "rustc-serialize" as rustc_serialize; extern crate docopt; #[plugin] #[no_link] extern crate docopt_macros; use std::borrow::ToOwned; use std::os; use std::path; use baps3_cli::{ Baps3, Baps3Error, Baps3Result, verbos...
use baps3_protocol::proto::Message; docopt!(Args, " Loads a file into a BAPS3 server. Usage: baps3-load -h baps3-load [-pv] [-t <target>] <file> Options: -h, --help Show this message. -p, --play If set, play the file upon loading. -v, --verbose Prints a trail of miscellaneo...
random_line_split
baps3-load.rs
#![feature(plugin)] extern crate baps3_protocol; #[macro_use] extern crate baps3_cli; extern crate "rustc-serialize" as rustc_serialize; extern crate docopt; #[plugin] #[no_link] extern crate docopt_macros; use std::borrow::ToOwned; use std::os; use std::path; use baps3_cli::{ Baps3, Baps3Error, Baps3Result, verbos...
() { let args: Args = Args::docopt().decode().unwrap_or_else(|e| e.exit()); load(args).unwrap_or_else(|&:e| werr!("error: {}", e)); }
main
identifier_name
baps3-load.rs
#![feature(plugin)] extern crate baps3_protocol; #[macro_use] extern crate baps3_cli; extern crate "rustc-serialize" as rustc_serialize; extern crate docopt; #[plugin] #[no_link] extern crate docopt_macros; use std::borrow::ToOwned; use std::os; use std::path; use baps3_cli::{ Baps3, Baps3Error, Baps3Result, verbos...
/// Converts a potentially-relative path string to an absolute path string. fn to_absolute_path_str(rel: &str) -> Baps3Result<String> { // This is a convoluted, entangled mess of Results and Options. // I sincerely apologise. let badpath = |&:| Baps3Error::InvalidPath { path: rel.to_owned() }; path:...
{ let ap = try!(to_absolute_path_str(&*arg_file)); let log = |&:s:&str| verbose_logger(flag_verbose, s); let mut baps3 = try!(Baps3::new(log, &*flag_target, &*(if flag_play { vec!["FileLoad", "PlayStop"] } else { vec!["FileLoad"] }))); try!(baps3.send...
identifier_body
che-text-info.directive.ts
/* * Copyright (c) 2015-2017 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Coden...
}
random_line_split
che-text-info.directive.ts
/* * Copyright (c) 2015-2017 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Coden...
}
{ this.restrict = 'E'; this.replace = true; this.transclude = false; this.templateUrl = 'components/widget/text-info/che-text-info.html'; // scope values this.scope = { textValue: '=cheText', hrefValue: '=cheHref', labelName: '@cheLabelName', copyClipboard: '@cheCopyClip...
identifier_body
che-text-info.directive.ts
/* * Copyright (c) 2015-2017 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Coden...
() { this.restrict = 'E'; this.replace = true; this.transclude = false; this.templateUrl = 'components/widget/text-info/che-text-info.html'; // scope values this.scope = { textValue: '=cheText', hrefValue: '=cheHref', labelName: '@cheLabelName', copyClipboard: '@cheCopyC...
constructor
identifier_name
stats.tsx
import * as React from 'react'; export const Stats: React.SFC<any> = ({ data }) => ( <ul className="o-Flex o-Flex--j--sb o-UIList u-center u-system"> <li className="Pane o-Column--4/12 u-p3 u-mr3"> <span className="h2 u-bl">7.3kb</span> <small>Gzip Size</small> </li> <li className="Pane o-C...
);
<small>Rules</small> </li> </ul>
random_line_split
AddFundsSourcePicker.js
import React from 'react'; import PropTypes from 'prop-types'; import gql from 'graphql-tag'; import { FormControl } from 'react-bootstrap'; import { graphql } from 'react-apollo'; import { defineMessages, FormattedMessage } from 'react-intl'; import { get, groupBy } from 'lodash'; import withIntl from '../lib/withIntl...
extends React.Component { static propTypes = { onChange: PropTypes.func, LoggedInUser: PropTypes.object.isRequired, }; constructor(props) { super(props); this.state = { loading: true }; } onChange = async e => { this.props.onChange(e.target.value); }; render() { const hosts = t...
AddFundsSourcePickerForUser
identifier_name
AddFundsSourcePicker.js
import React from 'react'; import PropTypes from 'prop-types'; import gql from 'graphql-tag'; import { FormControl } from 'react-bootstrap'; import { graphql } from 'react-apollo'; import { defineMessages, FormattedMessage } from 'react-intl'; import { get, groupBy } from 'lodash'; import withIntl from '../lib/withIntl...
onChange: PropTypes.func, LoggedInUser: PropTypes.object.isRequired, }; constructor(props) { super(props); this.state = { loading: true }; } onChange = async e => { this.props.onChange(e.target.value); }; render() { const hosts = this.props.LoggedInUser.hostsUserIsAdminOf(); r...
random_line_split
AddFundsSourcePicker.js
import React from 'react'; import PropTypes from 'prop-types'; import gql from 'graphql-tag'; import { FormControl } from 'react-bootstrap'; import { graphql } from 'react-apollo'; import { defineMessages, FormattedMessage } from 'react-intl'; import { get, groupBy } from 'lodash'; import withIntl from '../lib/withIntl...
} } const getSourcesQuery = gql` query PaymentMethod($id: Int!) { PaymentMethod(id: $id) { id fromCollectives { total collectives { id type name slug } } } } `; const addOrganizationsData = graphql(getSourcesQuery, { op...
{ const hosts = this.props.LoggedInUser.hostsUserIsAdminOf(); return ( <div> <FormControl id="sourcePicker" name="template" componentClass="select" placeholder="select" onChange={this.onChange} > <option value="" key="addfsph-00" ...
identifier_body
common.py
""" Common Django settings for the project. See the local, test, and production settings modules for the values used in each environment. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en...
# Application definition DJANGO_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize' ) THIRD_PARTY_APPS = ( ) LOCAL_APPS = ( 'dialer',...
missing_config_values = \ """ You must set the TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, TWILIO_NUMBER, and TWIML_APPLICATION_SID environment variables to run this app. Consult the README for instructions on how to find them. """ raise ImproperlyConfigured(missing_config_values)
conditional_block
common.py
""" Common Django settings for the project. See the local, test, and production settings modules for the values used in each environment. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en...
#} } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.8/howto/static-files/ STATIC_URL = '/static/' STATICFILES...
'PORT': '5432', }, #'default': { #'ENGINE': 'django.db.backends.sqlite3', #'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
random_line_split
CreateRecipe.test.js
import { expect } from 'chai'; import React from 'react'; import { Provider } from 'react-redux'; import { mount } from 'enzyme'; import fakeStore from './fakeStore'; import CreateRecipe from '../../client/components/CreateRecipe.js'; describe('<CreateRecipe />', () => { let wrapper; before('render CreateRecipe'...
yieldField.simulate('change', event2); expect(yieldField.prop('value')).to.equal(15); }); });
random_line_split
ListArtwork.js
import _BidStatus from "./BidStatus" import PropTypes from "prop-types" import block from "bem-cn-lite" import classNames from "classnames" import titleAndYear from "desktop/apps/auction/utils/titleAndYear" import { connect } from "react-redux" import { get } from "lodash" // FIXME: Rewire let BidStatus = _BidStatus ...
<a className={auctionArtworkClasses} key={saleArtwork._id} href={`/artwork/${saleArtwork.id}`} > <div className={b("image")}> <img src={image} alt={title} /> </div> <div className={b("metadata")}> {isAuction ? ( <div className={b("lot-number")}>Lot ...
{ const { saleArtwork, artistDisplay, date, image, isAuction, isClosed, isMobile, lotLabel, sale_message, title, } = props const b = block("auction-page-ListArtwork") const auctionArtworkClasses = classNames(String(b()), { "auction-open": isClosed, }) return isM...
identifier_body
ListArtwork.js
import _BidStatus from "./BidStatus" import PropTypes from "prop-types" import block from "bem-cn-lite" import classNames from "classnames" import titleAndYear from "desktop/apps/auction/utils/titleAndYear" import { connect } from "react-redux" import { get } from "lodash" // FIXME: Rewire let BidStatus = _BidStatus ...
title, } = props const b = block("auction-page-ListArtwork") const auctionArtworkClasses = classNames(String(b()), { "auction-open": isClosed, }) return isMobile ? ( <a className={auctionArtworkClasses} key={saleArtwork._id} href={`/artwork/${saleArtwork.id}`} > <div ...
isAuction, isClosed, isMobile, lotLabel, sale_message,
random_line_split
ListArtwork.js
import _BidStatus from "./BidStatus" import PropTypes from "prop-types" import block from "bem-cn-lite" import classNames from "classnames" import titleAndYear from "desktop/apps/auction/utils/titleAndYear" import { connect } from "react-redux" import { get } from "lodash" // FIXME: Rewire let BidStatus = _BidStatus ...
(props) { const { saleArtwork, artistDisplay, date, image, isAuction, isClosed, isMobile, lotLabel, sale_message, title, } = props const b = block("auction-page-ListArtwork") const auctionArtworkClasses = classNames(String(b()), { "auction-open": isClosed, }) re...
ListArtwork
identifier_name
Text.js
// Copyright 2013 SAP AG. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http: //www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing...
}
random_line_split
Text.js
// Copyright 2013 SAP AG. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http: //www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing...
(part, value) { /* jshint validthis:true */ value = value || this; part = part || {}; part.argumentCount = getArgumentCount(value); part.buffer = util.convert.encode(value, part.useCesu8); return part; } function getByteLength(value) { return Buffer.byteLength(value); } function getArgumentCount(value)...
write
identifier_name
Text.js
// Copyright 2013 SAP AG. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http: //www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing...
{ /* jshint unused:false */ return 1; }
identifier_body
markdown_to_html.py
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import codecs import...
wikilinks = util().WikilinksExtension(build_url) safe_mkdir(os.path.dirname(output_path)) with codecs.open(output_path, 'w', 'utf-8') as output: source_path = os.path.join(get_buildroot(), source) with codecs.open(source_path, 'r', 'utf-8') as source_stream: md_html = util().markdown....
components = label.split('|', 1) if len(components) == 1: return parse_url(label.strip()) else: alias, link = components _, url = parse_url(link.strip()) return alias, url
identifier_body
markdown_to_html.py
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import codecs import...
if self.open and page in roots: show.append(html) if page.provides: for wiki in page.provides: basedir = os.path.join(self.workdir, str(hash(wiki))) process_page((wiki, page), basedir, wiki.wiki.url_builder, wikigenmap, fragment=True) if show: bin...
plaingenmap.add(page, self.workdir, list(css_path))
conditional_block
markdown_to_html.py
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import codecs import...
anchor = match.group(2) or '' if not page: raise TaskError('Invalid markdown link to pants target: "{}". '.format(match.group(1)) + 'Is your page missing a dependency on this target?') alias, url = url_builder(page) return alias, url + anchor els...
page = self.context.build_graph.get_target(address)
random_line_split