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 |
|---|---|---|---|---|
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 | # Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==... |
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 | # Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==... |
```
# 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 | .
loss = classifier.evaluate(input_fn=input_fn_eval)["loss"]
# predict_classes outputs the most commonly seen class in training.
predicted_label = classifier.predict_classes(new_samples)
# predict_proba outputs the class distribution from training.
label_distribution = classifier.predict_proba(new_samples)
```
"""
fr... | """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 | used for debugging
and as simple baselines.
Example:
```
# 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.
class... | 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 ... | self.frequency = frequency
self.bandwidth = bandwidth
def binsend(self, bindata):
self.dispatcher(self.neighbor, bindata, self.frequency, self.bandwidth)
time.sleep(self.send_delay)
def binrecv(self, timeout=None):
if timeout is None:
timeout = self.RECEIVE_TIMEOUT
try:
bindata = self.q.get(True,... | 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 | // TODO: consider a mode of some sort where these are not shared between all DOM instances
// It'd be very memory-expensive in most cases, though.
define(window, dom);
///// PRIVATE DATA PROPERTIES
// vm initialization is defered until script processing is activated (in level1/core)
this._globalProxy = thi... | },
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 | // TODO: consider a mode of some sort where these are not shared between all DOM instances
// It'd be very memory-expensive in most cases, though.
define(window, dom);
///// PRIVATE DATA PROPERTIES
// vm initialization is defered until script processing is activated (in level1/core)
this._globalProxy = thi... | () {
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 | TODO: consider a mode of some sort where these are not shared between all DOM instances
// It'd be very memory-expensive in most cases, though.
define(window, dom);
///// PRIVATE DATA PROPERTIES
// vm initialization is defered until script processing is activated (in level1/core)
this._globalProxy = this;
... |
} 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 | .url,
referrer: options.referrer,
cookie: options.cookie,
deferClose: options.deferClose,
resourceLoader: options.resourceLoader,
concurrentNodeIterators: options.concurrentNodeIterators,
defaultView: this._globalProxy,
global: this
});
// Set up the window as if it's a top level windo... | { return true; } | identifier_body | |
nn_test.py | def testSoftplusGradNan(self):
check_grads(nn.softplus, (float('nan'),), order=1,
rtol=1e-2 if jtu.device_under_test() == "tpu" else None)
@parameterized.parameters([int, float] + jtu.dtypes.floating + jtu.dtypes.integer)
def testSoftplusZero(self, dtype):
self.assertEqual(jnp.log(dtype(2... | 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 | =True),
nn.relu, nn.softplus, nn.sigmoid)))
def testDtypeMatchesInput(self, dtype, fn):
x = jnp.zeros((), dtype=dtype)
out = fn(x)
self.assertEqual(out.dtype, dtype)
def testEluMemory(self):
# see https://github.com/google/jax/pull/1640
with jax.enable_checks(False): # With checks we ma... | absltest.main(testLoader=jtu.JaxTestLoader()) | conditional_block | |
nn_test.py | e4, check_dtypes=False)
def testGluValue(self):
val = nn.glu(jnp.array([1.0, 0.0]))
self.assertAllClose(val, jnp.array([0.5]))
@parameterized.parameters(False, True)
def testGelu(self, approximate):
def gelu_reference(x):
return x * scipy.stats.norm.cdf(x)
rng = jtu.rand_default(self.rng()... | testVarianceScalingMultiAxis | identifier_name | |
nn_test.py | 2 if jtu.device_under_test() == "tpu" else None)
def testSoftplusGradZero(self):
check_grads(nn.softplus, (0.,), order=1,
rtol=1e-2 if jtu.device_under_test() == "tpu" else None)
def testSoftplusGradInf(self):
self.assertAllClose(
1., jax.grad(nn.softplus)(float('inf')))
def tes... |
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 | import {Platform} from '@angular/cdk/platform';
import {
BasePortalOutlet,
CdkPortalOutlet,
ComponentPortal,
TemplatePortal,
DomPortal,
} from '@angular/cdk/portal';
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ComponentRef,
ElementRef,
EmbeddedViewRef,
NgZone,
OnDestroy,
... |
/** 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 | import {Platform} from '@angular/cdk/platform';
import {
BasePortalOutlet,
CdkPortalOutlet,
ComponentPortal,
TemplatePortal,
DomPortal,
} from '@angular/cdk/portal';
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ComponentRef,
ElementRef,
EmbeddedViewRef,
NgZone,
OnDestroy,
... |
}
}
/** 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 | ';
import {Platform} from '@angular/cdk/platform';
import {
BasePortalOutlet,
CdkPortalOutlet,
ComponentPortal,
TemplatePortal,
DomPortal,
} from '@angular/cdk/portal';
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ComponentRef,
ElementRef,
EmbeddedViewRef,
NgZone,
OnDestroy,... | 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 | ';
import {Platform} from '@angular/cdk/platform';
import {
BasePortalOutlet,
CdkPortalOutlet,
ComponentPortal,
TemplatePortal,
DomPortal,
} from '@angular/cdk/portal';
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ComponentRef,
ElementRef,
EmbeddedViewRef,
NgZone,
OnDestroy,... | (): 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 | , NavigateToAttribute
from wrapanapi.containers.image import Image as ApiImage
from cfme.common import (WidgetasticTaggable, PolicyProfileAssignable,
TagPageView)
from cfme.containers.provider import (Labelable,
ContainerObjectAllBaseView,
... | """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 | , NavigateToAttribute
from wrapanapi.containers.image import Image as ApiImage
from cfme.common import (WidgetasticTaggable, PolicyProfileAssignable,
TagPageView)
from cfme.containers.provider import (Labelable,
ContainerObjectAllBaseView,
... |
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 | NavigateToAttribute
from wrapanapi.containers.image import Image as ApiImage
from cfme.common import (WidgetasticTaggable, PolicyProfileAssignable,
TagPageView)
from cfme.containers.provider import (Labelable,
ContainerObjectAllBaseView,
... |
@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 | NavigateToAttribute
from wrapanapi.containers.image import Image as ApiImage
from cfme.common import (WidgetasticTaggable, PolicyProfileAssignable,
TagPageView)
from cfme.containers.provider import (Labelable,
ContainerObjectAllBaseView,
... | (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 | start', 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 type = e.dataTransfer.getData('text')
data.addNode(type, e.offsetX,... |
function mouseup() {
if (drawLineEnable && drawLineFrom) {
drag_line.classed('hidden', true)
drawLineFrom = null
} else {
clearAllEditStyle()
}
simulation.alphaTarget(0)
}
| drag_line.attr('d', `M${drawLineFrom.x},${drawLineFrom.y}L${centerX},${centerY}L${p[0]},${p[1]}`)
}
} | random_line_split |
index.ts | start', 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 type = e.dataTransfer.getData('text')
data.addNode(type, e.offsetX,... | 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 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 type = e.dataTransfer.getData('text')
data.addNode(type, e.offsetX, e.offsetY)
in... | 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 notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NO... | 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 | notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEM... | `Full Decoder State: ${inspect(decoder)}`;
assert.fail(output, expected, message);
}
});
}
// unicode
Escape prints the str contents as unicode escape codes.
function unicodeEscape(str) {
let r = '';
for (let i = 0; i < str.length | 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 | // Test default encoding
let decoder = new StringDecoder();
assert.strictEqual(decoder.encoding, 'utf8');
// Should work without 'new' keyword
const decoder2 = {};
StringDecoder.call(decoder2);
assert.strictEqual(decoder2.encoding, 'utf8');
// UTF-8
test('utf-8', Buffer.from('$', 'utf-8'), '$');
test('utf-8', Buffer.... | es(length, sta | identifier_name | |
test-string-decoder.js | notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEM... | 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 | GPL 2.1+/MPL 1.1 tri-license. See COPYING.GPL, COPYING.LGPL and
# COPYING.MPL for more details.
#
# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License... | (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 | GPL 2.1+/MPL 1.1 tri-license. See COPYING.GPL, COPYING.LGPL and
# COPYING.MPL for more details.
#
# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License... |
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 | GPL 2.1+/MPL 1.1 tri-license. See COPYING.GPL, COPYING.LGPL and
# COPYING.MPL for more details.
#
# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License... | 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 | GPL 2.1+/MPL 1.1 tri-license. See COPYING.GPL, COPYING.LGPL and
# COPYING.MPL for more details.
#
# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License... |
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 |
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 ] *... | # Print results
print( "Z =", z )
return
# Run main if this module is being run directly
if __name__ == '__main__':
main() | # Computer partition function
z = computePartitionFunction( factors )
| random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.