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
view.py
# Webhooks for external integrations. from __future__ import absolute_import from typing import Any, Dict, List, Optional, Text, Tuple from django.utils.translation import ugettext as _ from django.db.models import Q from django.conf import settings from django.http import HttpRequest, HttpResponse from zerver.models...
elif sub_event == 'issue_comment_edited': verb = 'edited comment on' else: verb = 'deleted comment from' content = u"{} **{}** {}{}".format(get_issue_author(payload), verb, issue, assignee_blurb) comment = get_in(payload, ['comment', 'body']) if comment: ...
verb = 'added comment to'
conditional_block
index.ts
import { window, document } from 'global'; import Channel, { ChannelEvent, ChannelHandler } from '@storybook/channels'; import { logger } from '@storybook/client-logger'; import { isJSON, parse, stringify } from 'telejson'; interface RawEvent { data: string; } interface Config { page: 'manager' | 'preview'; } i...
setHandler(handler: ChannelHandler): void { this.handler = (...args) => { handler.apply(this, args); if (!this.connected && this.getWindow()) { this.flush(); this.connected = true; } }; } /** * Sends `event` to the associated window. If the window does not yet exis...
{ this.buffer = []; this.handler = null; window.addEventListener('message', this.handleEvent.bind(this), false); // Check whether the config.page parameter has a valid value if (config.page !== 'manager' && config.page !== 'preview') { throw new Error(`postmsg-channel: "config.page" cannot be...
identifier_body
index.ts
import { window, document } from 'global'; import Channel, { ChannelEvent, ChannelHandler } from '@storybook/channels'; import { logger } from '@storybook/client-logger'; import { isJSON, parse, stringify } from 'telejson'; interface RawEvent { data: string; } interface Config { page: 'manager' | 'preview'; } i...
}; } /** * Sends `event` to the associated window. If the window does not yet exist * the event will be stored in a buffer and sent when the window exists. * @param event */ send(event: ChannelEvent, options?: any): Promise<any> { const iframeWindow = this.getWindow(); if (!iframeWindow)...
{ this.flush(); this.connected = true; }
conditional_block
index.ts
import { window, document } from 'global'; import Channel, { ChannelEvent, ChannelHandler } from '@storybook/channels'; import { logger } from '@storybook/client-logger'; import { isJSON, parse, stringify } from 'telejson'; interface RawEvent { data: string; } interface Config { page: 'manager' | 'preview'; } i...
// TODO: investigate http://blog.teamtreehouse.com/cross-domain-messaging-with-postmessage // might replace '*' with document.location ? iframeWindow.postMessage(data, '*'); return Promise.resolve(null); } private flush(): void { const { buffer } = this; this.buffer = []; buffer.forEach...
random_line_split
index.ts
import { window, document } from 'global'; import Channel, { ChannelEvent, ChannelHandler } from '@storybook/channels'; import { logger } from '@storybook/client-logger'; import { isJSON, parse, stringify } from 'telejson'; interface RawEvent { data: string; } interface Config { page: 'manager' | 'preview'; } i...
(event: ChannelEvent, options?: any): Promise<any> { const iframeWindow = this.getWindow(); if (!iframeWindow) { return new Promise((resolve, reject) => { this.buffer.push({ event, resolve, reject }); }); } let depth = 15; let allowFunction = true; if (options && typeof opti...
send
identifier_name
debug.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
else: size_checks.append(check_ops.assert_equal(batch_size, first_dim)) with ops.control_dependencies(size_checks): logits = array_ops.zeros([batch_size, head.logits_dimension]) def train_op_fn(loss): return optimizers.optimize_loss( loss, global_step=None, learning_rate=0.3, optimizer=...
batch_size = first_dim
conditional_block
debug.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
``` # Build DebugClassifier classifier = DebugClassifier() # Input builders def input_fn_train: # returns x, y (where y represents label's class index). pass def input_fn_eval: # returns x, y (where y represents label's class index). pass # Fit model. classifier.fit(input_fn=input_fn_train) # Evaluate cross en...
Debug estimators are bias-only estimators that can be used for debugging and as simple baselines. Example:
random_line_split
debug.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
"""Returns predicted scores for given features. Args: input_fn: Input function. batch_size: Override default batch size. Returns: An iterable of predicted scores. """ key = prediction_key.PredictionKey.SCORES preds = self.predict( input_fn=input_fn, batch_size=batch_size,...
identifier_body
debug.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
(self, input_fn=None, batch_size=None): """Returns predicted scores for given features. Args: input_fn: Input function. batch_size: Override default batch size. Returns: An iterable of predicted scores. """ key = prediction_key.PredictionKey.SCORES preds = self.predict( ...
predict_scores
identifier_name
volumes.rs
use std::path::PathBuf; use std::collections::BTreeMap; use quire::validate as V; use quire::ast::{Ast, Tag}; use libc::{uid_t, gid_t}; #[derive(RustcDecodable, Clone, PartialEq, Eq)] pub struct SnapshotInfo { pub size: usize, pub owner_uid: Option<uid_t>, pub owner_gid: Option<gid_t>, pub container:...
V::Directory::new().is_absolute(false), V::Structure::new() .member("mode", V::Numeric::new() .min(0).max(0o1777).default(0o755)) )) .member("files", V::Mapping::new( V::Directory::new().is_absolu...
random_line_split
volumes.rs
use std::path::PathBuf; use std::collections::BTreeMap; use quire::validate as V; use quire::ast::{Ast, Tag}; use libc::{uid_t, gid_t}; #[derive(RustcDecodable, Clone, PartialEq, Eq)] pub struct SnapshotInfo { pub size: usize, pub owner_uid: Option<uid_t>, pub owner_gid: Option<gid_t>, pub container:...
{ pub name: String, pub owner_uid: uid_t, pub owner_gid: gid_t, pub init_command: Option<String>, } #[derive(RustcDecodable, Clone, PartialEq, Eq)] pub enum Volume { Tmpfs(TmpfsInfo), BindRW(PathBuf), BindRO(PathBuf), Empty, VaggaBin, Snapshot(SnapshotInfo), Container(Strin...
PersistentInfo
identifier_name
test.py
#! /usr/bin/env python import numpy as np import gc import matplotlib.pyplot as plt from random import seed, sample, randint from ransac import LineModel, ransac from time import time random_seed = 0 num_iterations = 100 num_samples = 1000 noise_ratio = 0.8 num_noise = int(noise_ratio * num_sampl...
else: print 'RANSAC failed to find a sufficiently good fit for the data.' plt.show() if __name__ == '__main__': setup() run() summary()
print ' Parameters '.center(40, '=') print params print ' Residual '.center(40, '=') print residual print ' Time '.center(40, '=') print '%.1f msecs mean time spent per call' % (1000 * mean_time) X = np.asarray([0, num_samples - 1]) Y = params[0] * X + params[1] ...
conditional_block
test.py
#! /usr/bin/env python import numpy as np import gc import matplotlib.pyplot as plt from random import seed, sample, randint from ransac import LineModel, ransac from time import time random_seed = 0 num_iterations = 100 num_samples = 1000 noise_ratio = 0.8 num_noise = int(noise_ratio * num_sampl...
def run(): global params, residual, mean_time gc.disable() start_time = time() for i in xrange(num_iterations): try: (params, inliers, residual) = ransac(data, model, 2, (1 - noise_ratio) * num_samples) except ValueError: pass end_time = time() mean_time...
global data, model seed(random_seed) X = np.asarray(range(num_samples)) Y = 2 * X noise = [randint(0, 2 * (num_samples - 1)) for i in xrange(num_noise)] Y[sample(xrange(len(Y)), num_noise)] = noise data = np.asarray([X, Y]).T model = LineModel() plt.plot(X, Y, 'bx')
identifier_body
test.py
#! /usr/bin/env python import numpy as np import gc import matplotlib.pyplot as plt from random import seed, sample, randint from ransac import LineModel, ransac from time import time random_seed = 0 num_iterations = 100 num_samples = 1000 noise_ratio = 0.8 num_noise = int(noise_ratio * num_sampl...
try: (params, inliers, residual) = ransac(data, model, 2, (1 - noise_ratio) * num_samples) except ValueError: pass end_time = time() mean_time = (end_time - start_time) / num_iterations gc.enable() def summary(): if params: print ' Parameters '.center(40,...
def run(): global params, residual, mean_time gc.disable() start_time = time() for i in xrange(num_iterations):
random_line_split
test.py
#! /usr/bin/env python import numpy as np import gc import matplotlib.pyplot as plt from random import seed, sample, randint from ransac import LineModel, ransac from time import time random_seed = 0 num_iterations = 100 num_samples = 1000 noise_ratio = 0.8 num_noise = int(noise_ratio * num_sampl...
(): if params: print ' Parameters '.center(40, '=') print params print ' Residual '.center(40, '=') print residual print ' Time '.center(40, '=') print '%.1f msecs mean time spent per call' % (1000 * mean_time) X = np.asarray([0, num_samples - 1]) Y = ...
summary
identifier_name
exceptions.py
# Copyright (C) 2015 by Per Unneberg class NotInstalledError(Exception): """Error thrown if program/command/application cannot be found in path Args: msg (str): String described by exception code (int, optional): Error code, defaults to 2. """ def __init__(self, msg, code=2): sel...
(self, msg, code=2): self.msg = msg self.code = code
__init__
identifier_name
exceptions.py
# Copyright (C) 2015 by Per Unneberg class NotInstalledError(Exception):
class SamplesException(Exception): """Error thrown if samples missing or wrong number. Args: msg (str): String described by exception code (int, optional): Error code, defaults to 2. """ def __init__(self, msg, code=2): self.msg = msg self.code = code class OutputFiles...
"""Error thrown if program/command/application cannot be found in path Args: msg (str): String described by exception code (int, optional): Error code, defaults to 2. """ def __init__(self, msg, code=2): self.msg = msg self.code = code
identifier_body
exceptions.py
# Copyright (C) 2015 by Per Unneberg class NotInstalledError(Exception): """Error thrown if program/command/application cannot be found in path Args: msg (str): String described by exception code (int, optional): Error code, defaults to 2. """ def __init__(self, msg, code=2): sel...
msg (str): String described by exception code (int, optional): Error code, defaults to 2. """ def __init__(self, msg, code=2): self.msg = msg self.code = code
"""Error thrown if outputfiles missing or wrong number. Args:
random_line_split
simulation.py
# Copyright (C) 2015 SensorLab, Jozef Stefan Institute http://sensorlab.ijs.si # # Written by Tomaz Solc, tomaz.solc@ijs.si # # This work has been partially funded by the European Community through the # 7th Framework Programme project CREW (FP7-ICT-2009-258301). # # This program is free software: you can redistribute ...
(self): return self.power_range
get_power_range
identifier_name
simulation.py
# Copyright (C) 2015 SensorLab, Jozef Stefan Institute http://sensorlab.ijs.si # # Written by Tomaz Solc, tomaz.solc@ijs.si # # This work has been partially funded by the European Community through the # 7th Framework Programme project CREW (FP7-ICT-2009-258301). # # This program is free software: you can redistribute ...
def get_bandwidth_range(self): return self.bandwidth_range def get_power_range(self): return self.power_range
random_line_split
simulation.py
# Copyright (C) 2015 SensorLab, Jozef Stefan Institute http://sensorlab.ijs.si # # Written by Tomaz Solc, tomaz.solc@ijs.si # # This work has been partially funded by the European Community through the # 7th Framework Programme project CREW (FP7-ICT-2009-258301). # # This program is free software: you can redistribute ...
class Testbed(TestbedBase): RADIO_CLASS = Radio def __init__(self, send_delay=.1, frequency_range=64, bandwidth_range=10, power_range=10, packet_size=1024): self.send_delay = float(send_delay) self.frequency_range = int(frequency_range) self.bandwidth_range = int(bandwidth_range) self.power_range = int(po...
RECEIVE_TIMEOUT = 2. def __init__(self, addr, dispatcher, send_delay): super(Radio, self).__init__() self.addr = addr self.neighbor = None self.dispatcher = dispatcher self.q = Queue.Queue() self.frequency = 0 self.bandwidth = 0 self.send_delay = send_delay def _recv(self, addr, bindata, frequenc...
identifier_body
simulation.py
# Copyright (C) 2015 SensorLab, Jozef Stefan Institute http://sensorlab.ijs.si # # Written by Tomaz Solc, tomaz.solc@ijs.si # # This work has been partially funded by the European Community through the # 7th Framework Programme project CREW (FP7-ICT-2009-258301). # # This program is free software: you can redistribute ...
try: bindata = self.q.get(True, timeout) except Queue.Empty: raise RadioTimeout else: return bindata class Testbed(TestbedBase): RADIO_CLASS = Radio def __init__(self, send_delay=.1, frequency_range=64, bandwidth_range=10, power_range=10, packet_size=1024): self.send_delay = float(send_delay) ...
timeout = self.RECEIVE_TIMEOUT
conditional_block
Window.js
"use strict"; var CSSStyleDeclaration = require("cssstyle").CSSStyleDeclaration; var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest; var notImplemented = require("./not-implemented"); var History = require("./history"); var VirtualConsole = require("../virtual-console"); var define = require("../utils").def...
}, get frames() { return window._globalProxy; }, get self() { return window._globalProxy; }, get parent() { return window._parent; }, get top() { return window._top; }, get document() { return window._document; }, get location() { retur...
return window._globalProxy;
random_line_split
Window.js
"use strict"; var CSSStyleDeclaration = require("cssstyle").CSSStyleDeclaration; var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest; var notImplemented = require("./not-implemented"); var History = require("./history"); var VirtualConsole = require("../virtual-console"); var define = require("../utils").def...
() { return window._parent; }, get top() { return window._top; }, get document() { return window._document; }, get location() { return window._document._location; } }); namedPropertiesWindow.initializeWindow(this, dom.HTMLCollection); ///// METHODS for [Implic...
parent
identifier_name
Window.js
"use strict"; var CSSStyleDeclaration = require("cssstyle").CSSStyleDeclaration; var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest; var notImplemented = require("./not-implemented"); var History = require("./history"); var VirtualConsole = require("../virtual-console"); var define = require("../utils").def...
} else { setPropertiesFromRule(rule); } }); } readStylesFromStyleSheet(defaultStyleSheet); forEach.call(node.ownerDocument.styleSheets, readStylesFromStyleSheet); forEach.call(s, function (property) { cs.setProperty(property, s.getPropertyValue(property), s.getPr...
{ forEach.call(rule.cssRules, setPropertiesFromRule); }
conditional_block
Window.js
"use strict"; var CSSStyleDeclaration = require("cssstyle").CSSStyleDeclaration; var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest; var notImplemented = require("./not-implemented"); var History = require("./history"); var VirtualConsole = require("../virtual-console"); var define = require("../utils").def...
}, name: "nodejs", innerWidth: 1024, innerHeight: 768, outerWidth: 1024, outerHeight: 768, pageXOffset: 0, pageYOffset: 0, screenX: 0, screenY: 0, screenLeft: 0, screenTop: 0, scrollX: 0, scrollY: 0, scrollTop: 0, scrollLeft: 0, screen: { width...
{ return true; }
identifier_body
nn_test.py
# 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
] class NNInitializersTest(jtu.JaxTestCase): @parameterized.named_parameters(jtu.cases_from_list( {"testcase_name": "_{}_{}".format( rec.name, jtu.format_shape_dtype_string(shape, dtype)), "initializer": rec.initializer(), "shape": shape, "dtype": dtype} for re...
initializer_record("glorot_uniform", nn.initializers.glorot_uniform, jtu.dtypes.inexact), initializer_record("lecun_normal", nn.initializers.lecun_normal, jtu.dtypes.inexact), initializer_record("lecun_uniform", nn.initializers.lecun_uniform, jtu.dtypes.inexact), initializer_record("orthogonal", nn.init...
random_line_split
nn_test.py
# 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
absltest.main(testLoader=jtu.JaxTestLoader())
conditional_block
nn_test.py
# 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
(self): rng = random.PRNGKey(0) shape = (2, 3, 4, 5) initializer = nn.initializers.variance_scaling( scale=1.0, mode='fan_avg', distribution='truncated_normal', in_axis=(0, 1), out_axis=(-2, -1)) val = initializer(rng, shape) self.assertEqual(shape, jnp.shape(val)) def testVarianceSc...
testVarianceScalingMultiAxis
identifier_name
nn_test.py
# 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
rng = jtu.rand_default(self.rng()) args_maker = lambda: [rng((4, 5, 6), jnp.float32)] self._CheckAgainstNumpy( gelu_reference, partial(nn.gelu, approximate=approximate), args_maker, check_dtypes=False, tol=1e-3 if approximate else None) @parameterized.parameters(*itertools.product( (jn...
return x * scipy.stats.norm.cdf(x)
identifier_body
schroedinger_app.py
from __future__ import absolute_import import os import time from math import pi import numpy as nm from sfepy.base.base import Struct, output, get_default from sfepy.applications import PDESolverApp from sfepy.solvers import Solver from six.moves import range def guess_n_eigs(n_electron, n_eigs=None): """ G...
def __init__(self, conf, options, output_prefix, **kwargs): PDESolverApp.__init__(self, conf, options, output_prefix, init_equations=False) def setup_options(self): PDESolverApp.setup_options(self) opts = SchroedingerApp.process_options(self.conf.options)...
""" Application options setup. Sets default values for missing non-compulsory options. Options: save_eig_vectors : (from_largest, from_smallest) or None If None, save all. """ get = options.get n_electron = get('n_electron', 5) n_eigs = gues...
identifier_body
schroedinger_app.py
from __future__ import absolute_import import os import time from math import pi import numpy as nm from sfepy.base.base import Struct, output, get_default from sfepy.applications import PDESolverApp from sfepy.solvers import Solver from six.moves import range def guess_n_eigs(n_electron, n_eigs=None): """ G...
state.set_full(mtx_phi[:,ii]) aux = state.create_output_dict() key = list(aux.keys())[0] out[key+'%03d' % ii] = aux[key] if aux.get('__mesh__') is not None: out['__mesh__'] = aux['__mesh__'] pb.save_state(mesh_results_name, out=out) ...
if (ii > save[0]) and (ii < (n_eigs - save[1])): continue
conditional_block
schroedinger_app.py
from __future__ import absolute_import import os import time from math import pi import numpy as nm from sfepy.base.base import Struct, output, get_default from sfepy.applications import PDESolverApp from sfepy.solvers import Solver from six.moves import range def guess_n_eigs(n_electron, n_eigs=None): """ G...
n_electron = get('n_electron', 5) n_eigs = guess_n_eigs(n_electron, n_eigs=get('n_eigs', None)) return Struct(eigen_solver=get('eigen_solver', None, 'missing "eigen_solver" in options!'), n_electron=n_electron, ...
save_eig_vectors : (from_largest, from_smallest) or None If None, save all. """ get = options.get
random_line_split
schroedinger_app.py
from __future__ import absolute_import import os import time from math import pi import numpy as nm from sfepy.base.base import Struct, output, get_default from sfepy.applications import PDESolverApp from sfepy.solvers import Solver from six.moves import range def guess_n_eigs(n_electron, n_eigs=None): """ G...
(PDESolverApp): """ Base application for electronic structure calculations. Subclasses should typically override `solve_eigen_problem()` method. This class allows solving only simple single electron problems, e.g. well, oscillator, hydrogen atom and boron atom with 1 electron. """ @static...
SchroedingerApp
identifier_name
info_result.rs
// // imag - the personal information management suite for the commandline // Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the F...
map_info, map_info_str, map_info_err, map_info_err_str, |s| { info!("{}", s); } );
InfoResult,
random_line_split
app.component.ts
import {Component} from '@angular/core'; import {OnInit, AfterContentInit, AfterViewInit} from '@angular/core'; @Component({ selector: 'yw-app', template: ` <div class="container-fluid"> <yw-messages [messages]="logMessages"> <header> <h2>Messages Logged</h2> </header> <...
log(message: string) { this.logMessages.push(`${++this.count}: ${message}`); } }
{ this.log('ngAfterViewInit'); }
identifier_body
app.component.ts
import {Component} from '@angular/core'; import {OnInit, AfterContentInit, AfterViewInit} from '@angular/core'; @Component({ selector: 'yw-app', template: ` <div class="container-fluid"> <yw-messages [messages]="logMessages"> <header> <h2>Messages Logged</h2> </header> <...
() { this.log('ngAfterViewInit'); } log(message: string) { this.logMessages.push(`${++this.count}: ${message}`); } }
ngAfterViewInit
identifier_name
app.component.ts
import {Component} from '@angular/core'; import {OnInit, AfterContentInit, AfterViewInit} from '@angular/core'; @Component({ selector: 'yw-app', template: ` <div class="container-fluid"> <yw-messages [messages]="logMessages"> <header> <h2>Messages Logged</h2> </header> <...
log(message: string) { this.logMessages.push(`${++this.count}: ${message}`); } }
this.log('ngAfterViewInit'); }
random_line_split
steps.js
module.exports = { '/': { backLink: '/../priority_service_170705/filter/uncancelled', next: '/what-you-need' }, '/before-you-continue-overseas': { backLink: '/../priority_service_170705/overseas/uncancelled', next: '/what-you-need-overseas' }, '/what-you-need': { ...
'/choose-photo-method': { fields: ['choose-photo'], next: '/../upload' }, '/choose-photo-method-overseas': { fields: ['choose-photo-overseas'], next: '/../upload' } };
next: '/choose-photo-method' },
random_line_split
snack-bar-container.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {AnimationEvent} from '@angular/animations'; import {AriaLivePoliteness} from '@angular/cdk/a11y'; import {Pla...
/** Begin animation of the snack bar exiting from view. */ exit(): Observable<void> { // Note: this one transitions to `hidden`, rather than `void`, in order to handle the case // where multiple snack bars are opened in quick succession (e.g. two consecutive calls to // `MatSnackBar.open`). this._...
{ if (!this._destroyed) { this._animationState = 'visible'; this._changeDetectorRef.detectChanges(); this._screenReaderAnnounce(); } }
identifier_body
snack-bar-container.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {AnimationEvent} from '@angular/animations'; import {AriaLivePoliteness} from '@angular/cdk/a11y'; import {Pla...
} } /** Attach a component portal as content to this snack bar container. */ attachComponentPortal<T>(portal: ComponentPortal<T>): ComponentRef<T> { this._assertNotAttached(); this._applySnackBarClasses(); return this._portalOutlet.attachComponentPortal(portal); } /** Attach a template port...
{ this._role = 'alert'; }
conditional_block
snack-bar-container.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {AnimationEvent} from '@angular/animations'; import {AriaLivePoliteness} from '@angular/cdk/a11y'; import {Pla...
templateUrl: 'snack-bar-container.html', styleUrls: ['snack-bar-container.css'], // In Ivy embedded views will be change detected from their declaration place, rather than // where they were stamped out. This means that we can't have the snack bar container be OnPush, // because it might cause snack bars that...
*/ @Component({ selector: 'snack-bar-container',
random_line_split
snack-bar-container.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {AnimationEvent} from '@angular/animations'; import {AriaLivePoliteness} from '@angular/cdk/a11y'; import {Pla...
(): Observable<void> { // Note: this one transitions to `hidden`, rather than `void`, in order to handle the case // where multiple snack bars are opened in quick succession (e.g. two consecutive calls to // `MatSnackBar.open`). this._animationState = 'hidden'; // Mark this element with an 'exit' a...
exit
identifier_name
pig_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): if self.pigparams_jinja_translate: self.pig = re.sub( r"(\$([a-zA-Z_][a-zA-Z0-9_]*))", r"{{ \g<2> }}", self.pig) def execute(self, context): self.log.info('Executing: %s', self.pig) self.hook = self.get_hook() self.hook.run_cli(pig=self.pig, pig_o...
prepare_template
identifier_name
pig_operator.py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
# -*- coding: utf-8 -*- #
random_line_split
pig_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.pig) self.hook = self.get_hook() self.hook.run_cli(pig=self.pig, pig_opts=self.pig_opts) def on_kill(self): self.hook.kill()
self.pig = re.sub( r"(\$([a-zA-Z_][a-zA-Z0-9_]*))", r"{{ \g<2> }}", self.pig)
conditional_block
pig_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 get_hook(self): return PigCliHook(pig_cli_conn_id=self.pig_cli_conn_id) def prepare_template(self): if self.pigparams_jinja_translate: self.pig = re.sub( r"(\$([a-zA-Z_][a-zA-Z0-9_]*))", r"{{ \g<2> }}", self.pig) def execute(self, context): self.lo...
super().__init__(*args, **kwargs) self.pigparams_jinja_translate = pigparams_jinja_translate self.pig = pig self.pig_cli_conn_id = pig_cli_conn_id self.pig_opts = pig_opts
identifier_body
synth.py
# Copyright 2018 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 writing, s...
"docs/index.rst", f"tests/system/gapic/{version}/" f"test_system_video_intelligence_service_{version}.py", # f'tests/unit/gapic/{version}/' # f'test_video_intelligence_service_client_{version}.py', ], ) s.replace( "**/*/video_intelligence_serv...
library, excludes=[ "setup.py", "nox*.py", "README.rst",
random_line_split
synth.py
# Copyright 2018 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 writing, s...
s.replace( "**/*/video_intelligence_service_client.py", "'google-cloud-video-intelligence', \).version", "'google-cloud-videointelligence', ).version", ) s.replace( "tests/unit/gapic/**/test_video_intelligence_service_client_*.py", "^(\s+)expected_request = video_intelligence_pb2.AnnotateVideoReq...
library = gapic.py_library( "videointelligence", version, artman_output_name=f"video-intelligence-{version}" ) # TODO: stop excluding tests and nox.py (excluded as we lack system tests) s.move( library, excludes=[ "setup.py", "nox*.py", "README.rs...
conditional_block
image.py
# -*- coding: utf-8 -*- import attr from cached_property import cached_property from navmazing import NavigateToSibling, NavigateToAttribute from wrapanapi.containers.image import Image as ApiImage from cfme.common import (WidgetasticTaggable, PolicyProfileAssignable, TagPageView) from cfme.c...
"""Initiates compliance check and waits for it to finish on several Images. Args: image_entities: list of Image entities that need to perform compliance check on them check_on_entity (bool): check the compliance status on the entity summary view if True, ...
random_line_split
image.py
# -*- coding: utf-8 -*- import attr from cached_property import cached_property from navmazing import NavigateToSibling, NavigateToAttribute from wrapanapi.containers.image import Image as ApiImage from cfme.common import (WidgetasticTaggable, PolicyProfileAssignable, TagPageView) from cfme.c...
else: raise ValueError("{} is not a known state for compliance".format(text)) @attr.s class ImageCollection(GetRandomInstancesMixin, BaseCollection, PolicyProfileAssignable): """Collection object for :py:class:`Image`.""" ENTITY = Image def all(self): # container_images has ...
return True
conditional_block
image.py
# -*- coding: utf-8 -*- import attr from cached_property import cached_property from navmazing import NavigateToSibling, NavigateToAttribute from wrapanapi.containers.image import Image as ApiImage from cfme.common import (WidgetasticTaggable, PolicyProfileAssignable, TagPageView) from cfme.c...
@navigator.register(Image, 'Details') class Details(CFMENavigateStep): VIEW = ImageDetailsView prerequisite = NavigateToAttribute('parent', 'All') def step(self): search_visible = self.prerequisite_view.entities.search.is_displayed self.prerequisite_view.entities.get_entity(provider=self...
self.view.entities.search.clear_simple_search() self.view.toolbar.view_selector.select("List View")
identifier_body
image.py
# -*- coding: utf-8 -*- import attr from cached_property import cached_property from navmazing import NavigateToSibling, NavigateToAttribute from wrapanapi.containers.image import Image as ApiImage from cfme.common import (WidgetasticTaggable, PolicyProfileAssignable, TagPageView) from cfme.c...
(BaseEntity, WidgetasticTaggable, Labelable, LoadDetailsMixin, PolicyProfileAssignable): PLURAL = 'Container Images' all_view = ImageAllView details_view = ImageDetailsView name = attr.ib() id = attr.ib() provider = attr.ib() @cached_property def mgmt(self): return ApiImage(se...
Image
identifier_name
animation.py
"""Animation. Animation is set of keyframes. Value of selected attribute changes in time. Keyframe: (time, value) Objects have animation manager which manages animation graph and switching.""" from operator import itemgetter from eaf import Timer from xoinvader.utils import Point class AnimationBoundariesExce...
(values, types): """Check if values are belongs to same type or type tuple. :param collections.Iterable values: values to check type similarity :param tuple|type types: type or tuple of types """ return all(map(lambda it: isinstance(it, types), values)) def interpolate(first, second, current_tim...
same_type
identifier_name
animation.py
"""Animation. Animation is set of keyframes. Value of selected attribute changes in time. Keyframe: (time, value) Objects have animation manager which manages animation graph and switching.""" from operator import itemgetter from eaf import Timer from xoinvader.utils import Point class AnimationBoundariesExce...
def add(self, name, *args, **kwargs): """Add new animation, pass args to Animation class. See interface of `class::xoinvader.animation.Animation`. :param str name: animation name """ animation = Animation(name, *args, **kwargs) self._animations[name] = animation ...
raise ValueError(f"No such animation: '{name}'.")
conditional_block
animation.py
"""Animation. Animation is set of keyframes. Value of selected attribute changes in time. Keyframe: (time, value) Objects have animation manager which manages animation graph and switching.""" from operator import itemgetter from eaf import Timer from xoinvader.utils import Point class AnimationBoundariesExce...
@animation.setter def animation(self, name): if name in self._animations: self._animation = self._animations[name] else: raise ValueError(f"No such animation: '{name}'.") def add(self, name, *args, **kwargs): """Add new animation, pass args to Animation cla...
"""AnimationManager's current animation name. To set animation - assign it's name. :getter: yes :setter: yes :type: str """ if self._animation: return self._animation.name else: raise AttributeError("There is no available animation.")
identifier_body
animation.py
"""Animation. Animation is set of keyframes. Value of selected attribute changes in time. Keyframe: (time, value) Objects have animation manager which manages animation graph and switching.""" from operator import itemgetter from eaf import Timer from xoinvader.utils import Point class AnimationBoundariesExce...
if not self._animation: self._animation = animation def update(self, dt): """Update manager's state.""" if not self._animation: return try: self._animation.update(dt) except StopIteration: return # TODO: think about method t...
random_line_split
kblink.directive.js
(function() { 'use strict'; angular.module('facetApp') .directive('kblink', function() { return { restrict: 'EC', scope: { href: '@' }, transclude: true, controller: ['$scope', 'popoverService', function($scope, popoverService){ if (!$scope.href) return; $scope.image...
if (data.hasOwnProperty('image')) $scope.image = data.image; }); }], template: '<a uib-popover-template="\'views/tooltips/personTooltipTemplate.html\'" popover-trigger="\'mouseenter\'" ng-href="{{ link }}" ng-transclude></a>' }}); })();
{ // remove leading zeros (0800-0900) -> (800-900) data.lifespan = data.lifespan.replace(/(\D)0/g, "$1"); $scope.lifespan = data.lifespan; }
conditional_block
kblink.directive.js
(function() { 'use strict'; angular.module('facetApp')
scope: { href: '@' }, transclude: true, controller: ['$scope', 'popoverService', function($scope, popoverService){ if (!$scope.href) return; $scope.image = false; $scope.lifespan = ''; popoverService.getHrefPopover($scope.href).then(function(data) ...
.directive('kblink', function() { return { restrict: 'EC',
random_line_split
old-state-manager.ts
import mapValues from 'lodash-es/mapValues' import {IOldGameData, OldState} from './types' const KEYS = { currentRound: 'Bridge.currentRound', maker: 'Bridge.maker', players: 'Bridge.players', state: 'Bridge.state', totalRounds: 'Bridge.totalRounds' } /** * Attempt to get v1.0.0 data from localStorage. * ...
else { return dataMap as any } } /** * Test if there is v1.0.0 data. * Even the state is notStarted, this function will still return true. */ export function hasOldData(): boolean { return localStorage.getItem('Bridge.state') !== null } /** * Check if old data is on state `notStarted` or does not have th...
{ return null }
conditional_block
old-state-manager.ts
import mapValues from 'lodash-es/mapValues' import {IOldGameData, OldState} from './types' const KEYS = { currentRound: 'Bridge.currentRound', maker: 'Bridge.maker', players: 'Bridge.players', state: 'Bridge.state', totalRounds: 'Bridge.totalRounds' } /** * Attempt to get v1.0.0 data from localStorage. * ...
* Remove all old data in v1.0.0 from localStorage */ export function deleteOldData(): void { Object.values(KEYS).forEach(key => localStorage.removeItem(key) ) }
/**
random_line_split
old-state-manager.ts
import mapValues from 'lodash-es/mapValues' import {IOldGameData, OldState} from './types' const KEYS = { currentRound: 'Bridge.currentRound', maker: 'Bridge.maker', players: 'Bridge.players', state: 'Bridge.state', totalRounds: 'Bridge.totalRounds' } /** * Attempt to get v1.0.0 data from localStorage. * ...
/** * Check if old data is on state `notStarted` or does not have the game. * If either one of the above condition met, false will be returned */ export function isNotStarted(data: IOldGameData | null): boolean { return data == null || data.state === OldState.notStarted } /** * Remove all old data in v1.0.0 fr...
{ return localStorage.getItem('Bridge.state') !== null }
identifier_body
old-state-manager.ts
import mapValues from 'lodash-es/mapValues' import {IOldGameData, OldState} from './types' const KEYS = { currentRound: 'Bridge.currentRound', maker: 'Bridge.maker', players: 'Bridge.players', state: 'Bridge.state', totalRounds: 'Bridge.totalRounds' } /** * Attempt to get v1.0.0 data from localStorage. * ...
(): boolean { return localStorage.getItem('Bridge.state') !== null } /** * Check if old data is on state `notStarted` or does not have the game. * If either one of the above condition met, false will be returned */ export function isNotStarted(data: IOldGameData | null): boolean { return data == null || data.st...
hasOldData
identifier_name
fuzz_target_1.rs
#![no_main] #[macro_use] extern crate libfuzzer_sys; extern crate quick_xml;
fuzz_target!(|data: &[u8]| { // fuzzed code goes here let cursor = Cursor::new(data); let mut reader = Reader::from_reader(cursor); let mut buf = vec![]; loop { match reader.read_event(&mut buf) { Ok(Event::Start(ref e)) | Ok(Event::Empty(ref e))=> { if e.unescape...
use quick_xml::Reader; use quick_xml::events::Event; use std::io::Cursor;
random_line_split
cabi_arm.rs
// Copyright 2012-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-MI...
let align = align_fn(ty); let size = ty_size(ty, align_fn); let llty = if align <= 4 { Type::array(&Type::i32(ccx), ((size + 3) / 4) as u64) } else { Type::array(&Type::i64(ccx), ((size + 7) / 8) as u64) }; ArgType::direct(ty, Some(llty), None, None) } fn is_reg_ty(ty: Type) -> ...
random_line_split
cabi_arm.rs
// Copyright 2012-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-MI...
fn is_reg_ty(ty: Type) -> bool { match ty.kind() { Integer | Pointer | Float | Double | Vector => true, _ => false } } pub fn compute_abi_info(ccx: &CrateContext, atys: &[Type], rty: Type, ...
{ if is_reg_ty(ty) { let attr = if ty == Type::i1(ccx) { Some(ZExtAttribute) } else { None }; return ArgType::direct(ty, None, None, attr); } let align = align_fn(ty); let size = ty_size(ty, align_fn); let llty = if align <= 4 { Type::array(&Type::i32(ccx), ((size + 3) / 4) a...
identifier_body
cabi_arm.rs
// Copyright 2012-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-MI...
(ty: Type) -> uint { match ty.kind() { Integer => ((ty.int_width() as uint) + 7) / 8, Pointer => 4, Float => 4, Double => 8, Struct => { if ty.is_packed() { 1 } else { let str_tys = ty.field_types(); str_...
general_ty_align
identifier_name
scene.py
"""Support for Lutron Caseta scenes.""" from typing import Any from homeassistant.components.scene import Scene from .const import BRIDGE_LEAP, DOMAIN as CASETA_DOMAIN async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Lutron Caseta scene platform. Adds scenes from the Caset...
async def async_activate(self, **kwargs: Any) -> None: """Activate the scene.""" await self._bridge.activate_scene(self._scene_id)
"""Return the name of the scene.""" return self._scene_name
identifier_body
scene.py
"""Support for Lutron Caseta scenes.""" from typing import Any from homeassistant.components.scene import Scene from .const import BRIDGE_LEAP, DOMAIN as CASETA_DOMAIN async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Lutron Caseta scene platform. Adds scenes from the Caset...
for scene in scenes: entity = LutronCasetaScene(scenes[scene], bridge) entities.append(entity) async_add_entities(entities, True) class LutronCasetaScene(Scene): """Representation of a Lutron Caseta scene.""" def __init__(self, scene, bridge): """Initialize the Lutron Caseta ...
random_line_split
scene.py
"""Support for Lutron Caseta scenes.""" from typing import Any from homeassistant.components.scene import Scene from .const import BRIDGE_LEAP, DOMAIN as CASETA_DOMAIN async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Lutron Caseta scene platform. Adds scenes from the Caset...
async_add_entities(entities, True) class LutronCasetaScene(Scene): """Representation of a Lutron Caseta scene.""" def __init__(self, scene, bridge): """Initialize the Lutron Caseta scene.""" self._scene_name = scene["name"] self._scene_id = scene["scene_id"] self._bridge...
entity = LutronCasetaScene(scenes[scene], bridge) entities.append(entity)
conditional_block
scene.py
"""Support for Lutron Caseta scenes.""" from typing import Any from homeassistant.components.scene import Scene from .const import BRIDGE_LEAP, DOMAIN as CASETA_DOMAIN async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Lutron Caseta scene platform. Adds scenes from the Caset...
(self, scene, bridge): """Initialize the Lutron Caseta scene.""" self._scene_name = scene["name"] self._scene_id = scene["scene_id"] self._bridge = bridge @property def name(self): """Return the name of the scene.""" return self._scene_name async def async_a...
__init__
identifier_name
index.ts
let rectWidth = 70, rectHeight = 70 document.addEventListener('dragstart', e => { let fa = e.target.querySelector('i.fa') if (fa) { let type = fa.className.split(' ')[1] e.dataTransfer.setData('text/plain', type) } }) document.querySelector('svg').addEventListener('drop', e => { let ...
function mouseup() { if (drawLineEnable && drawLineFrom) { drag_line.classed('hidden', true) drawLineFrom = null } else { clearAllEditStyle() } simulation.alphaTarget(0) } function clearAllEditStyle() { d3.selectAll('.node').classed('selected', false) d3.selectAll('.cro...
drag_line.attr('d', `M${drawLineFrom.x},${drawLineFrom.y}L${centerX},${centerY}L${p[0]},${p[1]}`) } }
random_line_split
index.ts
let rectWidth = 70, rectHeight = 70 document.addEventListener('dragstart', e => { let fa = e.target.querySelector('i.fa') if (fa) { let type = fa.className.split(' ')[1] e.dataTransfer.setData('text/plain', type) } }) document.querySelector('svg').addEventListener('drop', e => { let ...
ument.querySelector('.connect .add'), buttonView = document.querySelector('.connect .view'), buttonEdit = document.querySelector('.connect .edit'), svg = document.querySelector('svg') buttonView.addEventListener('click', e => { buttonView.classList.add('hidden') buttonEdit.c...
dd = doc
identifier_name
index.ts
let rectWidth = 70, rectHeight = 70 document.addEventListener('dragstart', e => { let fa = e.target.querySelector('i.fa') if (fa) { let type = fa.className.split(' ')[1] e.dataTransfer.setData('text/plain', type) } }) document.querySelector('svg').addEventListener('drop', e => { let ...
() { d3.selectAll('.node').classed('selected', false) d3.selectAll('.cross').classed('hidden', true) d3.selectAll('.selected').classed('selected', false) }
drawLineFrom) { drag_line.classed('hidden', true) drawLineFrom = null } else { clearAllEditStyle() } simulation.alphaTarget(0) } function clearAllEditStyle
identifier_body
CommandTester.d.ts
declare namespace Jymfony.Component.Console.Tester { import Command = Jymfony.Component.Console.Command.Command; import InputInterface = Jymfony.Component.Console.Input.InputInterface; import OutputInterface = Jymfony.Component.Console.Output.OutputInterface; import ArrayInput = Jymfony.Component.Consol...
{ /** * Gets the input instance used by the last execution of application. */ public readonly input: InputInterface; /** * Sets the user input. */ public /* writeonly */ inputs: string[]; /** * Gets the output instance used by the l...
CommandTester
identifier_name
CommandTester.d.ts
import Command = Jymfony.Component.Console.Command.Command; import InputInterface = Jymfony.Component.Console.Input.InputInterface; import OutputInterface = Jymfony.Component.Console.Output.OutputInterface; import ArrayInput = Jymfony.Component.Console.Input.ArrayInput; export class CommandTester {...
declare namespace Jymfony.Component.Console.Tester {
random_line_split
test-string-decoder.js
// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modi...
function test(encoding, input, expected, singleSequence) { let sequences; if (!singleSequence) { sequences = writeSequences(input.length); } else { sequences = [singleSequence]; } const hexNumberRE = /.{2}/g; sequences.forEach((sequence) => { const decoder = new StringDecoder(encoding); let ...
// singleSequence allows for easy debugging of a specific sequence which is // useful in case of test failures.
random_line_split
test-string-decoder.js
// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modi...
Escape prints the str contents as unicode escape codes. function unicodeEscape(str) { let r = ''; for (let i = 0; i < str.length; i++) { r += `\\u${str.charCodeAt(i).toString(16)}`; } return r; } // writeSequences returns an array of arrays that describes all possible ways a // buffer of the given length c...
ences; if (!singleSequence) { sequences = writeSequences(input.length); } else { sequences = [singleSequence]; } const hexNumberRE = /.{2}/g; sequences.forEach((sequence) => { const decoder = new StringDecoder(encoding); let output = ''; sequence.forEach((write) => { output += decode...
identifier_body
test-string-decoder.js
// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modi...
rt, sequence) { if (start === undefined) { start = 0; sequence = []; } else if (start === length) { return [sequence]; } let sequences = []; for (let end = length; end > start; end--) { const subSequence = sequence.concat([[start, end]]); const subSequences = writeSequences(length, end, su...
es(length, sta
identifier_name
test-string-decoder.js
// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modi...
sequences = [singleSequence]; } const hexNumberRE = /.{2}/g; sequences.forEach((sequence) => { const decoder = new StringDecoder(encoding); let output = ''; sequence.forEach((write) => { output += decoder.write(input.slice(write[0], write[1])); }); output += decoder.end(); if (output...
ces = writeSequences(input.length); } else {
conditional_block
main.rs
extern crate libc; extern crate scaly; use libc::c_char; use libc::c_int; use scaly::containers::{Array, Ref, String, Vector}; use scaly::memory::Heap; use scaly::memory::Page; use scaly::memory::Region; use scaly::memory::StackBucket; use std::ffi::CString; mod scalyc; // Rust's main which converts args back to C...
.map(|arg| arg.as_ptr()) .collect::<Vec<*const c_char>>(); _main(c_args.len() as c_int, c_args.as_ptr()); } // C style main function which converts args to Scaly's main convention (would be provided by the LLVM backend) fn _main(argc: c_int, argv: *const *const c_char) { let _r = Region::create...
.map(|arg| CString::new(arg).unwrap()) .collect::<Vec<CString>>(); let c_args = args .iter()
random_line_split
main.rs
extern crate libc; extern crate scaly; use libc::c_char; use libc::c_int; use scaly::containers::{Array, Ref, String, Vector}; use scaly::memory::Heap; use scaly::memory::Page; use scaly::memory::Region; use scaly::memory::StackBucket; use std::ffi::CString; mod scalyc; // Rust's main which converts args back to C...
(argc: c_int, argv: *const *const c_char) { let _r = Region::create_from_page(Page::get(StackBucket::create(&mut Heap::create()) as usize)); _scalyc_main(&_r, { let _r_1 = Region::create(&_r); let mut arguments: Ref<Array<String>> = Ref::new(_r_1.page, Array::new()); for n in 0..argc { ...
_main
identifier_name
main.rs
extern crate libc; extern crate scaly; use libc::c_char; use libc::c_int; use scaly::containers::{Array, Ref, String, Vector}; use scaly::memory::Heap; use scaly::memory::Page; use scaly::memory::Region; use scaly::memory::StackBucket; use std::ffi::CString; mod scalyc; // Rust's main which converts args back to C...
unsafe { let arg = argv.offset(n as isize); let s = String::from_c_string(_r.page, *arg); (*arguments).add(s); } } Ref::new(_r.page, Vector::from_array(_r.page, arguments)) }); } fn _scalyc_main(_pr: &Region, arguments: Ref<V...
{ continue; }
conditional_block
main.rs
extern crate libc; extern crate scaly; use libc::c_char; use libc::c_int; use scaly::containers::{Array, Ref, String, Vector}; use scaly::memory::Heap; use scaly::memory::Page; use scaly::memory::Region; use scaly::memory::StackBucket; use std::ffi::CString; mod scalyc; // Rust's main which converts args back to C...
{ use scalyc::compiler::Compiler; let _r = Region::create(_pr); let compiler = Ref::new(_r.page, Compiler::new(_r.page, arguments)); (*compiler).compile(&_r, _r.page, _r.page); }
identifier_body
dashboard_deeplink_provider_types.ts
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or a...
==============================================================================*/ import {URLDeserializedState as MetricsURLDeserializedState} from '../metrics/types'; import {URLDeserializedState as RunsURLDeserializedState} from '../runs/types'; // No need to deserialize the Experimental Plugins as it is immutable an...
See the License for the specific language governing permissions and limitations under the License.
random_line_split
__init__.py
# This file is part of Pyphen # # Copyright 2008 - Wilbert Berendsen <info@wilbertberendsen.nl> # Copyright 2012-2013 - Guillaume Ayoub <guillaume.ayoub@kozea.fr> # # This library is free software. It is released under the # GPL 2.0+/LGPL 2.1+/MPL 1.1 tri-license. See COPYING.GPL, COPYING.LGPL and # COPYING.MPL for m...
(self, word, width, hyphen='-'): """Get the longest possible first part and the last part of a word. :param word: unicode string of the word to hyphenate :param width: maximum length of the first part :param hyphen: unicode string used as hyphen character The first part has the...
wrap
identifier_name
__init__.py
# This file is part of Pyphen # # Copyright 2008 - Wilbert Berendsen <info@wilbertberendsen.nl> # Copyright 2012-2013 - Guillaume Ayoub <guillaume.ayoub@kozea.fr> # # This library is free software. It is released under the # GPL 2.0+/LGPL 2.1+/MPL 1.1 tri-license. See COPYING.GPL, COPYING.LGPL and # COPYING.MPL for m...
def wrap(self, word, width, hyphen='-'): """Get the longest possible first part and the last part of a word. :param word: unicode string of the word to hyphenate :param width: maximum length of the first part :param hyphen: unicode string used as hyphen character The firs...
if position.data: # get the nonstandard hyphenation data change, index, cut = position.data index += position if word.isupper(): change = change.upper() c1, c2 = change.split('=') yield word[:index] + c1,...
conditional_block
__init__.py
# This file is part of Pyphen # # Copyright 2008 - Wilbert Berendsen <info@wilbertberendsen.nl> # Copyright 2012-2013 - Guillaume Ayoub <guillaume.ayoub@kozea.fr> # # This library is free software. It is released under the # GPL 2.0+/LGPL 2.1+/MPL 1.1 tri-license. See COPYING.GPL, COPYING.LGPL and # COPYING.MPL for m...
else: return value class DataInt(int): """``int`` with some other data can be stuck to in a ``data`` attribute.""" def __new__(cls, value, data=None, reference=None): """Create a new ``DataInt``. Call with ``reference=dataint_object`` to use the data from another `...
def __call__(self, value): self.index -= 1 value = int(value) if value & 1: return DataInt(value, (self.change, self.index, self.cut))
random_line_split
__init__.py
# This file is part of Pyphen # # Copyright 2008 - Wilbert Berendsen <info@wilbertberendsen.nl> # Copyright 2012-2013 - Guillaume Ayoub <guillaume.ayoub@kozea.fr> # # This library is free software. It is released under the # GPL 2.0+/LGPL 2.1+/MPL 1.1 tri-license. See COPYING.GPL, COPYING.LGPL and # COPYING.MPL for m...
def wrap(self, word, width, hyphen='-'): """Get the longest possible first part and the last part of a word. :param word: unicode string of the word to hyphenate :param width: maximum length of the first part :param hyphen: unicode string used as hyphen character The firs...
"""Iterate over all hyphenation possibilities, the longest first. :param word: unicode string of the word to hyphenate """ for position in reversed(self.positions(word)): if position.data: # get the nonstandard hyphenation data change, index, cut = p...
identifier_body
hex.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...
#[test] pub fn test_from_hex_invalid_char() { assert!("66y6".from_hex().is_err()); } #[test] pub fn test_from_hex_ignores_whitespace() { assert_eq!("666f 6f6\r\n26172 ".from_hex().unwrap(), b"foobar"); } #[test] pub fn test_to_hex_all_bytes() { ...
{ assert!("666".from_hex().is_err()); assert!("66 6".from_hex().is_err()); }
identifier_body
hex.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...
use std::fmt; use std::error; /// A trait for converting a value to hexadecimal encoding pub trait ToHex { /// Converts the value of `self` to a hex value, returning the owned /// string. fn to_hex(&self) -> String; } const CHARS: &'static [u8] = b"0123456789abcdef"; impl ToHex for [u8] { /// Turn a ...
//! Hex binary-to-text encoding pub use self::FromHexError::*;
random_line_split
hex.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...
(&self) -> Result<Vec<u8>, FromHexError> { // This may be an overestimate if there is any whitespace let mut b = Vec::with_capacity(self.len() / 2); let mut modulus = 0; let mut buf = 0; for (idx, byte) in self.bytes().enumerate() { buf <<= 4; match byte...
from_hex
identifier_name
97bbc733896c_create_oauthclient_tables.py
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Create oauthclient tables.""" import sqlalchemy as sa import sqlalchemy_utils fro...
"""Downgrade database.""" ctx = op.get_context() insp = Inspector.from_engine(ctx.connection.engine) op.drop_table('oauthclient_remotetoken') for fk in insp.get_foreign_keys('oauthclient_useridentity'): if fk['referred_table'] == 'accounts_user': op.drop_constraint( ...
identifier_body
97bbc733896c_create_oauthclient_tables.py
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Create oauthclient tables.""" import sqlalchemy as sa import sqlalchemy_utils fro...
op.drop_index( 'useridentity_id_user_method', table_name='oauthclient_useridentity') op.drop_table('oauthclient_useridentity') op.drop_table('oauthclient_remoteaccount')
op.drop_constraint( op.f(fk['name']), 'oauthclient_useridentity', type_='foreignkey' )
conditional_block
97bbc733896c_create_oauthclient_tables.py
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Create oauthclient tables.""" import sqlalchemy as sa import sqlalchemy_utils
# revision identifiers, used by Alembic. revision = '97bbc733896c' down_revision = '44ab9963e8cf' branch_labels = () depends_on = '9848d0149abd' def upgrade(): """Upgrade database.""" op.create_table( 'oauthclient_remoteaccount', sa.Column('id', sa.Integer(), nullable=False), sa.Column...
from alembic import op from sqlalchemy.engine.reflection import Inspector
random_line_split
97bbc733896c_create_oauthclient_tables.py
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Create oauthclient tables.""" import sqlalchemy as sa import sqlalchemy_utils fro...
(): """Downgrade database.""" ctx = op.get_context() insp = Inspector.from_engine(ctx.connection.engine) op.drop_table('oauthclient_remotetoken') for fk in insp.get_foreign_keys('oauthclient_useridentity'): if fk['referred_table'] == 'accounts_user': op.drop_constraint( ...
downgrade
identifier_name
40.rs
/* Problem 40: Champernowne's constant * * An irrational decimal fraction is created by concatenating the positive integers: * * 0.123456789101112131415161718192021... * * It can be seen that the 12th digit of the fractional part is 1. * * If dn represents the nth digit of the fractional part, find the value of...
let result: u32 = [1, 10, 100, 1000, 10000, 100000, 1000000] .iter() .map(|&position| { (1..) .flat_map(digits::new::<_, u32>) .nth(position as usize - 1) .unwrap() }) .fold(1, |acc, n| acc * n); println!("{}", result); ...
{
identifier_name
40.rs
/* Problem 40: Champernowne's constant * * An irrational decimal fraction is created by concatenating the positive integers: * * 0.123456789101112131415161718192021... * * It can be seen that the 12th digit of the fractional part is 1. * * If dn represents the nth digit of the fractional part, find the value of...
* * d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000 */ use shared::digits; fn main() { let result: u32 = [1, 10, 100, 1000, 10000, 100000, 1000000] .iter() .map(|&position| { (1..) .flat_map(digits::new::<_, u32>) .nth(position as usize - 1) ...
random_line_split
40.rs
/* Problem 40: Champernowne's constant * * An irrational decimal fraction is created by concatenating the positive integers: * * 0.123456789101112131415161718192021... * * It can be seen that the 12th digit of the fractional part is 1. * * If dn represents the nth digit of the fractional part, find the value of...
let result: u32 = [1, 10, 100, 1000, 10000, 100000, 1000000] .iter() .map(|&position| { (1..) .flat_map(digits::new::<_, u32>) .nth(position as usize - 1) .unwrap() }) .fold(1, |acc, n| acc * n); println!("{}", result); }
identifier_body
hw5_start.py
# CIS 410/510pm # Homework 5 beta 0.0.1 # Cameron Palk # May 2016 # # Special thanks to Daniel Lowd for the skeletor code import sys import tokenize from functools import reduce global_card = [] num_vars = 0 ''' Calc Strides ''' def calcStrides( scope ): rev_scope = list( reversed( scope ) ) res = [ 1 ] + [ 0 ] *...
( dict ): # Constructor def __init__(self, scope_, vals_): self.scope = scope_ self.vals = vals_ self.stride = calcStrides( scope_ ) # # Are two object EQual, True of False def __eq__(self, other): return (self.scope == other.scope and self.vals == other.vals and self.stride == other.stride ) ...
Factor
identifier_name