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
huffman.py
class ResizeError(Exception):
def codelengths_from_frequencies(freqs): freqs = sorted(freqs.items(), key=lambda item: (item[1], -item[0]), reverse=True) nodes = [Node(char=key, weight=value) for (key, value) in freqs] while len(nodes) > 1: right, left = nodes.pop(), nodes.pop() node = Node(weight=right.weight +...
pass
identifier_body
huffman.py
class ResizeError(Exception): pass def codelengths_from_frequencies(freqs): freqs = sorted(freqs.items(), key=lambda item: (item[1], -item[0]), reverse=True) nodes = [Node(char=key, weight=value) for (key, value) in freqs] while len(nodes) > 1: right, left = nodes.pop(), nodes.pop() ...
(self, compressed, codelengths): self.compressed = compressed codes = normalized(codelengths) self.codes = {value : key for key, value in codes.items()} self.root = Node() self.make_tree(self.root) def make_tree(self, node): if node is self.root: node.cod...
__init__
identifier_name
androidUnlock.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true });
var androidUnlock = exports.androidUnlock = { "viewBox": "0 0 512 512", "children": [{ "name": "path", "attribs": { "d": "M376,186h-20v-40c0-55-45-100-100-100S156,91,156,146h37.998c0-34.004,28.003-62.002,62.002-62.002\r\n\tc34.004,0,62.002,27.998,62.002,62.002H318v40H136c-22.002,0-40,17.998-40,40v200c0,22.002,17.998,40...
random_line_split
test_history.js
/* Any copyright is dedicated to the Public Domain. http://creativecommons.org/publicdomain/zero/1.0/ */ /* * The list of phases mapped to their corresponding profiles. The object * here must be in strict JSON format, as it will get parsed by the Python * testrunner (no single quotes, extra comma's, etc). */ E...
/* * History asset lists: these define history entries that are used during * the test */ // the initial list of history items to add to the browser var history1 = [ { uri: "http://www.google.com/", title: "Google", visits: [ { type: 1, date: 0 }, { type: 2, date: -1 ...
"phase2": "profile2" };
random_line_split
config_loader.test.js
'use strict'; const path = require('path'); const mm = require('egg-mock'); const utils = require('../../../utils'); describe('test/lib/core/loader/config_loader.test.js', () => { let app; const home = utils.getFilepath('apps/demo/logs/home'); afterEach(() => app.close()); afterEach(mm.restore); it('should...
'session', ]); }); it('should get logger dir when unittest', function* () { mm(process.env, 'EGG_HOME', home); mm(process.env, 'EGG_SERVER_ENV', 'unittest'); app = utils.app('apps/demo'); yield app.ready(); app.config.logger.dir.should.eql(utils.getFilepath('apps/demo/logs/demo')); ...
'static', 'bodyParser',
random_line_split
progressbar.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
/** * Tells the progress bar that an amount of work has been completed. */ public worked(value: number): ProgressBar { assert.ok(!isNaN(this.totalWork), 'Total work not set'); value = Number(value); assert.ok(!isNaN(value), 'Value is not a number'); value = Math.max(1, value); this.workedVal += valu...
{ return !isNaN(this.totalWork); }
identifier_body
progressbar.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
return this; } /** * Use this mode to indicate progress that has no total number of work units. */ public infinite(): ProgressBar { this.bit.style.width = '2%'; this.bit.style.opacity = '1'; this.element.removeClass(css_discrete); this.element.removeClass(css_done); this.element.addClass(css_acti...
{ this.bit.style.opacity = '0'; if (delayed) { TPromise.timeout(200).then(() => this.off()); } else { this.off(); } }
conditional_block
progressbar.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
(): boolean { return !isNaN(this.totalWork); } /** * Tells the progress bar that an amount of work has been completed. */ public worked(value: number): ProgressBar { assert.ok(!isNaN(this.totalWork), 'Total work not set'); value = Number(value); assert.ok(!isNaN(value), 'Value is not a number'); valu...
hasTotal
identifier_name
progressbar.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
this.bit.style.width = 'inherit'; this.bit.style.opacity = '1'; this.element.removeClass(css_active); this.element.removeClass(css_infinite); this.element.removeClass(css_discrete); this.workedVal = 0; this.totalWork = undefined; } /** * Indicates to the progress bar that all work is done. */ pub...
private off(): void {
random_line_split
tooltip.rs
// This file was generated by gir (b7f5189) from gir-files (71d73f0) // DO NOT EDIT use Widget; use ffi; use gdk; use gdk_pixbuf; use glib::object::IsA; use glib::translate::*; glib_wrapper! { pub struct Tooltip(Object<ffi::GtkTooltip>); match fn { get_type => || ffi::gtk_tooltip_get_type(), } } ...
<'a, T: Into<Option<&'a str>>>(&self, text: T) { unsafe { ffi::gtk_tooltip_set_text(self.to_glib_none().0, text.into().to_glib_none().0); } } pub fn set_tip_area(&self, rect: &gdk::Rectangle) { unsafe { ffi::gtk_tooltip_set_tip_area(self.to_glib_none().0, rect.to...
set_text
identifier_name
tooltip.rs
// This file was generated by gir (b7f5189) from gir-files (71d73f0) // DO NOT EDIT use Widget; use ffi; use gdk; use gdk_pixbuf; use glib::object::IsA; use glib::translate::*; glib_wrapper! { pub struct Tooltip(Object<ffi::GtkTooltip>); match fn { get_type => || ffi::gtk_tooltip_get_type(), } } ...
pub fn set_text<'a, T: Into<Option<&'a str>>>(&self, text: T) { unsafe { ffi::gtk_tooltip_set_text(self.to_glib_none().0, text.into().to_glib_none().0); } } pub fn set_tip_area(&self, rect: &gdk::Rectangle) { unsafe { ffi::gtk_tooltip_set_tip_area(self.to_g...
{ unsafe { ffi::gtk_tooltip_set_markup(self.to_glib_none().0, markup.into().to_glib_none().0); } }
identifier_body
tooltip.rs
// This file was generated by gir (b7f5189) from gir-files (71d73f0) // DO NOT EDIT use Widget; use ffi; use gdk; use gdk_pixbuf; use glib::object::IsA; use glib::translate::*; glib_wrapper! { pub struct Tooltip(Object<ffi::GtkTooltip>); match fn { get_type => || ffi::gtk_tooltip_get_type(), } } ...
} } pub fn set_tip_area(&self, rect: &gdk::Rectangle) { unsafe { ffi::gtk_tooltip_set_tip_area(self.to_glib_none().0, rect.to_glib_none().0); } } pub fn trigger_tooltip_query(display: &gdk::Display) { assert_initialized_main_thread!(); unsafe { ...
pub fn set_text<'a, T: Into<Option<&'a str>>>(&self, text: T) { unsafe { ffi::gtk_tooltip_set_text(self.to_glib_none().0, text.into().to_glib_none().0);
random_line_split
speed_limit_exceeded_by_hour.py
#!/usr/bin/python # -*- coding: utf-8 -*- from scripts.db_api import accident def usa_query(hour): return ''' SELECT count(*), (select count(*) from accident join vehicle on(acc_id = accident.id) where country = 'USA' and vehicle.speed > accident.speed_limit and vehicle.speed > -1 and acciden...
def get_value(age, dictionary): if age not in dictionary: return 0 return dictionary[age] if __name__ == '__main__': print('HOUR\tALL\tEXCEEDED') for i in xrange(0, 24): usa_count = accident.execute_query(usa_query(i)) print('{0}\t{1}\t{2}'.format(i, usa_count[0][0], usa_count...
where country = 'USA' and date_part('hour', timestamp) = {0}; '''.format(hour)
random_line_split
speed_limit_exceeded_by_hour.py
#!/usr/bin/python # -*- coding: utf-8 -*- from scripts.db_api import accident def usa_query(hour): return ''' SELECT count(*), (select count(*) from accident join vehicle on(acc_id = accident.id) where country = 'USA' and vehicle.speed > accident.speed_limit and vehicle.speed > -1 and acciden...
return dictionary[age] if __name__ == '__main__': print('HOUR\tALL\tEXCEEDED') for i in xrange(0, 24): usa_count = accident.execute_query(usa_query(i)) print('{0}\t{1}\t{2}'.format(i, usa_count[0][0], usa_count[0][1]))
return 0
conditional_block
speed_limit_exceeded_by_hour.py
#!/usr/bin/python # -*- coding: utf-8 -*- from scripts.db_api import accident def usa_query(hour): return ''' SELECT count(*), (select count(*) from accident join vehicle on(acc_id = accident.id) where country = 'USA' and vehicle.speed > accident.speed_limit and vehicle.speed > -1 and acciden...
if __name__ == '__main__': print('HOUR\tALL\tEXCEEDED') for i in xrange(0, 24): usa_count = accident.execute_query(usa_query(i)) print('{0}\t{1}\t{2}'.format(i, usa_count[0][0], usa_count[0][1]))
if age not in dictionary: return 0 return dictionary[age]
identifier_body
speed_limit_exceeded_by_hour.py
#!/usr/bin/python # -*- coding: utf-8 -*- from scripts.db_api import accident def usa_query(hour): return ''' SELECT count(*), (select count(*) from accident join vehicle on(acc_id = accident.id) where country = 'USA' and vehicle.speed > accident.speed_limit and vehicle.speed > -1 and acciden...
(age, dictionary): if age not in dictionary: return 0 return dictionary[age] if __name__ == '__main__': print('HOUR\tALL\tEXCEEDED') for i in xrange(0, 24): usa_count = accident.execute_query(usa_query(i)) print('{0}\t{1}\t{2}'.format(i, usa_count[0][0], usa_count[0][1]))
get_value
identifier_name
submit.tsx
import Link from 'next/link'; import Router from 'next/router'; import React, { useState } from 'react'; import { useMutation } from '@apollo/client'; import { SUBMIT_NEWS_ITEM_MUTATION } from '../src/data/mutations/submit-news-item-mutation'; import { withDataAndRouter } from '../src/helpers/with-data'; import { Main...
(res) { if (res && res.data) { void Router.push(`/item?id=${res.data.submitNewsItem.id}`); } }, onError(err) { console.error(err); }, }); return ( <MainLayout currentUrl={router.pathname} title="Submit" isNavVisible={false} isFooterVisible={false} ...
onCompleted
identifier_name
submit.tsx
import Link from 'next/link'; import Router from 'next/router'; import React, { useState } from 'react'; import { useMutation } from '@apollo/client'; import { SUBMIT_NEWS_ITEM_MUTATION } from '../src/data/mutations/submit-news-item-mutation'; import { withDataAndRouter } from '../src/helpers/with-data'; import { Main...
</tr> <tr> <td /> <td> <input type="submit" value="submit" onClick={(): Promise<any> => submitNewsItem()} /> </td> ...
<tr> <td /> <td />
random_line_split
submit.tsx
import Link from 'next/link'; import Router from 'next/router'; import React, { useState } from 'react'; import { useMutation } from '@apollo/client'; import { SUBMIT_NEWS_ITEM_MUTATION } from '../src/data/mutations/submit-news-item-mutation'; import { withDataAndRouter } from '../src/helpers/with-data'; import { Main...
}, onError(err) { console.error(err); }, }); return ( <MainLayout currentUrl={router.pathname} title="Submit" isNavVisible={false} isFooterVisible={false} > <tr> <td> <form onSubmit={(e): void => e.preventDefault()}> <input type...
{ void Router.push(`/item?id=${res.data.submitNewsItem.id}`); }
conditional_block
submit.tsx
import Link from 'next/link'; import Router from 'next/router'; import React, { useState } from 'react'; import { useMutation } from '@apollo/client'; import { SUBMIT_NEWS_ITEM_MUTATION } from '../src/data/mutations/submit-news-item-mutation'; import { withDataAndRouter } from '../src/helpers/with-data'; import { Main...
, }); return ( <MainLayout currentUrl={router.pathname} title="Submit" isNavVisible={false} isFooterVisible={false} > <tr> <td> <form onSubmit={(e): void => e.preventDefault()}> <input type="hidden" name="fnid" value="GvyHFpy11L26dCAIgGQ9rv" /> ...
{ console.error(err); }
identifier_body
example_pNH2D.py
import pyspeckit import os from pyspeckit.spectrum.models import nh2d import numpy as np import astropy.units as u if not os.path.exists('p-nh2d_spec.fits'):
# Load the spectrum spec = pyspeckit.Spectrum('p-nh2d_spec.fits') # Determine rms from line free section and load into cube rms = np.std(spec.data[10:340]) spec.error[:] = rms # setup spectral axis spec.xarr.refX = 110.153594*u.GHz spec.xarr.velocity_convention = 'radio' spec.xarr.convert_to_unit('km/s') # define us...
import astropy.utils.data as aud from astropy.io import fits f = aud.download_file('https://github.com/pyspeckit/pyspeckit-example-files/raw/master/p-nh2d_spec.fits') with fits.open(f) as ff: ff.writeto('p-nh2d_spec.fits')
conditional_block
example_pNH2D.py
import pyspeckit import os from pyspeckit.spectrum.models import nh2d import numpy as np import astropy.units as u if not os.path.exists('p-nh2d_spec.fits'): import astropy.utils.data as aud from astropy.io import fits f = aud.download_file('https://github.com/pyspeckit/pyspeckit-example-files/raw/master/...
plt.savefig('example_p-NH2D.png')
random_line_split
ndarray.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
# under the License. # coding: utf-8 # pylint: disable=invalid-name, protected-access, too-many-arguments # pylint: disable=global-statement, unused-import """NDArray configuration API.""" from __future__ import absolute_import as _abs import ctypes from ..base import _LIB from ..base import c_str_array, c_handle_ar...
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations
random_line_split
ndarray.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
def __del__(self): check_call(_LIB.MXFreeCachedOp(self.handle)) def __call__(self, *args, **kwargs): """ctypes implementation of imperative invoke wrapper""" out = kwargs.pop('out', None) if out is not None: original_output = out if isinstance(out, NDAr...
self.handle = CachedOpHandle() check_call(_LIB.MXCreateCachedOp( sym.handle, ctypes.byref(self.handle)))
identifier_body
ndarray.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
if num_output.value == 1: return _ndarray_cls(ctypes.cast(output_vars[0], NDArrayHandle), stype=out_stypes[0]) else: return [_ndarray_cls(ctypes.cast(output_vars[i], NDArrayHandle), stype=out_stypes[i]) ...
return original_output
conditional_block
ndarray.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
(self, sym): self.handle = CachedOpHandle() check_call(_LIB.MXCreateCachedOp( sym.handle, ctypes.byref(self.handle))) def __del__(self): check_call(_LIB.MXFreeCachedOp(self.handle)) def __call__(self, *args, **kwargs): """ctypes implementation of imperat...
__init__
identifier_name
mxRhombus.js
/** * Copyright (c) 2006-2015, JGraph Ltd * Copyright (c) 2006-2015, Gaudenz Alder */ /** * Class: mxRhombus
* in <mxCellRenderer>. * * Constructor: mxRhombus * * Constructs a new rhombus shape. * * Parameters: * * bounds - <mxRectangle> that defines the bounds. This is stored in * <mxShape.bounds>. * fill - String that defines the fill color. This is stored in <fill>. * stroke - String that defines the stroke ...
* * Extends <mxShape> to implement a rhombus (aka diamond) shape. * This shape is registered under <mxConstants.SHAPE_RHOMBUS>
random_line_split
mxRhombus.js
/** * Copyright (c) 2006-2015, JGraph Ltd * Copyright (c) 2006-2015, Gaudenz Alder */ /** * Class: mxRhombus * * Extends <mxShape> to implement a rhombus (aka diamond) shape. * This shape is registered under <mxConstants.SHAPE_RHOMBUS> * in <mxCellRenderer>. * * Constructor: mxRhombus * * Constructs a new ...
; /** * Extends mxShape. */ mxUtils.extend(mxRhombus, mxShape); /** * Function: paintVertexShape * * Generic painting implementation. */ mxRhombus.prototype.paintVertexShape = function(c, x, y, w, h) { var hw = w / 2; var hh = h / 2; var arcSize = mxUtils.getValue(this.style, mxConstants.STYLE_ARCSIZE, mx...
{ mxShape.call(this); this.bounds = bounds; this.fill = fill; this.stroke = stroke; this.strokewidth = (strokewidth != null) ? strokewidth : 1; }
identifier_body
mxRhombus.js
/** * Copyright (c) 2006-2015, JGraph Ltd * Copyright (c) 2006-2015, Gaudenz Alder */ /** * Class: mxRhombus * * Extends <mxShape> to implement a rhombus (aka diamond) shape. * This shape is registered under <mxConstants.SHAPE_RHOMBUS> * in <mxCellRenderer>. * * Constructor: mxRhombus * * Constructs a new ...
(bounds, fill, stroke, strokewidth) { mxShape.call(this); this.bounds = bounds; this.fill = fill; this.stroke = stroke; this.strokewidth = (strokewidth != null) ? strokewidth : 1; }; /** * Extends mxShape. */ mxUtils.extend(mxRhombus, mxShape); /** * Function: paintVertexShape * * Generic painting implemen...
mxRhombus
identifier_name
selector_scope.ts
// Compilation scope computation is somewhat expensive, so it's cached. Check the cache for // the module. if (this._compilationScopeCache.has(module)) { // The compilation scope was cached. const scope = this._compilationScopeCache.get(module) !; // The scope as cached is in terms of Ref...
random_line_split
selector_scope.ts
Scopes { const result = this.lookupScopes(node, ngModuleImportedFrom); if (result === null) { throw new Error(`Module not found: ${reflectIdentifierOfDeclaration(node)}`); } return result; } /** * Lookup `SelectorScopes` for a given module. * * This function assumes that if the given...
{ const newMap = new Map<string, ScopeDirective<Expression>>(); map.forEach((meta, selector) => { newMap.set(selector, {...meta, directive: toR3Reference(meta.directive, context).value}); }); return newMap; }
identifier_body
selector_scope.ts
clarations.forEach(decl => { this._declararedTypeToModule.set(ts.getOriginalNode(decl.node) as ts.Declaration, node); }); } /** * Register the metadata of a component or directive with the registry. */ registerDirective(node: ts.Declaration, metadata: ScopeDirective<Reference>): void { node =...
{ // The type metadata was the wrong shape. return null; }
conditional_block
selector_scope.ts
.Declaration, data: ModuleData): void { node = ts.getOriginalNode(node) as ts.Declaration; if (this._moduleToData.has(node)) { throw new Error(`Module already registered: ${reflectNameOfDeclaration(node)}`); } this._moduleToData.set(node, data); // Register all of the module's declarations i...
( clazz: ts.Declaration, ngModuleImportedFrom: string|null): ModuleData|null { // This operation is explicitly not memoized, as it depends on `ngModuleImportedFrom`. // TODO(alxhub): investigate caching of .d.ts module metadata. const ngModuleDef = this.reflector.getMembersOfClass(clazz).find( ...
_readModuleDataFromCompiledClass
identifier_name
hepdata_test.py
# -*- coding: utf-8 -*- # # This file is part of HEPData. # Copyright (C) 2016 CERN. # # HEPData is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later...
(): """Test version import.""" from hepdata import __version__ assert __version__
test_version
identifier_name
hepdata_test.py
# -*- coding: utf-8 -*- #
# HEPData is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later version. # # HEPData is distributed in the hope that it will be # useful, but WITHOUT ...
# This file is part of HEPData. # Copyright (C) 2016 CERN. #
random_line_split
hepdata_test.py
# -*- coding: utf-8 -*- # # This file is part of HEPData. # Copyright (C) 2016 CERN. # # HEPData is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later...
"""Test version import.""" from hepdata import __version__ assert __version__
identifier_body
about_troy.js
var data = [ {title:'Basic Information', hasChild:true, test:'../examples/about_troy_more/basic_info.js'}, {title:'Vision Statement', hasChild:true, test:'../examples/about_troy_more/vision.js'}, {title:'ESLRs', hasChild:true, test:'../examples/about_troy_more/eslr_s.js'} ]; var tableview = Titanium.UI.createTableV...
Titanium.UI.currentTab.open(win,{animated:true}); } }); Titanium.UI.currentWindow.add(tableview); Titanium.UI.currentWindow.addEventListener('focus', function() { Ti.API.info('FOCUS RECEIVED IN base_ui'); });
{ win.hideTabBar(); }
conditional_block
about_troy.js
var data = [ {title:'Basic Information', hasChild:true, test:'../examples/about_troy_more/basic_info.js'}, {title:'Vision Statement', hasChild:true, test:'../examples/about_troy_more/vision.js'},
}); tableview.addEventListener('click', function(e){ if(e.rowData.test){ var win = null; win = Titanium.UI.createWindow({ url:e.rowData.test, title:e.rowData.title, backgroundColor:'#fff', barColor:'#B22222' }); if (e.index == 3) { win.hideTabBar(); } Titanium.UI.currentTab.open(win,{animated:true}...
{title:'ESLRs', hasChild:true, test:'../examples/about_troy_more/eslr_s.js'} ]; var tableview = Titanium.UI.createTableView({ data:data
random_line_split
system_clock_pt.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com> // // 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.o...
}, other => { source_freq = 0; cx.span_err( node.get_attr("source").value_span, format!("unknown oscillator value `{}`", other).as_slice()); "BAD".to_string() }, }); let some_pll_conf = node.get_by_path("pll").and_then(|sub| -> Option<(uint, uint, uint)> { ...
source_freq = some_source_frequency.unwrap(); format!("system_clock::Main({})", source_freq) }
random_line_split
system_clock_pt.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com> // // 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.o...
#[test] fn fails_to_parse_bad_clock_conf() { fails_to_build("lpc17xx@mcu { clock { no_source = 1; source_frequency = 12_000_000; }}"); fails_to_build("lpc17xx@mcu { clock { source = \"missing\"; source_frequency = 12_000_000; }}"); } #[test] fn fails_to_parse_no_pll_...
{ with_parsed(" clock { source = \"main-oscillator\"; source_frequency = 12_000_000; pll { m = 50; n = 3; divisor = 4; } }", |cx, _, pt| { let mut builder = Builder::new(pt.clone()); let node = pt.get_by_path("clock").unwrap(); ...
identifier_body
system_clock_pt.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com> // // 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.o...
() { with_parsed(" clock { source = \"main-oscillator\"; source_frequency = 12_000_000; pll { m = 50; n = 3; divisor = 4; } }", |cx, failed, pt| { let mut builder = Builder::new(pt.clone()); super::build_clock(&mut builder, cx, pt...
builds_clock_init
identifier_name
system_clock_pt.rs
// Zinc, the bare metal stack for rust. // Copyright 2014 Vladimir "farcaller" Pouzanov <farcaller@gmail.com> // // 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.o...
else { let m = sub.get_int_attr("m").unwrap(); let n = sub.get_int_attr("n").unwrap(); let divisor = sub.get_int_attr("divisor").unwrap(); Some((m, n, divisor)) } }); if some_pll_conf.is_none() { cx.parse_sess().span_diagnostic.span_err(node.name_span, "required subnode `pll...
{ None }
conditional_block
build.rs
use std::env; fn main() { let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap(); let weak_linkage = match env::var("CARGO_FEATURE_WEAK_LINKAGE") { Ok(_) => true, Err(_) => false, }; if weak_linkage { if target_os == "linux" { println!("cargo:rustc-cdylib-link-arg...
println!("cargo:rustc-cdylib-link-arg=-Wl,-rpath,{}/../lldb/lib", origin); // Relative to target/debug/deps/ - for `cargo test` println!("cargo:rustc-cdylib-link-arg=-Wl,-rpath,{}/../../../lldb/lib", origin); } } }
} else { if target_os == "linux" || target_os == "macos" { #[rustfmt::skip] let origin = if target_os == "linux" { "$ORIGIN" } else { "@loader_path" }; // Relative to adapter/
random_line_split
build.rs
use std::env; fn
() { let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap(); let weak_linkage = match env::var("CARGO_FEATURE_WEAK_LINKAGE") { Ok(_) => true, Err(_) => false, }; if weak_linkage { if target_os == "linux" { println!("cargo:rustc-cdylib-link-arg=-Wl,-Bstatic"); ...
main
identifier_name
build.rs
use std::env; fn main()
// Relative to adapter/ println!("cargo:rustc-cdylib-link-arg=-Wl,-rpath,{}/../lldb/lib", origin); // Relative to target/debug/deps/ - for `cargo test` println!("cargo:rustc-cdylib-link-arg=-Wl,-rpath,{}/../../../lldb/lib", origin); } } }
{ let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap(); let weak_linkage = match env::var("CARGO_FEATURE_WEAK_LINKAGE") { Ok(_) => true, Err(_) => false, }; if weak_linkage { if target_os == "linux" { println!("cargo:rustc-cdylib-link-arg=-Wl,-Bstatic"); ...
identifier_body
recipe-416087.py
from _winreg import * import os, sys, win32gui, win32con def queryValue(key, name): value, type_id = QueryValueEx(key, name) return value def show(key): for i in range(1024): try: n,v,t = EnumValue(key, i) print '%s=%s' % (n...
DeleteValue(key, name) win32gui.SendMessage(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment') except Exception, e: print e CloseKey(key) CloseKey(reg) if __name__=='__main__': usage = \ """ Usage:...
SetValueEx(key, name, 0, REG_EXPAND_SZ, value) else:
random_line_split
recipe-416087.py
from _winreg import * import os, sys, win32gui, win32con def queryValue(key, name): value, type_id = QueryValueEx(key, name) return value def show(key): for i in range(1024): try: n,v,t = EnumValue(key, i) print '%s=%s' % (n...
CloseKey(key) CloseKey(reg) if __name__=='__main__': usage = \ """ Usage: Show all environment vsarisbles - enver Add/Modify/Delete environment variable - enver <name>=[value] If <name> is PATH enver will append the value prefixed with ; If there is no value enver will delete the <name> en...
try: path = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment' reg = ConnectRegistry(None, HKEY_LOCAL_MACHINE) key = OpenKey(reg, path, 0, KEY_ALL_ACCESS) if len(sys.argv) == 1: show(key) else: name, value = sys.argv[1].split('=') ...
identifier_body
recipe-416087.py
from _winreg import * import os, sys, win32gui, win32con def queryValue(key, name): value, type_id = QueryValueEx(key, name) return value def show(key): for i in range(1024): try: n,v,t = EnumValue(key, i) print '%s=%s' % (n...
win32gui.SendMessage(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment') except Exception, e: print e CloseKey(key) CloseKey(reg) if __name__=='__main__': usage = \ """ Usage: Show all environment vsarisbles - en...
DeleteValue(key, name)
conditional_block
recipe-416087.py
from _winreg import * import os, sys, win32gui, win32con def queryValue(key, name): value, type_id = QueryValueEx(key, name) return value def show(key): for i in range(1024): try: n,v,t = EnumValue(key, i) print '%s=%s' % (n...
(): try: path = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment' reg = ConnectRegistry(None, HKEY_LOCAL_MACHINE) key = OpenKey(reg, path, 0, KEY_ALL_ACCESS) if len(sys.argv) == 1: show(key) else: name, value = sys.argv[1].split(...
main
identifier_name
servermessagearchive.ts
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.0" language="ru" sourcelanguage="en"> <context> <name>ServerMessageArchive</name> <message> <source>Server Message Archive</source> <translation>Серверный архив сообщений</translation> </message> <message> <sourc...
</message> <message> <source>History of conversations is stored on your jabber server</source> <translation>История общения сохраняется на вашем jabber сервере</translation> </message> </context> </TS>
<translation>Позволяет сохранять историю общения на сервере</translation> </message> <message> <source>Standard Server Side Archive</source> <translation>Стандартный архив на сервере</translation>
random_line_split
1d76643bcec4_nvp_netbinding.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2013 OpenStack Foundation # # 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...
(active_plugins=None, options=None): if not migration.should_run(active_plugins, migration_for_plugins): return op.drop_table('nvp_network_bindings')
downgrade
identifier_name
1d76643bcec4_nvp_netbinding.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2013 OpenStack Foundation # # 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...
if not migration.should_run(active_plugins, migration_for_plugins): return op.drop_table('nvp_network_bindings')
identifier_body
1d76643bcec4_nvp_netbinding.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2013 OpenStack Foundation # # 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...
op.drop_table('nvp_network_bindings')
return
conditional_block
1d76643bcec4_nvp_netbinding.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2013 OpenStack Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); you may
# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # ...
# not use this file except in compliance with the License. You may obtain
random_line_split
Screen.js
/* @flow */ import React, { PureComponent } from 'react'; import { View, StyleSheet, KeyboardAvoidingView, Platform } from 'react-native'; import type { LocalizableText } from '../types'; import { ZulipStatusBar } from '../common'; import ModalNavBar from '../nav/ModalNavBar';
flexDirection: 'column', justifyContent: 'center', alignItems: 'stretch', }, }); export default class Screen extends PureComponent { props: { search?: boolean, keyboardAvoiding?: boolean, title?: LocalizableText, children: [], searchBarOnChange?: (text: string) => void, }; stat...
import ModalSearchNavBar from '../nav/ModalSearchNavBar'; const componentStyles = StyleSheet.create({ screenWrapper: { flex: 1,
random_line_split
index.js
import React, { Component } from 'react' import { connect } from 'react-redux' import { forceCheck } from 'react-lazyload' import { getFiles, thumbnailGenerated, makeFilesLoadedSelector } from 'ducks/files' import { openFileModal } from 'ducks/fileModal' import SingleSelect from 'containers/SingleSelect' import Multi...
if (mode === 'index') { return <IndexMode fileType={fileType} filesUrl={filesUrl} readOnly={readOnly} /> } if (mode === 'modal-single-select') { return ( <ModalSingleSelect fileType={fileType} filesUrl={filesUrl} reactType={reactType} loadFiles=...
{ return <SingleSelect fileType={fileType} filesUrl={filesUrl} /> }
conditional_block
index.js
import React, { Component } from 'react' import { connect } from 'react-redux' import { forceCheck } from 'react-lazyload' import { getFiles, thumbnailGenerated, makeFilesLoadedSelector } from 'ducks/files' import { openFileModal } from 'ducks/fileModal' import SingleSelect from 'containers/SingleSelect' import Multi...
() { if (!window.FolioCable) return this.cableSubscription = window.FolioCable.cable.subscriptions.create('FolioThumbnailsChannel', { received: (data) => { if (!data) return if (!data.temporary_url || !data.url) return this.props.dispatch(thumbnailGenerated('images', data.temporar...
listenOnActionCable
identifier_name
index.js
import React, { Component } from 'react' import { connect } from 'react-redux' import { forceCheck } from 'react-lazyload' import { getFiles, thumbnailGenerated, makeFilesLoadedSelector } from 'ducks/files' import { openFileModal } from 'ducks/fileModal' import SingleSelect from 'containers/SingleSelect' import Multi...
} } listenOnActionCable () { if (!window.FolioCable) return this.cableSubscription = window.FolioCable.cable.subscriptions.create('FolioThumbnailsChannel', { received: (data) => { if (!data) return if (!data.temporary_url || !data.url) return this.props.dispatch(thumbnailG...
loadFiles = (fileType, filesUrl) => { if (!this.props.filesLoaded) { this.props.dispatch(getFiles(fileType, filesUrl))
random_line_split
index.ts
import { DebugHandler, DebugConsume } from "./debugging"; import * as en from "./locales/en"; import { Chrono, Parser, Refiner } from "./chrono"; export { en, Chrono, Parser, Refiner }; export interface ParsingOption { /** * To parse only forward dates (the results should be after the reference date). *...
export const casual = en.casual; /** * A shortcut for {@link en | chrono.en.casual.parse()} */ export function parse(text: string, ref?: ParsingReference | Date, option?: ParsingOption): ParsedResult[] { return casual.parse(text, ref, option); } /** * A shortcut for {@link en | chrono.en.casual.parseDate()} *...
export const strict = en.strict; /** * A shortcut for {@link en | chrono.en.casual} */
random_line_split
index.ts
import { DebugHandler, DebugConsume } from "./debugging"; import * as en from "./locales/en"; import { Chrono, Parser, Refiner } from "./chrono"; export { en, Chrono, Parser, Refiner }; export interface ParsingOption { /** * To parse only forward dates (the results should be after the reference date). *...
(text: string, ref?: ParsingReference | Date, option?: ParsingOption): Date { return casual.parseDate(text, ref, option); }
parseDate
identifier_name
index.ts
import { DebugHandler, DebugConsume } from "./debugging"; import * as en from "./locales/en"; import { Chrono, Parser, Refiner } from "./chrono"; export { en, Chrono, Parser, Refiner }; export interface ParsingOption { /** * To parse only forward dates (the results should be after the reference date). *...
/** * A shortcut for {@link en | chrono.en.casual.parseDate()} */ export function parseDate(text: string, ref?: ParsingReference | Date, option?: ParsingOption): Date { return casual.parseDate(text, ref, option); }
{ return casual.parse(text, ref, option); }
identifier_body
app-bootstrap.service.ts
import { Injectable } from '@angular/core'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; import { Observable } from 'rxjs'; import { BehaviorSubject } from 'rxjs'; import { AppLocalization } from '@kaltura-ng/mc-shared'; import { AppAuthentication } from './app-authenticat...
observer.next(false); observer.complete(); // we must modify document.location instead of using Angular router because // router is not supported until at least once component // ...
if (statusChangeSubscription) statusChangeSubscription.unsubscribe(); } else { if (status === BoostrappingStatus.Error) {
random_line_split
app-bootstrap.service.ts
import { Injectable } from '@angular/core'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; import { Observable } from 'rxjs'; import { BehaviorSubject } from 'rxjs'; import { AppLocalization } from '@kaltura-ng/mc-shared'; import { AppAuthentication } from './app-authenticat...
bootstrapFailure(error); } ); } } private getCurrentLanguage(): string { let lang: string = null; // try getting last selected language from local storage if (this._browserService.getFromLocalStorage('kmc_lang') !== null) { ...
{ if (!this._initialized) { const bootstrapFailure = (error: any) => { console.log("Bootstrap Error::" + error); // TODO [kmc-infra] - move to log this._bootstrapStatusSource.next(BoostrappingStatus.Error); } this._initialized = true; ...
identifier_body
app-bootstrap.service.ts
import { Injectable } from '@angular/core'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; import { Observable } from 'rxjs'; import { BehaviorSubject } from 'rxjs'; import { AppLocalization } from '@kaltura-ng/mc-shared'; import { AppAuthentication } from './app-authenticat...
(): string { let lang: string = null; // try getting last selected language from local storage if (this._browserService.getFromLocalStorage('kmc_lang') !== null) { const userLanguage: string = this._browserService.getFromLocalStorage('kmc_lang'); if (kmcAppConfig.locales....
getCurrentLanguage
identifier_name
main.rs
#![feature(iter_max_by, iter_min_by)] use std::collections::HashMap; use std::io; use std::io::prelude::*; enum DecodingMethod { MostLikely, LeastLikely, } fn decode_message(input: &str, method: DecodingMethod) -> String
} } .unwrap() .0 }) .collect() } fn main() { let mut message_str = String::new(); io::stdin().read_to_string(&mut message_str).expect("Invalid input string!"); println!("The initial decoded message is: {}", d...
{ let len = input.lines().map(|line| line.chars().count()).max().unwrap(); let mut histograms = vec![HashMap::new(); len]; for line in input.lines() { for (pos, ch) in line.chars().enumerate() { let cnt = histograms[pos].entry(ch).or_insert(0); *cnt += 1; } } ...
identifier_body
main.rs
#![feature(iter_max_by, iter_min_by)] use std::collections::HashMap; use std::io; use std::io::prelude::*; enum
{ MostLikely, LeastLikely, } fn decode_message(input: &str, method: DecodingMethod) -> String { let len = input.lines().map(|line| line.chars().count()).max().unwrap(); let mut histograms = vec![HashMap::new(); len]; for line in input.lines() { for (pos, ch) in line.chars().enumerate() {...
DecodingMethod
identifier_name
main.rs
#![feature(iter_max_by, iter_min_by)] use std::collections::HashMap; use std::io; use std::io::prelude::*; enum DecodingMethod { MostLikely, LeastLikely, } fn decode_message(input: &str, method: DecodingMethod) -> String { let len = input.lines().map(|line| line.chars().count()).max().unwrap(); let...
.map(|h| { match method { DecodingMethod::MostLikely => { h.into_iter().max_by(|&(_, cnt_a), &(_, cnt_b)| cnt_a.cmp(&cnt_b)) } DecodingMethod::LeastLikely => { h.into_iter().min_by(|&(_, cnt_a...
*cnt += 1; } } histograms.into_iter()
random_line_split
vpcs-templates.component.ts
import { Component, OnInit, ViewChild } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { Server } from '../../../../models/server'; import { VpcsTemplate } from '../../../../models/templates/vpcs-template'; import { ServerService } from '../../../../services/server.service'; import { Vpc...
(private route: ActivatedRoute, private serverService: ServerService, private vpcsService: VpcsService) {} ngOnInit() { const server_id = this.route.snapshot.paramMap.get('server_id'); this.serverService.get(parseInt(server_id, 10)).then((server: Server) => { this.server = server; this.getTemplat...
constructor
identifier_name
vpcs-templates.component.ts
import { Component, OnInit, ViewChild } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { Server } from '../../../../models/server'; import { VpcsTemplate } from '../../../../models/templates/vpcs-template'; import { ServerService } from '../../../../services/server.service'; import { Vpc...
getTemplates() { this.vpcsService.getTemplates(this.server).subscribe((vpcsTemplates: VpcsTemplate[]) => { this.vpcsTemplates = vpcsTemplates.filter((elem) => elem.template_type === 'vpcs' && !elem.builtin); }); } deleteTemplate(template: VpcsTemplate) { this.deleteComponent.deleteItem(templa...
{ const server_id = this.route.snapshot.paramMap.get('server_id'); this.serverService.get(parseInt(server_id, 10)).then((server: Server) => { this.server = server; this.getTemplates(); }); }
identifier_body
vpcs-templates.component.ts
import { Component, OnInit, ViewChild } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { Server } from '../../../../models/server'; import { VpcsTemplate } from '../../../../models/templates/vpcs-template'; import { ServerService } from '../../../../services/server.service'; import { Vpc...
} deleteTemplate(template: VpcsTemplate) { this.deleteComponent.deleteItem(template.name, template.template_id); } onDeleteEvent() { this.getTemplates(); } }
this.vpcsService.getTemplates(this.server).subscribe((vpcsTemplates: VpcsTemplate[]) => { this.vpcsTemplates = vpcsTemplates.filter((elem) => elem.template_type === 'vpcs' && !elem.builtin); });
random_line_split
vec-tail-matching.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 ...
match tail { [Foo { .. }, _, Foo { .. }, .. _tail] => { unreachable!(); } [Foo { string: ref a }, Foo { string: ref b }] => { assert_eq!("bar", a.as_slice().slice(0, a.len())); assert_eq!("baz", b.as_...
random_line_split
vec-tail-matching.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 ...
() { let x = [ Foo { string: "foo".to_string() }, Foo { string: "bar".to_string() }, Foo { string: "baz".to_string() } ]; match x { [ref first, ..tail] => { assert!(first.string == "foo".to_string()); assert_eq!(tail.len(), 2); assert!(tail...
main
identifier_name
vec-tail-matching.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 ...
[Foo { string: ref a }, Foo { string: ref b }] => { assert_eq!("bar", a.as_slice().slice(0, a.len())); assert_eq!("baz", b.as_slice().slice(0, b.len())); } _ => { unreachable!(); } } ...
{ unreachable!(); }
conditional_block
vec-tail-matching.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 ...
} _ => { unreachable!(); } } } } }
{ let x = [ Foo { string: "foo".to_string() }, Foo { string: "bar".to_string() }, Foo { string: "baz".to_string() } ]; match x { [ref first, ..tail] => { assert!(first.string == "foo".to_string()); assert_eq!(tail.len(), 2); assert!(tail[0]...
identifier_body
queue.py
from fabric.context_managers import settings from golive.layers.base import BaseTask, DebianPackageMixin, IPTablesSetup from golive.stacks.stack import environment from golive.utils import get_remote_envvar class RabbitMqSetup(BaseTask, DebianPackageMixin): package_name = "rabbitmq-server" GUEST_USER = "guest...
def status(self): out = self.run("sudo %s status" % self.RABBIT_INITSCRIPT) self._check_output(out, "running_applications", self.NAME) def _set_listen_port(self): self.append(self.__class__.RABBITMQ_CONFIGFILE, "[{kernel, [ {inet_dist_listen_min, 9100}, {inet_dist_...
self._create_user()
identifier_body
queue.py
from fabric.context_managers import settings from golive.layers.base import BaseTask, DebianPackageMixin, IPTablesSetup from golive.stacks.stack import environment from golive.utils import get_remote_envvar class RabbitMqSetup(BaseTask, DebianPackageMixin): package_name = "rabbitmq-server" GUEST_USER = "guest...
allow = [ (environment.hosts, IPTablesSetup.DESTINATION_ALL, "9101:9105"), (environment.hosts, IPTablesSetup.DESTINATION_ALL, "4369"), (environment.hosts, IPTablesSetup.DESTINATION_ALL, "8612"), (environment.hosts, IPTablesSetup.DESTINATION_ALL, "5...
DebianPackageMixin.init(self, update) self._set_listen_port()
random_line_split
queue.py
from fabric.context_managers import settings from golive.layers.base import BaseTask, DebianPackageMixin, IPTablesSetup from golive.stacks.stack import environment from golive.utils import get_remote_envvar class RabbitMqSetup(BaseTask, DebianPackageMixin): package_name = "rabbitmq-server" GUEST_USER = "guest...
(self): self.append(self.__class__.RABBITMQ_CONFIGFILE, "[{kernel, [ {inet_dist_listen_min, 9100}, {inet_dist_listen_max, 9105} ]}].") def _add_repo(self): # as described at http://www.rabbitmq.com/install-debian.html self.append("/etc/apt/sources.list", "deb http://www....
_set_listen_port
identifier_name
geostats.js
i = 0; i < this.pop(); i++) { if (this.serie[i] < this.stat_min) { this.stat_min = this.serie[i]; } } } return this.stat_min; }; /** return max value */ this.max = function() { if (this._nodata()) return; if (this.stat_max == null) { this.stat_max = this.serie[0]; ...
}; /** return mean value */ this.mean = function() { if (this._nodata()) return; if (this.stat_mean == null) { this.stat_mean = this.sum() / this.pop(); } return this.stat_mean; }; /** return median value */ this.median = function() { if (this._nodata()) return; if (...
this.stat_pop = this.serie.length; } return this.stat_pop;
random_line_split
multichecksum.py
#!/usr/bin/env python __author__ = "Andrew Hankinson (andrew.hankinson@mail.mcgill.ca)" __version__ = "1.5" __date__ = "2011" __copyright__ = "Creative Commons Attribution" __license__ = """The MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of ...
def csumfile(filename): """ Based on http://abstracthack.wordpress.com/2007/10/19/calculating-md5-checksum/ """ hashalg = getattr(hashlib, HASHALG)() # == 'hashlib.md5' or 'hashlib.sha1' blocksize = 0x10000 def __upd(m, data): m.update(data) return m fd = open(filen...
datafiles = [] for dirpath, dirnames, filenames in os.walk(u"{0}".format(datadir)): for fn in filenames: datafiles.append(os.path.join(dirpath, fn)) return datafiles
identifier_body
multichecksum.py
#!/usr/bin/env python __author__ = "Andrew Hankinson (andrew.hankinson@mail.mcgill.ca)" __version__ = "1.5" __date__ = "2011" __copyright__ = "Creative Commons Attribution" __license__ = """The MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of ...
(datadir): datafiles = [] for dirpath, dirnames, filenames in os.walk(u"{0}".format(datadir)): for fn in filenames: datafiles.append(os.path.join(dirpath, fn)) return datafiles def csumfile(filename): """ Based on http://abstracthack.wordpress.com/2007/10/19/calculating-md...
dirwalk
identifier_name
multichecksum.py
#!/usr/bin/env python __author__ = "Andrew Hankinson (andrew.hankinson@mail.mcgill.ca)" __version__ = "1.5" __date__ = "2011" __copyright__ = "Creative Commons Attribution" __license__ = """The MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of ...
try: contents = iter(lambda: fd.read(blocksize), "") m = reduce(__upd, contents, hashalg) finally: fd.close() return (m.hexdigest(), filename) def ensure_unix_pathname(pathname): # it's only windows we have to worry about if sys.platform != "win32": return pathname...
random_line_split
multichecksum.py
#!/usr/bin/env python __author__ = "Andrew Hankinson (andrew.hankinson@mail.mcgill.ca)" __version__ = "1.5" __date__ = "2011" __copyright__ = "Creative Commons Attribution" __license__ = """The MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of ...
write_manifest(args[0], ENCODING, update=options.update)
parser.error("You must specify a data directory")
conditional_block
0121_workflow_uuids.py
""" Add UUIDs to workflows """ from sqlalchemy import * from sqlalchemy.orm import * from migrate import * from migrate.changeset import * from galaxy.model.custom_types import UUIDType, TrimmedString import logging log = logging.getLogger( __name__ ) metadata = MetaData() """ Because both workflow and job reques...
(migrate_engine): metadata.bind = migrate_engine metadata.reflect() # Drop the workflow table's uuid column. try: workflow_table = Table( "workflow", metadata, autoload=True ) workflow_uuid = workflow_table.c.uuid workflow_uuid.drop() except Exception, e: log.debug( ...
downgrade
identifier_name
0121_workflow_uuids.py
""" Add UUIDs to workflows """ from sqlalchemy import * from sqlalchemy.orm import * from migrate import * from migrate.changeset import * from galaxy.model.custom_types import UUIDType, TrimmedString import logging log = logging.getLogger( __name__ ) metadata = MetaData() """ Because both workflow and job reques...
workflow_table = Table( "workflow", metadata, autoload=True ) workflow_uuid_column.create( workflow_table ) assert workflow_uuid_column is workflow_table.c.uuid except Exception, e: print str(e) log.error( "Adding column 'uuid' to workflow table failed: %s" % str( e ) ) ...
# Add the uuid colum to the workflow table try:
random_line_split
0121_workflow_uuids.py
""" Add UUIDs to workflows """ from sqlalchemy import * from sqlalchemy.orm import * from migrate import * from migrate.changeset import * from galaxy.model.custom_types import UUIDType, TrimmedString import logging log = logging.getLogger( __name__ ) metadata = MetaData() """ Because both workflow and job reques...
def upgrade(migrate_engine): print __doc__ metadata.bind = migrate_engine metadata.reflect() # Add the uuid colum to the workflow table try: workflow_table = Table( "workflow", metadata, autoload=True ) workflow_uuid_column.create( workflow_table ) assert workflow_uuid_col...
print "This migration script adds a UUID column to workflows"
identifier_body
SelectMaxBidEdit.tsx
import React from "react" import { View, ViewProperties } from "react-native" import NavigatorIOS from "react-native-navigator-ios" import { Schema, screenTrack } from "../../../utils/track" import { Box, Button } from "@artsy/palette" import { BackButton } from "lib/Components/Bidding/Components/BackButton" import {...
() { const bids = this.props.increments || [] return ( <BiddingThemeProvider> <Container m={0}> <View> <BackButton navigator={this.props.navigator} /> <Title>Your max bid</Title> </View> <MaxBidPicker bids={bids} onVal...
render
identifier_name
SelectMaxBidEdit.tsx
import React from "react" import { View, ViewProperties } from "react-native" import NavigatorIOS from "react-native-navigator-ios" import { Schema, screenTrack } from "../../../utils/track" import { Box, Button } from "@artsy/palette" import { BackButton } from "lib/Components/Bidding/Components/BackButton" import {...
<Container m={0}> <View> <BackButton navigator={this.props.navigator} /> <Title>Your max bid</Title> </View> <MaxBidPicker bids={bids} onValueChange={(_, index) => this.setState({ selectedBidIndex: index })} selectedValue...
<BiddingThemeProvider>
random_line_split
SelectMaxBidEdit.tsx
import React from "react" import { View, ViewProperties } from "react-native" import NavigatorIOS from "react-native-navigator-ios" import { Schema, screenTrack } from "../../../utils/track" import { Box, Button } from "@artsy/palette" import { BackButton } from "lib/Components/Bidding/Components/BackButton" import {...
</Button> </Box> </Container> </BiddingThemeProvider> ) } }
{ const bids = this.props.increments || [] return ( <BiddingThemeProvider> <Container m={0}> <View> <BackButton navigator={this.props.navigator} /> <Title>Your max bid</Title> </View> <MaxBidPicker bids={bids} onValueC...
identifier_body
package_id.rs
// Copyright 2013 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 ...
path: Path, /// Short name. This is the path's filestem, but we store it /// redundantly so as to not call get() everywhere (filestem() returns an /// option) /// The short name does not need to be a valid Rust identifier. /// Users can write: `extern mod foo = "...";` to get around the issue ...
/// the sources into a local directory in the RUST_PATH).
random_line_split
package_id.rs
// Copyright 2013 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 ...
} impl PkgId { pub fn new(s: &str) -> PkgId { use conditions::bad_pkg_id::cond; let mut given_version = None; // Did the user request a specific version? let s = match split_version(s) { Some((path, v)) => { given_version = Some(v); pat...
{ self.path == other.path && self.version == other.version }
identifier_body
package_id.rs
// Copyright 2013 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 short_name = path.filestem().expect(fmt!("Strange path! %s", s)); let version = match given_version { Some(v) => v, None => match try_getting_local_version(&path) { Some(v) => v, None => match try_getting_version(&path) { ...
{ return cond.raise((path, ~"0-length pkgid")); }
conditional_block
package_id.rs
// Copyright 2013 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 ...
(&self) -> ~str { fmt!("install(%s)", self.to_str()) } } struct Prefixes { priv components: ~[~str], priv remaining: ~[~str] } impl Iterator<(Path, Path)> for Prefixes { #[inline] fn next(&mut self) -> Option<(Path, Path)> { if self.components.len() <= 1 { None ...
install_tag
identifier_name
isSameMapKey.ts
import isSubtypeOf from '../dataTypes/isSubtypeOf'; import Value, { ValueType } from '../dataTypes/Value'; export default function
(k1: Value, k2: Value): boolean { const k1IsStringLike = isSubtypeOf(k1.type, ValueType.XSSTRING) || isSubtypeOf(k1.type, ValueType.XSANYURI) || isSubtypeOf(k1.type, ValueType.XSUNTYPEDATOMIC); const k2IsStringLike = isSubtypeOf(k2.type, ValueType.XSSTRING) || isSubtypeOf(k2.type, ValueType.XSANYURI) || i...
isSameMapKey
identifier_name
isSameMapKey.ts
import isSubtypeOf from '../dataTypes/isSubtypeOf'; import Value, { ValueType } from '../dataTypes/Value'; export default function isSameMapKey(k1: Value, k2: Value): boolean
isSubtypeOf(k2.type, ValueType.XSDECIMAL) || isSubtypeOf(k2.type, ValueType.XSDOUBLE) || isSubtypeOf(k2.type, ValueType.XSFLOAT); if (k1IsNumeric && k2IsNumeric) { if (isNaN(k1.value) && isNaN(k2.value)) { return true; } return k1.value === k2.value; } // TODO: dateTime const k1IsOther = isSubtype...
{ const k1IsStringLike = isSubtypeOf(k1.type, ValueType.XSSTRING) || isSubtypeOf(k1.type, ValueType.XSANYURI) || isSubtypeOf(k1.type, ValueType.XSUNTYPEDATOMIC); const k2IsStringLike = isSubtypeOf(k2.type, ValueType.XSSTRING) || isSubtypeOf(k2.type, ValueType.XSANYURI) || isSubtypeOf(k2.type, ValueType.XS...
identifier_body
isSameMapKey.ts
import isSubtypeOf from '../dataTypes/isSubtypeOf'; import Value, { ValueType } from '../dataTypes/Value'; export default function isSameMapKey(k1: Value, k2: Value): boolean { const k1IsStringLike = isSubtypeOf(k1.type, ValueType.XSSTRING) || isSubtypeOf(k1.type, ValueType.XSANYURI) || isSubtypeOf(k1.type, Val...
} return false; }
random_line_split
isSameMapKey.ts
import isSubtypeOf from '../dataTypes/isSubtypeOf'; import Value, { ValueType } from '../dataTypes/Value'; export default function isSameMapKey(k1: Value, k2: Value): boolean { const k1IsStringLike = isSubtypeOf(k1.type, ValueType.XSSTRING) || isSubtypeOf(k1.type, ValueType.XSANYURI) || isSubtypeOf(k1.type, Val...
return k1.value === k2.value; } // TODO: dateTime const k1IsOther = isSubtypeOf(k1.type, ValueType.XSBOOLEAN) || isSubtypeOf(k1.type, ValueType.XSHEXBINARY) || isSubtypeOf(k1.type, ValueType.XSDURATION) || isSubtypeOf(k1.type, ValueType.XSQNAME) || isSubtypeOf(k1.type, ValueType.XSNOTATION); const k2I...
{ return true; }
conditional_block
leafmt.rs
//! Lea code formatter. // FIXME This requires the parser to preserve comments to work properly // This is blocked on an upstream issue: https://github.com/kevinmehall/rust-peg/issues/84 #[macro_use] extern crate clap; extern crate term; extern crate rustc_serialize; extern crate lea_parser as parser; extern crate le...
() -> Box<term::StderrTerminal> { term::stderr().unwrap_or_else(|| Box::new(DummyTerm(io::stderr()))) } /// Parses the given source code and pretty-prints it fn prettyprint<W: Write>(code: &str, source_name: &str, mut target: W) -> io::Result<()> { match parser::block(code) { Ok(main) => { ...
stderr_term
identifier_name
leafmt.rs
//! Lea code formatter. // FIXME This requires the parser to preserve comments to work properly // This is blocked on an upstream issue: https://github.com/kevinmehall/rust-peg/issues/84 #[macro_use] extern crate clap; extern crate term; extern crate rustc_serialize; extern crate lea_parser as parser; extern crate le...
Ok(content) => content, Err(e) => { writeln!(stderr(), "{}", e).unwrap(); return; } } } // Open output let writer: Box<Write>; match matches.value_of("out") { None | Some("-") => { writer = Box::new(stdout()...
{ let matches = clap_app!(leafmt => (version: lea::version_str()) (about: "Lea source code formatter / pretty printer") (@arg FILE: +required "The file to format (`-` to read from stdin)") (@arg out: -o --out +takes_value "Write output to <out> (`-` to write to stdout).") (af...
identifier_body
leafmt.rs
//! Lea code formatter. // FIXME This requires the parser to preserve comments to work properly // This is blocked on an upstream issue: https://github.com/kevinmehall/rust-peg/issues/84 #[macro_use] extern crate clap; extern crate term; extern crate rustc_serialize; extern crate lea_parser as parser; extern crate le...
else { source_name = file; code = match read_file(&source_name) { Ok(content) => content, Err(e) => { writeln!(stderr(), "{}", e).unwrap(); return; } } } // Open output let writer: Box<Write>; match matches.val...
{ stdin().read_to_string(&mut code).unwrap(); source_name = "<stdin>"; }
conditional_block
leafmt.rs
//! Lea code formatter. // FIXME This requires the parser to preserve comments to work properly // This is blocked on an upstream issue: https://github.com/kevinmehall/rust-peg/issues/84 #[macro_use] extern crate clap; extern crate term; extern crate rustc_serialize; extern crate lea_parser as parser; extern crate le...
fn prettyprint<W: Write>(code: &str, source_name: &str, mut target: W) -> io::Result<()> { match parser::block(code) { Ok(main) => { let mut pp = PrettyPrinter::new(&mut target); try!(pp.print_block(&main)); } Err(e) => { try!(e.format(code, source_name, &...
random_line_split