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
factory.py
# Copyright 2012 Kevin Ormbrek # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
def create_wsdl_object(self, type, *name_value_pairs): """Creates a WSDL object of the specified `type`. Requested `type` must be defined in the WSDL, in an import specified by the WSDL, or with `Add Doctor Import`. `type` is case sensitive. Example: | ${contact}= ...
"""Gets the attribute of a WSDL object. Extendend variable syntax may be used to access attributes; however, some WSDL objects may have attribute names that are illegal in Python, necessitating this keyword. Example: | ${sale record}= | Call Soap Method | getLastSale ...
identifier_body
factory.py
# Copyright 2012 Kevin Ormbrek # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
(object): def set_wsdl_object_attribute(self, object, name, value): """Sets the attribute of a WSDL object. Example: | ${order search request}= | Create Wsdl Object | OrderSearchRequest | | | Set Wsdl Object Attribute | ${order search request} | id | 4065...
_FactoryKeywords
identifier_name
daint.rs
#[doc = "Register `DAINT` reader"] pub struct R(crate::R<DAINT_SPEC>); impl core::ops::Deref for R { type Target = crate::R<DAINT_SPEC>; #[inline(always)] fn
(&self) -> &Self::Target { &self.0 } } impl From<crate::R<DAINT_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<DAINT_SPEC>) -> Self { R(reader) } } #[doc = "Field `InEpInt` reader - IN Endpoint Interrupt Bits"] pub struct INEPINT_R(crate::FieldReader<u16, u16>); impl INEPINT_R...
deref
identifier_name
daint.rs
#[doc = "Register `DAINT` reader"] pub struct R(crate::R<DAINT_SPEC>); impl core::ops::Deref for R { type Target = crate::R<DAINT_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<DAINT_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<DAI...
} impl core::ops::Deref for OUTEPINT_R { type Target = crate::FieldReader<u16, u16>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl R { #[doc = "Bits 0:15 - IN Endpoint Interrupt Bits"] #[inline(always)] pub fn in_ep_int(&self) -> INEPINT_R { INEPINT_R...
{ OUTEPINT_R(crate::FieldReader::new(bits)) }
identifier_body
daint.rs
#[doc = "Register `DAINT` reader"] pub struct R(crate::R<DAINT_SPEC>); impl core::ops::Deref for R { type Target = crate::R<DAINT_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<DAINT_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<DAI...
pub struct DAINT_SPEC; impl crate::RegisterSpec for DAINT_SPEC { type Ux = u32; } #[doc = "`read()` method returns [daint::R](R) reader structure"] impl crate::Readable for DAINT_SPEC { type Reader = R; } #[doc = "`reset()` method sets DAINT to value 0"] impl crate::Resettable for DAINT_SPEC { #[inline(alwa...
} #[doc = "Device All Endpoints Interrupt Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [daint](index.html) module"]
random_line_split
detector.py
""" Protocol Buffer Breaking Change Detector This tool is used to detect "breaking changes" in protobuf files, to ensure proper backwards-compatibility in protobuf API updates. The tool can check for breaking changes of a single API by taking 2 .proto file paths as input (before and after) and outputting a bool `is_br...
def run_detector(self) -> None: self._final_result = check_breaking( self._buf_path, self._path_to_changed_dir, git_ref=self._git_ref, git_path=self._git_path, subdir=self._subdir, config_file_loc=self._config_file_loc, ad...
"""Initialize the configuration of buf This function sets up any necessary config without actually running buf against any proto files. BufWrapper takes a path to a directory containing proto files as input, and it checks if these proto files break any changes from a given init...
identifier_body
detector.py
""" Protocol Buffer Breaking Change Detector This tool is used to detect "breaking changes" in protobuf files, to ensure proper backwards-compatibility in protobuf API updates. The tool can check for breaking changes of a single API by taking 2 .proto file paths as input (before and after) and outputting a bool `is_br...
return filter(lambda x: len(x) > 0, final_out) if self.is_breaking() else []
random_line_split
detector.py
""" Protocol Buffer Breaking Change Detector This tool is used to detect "breaking changes" in protobuf files, to ensure proper backwards-compatibility in protobuf API updates. The tool can check for breaking changes of a single API by taking 2 .proto file paths as input (before and after) and outputting a bool `is_br...
(self) -> List[str]: """Return a list of strings containing breaking changes output by the tool""" pass class BufWrapper(ProtoBreakingChangeDetector): """Breaking change detector implemented with buf""" def __init__( self, path_to_changed_dir: str, git_ref:...
get_breaking_changes
identifier_name
detector.py
""" Protocol Buffer Breaking Change Detector This tool is used to detect "breaking changes" in protobuf files, to ensure proper backwards-compatibility in protobuf API updates. The tool can check for breaking changes of a single API by taking 2 .proto file paths as input (before and after) and outputting a bool `is_br...
if Path.cwd() not in Path(path_to_changed_dir).parents: raise ValueError( f"path_to_changed_dir {path_to_changed_dir} must be a subdirectory of the cwd ({ Path.cwd() })" ) if not Path(git_path).exists(): raise ChangeDetectorError(f'path to .git fold...
raise ValueError(f"path_to_changed_dir {path_to_changed_dir} is not a valid directory")
conditional_block
htmlhrelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLHRElementBinding; use dom::bindings::js::Root; use dom::document::Docume...
}
{ let element = HTMLHRElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLHRElementBinding::Wrap) }
identifier_body
htmlhrelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLHRElementBinding; use dom::bindings::js::Root; use dom::document::Docume...
(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> HTMLHRElement { HTMLHRElement { htmlelement: HTMLElement::new_inherited(localName, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMStrin...
new_inherited
identifier_name
htmlhrelement.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLHRElementBinding; use dom::bindings::js::Root; use dom::document::Docume...
#[allow(unrooted_must_root)] pub fn new(localName: DOMString, prefix: Option<DOMString>, document: &Document) -> Root<HTMLHRElement> { let element = HTMLHRElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLHRElementBi...
htmlelement: HTMLElement::new_inherited(localName, prefix, document) } }
random_line_split
pseudo_element.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Gecko's definition of a pseudo-element. //! //! Note that a few autogenerated bits of this live in //! `pseudo...
/// Covert non-canonical pseudo-element to canonical one, and keep a /// canonical one as it is. pub fn canonical(&self) -> PseudoElement { match *self { PseudoElement::MozPlaceholder => PseudoElement::Placeholder, _ => self.clone(), } } /// Property flag t...
{ self.is_anon_box() }
identifier_body
pseudo_element.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Gecko's definition of a pseudo-element. //! //! Note that a few autogenerated bits of this live in //! `pseudo...
}
random_line_split
pseudo_element.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Gecko's definition of a pseudo-element. //! //! Note that a few autogenerated bits of this live in //! `pseudo...
(&self) -> Option<PropertyFlags> { match *self { PseudoElement::FirstLetter => Some(PropertyFlags::APPLIES_TO_FIRST_LETTER), PseudoElement::FirstLine => Some(PropertyFlags::APPLIES_TO_FIRST_LINE), PseudoElement::Placeholder => Some(PropertyFlags::APPLIES_TO_PLACEHOLDER), ...
property_restriction
identifier_name
CreateSamples.py
import os import unittest from __main__ import vtk, qt, ctk, slicer from slicer.ScriptedLoadableModule import * import logging # # CreateSamples # class CreateSamples(ScriptedLoadableModule): """Uses ScriptedLoadableModule base class, available at: https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/S...
"""This class should implement all the actual computation done by your module. The interface should be such that other python code can import this class and make use of the functionality without requiring an instance of the Widget. Uses ScriptedLoadableModuleLogic base class, available at: https://github...
class CreateSamplesLogic(ScriptedLoadableModuleLogic):
random_line_split
CreateSamples.py
import os import unittest from __main__ import vtk, qt, ctk, slicer from slicer.ScriptedLoadableModule import * import logging # # CreateSamples # class CreateSamples(ScriptedLoadableModule): """Uses ScriptedLoadableModule base class, available at: https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/S...
(self): """ Do whatever is needed to reset the state - typically a scene clear will be enough. """ slicer.mrmlScene.Clear(0) def runTest(self): """Run as few or as many tests as needed here. """ self.setUp()
setUp
identifier_name
CreateSamples.py
import os import unittest from __main__ import vtk, qt, ctk, slicer from slicer.ScriptedLoadableModule import * import logging # # CreateSamples # class CreateSamples(ScriptedLoadableModule): """Uses ScriptedLoadableModule base class, available at: https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/S...
else: volumeDisplayNode = slicer.vtkMRMLScalarVolumeDisplayNode() slicer.mrmlScene.AddNode(volumeDisplayNode) colorNode = slicer.util.getNode('Grey') volumeDisplayNode.SetAndObserveColorNodeID(colorNode.GetID()) volumeDisplayNode.VisibilityOn() sampleVolumeNode.SetAn...
sampleVolumeNode.SetLabelMap(1) labelmapVolumeDisplayNode = slicer.vtkMRMLLabelMapVolumeDisplayNode() slicer.mrmlScene.AddNode(labelmapVolumeDisplayNode) colorNode = slicer.util.getNode('GenericAnatomyColors') labelmapVolumeDisplayNode.SetAndObserveColorNodeID(colorNode.GetID()) ...
conditional_block
CreateSamples.py
import os import unittest from __main__ import vtk, qt, ctk, slicer from slicer.ScriptedLoadableModule import * import logging # # CreateSamples # class CreateSamples(ScriptedLoadableModule): """Uses ScriptedLoadableModule base class, available at: https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/S...
"""Run as few or as many tests as needed here. """ self.setUp()
identifier_body
flatten.rs
use std::borrow::Cow; use std::io::{self, Write}; use tabwriter::TabWriter; use CliResult; use config::{Config, Delimiter}; use util; static USAGE: &'static str = " Prints flattened records such that fields are labeled separated by a new line. This mode is particularly useful for viewing one record at a time. Each r...
{ let args: Args = util::get_args(USAGE, argv)?; let rconfig = Config::new(&args.arg_input) .delimiter(args.flag_delimiter) .no_headers(args.flag_no_headers); let mut rdr = rconfig.reader()?; let headers = rdr.byte_headers()?.clone(); let mut wtr = TabWriter::new(io::stdout()); ...
identifier_body
flatten.rs
use std::borrow::Cow; use std::io::{self, Write}; use tabwriter::TabWriter; use CliResult; use config::{Config, Delimiter}; use util; static USAGE: &'static str = " Prints flattened records such that fields are labeled separated by a new line. This mode is particularly useful for viewing one record at a time. Each r...
-d, --delimiter <arg> The field delimiter for reading CSV data. Must be a single character. (default: ,) "; #[derive(RustcDecodable)] struct Args { arg_input: Option<String>, flag_condense: Option<usize>, flag_separator: String, flag_no_headers: bool, flag_delimiter:...
Common options: -h, --help Display this message -n, --no-headers When set, the first row will not be interpreted as headers. When set, the name of each field will be its index.
random_line_split
flatten.rs
use std::borrow::Cow; use std::io::{self, Write}; use tabwriter::TabWriter; use CliResult; use config::{Config, Delimiter}; use util; static USAGE: &'static str = " Prints flattened records such that fields are labeled separated by a new line. This mode is particularly useful for viewing one record at a time. Each r...
wtr.write_all(b"\t")?; wtr.write_all(&*util::condense( Cow::Borrowed(&*field), args.flag_condense))?; wtr.write_all(b"\n")?; } } wtr.flush()?; Ok(()) }
{ wtr.write_all(&header)?; }
conditional_block
flatten.rs
use std::borrow::Cow; use std::io::{self, Write}; use tabwriter::TabWriter; use CliResult; use config::{Config, Delimiter}; use util; static USAGE: &'static str = " Prints flattened records such that fields are labeled separated by a new line. This mode is particularly useful for viewing one record at a time. Each r...
(argv: &[&str]) -> CliResult<()> { let args: Args = util::get_args(USAGE, argv)?; let rconfig = Config::new(&args.arg_input) .delimiter(args.flag_delimiter) .no_headers(args.flag_no_headers); let mut rdr = rconfig.reader()?; let headers = rdr.byte_headers()?.clone(); let mut wtr = T...
run
identifier_name
lib.rs
//! Library that contains utility functions for tests. //! //! It also contains a test module, which checks if all source files are covered by `Cargo.toml` extern crate hyper; extern crate regex; extern crate rustc_serialize; pub mod rosetta_code; use std::fmt::Debug; #[allow(dead_code)] fn main() {} /// Check if ...
}
{ sources.difference(paths).collect() }
identifier_body
lib.rs
//! Library that contains utility functions for tests. //! //! It also contains a test module, which checks if all source files are covered by `Cargo.toml` extern crate hyper; extern crate regex; extern crate rustc_serialize; pub mod rosetta_code; use std::fmt::Debug; #[allow(dead_code)] fn main() {} /// Check if ...
() { let unsorted = vec![1, 3, 2]; check_sorted(&unsorted); } #[cfg(test)] mod tests { use regex::Regex; use std::collections::HashSet; use std::io::{BufReader, BufRead}; use std::fs::{self, File}; use std::path::Path; /// A test to check if all source files are covered by `Cargo.toml...
test_check_unsorted
identifier_name
lib.rs
//! Library that contains utility functions for tests. //! //! It also contains a test module, which checks if all source files are covered by `Cargo.toml` extern crate hyper; extern crate regex; extern crate rustc_serialize; pub mod rosetta_code; use std::fmt::Debug; #[allow(dead_code)] fn main() {} /// Check if ...
} /// Returns the names of the source files in the `src` directory fn get_source_files() -> HashSet<String> { let paths = fs::read_dir("./src").unwrap(); paths.map(|p| { p.unwrap() .path() .file_name() .unwrap() ...
{ println!("Error, the following source files are not covered by Cargo.toml:"); for source in &not_covered { println!("{}", source); } panic!("Please add the previous source files to Cargo.toml"); }
conditional_block
lib.rs
//! Library that contains utility functions for tests. //! //! It also contains a test module, which checks if all source files are covered by `Cargo.toml` extern crate hyper; extern crate regex; extern crate rustc_serialize; pub mod rosetta_code; use std::fmt::Debug; #[allow(dead_code)] fn main() {} /// Check if ...
/// Returns the paths of the source files referenced in Cargo.toml fn get_toml_paths() -> HashSet<String> { let c_toml = File::open("./Cargo.toml").unwrap(); let reader = BufReader::new(c_toml); let regex = Regex::new("path = \"(.*)\"").unwrap(); reader.lines() .filte...
}
random_line_split
variablesView.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
return null; } } class VariablesController extends BaseDebugController { protected onLeftClick(tree: ITree, element: any, event: IMouseEvent): boolean { // double click on primitive value: open input box to be able to set the value const process = this.debugService.getViewModel().focusedProcess; if (eleme...
{ return nls.localize('variableAriaLabel', "{0} value {1}, variables, debug", (<Variable>element).name, (<Variable>element).value); }
conditional_block
variablesView.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
implements IDataSource { public getId(tree: ITree, element: any): string { return element.getId(); } public hasChildren(tree: ITree, element: any): boolean { if (element instanceof ViewModel || element instanceof Scope) { return true; } let variable = <Variable>element; return variable.hasChildren &...
VariablesDataSource
identifier_name
variablesView.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
public getActions(tree: ITree, element: any): TPromise<IAction[]> { return TPromise.as([]); } public hasSecondaryActions(tree: ITree, element: any): boolean { // Only show context menu on "real" variables. Not on array chunk nodes. return element instanceof Variable && !!element.value; } public getSecond...
{ return false; }
identifier_body
variablesView.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
return null; } } class VariablesController extends BaseDebugController { protected onLeftClick(tree: ITree, element: any, event: IMouseEvent): boolean { // double click on primitive value: open input box to be able to set the value const process = this.debugService.getViewModel().focusedProcess; if (elemen...
}
random_line_split
rcp_log_linter.py
#!/usr/bin/env python3 import optparse class RcpLogValidator(object): MAX_ERRORS = 25 MAX_INTERVAL_STEP_MS = 3000 MIN_INTERVAL_STEP_MS = 1 def __init__(self): self.interval = 0 self.columns = 0 def _count_commas(self, line): return line.count(',') def _validate_colum...
print() print("=== Final Stats ===") print(" Lines Checked: {}".format(line_no)) print(" Errors Found: {}".format(errors)) print() def clean_logfile(self, input_path, output_path): errors = 0 line_no = 0 with open(input_path, 'r') as file_in: ...
line_no += 1 if errors >= self.MAX_ERRORS: break if not self._validate_line(line, line_no): errors += 1
conditional_block
rcp_log_linter.py
#!/usr/bin/env python3 import optparse class RcpLogValidator(object): MAX_ERRORS = 25 MAX_INTERVAL_STEP_MS = 3000 MIN_INTERVAL_STEP_MS = 1 def __init__(self): self.interval = 0 self.columns = 0 def _count_commas(self, line): return line.count(',') def _validate_colum...
def _validate_interval_time(self, line, line_no): try: interval = int(line.split(',', 1)[0]) except ValueError: interval = 0 # Deal with initialization. if self.interval == 0: self.interval = interval return True interval_min...
print(("Error: Column count mismatch on line {}. Expected {}, " + "found {}").format(line_no, self.columns, columns)) return False
random_line_split
rcp_log_linter.py
#!/usr/bin/env python3 import optparse class RcpLogValidator(object): MAX_ERRORS = 25 MAX_INTERVAL_STEP_MS = 3000 MIN_INTERVAL_STEP_MS = 1 def __init__(self): self.interval = 0 self.columns = 0 def _count_commas(self, line): return line.count(',') def _validate_colum...
def clean_logfile(self, input_path, output_path): errors = 0 line_no = 0 with open(input_path, 'r') as file_in: with open(output_path, 'w') as file_out: for line in file_in: line_no += 1 if not self._validate_line(line, ...
errors = 0 line_no = 0 with open(log_path, 'r') as fil: for line in fil: line_no += 1 if errors >= self.MAX_ERRORS: break if not self._validate_line(line, line_no): errors += 1 print() ...
identifier_body
rcp_log_linter.py
#!/usr/bin/env python3 import optparse class RcpLogValidator(object): MAX_ERRORS = 25 MAX_INTERVAL_STEP_MS = 3000 MIN_INTERVAL_STEP_MS = 1 def __init__(self): self.interval = 0 self.columns = 0 def _count_commas(self, line): return line.count(',') def
(self, line, line_no): columns = self._count_commas(line) if columns == self.columns: return True # If here we failed. Print msg. print(("Error: Column count mismatch on line {}. Expected {}, " + "found {}").format(line_no, self.columns, columns)) re...
_validate_column_count
identifier_name
004-ship-movement.js
/* demo/test/004-ship-controls.js */ define ([ 'keypress', 'physicsjs', 'howler', '1401/objects/sysloop', '1401/settings', '1401/system/renderer', '1401/system/visualfactory', '1401/system/piecefactory', '1401-games/demo/modules/controls' ], function ( KEY, PHYSICS, HOWLER, SYSLOOP, SETTINGS, RENDERER, ...
( interval_ms ) { vp = RENDERER.Viewport(); vp.Track(crixa.Position()); /* rotate stars */ layers = starfields.length; for (i=0;i<starfields.length;i++){ sf = starfields[i]; sf.Track(crixa.Position()); } counter += interval_ms; } /////////////////////////////////////////////////////////////...
m_Update
identifier_name
004-ship-movement.js
/* demo/test/004-ship-controls.js */ define ([ 'keypress', 'physicsjs', 'howler', '1401/objects/sysloop', '1401/settings', '1401/system/renderer', '1401/system/visualfactory', '1401/system/piecefactory', '1401-games/demo/modules/controls' ], function ( KEY, PHYSICS, HOWLER, SYSLOOP, SETTINGS, RENDERER, ...
/// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - var counter = 0; var dx = 3; function m_Update ( interval_ms ) { vp = RENDERER.Viewport(); vp.Track(crixa.Position()); /* rotate stars */ layers = starfields.length; for (i=0;i<starfields.length;i++){ sf = starfields[i];...
{ cin = crixa_inputs = SHIPCONTROLS.GetInput(); if (!!crixa_inputs.forward_acc) { crixa.Visual().GoSequence("flicker",1); } else { crixa.Visual().GoSequence("flicker",0); } crixa.Accelerate(cin.forward_acc,cin.side_acc); crixa.Brake(crixa_inputs.brake_lin); crixa.AccelerateRotation(cin.rot_acc); c...
identifier_body
004-ship-movement.js
/* demo/test/004-ship-controls.js */ define ([ 'keypress', 'physicsjs', 'howler', '1401/objects/sysloop', '1401/settings', '1401/system/renderer', '1401/system/visualfactory', '1401/system/piecefactory', '1401-games/demo/modules/controls' ], function ( KEY, PHYSICS, HOWLER, SYSLOOP, SETTINGS, RENDERER, ...
});
random_line_split
004-ship-movement.js
/* demo/test/004-ship-controls.js */ define ([ 'keypress', 'physicsjs', 'howler', '1401/objects/sysloop', '1401/settings', '1401/system/renderer', '1401/system/visualfactory', '1401/system/piecefactory', '1401-games/demo/modules/controls' ], function ( KEY, PHYSICS, HOWLER, SYSLOOP, SETTINGS, RENDERER, ...
/* make crixa ship */ var shipSprite = VISUALFACTORY.MakeDefaultSprite(); shipSprite.SetZoom(1.0); RENDERER.AddWorldVisual(shipSprite); var seq = { grid: { columns:2, rows:1, stacked:true }, sequences: [ { name: 'flicker', framecount: 2, fps:4 } ]...
{ starSpec.color=starBright[i]; var sf = VISUALFACTORY.MakeStarField( starSpec ); starSpec.parallax *= 0.5; sf.position.set(0,0,-100-i); RENDERER.AddBackgroundVisual(sf); starfields.push(sf); }
conditional_block
expr-match-generic-unique1.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
<T: Clone, F>(expected: Box<T>, eq: F) where F: FnOnce(Box<T>, Box<T>) -> bool { let actual: Box<T> = match true { true => { expected.clone() }, _ => panic!("wat") }; assert!(eq(expected, actual)); } fn test_box() { fn compare_box(b1: Box<bool>, b2: Box<bool>) -> bool { return *...
test_generic
identifier_name
expr-match-generic-unique1.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
, _ => panic!("wat") }; assert!(eq(expected, actual)); } fn test_box() { fn compare_box(b1: Box<bool>, b2: Box<bool>) -> bool { return *b1 == *b2; } test_generic::<bool, _>(box true, compare_box); } pub fn main() { test_box(); }
{ expected.clone() }
conditional_block
expr-match-generic-unique1.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn main() { test_box(); }
{ fn compare_box(b1: Box<bool>, b2: Box<bool>) -> bool { return *b1 == *b2; } test_generic::<bool, _>(box true, compare_box); }
identifier_body
expr-match-generic-unique1.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
assert!(eq(expected, actual)); } fn test_box() { fn compare_box(b1: Box<bool>, b2: Box<bool>) -> bool { return *b1 == *b2; } test_generic::<bool, _>(box true, compare_box); } pub fn main() { test_box(); }
_ => panic!("wat") };
random_line_split
main-page.component.ts
import { Component, OnInit, ComponentFactoryResolver, Injector, ChangeDetectionStrategy } from '@angular/core'; import { Observable, combineLatest } from 'rxjs'; import { map } from 'rxjs/operators'; import { WebAppSettingDataService, NewUrlStateNotificationService, AnalyticsService, TRACKED_EVENT_LIST, DynamicPopupSe...
constructor( private newUrlStateNotificationService: NewUrlStateNotificationService, private webAppSettingDataService: WebAppSettingDataService, private analyticsService: AnalyticsService, private dynamicPopupService: DynamicPopupService, private componentFactoryResolver: Com...
isAppKeyProvided$: Observable<boolean>;
random_line_split
main-page.component.ts
import { Component, OnInit, ComponentFactoryResolver, Injector, ChangeDetectionStrategy } from '@angular/core'; import { Observable, combineLatest } from 'rxjs'; import { map } from 'rxjs/operators'; import { WebAppSettingDataService, NewUrlStateNotificationService, AnalyticsService, TRACKED_EVENT_LIST, DynamicPopupSe...
() { this.enableRealTime$ = combineLatest( this.newUrlStateNotificationService.onUrlStateChange$.pipe( map((urlService: NewUrlStateNotificationService) => urlService.isRealTimeMode()) ), this.webAppSettingDataService.useActiveThreadChart() ).pipe( ...
ngOnInit
identifier_name
main-page.component.ts
import { Component, OnInit, ComponentFactoryResolver, Injector, ChangeDetectionStrategy } from '@angular/core'; import { Observable, combineLatest } from 'rxjs'; import { map } from 'rxjs/operators'; import { WebAppSettingDataService, NewUrlStateNotificationService, AnalyticsService, TRACKED_EVENT_LIST, DynamicPopupSe...
ngOnInit() { this.enableRealTime$ = combineLatest( this.newUrlStateNotificationService.onUrlStateChange$.pipe( map((urlService: NewUrlStateNotificationService) => urlService.isRealTimeMode()) ), this.webAppSettingDataService.useActiveThreadChart() ...
{}
identifier_body
color.ts
import {constrainRange, loopRange} from '../../../common/number-util'; import {isEmpty} from '../../../misc/type-util'; import { appendAlphaComponent, ColorComponents3, ColorComponents4, ColorMode, convertColorMode, removeAlphaComponent, } from './color-model'; export interface RgbColorObject { r: number; g: n...
public getComponents(opt_mode?: ColorMode): ColorComponents4 { return appendAlphaComponent( convertColorMode( removeAlphaComponent(this.comps_), this.mode_, opt_mode || this.mode_, ), this.comps_[3], ); } public toRgbaObject(): RgbaColorObject { const rgbComps = this.getComponents('rgb'...
{ return this.mode_; }
identifier_body
color.ts
import {constrainRange, loopRange} from '../../../common/number-util'; import {isEmpty} from '../../../misc/type-util'; import { appendAlphaComponent, ColorComponents3, ColorComponents4, ColorMode, convertColorMode, removeAlphaComponent, } from './color-model'; export interface RgbColorObject { r: number; g: n...
public static isRgbColorObject(obj: unknown): obj is RgbColorObject { return ( isRgbColorComponent(obj, 'r') && isRgbColorComponent(obj, 'g') && isRgbColorComponent(obj, 'b') ); } public static isRgbaColorObject(obj: unknown): obj is RgbaColorObject { return this.isRgbColorObject(obj) && isRgbColorC...
public static toRgbaObject(color: Color): RgbaColorObject { return color.toRgbaObject(); }
random_line_split
color.ts
import {constrainRange, loopRange} from '../../../common/number-util'; import {isEmpty} from '../../../misc/type-util'; import { appendAlphaComponent, ColorComponents3, ColorComponents4, ColorMode, convertColorMode, removeAlphaComponent, } from './color-model'; export interface RgbColorObject { r: number; g: n...
} return true; } private comps_: ColorComponents4; private mode_: ColorMode; constructor(comps: ColorComponents3 | ColorComponents4, mode: ColorMode) { this.mode_ = mode; this.comps_ = CONSTRAINT_MAP[mode](comps); } public get mode(): ColorMode { return this.mode_; } public getComponents(opt_mode...
{ return false; }
conditional_block
color.ts
import {constrainRange, loopRange} from '../../../common/number-util'; import {isEmpty} from '../../../misc/type-util'; import { appendAlphaComponent, ColorComponents3, ColorComponents4, ColorMode, convertColorMode, removeAlphaComponent, } from './color-model'; export interface RgbColorObject { r: number; g: n...
(): RgbaColorObject { const rgbComps = this.getComponents('rgb'); return { r: rgbComps[0], g: rgbComps[1], b: rgbComps[2], a: rgbComps[3], }; } }
toRgbaObject
identifier_name
a00116.js
var a00116 = [ [ "Advertising Data Encoder", "a00118.html", null ], [ "Debug Assert Handler", "a00119.html", null ], [ "BLE Device Manager", "a00126.html", [ [ "Initialization", "a00126.html#lib_device_manaegerit", [ [ "Associated Events", "a00126.html#lib_device_manager_init_evt", null ], ...
[ "Initialization and Set-up", "a00120.html#lib_ble_conn_params_init", null ], [ "Shutdown", "a00120.html#lib_ble_conn_params_stop", null ], [ "Change/Update Connection Parameters Negotiated", "a00120.html#lib_ble_conn_params_change_conn_params", null ] ] ], [ "DTM - Direct Test Mode", "a00121...
] ] ] ], [ "Connection Parameters Negotiation", "a00120.html", [ [ "Overview", "a00120.html#Overview", null ],
random_line_split
plan-side-display.component.spec.ts
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in ...
}); });
random_line_split
main.rs
extern crate sdl2; extern crate rand; extern crate tile_engine; extern crate chrono; extern crate dungeon_generator; extern crate sdl2_image; mod visualizer; mod game; mod unit; mod common; mod ai; mod portal; use sdl2::event::Event; use visualizer::Visualizer; use game::Game; use chrono::{DateTime, UTC}; use std::ti...
() { // start sdl2 with everything let ctx = sdl2::init().unwrap(); let video_ctx = ctx.video().unwrap(); let mut lag = 0; let mut last_tick: DateTime<UTC> = UTC::now(); let _image_context = sdl2_image::init(INIT_PNG | INIT_JPG).unwrap(); // Create a window let window = match video_ct...
main
identifier_name
main.rs
extern crate sdl2; extern crate rand; extern crate tile_engine; extern crate chrono; extern crate dungeon_generator; extern crate sdl2_image; mod visualizer; mod game; mod unit; mod common; mod ai; mod portal; use sdl2::event::Event; use visualizer::Visualizer; use game::Game; use chrono::{DateTime, UTC}; use std::ti...
{ // start sdl2 with everything let ctx = sdl2::init().unwrap(); let video_ctx = ctx.video().unwrap(); let mut lag = 0; let mut last_tick: DateTime<UTC> = UTC::now(); let _image_context = sdl2_image::init(INIT_PNG | INIT_JPG).unwrap(); // Create a window let window = match video_ctx.w...
identifier_body
main.rs
extern crate sdl2; extern crate rand; extern crate tile_engine; extern crate chrono; extern crate dungeon_generator; extern crate sdl2_image; mod visualizer; mod game; mod unit; mod common; mod ai; mod portal; use sdl2::event::Event; use visualizer::Visualizer; use game::Game; use chrono::{DateTime, UTC}; use std::ti...
let mut visualizer = Visualizer::new(renderer); // loop until we receive a QuitEvent 'event : loop { for event in events.poll_iter() { match event { Event::Quit{..} => break 'event, _ => game.proc_event(event), } } ...
random_line_split
BBSProfile.ts
import {Document, Model, Schema, Types, model} from 'mongoose' import {IUser} from './User' const ObjectId = Schema.Types.ObjectId const BBSProfileSchema = new Schema({ // 用户 user: {type: ObjectId, ref: 'User', required: true}, // uid uid: {type: String, required: true}, // 用户名 username: {type: String, re...
uid: String, username: String, avatar: String, joinAt: Date } export interface IBBSProfileModel extends Model<IBBSProfile> {} export default model<IBBSProfile, IBBSProfileModel>('BBSProfile', BBSProfileSchema)
user: Types.ObjectId | IUser,
random_line_split
ppc.manager.js
(function(){ // Manager (static) ppc.manager = cloz(base, { init: function(){ try { ppc.logger.get('add', 'PPCの初期化を開始しました', 0, 'start initialization'); // 最大同時接続数を設定 ppc.user.set('connections', ppc.parser.created.get('val', 'connections')); // 測定日時を設定 var now = (new Date()).getTime() + (new Date())...
ting-count'), scored = ppc.parser.home.get('illust_figures', j, 'score'), commented = ppc.parser.home.get('illust_figures', j, 'comments'), viewed = ppc.parser.home.get('illust_figures', j, 'views'); illust.set('rated', rated); illust.set('scored', scored); illust.set('commented', commented)...
ト数・閲覧数 var rated = ppc.parser.home.get('illust_figures', j, 'ra
conditional_block
ppc.manager.js
(function(){ // Manager (static) ppc.manager = cloz(base, { init: function(){ try { ppc.logger.get('add', 'PPCの初期化を開始しました', 0, 'start initialization'); // 最大同時接続数を設定 ppc.user.set('connections', ppc.parser.created.get('val', 'connections')); // 測定日時を設定 var now = (new Date()).getTime() + (new Date())...
} // 最大測定対象数が測定対象下限数を下回っている場合、測定対象下限数に丸める if (max_illusts < ppc.admin.get('min_illusts')) { ppc.user.set('illusts', ppc.admin.get('min_illusts')); } // 測定するイラスト数を設定 var illusts = ppc.user.set('illusts', ppc.parser.home.get('length', 'illust')); // 最大測定対象数より表示されているイラストが多い場合、最大測定対象数に丸める if ...
random_line_split
functions.rs
use neon::prelude::*; use neon::object::This; use neon::result::Throw; fn add1(mut cx: FunctionContext) -> JsResult<JsNumber> { let x = cx.argument::<JsNumber>(0)?.value(); Ok(cx.number(x + 1.0)) } pub fn return_js_function(mut cx: FunctionContext) -> JsResult<JsFunction> { JsFunction::new(&mut cx, add1) ...
(mut cx: FunctionContext) -> JsResult<JsNumber> { let n = cx.len(); Ok(cx.number(n)) } pub fn return_this(mut cx: FunctionContext) -> JsResult<JsValue> { Ok(cx.this().upcast()) } pub fn require_object_this(mut cx: FunctionContext) -> JsResult<JsUndefined> { let this = cx.this(); let this = this.do...
num_arguments
identifier_name
functions.rs
use neon::prelude::*; use neon::object::This; use neon::result::Throw; fn add1(mut cx: FunctionContext) -> JsResult<JsNumber> { let x = cx.argument::<JsNumber>(0)?.value(); Ok(cx.number(x + 1.0)) } pub fn return_js_function(mut cx: FunctionContext) -> JsResult<JsFunction> { JsFunction::new(&mut cx, add1) ...
{ let s = cx.string("hi"); if let Err(e) = s.downcast::<JsNumber>() { Ok(cx.string(format!("{}", e))) } else { panic!() } }
identifier_body
functions.rs
use neon::prelude::*; use neon::object::This; use neon::result::Throw; fn add1(mut cx: FunctionContext) -> JsResult<JsNumber> { let x = cx.argument::<JsNumber>(0)?.value(); Ok(cx.number(x + 1.0)) } pub fn return_js_function(mut cx: FunctionContext) -> JsResult<JsFunction> { JsFunction::new(&mut cx, add1) ...
pub fn compute_scoped(mut cx: FunctionContext) -> JsResult<JsNumber> { let mut i = cx.number(0); for _ in 1..100 { i = cx.compute_scoped(|mut cx| { let n = cx.number(1); Ok(cx.number((i.value() as i32) + (n.value() as i32))) })?; } Ok(i) } pub fn throw_and_catch...
Ok(cx.number(i)) }
random_line_split
functions.rs
use neon::prelude::*; use neon::object::This; use neon::result::Throw; fn add1(mut cx: FunctionContext) -> JsResult<JsNumber> { let x = cx.argument::<JsNumber>(0)?.value(); Ok(cx.number(x + 1.0)) } pub fn return_js_function(mut cx: FunctionContext) -> JsResult<JsFunction> { JsFunction::new(&mut cx, add1) ...
else { panic!() } }
{ Ok(cx.string(format!("{}", e))) }
conditional_block
commands.test.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
}); let a = commands.executeCommand('vscode.diff', Uri.parse('sc:a'), Uri.parse('sc:b'), 'DIFF').then(value => { assert.ok(value === undefined); registration.dispose(); }); let b = commands.executeCommand('vscode.diff', Uri.parse('sc:a'), Uri.parse('sc:b')).then(value => { assert.ok(value === undef...
{ return `content of URI <b>${uri.toString()}</b>#${Math.random()}`; }
identifier_body
commands.test.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
} assert.ok(!hasOneWithUnderscore); }, done); Promise.all([p1, p2]).then(() => { done(); }, done); }); test('command with args', async function () { let args: IArguments; let registration = commands.registerCommand('t1', function () { args = arguments; }); await commands.executeCommand('...
for (let command of commands) { if (command[0] === '_') { hasOneWithUnderscore = true; break; }
random_line_split
commands.test.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
} assert.ok(!hasOneWithUnderscore); }, done); Promise.all([p1, p2]).then(() => { done(); }, done); }); test('command with args', async function () { let args: IArguments; let registration = commands.registerCommand('t1', function () { args = arguments; }); await commands.executeCommand(...
{ hasOneWithUnderscore = true; break; }
conditional_block
commands.test.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
(uri) { return `content of URI <b>${uri.toString()}</b>#${Math.random()}`; } }); let a = commands.executeCommand('vscode.diff', Uri.parse('sc:a'), Uri.parse('sc:b'), 'DIFF').then(value => { assert.ok(value === undefined); registration.dispose(); }); let b = commands.executeCommand('vscode.diff',...
provideTextDocumentContent
identifier_name
screenShare.js
'use strict'; var SIGNALING_SERVER = 'https://112.108.40.152:443/'; var config = { openSocket: function(config) { console.log('s1'); /* Firebase ver. */ var channel = config.channel || 'screen-capturing-' + location.href.replace( /\/|:|#|%|\.|\[|\]/g , ''); var so...
captureUserMedia(callback); }); return; } if(isChrome && !DetectRTC.screen.sourceId) { window.addEventListener('message', function (event) { console.log('s12'); if (event.data && event.data.chromeMediaSourceId) { var sourceId = even...
{ alert('PermissionDeniedError: User denied to share content of his screen.'); }
conditional_block
screenShare.js
'use strict'; var SIGNALING_SERVER = 'https://112.108.40.152:443/'; var config = { openSocket: function(config) { console.log('s1'); /* Firebase ver. */ var channel = config.channel || 'screen-capturing-' + location.href.replace( /\/|:|#|%|\.|\[|\]/g , ''); var so...
var video = media.video; video.setAttribute('controls', true); videosContainer.insertBefore(video, videosContainer.firstChild); video.play(); }, onRoomFound: function(room) { console.log('s5'); dualrtcUI.joinRoom({ roomToken: room.broadcaster, ...
random_line_split
screenShare.js
'use strict'; var SIGNALING_SERVER = 'https://112.108.40.152:443/'; var config = { openSocket: function(config) { console.log('s1'); /* Firebase ver. */ var channel = config.channel || 'screen-capturing-' + location.href.replace( /\/|:|#|%|\.|\[|\]/g , ''); var so...
(callback, extensionAvailable) { console.log('s9'); console.log('captureUserMedia chromeMediaSource', DetectRTC.screen.chromeMediaSource); var screen_constraints = { mandatory: { chromeMediaSource: DetectRTC.screen.chromeMediaSource, maxWidth: screen.width > 1920 ? screen.w...
captureUserMedia
identifier_name
screenShare.js
'use strict'; var SIGNALING_SERVER = 'https://112.108.40.152:443/'; var config = { openSocket: function(config) { console.log('s1'); /* Firebase ver. */ var channel = config.channel || 'screen-capturing-' + location.href.replace( /\/|:|#|%|\.|\[|\]/g , ''); var so...
var dualrtcUI = dualrtc(config); var videosContainer = document.getElementById('videos-container'); var secure = (Math.random() * new Date().getTime()).toString(36).toUpperCase().replace( /\./g , '-'); var makeName = $('#makeName'); var joinName = $('#joinName'); var btnMakeRoom = $('#btnMakeRoom'); var btnJoinRoo...
{ console.log('s9'); console.log('captureUserMedia chromeMediaSource', DetectRTC.screen.chromeMediaSource); var screen_constraints = { mandatory: { chromeMediaSource: DetectRTC.screen.chromeMediaSource, maxWidth: screen.width > 1920 ? screen.width : 1920, maxHei...
identifier_body
worksheet.rs
use nickel::{Request, Response, MiddlewareResult}; use nickel::status::StatusCode; pub fn handler<'mw>(req: &mut Request, mut res: Response<'mw>) -> MiddlewareResult<'mw> { // When you need user in the future, user this stuff // use ::auth::UserCookie; // let user = req.get_user(); // if user.is_none() { ...
let year = year.unwrap(); let activities: Vec<::models::activity::Activity> = Vec::new();// = ::models::activity::get_activities_by_user(user.id); let data = WorksheetModel { year: year, has_activities: activities.len() > 0, activities: activities.iter().map(|a| ActivityModel { ...
{ res.set(StatusCode::BadRequest); return res.send("Invalid year"); }
conditional_block
worksheet.rs
use nickel::{Request, Response, MiddlewareResult}; use nickel::status::StatusCode; pub fn handler<'mw>(req: &mut Request, mut res: Response<'mw>) -> MiddlewareResult<'mw> { // When you need user in the future, user this stuff // use ::auth::UserCookie; // let user = req.get_user(); // if user.is_none() { ...
} #[derive(RustcEncodable)] struct WorksheetModel { year: i32, has_activities: bool, activities: Vec<ActivityModel> } #[derive(RustcEncodable)] struct ActivityModel { points: i32, description: String }
random_line_split
worksheet.rs
use nickel::{Request, Response, MiddlewareResult}; use nickel::status::StatusCode; pub fn handler<'mw>(req: &mut Request, mut res: Response<'mw>) -> MiddlewareResult<'mw> { // When you need user in the future, user this stuff // use ::auth::UserCookie; // let user = req.get_user(); // if user.is_none() { ...
{ points: i32, description: String }
ActivityModel
identifier_name
CreateFolder.js
import React, {Component} from "react/addons"; import {createFolder} from "editor/actions/TreeActions"; class CreateFolder extends Component<{}, {}, {}> { constructor() { super(); this.handleApply = this.handleApply.bind(this); this.handleClose = this.handleClose.bind(this); } handleClose() { th...
(e) { createFolder(this.props.options.get("parentId"), this.refs.nameInput.value); } render() { return ( <div className="modal-dialog width-500"> <div className="modal-content"> <div className="modal-header"> <button className="close" onClick={this.handleClose} aria-label="C...
handleApply
identifier_name
CreateFolder.js
import React, {Component} from "react/addons"; import {createFolder} from "editor/actions/TreeActions"; class CreateFolder extends Component<{}, {}, {}> { constructor() { super(); this.handleApply = this.handleApply.bind(this); this.handleClose = this.handleClose.bind(this); } handleClose()
handleApply(e) { createFolder(this.props.options.get("parentId"), this.refs.nameInput.value); } render() { return ( <div className="modal-dialog width-500"> <div className="modal-content"> <div className="modal-header"> <button className="close" onClick={this.handleClose...
{ this.props.onClose(); }
identifier_body
CreateFolder.js
import React, {Component} from "react/addons"; import {createFolder} from "editor/actions/TreeActions"; class CreateFolder extends Component<{}, {}, {}> { constructor() { super(); this.handleApply = this.handleApply.bind(this); this.handleClose = this.handleClose.bind(this); } handleClose() { th...
} render() { return ( <div className="modal-dialog width-500"> <div className="modal-content"> <div className="modal-header"> <button className="close" onClick={this.handleClose} aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 className="modal-...
} handleApply(e) { createFolder(this.props.options.get("parentId"), this.refs.nameInput.value);
random_line_split
array.rs
extern crate rand; use std::io; use std::f32; use std::f64; use std::ops::Add; use rand::{thread_rng, Rng}; pub trait Seq<T> { fn range(&self, start: usize, end: usize) -> &[T]; fn inverse(&self, &T) -> Option<usize>; } pub struct PrimeSeq { values: Vec<u64>, max: u64, } impl PrimeSeq { pub fn new() -> Prim...
let mut common = Vec::new(); if (all_factors.len() == 0) { return common; } let mut first = 0; let highest = all_factors[all_factors.len() - 1]; for comp in all_factors { if comp > 255 { return common; } let mut lowest_index = 0; let mut lowest = highest; let mut freq = 0; let mut have_remain...
let mut progress = vec![0; factors.len() as usize];
random_line_split
array.rs
extern crate rand; use std::io; use std::f32; use std::f64; use std::ops::Add; use rand::{thread_rng, Rng}; pub trait Seq<T> { fn range(&self, start: usize, end: usize) -> &[T]; fn inverse(&self, &T) -> Option<usize>; } pub struct PrimeSeq { values: Vec<u64>, max: u64, } impl PrimeSeq { pub fn new() -> Prim...
(factors: &Vec<Vec<u64>>, min_freq: u64, limit: u64) -> Vec<u64> { let all_factors = maximum_factors(factors); let mut progress = vec![0; factors.len() as usize]; let mut common = Vec::new(); if (all_factors.len() == 0) { return common; } let mut first = 0; let highest = all_factors[all_factors.len() - 1]; ...
high_freq_factors
identifier_name
array.rs
extern crate rand; use std::io; use std::f32; use std::f64; use std::ops::Add; use rand::{thread_rng, Rng}; pub trait Seq<T> { fn range(&self, start: usize, end: usize) -> &[T]; fn inverse(&self, &T) -> Option<usize>; } pub struct PrimeSeq { values: Vec<u64>, max: u64, } impl PrimeSeq { pub fn new() -> Prim...
} pub fn isqrt(number: u64) -> u64 { return (number as f64).sqrt().ceil() as u64; } pub fn factors(number: u64) -> Vec<u64> { let mut result = vec![]; let mut remain = number; let mut i = 2; while (i <= remain) { if remain % i == 0 { remain /= i; result.push(i); } else { i += 1; } } retur...
{ return match self.values.binary_search(elem) { Ok(index) => Some(index), Err(_) => None, } }
identifier_body
v2_deflate_serializer.rs
use super::v2_serializer::{V2SerializeError, V2Serializer}; use super::{Serializer, V2_COMPRESSED_COOKIE}; use crate::core::counter::Counter; use crate::Histogram; use byteorder::{BigEndian, WriteBytesExt}; use flate2::write::ZlibEncoder; use flate2::Compression; use std::io::{self, Write}; use std::{self, error, fmt};...
() -> V2DeflateSerializer { V2DeflateSerializer { uncompressed_buf: Vec::new(), compressed_buf: Vec::new(), v2_serializer: V2Serializer::new(), } } } impl Serializer for V2DeflateSerializer { type SerializeError = V2DeflateSerializeError; fn serialize<T:...
new
identifier_name
v2_deflate_serializer.rs
use super::v2_serializer::{V2SerializeError, V2Serializer}; use super::{Serializer, V2_COMPRESSED_COOKIE}; use crate::core::counter::Counter; use crate::Histogram; use byteorder::{BigEndian, WriteBytesExt}; use flate2::write::ZlibEncoder; use flate2::Compression; use std::io::{self, Write}; use std::{self, error, fmt};...
} impl fmt::Display for V2DeflateSerializeError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { V2DeflateSerializeError::InternalSerializationError(e) => { write!(f, "The underlying serialization failed: {}", e) } V2DeflateSerialize...
{ V2DeflateSerializeError::IoError(e) }
identifier_body
v2_deflate_serializer.rs
use super::v2_serializer::{V2SerializeError, V2Serializer}; use super::{Serializer, V2_COMPRESSED_COOKIE}; use crate::core::counter::Counter; use crate::Histogram; use byteorder::{BigEndian, WriteBytesExt}; use flate2::write::ZlibEncoder; use flate2::Compression; use std::io::{self, Write}; use std::{self, error, fmt};...
// TODO pluggable compressors? configurable compression levels? // TODO benchmark https://github.com/sile/libflate // TODO if uncompressed_len is near the limit of 16-bit usize, and compression grows the // data instead of shrinking it (which we cannot really predict), writing to compres...
.write_u32::<BigEndian>(V2_COMPRESSED_COOKIE)?; // placeholder for length self.compressed_buf.write_u32::<BigEndian>(0)?;
random_line_split
v2_deflate_serializer.rs
use super::v2_serializer::{V2SerializeError, V2Serializer}; use super::{Serializer, V2_COMPRESSED_COOKIE}; use crate::core::counter::Counter; use crate::Histogram; use byteorder::{BigEndian, WriteBytesExt}; use flate2::write::ZlibEncoder; use flate2::Compression; use std::io::{self, Write}; use std::{self, error, fmt};...
} } } impl error::Error for V2DeflateSerializeError { fn source(&self) -> Option<&(dyn error::Error + 'static)> { match self { V2DeflateSerializeError::InternalSerializationError(e) => Some(e), V2DeflateSerializeError::IoError(e) => Some(e), } } } /// Seria...
{ write!(f, "The underlying serialization failed: {}", e) }
conditional_block
400_nth_digit.py
# 400 Nth Digit # Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... # # Note: # n is positive and will fit within the range of a 32-bit signed integer (n < 231). # # Example 1: # # Input: # 3 # # Output: # 3 # # Example 2: # # Input: # 11 # # Output: # 0 # # Explanation: # The ...
findNthDigit(11))
conditional_block
400_nth_digit.py
# 400 Nth Digit # Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... # # Note: # n is positive and will fit within the range of a 32-bit signed integer (n < 231). # # Example 1: # # Input: # 3 # # Output: # 3 # # Example 2: # # Input: # 11 # # Output: # 0 # # Explanation: # The ...
n > num * cnt: n -= (num * cnt) num *= 10 cnt += 1 t = n // cnt base = 10 ** (cnt - 1) + t if t * cnt == n: return (base - 1) % 10 n -= t * cnt return int(str(base)[::-1][-n]) print(Solution().findNthDigit(11))
identifier_body
400_nth_digit.py
# 400 Nth Digit # Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... # # Note: # n is positive and will fit within the range of a 32-bit signed integer (n < 231). # # Example 1: # # Input: # 3 # # Output: # 3 # # Example 2: # # Input: # 11 # # Output: # 0
# https://www.hrwhisper.me/leetcode-contest-5-solution/ # 主要是求出该数字需要的位数,因为一位数有9*1,两位数有90*2,三位数有900*3以此类推。 # 剩下的直接看看是否整除啥的即可。 def findNthDigit(self, n): """ :type n: int :rtype: int """ num = 9 cnt = 1 while n > num * cnt: n -= (num * cn...
# # Explanation: # The 11th digit of the sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... is a 0, which is part of the number 10. class Solution(object):
random_line_split
400_nth_digit.py
# 400 Nth Digit # Find the nth digit of the infinite integer sequence 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ... # # Note: # n is positive and will fit within the range of a 32-bit signed integer (n < 231). # # Example 1: # # Input: # 3 # # Output: # 3 # # Example 2: # # Input: # 11 # # Output: # 0 # # Explanation: # The ...
(object): # https://www.hrwhisper.me/leetcode-contest-5-solution/ # 主要是求出该数字需要的位数,因为一位数有9*1,两位数有90*2,三位数有900*3以此类推。 # 剩下的直接看看是否整除啥的即可。 def findNthDigit(self, n): """ :type n: int :rtype: int """ num = 9 cnt = 1 while n > num * cnt: n -=...
Solution
identifier_name
index.js
import differenceInCalendarWeeks from '../differenceInCalendarWeeks/index.js' import lastDayOfMonth from '../lastDayOfMonth/index.js' import startOfMonth from '../startOfMonth/index.js' /** * @name getWeeksInMonth * @category Week Helpers * @summary Get the number of calendar weeks a month spans. * * @description...
return ( differenceInCalendarWeeks( lastDayOfMonth(date), startOfMonth(date), options ) + 1 ) }
{ throw new TypeError( '1 argument required, but only ' + arguments.length + ' present' ) }
conditional_block
index.js
import differenceInCalendarWeeks from '../differenceInCalendarWeeks/index.js' import lastDayOfMonth from '../lastDayOfMonth/index.js' import startOfMonth from '../startOfMonth/index.js' /** * @name getWeeksInMonth * @category Week Helpers * @summary Get the number of calendar weeks a month spans. * * @description...
{ if (arguments.length < 1) { throw new TypeError( '1 argument required, but only ' + arguments.length + ' present' ) } return ( differenceInCalendarWeeks( lastDayOfMonth(date), startOfMonth(date), options ) + 1 ) }
identifier_body
index.js
import differenceInCalendarWeeks from '../differenceInCalendarWeeks/index.js' import lastDayOfMonth from '../lastDayOfMonth/index.js' import startOfMonth from '../startOfMonth/index.js' /** * @name getWeeksInMonth * @category Week Helpers * @summary Get the number of calendar weeks a month spans. * * @description...
* @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday) * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale} * @returns {Number} the number of calendar weeks * @throws {TypeError} 2 arguments requir...
* - [Changes that are common for the whole library](https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#Common-Changes). * * @param {Date|Number} date - the given date * @param {Object} [options] - an object with options.
random_line_split
index.js
import differenceInCalendarWeeks from '../differenceInCalendarWeeks/index.js' import lastDayOfMonth from '../lastDayOfMonth/index.js' import startOfMonth from '../startOfMonth/index.js' /** * @name getWeeksInMonth * @category Week Helpers * @summary Get the number of calendar weeks a month spans. * * @description...
(date, options) { if (arguments.length < 1) { throw new TypeError( '1 argument required, but only ' + arguments.length + ' present' ) } return ( differenceInCalendarWeeks( lastDayOfMonth(date), startOfMonth(date), options ) + 1 ) }
getWeeksInMonth
identifier_name
linear-for-loop.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { let x = vec!(1, 2, 3); let mut y = 0; for i in x.iter() { println!("{:?}", *i); y += *i; } println!("{:?}", y); assert_eq!(y, 6); let s = "hello there".to_string(); let mut i: int = 0; for c in s.as_slice().bytes() { if i == 0 { assert!((c == 'h' as u8)); } if i == 1...
main
identifier_name
linear-for-loop.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub fn main() { let x = vec!(1, 2, 3); let mut y = 0; for i in x.iter() { println!("{:?}", *i); y += *i; } println!("{:?}", y); assert_eq!(y, 6); let s = "hello there".to_string(); let mut i: int = 0; for c in s.as_slice().bytes() { if i == 0 { assert!((c == 'h' as u8)); } ...
random_line_split
linear-for-loop.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let x = vec!(1, 2, 3); let mut y = 0; for i in x.iter() { println!("{:?}", *i); y += *i; } println!("{:?}", y); assert_eq!(y, 6); let s = "hello there".to_string(); let mut i: int = 0; for c in s.as_slice().bytes() { if i == 0 { assert!((c == 'h' as u8)); } if i == 1 { ...
identifier_body
linear-for-loop.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
if i == 4 { assert!((c == 'o' as u8)); } // ... i += 1; println!("{:?}", i); println!("{:?}", c); } assert_eq!(i, 11); }
{ assert!((c == 'l' as u8)); }
conditional_block
test.rs
#![allow(unstable)] extern crate "recursive_sync" as rs; use rs::RMutex; use std::thread::Thread; use std::sync::Arc; use std::io::timer::sleep; use std::time::duration::Duration; #[test] fn recursive_test() { let mutex = RMutex::new(0i32); { let mut outer_lock = mutex.lock(); { l...
() { let count = 1000; let mutex = Arc::new(RMutex::new(0i32)); let mut guards = Vec::new(); for _ in (0..count) { let mutex = mutex.clone(); guards.push(Thread::scoped(move || { let mut value_ref = mutex.lock(); let value = *value_ref; sleep(Duratio...
test_guarding
identifier_name
test.rs
#![allow(unstable)] extern crate "recursive_sync" as rs; use rs::RMutex; use std::thread::Thread; use std::sync::Arc; use std::io::timer::sleep; use std::time::duration::Duration; #[test] fn recursive_test() { let mutex = RMutex::new(0i32);
let mut outer_lock = mutex.lock(); { let mut inner_lock = mutex.lock(); *inner_lock = 1; } *outer_lock = 2; } assert_eq!(*mutex.lock(), 2); } #[test] fn test_guarding() { let count = 1000; let mutex = Arc::new(RMutex::new(0i32)); let mut guard...
{
random_line_split
test.rs
#![allow(unstable)] extern crate "recursive_sync" as rs; use rs::RMutex; use std::thread::Thread; use std::sync::Arc; use std::io::timer::sleep; use std::time::duration::Duration; #[test] fn recursive_test()
#[test] fn test_guarding() { let count = 1000; let mutex = Arc::new(RMutex::new(0i32)); let mut guards = Vec::new(); for _ in (0..count) { let mutex = mutex.clone(); guards.push(Thread::scoped(move || { let mut value_ref = mutex.lock(); let value = *value_ref; ...
{ let mutex = RMutex::new(0i32); { let mut outer_lock = mutex.lock(); { let mut inner_lock = mutex.lock(); *inner_lock = 1; } *outer_lock = 2; } assert_eq!(*mutex.lock(), 2); }
identifier_body
table.js
// GFM table, non-standard 'use strict'; function getLine(state, line)
function escapedSplit(str) { var result = [], pos = 0, max = str.length, ch, escapes = 0, lastPos = 0, backTicked = false, lastBackTick = 0; ch = str.charCodeAt(pos); while (pos < max) { if (ch === 0x60/* ` */ && (escapes % 2 === 0)) { backTicked = !backTic...
{ var pos = state.bMarks[line] + state.blkIndent, max = state.eMarks[line]; return state.src.substr(pos, max - pos); }
identifier_body
table.js
// GFM table, non-standard 'use strict'; function getLine(state, line) { var pos = state.bMarks[line] + state.blkIndent, max = state.eMarks[line]; return state.src.substr(pos, max - pos); } function escapedSplit(str) { var result = [], pos = 0, max = str.length, ch, escapes = 0,...
} ch = str.charCodeAt(pos); } result.push(str.substring(lastPos)); return result; } module.exports = function table(state, startLine, endLine, silent) { var ch, lineText, pos, i, nextLine, rows, token, aligns, t, tableLines, tbodyLines; // should have at least three lines if (startLine +...
random_line_split