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
site.ts
/// <reference path="../../typings/jquery/jquery.d.ts" />
"use strict"; module F { export function get(selector: string): HTMLElement { return <HTMLElement> document.querySelector(selector); } export function getAll(selector: string): NodeListOf<HTMLElement> { return <NodeListOf<HTMLElement>> document.querySelectorAll(selector); } export function formatTranslation...
/// <reference path="../../typings/localForage/localForage.d.ts" /> /// <reference path="../../typings/knockout/knockout.d.ts" />
random_line_split
forgotpasswordpin.js
define([], function () { function processForgotPasswordResult(result) { if (result.Success) {
Dashboard.alert({ message: Globalize.translate('MessageInvalidForgotPasswordPin'), title: Globalize.translate('HeaderPasswordReset') }); return; } return function (view, params) { function onSubmit(e) { ApiClient.ajax({ typ...
var msg = Globalize.translate('MessagePasswordResetForUsers'); msg += '<br/>'; msg += '<br/>'; msg += result.UsersReset.join('<br/>'); Dashboard.alert({ message: msg, title: Globalize.translate('HeaderPasswordReset'), ...
conditional_block
forgotpasswordpin.js
define([], function () { function processForgotPasswordResult(result) { if (result.Success) { var msg = Globalize.translate('MessagePasswordResetForUsers'); msg += '<br/>'; msg += '<br/>'; msg += result.UsersReset.join('<br/>'); Dashboard.ale...
) { ApiClient.ajax({ type: 'POST', url: ApiClient.getUrl('Users/ForgotPassword/Pin'), dataType: 'json', data: { Pin: view.querySelector('#txtPin').value } }).then(processForgotPasswordResult); ...
Submit(e
identifier_name
forgotpasswordpin.js
define([], function () { function processForgotPasswordResult(result) { if (result.Success) { var msg = Globalize.translate('MessagePasswordResetForUsers'); msg += '<br/>'; msg += '<br/>'; msg += result.UsersReset.join('<br/>'); Dashboard.ale...
url: ApiClient.getUrl('Users/ForgotPassword/Pin'), dataType: 'json', data: { Pin: view.querySelector('#txtPin').value } }).then(processForgotPasswordResult); e.preventDefault(); return false; ...
function onSubmit(e) { ApiClient.ajax({ type: 'POST',
random_line_split
forgotpasswordpin.js
define([], function () { function processForgotPasswordResult(result) {
} Dashboard.alert({ message: Globalize.translate('MessageInvalidForgotPasswordPin'), title: Globalize.translate('HeaderPasswordReset') }); return; } return function (view, params) { function onSubmit(e) { ApiClient.ajax({ ...
if (result.Success) { var msg = Globalize.translate('MessagePasswordResetForUsers'); msg += '<br/>'; msg += '<br/>'; msg += result.UsersReset.join('<br/>'); Dashboard.alert({ message: msg, title: Globalize.translate...
identifier_body
colors.py
""" dotcloud.ui.colors - Pythonic wrapper around colorama Usage: colors = Colors() # Format string inlining print '{c.green}->{c.reset} Hello world!'.format(c=colors) # Call print colors.blue('Hello world!') # Wrapper with colors.red: print 'Hello world' """ import sys import c...
(self, color): """ Lookup color by name """ if color is None: return None if not hasattr(colorama.Fore, color.upper()): raise KeyError('Unknown color "{0}"'.format(color)) return getattr(colorama.Fore, color.upper()) def __enter__(self): if self.color...
_lookup_color
identifier_name
colors.py
""" dotcloud.ui.colors - Pythonic wrapper around colorama Usage: colors = Colors() # Format string inlining print '{c.green}->{c.reset} Hello world!'.format(c=colors) # Call print colors.blue('Hello world!') # Wrapper with colors.red: print 'Hello world' """ import sys import c...
if self.color is None: return text return '{color}{text}{reset}'.format( color=self.color, text=text, reset=colorama.Style.RESET_ALL )
identifier_body
colors.py
""" dotcloud.ui.colors - Pythonic wrapper around colorama Usage: colors = Colors() # Format string inlining print '{c.green}->{c.reset} Hello world!'.format(c=colors) # Call print colors.blue('Hello world!') # Wrapper with colors.red: print 'Hello world' """ import sys import c...
if self.disable_colors is None: self.disable_colors = False if sys.stdout.isatty() else True def __getattr__(self, color): if self.disable_colors: return Color(None) color = color.upper() if color in ['DIM', 'BRIGHT']: return getattr(colorama.Styl...
""" self.disable_colors = disable_colors
random_line_split
colors.py
""" dotcloud.ui.colors - Pythonic wrapper around colorama Usage: colors = Colors() # Format string inlining print '{c.green}->{c.reset} Hello world!'.format(c=colors) # Call print colors.blue('Hello world!') # Wrapper with colors.red: print 'Hello world' """ import sys import c...
if color == 'RESET': return colorama.Style.RESET_ALL return Color(color) class Color(object): def __init__(self, color): self.color = self._lookup_color(color) def _lookup_color(self, color): """ Lookup color by name """ if color is None: retur...
return getattr(colorama.Style, color.upper())
conditional_block
encoder.rs
use crate::{Key, Value}; use std::fmt::{self, Write}; use std::sync::atomic::{AtomicUsize, Ordering}; static ENCODER_ID_COUNTER: AtomicUsize = AtomicUsize::new(0); /// Encoder is a mechanism for serializing an attribute set into a specific string /// representation that supports caching, to avoid repeated serializati...
if write!(acc, "{}", key).is_err() { acc.truncate(offset); return acc; } acc.push('='); if write!(acc, "{}", value).is_err() { acc.truncate(offset); return acc; ...
{ acc.push(',') }
conditional_block
encoder.rs
use crate::{Key, Value}; use std::fmt::{self, Write}; use std::sync::atomic::{AtomicUsize, Ordering}; static ENCODER_ID_COUNTER: AtomicUsize = AtomicUsize::new(0); /// Encoder is a mechanism for serializing an attribute set into a specific string /// representation that supports caching, to avoid repeated serializati...
return acc; } acc }) } fn id(&self) -> EncoderId { new_encoder_id() } } /// Build a new default encoder pub fn default_encoder() -> Box<dyn Encoder + Send + Sync> { Box::new(DefaultAttributeEncoder) } /// Build a new encoder id ...
random_line_split
encoder.rs
use crate::{Key, Value}; use std::fmt::{self, Write}; use std::sync::atomic::{AtomicUsize, Ordering}; static ENCODER_ID_COUNTER: AtomicUsize = AtomicUsize::new(0); /// Encoder is a mechanism for serializing an attribute set into a specific string /// representation that supports caching, to avoid repeated serializati...
(&self, attributes: &mut dyn Iterator<Item = (&Key, &Value)>) -> String { attributes .enumerate() .fold(String::new(), |mut acc, (idx, (key, value))| { let offset = acc.len(); if idx > 0 { acc.push(',') } ...
encode
identifier_name
cp-press-dialog.js
/** * Backbone Application File * @internal Obviously, I've dumped all the code into one file. This should probably be broken out into multiple * files and then concatenated and minified but as it's an example, it's all one lumpy file. * @package $.CpDialog.dialog */ /** * @type {Object} JavaScript namespace for...
getFormValues: function(formSelector){ if(typeof formSelector === "undefined"){ formSelector = '.cp-form'; } var $form = this.$(formSelector); var data = {}, parts; $form.find('[name]').each(function(){ var $$ = $(this); var name = /([A-Za-z0-9_]+)\[(.*)\]/.exec( $$.attr('name') ); i...
this.trigger('content-loaded'); },
random_line_split
cp-press-dialog.js
/** * Backbone Application File * @internal Obviously, I've dumped all the code into one file. This should probably be broken out into multiple * files and then concatenated and minified but as it's an example, it's all one lumpy file. * @package $.CpDialog.dialog */ /** * @type {Object} JavaScript namespace for...
} }); return data; }, /** * Closes the modal and cleans up after the instance. * @param e {object} A jQuery-normalized event object. */ close: function ( e ) { "use strict"; e.preventDefault(); this.undelegateEvents(); $( document ).off( "focusin" ); ...
{ for (var i = 0; i < parts.length; i++) { if (i === parts.length - 1) { if( parts[i] === '' ) { // This needs to be an array sub.push(fieldValue); }else { sub[parts[i]] = fieldValue; } }el...
conditional_block
list.d.ts
import { ElementRef, Renderer } from '@angular/core'; import { Config } from '../../config/config'; import { Ion } from '../ion'; import { GestureController } from '../../gestures/gesture-controller'; import { DomController } from '../../util/dom-controller'; /** * The List is a widely used interface element in almost...
extends Ion { private _gestureCtrl; private _domCtrl; private _enableSliding; private _containsSlidingItems; private _slidingGesture; constructor(config: Config, elementRef: ElementRef, renderer: Renderer, _gestureCtrl: GestureController, _domCtrl: DomController); /** * @input {string}...
List
identifier_name
list.d.ts
import { ElementRef, Renderer } from '@angular/core'; import { Config } from '../../config/config'; import { Ion } from '../ion'; import { GestureController } from '../../gestures/gesture-controller'; import { DomController } from '../../util/dom-controller'; /** * The List is a widely used interface element in almost...
*/ sliding: boolean; /** * @private */ containsSlidingItem(contains: boolean): void; private _updateSlidingState(); /** * Close any sliding items that are open. */ closeSlidingItems(): void; /** * @private */ destroy(): void; }
/** * @input {boolean} shouldEnable whether the item-sliding should be enabled or not
random_line_split
shift-various-types.rs
// run-pass // Test that we can do shifts by any integral type. struct Panolpy { i8: i8, i16: i16, i32: i32, i64: i64, isize: isize, u8: u8, u16: u16, u32: u32, u64: u64, usize: usize, } fn
(p: &Panolpy) { assert_eq!(22 >> p.i8, 11); assert_eq!(22 >> p.i16, 11); assert_eq!(22 >> p.i32, 11); assert_eq!(22 >> p.i64, 11); assert_eq!(22 >> p.isize, 11); assert_eq!(22 >> p.u8, 11); assert_eq!(22 >> p.u16, 11); assert_eq!(22 >> p.u32, 11); assert_eq!(22 >> p.u64, 11); as...
foo
identifier_name
shift-various-types.rs
// run-pass // Test that we can do shifts by any integral type.
struct Panolpy { i8: i8, i16: i16, i32: i32, i64: i64, isize: isize, u8: u8, u16: u16, u32: u32, u64: u64, usize: usize, } fn foo(p: &Panolpy) { assert_eq!(22 >> p.i8, 11); assert_eq!(22 >> p.i16, 11); assert_eq!(22 >> p.i32, 11); assert_eq!(22 >> p.i64, 11); ...
random_line_split
PyLocale.py
""" A location-aware script to manage ringer volume """ __author__ = 'Marco Bonifacio <bonifacio.marco@gmail.com>' __license__ = 'MIT License' import android import time # Parameters SSID = {'bonix-lan': 'casa', 'ZENIT SECURED WPA': 'lavoro'} RINGER = {'casa': 5, 'lavoro': 2, 'sconosciuto...
def check_state(droid, state, stateold): """ Check if environment has changed. Args: droid: an Android instance. state: a string, the present state. stateold: a string, the former state. Returns: a binary true if environment has changed. """ if state != stateold: ...
""" Check if wireless network SSID is known. Args: droid: an Android instance. Returns: a string representing a known or unknown environment. """ state = 'sconosciuto' try: lwifi = droid.wifiGetScanResults().result lssid = [w['ssid']for w in lwifi] for s in lssid:...
identifier_body
PyLocale.py
""" A location-aware script to manage ringer volume """ __author__ = 'Marco Bonifacio <bonifacio.marco@gmail.com>' __license__ = 'MIT License' import android import time # Parameters SSID = {'bonix-lan': 'casa', 'ZENIT SECURED WPA': 'lavoro'} RINGER = {'casa': 5, 'lavoro': 2, 'sconosciuto...
(droid): """ Check if wireless network SSID is known. Args: droid: an Android instance. Returns: a string representing a known or unknown environment. """ state = 'sconosciuto' try: lwifi = droid.wifiGetScanResults().result lssid = [w['ssid']for w in lwifi] fo...
check_ssid
identifier_name
PyLocale.py
""" A location-aware script to manage ringer volume """ __author__ = 'Marco Bonifacio <bonifacio.marco@gmail.com>' __license__ = 'MIT License' import android import time # Parameters SSID = {'bonix-lan': 'casa', 'ZENIT SECURED WPA': 'lavoro'} RINGER = {'casa': 5, 'lavoro': 2, 'sconosciuto...
def check_state(droid, state, stateold): """ Check if environment has changed. Args: droid: an Android instance. state: a string, the present state. stateold: a string, the former state. Returns: a binary true if environment has changed. """ if state != stateold: ...
state = SSID[s] except Exception, e: droid.notify('PyLocale', 'Errore: {}'.format(e)) finally: return(state)
random_line_split
PyLocale.py
""" A location-aware script to manage ringer volume """ __author__ = 'Marco Bonifacio <bonifacio.marco@gmail.com>' __license__ = 'MIT License' import android import time # Parameters SSID = {'bonix-lan': 'casa', 'ZENIT SECURED WPA': 'lavoro'} RINGER = {'casa': 5, 'lavoro': 2, 'sconosciuto...
except Exception, e: droid.notify('PyLocale', 'Errore: {}'.format(e)) finally: return(state) def check_state(droid, state, stateold): """ Check if environment has changed. Args: droid: an Android instance. state: a string, the present state. stateold: a string, ...
state = SSID[s]
conditional_block
reactor.rs
use std::io::{Result}; use std::net::ToSocketAddrs; use mio::{Sender, Evented, EventLoop, EventLoopConfig, Token, TimerResult, Timeout}; use reactor_handler::{ReactorHandler}; use context::{Context}; use reactor_ctrl::{ReactorCtrl, ReactorConfig, ReactorState, T...
(&mut self) { self.handler.state = self.state.take(); self.event_loop.run(&mut self.handler).map_err(|_| ()).unwrap(); self.state = self.handler.state.take(); } /// process all incoming and outgoing events in a loop pub fn run_once(&mut self) { self.handler.state = self.stat...
run
identifier_name
reactor.rs
use std::io::{Result}; use std::net::ToSocketAddrs; use mio::{Sender, Evented, EventLoop, EventLoopConfig, Token, TimerResult, Timeout}; use reactor_handler::{ReactorHandler}; use context::{Context}; use reactor_ctrl::{ReactorCtrl, ReactorConfig, ReactorState, T...
.deregister(token) } /// process all incoming and outgoing events in a loop pub fn run(&mut self) { self.handler.state = self.state.take(); self.event_loop.run(&mut self.handler).map_err(|_| ()).unwrap(); self.state = self.handler.state.take(); } /// process all...
/// from the event_loop pub fn deregister(&mut self, token: Token) -> Result<Box<Context>> { ReactorCtrl::new(self.state.as_mut().unwrap(), &mut self.event_loop)
random_line_split
reactor.rs
use std::io::{Result}; use std::net::ToSocketAddrs; use mio::{Sender, Evented, EventLoop, EventLoopConfig, Token, TimerResult, Timeout}; use reactor_handler::{ReactorHandler}; use context::{Context}; use reactor_ctrl::{ReactorCtrl, ReactorConfig, ReactorState, T...
/// fetch the event_loop channel for notifying the event_loop of new outbound data pub fn channel(&self) -> Sender<TaggedBuf> { self.event_loop.channel() } /// Set a timeout to be executed by the event loop after duration milliseconds /// The supplied handler, which is a FnMut will be inv...
{ ReactorCtrl::new(self.state.as_mut().unwrap(), &mut self.event_loop) .listen(addr, handler) }
identifier_body
recursive_link_results.py
''' usage: scrapy runspider recursive_link_results.py (or from root folder: scrapy crawl scrapy_spyder_recursive) ''' #from scrapy.spider import Spider from scrapy.selector import Selector from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor from scrapy.http import Reque...
to_page = PageItem.django_model.objects.get(url=tourl) to_id = to_page.id #newlink if not LinkItem.django_model.objects.filter(from_id=from_id).filter(to_id=to_id).exists(): newlink = LinkItem() newlink['searchterm'] = search_item n...
#get from_id,to_id from_page = PageItem.django_model.objects.get(url=fromurl) from_id = from_page.id
random_line_split
recursive_link_results.py
''' usage: scrapy runspider recursive_link_results.py (or from root folder: scrapy crawl scrapy_spyder_recursive) ''' #from scrapy.spider import Spider from scrapy.selector import Selector from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor from scrapy.http import Reque...
(CrawlSpider): # Parameters set used for spider crawling name = 'scrapy_spider_recursive' def __init__(self,url_list,search_id):#specified by -a #REMARK is allowed_domains is not set then ALL are allowed self.start_urls = url_list.split(',') self.search_id = int(search_id)...
Search
identifier_name
recursive_link_results.py
''' usage: scrapy runspider recursive_link_results.py (or from root folder: scrapy crawl scrapy_spyder_recursive) ''' #from scrapy.spider import Spider from scrapy.selector import Selector from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor from scrapy.http import Reque...
contents = sel.xpath('/html/head/meta[@name="description"]/@content').extract() content = ' '.join([c.encode('utf-8') for c in contents]).strip() fromurl = response.request.headers['Referer'] tourl = response.url depth = response.request.meta['depth'] ...
title = title[0].encode('utf-8')
conditional_block
recursive_link_results.py
''' usage: scrapy runspider recursive_link_results.py (or from root folder: scrapy crawl scrapy_spyder_recursive) ''' #from scrapy.spider import Spider from scrapy.selector import Selector from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor from scrapy.http import Reque...
newpage['title'] = title newpage['content'] = content newpage['url'] = tourl newpage['depth'] = depth newpage.save()#cant use pipeline cause the execution can finish here print fromurl,'--title:',title,'-',response.url,' depth:',depth ...
sel = Selector(response) ## Get meta info from website title = sel.xpath('//title/text()').extract() if len(title)>0: title = title[0].encode('utf-8') contents = sel.xpath('/html/head/meta[@name="description"]/@content').extract() content = ' '.j...
identifier_body
webpack.config.js
var webpack = require('webpack'); var path = require('path'); const ExtractTextPlugin = require("extract-text-webpack-plugin"); const extractLess = new ExtractTextPlugin({ filename: "[name].[contenthash].css", disable: process.env.NODE_ENV === "development" }); module.exports = { context: path.join(__dirn...
test: /\.scss$/, loader: "style-loader!css-loader!sass-loader" }, { test: /\.jpg$/, use: ["file-loader"] }, { test: /\.png$/, use: ["url-loader?mimetype=image/png"] }, ...
}, {
random_line_split
PageTracker.js
var PageChain = function(){ this.currentPointer = -1; this.chain = []; }; PageChain.prototype.add = function (page) { if(this.chain.length >= 1)
this.chain.push(page); this.currentPointer += 1; }; PageChain.prototype.goBack = function(){ var current = this.currentPointer; this.currentPointer -= 1; this.revivePage(current, this.currentPointer); }; PageChain.prototype.goForward = function(){ var current = this.currentPointer; this.currentPointer += ...
{ // the first page is where simulation starts for (var i = 0; i < this.chain.length; i++) { if(_.isEqual(this.chain[i], page)){ this.currentPointer = i; return; } } }
conditional_block
PageTracker.js
var PageChain = function(){ this.currentPointer = -1; this.chain = []; }; PageChain.prototype.add = function (page) { if(this.chain.length >= 1){ // the first page is where simulation starts for (var i = 0; i < this.chain.length; i++) { if(_.isEqual(this.chain[i], page)){ this.currentPointer = i; retur...
this.revivePage(current, this.currentPointer); }; PageChain.prototype.goForward = function(){ var current = this.currentPointer; this.currentPointer += 1; this.revivePage(current, this.currentPointer); }; PageChain.prototype.revivePage = function(current, newPage){ this.chain[current].sleep(); this.chain[ne...
PageChain.prototype.goBack = function(){ var current = this.currentPointer; this.currentPointer -= 1;
random_line_split
whenMessageEndsWith.test.ts
import { MessageHandler } from "../src"; import { MessageMock } from "./__mocks__/message-mock"; describe("MessageHandler.whenMessageEndsWith test", () => { test("whenMessageEndsWith should fire", () => { // Given const handler = new MessageHandler(); const callback = jest.fn() hand...
// Then expect(callback).toHaveBeenCalled(); }); test("whenMessageEndsWith should not fire", () => { // Given const handler = new MessageHandler(); const callback = jest.fn() handler.whenMessageEndsWith("foo").do(callback) // When const message =...
random_line_split
mobile-index-route.js
define("ghost/routes/mobile-index-route", ["ghost/utils/mobile","exports"], function(__dependency1__, __exports__) { "use strict"; var mobileQuery = __dependency1__["default"]; // Routes that extend MobileIndexRoute need to implement
var MobileIndexRoute = Ember.Route.extend({ desktopTransition: Ember.K, activate: function attachDesktopTransition() { this._super(); mobileQuery.addListener(this.desktopTransitionMQ); }, deactivate: function removeDesktopTransition() { t...
// desktopTransition, a function which is called when // the user resizes to desktop levels.
random_line_split
mobile-index-route.js
define("ghost/routes/mobile-index-route", ["ghost/utils/mobile","exports"], function(__dependency1__, __exports__) { "use strict"; var mobileQuery = __dependency1__["default"]; // Routes that extend MobileIndexRoute need to implement // desktopTransition, a function which is called when /...
}); }.on('init') }); __exports__["default"] = MobileIndexRoute; });
{ self.desktopTransition(); }
conditional_block
borrowck-multiple-captures.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
thread::spawn(move|| { drop(x); //~ ERROR cannot move `x` into closure because it is borrowed drop(x); //~ ERROR use of moved value: `x` }); borrow(&*p); } fn same_var_after_move() { let x: Box<_> = box 1; drop(x); thread::spawn(move|| { drop(x); //~ ERROR capture of mov...
let x: Box<_> = box 1; let p = &x;
random_line_split
borrowck-multiple-captures.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { different_vars_after_borrows(); different_vars_after_moves(); same_var_after_borrow(); same_var_after_move(); }
main
identifier_name
borrowck-multiple-captures.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn same_var_after_borrow() { let x: Box<_> = box 1; let p = &x; thread::spawn(move|| { drop(x); //~ ERROR cannot move `x` into closure because it is borrowed drop(x); //~ ERROR use of moved value: `x` }); borrow(&*p); } fn same_var_after_move() { let x: Box<_> = box 1; dro...
{ let x1: Box<_> = box 1; drop(x1); let x2: Box<_> = box 2; drop(x2); thread::spawn(move|| { drop(x1); //~ ERROR capture of moved value: `x1` drop(x2); //~ ERROR capture of moved value: `x2` }); }
identifier_body
sysconfig.py
build" in _PROJECT_BASE[-8:].lower(): _PROJECT_BASE = _safe_realpath(os.path.join(_PROJECT_BASE, pardir)) # PC/VS7.1 if os.name == "nt" and "\\pc\\v" in _PROJECT_BASE[-10:].lower(): _PROJECT_BASE = _safe_realpath(os.path.join(_PROJECT_BASE, pardir, pardir)) # PC/AMD64 if os.name == "nt" and "\\pcbuild\\am...
def get_makefile_filename(): """Return the path of the Makefile.""" if _PYTHON_BUILD: return os.path.join(_PROJECT_BASE, "Makefile") return os.path.join(get_path('platstdlib'), "config", "Makefile") # Issue #22199: retain undocumented private name for compatibility _get_makefile_filename...
done[k] = v.strip() # save the results in the global dictionary vars.update(done) return vars
random_line_split
sysconfig.py
build" in _PROJECT_BASE[-8:].lower(): _PROJECT_BASE = _safe_realpath(os.path.join(_PROJECT_BASE, pardir)) # PC/VS7.1 if os.name == "nt" and "\\pc\\v" in _PROJECT_BASE[-10:].lower(): _PROJECT_BASE = _safe_realpath(os.path.join(_PROJECT_BASE, pardir, pardir)) # PC/AMD64 if os.name == "nt" and "\\pcbuild\\am...
(target_dict, other_dict): target_keys = target_dict.keys() for key, value in other_dict.items(): if key in target_keys: continue target_dict[key] = value def _expand_vars(scheme, vars): res = {} if vars is None: vars = {} _extend_dict(vars, get_config...
_extend_dict
identifier_name
sysconfig.py
build" in _PROJECT_BASE[-8:].lower(): _PROJECT_BASE = _safe_realpath(os.path.join(_PROJECT_BASE, pardir)) # PC/VS7.1 if os.name == "nt" and "\\pc\\v" in _PROJECT_BASE[-10:].lower(): _PROJECT_BASE = _safe_realpath(os.path.join(_PROJECT_BASE, pardir, pardir)) # PC/AMD64 if os.name == "nt" and "\\pcbuild\\am...
# do variable interpolation here while notdone: for name in notdone.keys(): value = notdone[name] m = _findvar1_rx.search(value) or _findvar2_rx.search(value) if m: n = m.group(1) found = True if n in done: ...
if line.startswith('#') or line.strip() == '': continue m = _variable_rx.match(line) if m: n, v = m.group(1, 2) v = v.strip() # `$$' is a literal `$' in make tmpv = v.replace('$$', '') if "$" in tmpv: notd...
conditional_block
sysconfig.py
build" in _PROJECT_BASE[-8:].lower(): _PROJECT_BASE = _safe_realpath(os.path.join(_PROJECT_BASE, pardir)) # PC/VS7.1 if os.name == "nt" and "\\pc\\v" in _PROJECT_BASE[-10:].lower(): _PROJECT_BASE = _safe_realpath(os.path.join(_PROJECT_BASE, pardir, pardir)) # PC/AMD64 if os.name == "nt" and "\\pcbuild\\am...
# what about 'os2emx', 'riscos' ? if os.name == "nt": base = os.environ.get("APPDATA") or "~" return env_base if env_base else joinuser(base, "Python") if sys.platform == "darwin": framework = get_config_var("PYTHONFRAMEWORK") if framework: return env...
return os.path.expanduser(os.path.join(*args))
identifier_body
strings.js
"addGeocoder": "Dodaj geokoder", "geocoder": "Geokoder", "setLayerSource": "Postavi izvor sloja", "setGeocoderURL": "Postavi URL adresu geokôdera", "searchableLayer": "Sloj geoobjekata", "name": "Naziv", "countryCode": "Kôd(ovi) zemlje ili regiona", "countryCodeEg": "npr. ", "countryCodeHint": "Ako ov...
define({ "sourceSetting": "Pretraži postavke izvora", "instruction": "Dodaj i konfiguriši servise za geokodiranje ili slojeve geoobjekata kao izvore pretrage. Ovi navedeni izvori određuju šta može da se pretražuje unutar trake za pretragu.", "add": "Dodaj izvor pretrage",
random_line_split
TimePickerContent.tsx
{ css, cx } from 'emotion'; import React, { memo, useState } from 'react'; import { useMedia } from 'react-use'; import { stylesFactory, useTheme } from '../../../themes'; import { CustomScrollbar } from '../../CustomScrollbar/CustomScrollbar'; import { Icon } from '../../Icon/Icon'; import { mapRangeToTimeOption } fr...
value={props.value} onApply={props.onChange} timeZone={props.timeZone} isFullscreen={false} /> </div> {props.showHistory && ( <TimeRangeList title="Recently used absolute ranges" options={prop...
{collapsed && ( <div className={styles.body}> <div className={styles.form}> <TimeRangeForm
random_line_split
TimePickerContent.tsx
css, cx } from 'emotion'; import React, { memo, useState } from 'react'; import { useMedia } from 'react-use'; import { stylesFactory, useTheme } from '../../../themes'; import { CustomScrollbar } from '../../CustomScrollbar/CustomScrollbar'; import { Icon } from '../../Icon/Icon'; import { mapRangeToTimeOption } from...
const theme = useTheme(); const styles = getNarrowScreenStyles(theme); const isAbsolute = isDateTime(props.value.raw.from) || isDateTime(props.value.raw.to); const [collapsed, setCollapsed] = useState(isAbsolute); return ( <> <div aria-label="TimePicker absolute time range" classN...
{ return null; }
conditional_block
submittable-textarea-test.js
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; import pageComponent from 'code-corps-ember/tests/pages/components/submittable-textarea'; import PageObject from 'ember-cli-page-object'; let page = PageObject.create(pageComponent); function
(context, modifiedSubmitHandler = () => {}) { context.set('modifiedSubmitHandler', modifiedSubmitHandler); } moduleForComponent('submittable-textarea', 'Integration | Component | submittable textarea', { integration: true, beforeEach() { page.setContext(this); setHandler(this); }, afterEach() { p...
setHandler
identifier_name
submittable-textarea-test.js
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; import pageComponent from 'code-corps-ember/tests/pages/components/submittable-textarea'; import PageObject from 'ember-cli-page-object'; let page = PageObject.create(pageComponent); function setHandler(context, modi...
, afterEach() { page.removeContext(); } }); // This test is necessary because a new line after yield in the file will // cause a new line in the textarea itself test('it has no extra content when created', function(assert) { this.render(hbs`{{submittable-textarea modifiedSubmit=modifiedSubmitHandler}}`); a...
{ page.setContext(this); setHandler(this); }
identifier_body
submittable-textarea-test.js
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; import pageComponent from 'code-corps-ember/tests/pages/components/submittable-textarea'; import PageObject from 'ember-cli-page-object'; let page = PageObject.create(pageComponent); function setHandler(context, modi...
setHandler(this, () => { assert.equal(page.value, '', 'Action was called. Input content was unchanged.'); }); this.render(hbs`{{submittable-textarea modifiedSubmit=modifiedSubmitHandler}}`); page.keySubmit(); });
random_line_split
Form.js
/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/d...
}, this); //////////////////////////////////// } } });
{ alert("You are sending: " + qx.util.Serializer.toUriParameter(model, qxSerializer)); }
conditional_block
Form.js
/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2009 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/d...
* @tag databinding * @tag validation * @tag serialization */ qx.Class.define("demobrowser.demo.data.Form", { extend : qx.application.Standalone, members : { main: function() { this.base(arguments); // create the UI /////////////////// // groupbox var groupBox = new qx.ui.gro...
/** * @lint ignoreDeprecated(alert)
random_line_split
cloudlet_edge_redirector.py
#! /usr/bin/env python # Very basic script template. Use this to build new # examples for use in the api-kickstart repository # """ Copyright 2015 Akamai Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the L...
# "cloudletId": 0, # "cloudletCode": "ER", # "capabilities": [ # "View", # "Edit", # "Activate", # "Internal", # "AdvancedEdit" # ] # }, sample_post_body = { "cloudletId": 0, "groupId": 77649, "name": "APIBootca...
endpoint_result = httpCaller.getResult("/cloudlets/api/v2/cloudlet-info") # Result for edge redirector: # { # "location": "/cloudlets/api/v2/cloudlet-info/2", # "cloudletId": 2, # "cloudletCode": "SA", # "apiVersion": "2.0", # "cloudletName": "SAASACCESS" #}, # Get the group ID for the c...
conditional_block
cloudlet_edge_redirector.py
#! /usr/bin/env python # Very basic script template. Use this to build new # examples for use in the api-kickstart repository # """ Copyright 2015 Akamai Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the L...
) # Set the baseurl based on config.host baseurl = '%s://%s/' % ('https', config.host) httpCaller = EdgeGridHttpCaller(session, debug, verbose, baseurl) if __name__ == "__main__": # Get the list of cloudlets to pick the one we want to use endpoint_result = httpCaller.getResult("/cloudlets/api/v2/cloudlet-info") ...
client_secret=config.client_secret, access_token=config.access_token
random_line_split
stdlib.js
var NULL = null; function NOP() {} function NOT_IMPLEMENTED() { throw new Error("not implemented."); } function
(x) { return x|0; } function pointer(src, offset, length) { offset = src.byteOffset + offset * src.BYTES_PER_ELEMENT; if (typeof length === "number") { return new src.constructor(src.buffer, offset, length); } else { return new src.constructor(src.buffer, offset); } } var uint8 = 0; var int32 = 1; ...
int
identifier_name
stdlib.js
var NULL = null; function NOP() {} function NOT_IMPLEMENTED() { throw new Error("not implemented."); } function int(x) { return x|0; } function pointer(src, offset, length) { offset = src.byteOffset + offset * src.BYTES_PER_ELEMENT; if (typeof length === "number") { return new src.constructor(src.buffer, o...
var ret = new src.constructor(newSize); ret.set(src); return ret; } function copy(dst, src, offset) { dst.set(src, offset||0); }
function realloc(src, newSize) {
random_line_split
stdlib.js
var NULL = null; function NOP() {} function NOT_IMPLEMENTED() { throw new Error("not implemented."); } function int(x) { return x|0; } function pointer(src, offset, length)
var uint8 = 0; var int32 = 1; function calloc(n, type) { switch (type) { case uint8: return new Uint8Array(n); case int32: return new Int32Array(n); } throw new Error("calloc failed."); } function realloc(src, newSize) { var ret = new src.constructor(newSize); ret.set(src); return ret; } function c...
{ offset = src.byteOffset + offset * src.BYTES_PER_ELEMENT; if (typeof length === "number") { return new src.constructor(src.buffer, offset, length); } else { return new src.constructor(src.buffer, offset); } }
identifier_body
stdlib.js
var NULL = null; function NOP() {} function NOT_IMPLEMENTED() { throw new Error("not implemented."); } function int(x) { return x|0; } function pointer(src, offset, length) { offset = src.byteOffset + offset * src.BYTES_PER_ELEMENT; if (typeof length === "number") { return new src.constructor(src.buffer, o...
} var uint8 = 0; var int32 = 1; function calloc(n, type) { switch (type) { case uint8: return new Uint8Array(n); case int32: return new Int32Array(n); } throw new Error("calloc failed."); } function realloc(src, newSize) { var ret = new src.constructor(newSize); ret.set(src); return ret; } function...
{ return new src.constructor(src.buffer, offset); }
conditional_block
lexer.py
# ----------------------------------------------------------------------------- # lexer.py # # A simple calculator with variables -- all in one file. # ----------------------------------------------------------------------------- reserved = { 'class':'CLASS', 'block':'BLOCK', 'event':'EVENT', 'transiti...
data += line #print(data) lex.input(data) #while True: # tok = lex.token() # print(tok) # if not tok: break
break
conditional_block
lexer.py
# ----------------------------------------------------------------------------- # lexer.py # # A simple calculator with variables -- all in one file. # ----------------------------------------------------------------------------- reserved = { 'class':'CLASS', 'block':'BLOCK', 'event':'EVENT', 'transiti...
def t_IDENTIFIER(t): r'[a-zA-Z_][a-zA-Z_0-9]*' t.type = reserved.get(t.value,'IDENTIFIER') # Check for reserved words t.value = t.value return t def t_error(t): print("lexer : Illegal character '%s'" % t.value[0]) t.lexer.skip(1) # Build the lexer import ply.lex as lex lex.lex() file =...
r'\n+' t.lexer.lineno += t.value.count("\n")
identifier_body
lexer.py
# ----------------------------------------------------------------------------- # lexer.py # # A simple calculator with variables -- all in one file. # ----------------------------------------------------------------------------- reserved = { 'class':'CLASS', 'block':'BLOCK', 'event':'EVENT', 'transiti...
(t): print("lexer : Illegal character '%s'" % t.value[0]) t.lexer.skip(1) # Build the lexer import ply.lex as lex lex.lex() file = open("../data/automate.txt") data='' while 1: line = file.readline() if not line: break data += line #print(data) lex.input(data) #while True: # tok = le...
t_error
identifier_name
lexer.py
# ----------------------------------------------------------------------------- # lexer.py # # A simple calculator with variables -- all in one file. # ----------------------------------------------------------------------------- reserved = { 'class':'CLASS', 'block':'BLOCK', 'event':'EVENT', 'transiti...
t.type = reserved.get(t.value,'IDENTIFIER') # Check for reserved words t.value = t.value return t def t_error(t): print("lexer : Illegal character '%s'" % t.value[0]) t.lexer.skip(1) # Build the lexer import ply.lex as lex lex.lex() file = open("../data/automate.txt") data='' while 1: li...
t.lexer.lineno += t.value.count("\n") def t_IDENTIFIER(t): r'[a-zA-Z_][a-zA-Z_0-9]*'
random_line_split
extractor_cansem.py
import argparse import sys import os from annotated_set import loadData from data_structures import CanonicalDerivation from canonical_parser import CanonicalParser from derivation_tree import DerivationTree from conversion.ghkm2tib import ghkm2tib #from lib.amr.dag import Dag class ExtractorCanSem: def __init_...
parse_file.close() align_file.close() text_file.close() print "Running GHKM Java rule extraction" mem = "2g" ghkm_opts = "-fCorpus %s -eParsedCorpus %s -align %s -joshuaFormat false -maxLHS 200 -maxRHS 15 -MaxUnalignedRHS 15" % (args.text_path,args.parse_path,args.alig...
x = DerivationTree.fromDerivation(d) parse,align = x.getGHKMtriple_Java() text = s["nl"].strip(' \t\n\r') parse_file.write("%s\n"%parse) align_file.write("%s\n"%align) text_file.write("%s\n"%text)
conditional_block
extractor_cansem.py
import argparse import sys import os from annotated_set import loadData from data_structures import CanonicalDerivation from canonical_parser import CanonicalParser from derivation_tree import DerivationTree from conversion.ghkm2tib import ghkm2tib #from lib.amr.dag import Dag class ExtractorCanSem: def __init_...
def main(self, *args): parser = argparse.ArgumentParser(description='CanSem Extraction Algorithm for SHRG', fromfile_prefix_chars='@', prog='%s extract-cansem'%sys.argv[0]) parser.add_argument('nl_file', type=str, h...
""" Returns CanSem help message. """ return ExtractorCanSem.main(ExtractorCanSem(),"--help")
identifier_body
extractor_cansem.py
import argparse import sys import os from annotated_set import loadData from data_structures import CanonicalDerivation from canonical_parser import CanonicalParser from derivation_tree import DerivationTree from conversion.ghkm2tib import ghkm2tib #from lib.amr.dag import Dag class ExtractorCanSem: def __init_...
return ExtractorCanSem.main(ExtractorCanSem(),"--help") def main(self, *args): parser = argparse.ArgumentParser(description='CanSem Extraction Algorithm for SHRG', fromfile_prefix_chars='@', prog='%s extract-cansem'%s...
Returns CanSem help message. """
random_line_split
extractor_cansem.py
import argparse import sys import os from annotated_set import loadData from data_structures import CanonicalDerivation from canonical_parser import CanonicalParser from derivation_tree import DerivationTree from conversion.ghkm2tib import ghkm2tib #from lib.amr.dag import Dag class ExtractorCanSem: def __init_...
(self, *args): parser = argparse.ArgumentParser(description='CanSem Extraction Algorithm for SHRG', fromfile_prefix_chars='@', prog='%s extract-cansem'%sys.argv[0]) parser.add_argument('nl_file', type=str, help="Natural L...
main
identifier_name
leftnav.client.controller.js
'use strict'; angular.module(ApplicationConfiguration.applicationModuleName).controller('LeftNavController', function(Authentication, $mdSidenav, Menus, $log) { this.authentication = Authentication; this.isCollapsed = false; this.menu = Menus.getMenu('sidenav'); this.selected = ''; this.isSelected = functi...
}; //this.toggleCollapsibleMenu = function() { // this.isCollapsed = !this.isCollapsed; //}; // //// Collapsing the menu after navigation //this.$on('$stateChangeSuccess', function() { // this.isCollapsed = false; //}); // //this.toggleMenu = function() { // $mdSidenav('left').toggl...
random_line_split
expr-if-struct.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn test_rec() { let rs = if true { I {i: 100} } else { I {i: 101} }; assert_eq!(rs.i, 100); } #[derive(Copy, Debug)] enum mood { happy, sad, } impl PartialEq for mood { fn eq(&self, other: &mood) -> bool { ((*self) as uint) == ((*other) as uint) } fn ne(&self, other: &mood) -> bool { !(*se...
random_line_split
expr-if-struct.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn main() { test_rec(); test_tag(); }
{ let rs = if true { mood::happy } else { mood::sad }; assert_eq!(rs, mood::happy); }
identifier_body
expr-if-struct.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let rs = if true { I {i: 100} } else { I {i: 101} }; assert_eq!(rs.i, 100); } #[derive(Copy, Debug)] enum mood { happy, sad, } impl PartialEq for mood { fn eq(&self, other: &mood) -> bool { ((*self) as uint) == ((*other) as uint) } fn ne(&self, other: &mood) -> bool { !(*self).eq(othe...
test_rec
identifier_name
expr-if-struct.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
else { mood::sad }; assert_eq!(rs, mood::happy); } pub fn main() { test_rec(); test_tag(); }
{ mood::happy }
conditional_block
services.py
import oauth2 as oauth import sher.settings as settings import cgi import urlparse import urllib import gdata.youtube import gdata.youtube.service import twitter class TwitterService(object): def __init__(self, consumer_key, consumer_secret): self.consumer_key = consumer_key self.consumer_secret =...
(self, token): """Calls flickrs getToken to obtain a persistent auth token.""" url = self.gen_sig(self.rest_url, api_key=self.api_key, method="flickr.auth.getToken", frob=token) return url def authenticated(self, account, format="etree"): import flickrapi return flickrapi.Fl...
get_auth_token
identifier_name
services.py
import oauth2 as oauth import sher.settings as settings import cgi import urlparse import urllib import gdata.youtube import gdata.youtube.service import twitter class TwitterService(object): def __init__(self, consumer_key, consumer_secret): self.consumer_key = consumer_key self.consumer_secret =...
if resp['status'] != '200': raise Exception("Invalid Response from Twitter") request_token = dict(cgi.parse_qsl(content)) self.request_token = request_token['oauth_token'] self.request_token_secret = request_token['oauth_token_secret'] return self.request_token ...
resp, content = self.client.request(request_token_url, "POST")
random_line_split
services.py
import oauth2 as oauth import sher.settings as settings import cgi import urlparse import urllib import gdata.youtube import gdata.youtube.service import twitter class TwitterService(object): def __init__(self, consumer_key, consumer_secret): self.consumer_key = consumer_key self.consumer_secret =...
request_token = dict(cgi.parse_qsl(content)) self.request_token = request_token['oauth_token'] self.request_token_secret = request_token['oauth_token_secret'] return self.request_token def get_access_token(self, oauth_verifier): access_token_url = self.access_token_url ...
raise Exception("Invalid Response from Twitter")
conditional_block
services.py
import oauth2 as oauth import sher.settings as settings import cgi import urlparse import urllib import gdata.youtube import gdata.youtube.service import twitter class TwitterService(object): def __init__(self, consumer_key, consumer_secret): self.consumer_key = consumer_key self.consumer_secret =...
def get_authsub_url(self, callback): next = callback scope = "http://gdata.youtube.com" secure = False session = True return self.yt_service.GenerateAuthSubURL(next, scope, secure, session) def upgrade_to_session(self, token): """ Takes an authsub toke...
self.developer_key = developer_key self.client_id = client_id self.yt_service = gdata.youtube.service.YouTubeService()
identifier_body
logsettings.py
"""Get log settings.""" import os import platform import sys from logging.handlers import SysLogHandler LOG_LEVELS = ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'] def
(log_dir, logging_env="no_env", tracking_filename="tracking.log", edx_filename="edx.log", dev_env=False, syslog_addr=None, debug=False, local_loglevel='INFO', ...
get_logger_config
identifier_name
logsettings.py
"""Get log settings.""" import os import platform import sys from logging.handlers import SysLogHandler LOG_LEVELS = ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'] def get_logger_config(log_dir, logging_env="no_env", tracking_filename="tracking.log", ...
if console_loglevel is None or console_loglevel not in LOG_LEVELS: console_loglevel = 'DEBUG' if debug else 'INFO' if service_variant is None: # default to a blank string so that if SERVICE_VARIANT is not # set we will not log to a sub directory service_variant = '' hostnam...
""" Return the appropriate logging config dictionary. You should assign the result of this to the LOGGING var in your settings. The reason it's done this way instead of registering directly is because I didn't want to worry about resetting the logging state if this is called multiple times when set...
identifier_body
logsettings.py
"""Get log settings.""" import os import platform import sys from logging.handlers import SysLogHandler LOG_LEVELS = ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'] def get_logger_config(log_dir, logging_env="no_env", tracking_filename="tracking.log", ...
this way instead of registering directly is because I didn't want to worry about resetting the logging state if this is called multiple times when settings are extended. If dev_env is set to true logging will not be done via local rsyslogd, instead, tracking and application logs will be dropped in ...
result of this to the LOGGING var in your settings. The reason it's done
random_line_split
logsettings.py
"""Get log settings.""" import os import platform import sys from logging.handlers import SysLogHandler LOG_LEVELS = ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'] def get_logger_config(log_dir, logging_env="no_env", tracking_filename="tracking.log", ...
return logger_config
logger_config['loggers']['']['level'] = 'INFO' logger_config['handlers'].update({ 'local': { 'level': local_loglevel, 'class': 'logging.handlers.SysLogHandler', 'address': '/dev/log', 'formatter': 'syslog_format', 'facil...
conditional_block
sigfig.py
from math import floor, log10 def round_(x, n): """Round a float, x, to n significant figures. Caution should be applied when performing this operation. Significant figures are an implication of precision; arbitrarily truncating floats mid-calculation is probably not Good Practice in almost all cases. Rounding...
return ''.join(('{:.', str(n - 1), 'e}')).format(x) def general(x, n): """Represent a float in general form. This function is merely a wrapper around the 'g' type flag in the formatting specification. """ n = int(n) x = float(x) if n < 1: raise ValueError("1+ significant digits required.") return ''.joi...
raise ValueError("1+ significant digits required.")
conditional_block
sigfig.py
from math import floor, log10 def round_(x, n): """Round a float, x, to n significant figures. Caution should be applied when performing this operation. Significant figures are an implication of precision; arbitrarily truncating floats mid-calculation is probably not Good Practice in almost all cases. Rounding...
def general(x, n): """Represent a float in general form. This function is merely a wrapper around the 'g' type flag in the formatting specification. """ n = int(n) x = float(x) if n < 1: raise ValueError("1+ significant digits required.") return ''.join(('{:#.', str(n), 'g}')).format(x)
"""Represent a float in scientific notation. This function is merely a wrapper around the 'e' type flag in the formatting specification. """ n = int(n) x = float(x) if n < 1: raise ValueError("1+ significant digits required.") return ''.join(('{:.', str(n - 1), 'e}')).format(x)
identifier_body
sigfig.py
from math import floor, log10 def round_(x, n): """Round a float, x, to n significant figures. Caution should be applied when performing this operation. Significant figures are an implication of precision; arbitrarily truncating floats mid-calculation is probably not Good Practice in almost all cases. Rounding...
x = float(x) if n < 1: raise ValueError("1+ significant digits required.") # retrieve the significand and exponent from the S.N. form s, e = ''.join(( '{:.', str(n - 1), 'e}')).format(x).split('e') e = int(e) # might as well coerce now if e == 0: # Significand requires no adjustment return s s = s.replac...
number itself (which is in turn only approximated by a float). """ n = int(n)
random_line_split
sigfig.py
from math import floor, log10 def round_(x, n): """Round a float, x, to n significant figures. Caution should be applied when performing this operation. Significant figures are an implication of precision; arbitrarily truncating floats mid-calculation is probably not Good Practice in almost all cases. Rounding...
(x, n): """Represent a float in scientific notation. This function is merely a wrapper around the 'e' type flag in the formatting specification. """ n = int(n) x = float(x) if n < 1: raise ValueError("1+ significant digits required.") return ''.join(('{:.', str(n - 1), 'e}')).format(x) def general(x, n): ...
scientific
identifier_name
crayon.rs
][wp]. /// /// [wp]: https://en.wikipedia.org/wiki/ANSI_escape_code#Colors #[derive(Debug, Clone, Copy, PartialEq)] pub enum Color { /// Foreground code `30`, background code `40`. Black, /// Foreground code `31`, background code `41`. Red, /// Foreground code `32`, background code `42`. Green...
italic
identifier_name
crayon.rs
`]: struct.Style.html #[derive(Debug, Clone, PartialEq)] pub struct StyledString<'a> { string: Cow<'a, str>, style: Style, } impl<'a> fmt::Display for StyledString<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // TODO: Convert the `try!()` calls to the `?` operator once it is ...
/// Returns a [`Style`] with the 'underline' property set and the foreground /// colour set to this colour. /// /// [`Style`]: struct.Style.html pub fn underline(self) -> Style { Style { foreground: Some(self), underline: true, ..Style::default() } } /// Returns a [`Style`] with t...
{ Style { foreground: Some(self), italic: true, ..Style::default() } }
identifier_body
crayon.rs
Style`]: struct.Style.html #[derive(Debug, Clone, PartialEq)] pub struct StyledString<'a> { string: Cow<'a, str>, style: Style, } impl<'a> fmt::Display for StyledString<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // TODO: Convert the `try!()` calls to the `?` operator once it is ...
pub fn reverse(self) -> Style { Style { foreground: Some(self), reverse: true, ..Style::default() } } /// Returns a [`Style`] with the 'hidden' property set and the foreground /// colour set to this colour. /// /// [`Style`]: struct.Style.html pub fn hidden(self) -> Style { ...
random_line_split
dropdown.d.ts
import * as Popper from "@popperjs/core"; import BaseComponent, { GetInstanceFactory } from './base-component'; declare class Dropdown extends BaseComponent { constructor(element: string | Element, options?: Partial<Dropdown.Options>); /** * Toggles the dropdown menu of a given navbar or tabbed navigatio...
* * @see {@link https://popper.js.org/docs/v2} * @default null */ popperConfig: Partial<Popper.Options> | PopperConfigFunction | null; } type jQueryInterface = (config?: Partial<Options> | "toggle" | "show" | "hide" | "update" | "dispose") => void; } export default ...
random_line_split
dropdown.d.ts
import * as Popper from "@popperjs/core"; import BaseComponent, { GetInstanceFactory } from './base-component'; declare class
extends BaseComponent { constructor(element: string | Element, options?: Partial<Dropdown.Options>); /** * Toggles the dropdown menu of a given navbar or tabbed navigation. */ toggle(): void; /** * Shows the dropdown menu of a given navbar or tabbed navigation. */ show(): void...
Dropdown
identifier_name
gemm3_ab_bc_kernel.rs
extern crate momms; extern crate core; extern crate typenum; extern crate hwloc; extern crate libc; use typenum::{Unsigned}; use std::time::{Instant}; pub use momms::matrix::{ColumnPanelMatrix, Matrix, Mat}; pub use momms::composables::{GemmNode}; pub use momms::algorithms::{Dgemm3, GotoDgemm3, ...
() { let mut chained = Dgemm3::new(); let mut goto = GotoDgemm3::new(); let flusher_len = 4*1024*1024; //32MB let mut flusher: Vec<f64> = Vec::with_capacity(flusher_len); for _ in 0..flusher_len { flusher.push(0.0); } for index in 1..308 {//512 { let mut best_time: f64 = 99...
test_gemm3
identifier_name
gemm3_ab_bc_kernel.rs
extern crate momms; extern crate core; extern crate typenum; extern crate hwloc; extern crate libc; use typenum::{Unsigned}; use std::time::{Instant}; pub use momms::matrix::{ColumnPanelMatrix, Matrix, Mat}; pub use momms::composables::{GemmNode}; pub use momms::algorithms::{Dgemm3, GotoDgemm3, ...
let mut b: Matrix<f64> = Matrix::new(k, l); let mut c: Matrix<f64> = Matrix::new(l, n); let mut d: Matrix<f64> = Matrix::new(m, n); a.fill_rand(); b.fill_rand(); c.fill_rand(); d.fill_zero(); let mut tmp = ColPM::<f64>::new(Dgemm3TmpWidth::to_usize(), ...
{ let mut chained = Dgemm3::new(); let mut goto = GotoDgemm3::new(); let flusher_len = 4*1024*1024; //32MB let mut flusher: Vec<f64> = Vec::with_capacity(flusher_len); for _ in 0..flusher_len { flusher.push(0.0); } for index in 1..308 {//512 { let mut best_time: f64 = 99999...
identifier_body
gemm3_ab_bc_kernel.rs
extern crate momms; extern crate core; extern crate typenum; extern crate hwloc; extern crate libc; use typenum::{Unsigned}; use std::time::{Instant}; pub use momms::matrix::{ColumnPanelMatrix, Matrix, Mat}; pub use momms::composables::{GemmNode}; pub use momms::algorithms::{Dgemm3, GotoDgemm3, ...
let mut flusher: Vec<f64> = Vec::with_capacity(flusher_len); for _ in 0..flusher_len { flusher.push(0.0); } for index in 1..308 {//512 { let mut best_time: f64 = 9999999999.0; let mut best_time_stock: f64 = 9999999999.0; let mut worst_err: f64 = 0.0; let size = i...
let flusher_len = 4*1024*1024; //32MB
random_line_split
Icon.js
/** * @ngdoc directive * @name ui.controls.uiIcon * @description * * uiIcon is used to render font icons. When uiIcon is placed inside a uiButton or uiToolbar it adjusts it's size to * match it's parent size. * * @param {string} name The name of the font icon. * * @restrict E * @example <example module="ui"...
// using Material Icons el.addClass('material-icons'); el.text(value); }); if(!$uiHeight) { $el.addClass('ui-height-md'); return; } $uiHeight.setHeight($...
{ $el.addClass('fa'); $el.addClass(value); return; }
conditional_block
Icon.js
/** * @ngdoc directive * @name ui.controls.uiIcon * @description * * uiIcon is used to render font icons. When uiIcon is placed inside a uiButton or uiToolbar it adjusts it's size to * match it's parent size. * * @param {string} name The name of the font icon. * * @restrict E * @example <example module="ui"...
$uiHeight.setHeight($el); if($uiHeight.getHeight() === 'sd' && $uiHeight.getParentHeight() === 'md') { $el.addClass('ui-fit-md'); } } return { restrict: 'E', require: '?^uiHeight', ...
{ var $el = angular.element(el); $el.addClass('ui-icon'); scope.$watch('name', function (value) { // using font-awesome if (_.startsWith(value, 'fa-')) { $el.addClass('fa'); $el.addCla...
identifier_body
Icon.js
/** * @ngdoc directive * @name ui.controls.uiIcon * @description * * uiIcon is used to render font icons. When uiIcon is placed inside a uiButton or uiToolbar it adjusts it's size to * match it's parent size. * * @param {string} name The name of the font icon. * * @restrict E * @example <example module="ui"...
(scope, el, attr, $uiHeight) { var $el = angular.element(el); $el.addClass('ui-icon'); scope.$watch('name', function (value) { // using font-awesome if (_.startsWith(value, 'fa-')) { $el.addClass('fa'); ...
_link
identifier_name
Icon.js
/** * @ngdoc directive * @name ui.controls.uiIcon * @description * * uiIcon is used to render font icons. When uiIcon is placed inside a uiButton or uiToolbar it adjusts it's size to * match it's parent size. * * @param {string} name The name of the font icon. * * @restrict E * @example <example module="ui"...
}, link: _link, controller: '$uiSizeController' } }]); })(angular.module('thinkingmedia.ui.controls'));
restrict: 'E', require: '?^uiHeight', scope: { name: '@'
random_line_split
add.ts
import $ from 'cafy'; import { ID } from '../../../../../misc/cafy-id'; import define from '../../../define'; import { Users } from '../../../../../models'; export const meta = { desc: { 'ja-JP': '指定したユーザーをモデレーターにします。', 'en-US': 'Mark a user as moderator.' }, tags: ['admin'], requireCredential: true as const...
} }; export default define(meta, async (ps) => { const user = await Users.findOne(ps.userId as string); if (user == null) { throw new Error('user not found'); } if (user.isAdmin) { throw new Error('cannot mark as moderator if admin user'); } await Users.update(user.id, { isModerator: true }); });
} },
random_line_split
add.ts
import $ from 'cafy'; import { ID } from '../../../../../misc/cafy-id'; import define from '../../../define'; import { Users } from '../../../../../models'; export const meta = { desc: { 'ja-JP': '指定したユーザーをモデレーターにします。', 'en-US': 'Mark a user as moderator.' }, tags: ['admin'], requireCredential: true as const...
}); });
user'); } await Users.update(user.id, { isModerator: true
conditional_block
AppBar.test.js
import React from 'react'; import { assert } from 'chai'; import { createMount, createShallow, getClasses } from '@material-ui/core/test-utils'; import describeConformance from '../test-utils/describeConformance'; import AppBar from './AppBar'; import Paper from '../Paper'; describe('<AppBar />', () => { let mount; ...
const wrapper = shallow(<AppBar color="primary">Hello World</AppBar>); assert.strictEqual(wrapper.hasClass(classes.root), true); assert.strictEqual(wrapper.hasClass(classes.colorPrimary), true); assert.strictEqual(wrapper.hasClass(classes.colorSecondary), false); }); it('should render an secondary ...
it('should render a primary app bar', () => {
random_line_split
states.py
# -*- coding: utf-8 -*- # __author__ = chenchiyuan from __future__ import division, unicode_literals, print_function from hawaii.apps.weixin.models import App from hawaii.apps.weixin.response import MessageResponse, EventResponse from hawaii.apps.weixin.weixin.interface import StateInterface class NoCacheState(State...
elif type(response) in (unicode, str): return self._to_wx_text(response) else: return self._to_wx_text("") class MenuEventState(NoCacheState): def to_xml(self, input): response = EventResponse.response(input) return self.response_articles(response) class ...
context = self.get_context() return self._to_full_text(response, context=context)
conditional_block
states.py
# -*- coding: utf-8 -*- # __author__ = chenchiyuan from __future__ import division, unicode_literals, print_function from hawaii.apps.weixin.models import App from hawaii.apps.weixin.response import MessageResponse, EventResponse from hawaii.apps.weixin.weixin.interface import StateInterface class NoCacheState(State...
class SubscribeEventState(NoCacheState): def to_xml(self, input): app = App.only_one() rule = app.subscribe_rule if not rule: return self._to_wx_text("") response = EventResponse.response(rule.id) return self.response_articles(response)
return self.response_articles(response)
random_line_split
states.py
# -*- coding: utf-8 -*- # __author__ = chenchiyuan from __future__ import division, unicode_literals, print_function from hawaii.apps.weixin.models import App from hawaii.apps.weixin.response import MessageResponse, EventResponse from hawaii.apps.weixin.weixin.interface import StateInterface class NoCacheState(State...
(self, input): app = App.only_one() rule = app.subscribe_rule if not rule: return self._to_wx_text("") response = EventResponse.response(rule.id) return self.response_articles(response)
to_xml
identifier_name
states.py
# -*- coding: utf-8 -*- # __author__ = chenchiyuan from __future__ import division, unicode_literals, print_function from hawaii.apps.weixin.models import App from hawaii.apps.weixin.response import MessageResponse, EventResponse from hawaii.apps.weixin.weixin.interface import StateInterface class NoCacheState(State...
class MenuEventState(NoCacheState): def to_xml(self, input): response = EventResponse.response(input) return self.response_articles(response) class SubscribeEventState(NoCacheState): def to_xml(self, input): app = App.only_one() rule = app.subscribe_rule if not rule:...
if type(response) is list: context = self.get_context() return self._to_full_text(response, context=context) elif type(response) in (unicode, str): return self._to_wx_text(response) else: return self._to_wx_text("")
identifier_body