file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
analytics.service.ts
import { Injectable } from '@angular/core'; import { environment } from '../../../environments/environment'; import { AppInsights } from 'applicationinsights-js'; // Declare ga function as ambient declare const ga: Function; @Injectable() export class AnalyticsService { private config: Microsoft.ApplicationInsig...
} logPageView(name?: string, url?: string, properties?: any, measurements?: any, duration?: number) { AppInsights.trackPageView( name, url, properties, measurements, duration); ...
AppInsights.downloadAndSetup(this.config); }
conditional_block
read_multifield_dataset.py
import sys if __name__ == "__main__": # Parse command line arguments if len(sys.argv) < 2: sys.exit("python {} <datasetFilename> {{<maxPoints>}}".format(sys.argv[0])) datasetFilename = sys.argv[1] if len(sys.argv) >= 3: maxPoints = int(sys.argv[2]) else: maxPoints = None # Perform initial pass through fil...
# Print initial header at END of file (so we have number of points already) if maxPoints: numPoints = min(lineCount, maxPoints) else: numPoints = lineCount print("{} {}".format(numDimensions, numPoints)) # Output dataset header which defines dimensionality of data and number of points # Read entire file line-...
# If dimensionality of dataset is 0, print error message and exit if numDimensions == 0: sys.exit("Could not determine dimensionality of dataset")
random_line_split
read_multifield_dataset.py
import sys if __name__ == "__main__": # Parse command line arguments if len(sys.argv) < 2: sys.exit("python {} <datasetFilename> {{<maxPoints>}}".format(sys.argv[0])) datasetFilename = sys.argv[1] if len(sys.argv) >= 3: maxPoints = int(sys.argv[2]) else: maxPoints = None # Perform initial pass through fil...
else: numPoints = lineCount print("{} {}".format(numDimensions, numPoints)) # Output dataset header which defines dimensionality of data and number of points # Read entire file line-by-line, printing out each line as a point with open(datasetFilename, "r") as f: pointsRead = 0 line = f.readline() while li...
numPoints = min(lineCount, maxPoints)
conditional_block
utils.py
from collections import OrderedDict from purl import URL as PURL def URL(base, path, segments=None, defaults=None): """ URL segment handler capable of getting and setting segments by name. The URL is constructed by joining base, path and segments. For each segment a property capable of getting and se...
""" # Make a copy of the Segments class url_class = type(Segments.__name__, Segments.__bases__, dict(Segments.__dict__)) segments = [] if segments is None else segments defaults = [] if defaults is None else defaults # For each segment attach a property capable of getting ...
created dinamically.
random_line_split
utils.py
from collections import OrderedDict from purl import URL as PURL def URL(base, path, segments=None, defaults=None): """ URL segment handler capable of getting and setting segments by name. The URL is constructed by joining base, path and segments. For each segment a property capable of getting and se...
(self): return self.build().as_string() def _get_segment(self, segment): return self.segments[segment] def _set_segment(self, segment, value): self.segments[segment] = value @classmethod def _segment(cls, segment): """ Returns a property capable of setting and ...
__str__
identifier_name
utils.py
from collections import OrderedDict from purl import URL as PURL def URL(base, path, segments=None, defaults=None): """ URL segment handler capable of getting and setting segments by name. The URL is constructed by joining base, path and segments. For each segment a property capable of getting and se...
# Instantiate the class with the actual parameters return url_class(base, path, segments, defaults) class Segments(object): """ URL segment handler, not intended for direct use. The URL is constructed by joining base, path and segments. """ def __init__(self, base, path, segments, defaul...
setattr(url_class, segment, url_class._segment(segment))
conditional_block
utils.py
from collections import OrderedDict from purl import URL as PURL def URL(base, path, segments=None, defaults=None): """ URL segment handler capable of getting and setting segments by name. The URL is constructed by joining base, path and segments. For each segment a property capable of getting and se...
full_path = full_path.replace(self.base.host(), '') full_path = full_path.replace(self.base.scheme(), '') return full_path[4:] def __str__(self): return self.build().as_string() def _get_segment(self, segment): return self.segments[segment] def _set_segment(self, s...
""" URL segment handler, not intended for direct use. The URL is constructed by joining base, path and segments. """ def __init__(self, base, path, segments, defaults): # Preserve the base URL self.base = PURL(base, path=path) # Map the segments and defaults lists to an ordered d...
identifier_body
benchmark.ndarray_nd_singleton_dims_float64.native.js
/** * @license Apache-2.0 * * Copyright (c) 2021 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 a...
* @private * @param {Benchmark} b - benchmark instance */ function benchmark( b ) { var y; var i; b.tic(); for ( i = 0; i < b.iterations; i++ ) { y = abs( x ); if ( isnan( y.data[ i%len ] ) ) { b.fail( 'should not return NaN' ); } } b.toc(); if ( isnan( y.data[ i%len ] ) ) { b.fail( '...
{ var buf; var sh; var st; var x; var i; buf = new Float64Array( len*2 ); for ( i = 0; i < len*2; i++ ) { buf[ i ] = rand(); } sh = [ len, 1, 1 ]; st = [ 2, 1, 1 ]; x = ndarray( 'float64', buf, sh, st, 0, 'row-major' ); return benchmark; /** * Benchmark function. *
identifier_body
benchmark.ndarray_nd_singleton_dims_float64.native.js
/** * @license Apache-2.0 * * Copyright (c) 2021 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 a...
( len ) { var buf; var sh; var st; var x; var i; buf = new Float64Array( len*2 ); for ( i = 0; i < len*2; i++ ) { buf[ i ] = rand(); } sh = [ len, 1, 1 ]; st = [ 2, 1, 1 ]; x = ndarray( 'float64', buf, sh, st, 0, 'row-major' ); return benchmark; /** * Benchmark function. * * @private * @param {Ben...
createBenchmark
identifier_name
benchmark.ndarray_nd_singleton_dims_float64.native.js
/** * @license Apache-2.0 * * Copyright (c) 2021 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 a...
var isnan = require( '@stdlib/math/base/assert/is-nan' ); var pow = require( '@stdlib/math/base/special/pow' ); var Float64Array = require( '@stdlib/array/float64' ); var ndarray = require( '@stdlib/ndarray/ctor' ); var pkg = require( './../package.json' ).name; // VARIABLES // var abs = tryRequire( resolve( __dirna...
var uniform = require( '@stdlib/random/base/uniform' ).factory;
random_line_split
benchmark.ndarray_nd_singleton_dims_float64.native.js
/** * @license Apache-2.0 * * Copyright (c) 2021 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 a...
} main();
{ len = pow( 10, i ); f = createBenchmark( len ); bench( pkg+'::native,ndarray:contiguous=false,ndims=3,singleton_dims=2,dtype=float64,len='+len, opts, f ); }
conditional_block
cancel-app-deployment.spec.ts
import axios from 'axios'; import MockAdapter from 'axios-mock-adapter'; import { createContext } from '../../common';
import * as MOCK from './cancel-app-deployment.mock'; describe('app', () => { const DEPLOY_ID = 'deploy-id'; const URL = `/apps/${MOCK.request.body.app_id}/deployments/${DEPLOY_ID}/cancel`; const TOKEN = process.env.TEST_TOKEN as string; const mock = new MockAdapter(axios); mock.onPost(URL, undefined).reply(...
import {cancelAppDeployment} from './cancel-app-deployment';
random_line_split
issue-7563.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn do_nothing(&self); } struct A { a: int } struct B<'a> { b: int, pa: &'a A } impl IDummy for A { fn do_nothing(&self) { println!("A::do_nothing() is called"); } } impl<'a> B<'a> { fn get_pa(&self) -> &'a IDummy { self.pa as &'a IDummy } } pub fn main() { let sa = A ...
extern crate debug; trait IDummy {
random_line_split
issue-7563.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 ...
<'a> { b: int, pa: &'a A } impl IDummy for A { fn do_nothing(&self) { println!("A::do_nothing() is called"); } } impl<'a> B<'a> { fn get_pa(&self) -> &'a IDummy { self.pa as &'a IDummy } } pub fn main() { let sa = A { a: 100 }; let sb = B { b: 200, pa: &sa }; prin...
B
identifier_name
$VirtualScrollExample.ts
import { Behavior } from '@aelea/core' import { $text, component, style } from '@aelea/dom' import { $card, $column, $row, $seperator, $TextField, $VirtualScroll, layoutSheet, ScrollRequest, ScrollResponse } from '@aelea/ui-components' import { pallete } from '@aelea/ui-components-theme' import { at, debounce, empty, ...
const $label = (label: string, value: Stream<string> | string) => $row(layoutSheet.spacingSmall)( $text(style({ color: pallete.foreground }))(label), $text(value) ) export const $VirtualScrollExample = component(( [scrollRequest, scrollRequestTether]: Behavior<ScrollRequest, ScrollRequest>, [delayResponse, d...
{ const filterLowercase = filter.toLocaleLowerCase() return array.filter(id => id.indexOf(filterLowercase) > -1 ) }
identifier_body
$VirtualScrollExample.ts
import { Behavior } from '@aelea/core' import { $text, component, style } from '@aelea/dom' import { $card, $column, $row, $seperator, $TextField, $VirtualScroll, layoutSheet, ScrollRequest, ScrollResponse } from '@aelea/ui-components' import { pallete } from '@aelea/ui-components-theme' import { at, debounce, empty, ...
(array: string[], filter: string) { const filterLowercase = filter.toLocaleLowerCase() return array.filter(id => id.indexOf(filterLowercase) > -1 ) } const $label = (label: string, value: Stream<string> | string) => $row(layoutSheet.spacingSmall)( $text(style({ color: pallete.foreground }))(label), $text...
filterArrayByText
identifier_name
$VirtualScrollExample.ts
import { Behavior } from '@aelea/core' import { $text, component, style } from '@aelea/dom' import { $card, $column, $row, $seperator, $TextField, $VirtualScroll, layoutSheet, ScrollRequest, ScrollResponse } from '@aelea/ui-components' import { pallete } from '@aelea/ui-components-theme' import { at, debounce, empty, j...
$card(style({ padding: 0 }))( switchLatest( map(searchText => $VirtualScroll({ dataSource: dataSourceFilter(searchText), containerOps: style({ padding: '8px', maxHeight: '400px' }) })({ scrollIndex: scrollRequestTether(), ...
), $seperator,
random_line_split
cfg-macros-foo.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ assert!(bar!()) }
identifier_body
cfg-macros-foo.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
assert!(bar!()) }
} } pub fn main() {
random_line_split
cfg-macros-foo.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() { assert!(bar!()) }
main
identifier_name
tag_follow_disagreement.py
import sys tagging_filepath = sys.argv[1] following_filepath = sys.argv[2] delim = '\t' if len(sys.argv) > 3: delim = sys.argv[3] graph = {} for line in open(tagging_filepath): entry = line.rstrip().split('\t') src = entry[0] dst = entry[1] if not src in graph: graph[src] = {} graph[src][dst]...
print "%s\t%s" % (w_dir/count, wo_dir/count)
wo_dir += 1
random_line_split
tag_follow_disagreement.py
import sys tagging_filepath = sys.argv[1] following_filepath = sys.argv[2] delim = '\t' if len(sys.argv) > 3: delim = sys.argv[3] graph = {} for line in open(tagging_filepath): entry = line.rstrip().split('\t') src = entry[0] dst = entry[1] if not src in graph:
graph[src][dst] = 0 for line in open(following_filepath): entry = line.rstrip().split('\t') src = entry[0] dst = entry[1] if src in graph and dst in graph[src]: graph[src][dst] += 1 if dst in graph and src in graph[dst]: graph[dst][src] += 2 w_dir = 0 wo_dir = 0 count = 0.0 fo...
graph[src] = {}
conditional_block
kindck-copy.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 ...
trait Dummy { } struct MyStruct { x: isize, y: isize, } impl Copy for MyStruct {} struct MyNoncopyStruct { x: Box<char>, } fn test<'a,T,U:Copy>(_: &'a isize) { // lifetime pointers are ok... assert_copy::<&'static isize>(); assert_copy::<&'a isize>(); assert_copy::<&'a str>(); asse...
{ }
identifier_body
kindck-copy.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 ...
{ x: isize, y: isize, } impl Copy for MyStruct {} struct MyNoncopyStruct { x: Box<char>, } fn test<'a,T,U:Copy>(_: &'a isize) { // lifetime pointers are ok... assert_copy::<&'static isize>(); assert_copy::<&'a isize>(); assert_copy::<&'a str>(); assert_copy::<&'a [isize]>(); // ...
MyStruct
identifier_name
kindck-copy.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 ...
// tuples are ok assert_copy::<(isize,isize)>(); // structs of POD are ok assert_copy::<MyStruct>(); // structs containing non-POD are not ok assert_copy::<MyNoncopyStruct>(); //~ ERROR `core::marker::Copy` is not implemented // ref counted types are not ok assert_copy::<Rc<isize>>();...
assert_copy::<bool>(); assert_copy::<()>();
random_line_split
helper_thread.rs
// Copyright 2013-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-MI...
fn shutdown(&'static self) { unsafe { // Shut down, but make sure this is done inside our lock to ensure // that we'll always receive the exit signal when the thread // returns. let guard = self.lock.lock(); // Close the channel by destroying it...
{ unsafe { let _guard = self.lock.lock(); // Must send and *then* signal to ensure that the child receives the // message. Otherwise it could wake up and go to sleep before we // send the message. assert!(!self.chan.get().is_null()); (**se...
identifier_body
helper_thread.rs
// Copyright 2013-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-MI...
<M> { /// Internal lock which protects the remaining fields pub lock: StaticNativeMutex, // You'll notice that the remaining fields are UnsafeCell<T>, and this is // because all helper thread operations are done through &self, but we need // these to be mutable (once `lock` is held). /// Lazil...
Helper
identifier_name
helper_thread.rs
// Copyright 2013-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-MI...
} } /// Sends a message to a spawned worker thread. /// /// This is only valid if the worker thread has previously booted pub fn send(&'static self, msg: M) { unsafe { let _guard = self.lock.lock(); // Must send and *then* signal to ensure that the child re...
{ let (tx, rx) = channel(); *self.chan.get() = mem::transmute(box tx); let (receive, send) = helper_signal::new(); *self.signal.get() = send as uint; let t = f(); task::spawn(proc() { bookkeeping::decrem...
conditional_block
helper_thread.rs
// Copyright 2013-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-MI...
//! The timer thread is lazily initialized, and it's shut down via the //! `shutdown` function provided. It must be maintained as an invariant that //! `shutdown` is only called when the entire program is finished. No new timers //! can be created in the future and there must be no active timers at that //! time. use ...
//!
random_line_split
base.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from abc import ABCMeta import csv from performance_tools.exceptions import ProgressBarException, ElasticsearchException from performance_tools.utils.progress_bar import create_progress_bar class BaseURLFlowBackend(object): """Collect URL flow fro...
except ZeroDivisionError: raise ElasticsearchException("Search doesn't return any result") except KeyError: raise ElasticsearchException("Invalid result") def __iter__(self): """Iterate over each result. """ raise NotImplementedError
if verbose == 2 and progress is None: try: progress = create_progress_bar(self._total_hits, 'Extract URLs', 'url') except ProgressBarException: verbose = 1 # Write results to csv ...
conditional_block
base.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from abc import ABCMeta import csv from performance_tools.exceptions import ProgressBarException, ElasticsearchException from performance_tools.utils.progress_bar import create_progress_bar class BaseURLFlowBackend(object): """Collect URL flow fro...
:type filename: str :raise: ValueError if not found any result. """ progress = None try: with open(filename, 'w') as csv_file: writer = csv.writer(csv_file) writer.writerow(['Referrer', 'Request', 'Time']) count = 0 ...
def to_csv(self, filename, regex=None, verbose=2): """Save results as a CSV file. :param filename: CSV output file.
random_line_split
base.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from abc import ABCMeta import csv from performance_tools.exceptions import ProgressBarException, ElasticsearchException from performance_tools.utils.progress_bar import create_progress_bar class BaseURLFlowBackend(object):
def to_csv(self, filename, regex=None, verbose=2): """Save results as a CSV file. :param filename: CSV output file. :type filename: str :raise: ValueError if not found any result. """ progress = None try: with open(filename, 'w') as csv_file: ...
"""Collect URL flow from backend. URL Flow: Referrer, Request, Time. It's necessary to implement extract_url_from_result and __iter__ methods. """ __metaclass__ = ABCMeta def __init__(self): self._total_hits = 0 def extract_url_from_result(self, result, regex=None): """Extract orig...
identifier_body
base.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from abc import ABCMeta import csv from performance_tools.exceptions import ProgressBarException, ElasticsearchException from performance_tools.utils.progress_bar import create_progress_bar class BaseURLFlowBackend(object): """Collect URL flow fro...
(self, result, regex=None): """Extract origin url and destination url for each entry in result and construct a list with them. :param result: results obtained from backend in each iteration. :type result: object :param regex: Regular expression to normalize id's in URL. :type re...
extract_url_from_result
identifier_name
plot_morph_surface_stc.py
""" .. _ex-morph-surface: ============================= Morph surface source estimate ============================= This example demonstrates how to morph an individual subject's :class:`mne.SourceEstimate` to a common reference space. We achieve this using :class:`mne.SourceMorph`. Pre-computed data will be morphed ...
https://surfer.nmr.mgh.harvard.edu/fswiki/FsAverage). The transformation will be applied to the surface source estimate. A plot depicting the successful morph will be created for the spherical and inflated surface representation of ``'fsaverage'``, overlaid with the morphed surface source estimate. References -------...
a spherical representation of the cortex computed using the spherical registration of :ref:`FreeSurfer <tut-freesurfer>` (https://surfer.nmr.mgh.harvard.edu/fswiki/SurfaceRegAndTemplates) [1]_. This transform will be used to morph the surface vertices of the subject towards the reference vertices. Here we will use 'fsa...
random_line_split
ipc.rs
//! Alacritty socket IPC. use std::ffi::OsStr; use std::io::{BufRead, BufReader, Error as IoError, ErrorKind, Result as IoResult, Write}; use std::os::unix::net::{UnixListener, UnixStream}; use std::path::PathBuf; use std::{env, fs, process}; use glutin::event_loop::EventLoopProxy; use log::warn; use alacritty_termi...
() -> PathBuf { env::temp_dir() } /// Find the IPC socket path. fn find_socket(socket_path: Option<PathBuf>) -> IoResult<UnixStream> { // Handle --socket CLI override. if let Some(socket_path) = socket_path { // Ensure we inform the user about an invalid path. return UnixStream::connect(&so...
socket_dir
identifier_name
ipc.rs
//! Alacritty socket IPC. use std::ffi::OsStr; use std::io::{BufRead, BufReader, Error as IoError, ErrorKind, Result as IoResult, Write}; use std::os::unix::net::{UnixListener, UnixStream}; use std::path::PathBuf; use std::{env, fs, process}; use glutin::event_loop::EventLoopProxy; use log::warn; use alacritty_termi...
warn!("Unable to create socket: {:?}", err); return None; }, }; // Spawn a thread to listen on the IPC socket. thread::spawn_named("socket listener", move || { let mut data = String::new(); for stream in listener.incoming().filter_map(Result::ok) { ...
env::set_var(ALACRITTY_SOCKET_ENV, socket_path.as_os_str()); let listener = match UnixListener::bind(&socket_path) { Ok(listener) => listener, Err(err) => {
random_line_split
ipc.rs
//! Alacritty socket IPC. use std::ffi::OsStr; use std::io::{BufRead, BufReader, Error as IoError, ErrorKind, Result as IoResult, Write}; use std::os::unix::net::{UnixListener, UnixStream}; use std::path::PathBuf; use std::{env, fs, process}; use glutin::event_loop::EventLoopProxy; use log::warn; use alacritty_termi...
/// File prefix matching all available sockets. #[cfg(target_os = "macos")] fn socket_prefix() -> String { String::from("Alacritty") }
{ let display = env::var("WAYLAND_DISPLAY").or_else(|_| env::var("DISPLAY")).unwrap_or_default(); format!("Alacritty-{}", display) }
identifier_body
mmerge-sort-for-linked-list.py
# key point is to find the half node class Node: def __init__(self, val): self.val = val self.next = None class LinkList: def __init__(self): self.head = None def push(self, val): node = Node(val) if self.head: node.next = self.head self.he...
# 2 3 20 5 10 15 frontHalf = head backHalf = slow.next slow.next = None mergeSort(frontHalf) mergeSort(backHalf) head = sortedMerge(frontHalf, backHalf) return head def sortedMerge(a, b): if not a: return b elif not b: return a temp = None if a.val <= b...
fast = fast.next if fast: slow = slow.next fast = fast.next
conditional_block
mmerge-sort-for-linked-list.py
# key point is to find the half node class Node: def __init__(self, val): self.val = val self.next = None class LinkList: def __init__(self): self.head = None def push(self, val): node = Node(val) if self.head: node.next = self.head self.he...
def sortedMerge(a, b): if not a: return b elif not b: return a temp = None if a.val <= b.val: temp = a a.next = sortedMerge(temp.next, b) return a else: temp = b b.next = sortedMerge(a, temp.next) return b ll = LinkList() ll.push(1...
if not head: return if not head.next: return slow = head fast = head.next while fast: fast = fast.next if fast: slow = slow.next fast = fast.next # 2 3 20 5 10 15 frontHalf = head backHalf = slow.next slow.next = None mergeSort...
identifier_body
mmerge-sort-for-linked-list.py
# key point is to find the half node class Node: def __init__(self, val): self.val = val self.next = None class LinkList: def __init__(self): self.head = None def push(self, val): node = Node(val) if self.head: node.next = self.head self.he...
elif not b: return a temp = None if a.val <= b.val: temp = a a.next = sortedMerge(temp.next, b) return a else: temp = b b.next = sortedMerge(a, temp.next) return b ll = LinkList() ll.push(15) ll.push(10) ll.push(5) ll.push(20) ll.push(3) ll.push(...
random_line_split
mmerge-sort-for-linked-list.py
# key point is to find the half node class Node: def
(self, val): self.val = val self.next = None class LinkList: def __init__(self): self.head = None def push(self, val): node = Node(val) if self.head: node.next = self.head self.head = node else: self.head = node def prin...
__init__
identifier_name
oracle_operator.py
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the #...
(self, context): self.log.info('Executing: %s', self.sql) hook = OracleHook(oracle_conn_id=self.oracle_conn_id) hook.run( self.sql, autocommit=self.autocommit, parameters=self.parameters)
execute
identifier_name
oracle_operator.py
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the #...
def execute(self, context): self.log.info('Executing: %s', self.sql) hook = OracleHook(oracle_conn_id=self.oracle_conn_id) hook.run( self.sql, autocommit=self.autocommit, parameters=self.parameters)
super(OracleOperator, self).__init__(*args, **kwargs) self.oracle_conn_id = oracle_conn_id self.sql = sql self.autocommit = autocommit self.parameters = parameters
identifier_body
oracle_operator.py
# -*- coding: utf-8 -*- # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the #...
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from airflow.hooks.oracle_hook import OracleHook from airflow.models import BaseOperator from airflow.utils.decorators impo...
# # 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
random_line_split
model.rs
use chrono::*; pub use location::GpsCoordinates; use irradiance; pub struct
<Tz: TimeZone> { pub coords: GpsCoordinates, pub date_time: DateTime<Tz>, } pub struct ModelOutput { pub day_of_year: u32, pub eot: f64, pub local_meridian_long: f64, pub time_correction_factor: f64, pub solar_time: f64, pub hour_angle: f64, pub declination_angle: f64, pub eleva...
ModelParams
identifier_name
model.rs
use chrono::*; pub use location::GpsCoordinates; use irradiance; pub struct ModelParams<Tz: TimeZone> { pub coords: GpsCoordinates, pub date_time: DateTime<Tz>, } pub struct ModelOutput { pub day_of_year: u32, pub eot: f64, pub local_meridian_long: f64, pub time_correction_factor: f64, pub...
hour_angle); let zenith_angle = irradiance::zenith_angle(elevation_angle); let air_mass = irradiance::air_mass(zenith_angle); let irradiance = irradiance::irradiance(air_mass); ModelOutput { day_of_year: day_of_year, eot: eot, ...
let ModelParams { coords, date_time } = params; let gmt_offset = date_time.offset().local_minus_utc(); let day_of_year = date_time.ordinal(); let eot = irradiance::equation_of_time(day_of_year); let local_meridian_long = irradiance::local_standard_meridian_longitude(gmt_...
identifier_body
model.rs
use chrono::*; pub use location::GpsCoordinates; use irradiance; pub struct ModelParams<Tz: TimeZone> { pub coords: GpsCoordinates, pub date_time: DateTime<Tz>, } pub struct ModelOutput { pub day_of_year: u32, pub eot: f64, pub local_meridian_long: f64, pub time_correction_factor: f64, pub...
zenith_angle: zenith_angle, air_mass: air_mass, irradiance: irradiance, } }
solar_time: solar_time, hour_angle: hour_angle, declination_angle: declination_angle, elevation_angle: elevation_angle,
random_line_split
markers.py
from numpy.random import random from bokeh.plotting import figure, show, output_file def mscatter(p, x, y, marker): p.scatter(x, y, marker=marker, size=15, line_color="navy", fill_color="orange", alpha=0.5) def
(p, x, y, text): p.text(x, y, text=[text], text_color="firebrick", text_align="center", text_font_size="10pt") p = figure(title="Bokeh Markers", toolbar_location=None) p.grid.grid_line_color = None p.background_fill_color = "#eeeeee" N = 10 mscatter(p, random(N)+2, random(N)+1, "circle") mscatter(p, r...
mtext
identifier_name
markers.py
from numpy.random import random from bokeh.plotting import figure, show, output_file def mscatter(p, x, y, marker): p.scatter(x, y, marker=marker, size=15, line_color="navy", fill_color="orange", alpha=0.5) def mtext(p, x, y, text): p.text(x, y, text=[text], text_color="firebrick", t...
output_file("markers.html", title="markers.py example") show(p) # open a browser
random_line_split
markers.py
from numpy.random import random from bokeh.plotting import figure, show, output_file def mscatter(p, x, y, marker):
def mtext(p, x, y, text): p.text(x, y, text=[text], text_color="firebrick", text_align="center", text_font_size="10pt") p = figure(title="Bokeh Markers", toolbar_location=None) p.grid.grid_line_color = None p.background_fill_color = "#eeeeee" N = 10 mscatter(p, random(N)+2, random(N)+1, "circle") ms...
p.scatter(x, y, marker=marker, size=15, line_color="navy", fill_color="orange", alpha=0.5)
identifier_body
base.py
# -*- encoding: utf-8 -*- # Copyright (c) 2015 b<>com # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
else: continue mac = iface.find('mac') if mac is not None: mac_address = mac.get('address') else: continue fref = iface.find('filterref') if fref is not None: fref = fref.get('filter'...
name = target.get('dev')
conditional_block
base.py
# -*- encoding: utf-8 -*- # Copyright (c) 2015 b<>com # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
(self, instance): domain = self._lookup_by_uuid(instance) dom_info = domain.info() return virt_inspector.CPUStats(number=dom_info[3], time=dom_info[4]) def _get_domain_not_shut_off_or_raise(self, instance): instance_name = util.instance_name(instance) domain = self._lookup_b...
inspect_cpus
identifier_name
base.py
# -*- encoding: utf-8 -*- # Copyright (c) 2015 b<>com # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
def _get_connection(self): if not self.connection: global libvirt if libvirt is None: libvirt = __import__('libvirt') LOG.debug(('Connecting to libvirt: %s'), self.uri) self.connection = libvirt.openReadOnly(self.uri) return self.conn...
random_line_split
base.py
# -*- encoding: utf-8 -*- # Copyright (c) 2015 b<>com # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
# by the underlying hypervisor being used by libvirt. except libvirt.libvirtError as e: msg = ('Failed to inspect memory usage of %(instance_uuid)s, ' 'can not get info from libvirt: %(error)s') % { 'instance_uuid': instance.id, 'error': e} rais...
instance_name = util.instance_name(instance) domain = self._get_domain_not_shut_off_or_raise(instance) try: memory_stats = domain.memoryStats() if (memory_stats and memory_stats.get('available') and memory_stats.get('unused')): ...
identifier_body
stock_reconciliation.js
// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors // License: GNU General Public License v3. See license.txt frappe.provide("erpnext.stock"); frappe.ui.form.on("Stock Reconciliation", { onload: function(frm) { frm.add_fetch("item_code", "item_name", "item_name"); // end of life frm.set_que...
if (erpnext.is_perpetual_inventory_enabled(this.frm.doc.company)) { this.show_general_ledger(); } } }, }); cur_frm.cscript = new erpnext.stock.StockReconciliation({frm: cur_frm});
random_line_split
link_style.rs
/// Determines the hyperlink style used in commit and issue links. Defaults to `LinksStyle::Github` /// /// # Example /// /// ```no_run /// # use clog::{LinkStyle, Clog}; /// let mut clog = Clog::new().unwrap(); /// clog.link_style(LinkStyle::Stash); /// ``` clog_enum!{ #[derive(Debug)] pub enum LinkStyle { ...
} } /// Gets a hyperlink url to a commit in the specified format. /// /// # Example /// ```no_run /// # use clog::{LinkStyle, Clog}; /// let link = LinkStyle::Github; /// let commit = link.commit_link("123abc891234567890abcdefabc4567898724", "https://github.com/thoughtram/clog")...
LinkStyle::Stash => format!("{}", issue.as_ref()), } }
random_line_split
link_style.rs
/// Determines the hyperlink style used in commit and issue links. Defaults to `LinksStyle::Github` /// /// # Example /// /// ```no_run /// # use clog::{LinkStyle, Clog}; /// let mut clog = Clog::new().unwrap(); /// clog.link_style(LinkStyle::Stash); /// ``` clog_enum!{ #[derive(Debug)] pub enum LinkStyle { ...
} } /// Gets a hyperlink url to a commit in the specified format. /// /// # Example /// ```no_run /// # use clog::{LinkStyle, Clog}; /// let link = LinkStyle::Github; /// let commit = link.commit_link("123abc891234567890abcdefabc4567898724", "https://github.com/thoughtram/clog"...
{ match *self { LinkStyle::Github => format!("{}/issues/{}", link, issue.as_ref()), LinkStyle::Gitlab => format!("{}/issues/{}", link, issue.as_ref()), LinkStyle::Stash => format!("{}", issue.as_ref()), } }
conditional_block
link_style.rs
/// Determines the hyperlink style used in commit and issue links. Defaults to `LinksStyle::Github` /// /// # Example /// /// ```no_run /// # use clog::{LinkStyle, Clog}; /// let mut clog = Clog::new().unwrap(); /// clog.link_style(LinkStyle::Stash); /// ``` clog_enum!{ #[derive(Debug)] pub enum LinkStyle { ...
/// Gets a hyperlink url to a commit in the specified format. /// /// # Example /// ```no_run /// # use clog::{LinkStyle, Clog}; /// let link = LinkStyle::Github; /// let commit = link.commit_link("123abc891234567890abcdefabc4567898724", "https://github.com/thoughtram/clog"); /// /...
{ match repo.as_ref() { "" => format!("{}", issue.as_ref()), link => { match *self { LinkStyle::Github => format!("{}/issues/{}", link, issue.as_ref()), LinkStyle::Gitlab => format!("{}/issues/{}", link, issue.as_ref()), ...
identifier_body
link_style.rs
/// Determines the hyperlink style used in commit and issue links. Defaults to `LinksStyle::Github` /// /// # Example /// /// ```no_run /// # use clog::{LinkStyle, Clog}; /// let mut clog = Clog::new().unwrap(); /// clog.link_style(LinkStyle::Stash); /// ``` clog_enum!{ #[derive(Debug)] pub enum LinkStyle { ...
<S: AsRef<str>>(&self, hash: S, repo: S) -> String { match repo.as_ref() { "" => format!("{}", &hash.as_ref()[0..8]), link => { match *self { LinkStyle::Github => format!("{}/commit/{}", link, hash.as_ref()), LinkStyle::Gitlab => fo...
commit_link
identifier_name
marm2.py
from rsf.proj import * from math import * import fdmod,pcsutil,wefd def data(par): # ------------------------------------------------------------ Fetch('vp_marmousi-ii.segy',"marm2") Fetch('vs_marmousi-ii.segy',"marm2") Fetch('density_marmousi-ii.segy',"marm2") # ---------------------------------...
(mod,s1,s2,e1,e2,vi,vt,n1,o1,d1,n2,o2,d2): min1=o1 max1=o1+(n1-1)*d1 min2=o2 max2=o2+(n2-1)*d2 ra = (e1-s1)/(e2-s2) vels = "%s,%s,%s" %(vi,vt,vt) drvs = "%s,%s" %(tan(ra),tan(ra)) dim1 = 'd1=%g o1=%g n1=%d' % (d2,o2,n2) dim2 = 'd2=%g o2=%g n2=%d' % (d1,o1,n1) Flow(mod+'lay2',...
dipline1
identifier_name
marm2.py
from rsf.proj import * from math import * import fdmod,pcsutil,wefd def data(par): # ------------------------------------------------------------ Fetch('vp_marmousi-ii.segy',"marm2") Fetch('vs_marmousi-ii.segy',"marm2") Fetch('density_marmousi-ii.segy',"marm2") # ---------------------------------...
min1=o1 max1=o1+(n1-1)*d1 min2=o2 max2=o2+(n2-1)*d2 ra = (e1-s1)/(e2-s2) vels = "%s,%s,%s" %(vi,vt,vt) drvs = "%s,%s" %(tan(ra),tan(ra)) dim1 = 'd1=%g o1=%g n1=%d' % (d2,o2,n2) dim2 = 'd2=%g o2=%g n2=%d' % (d1,o1,n1) Flow(mod+'lay2',None, ''' spike nsp=4 mag...
random_line_split
marm2.py
from rsf.proj import * from math import * import fdmod,pcsutil,wefd def data(par): # ------------------------------------------------------------ Fetch('vp_marmousi-ii.segy',"marm2") Fetch('vs_marmousi-ii.segy',"marm2") Fetch('density_marmousi-ii.segy',"marm2") # ---------------------------------...
# ------------------------------------------------------------ Flow( 'wmask','vpraw','mask max=1.5 | dd type=float') # Result('wmask',fdmod.cgrey('allpos=y',par)) Flow('rx','vpraw','math output="1.0e6+1.5e6*(input-1.5)/3" ') Flow('ro','roraw','math output=1') Flow('vp...
Flow(file+'raw','_'+file,'window n1=%(nz)d n2=%(nx)d min1=%(oz)g min2=%(ox)g' % par)
conditional_block
marm2.py
from rsf.proj import * from math import * import fdmod,pcsutil,wefd def data(par): # ------------------------------------------------------------ Fetch('vp_marmousi-ii.segy',"marm2") Fetch('vs_marmousi-ii.segy',"marm2") Fetch('density_marmousi-ii.segy',"marm2") # ---------------------------------...
def dipline1(mod,s1,s2,e1,e2,vi,vt,n1,o1,d1,n2,o2,d2): min1=o1 max1=o1+(n1-1)*d1 min2=o2 max2=o2+(n2-1)*d2 ra = (e1-s1)/(e2-s2) vels = "%s,%s,%s" %(vi,vt,vt) drvs = "%s,%s" %(tan(ra),tan(ra)) dim1 = 'd1=%g o1=%g n1=%d' % (d2,o2,n2) dim2 = 'd2=%g o2=%g n2=%d' % (d1,o1,n1) ...
Flow( dip+'-one',dip,'window n2=1 min2=%g'%x) #vpvs ratio at cig location x Flow('vratioPP',vpvs,'window n3=1 f3=0 n2=1 min2=%g'%x) Flow('vratioPS',vpvs,'window n3=1 f3=1 n2=1 min2=%g'%x) Flow('vratioSP',vpvs,'window n3=1 f3=2 n2=1 min2=%g'%x) Flow('vratioSS',vpvs,'window n3=1 f3=3 n2=1 min2=%g'%x...
identifier_body
cfg.rs
macro_rules! cfg_feature { ( #![$meta:meta] $($item:item)* ) => { $( #[cfg($meta)] #[cfg_attr(docsrs, doc(cfg($meta)))] $item )* } } macro_rules! cfg_proto { ($($item:item)*) => { cfg_feature! { #![all( ...
} } }
random_line_split
lib.rs
/*! Tetris game engine. */ extern crate rand; mod bot; pub use self::bot::{Weights, PlayI, Play}; mod bag; pub use self::bag::{Bag, OfficialBag, BestBag, WorstBag}; mod input; pub use self::input::{Clock, Input}; mod pt; pub use self::pt::Point; mod piece; pub use self::piece::{Piece, Sprite}; mod rot; pub use s...
pub use self::srs::{SrsData, srs_cw, srs_ccw, srs_data_cw, srs_data_ccw}; mod player; pub use self::player::Player; mod well; pub use self::well::{Well, Line, ParseWellError, MAX_WIDTH, MAX_HEIGHT}; mod tile; pub use self::tile::{Tile, TileTy, TILE_BG0, TILE_BG1, TILE_BG2}; mod scene; pub use self::scene::{Scene}; ...
random_line_split
Invitations.page.tsx
import React from "react" import { Button, TextArea, Form, Input, Field } from "@fider/components" import { actions, notify, Failure, Fider } from "@fider/services" import { AdminBasePage } from "../components/AdminBasePage" interface InvitationsPageState { subject: string message: string recipients: string[] ...
(props: any) { super(props) this.state = { subject: `[${Fider.session.tenant.name}] We would like to hear from you!`, message: `Hi, We are inviting you to join the ${Fider.session.tenant.name} feedback site, a place where you can vote, discuss and share your ideas and thoughts on how to improve ou...
constructor
identifier_name
Invitations.page.tsx
import React from "react" import { Button, TextArea, Form, Input, Field } from "@fider/components" import { actions, notify, Failure, Fider } from "@fider/services" import { AdminBasePage } from "../components/AdminBasePage" interface InvitationsPageState { subject: string message: string recipients: string[] ...
private setRecipients = (rawRecipients: string) => { const recipients = rawRecipients.split(/\n|;|,|\s/gm).filter((x) => !!x) this.setState({ rawRecipients, recipients, numOfRecipients: recipients.length }) } private sendSample = async () => { const result = await actions.sendSampleInvite(this.stat...
{ super(props) this.state = { subject: `[${Fider.session.tenant.name}] We would like to hear from you!`, message: `Hi, We are inviting you to join the ${Fider.session.tenant.name} feedback site, a place where you can vote, discuss and share your ideas and thoughts on how to improve our services! ...
identifier_body
Invitations.page.tsx
import React from "react" import { Button, TextArea, Form, Input, Field } from "@fider/components" import { actions, notify, Failure, Fider } from "@fider/services" import { AdminBasePage } from "../components/AdminBasePage" interface InvitationsPageState { subject: string message: string recipients: string[] ...
public content() { return ( <Form error={this.state.error}> <TextArea field="recipients" label="Send invitations to" placeholder="james@example.com; mary@example.com" minRows={1} value={this.state.rawRecipients} onChange={this.setRecipient...
this.setState({ message }) }
random_line_split
Invitations.page.tsx
import React from "react" import { Button, TextArea, Form, Input, Field } from "@fider/components" import { actions, notify, Failure, Fider } from "@fider/services" import { AdminBasePage } from "../components/AdminBasePage" interface InvitationsPageState { subject: string message: string recipients: string[] ...
else { this.setState({ error: result.error }) } } private setSubject = (subject: string): void => { this.setState({ subject }) } private setMessage = (message: string): void => { this.setState({ message }) } public content() { return ( <Form error={this.state.error}> ...
{ notify.success("Your invites have been sent.") this.setState({ rawRecipients: "", numOfRecipients: 0, recipients: [], error: undefined }) }
conditional_block
urls.py
from django.conf.urls import patterns, include, url from django.views.generic import TemplateView # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() import api, foxycart urlpatterns = patterns('', url(r'^$', TemplateView.as_view(template_name='index.html')),...
url(r'^api/', include('api.urls')), url(r"^foxycart/", include('foxycart.urls')), url(r"^foxycart/checkout", TemplateView.as_view(template_name='foxycart_checkout_template.html')), url(r'^accounts/login/$', 'django.contrib.auth.views.login', {"template_name": "login.html"}), url(r'^accounts/logout...
#url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
random_line_split
vga.rs
use core::mem; use core::ptr::Unique; use volatile::Volatile; use libd7::{syscall, PhysAddr, VirtAddr}; const SCREEN_HEIGHT: usize = 25; const SCREEN_WIDTH: usize = 80; const HARDWARE_BUFFER_ADDR: u64 = 0xb8000; const HARDWARE_BUFFER_SIZE: u64 = mem::size_of::<Buffer>() as u64; /// Should be free to use. Check plan....
.unwrap(); Unique::new_unchecked((VIRTUAL_ADDR + HARDWARE_BUFFER_ADDR).as_mut_ptr()) }
random_line_split
vga.rs
use core::mem; use core::ptr::Unique; use volatile::Volatile; use libd7::{syscall, PhysAddr, VirtAddr}; const SCREEN_HEIGHT: usize = 25; const SCREEN_WIDTH: usize = 80; const HARDWARE_BUFFER_ADDR: u64 = 0xb8000; const HARDWARE_BUFFER_SIZE: u64 = mem::size_of::<Buffer>() as u64; /// Should be free to use. Check plan....
(self) -> Color { unsafe { mem::transmute::<u8, Color>(self.0 & 0xf) } } pub fn background(self) -> Color { unsafe { mem::transmute::<u8, Color>((self.0 & 0xf0) >> 4) } } pub fn invert(self) -> CellColor { CellColor::new(self.background(), self.foreground()) } } /// Charac...
foreground
identifier_name
vga.rs
use core::mem; use core::ptr::Unique; use volatile::Volatile; use libd7::{syscall, PhysAddr, VirtAddr}; const SCREEN_HEIGHT: usize = 25; const SCREEN_WIDTH: usize = 80; const HARDWARE_BUFFER_ADDR: u64 = 0xb8000; const HARDWARE_BUFFER_SIZE: u64 = mem::size_of::<Buffer>() as u64; /// Should be free to use. Check plan....
{ syscall::mmap_physical( // Assumes 2MiB pages, so that 0xb8000 falls on the first page PhysAddr::new(0), VIRTUAL_ADDR, HARDWARE_BUFFER_SIZE, syscall::MemoryProtectionFlags::READ | syscall::MemoryProtectionFlags::WRITE, ) .unwrap(); Unique::new_unchecked((VIRTUAL...
identifier_body
user_profile.ts
import {badgesList} from '../views/badgesList'; import init_rpc from '../utils/rpc'; import {get_user_profile_login} from '../utils/github'; import {render} from '../utils/h'; import {BiEvents} from '../../common/bi.schema'; export default function route_user_profile(browser: typeof window.browser): void { const r...
function find_anchor_for_user_profile_info() { const profileRoot = document.querySelector('[itemtype="http://schema.org/Person"]'); const h1 = profileRoot && profileRoot.querySelector('h1.vcard-names'); const candidate3 = h1 && h1.parentElement; const candidate2 = candidate3 && candidate3.nextElement...
{ return document.getElementsByClassName('githubuserrank-extension-section').length > 0; }
identifier_body
user_profile.ts
import {badgesList} from '../views/badgesList';
import {get_user_profile_login} from '../utils/github'; import {render} from '../utils/h'; import {BiEvents} from '../../common/bi.schema'; export default function route_user_profile(browser: typeof window.browser): void { const rpc = init_rpc(browser); const login = get_user_profile_login(); if (!login) ...
import init_rpc from '../utils/rpc';
random_line_split
user_profile.ts
import {badgesList} from '../views/badgesList'; import init_rpc from '../utils/rpc'; import {get_user_profile_login} from '../utils/github'; import {render} from '../utils/h'; import {BiEvents} from '../../common/bi.schema'; export default function route_user_profile(browser: typeof window.browser): void { const r...
() { return document.getElementsByClassName('githubuserrank-extension-section').length > 0; } function find_anchor_for_user_profile_info() { const profileRoot = document.querySelector('[itemtype="http://schema.org/Person"]'); const h1 = profileRoot && profileRoot.querySelector('h1.vcard-names'); const...
is_there_a_previously_inserted_section
identifier_name
user_profile.ts
import {badgesList} from '../views/badgesList'; import init_rpc from '../utils/rpc'; import {get_user_profile_login} from '../utils/github'; import {render} from '../utils/h'; import {BiEvents} from '../../common/bi.schema'; export default function route_user_profile(browser: typeof window.browser): void { const r...
if (is_there_a_previously_inserted_section()) { return; } rpc.fetch_languages_for(login).then(languages => { const badges = render(badgesList(login, languages)); const parent = anchor.parentElement; parent && parent.insertBefore(badges, anchor); }); } function is_ther...
{ rpc.report_bi(BiEvents.PLACEHOLDER_NOT_FOUND); return; }
conditional_block
ConfigurationDialog.tsx
intlShape, FormattedHTMLMessage } from 'react-intl'; import vjf from 'mobx-react-form/lib/validators/VJF'; import SVGInline from 'react-svg-inline'; import { PopOver } from 'react-polymorph/lib/components/PopOver'; import { PasswordInput } from '../../widgets/forms/PasswordInput'; import WalletRestoreDialog from './wi...
} form = new ReactToolboxMobxForm<FormFields>( { fields: { walletName: { label: this.context.intl.formatMessage(messages.walletNameLabel), placeholder: this.context.intl.formatMessage( messages.walletNamePlaceholder ), value: this.props.walletNam...
handleFormErrors('.ConfigurationDialog_error'); }
conditional_block
ConfigurationDialog.tsx
, intlShape, FormattedHTMLMessage } from 'react-intl'; import vjf from 'mobx-react-form/lib/validators/VJF'; import SVGInline from 'react-svg-inline'; import { PopOver } from 'react-polymorph/lib/components/PopOver'; import { PasswordInput } from '../../widgets/forms/PasswordInput'; import WalletRestoreDialog from './w...
import infoIconInline from '../../../assets/images/info-icon.inline.svg'; import LoadingSpinner from '../../widgets/LoadingSpinner'; const messages = defineMessages({ description1: { id: 'wallet.restore.dialog.step.configuration.description1', defaultMessage: '!!!Name your restored wallet and set a spe...
import LocalizableError from '../../../i18n/LocalizableError'; import { FORM_VALIDATION_DEBOUNCE_WAIT } from '../../../config/timingConfig'; // @ts-ignore ts-migrate(2307) FIXME: Cannot find module '../../../assets/images/info-ic... Remove this comment to see the full error message
random_line_split
ConfigurationDialog.tsx
intlShape, FormattedHTMLMessage } from 'react-intl'; import vjf from 'mobx-react-form/lib/validators/VJF'; import SVGInline from 'react-svg-inline'; import { PopOver } from 'react-polymorph/lib/components/PopOver'; import { PasswordInput } from '../../widgets/forms/PasswordInput'; import WalletRestoreDialog from './wi...
form = new ReactToolboxMobxForm<FormFields>( { fields: { walletName: { label: this.context.intl.formatMessage(messages.walletNameLabel), placeholder: this.context.intl.formatMessage( messages.walletNamePlaceholder ), value: this.props.walletName, ...
if (this.props.error) { handleFormErrors('.ConfigurationDialog_error'); } }
identifier_body
ConfigurationDialog.tsx
intlShape, FormattedHTMLMessage } from 'react-intl'; import vjf from 'mobx-react-form/lib/validators/VJF'; import SVGInline from 'react-svg-inline'; import { PopOver } from 'react-polymorph/lib/components/PopOver'; import { PasswordInput } from '../../widgets/forms/PasswordInput'; import WalletRestoreDialog from './wi...
{ const { intl } = this.context; const { onClose, onBack, error, isSubmitting, currentLocale } = this.props; const { form } = this; const walletNameField = form.$('walletName'); const spendingPasswordField = form.$('spendingPassword'); const repeatPasswordField = form.$('repeatPassword'); c...
nder()
identifier_name
strings.js
define( ({ showArcgisBasemaps: "Inclure les fonds de carte du portail", settings: "Paramètres", add: "Cliquez pour ajouter un nouveau fond de carte", edit: "Propriétés", title: "Titre", titlePH: "Titre du fond de carte", thumbnail: "Miniature", thumbnailHint: "Cliquez sur l’image pou...
back: "Retour et annuler", addUrl: "Ajouter une URL", autoCheck: "Vérification automatique", checking: "Vérification...", ok: "OK", cancel: "Annuler", result: "Enregistrement réussi", spError: "Tous les fonds de carte ajoutés à la bibliothèque requièrent les mêmes références spatiales.",...
urlPH: "URL de la couche", addlayer: "Ajouter un fond de carte", actions: "Actions", warning: "Entrée incorrecte", save: "Retour et enregistrer",
random_line_split
iconWight.node.tsx
import { NG } from '@web-companions/gfc'; import { svg } from 'lit-html2'; import { renderNode } from 'utils/nodeRender'; export const iconWightNode = NG(function* (props: { strokeWidth?: string } = { strokeWidth: '1' }) { while (true)
); } });
{ props = yield renderNode( svg/*html*/ ` <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-ripple" width="24" height="24" viewBox="0 0 24 24" stroke-width=${props.strokeWidth} stroke="currentColor" fill="n...
conditional_block
iconWight.node.tsx
while (true) { props = yield renderNode( svg/*html*/ ` <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-ripple" width="24" height="24" viewBox="0 0 24 24" stroke-width=${props.strokeWidth} stroke="currentColor" ...
import { NG } from '@web-companions/gfc'; import { svg } from 'lit-html2'; import { renderNode } from 'utils/nodeRender'; export const iconWightNode = NG(function* (props: { strokeWidth?: string } = { strokeWidth: '1' }) {
random_line_split
mesonlib.py
ret += ' (not built)' ret += '>' return ret.format(os.path.join(self.subdir, self.fname)) @staticmethod def from_source_file(source_root, subdir, fname): if not os.path.isfile(os.path.join(source_root, subdir, fname)): raise MesonException('File %s does not exist...
(): platname = platform.system().lower() return platname == 'windows' or 'mingw' in platname def is_debianlike(): return os.path.isfile('/etc/debian_version') def exe_exists(arglist): try: p = subprocess.Popen(arglist, stdout=subprocess.PIPE, stderr=subprocess.PIPE) p.communicate() ...
is_windows
identifier_name
mesonlib.py
ret += ' (not built)' ret += '>' return ret.format(os.path.join(self.subdir, self.fname)) @staticmethod def from_source_file(source_root, subdir, fname): if not os.path.isfile(os.path.join(source_root, subdir, fname)): raise MesonException('File %s does not exist...
def exe_exists(arglist): try: p = subprocess.Popen(arglist, stdout=subprocess.PIPE, stderr=subprocess.PIPE) p.communicate() if p.returncode == 0: return True except FileNotFoundError: pass return False def detect_vcs(source_dir): vcs_systems = [ dic...
return os.path.isfile('/etc/debian_version')
identifier_body
mesonlib.py
: ret += ' (not built)' ret += '>' return ret.format(os.path.join(self.subdir, self.fname)) @staticmethod def from_source_file(source_root, subdir, fname): if not os.path.isfile(os.path.join(source_root, subdir, fname)): raise MesonException('File %s does not exi...
dict(name = 'subversion', cmd = 'svn', repo_dir = '.svn', get_rev = 'svn info', rev_regex = 'Revision: (.*)', dep = '.svn/wc.db'), dict(name = 'bazaar', cmd = 'bzr', repo_dir = '.bzr', get_rev = 'bzr revno', rev_regex = '(.*)', dep = '.bzr'), ] segs = source_dir.r...
dict(name = 'mercurial', cmd = 'hg', repo_dir = '.hg', get_rev = 'hg id -i', rev_regex = '(.*)', dep = '.hg/dirstate'),
random_line_split
mesonlib.py
ret += ' (not built)' ret += '>' return ret.format(os.path.join(self.subdir, self.fname)) @staticmethod def from_source_file(source_root, subdir, fname): if not os.path.isfile(os.path.join(source_root, subdir, fname)): raise MesonException('File %s does not exist...
def endswith(self, ending): return self.fname.endswith(ending) def split(self, s): return self.fname.split(s) def __eq__(self, other): return (self.fname, self.subdir, self.is_built) == (other.fname, other.subdir, other.is_built) def __hash__(self): return hash((self...
return os.path.join(build_to_src, self.subdir, self.fname)
conditional_block
mizrahi.ts
import moment from 'moment'; import { Frame, Page, Request } from 'puppeteer'; import { SHEKEL_CURRENCY } from '../constants'; import { pageEvalAll, waitUntilElementDisappear, waitUntilElementFound, waitUntilIframeFound, } from '../helpers/elements-interactions'; import { fetchPostWithinPage } from '../helpers/fetch'...
class MizrahiScraper extends BaseScraperWithBrowser { getLoginOptions(credentials: ScraperCredentials) { return { loginUrl: LOGIN_URL, fields: createLoginFields(credentials), submitButtonSelector, checkReadiness: async () => waitUntilElementDisappear(this.page, loginSpinnerSelector), ...
}
random_line_split
mizrahi.ts
import moment from 'moment'; import { Frame, Page, Request } from 'puppeteer'; import { SHEKEL_CURRENCY } from '../constants'; import { pageEvalAll, waitUntilElementDisappear, waitUntilElementFound, waitUntilIframeFound, } from '../helpers/elements-interactions'; import { fetchPostWithinPage } from '../helpers/fetch'...
return { success: true, accounts: results, }; } catch (e) { return { success: false, errorType: ScraperErrorTypes.Generic, errorMessage: (e as Error).message, }; } } private async fetchAccount() { await this.navigateTo(OSH_PAGE, this.pag...
{ await this.page.$$eval(accountDropDownItemSelector, (els, i) => (els[i] as HTMLElement).click(), i); results.push(await this.fetchAccount()); }
conditional_block
mizrahi.ts
import moment from 'moment'; import { Frame, Page, Request } from 'puppeteer'; import { SHEKEL_CURRENCY } from '../constants'; import { pageEvalAll, waitUntilElementDisappear, waitUntilElementFound, waitUntilIframeFound, } from '../helpers/elements-interactions'; import { fetchPostWithinPage } from '../helpers/fetch'...
function getPossibleLoginResults(page: Page): PossibleLoginResults { return { [LoginResults.Success]: [AFTER_LOGIN_BASE_URL], [LoginResults.InvalidPassword]: [async () => !!(await page.$(invalidPasswordSelector))], [LoginResults.ChangePassword]: [CHANGE_PASSWORD_URL], }; } function getStartMoment(opt...
{ return [ { selector: usernameSelector, value: credentials.username }, { selector: passwordSelector, value: credentials.password }, ]; }
identifier_body
mizrahi.ts
import moment from 'moment'; import { Frame, Page, Request } from 'puppeteer'; import { SHEKEL_CURRENCY } from '../constants'; import { pageEvalAll, waitUntilElementDisappear, waitUntilElementFound, waitUntilIframeFound, } from '../helpers/elements-interactions'; import { fetchPostWithinPage } from '../helpers/fetch'...
() { const numOfAccounts = (await this.page.$$(accountDropDownItemSelector)).length; try { const results: TransactionsAccount[] = []; for (let i = 0; i < numOfAccounts; i += 1) { await this.page.$$eval(accountDropDownItemSelector, (els, i) => (els[i] as HTMLElement).click(), i); resu...
fetchData
identifier_name
ExpandableGalleryTest.js
/** * Copyright (C) 2005-2016 Alfresco Software Limited. *
* 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 version. * * Alfresco is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of ...
* This file is part of Alfresco * * Alfresco is free software: you can redistribute it and/or modify
random_line_split
install.js
/** * @module opcua.address_space * @class AddressSpace */ import assert from "better-assert"; import _ from "underscore"; import NodeClass from "lib/datamodel/NodeClass"; import Argument from "lib/datamodel/argument-list/Argument"; import DataValue from "lib/datamodel/DataValue"; import { Variant } from "lib/datamo...
function install(AddressSpace) { assert(_.isUndefined(AddressSpace._install_TwoStateVariable_machinery)); AddressSpace._install_TwoStateVariable_machinery = _install_TwoStateVariable_machinery; /** * * @method addTwoStateVariable * * @param options * @param options.browseName {...
{ assert(node.dataTypeObj.browseName.toString() === "LocalizedText"); assert(node.minimumSamplingInterval === 0); assert(node.typeDefinitionObj.browseName.toString() === "TwoStateVariableType"); assert(node.dataTypeObj.browseName.toString() === "LocalizedText"); assert(node.hasOwnProperty("valueRank...
identifier_body
install.js
/** * @module opcua.address_space * @class AddressSpace */ import assert from "better-assert"; import _ from "underscore"; import NodeClass from "lib/datamodel/NodeClass"; import Argument from "lib/datamodel/argument-list/Argument"; import DataValue from "lib/datamodel/DataValue"; import { Variant } from "lib/datamo...
import { BrowseDirection } from "lib/services/browse_service"; import UAVariable from "lib/address_space/UAVariable"; import UATwoStateVariable from './UATwoStateVariable'; import util from "util"; function _install_TwoStateVariable_machinery(node,options) { assert(node.dataTypeObj.browseName.toString() === "Local...
random_line_split
install.js
/** * @module opcua.address_space * @class AddressSpace */ import assert from "better-assert"; import _ from "underscore"; import NodeClass from "lib/datamodel/NodeClass"; import Argument from "lib/datamodel/argument-list/Argument"; import DataValue from "lib/datamodel/DataValue"; import { Variant } from "lib/datamo...
(node,options) { assert(node.dataTypeObj.browseName.toString() === "LocalizedText"); assert(node.minimumSamplingInterval === 0); assert(node.typeDefinitionObj.browseName.toString() === "TwoStateVariableType"); assert(node.dataTypeObj.browseName.toString() === "LocalizedText"); assert(node.hasOwnProp...
_install_TwoStateVariable_machinery
identifier_name
install.js
/** * @module opcua.address_space * @class AddressSpace */ import assert from "better-assert"; import _ from "underscore"; import NodeClass from "lib/datamodel/NodeClass"; import Argument from "lib/datamodel/argument-list/Argument"; import DataValue from "lib/datamodel/DataValue"; import { Variant } from "lib/datamo...
if (options.falseState) { options.optionals.push("FalseState"); } // we want event based change... options.minimumSamplingInterval = 0; const node = twoStateVariableType.instantiate({ browseName: options.browseName, nodeId: options.nodeId, ...
{ options.optionals.push("TrueState"); }
conditional_block
transform.ts
/// <reference path="..\compiler\transformer.ts"/> /// <reference path="transpile.ts"/> namespace ts { /** * Transform one or more nodes using the supplied transformers. * @param source A single `Node` or an array of `Node` objects. * @param transformers An array of `TransformerFactory` callbacks use...
} }
return result;
random_line_split
transform.ts
/// <reference path="..\compiler\transformer.ts"/> /// <reference path="transpile.ts"/> namespace ts { /** * Transform one or more nodes using the supplied transformers. * @param source A single `Node` or an array of `Node` objects. * @param transformers An array of `TransformerFactory` callbacks use...
<T extends Node>(source: T | T[], transformers: TransformerFactory<T>[], compilerOptions?: CompilerOptions) { const diagnostics: Diagnostic[] = []; compilerOptions = fixupCompilerOptions(compilerOptions, diagnostics); const nodes = isArray(source) ? source : [source]; const result = tran...
transform
identifier_name
transform.ts
/// <reference path="..\compiler\transformer.ts"/> /// <reference path="transpile.ts"/> namespace ts { /** * Transform one or more nodes using the supplied transformers. * @param source A single `Node` or an array of `Node` objects. * @param transformers An array of `TransformerFactory` callbacks use...
}
{ const diagnostics: Diagnostic[] = []; compilerOptions = fixupCompilerOptions(compilerOptions, diagnostics); const nodes = isArray(source) ? source : [source]; const result = transformNodes(/*resolver*/ undefined, /*emitHost*/ undefined, compilerOptions, nodes, transformers, /*allowDtsF...
identifier_body