file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
Presence.ts
export interface Presence { subscribe(topic: string, callback: Function); unsubscribe(topic: string, callback?: Function); publish(topic: string, data: any); exists(roomId: string): Promise<boolean>; setex(key: string, value: string, seconds: number); get(key: string); del(key: string): v...
srem(key: string, value: any); scard(key: string); sinter(...keys: string[]): Promise<string[]>; hset(key: string, field: string, value: string); hincrby(key: string, field: string, value: number); hget(key: string, field: string): Promise<string>; hgetall(key: string): Promise<{ [key: stri...
random_line_split
setup.py
#!/usr/bin/env python # coding=utf-8 from setuptools import setup, find_packages setup(name='french_dates_to_ical', version='0.0.1', author='Michaël Launay', author_email='michaellaunay@ecreall.com', url='http://www.ecreall.com/ressources/french_dates_to_ical', download_url='https://git...
#setup_requires = ['python-stdeb', 'fakeroot', 'python-all'], install_requires = ['setuptools', 'docutils>=0.3', 'parsimonious', 'pytest'], )
],
random_line_split
unreachable_rule.rs
// Copyright 2018 Chao Lin & William Sergeant (Sorbonne University) // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by...
fn visit_str_literal(&mut self, _this: usize, lit: String) -> Occurence{ let mut seq = vec![]; for c in lit.chars(){ seq.push((Char(c),One)) } let mut res = vec![]; res.push(seq); Occurence{ choice: res } } fn visit_any_single_char(&mut self, _this: usize) -> Occurence{ ...
{ Occurence{ choice: vec![] } }
identifier_body
unreachable_rule.rs
// Copyright 2018 Chao Lin & William Sergeant (Sorbonne University) // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by...
Occurence{ choice: vec![] } } fn visit_one_or_more(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } fn visit_optional(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } fn visit_not_predicate(&mu...
} fn visit_zero_or_more(&mut self, _this: usize, _child: usize) -> Occurence{
random_line_split
unreachable_rule.rs
// Copyright 2018 Chao Lin & William Sergeant (Sorbonne University) // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by...
} res } fn success_with(&self, seq2: Vec<(Character, Pattern)>) -> bool { let mut res = false; for seq1 in self.choice.clone(){ if self.succeed_before(seq1,seq2.to_vec()) { res = true; } } res } fn succeed_before(&self, seq1: Vec<(Character, Pattern)>, seq2: Vec<(C...
{ res = false; break; }
conditional_block
unreachable_rule.rs
// Copyright 2018 Chao Lin & William Sergeant (Sorbonne University) // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by...
(&mut self, _this: usize, _rule: Ident) -> Occurence{ Occurence{ choice: vec![] } } fn visit_zero_or_more(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ choice: vec![] } } fn visit_one_or_more(&mut self, _this: usize, _child: usize) -> Occurence{ Occurence{ ...
visit_non_terminal_symbol
identifier_name
wrapped_mesh.py
# Copyright (C) 2011-2015 Claas Abert # # This file is part of magnum.fe. # # magnum.fe is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later ...
submesh.__class__ = WrappedMesh submesh._init(mesh) return submesh
submesh = SubMesh(mesh, domain_ids)
conditional_block
wrapped_mesh.py
# Copyright (C) 2011-2015 Claas Abert # # This file is part of magnum.fe. # # magnum.fe is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later ...
(self, f, **kwargs): """ Takes a function defined on the super mesh and returns a truncated function defined on the sub mesh. *Arguments* f (:class:`dolfin.Function`) The function on the super mesh. *Returns* :class:`dolfin.Function` The function on the sub mesh. ""...
cut
identifier_name
wrapped_mesh.py
# Copyright (C) 2011-2015 Claas Abert # # This file is part of magnum.fe. # # magnum.fe is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later ...
Invert list of domain IDs *Returns* :class:`WrappedMesh` The wrapped mesh """ if invert or isinstance(domain_ids, list) or isinstance(domain_ids, tuple): if isinstance(domain_ids, int): domain_ids = (domain_ids,) subdomains = MeshFunction('size_t', mesh, 3, mesh.domains()...
random_line_split
wrapped_mesh.py
# Copyright (C) 2011-2015 Claas Abert # # This file is part of magnum.fe. # # magnum.fe is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later ...
""" Creates a wrapped mesh from a super mesh for a given collection of domain IDs. *Arguments* mesh (:class:`dolfin.Mesh`) The mesh. domain_ids (:class:`[int]`) List of domain IDs invert (:class:`bool`) Invert list of domain IDs *Returns* :class:`Wrapped...
identifier_body
stenciledsum.py
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import numpy as np def subarray_multislice(array_ndim, fixed_axes, indices): ''' Return tuple of slices that if indexed into an array with given dimensions will return subarray with the axes in axes fixed at given indices ...
# Coerce the inputs into flat numpy arrays to allow for easy handling # of a variety of input types fixed_axes = np.atleast_1d(np.array(fixed_axes)).flatten() indices = np.atleast_1d(np.array(indices)).flatten() check_axes_access(fixed_axes, array.ndim) convert_axes_to_po...
''' Return view of subarray of input array with fixed_axes at corresponding indices.''' if checks:
random_line_split
stenciledsum.py
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import numpy as np def subarray_multislice(array_ndim, fixed_axes, indices): ''' Return tuple of slices that if indexed into an array with given dimensions will return subarray with the axes in axes fixed at given indices ...
def check_axes_access(axes, array_ndim): if np.max(axes) >= array_ndim or np.min(axes) < -array_ndim: raise IndexError('too many indices for array') # regular numpy scheme for which positive index a negative index corresponds to def convert_axes_to_positive(axes, array_ndim): for index, element...
''' Return view of array with each axes indexed between starts and ends. ''' if checks: # Coerce the inputs into flat numpy arrays to allow for easy handling # of a variety of input types starts = np.atleast_1d(np.array(starts)).flatten() ends = np.atleast_1d(np.array(ends))....
identifier_body
stenciledsum.py
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import numpy as np def subarray_multislice(array_ndim, fixed_axes, indices): ''' Return tuple of slices that if indexed into an array with given dimensions will return subarray with the axes in axes fixed at given indices ...
def correct_stencil_shape(array_ndim, axes, summed_axes_shape): return np.hstack([np.array(summed_axes_shape), np.array(array_ndim - len(axes))]) def check_stencil_shape(array_ndim, axes, summed_axes_shape, stencil): if not np.all(np.array(stencil.shape) == correct_st...
axes[index] = element + array_ndim
conditional_block
stenciledsum.py
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import numpy as np def subarray_multislice(array_ndim, fixed_axes, indices): ''' Return tuple of slices that if indexed into an array with given dimensions will return subarray with the axes in axes fixed at given indices ...
(self, array_ndim, axes_summed_over, summed_axes_shape, stencil): axes = np.atleast_1d(np.array(axes_summed_over)).flatten() # check that inputs are compatible check_axes_access(axes, array_ndim) convert_axes_to_positive(axes, array_ndim) check_stencil_shape(arra...
__init__
identifier_name
parent-hoc.tsx
import * as React from 'react' import {isMobile, hoistNonReactStatic} from '../../util/container' export type OverlayParentProps = { getAttachmentRef?: () => React.Component<any> | null showingMenu: boolean setAttachmentRef: (arg0: React.Component<any> | null) => void setShowingMenu: (arg0: boolean) => void ...
} const OverlayParent: React.ComponentClass<PropsWithoutOverlay<Props>, OverlayParentState> = _OverlayParent OverlayParent.displayName = ComposedComponent.displayName || 'OverlayParent' hoistNonReactStatic(OverlayParent, ComposedComponent) return OverlayParent } export default OverlayParentHOC
{ return ( <ComposedComponent {...this.props} setShowingMenu={this.setShowingMenu} toggleShowingMenu={this.toggleShowingMenu} setAttachmentRef={this.setAttachmentRef} getAttachmentRef={this.getAttachmentRef} showingMenu={this.state.showingMenu} ...
identifier_body
parent-hoc.tsx
import * as React from 'react' import {isMobile, hoistNonReactStatic} from '../../util/container' export type OverlayParentProps = { getAttachmentRef?: () => React.Component<any> | null showingMenu: boolean setAttachmentRef: (arg0: React.Component<any> | null) => void setShowingMenu: (arg0: boolean) => void ...
this._ref = attachmentRef } getAttachmentRef = () => this._ref render() { return ( <ComposedComponent {...this.props} setShowingMenu={this.setShowingMenu} toggleShowingMenu={this.toggleShowingMenu} setAttachmentRef={this.setAttachmentRef} ...
toggleShowingMenu = () => this.setState(oldState => ({showingMenu: !oldState.showingMenu})) setAttachmentRef = isMobile ? () => {} : (attachmentRef: React.Component<any> | null) => {
random_line_split
parent-hoc.tsx
import * as React from 'react' import {isMobile, hoistNonReactStatic} from '../../util/container' export type OverlayParentProps = { getAttachmentRef?: () => React.Component<any> | null showingMenu: boolean setAttachmentRef: (arg0: React.Component<any> | null) => void setShowingMenu: (arg0: boolean) => void ...
extends React.Component<PropsWithoutOverlay<Props>, OverlayParentState> { state = {showingMenu: false} _ref: React.Component<any> | null = null setShowingMenu = (showingMenu: boolean) => this.setState(oldState => (oldState.showingMenu === showingMenu ? null : {showingMenu})) toggleShowingMenu = (...
_OverlayParent
identifier_name
process.rs
//! System calls related to process managment. use arch::context::{context_clone, context_switch, ContextFile}; use arch::regs::Regs; use collections::{BTreeMap, Vec}; use collections::string::ToString; use core::mem; use core::ops::DerefMut; use system::{c_array_to_slice, c_string_to_str}; use system::error::{Err...
else { Err(Error::new(EINVAL)) } } //TODO: Finish implementation, add more functions to WaitMap so that matching any or using WNOHANG works pub fn waitpid(pid: isize, status_ptr: *mut usize, _options: usize) -> Result<usize> { let contexts = unsafe { &mut *::env().contexts.get() }; let current = t...
{ let contexts = unsafe { &mut *::env().contexts.get() }; let mut current = try!(contexts.current_mut()); current.iopl = level; regs.flags &= 0xFFFFFFFFFFFFFFFF - 0x3000; regs.flags |= (current.iopl << 12) & 0x3000; Ok(0) }
conditional_block
process.rs
//! System calls related to process managment. use arch::context::{context_clone, context_switch, ContextFile}; use arch::regs::Regs; use collections::{BTreeMap, Vec}; use collections::string::ToString; use core::mem; use core::ops::DerefMut; use system::{c_array_to_slice, c_string_to_str}; use system::error::{Err...
//TODO: Finish implementation, add more functions to WaitMap so that matching any or using WNOHANG works pub fn waitpid(pid: isize, status_ptr: *mut usize, _options: usize) -> Result<usize> { let contexts = unsafe { &mut *::env().contexts.get() }; let current = try!(contexts.current_mut()); if pid > 0 { ...
Err(Error::new(EINVAL)) } }
random_line_split
process.rs
//! System calls related to process managment. use arch::context::{context_clone, context_switch, ContextFile}; use arch::regs::Regs; use collections::{BTreeMap, Vec}; use collections::string::ToString; use core::mem; use core::ops::DerefMut; use system::{c_array_to_slice, c_string_to_str}; use system::error::{Err...
/// Supervise a child process of the current context. /// /// This will make all syscalls the given process makes mark the process as blocked, until it is /// handled by the supervisor (parrent process) through the returned handle (for details, see the /// docs in the `system` crate). /// /// This routine is done by ...
{ unsafe { context_switch(); } Ok(0) }
identifier_body
process.rs
//! System calls related to process managment. use arch::context::{context_clone, context_switch, ContextFile}; use arch::regs::Regs; use collections::{BTreeMap, Vec}; use collections::string::ToString; use core::mem; use core::ops::DerefMut; use system::{c_array_to_slice, c_string_to_str}; use system::error::{Err...
(regs: &mut Regs) -> Result<usize> { let level = regs.bx; if level <= 3 { let contexts = unsafe { &mut *::env().contexts.get() }; let mut current = try!(contexts.current_mut()); current.iopl = level; regs.flags &= 0xFFFFFFFF - 0x3000; regs.flags |= (current.iopl << 12) &...
iopl
identifier_name
enrichment.rs
use serde_json::Value; use {PassiveTotal, Result}; const URL_DATA: &str = "/enrichment"; const URL_OSINT: &str = "/enrichment/osint"; const URL_MALWARE: &str = "/enrichment/malware"; const URL_SUBDOMAINS: &str = "/enrichment/subdomains"; pub struct EnrichmentRequest<'a> { pt: &'a PassiveTotal, } request_struct!...
(&self) -> EnrichmentRequest { EnrichmentRequest { pt: self } } }
enrichment
identifier_name
enrichment.rs
use serde_json::Value; use {PassiveTotal, Result}; const URL_DATA: &str = "/enrichment"; const URL_OSINT: &str = "/enrichment/osint"; const URL_MALWARE: &str = "/enrichment/malware"; const URL_SUBDOMAINS: &str = "/enrichment/subdomains"; pub struct EnrichmentRequest<'a> { pt: &'a PassiveTotal, } request_struct!...
S: Into<String>, { EnrichmentSubdomains { pt: self.pt, url: URL_SUBDOMAINS, query: query.into(), } } } impl_send!(EnrichmentData); impl_send!(EnrichmentOsint); impl_send!(EnrichmentMalware); impl_send!(EnrichmentSubdomains); impl PassiveTotal { p...
pub fn subdomains<S>(self, query: S) -> EnrichmentSubdomains<'a> where
random_line_split
enrichment.rs
use serde_json::Value; use {PassiveTotal, Result}; const URL_DATA: &str = "/enrichment"; const URL_OSINT: &str = "/enrichment/osint"; const URL_MALWARE: &str = "/enrichment/malware"; const URL_SUBDOMAINS: &str = "/enrichment/subdomains"; pub struct EnrichmentRequest<'a> { pt: &'a PassiveTotal, } request_struct!...
pub fn osint<S>(self, query: S) -> EnrichmentOsint<'a> where S: Into<String>, { EnrichmentOsint { pt: self.pt, url: URL_OSINT, query: query.into(), } } pub fn malware<S>(self, query: S) -> EnrichmentMalware<'a> where S: Into<...
{ EnrichmentData { pt: self.pt, url: URL_DATA, query: query.into(), } }
identifier_body
fashion_compatibility.py
# Copyright 2017 Xintong Han. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
if __name__ == "__main__": tf.app.run()
g = tf.Graph() with g.as_default(): model_config = configuration.ModelConfig() model_config.rnn_type = FLAGS.rnn_type model = polyvore_model.PolyvoreModel(model_config, mode="inference") model.build() saver = tf.train.Saver() # Load pre-computed image features. with open(FLAGS.feature...
identifier_body
fashion_compatibility.py
# Copyright 2017 Xintong Han. All Rights Reserved. # # 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 #
# See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Predict the fashion compatibility of a given image sequence.""" from __future__ import absolute_import from __future__ import divisi...
# 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.
random_line_split
fashion_compatibility.py
# Copyright 2017 Xintong Han. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
(sess, image_seqs, test_feat, num_lstm_units, model): emb_seqs = test_feat[image_seqs,:] num_images = float(len(image_seqs)) if FLAGS.rnn_type == "lstm": zero_state = np.zeros([1, 2 * num_lstm_units]) else: zero_state = np.zeros([1, num_lstm_units]) f_score = 0 b_s...
run_compatibility_inference
identifier_name
fashion_compatibility.py
# Copyright 2017 Xintong Han. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
[f_score, b_score] = run_compatibility_inference(sess, image_seqs, test_feat, model_config.num_lstm_units, model) all_f_scores.append(f_score) all_b_scores.append(b_score) all_scores.append(f_score + b_score) all_labels.append(int(test_o...
image_seqs.append(test_ids.index(test_image))
conditional_block
mocha.d.ts
// Type definitions for mocha 1.9.0 // Project: http://visionmedia.github.io/mocha/ // Definitions by: Kazi Manzur Rashid <https://github.com/kazimanzurrashid/> // DefinitelyTyped: https://github.com/borisyankov/DefinitelyTyped interface Mocha { // Setup mocha with the given setting options. setup(options: Moc...
// Set reporter, defaults to "dot" reporter(reporter: string): Mocha; // Enable growl support. growl(): Mocha } interface MochaSetupOptions { //milliseconds to wait before considering a test slow slow?: number; // timeout in milliseconds timeout?: number; // ui name "bdd", "tdd",...
// Set reporter as function reporter(reporter: () => void): Mocha;
random_line_split
Debug.js
/////////////////////////////////////////////////////////////////////////////// // Debug Extensions ss.Debug = global.Debug || function() {}; ss.Debug.__typeName = 'Debug'; if (!ss.Debug.writeln) { ss.Debug.writeln = function#? DEBUG Debug$writeln##(text) { if (global.console) { if (global.console.debug)
else if (global.console.log) { global.console.log(text); return; } } else if (global.opera && global.opera.postError) { global.opera.postError(text); return; } } }; ss.Debug._fail = function#? DEBUG Debug$_fail##(message) { ss.Debug.writeln(message); debugger; }; ss.Debug.assert = fun...
{ global.console.debug(text); return; }
conditional_block
Debug.js
/////////////////////////////////////////////////////////////////////////////// // Debug Extensions ss.Debug = global.Debug || function() {}; ss.Debug.__typeName = 'Debug'; if (!ss.Debug.writeln) { ss.Debug.writeln = function#? DEBUG Debug$writeln##(text) { if (global.console) { if (global.console.debug) { ...
debugger; }; ss.Debug.assert = function#? DEBUG Debug$assert##(condition, message) { if (!condition) { message = 'Assert failed: ' + message; if (confirm(message + '\r\n\r\nBreak into debugger?')) { ss.Debug._fail(message); } } }; ss.Debug.fail = function#? DEBUG Debug$fail##(message) { ss.Debug._fail(me...
}; ss.Debug._fail = function#? DEBUG Debug$_fail##(message) { ss.Debug.writeln(message);
random_line_split
action-constraint-form-control.ts
/* * Lumeer: Modern Data Definition and Processing Platform * * Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates. * * This program 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 ...
RequiresConfirmation = 'requiresConfirmation', ConfirmationTitle = 'confirmationTitle', }
random_line_split
jquery.ui.datepicker-ja.min.js
/*! jQuery UI - v1.9.2 - 2015-05-24 * http://jqueryui.com * Copyright 2015 jQuery Foundation and other contributors; Licensed MIT */
jQuery(function(e){e.datepicker.regional.ja={closeText:"閉じる",prevText:"&#x3C;前",nextText:"次&#x3E;",currentText:"今日",monthNames:["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],monthNamesShort:["1月","2月","3月","4月","5月","6月","7月","8月","9月","10月","11月","12月"],dayNames:["日曜日","月曜日","火曜日","水曜日","木曜日","金曜日","...
random_line_split
anmr_platform_win.py
#from matplotlib.backends.backend_gtk import NavigationToolbar2GTK as NavigationToolbar2 from matplotlib.backends.backend_gtkagg import NavigationToolbar2GTKAgg as NavigationToolbar2 import subprocess import shlex import re import posixpath from anmr_common import * # use hub4com ? USE_SERIAL_PIPE=False #external hel...
(tempDir): head,tail = os.path.split(HUB4COM) wmi=win32com.client.GetObject('winmgmts:') for p in wmi.InstancesOf('win32_process'): # if p.Name == 'hub4com.exe': if p.Name == tail: pid = int(p.Properties_('ProcessId')) print('Found: ',p.Name, 'pid: ',pid, ' Killing.') ...
killSerialPipe
identifier_name
anmr_platform_win.py
#from matplotlib.backends.backend_gtk import NavigationToolbar2GTK as NavigationToolbar2 from matplotlib.backends.backend_gtkagg import NavigationToolbar2GTKAgg as NavigationToolbar2 import subprocess import shlex import re import posixpath from anmr_common import * # use hub4com ? USE_SERIAL_PIPE=False #external hel...
def detectArduino(tempDir): #tempDir is ignored here, used in linux version global ARDUINO_DEV,ARDUINO_BOARD,HUB1,HUB2 myArduinoDev = ARDUINO_DEV if myArduinoDev == 'auto': ARDUINO_BOARD = 'auto' HUB1 = None HUB2 = None for port, desc in enumerate_serial_ports(): ...
head,tail = os.path.split(HUB4COM) wmi=win32com.client.GetObject('winmgmts:') for p in wmi.InstancesOf('win32_process'): # if p.Name == 'hub4com.exe': if p.Name == tail: return True return False
identifier_body
anmr_platform_win.py
#from matplotlib.backends.backend_gtk import NavigationToolbar2GTK as NavigationToolbar2 from matplotlib.backends.backend_gtkagg import NavigationToolbar2GTKAgg as NavigationToolbar2 import subprocess import shlex import re import posixpath from anmr_common import * # use hub4com ? USE_SERIAL_PIPE=False #external hel...
#it still gets detected unless we wait a moment: time.sleep(0.1) if pipeRunning(None) == False: print('successfully killed hub4com') return True print('tried to kill hub4com, but seems to still be running') return False
pid = int(p.Properties_('ProcessId')) print('Found: ',p.Name, 'pid: ',pid, ' Killing.') kernel32 = ctypes.windll.kernel32 handle = kernel32.OpenProcess(1,0,pid) kernel32.TerminateProcess(handle,0)
conditional_block
anmr_platform_win.py
#from matplotlib.backends.backend_gtk import NavigationToolbar2GTK as NavigationToolbar2 from matplotlib.backends.backend_gtkagg import NavigationToolbar2GTKAgg as NavigationToolbar2 import subprocess import shlex import re import posixpath from anmr_common import * # use hub4com ? USE_SERIAL_PIPE=False #external hel...
#in here arduinoDev is ignored, used in linux version. We link the #hardwareDev to HUM1, then HUB2 is what's talked to. args = [HUB4COM,'--route=All:All','--octs=off','--baud=1000000','\\\\.\\'+hardwareDev,'--baud=1000000','\\\\.\\'+HUB1] print('args are:',args) try: proc = ...
random_line_split
BaristaCardView.js
/** * card_view = new BaristaCardView({el: $("target_selector", url:"", title:"", subtitle:"", fg_color: "#1b9e77", image:"", span_class: "col-lg-12"}); * * A Backbone View that displays a card of information wrapped in link * The view is meant to be a top level...
* #1b9e77 * @param {string} span_class a bootstrap span class to size the width of the view, defaults to * "col-lg-12" */ Barista.Views.BaristaCardView = Backbone.View.extend({ /** * give the view a name to be used throughout the View's functions when it n...
* @param {string} fg_color the hex color code to use as the foreground color of the view, defaults to
random_line_split
stability_summary.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 ...
, } } // Produce the summary for an arbitrary item. If the item is a module, include a // module summary. The counts for items with nested items (e.g. modules, traits, // impls) include all children counts. fn summarize_item(item: &Item) -> (Counts, Option<ModuleSummary>) { let item_counts = count_stability(i...
{ Counts::zero() }
conditional_block
stability_summary.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 ...
} impl Ord for ModuleSummary { fn cmp(&self, other: &ModuleSummary) -> Ordering { self.name.cmp(&other.name) } } // is the item considered publically visible? fn visible(item: &Item) -> bool { match item.inner { ImplItem(_) => true, _ => item.visibility == Some(Public) } } fn...
{ self.name.partial_cmp(&other.name) }
identifier_body
stability_summary.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 ...
() -> Counts { Counts { deprecated: 0, experimental: 0, unstable: 0, stable: 0, frozen: 0, locked: 0, unmarked: 0, } } pub fn total(&self) -> uint { self.deprecated + self.exp...
zero
identifier_name
package.py
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Samrai(AutotoolsPackage):
"""SAMRAI (Structured Adaptive Mesh Refinement Application Infrastructure) is an object-oriented C++ software library enables exploration of numerical, algorithmic, parallel computing, and software issues associated with applying structured adaptive mesh refinement (SAMR) technology in large...
identifier_body
package.py
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Samrai(AutotoolsPackage): """SAMRAI (Structured Adaptive Mesh Refinement Application Infra...
depends_on('mpi') depends_on('zlib') depends_on('hdf5+mpi') depends_on('m4', type='build') depends_on('boost@:1.64.0', when='@3.0.0:3.11', type='build') depends_on('silo+mpi', when='+silo') # don't build SAMRAI 3+ with tools with gcc patch('no-tool-build.patch', when='@3.0.0:%gcc') ...
# and more print statements variant('debug', default=False, description='Compile with reduced optimization and debugging on') variant('silo', default=False, description='Compile with support for silo')
random_line_split
package.py
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Samrai(AutotoolsPackage): """SAMRAI (Structured Adaptive Mesh Refinement Application Infra...
(self): options = [] options.extend([ '--with-CXX=%s' % self.spec['mpi'].mpicxx, '--with-CC=%s' % self.spec['mpi'].mpicc, '--with-F77=%s' % self.spec['mpi'].mpifc, '--with-M4=%s' % self.spec['m4'].prefix, '--with-hdf5=%s' % self.spec['hdf5'].p...
configure_args
identifier_name
package.py
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Samrai(AutotoolsPackage): """SAMRAI (Structured Adaptive Mesh Refinement Application Infra...
return options def setup_dependent_build_environment(self, env, dependent_spec): if self.spec.satisfies('@3.12:'): env.append_flags('CXXFLAGS', self.compiler.cxx11_flag)
options.append('--with-boost=%s' % self.spec['boost'].prefix)
conditional_block
test.ts
/* * @license Apache-2.0 * * Copyright (c) 2020 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by ap...
(): ndarray { const arr: ndarray = { 'byteLength': null, 'BYTES_PER_ELEMENT': null, 'data': new Float64Array( [ 1, 2, 3 ] ), 'dtype': 'float64', 'flags': { 'ROW_MAJOR_CONTIGUOUS': true, 'COLUMN_MAJOR_CONTIGUOUS': false }, 'length': 3, 'ndims': 1, 'offset': 0, 'order': 'row-major', 'shape': ...
createArray
identifier_name
test.ts
/* * @license Apache-2.0 * * Copyright (c) 2020 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by ap...
sdot( [], y ); // $ExpectError sdot( ( x: number ): number => x, y ); // $ExpectError } // The compiler throws an error if the function is provided a second argument which is not an ndarray... { const x: ndarray = createArray(); sdot( x, 10 ); // $ExpectError sdot( x, '10' ); // $ExpectError sdot( x, true ); //...
sdot( null, y ); // $ExpectError sdot( undefined, y ); // $ExpectError sdot( {}, y ); // $ExpectError
random_line_split
test.ts
/* * @license Apache-2.0 * * Copyright (c) 2020 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by ap...
// TESTS // // The function returns a number... { sdot( createArray(), createArray() ); // $ExpectType number } // The compiler throws an error if the function is provided a first argument which is not an ndarray... { const y: ndarray = createArray(); sdot( 10, y ); // $ExpectError sdot( '10', y ); // $Expect...
{ const arr: ndarray = { 'byteLength': null, 'BYTES_PER_ELEMENT': null, 'data': new Float64Array( [ 1, 2, 3 ] ), 'dtype': 'float64', 'flags': { 'ROW_MAJOR_CONTIGUOUS': true, 'COLUMN_MAJOR_CONTIGUOUS': false }, 'length': 3, 'ndims': 1, 'offset': 0, 'order': 'row-major', 'shape': [ 3 ], 'st...
identifier_body
package.py
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
(CMakePackage): """SIMD Library for Evaluating Elementary Functions, vectorized libm and DFT.""" homepage = "http://sleef.org" url = "https://github.com/shibatch/sleef/archive/3.2.tar.gz" version('3.2', '459215058f2c8d55cd2b644d56c8c4f0')
Sleef
identifier_name
package.py
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
# # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class ...
# This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details.
random_line_split
package.py
############################################################################## # Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-64...
"""SIMD Library for Evaluating Elementary Functions, vectorized libm and DFT.""" homepage = "http://sleef.org" url = "https://github.com/shibatch/sleef/archive/3.2.tar.gz" version('3.2', '459215058f2c8d55cd2b644d56c8c4f0')
identifier_body
into_iterator.rs
#![allow(dead_code, unused_imports)] #[macro_use] extern crate derive_more; #[derive(IntoIterator)] #[into_iterator(owned, ref, ref_mut)] struct MyVec(Vec<i32>); #[derive(IntoIterator)] #[into_iterator(owned, ref, ref_mut)] struct Numbers { numbers: Vec<i32>, } #[derive(IntoIterator)] struct
{ #[into_iterator(owned, ref, ref_mut)] numbers: Vec<i32>, useless: bool, useless2: bool, } #[derive(IntoIterator)] struct Numbers3 { #[into_iterator(ref, ref_mut)] numbers: Vec<i32>, useless: bool, useless2: bool, } // Test that owned is not enabled when ref/ref_mut are enabled witho...
Numbers2
identifier_name
into_iterator.rs
#![allow(dead_code, unused_imports)]
#[derive(IntoIterator)] #[into_iterator(owned, ref, ref_mut)] struct MyVec(Vec<i32>); #[derive(IntoIterator)] #[into_iterator(owned, ref, ref_mut)] struct Numbers { numbers: Vec<i32>, } #[derive(IntoIterator)] struct Numbers2 { #[into_iterator(owned, ref, ref_mut)] numbers: Vec<i32>, useless: bool, ...
#[macro_use] extern crate derive_more;
random_line_split
common.js
/* * Copyright © Enable Software Pty Ltd 2013 - All rights reserved */ var common = {}; common.unique = function (array) { var results = []; var dict = {}; for (var i in array) { dict[array[i]] = true; } for (var y in dict) { results.push(y); } return results; }; common....
// Handle Object if (obj instanceof Object) { var copy = {}; for (var attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]); } return copy; } throw new Error("Unable to copy obj! Its type isn't supported."); }
var copy = []; for (var i = 0, len = obj.length; i < len; i++) { copy[i] = clone(obj[i]); } return copy; }
conditional_block
common.js
/* * Copyright © Enable Software Pty Ltd 2013 - All rights reserved */ var common = {}; common.unique = function (array) { var results = []; var dict = {}; for (var i in array) { dict[array[i]] = true; } for (var y in dict) { results.push(y); } return results; }; common....
} // Handle Object if (obj instanceof Object) { var copy = {}; for (var attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]); } return copy; } throw new Error("Unable to copy obj! Its type isn't supported."); }
copy[i] = clone(obj[i]); } return copy;
random_line_split
common.js
/* * Copyright © Enable Software Pty Ltd 2013 - All rights reserved */ var common = {}; common.unique = function (array) { var results = []; var dict = {}; for (var i in array) { dict[array[i]] = true; } for (var y in dict) { results.push(y); } return results; }; common....
mask, bit) { return mask &= ~(1 << bit); } function BitSet(mask, bit) { return (mask & (1 << bit)) ? 1 : 0; } /*function copy(buffer) { var bytes = new Uint8Array(buffer); var output = new ArrayBuffer(buffer.byteLength); var outputBytes = new Uint8Array(output); for (var i = 0; i < bytes.lengt...
learBit(
identifier_name
common.js
/* * Copyright © Enable Software Pty Ltd 2013 - All rights reserved */ var common = {}; common.unique = function (array) { var results = []; var dict = {}; for (var i in array) { dict[array[i]] = true; } for (var y in dict) { results.push(y); } return results; }; common....
/*function copy(buffer) { var bytes = new Uint8Array(buffer); var output = new ArrayBuffer(buffer.byteLength); var outputBytes = new Uint8Array(output); for (var i = 0; i < bytes.length; i++) outputBytes[i] = bytes[i]; return output; }*/ function clone(obj) { // Handle the 3 simple typ...
return (mask & (1 << bit)) ? 1 : 0; }
identifier_body
WolframAlphaLookup.py
import sublime, sublime_plugin, requests from xml.etree import ElementTree as ET class WolframAlphaLookupCommand(sublime_plugin.WindowCommand): def run(self): settings = sublime.load_settings("Preferences.sublime-settings") if settings.has("wolfram_api_key"): API_KEY = setting...
(self, edit, data): for region in self.view.sel(): if region.empty(): line = self.view.line(region) self.view.insert(edit, line.end(), '\n' + (data[:-1] if data[-1] == '\n' else data)) else: self.view.insert(edit, region.end(), data) ...
run
identifier_name
WolframAlphaLookup.py
import sublime, sublime_plugin, requests from xml.etree import ElementTree as ET class WolframAlphaLookupCommand(sublime_plugin.WindowCommand): def run(self): settings = sublime.load_settings("Preferences.sublime-settings") if settings.has("wolfram_api_key"): API_KEY = setting...
break else: sublime.error_message("Please add a \"wolfram_api_key\" to the settings!") class InsertResultCommand(sublime_plugin.TextCommand): def run(self, edit, data): for region in self.view.sel(): if region.empty(): line = self.vi...
sublime.error_message("Wolfram|Alpha could not understand your query!")
conditional_block
WolframAlphaLookup.py
import sublime, sublime_plugin, requests from xml.etree import ElementTree as ET class WolframAlphaLookupCommand(sublime_plugin.WindowCommand): def run(self): settings = sublime.load_settings("Preferences.sublime-settings") if settings.has("wolfram_api_key"): API_KEY = setting...
self.window.show_quick_panel(items, on_select) else: sublime.error_message("Wolfram|Alpha could not understand your query!") break else: sublime.error_message("Please add a \"wolfram_api_key\" to the settings!") clas...
if index > -1: print(items[index]) print(region) self.window.active_view().run_command("insert_result", {"data": items[index][1]})
identifier_body
WolframAlphaLookup.py
import sublime, sublime_plugin, requests from xml.etree import ElementTree as ET class WolframAlphaLookupCommand(sublime_plugin.WindowCommand): def run(self): settings = sublime.load_settings("Preferences.sublime-settings") if settings.has("wolfram_api_key"): API_KEY = setting...
else: query = self.window.active_view().substr(self.window.active_view().line(region)) query = query.strip() r = requests.get("http://api.wolframalpha.com/v2/query", params={ "input": query, "appid": API_K...
for region in self.window.active_view().sel(): if not region.empty(): query = self.window.active_view().substr(region)
random_line_split
util.py
from django.utils.encoding import smart_unicode def ssn_check_digit(value):
def vat_number_check_digit(vat_number): "Calculate Italian VAT number check digit." normalized_vat_number = smart_unicode(vat_number).zfill(10) total = 0 for i in range(0, 10, 2): total += int(normalized_vat_number[i]) for i in range(1, 11, 2): quotient , remainder = divmod(int(nor...
"Calculate Italian social security number check digit." ssn_even_chars = { '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'I': 8, 'J': 9, 'K': 10, 'L': 11, 'M': 12, 'N': 13, 'O': 14, 'P': 15, ...
identifier_body
util.py
from django.utils.encoding import smart_unicode def ssn_check_digit(value): "Calculate Italian social security number check digit." ssn_even_chars = { '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, ...
for i in range(1, 11, 2): quotient , remainder = divmod(int(normalized_vat_number[i]) * 2, 10) total += quotient + remainder return smart_unicode((10 - total % 10) % 10)
total += int(normalized_vat_number[i])
conditional_block
util.py
from django.utils.encoding import smart_unicode def ssn_check_digit(value): "Calculate Italian social security number check digit." ssn_even_chars = { '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, ...
(vat_number): "Calculate Italian VAT number check digit." normalized_vat_number = smart_unicode(vat_number).zfill(10) total = 0 for i in range(0, 10, 2): total += int(normalized_vat_number[i]) for i in range(1, 11, 2): quotient , remainder = divmod(int(normalized_vat_number[i]) * 2, ...
vat_number_check_digit
identifier_name
util.py
from django.utils.encoding import smart_unicode def ssn_check_digit(value): "Calculate Italian social security number check digit." ssn_even_chars = { '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, ...
raise ValueError(msg) return ssn_check_digits[total % 26] def vat_number_check_digit(vat_number): "Calculate Italian VAT number check digit." normalized_vat_number = smart_unicode(vat_number).zfill(10) total = 0 for i in range(0, 10, 2): total += int(normalized_vat_number[i]) ...
total += ssn_even_chars[ssn[i]] except KeyError: msg = "Character '%(char)s' is not allowed." % {'char': ssn[i]}
random_line_split
check_field_existence.py
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2004, 2005, 2006, 2007, 2008, 2010, 2011, 2013 CERN. # # Invenio 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 th...
if isinstance(value, list) and len(value) != 1: raise error("Field '%s' is mandatory and not repeatable" % (key,)) elif max_value != 'n': if isinstance(value, list) and len(value) > max_value: raise error("Field '%s' is mandatory and repeatable only %s tim...
raise error("Field '%s' is mandatory" % (key,)) if not max_value:
random_line_split
check_field_existence.py
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2004, 2005, 2006, 2007, 2008, 2010, 2011, 2013 CERN. # # Invenio 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 th...
""" Checks field.subfield existence inside the record according to max and min values @param record: BibFieldDict where the record is stored @param field: Main json ID or field name to make test on @param min_value: Minimum number of occurrences of field. If max_value is not present then min_value ...
identifier_body
check_field_existence.py
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2004, 2005, 2006, 2007, 2008, 2010, 2011, 2013 CERN. # # Invenio 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 th...
else: if not key in record: raise error("Field '%s' must be present inside the record %s times" % (key, min_value)) value = record[key] if not value: raise error("Field '%s' must be present inside the record %s times" % (key, min_value)) if not max_value: ...
if isinstance(value, list) and len(value) > max_value: raise error("Field '%s' is mandatory and repeatable only %s times" % (key, max_value))
conditional_block
check_field_existence.py
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2004, 2005, 2006, 2007, 2008, 2010, 2011, 2013 CERN. # # Invenio 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 th...
(record, field, min_value, max_value=None, subfield=None, continuable=True): """ Checks field.subfield existence inside the record according to max and min values @param record: BibFieldDict where the record is stored @param field: Main json ID or field name to make test on @param min_value: Minimu...
check_field_existence
identifier_name
odin.js
module.exports.odin = { baseUrl: 'http://localhost:3000', kongHost: '0.0.0.0', kongAdmin: '0.0.0.0:8001', recaptchaSecret: '6LcBhAkUAAAAABqD6jm_Cd3uFALNoXRr6ZXqvyBG', uploadFolder: 'files', datasetZipFolder: 'datasets', logFolder: 'logs', logFile: 'sailsApp.log',
defaultEncoding: 'utf8', dataStorage: { host: 'localhost', port: '27017' }, logLevel: 'error' }; module.exports.email = { service: 'Gmail', auth: {user: 'examplemail@gmail.com', pass: 'onepass'}, alwaysSendTo: 'examplemail@gmail.com', testMode: false, templateDir: 'api/views...
statisticsPath: 'stats', backupFolder: 'backups',
random_line_split
ch15-closures.rs
/*Named functions, like those we've seen so far, may not refer to local variables declared outside the function: they do not close over their environment (sometimes referred to as "capturing" variables in their environment). A closure does support accessing the enclosing scope */ let x = 3; // `fun` is an invalid de...
has type || and can directly access local variables in the enclosing scope.*/ let mut max = 0; let f = |x: int| if x > max { max = x }; for x in [1, 2, 3].iter() { f(*x); } /*Stack closures are very efficient because their environment is allocated on the call stack and refers by pointer to captured locals. To en...
println!("{}", square_infer(-20)); // 400 /*There are several forms of closure, each with its own role. The most common, called a stack closure,
random_line_split
ch15-closures.rs
/*Named functions, like those we've seen so far, may not refer to local variables declared outside the function: they do not close over their environment (sometimes referred to as "capturing" variables in their environment). A closure does support accessing the enclosing scope */ let x = 3; // `fun` is an invalid de...
(x: int) { println!("{}", x) } // this is same as saying `-> ()` fn square(x: int) -> uint { (x * x) as uint } // other return types are explicit // Error: mismatched types: expected `()` but found `uint` fn badfun(x: int) { (x * x) as uint } /*On the other hand, the compiler can usually infer ...
fun
identifier_name
ch15-closures.rs
/*Named functions, like those we've seen so far, may not refer to local variables declared outside the function: they do not close over their environment (sometimes referred to as "capturing" variables in their environment). A closure does support accessing the enclosing scope */ let x = 3; // `fun` is an invalid de...
; for x in [1, 2, 3].iter() { f(*x); } /*Stack closures are very efficient because their environment is allocated on the call stack and refers by pointer to captured locals. To ensure that stack closures never outlive the local variables to which they refer, stack closures are not first-class. That is, they can ...
{ max = x }
conditional_block
ch15-closures.rs
/*Named functions, like those we've seen so far, may not refer to local variables declared outside the function: they do not close over their environment (sometimes referred to as "capturing" variables in their environment). A closure does support accessing the enclosing scope */ let x = 3; // `fun` is an invalid de...
let closure = |x | { println!("{}", x) }; // infers `x: int`, return type `()` // For closures, omitting a return type is *not* synonymous with `-> ()` let add_3 = |y | { 3i + y }; // infers `y: int`, return type `int`. fun(10); // Prints 10 closure(20); // Prints 20 closure(add_3(30)); /...
{ println!("{}", x) }
identifier_body
base.py
""" File: base.py Author: Me Email: yourname@email.com Github: https://github.com/yourname Description:
from django.test import TestCase from django.urls import reverse from django.utils import timezone from django.utils.crypto import get_random_string from rest_framework.test import APITestCase # from oauth2_provider.tests.test_utils import TestCaseUtils from oauth2_provider.models import get_application_model, AccessT...
""" from datetime import timedelta from django.contrib.auth.models import User
random_line_split
base.py
""" File: base.py Author: Me Email: yourname@email.com Github: https://github.com/yourname Description: """ from datetime import timedelta from django.contrib.auth.models import User from django.test import TestCase from django.urls import reverse from django.utils import timezone from django.utils.crypto import get_...
(self): User.objects.create( username='Hello_World' ) assert User.objects.count() == 1, "Should be equal" def set_oauth2_app_by_admin(self, user): app = Application.objects.create( name='SuperAPI OAUTH2 APP', user=user, ...
test_create_user_model
identifier_name
base.py
""" File: base.py Author: Me Email: yourname@email.com Github: https://github.com/yourname Description: """ from datetime import timedelta from django.contrib.auth.models import User from django.test import TestCase from django.urls import reverse from django.utils import timezone from django.utils.crypto import get_...
random = get_random_string(length=1024) access_token = AccessToken.objects.create( user=access_user, scope='read write', expires=timezone.now() + timedelta(minutes=5), token=f'{random}---{access_user.username}', application=app ...
identifier_body
danmaku.dom.js
var transform = (function() { var properties = [ 'oTransform', // Opera 11.5 'msTransform', // IE 9 'mozTransform', 'webkitTransform', 'transform' ]; var style = document.createElement('div').style; for (var i = 0; i < properties.length; i++) { /* istanbul ignore else */ if (properti...
var caf = window.cancelAnimationFrame || window.mozCancelAnimationFrame || window.webkitCancelAnimationFrame || clearTimeout; function binsearch(arr, prop, key) { var mid = 0; var left = 0; var right = arr.length; while (left < right - 1) { mid = (left + right) >> 1; if (key >= arr[mid][prop]) ...
random_line_split
danmaku.dom.js
var transform = (function() { var properties = [ 'oTransform', // Opera 11.5 'msTransform', // IE 9 'mozTransform', 'webkitTransform', 'transform' ]; var style = document.createElement('div').style; for (var i = 0; i < properties.length; i++) { /* istanbul ignore else */ if (properti...
() { if (!this.container) { return this; } pause.call(this); this.clear(); this.container.removeChild(this._.stage); if (this.media) { unbindEvents.call(this, this._.listener); } for (var key in this) { /* istanbul ignore else */ if (Object.prototype.hasOwnProperty.call(this, key)) { ...
destroy
identifier_name
danmaku.dom.js
var transform = (function() { var properties = [ 'oTransform', // Opera 11.5 'msTransform', // IE 9 'mozTransform', 'webkitTransform', 'transform' ]; var style = document.createElement('div').style; for (var i = 0; i < properties.length; i++) { /* istanbul ignore else */ if (properti...
var that = this; var engine = createEngine( this._.engine.framing.bind(this), this._.engine.setup.bind(this), this._.engine.render.bind(this), this._.engine.remove.bind(this) ); function frame() { engine.call(that); that._.requestID = raf(frame); } this._.requestID = raf(frame); r...
{ for (var i = 0; i < this._.runningList.length; i++) { var cmt = this._.runningList[i]; cmt._utc = Date.now() / 1000 - (this.media.currentTime - cmt.time); } }
conditional_block
danmaku.dom.js
var transform = (function() { var properties = [ 'oTransform', // Opera 11.5 'msTransform', // IE 9 'mozTransform', 'webkitTransform', 'transform' ]; var style = document.createElement('div').style; for (var i = 0; i < properties.length; i++) { /* istanbul ignore else */ if (properti...
/* eslint-disable no-invalid-this */ function resize$1() { this._.stage.width = this.container.offsetWidth; this._.stage.height = this.container.offsetHeight; this._.engine.resize(this._.stage); this._.duration = this._.stage.width / this._.speed; return this; } var speed = { get: function() { return...
{ this._.engine.clear(this._.stage, this._.runningList); this._.runningList = []; return this; }
identifier_body
navigation.component.ts
import { Component, AfterViewInit, Input } from '@angular/core'; import { User } from '../../models'; import { AuthenticationService, AlertService } from '../../services'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'nav-menu', template: require('./navigation.component.html') }) exp...
this.showForgotPassword = true; this.showLogIn = false; this.showSignIn = false; } showSignUp(){ this.showSignIn = true; this.showForgotPassword = false; this.showLogIn = false; } closeForgot(){ this.showForgotPassword = false; } closeLogin...
} showForgot(){
random_line_split
navigation.component.ts
import { Component, AfterViewInit, Input } from '@angular/core'; import { User } from '../../models'; import { AuthenticationService, AlertService } from '../../services'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'nav-menu', template: require('./navigation.component.html') }) exp...
(){ this.showForgotPassword = true; this.showLogIn = false; this.showSignIn = false; } showSignUp(){ this.showSignIn = true; this.showForgotPassword = false; this.showLogIn = false; } closeForgot(){ this.showForgotPassword = false; } closeL...
showForgot
identifier_name
navigation.component.ts
import { Component, AfterViewInit, Input } from '@angular/core'; import { User } from '../../models'; import { AuthenticationService, AlertService } from '../../services'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'nav-menu', template: require('./navigation.component.html') }) exp...
showSignUp(){ this.showSignIn = true; this.showForgotPassword = false; this.showLogIn = false; } closeForgot(){ this.showForgotPassword = false; } closeLogin(){ this.showLogIn = false; } closeSignup(){ this.user = this.authService.getLoggedInU...
{ this.showForgotPassword = true; this.showLogIn = false; this.showSignIn = false; }
identifier_body
account_config.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2012 Andrea Cometa. # Email: info@andreacometa.it # Web site: http://www.andreacometa.it # Copyright (C) 2012 Agile Business Group sagl (<http://www.agilebg.com>) # Copyright (C) 2012 ...
class ResCompany(models.Model): _inherit = 'res.company' due_cost_service_id = fields.Many2one('product.product')
res = super(AccountConfigSettings, self).default_get( cr, uid, fields, context) if res: user = self.pool['res.users'].browse(cr, uid, uid, context) res['due_cost_service_id'] = user.company_id.due_cost_service_id.id return res
identifier_body
account_config.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2012 Andrea Cometa. # Email: info@andreacometa.it # Web site: http://www.andreacometa.it # Copyright (C) 2012 Agile Business Group sagl (<http://www.agilebg.com>) # Copyright (C) 2012 ...
return res class ResCompany(models.Model): _inherit = 'res.company' due_cost_service_id = fields.Many2one('product.product')
user = self.pool['res.users'].browse(cr, uid, uid, context) res['due_cost_service_id'] = user.company_id.due_cost_service_id.id
conditional_block
account_config.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2012 Andrea Cometa. # Email: info@andreacometa.it # Web site: http://www.andreacometa.it # Copyright (C) 2012 Agile Business Group sagl (<http://www.agilebg.com>) # Copyright (C) 2012 ...
(models.TransientModel): _inherit = 'account.config.settings' due_cost_service_id = fields.Many2one( related='company_id.due_cost_service_id', help='Default Service for RiBa Due Cost (collection fees) on invoice', domain=[('type', '=', 'service')]) def default_get(self, cr, uid, f...
AccountConfigSettings
identifier_name
account_config.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2012 Andrea Cometa. # Email: info@andreacometa.it # Web site: http://www.andreacometa.it # Copyright (C) 2012 Agile Business Group sagl (<http://www.agilebg.com>) # Copyright (C) 2012 ...
# (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You shoul...
# it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or
random_line_split
Reflector.js
console.warn( "THREE.Reflector: As part of the transition to ES6 Modules, the files in 'examples/js' were deprecated in May 2020 (r117) and will be deleted in December 2020 (r124). You can find more information about developing using ES6 Modules in https://threejs.org/docs/index.html#manual/en/introduction/Import-via-m...
var material = new THREE.ShaderMaterial( { uniforms: THREE.UniformsUtils.clone( shader.uniforms ), fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader } ); material.uniforms[ "tDiffuse" ].value = renderTarget.texture; material.uniforms[ "color" ].value = color; material.uniforms[ "tex...
{ renderTarget.texture.generateMipmaps = false; }
conditional_block
Reflector.js
console.warn( "THREE.Reflector: As part of the transition to ES6 Modules, the files in 'examples/js' were deprecated in May 2020 (r117) and will be deleted in December 2020 (r124). You can find more information about developing using ES6 Modules in https://threejs.org/docs/index.html#manual/en/introduction/Import-via-m...
view.reflect( normal ).negate(); view.add( reflectorWorldPosition ); rotationMatrix.extractRotation( camera.matrixWorld ); lookAtPosition.set( 0, 0, - 1 ); lookAtPosition.applyMatrix4( rotationMatrix ); lookAtPosition.add( cameraWorldPosition ); target.subVectors( reflectorWorldPosition, lookAtPosition...
if ( view.dot( normal ) > 0 ) return;
random_line_split
pragma.rs
use std::fmt; use std::ascii::AsciiExt; use header::{Header, Raw, parsing}; /// The `Pragma` header defined by HTTP/1.0. /// /// > The "Pragma" header field allows backwards compatibility with /// > HTTP/1.0 caches, so that clients can specify a "no-cache" request /// > that they will understand (as Cache-Control was...
}) } } #[test] fn test_parse_header() { let a: Pragma = Header::parse_header(&"no-cache".into()).unwrap(); let b = Pragma::NoCache; assert_eq!(a, b); let c: Pragma = Header::parse_header(&"FoObar".into()).unwrap(); let d = Pragma::Ext("FoObar".to_owned()); assert_eq!(c, d); let ...
fn fmt_header(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(match *self { Pragma::NoCache => "no-cache", Pragma::Ext(ref string) => &string[..],
random_line_split
pragma.rs
use std::fmt; use std::ascii::AsciiExt; use header::{Header, Raw, parsing}; /// The `Pragma` header defined by HTTP/1.0. /// /// > The "Pragma" header field allows backwards compatibility with /// > HTTP/1.0 caches, so that clients can specify a "no-cache" request /// > that they will understand (as Cache-Control was...
} #[test] fn test_parse_header() { let a: Pragma = Header::parse_header(&"no-cache".into()).unwrap(); let b = Pragma::NoCache; assert_eq!(a, b); let c: Pragma = Header::parse_header(&"FoObar".into()).unwrap(); let d = Pragma::Ext("FoObar".to_owned()); assert_eq!(c, d); let e: ::Result<Prag...
{ f.write_str(match *self { Pragma::NoCache => "no-cache", Pragma::Ext(ref string) => &string[..], }) }
identifier_body
pragma.rs
use std::fmt; use std::ascii::AsciiExt; use header::{Header, Raw, parsing}; /// The `Pragma` header defined by HTTP/1.0. /// /// > The "Pragma" header field allows backwards compatibility with /// > HTTP/1.0 caches, so that clients can specify a "no-cache" request /// > that they will understand (as Cache-Control was...
() { let a: Pragma = Header::parse_header(&"no-cache".into()).unwrap(); let b = Pragma::NoCache; assert_eq!(a, b); let c: Pragma = Header::parse_header(&"FoObar".into()).unwrap(); let d = Pragma::Ext("FoObar".to_owned()); assert_eq!(c, d); let e: ::Result<Pragma> = Header::parse_header(&"".i...
test_parse_header
identifier_name
message_dialog.rs
// Copyright 2013-2016, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use libc::c_char; use ffi; use glib::translate::*; use glib::object::{Cast, IsA}; use std::pt...
}
random_line_split
message_dialog.rs
// Copyright 2013-2016, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use libc::c_char; use ffi; use glib::translate::*; use glib::object::{Cast, IsA}; use std::pt...
<'a, I: Into<Option<&'a str>>>(&self, message: I) { let message = message.into(); match message { Some(m) => unsafe { let message: Stash<*const c_char, _> = m.to_glib_none(); ffi::gtk_message_dialog_format_secondary_markup( self.as_ref().to...
set_secondary_markup
identifier_name
message_dialog.rs
// Copyright 2013-2016, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use libc::c_char; use ffi; use glib::translate::*; use glib::object::{Cast, IsA}; use std::pt...
fn set_secondary_text<'a, I: Into<Option<&'a str>>>(&self, message: I) { let message = message.into(); match message { Some(m) => unsafe { let message: Stash<*const c_char, _> = m.to_glib_none(); ffi::gtk_message_dialog_format_secondary_text( ...
{ let message = message.into(); match message { Some(m) => unsafe { let message: Stash<*const c_char, _> = m.to_glib_none(); ffi::gtk_message_dialog_format_secondary_markup( self.as_ref().to_glib_none().0, b"%s\0".as_ptr() as *const c_char,...
identifier_body
HeroBusiness.ts
/** * Created by Moiz.Kachwala on 15-06-2016. */ import HeroRepository = require("./../repository/HeroRepository"); import IHeroBusiness = require("./interfaces/HeroBusiness"); import IHeroModel = require("./../model/interfaces/HeroModel"); import HeroModel = require("./../model/HeroModel"); class
implements IHeroBusiness { private _heroRepository: HeroRepository; constructor () { this._heroRepository = new HeroRepository(); } create (item: IHeroModel, callback: (error: any, result: any) => void) { console.log(JSON.stringify(item)); this._heroRepository.create(item, cal...
HeroBusiness
identifier_name
HeroBusiness.ts
/** * Created by Moiz.Kachwala on 15-06-2016. */ import HeroRepository = require("./../repository/HeroRepository"); import IHeroBusiness = require("./interfaces/HeroBusiness"); import IHeroModel = require("./../model/interfaces/HeroModel"); import HeroModel = require("./../model/HeroModel"); class HeroBusiness imp...
retrieve (callback: (error: any, result: any) => void) { this._heroRepository.retrieve(callback); } update (_id: string, item: IHeroModel, callback: (error: any, result: any) => void) { this._heroRepository.findById(_id, (err, res) => { if(err) callback(err, res); ...
{ console.log(JSON.stringify(item)); this._heroRepository.create(item, callback); }
identifier_body
HeroBusiness.ts
/** * Created by Moiz.Kachwala on 15-06-2016. */ import HeroRepository = require("./../repository/HeroRepository"); import IHeroBusiness = require("./interfaces/HeroBusiness"); import IHeroModel = require("./../model/interfaces/HeroModel"); import HeroModel = require("./../model/HeroModel"); class HeroBusiness imp...
retrieve (callback: (error: any, result: any) => void) { this._heroRepository.retrieve(callback); } update (_id: string, item: IHeroModel, callback: (error: any, result: any) => void) { this._heroRepository.findById(_id, (err, res) => { if(err) callback(err, res); ...
}
random_line_split
solarAdd.py
from omf import feeder import omf.solvers.gridlabd feed = feeder.parse('GC-12.47-1.glm') maxKey = feeder.getMaxKey(feed) print(feed[1]) feed[maxKey + 1] = { 'object': 'node', 'name': 'test_solar_node', 'phases': 'ABCN', 'nominal_voltage': '7200' } feed[maxKey + 2] = { 'object': 'underground_line', 'name': 'test_s...
'object': 'meter', 'name': 'test_solar_meter', 'parent': 'test_solar_node', 'phases': 'ABCN', 'nominal_voltage': '480' } feed[maxKey + 4] = { 'object': 'inverter', 'name': 'test_solar_inverter', 'parent': 'test_solar_meter', 'phases': 'AS', 'inverter_type': 'PWM', 'power_factor': '1.0', 'generator_status': 'ONLIN...
feed[maxKey + 3] = {
random_line_split