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 |
|---|---|---|---|---|
TestController.py | #!/usr/bin/env python
# **********************************************************************
#
# Copyright (c) 2003-2015 ZeroC, Inc. All rights reserved.
#
# This copy of Ice is licensed to you under the terms described in the
# ICE_LICENSE file included in this distribution.
#
# *************************************... |
while(True):
c = p.stdout.read(1)
if not c: break
if c == '\r': continue
# Depending on Python version and platform, the value c could be a
# string or a bytes object.
if type(c) != str:
c = c.decode()
sys.stdout.write(c)
sys.stdout.flush() | print("run " + sys.argv[0] + " --clean to remove the trust setting") | random_line_split |
TestController.py | #!/usr/bin/env python
# **********************************************************************
#
# Copyright (c) 2003-2015 ZeroC, Inc. All rights reserved.
#
# This copy of Ice is licensed to you under the terms described in the
# ICE_LICENSE file included in this distribution.
#
# *************************************... |
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
if TestUtil.isDarwin():
#
# On OS X, we set the trust settings on the certificate to prevent
# the Web browsers from prompting the user about the unstrusted
# certificate. Some browsers such as Chrome don't prov... | if p:
p.terminate()
sys.exit(0) | identifier_body |
TestController.py | #!/usr/bin/env python
# **********************************************************************
#
# Copyright (c) 2003-2015 ZeroC, Inc. All rights reserved.
#
# This copy of Ice is licensed to you under the terms described in the
# ICE_LICENSE file included in this distribution.
#
# *************************************... | (signal, frame):
if p:
p.terminate()
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
if TestUtil.isDarwin():
#
# On OS X, we set the trust settings on the certificate to prevent
# the Web browsers from prompting the user about the unstr... | signal_handler | identifier_name |
TestController.py | #!/usr/bin/env python
# **********************************************************************
#
# Copyright (c) 2003-2015 ZeroC, Inc. All rights reserved.
#
# This copy of Ice is licensed to you under the terms described in the
# ICE_LICENSE file included in this distribution.
#
# *************************************... |
p = subprocess.Popen(command, shell = False, stdin = subprocess.PIPE, stdout = subprocess.PIPE,
stderr = subprocess.STDOUT, bufsize = 0)
def signal_handler(signal, frame):
if p:
p.terminate()
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, s... | command += sys.argv[1:] | conditional_block |
classif_and_ktst.py | _two_sample_test import MMD2u, compute_null_distribution
from kernel_two_sample_test import compute_null_distribution_given_permutations
import matplotlib.pylab as plt
from joblib import Parallel, delayed
def compute_rbf_kernel_matrix(X):
"""Compute the RBF kernel matrix with sigma2 as the median pairwise
dis... |
p_value = max(1.0/iterations, (mmd2u_null > mmd2u).sum()
/ float(iterations))
if verbose:
print("p-value ~= %s \t (resolution : %s)" % (p_value, 1.0/iterations))
return mmd2u, mmd2u_null, p_value
def plot_null_distribution(stats, stats_null, p_value, data_name='',
... | mmd2u_null = compute_null_distribution(K, m, n, iterations,
verbose=verbose) | conditional_block |
classif_and_ktst.py | _two_sample_test import MMD2u, compute_null_distribution
from kernel_two_sample_test import compute_null_distribution_given_permutations
import matplotlib.pylab as plt
from joblib import Parallel, delayed
def compute_rbf_kernel_matrix(X):
"""Compute the RBF kernel matrix with sigma2 as the median pairwise
dis... |
def compute_svm_cv(K, y, C=100.0, n_folds=5,
scoring=balanced_accuracy_scoring):
"""Compute cross-validated score of SVM with given precomputed kernel.
"""
cv = StratifiedKFold(y, n_folds=n_folds)
clf = SVC(C=C, kernel='precomputed', class_weight='auto')
scores = cross_val_scor... | """Scoring function that computes the balanced accuracy to be used
internally in the cross-validation procedure.
"""
y_pred = clf.predict(X)
conf_mat = confusion_matrix(y, y_pred)
bal_acc = 0.
for i in range(len(conf_mat)):
bal_acc += (float(conf_mat[i, i])) / np.sum(conf_mat[i])
ba... | identifier_body |
classif_and_ktst.py | _two_sample_test import MMD2u, compute_null_distribution
from kernel_two_sample_test import compute_null_distribution_given_permutations
import matplotlib.pylab as plt
from joblib import Parallel, delayed
def compute_rbf_kernel_matrix(X):
"""Compute the RBF kernel matrix with sigma2 as the median pairwise
dis... | (K, y, n_folds,
scoring=balanced_accuracy_scoring,
random_state=None,
param_grid=[{'C': np.logspace(-5, 5, 25)}]):
"""Compute cross-validated score of SVM using precomputed kernel.
"""
cv = StratifiedKFold(y, n_fold... | compute_svm_score_nestedCV | identifier_name |
classif_and_ktst.py | _two_sample_test import MMD2u, compute_null_distribution
from kernel_two_sample_test import compute_null_distribution_given_permutations
import matplotlib.pylab as plt
from joblib import Parallel, delayed
def compute_rbf_kernel_matrix(X):
"""Compute the RBF kernel matrix with sigma2 as the median pairwise
dis... | random_state=None):
"""
Compute the balanced accuracy, its null distribution and the p-value.
Parameters:
----------
K: array-like
Kernel matrix
y: array_like
class labels
cv: Number of folds in the stratified cross-validation
verbose: bool
Verbosit... |
return scores.mean()
def apply_svm(K, y, n_folds=5, iterations=10000, subjects=False, verbose=True, | random_line_split |
git.rs | use std::collections::HashMap;
use std::env;
use crate::config;
use crate::errors::*;
use crate::ConfigScope;
pub struct Repo {
repo: git2::Repository,
}
impl Repo {
pub fn new() -> Result<Self> {
let repo = env::current_dir()
.chain_err(|| "")
.and_then(|current_dir| git2::Re... | fn include_paths(&self) -> Result<Vec<String>> {
let config = self.local_config()?;
let include_paths: Vec<String> = config
.entries(Some("include.path"))
.chain_err(|| "")?
.into_iter()
.map(|entry| {
entry
.chain_e... | .and(Ok(()))
.chain_err(|| "")
}
| random_line_split |
git.rs | use std::collections::HashMap;
use std::env;
use crate::config;
use crate::errors::*;
use crate::ConfigScope;
pub struct Repo {
repo: git2::Repository,
}
impl Repo {
pub fn new() -> Result<Self> {
let repo = env::current_dir()
.chain_err(|| "")
.and_then(|current_dir| git2::Re... | (&mut self, name: &str, value: &str) -> Result<()> {
self.config
.set_multivar(name, "^$", value)
.chain_err(|| format!("error adding git config '{}': '{}'", name, value))
}
fn set(&mut self, name: &str, value: &str) -> Result<()> {
self.config
.set_str(name,... | add | identifier_name |
git.rs | use std::collections::HashMap;
use std::env;
use crate::config;
use crate::errors::*;
use crate::ConfigScope;
pub struct Repo {
repo: git2::Repository,
}
impl Repo {
pub fn new() -> Result<Self> {
let repo = env::current_dir()
.chain_err(|| "")
.and_then(|current_dir| git2::Re... |
let include_paths = self.include_paths()?;
if include_paths.contains(&include_path) {
return Ok(());
}
let mut config = self.local_config()?;
config
.set_multivar("include.path", "^$", &include_path)
.and(Ok(()))
.chain_err(|| ""... | {
return Ok(());
} | conditional_block |
git.rs | use std::collections::HashMap;
use std::env;
use crate::config;
use crate::errors::*;
use crate::ConfigScope;
pub struct Repo {
repo: git2::Repository,
}
impl Repo {
pub fn new() -> Result<Self> {
let repo = env::current_dir()
.chain_err(|| "")
.and_then(|current_dir| git2::Re... |
fn add(&mut self, name: &str, value: &str) -> Result<()> {
self.config
.set_multivar(name, "^$", value)
.chain_err(|| format!("error adding git config '{}': '{}'", name, value))
}
fn set(&mut self, name: &str, value: &str) -> Result<()> {
self.config
.s... | {
let mut result = HashMap::new();
let entries = self
.config
.entries(Some(glob))
.chain_err(|| "error getting git config entries")?;
for entry in &entries {
let entry = entry.chain_err(|| "error getting git config entry")?;
if let (So... | identifier_body |
home_languages_persian.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This file is part of XBMC Mega Pack Addon.
Copyright (C) 2014 Wolverine (xbmcmegapack@gmail.com)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Softwar... |
You should have received a copy of the GNU General Public License along
with this program. If not, see http://www.gnu.org/licenses/gpl-3.0.html
"""
class Languages_Persian():
'''Class that manages this specific menu context.'''
def open(self, plugin, menu):
menu.add_xplugins(plugin.get_xplu... | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. | random_line_split |
home_languages_persian.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This file is part of XBMC Mega Pack Addon.
Copyright (C) 2014 Wolverine (xbmcmegapack@gmail.com)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Softwar... | :
'''Class that manages this specific menu context.'''
def open(self, plugin, menu):
menu.add_xplugins(plugin.get_xplugins(dictionaries=["Channels",
"Events", "Live", "Movies", "Sports", "TVShows"],
languages=["Persian"])) | nguages_Persian() | identifier_name |
home_languages_persian.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This file is part of XBMC Mega Pack Addon.
Copyright (C) 2014 Wolverine (xbmcmegapack@gmail.com)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Softwar... | nu.add_xplugins(plugin.get_xplugins(dictionaries=["Channels",
"Events", "Live", "Movies", "Sports", "TVShows"],
languages=["Persian"])) | identifier_body | |
sermons_to_dynalist.py | #!/usr/bin/env python3
#
################################################################################
# Important note:
# Because of the highly individual nature of the ODT files to be processed, each
# user will have to adjust this script according to their needs. It will fail
# out of the box unless you happen to... |
def main():
args = parse_args()
if args.infile:
if not os.path.isfile(args.infile):
exit('ERROR: Input file doesn\'t exist: {}'.format(args.infile))
with open(args.infile) as f:
infile = f.read()
else:
with open(sys.stdin) as f:
infile = f.read()
... | add('-f', '--force', action='store_true', default=False, help=force)
add('-t', '--type', default='text', help=type_)
return parser.parse_args() | random_line_split |
sermons_to_dynalist.py | #!/usr/bin/env python3
#
################################################################################
# Important note:
# Because of the highly individual nature of the ODT files to be processed, each
# user will have to adjust this script according to their needs. It will fail
# out of the box unless you happen to... | elif args.type == 'html':
if html_mode_available:
soup = BeautifulSoup(infile, 'html.parser')
output = format_html(soup)
else:
exit("ERROR: Please install Beautiful Soup 4 (Ubuntu package python-bs4) to use HTML mode.")
else:
exit("ERROR: Invalid input... | = parse_args()
if args.infile:
if not os.path.isfile(args.infile):
exit('ERROR: Input file doesn\'t exist: {}'.format(args.infile))
with open(args.infile) as f:
infile = f.read()
else:
with open(sys.stdin) as f:
infile = f.read()
if args.outfile an... | identifier_body |
sermons_to_dynalist.py | #!/usr/bin/env python3
#
################################################################################
# Important note:
# Because of the highly individual nature of the ODT files to be processed, each
# user will have to adjust this script according to their needs. It will fail
# out of the box unless you happen to... | o = [''.join(accumulator)]
for f in footnotes:
o.append('\n' + '\t' * item_level + f)
return ''.join(o)
for outer_list in soup.contents:
if outer_list.name != 'div' or outer_list.attrs.get('type') not in html_types:
continue
iterate_children(outer_lis... | = item.replace('<i>', '__')
item = item.replace('</i>', '__')
item = item.replace('<b>', '**')
item = item.replace('</b>', '**')
item = re.sub(r'<[^>]{2,100}>', '', item)
accumulator.append(item)
| conditional_block |
sermons_to_dynalist.py | #!/usr/bin/env python3
#
################################################################################
# Important note:
# Because of the highly individual nature of the ODT files to be processed, each
# user will have to adjust this script according to their needs. It will fail
# out of the box unless you happen to... | args = parse_args()
if args.infile:
if not os.path.isfile(args.infile):
exit('ERROR: Input file doesn\'t exist: {}'.format(args.infile))
with open(args.infile) as f:
infile = f.read()
else:
with open(sys.stdin) as f:
infile = f.read()
if args.ou... | ):
| identifier_name |
tutorial_quanconv_cifar10.py | : 8 bits here, you can change the setting),
after 705 epoches' training with GPU, test accurcy of 84.0% was found.
- 2. For simplified CNN layers see "Convolutional layer (Simplified)"
in read the docs website.
- 3. Data augmentation without TFRecord see `tutorial_image_preprocess.py` !!
Links
-------
.. paper:https... | (network, X_batch, y_batch, cost, train_op=tf.optimizers.Adam(learning_rate=0.0001), acc=None):
with tf.GradientTape() as tape:
y_pred = network(X_batch)
_loss = cost(y_pred, y_batch)
grad = tape.gradient(_loss, network.trainable_weights)
train_op.apply_gradients(zip(grad, network.trainable_... | _train_step | identifier_name |
tutorial_quanconv_cifar10.py | : 8 bits here, you can change the setting),
after 705 epoches' training with GPU, test accurcy of 84.0% was found.
- 2. For simplified CNN layers see "Convolutional layer (Simplified)"
in read the docs website.
- 3. Data augmentation without TFRecord see `tutorial_image_preprocess.py` !!
Links
-------
.. paper:https... |
for _input, _target in zip(inputs, targets):
# yield _input.encode('utf-8'), _target.encode('utf-8')
yield _input, _target
def _map_fn_train(img, target):
# 1. Randomly crop a [height, width] section of the image.
img = tf.image.random_crop(img, [24, 24, 3])
# 2. Randomly flip the ima... | raise AssertionError("The length of inputs and targets should be equal") | conditional_block |
tutorial_quanconv_cifar10.py | : 8 bits here, you can change the setting),
after 705 epoches' training with GPU, test accurcy of 84.0% was found.
- 2. For simplified CNN layers see "Convolutional layer (Simplified)"
in read the docs website.
- 3. Data augmentation without TFRecord see `tutorial_image_preprocess.py` !!
Links
-------
.. paper:https... |
def _map_fn_train(img, target):
# 1. Randomly crop a [height, width] section of the image.
img = tf.image.random_crop(img, [24, 24, 3])
# 2. Randomly flip the image horizontally.
img = tf.image.random_flip_left_right(img)
# 3. Randomly change brightness.
img = tf.image.random_brightness(img, ... | inputs = X_test
targets = y_test
if len(inputs) != len(targets):
raise AssertionError("The length of inputs and targets should be equal")
for _input, _target in zip(inputs, targets):
# yield _input.encode('utf-8'), _target.encode('utf-8')
yield _input, _target | identifier_body |
tutorial_quanconv_cifar10.py | active: 8 bits here, you can change the setting),
after 705 epoches' training with GPU, test accurcy of 84.0% was found.
- 2. For simplified CNN layers see "Convolutional layer (Simplified)"
in read the docs website.
- 3. Data augmentation without TFRecord see `tutorial_image_preprocess.py` !!
Links
-------
.. pape... | X_train, y_train, X_test, y_test = tl.files.load_cifar10_dataset(shape=(-1, 32, 32, 3), plotable=False)
def model(input_shape, n_classes, bitW, bitA):
in_net = Input(shape=input_shape, name='input')
net = QuanConv2dWithBN(64, (5, 5), (1, 1), act='relu', padding='SAME', bitW=bitW, bitA=bitA, name='qcnnbn1')(in... | # Download data, and convert to TFRecord format, see ```tutorial_tfrecord.py```
# prepare cifar10 data | random_line_split |
poloniexFactories.ts | /***************************************************************************************************************************
* @license *
* Copyright 2017 Coinbase, Inc. ... | (logger: Logger, products: string[], auth?: ExchangeAuthConfig): Promise<PoloniexFeed> {
// auth = auth || {
// key: process.env.POLONIEX_KEY,
// secret: process.env.POLONIEX_SECRET,
// };
auth = null; // Polo doesn't provide auth feeds yet
return getSubscribedFeeds({ auth: a... | FeedFactory | identifier_name |
poloniexFactories.ts | /***************************************************************************************************************************
* @license *
* Copyright 2017 Coinbase, Inc. ... |
function subscribeToAll(products: string[], feed: PoloniexFeed, info: PoloniexProducts) {
products.forEach((product: string) => {
const id: number = getChannelId(product, info);
if (id > 0) {
feed.subscribe(id);
}
});
}
function getChannelId(product: string, info: Poloniex... | {
return getAllProductInfo(false, options.logger).then((info: PoloniexProducts) => {
const config: PoloniexFeedConfig = {
wsUrl: options.wsUrl || POLONIEX_WS_FEED,
auth: options.auth,
logger: options.logger,
tickerChannel: !!options.tickerChannel
};
... | identifier_body |
poloniexFactories.ts | /***************************************************************************************************************************
* @license *
* Copyright 2017 Coinbase, Inc. ... |
/**
* A convenience function that returns a GDAXExchangeAPI instance for accessing REST methods conveniently. If API
* key details are found in the GDAX_KEY etc. envars, they will be used
*/
export function DefaultAPI(logger: Logger): CCXTExchangeWrapper {
if (!publicAPIInstance) {
publicAPIInstance = C... | let publicAPIInstance: CCXTExchangeWrapper; | random_line_split |
poloniexFactories.ts | /***************************************************************************************************************************
* @license *
* Copyright 2017 Coinbase, Inc. ... |
return Promise.resolve(feed);
});
}
function subscribeToAll(products: string[], feed: PoloniexFeed, info: PoloniexProducts) {
products.forEach((product: string) => {
const id: number = getChannelId(product, info);
if (id > 0) {
feed.subscribe(id);
}
});
}
funct... | {
subscribeToAll(products, feed, info);
} | conditional_block |
controller.py | # Copyright 2011 Tsutomu Uchino
#
# 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 ... |
def suspend(self, Suspend):
return True
def getViewData(self):
""" Returns current instance inspected. """
return self.ui.main.current.target
def restoreViewData(self, Data):
pass
def getModel(self):
return self.model
def getFrame(self):
ret... | self.model = model | identifier_body |
controller.py | # Copyright 2011 Tsutomu Uchino
#
# 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 ... | (self, name):
return name == self.IMPLE_NAME
def getSupportedServiceNames(self):
return self.IMPLE_NAME,
| supportsService | identifier_name |
controller.py | # Copyright 2011 Tsutomu Uchino
#
# 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 ... | class MRIUIController(unohelper.Base,
XController, XTitle, XDispatchProvider,
XStatusIndicatorSupplier, XServiceInfo):
""" Provides controller which connects between frame and model. """
IMPLE_NAME = "mytools.mri.UIController"
def __init__(self,frame, model):
self.frame = frame
... | from com.sun.star.lang import XServiceInfo
from com.sun.star.task import XStatusIndicatorSupplier
| random_line_split |
boolean_mask.ts | /**
* @license
* Copyright 2018 Google Inc. 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 a... | (
tensor: Tensor|TensorLike, mask: Tensor|TensorLike,
axis?: number): Promise<Tensor> {
const $tensor = convertToTensor(tensor, 'tensor', 'boolMask');
const $mask = convertToTensor(mask, 'mask', 'boolMask', 'bool');
const axisFrom = axis == null ? 0 : axis;
const maskDim = $mask.rank;
const tensorSha... | booleanMaskAsync_ | identifier_name |
boolean_mask.ts | /**
* @license
* Copyright 2018 Google Inc. 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 a... |
if (mask !== $mask) {
$mask.dispose();
}
indices.dispose();
reshapedTensor.dispose();
reshapedMask.dispose();
positivePositions.dispose();
return res;
}
export const booleanMaskAsync = booleanMaskAsync_;
| {
$tensor.dispose();
} | conditional_block |
boolean_mask.ts | /**
* @license
* Copyright 2018 Google Inc. 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 a... | `mask's shape must match the first K dimensions of tensor's shape,`);
let leadingSize = 1;
for (let i = axisFrom; i < axisFrom + maskDim; i++) {
leadingSize *= tensorShape[i];
}
const targetTensorShape =
tensorShape.slice(0, axisFrom)
.concat([leadingSize], tensorShape.slice(axisFrom ... | util.assertShapesMatch(
tensorShape.slice(axisFrom, axisFrom + maskDim), $mask.shape, | random_line_split |
boolean_mask.ts | /**
* @license
* Copyright 2018 Google Inc. 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 a... | const reshapedTensor = $tensor.reshape(targetTensorShape);
const reshapedMask = $mask.reshape([-1]);
const positivePositions = await whereAsync(reshapedMask);
const indices = positivePositions.squeeze([1]);
const res = gather(reshapedTensor, indices, axisFrom);
// Ensure no memory leak.
if (tensor !== $... | {
const $tensor = convertToTensor(tensor, 'tensor', 'boolMask');
const $mask = convertToTensor(mask, 'mask', 'boolMask', 'bool');
const axisFrom = axis == null ? 0 : axis;
const maskDim = $mask.rank;
const tensorShape = $tensor.shape;
util.assert(maskDim > 0, () => 'mask cannot be scalar');
util.assertS... | identifier_body |
dashboard.module.ts |
import { GooglechartComponent } from './googlechart/googlechart.component';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { AppTranslationModule } from '../../app.translation.module';
import { NgaModule } from '../../theme... | {}
| DashboardModule | identifier_name |
dashboard.module.ts | import { GooglechartComponent } from './googlechart/googlechart.component';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { AppTranslationModule } from '../../app.translation.module';
import { NgaModule } from '../../theme/... | CommonModule,
FormsModule,
AppTranslationModule,
NgaModule,
routing,
],
declarations: [
PopularApp,
PieChart,
TrafficChart,
UsersMap,
LineChart,
Feed,
Todo,
Calendar,
Dashboard,
GooglechartComponent,
GaugechartComponent,
TabelaCidadesComponent,
]... | import { SimpleTimer } from 'ng2-simple-timer';
@NgModule({
imports: [ | random_line_split |
partialeq_ne_impl.rs | use clippy_utils::diagnostics::span_lint_hir;
use clippy_utils::is_automatically_derived;
use if_chain::if_chain;
use rustc_hir::{Impl, Item, ItemKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::sym;
declare_clippy_lint! {
/// ### What i... |
declare_lint_pass!(PartialEqNeImpl => [PARTIALEQ_NE_IMPL]);
impl<'tcx> LateLintPass<'tcx> for PartialEqNeImpl {
fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
if_chain! {
if let ItemKind::Impl(Impl { of_trait: Some(ref trait_ref), items: impl_items, .. }) = item.kind;... | /// ```
pub PARTIALEQ_NE_IMPL,
complexity,
"re-implementing `PartialEq::ne`"
} | random_line_split |
partialeq_ne_impl.rs | use clippy_utils::diagnostics::span_lint_hir;
use clippy_utils::is_automatically_derived;
use if_chain::if_chain;
use rustc_hir::{Impl, Item, ItemKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::sym;
declare_clippy_lint! {
/// ### What i... | };
}
}
| {
if_chain! {
if let ItemKind::Impl(Impl { of_trait: Some(ref trait_ref), items: impl_items, .. }) = item.kind;
let attrs = cx.tcx.hir().attrs(item.hir_id());
if !is_automatically_derived(attrs);
if let Some(eq_trait) = cx.tcx.lang_items().eq_trait();
... | identifier_body |
partialeq_ne_impl.rs | use clippy_utils::diagnostics::span_lint_hir;
use clippy_utils::is_automatically_derived;
use if_chain::if_chain;
use rustc_hir::{Impl, Item, ItemKind};
use rustc_lint::{LateContext, LateLintPass};
use rustc_session::{declare_lint_pass, declare_tool_lint};
use rustc_span::sym;
declare_clippy_lint! {
/// ### What i... | (&mut self, cx: &LateContext<'tcx>, item: &'tcx Item<'_>) {
if_chain! {
if let ItemKind::Impl(Impl { of_trait: Some(ref trait_ref), items: impl_items, .. }) = item.kind;
let attrs = cx.tcx.hir().attrs(item.hir_id());
if !is_automatically_derived(attrs);
if let Som... | check_item | identifier_name |
lib.rs | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! This crate prov... | // file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
// | random_line_split | |
ex6_2.py | ST.CLIGHT * Ne * Rstr**2)
def QH0_def(Rstr, Ne, ff, Te = 1e4):
"""
Volume of
"""
return 4. / 3. * np.pi * Rstr**3 * Ne**2 * ff * alpha_B(Te)
def Rstr(QH0, Ne, ff, Te = 1e4):
return (3. * QH0 / (4. * np.pi * ff * alpha_B(Te) * Ne**2))**(1./3.)
def U_mean(QH0, Ne, ff, Te = 1e4):
ret... | (name, models_dir = './', style='-', fig_num = 1):
pc.log_.level=3
M = pc.CloudyModel('{0}/{1}'.format(models_dir, name), read_emis = False)
X = M.radius/1e19
colors = ['r', 'g', 'b', 'y', 'm', 'c']
plt.figure(fig_num)
plt.subplot(3, 3, 1)
plt.plot(X, M.get_ionic('H', 0), label='H0', l... | plot_model | identifier_name |
ex6_2.py | ST.CLIGHT * Ne * Rstr**2)
def QH0_def(Rstr, Ne, ff, Te = 1e4):
"""
Volume of
"""
return 4. / 3. * np.pi * Rstr**3 * Ne**2 * ff * alpha_B(Te)
def Rstr(QH0, Ne, ff, Te = 1e4):
return (3. * QH0 / (4. * np.pi * ff * alpha_B(Te) * Ne**2))**(1./3.)
def U_mean(QH0, Ne, ff, Te = 1e4):
ret... | Ms[1].get_ab_ion_vol('He', 2),
Ms[2].get_ab_ion_vol('He', 2)))
for elem in ['N', 'O', 'Ne', 'S', 'Ar']:
for i in | Ms = pc.load_models('{0}/{1}'.format(models_dir, name), read_emis = False)
names = [M.model_name_s for M in Ms]
print(names)
print('H0/H: {0:.2e} {1:.2e} {2:.2e}'.format(Ms[0].get_ab_ion_vol('H', 0),
Ms[1].get_ab_ion_vol('H', 0),
... | identifier_body |
ex6_2.py | ST.CLIGHT * Ne * Rstr**2)
def QH0_def(Rstr, Ne, ff, Te = 1e4):
"""
Volume of
"""
return 4. / 3. * np.pi * Rstr**3 * Ne**2 * ff * alpha_B(Te)
def Rstr(QH0, Ne, ff, Te = 1e4):
return (3. * QH0 / (4. * np.pi * ff * alpha_B(Te) * Ne**2))**(1./3.)
def U_mean(QH0, Ne, ff, Te = 1e4):
ret... | 'element limit off -8',
)
c_input = pc.CloudyInput('{0}/{1}'.format(models_dir, name))
if SED == 'BB':
c_input.set_BB(Teff = SED_params, lumi_unit = 'q(H)', lumi_value = qH)
else:
c_input.set_star(SED = SED, SED_params = SED_params, lumi_unit = 'q(H)', lumi... | 'COSMIC RAY BACKGROUND', | random_line_split |
ex6_2.py | ST.CLIGHT * Ne * Rstr**2)
def QH0_def(Rstr, Ne, ff, Te = 1e4):
"""
Volume of
"""
return 4. / 3. * np.pi * Rstr**3 * Ne**2 * ff * alpha_B(Te)
def Rstr(QH0, Ne, ff, Te = 1e4):
return (3. * QH0 / (4. * np.pi * ff * alpha_B(Te) * Ne**2))**(1./3.)
def U_mean(QH0, Ne, ff, Te = 1e4):
ret... |
c_input.print_input()
c_input.run_cloudy()
def plot_model(name, models_dir = './', style='-', fig_num = 1):
pc.log_.level=3
M = pc.CloudyModel('{0}/{1}'.format(models_dir, name), read_emis = False)
X = M.radius/1e19
colors = ['r', 'g', 'b', 'y', 'm', 'c']
plt.figure(fig_num)
... | c_input.set_stop('zones {0}'.format(n_zones)) | conditional_block |
installed_packages.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (p: &Path) -> Option<~str> {
let files = {
let _guard = io::ignore_io_error();
fs::readdir(p)
};
for path in files.iter() {
if path.extension_str() == Some(os::consts::DLL_EXTENSION) {
let stuff : &str = path.filestem_str().expect("has_library: weird path");
l... | has_library | identifier_name |
installed_packages.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | let workspaces = rust_path();
for p in workspaces.iter() {
let binfiles = {
let _guard = io::ignore_io_error();
fs::readdir(&p.join("bin"))
};
for exec in binfiles.iter() {
// FIXME (#9639): This needs to handle non-utf8 paths
match exec.fi... |
pub fn list_installed_packages(f: |&CrateId| -> bool) -> bool { | random_line_split |
installed_packages.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
}
let libfiles = {
let _guard = io::ignore_io_error();
fs::readdir(&p.join("lib"))
};
for lib in libfiles.iter() {
debug!("Full name: {}", lib.display());
match has_library(lib) {
Some(basename) => {
... | {
if !f(&CrateId::new(exec_path)) {
return false;
}
} | conditional_block |
installed_packages.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let mut is_installed = false;
list_installed_packages(|installed| {
if installed == p {
is_installed = true;
false
} else {
true
}
});
is_installed
} | identifier_body | |
index.js | /*!
* content-type
* Copyright(c) 2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1
*
* parameter = token "=" ( token / quoted-string )
* token = 1*tchar
* tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
* ... | (string) {
if (!string) {
throw new TypeError('argument string is required')
}
if (typeof string === 'object') {
// support req/res-like objects as argument
string = getcontenttype(string)
if (typeof string !== 'string') {
throw new TypeError('content-type header is missing from object');
... | parse | identifier_name |
index.js | /*!
* content-type
* Copyright(c) 2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1
*
* parameter = token "=" ( token / quoted-string )
* token = 1*tchar
* tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
* ... |
/**
* Quote a string if necessary.
*
* @param {string} val
* @return {string}
* @private
*/
function qstring(val) {
var str = String(val)
// no need to quote tokens
if (tokenRegExp.test(str)) {
return str
}
if (str.length > 0 && !textRegExp.test(str)) {
throw new TypeError('invalid paramete... | {
if (typeof obj.getHeader === 'function') {
// res-like
return obj.getHeader('content-type')
}
if (typeof obj.headers === 'object') {
// req-like
return obj.headers && obj.headers['content-type']
}
} | identifier_body |
index.js | /*!
* content-type
* Copyright(c) 2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1
*
* parameter = token "=" ( token / quoted-string )
* token = 1*tchar
* tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
* ... |
if (typeof string !== 'string') {
throw new TypeError('argument string is required to be a string')
}
var index = string.indexOf(';')
var type = index !== -1
? string.substr(0, index).trim()
: string.trim()
if (!typeRegExp.test(type)) {
throw new TypeError('invalid media type')
}
var ... | {
// support req/res-like objects as argument
string = getcontenttype(string)
if (typeof string !== 'string') {
throw new TypeError('content-type header is missing from object');
}
} | conditional_block |
index.js | /*!
* content-type
* Copyright(c) 2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1
*
* parameter = token "=" ( token / quoted-string )
* token = 1*tchar
* tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
* ... | var qescRegExp = /\\([\u000b\u0020-\u00ff])/g
/**
* RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6
*/
var quoteRegExp = /([\\"])/g
/**
* RegExp to match type in RFC 6838
*
* media-type = type "/" subtype
* type = token
* subtype = token
*/
var typeRegExp = /^[!#$%&'\*\+\-\.\^_`\... | random_line_split | |
mod.rs | mod boss;
mod player;
use Item;
use num::integer::Integer;
pub use self::boss::Boss;
pub use self::player::Player;
pub fn player(weapon: &Item, armor: &Item, rings: Vec<&Item>) -> Player {
Player::new(weapon, armor, rings)
}
pub fn boss(hit_points: u32, damage: u32, armor: u32) -> Boss {
Boss::new(hit_poin... | ;
let (div, rem) = hit_points.div_rem(&effective_damage);
if rem == 0 { div } else { div + 1 }
}
| { 1 } | conditional_block |
mod.rs | mod boss;
mod player;
use Item;
use num::integer::Integer;
pub use self::boss::Boss;
pub use self::player::Player;
pub fn player(weapon: &Item, armor: &Item, rings: Vec<&Item>) -> Player {
Player::new(weapon, armor, rings)
}
pub fn boss(hit_points: u32, damage: u32, armor: u32) -> Boss {
Boss::new(hit_poin... | (damage: u32, hit_points: u32, armor: u32) -> u32 {
let effective_damage = if damage > armor { damage - armor } else { 1 };
let (div, rem) = hit_points.div_rem(&effective_damage);
if rem == 0 { div } else { div + 1 }
}
| turns_to_beat | identifier_name |
mod.rs | mod boss;
mod player;
use Item;
use num::integer::Integer;
pub use self::boss::Boss;
pub use self::player::Player;
pub fn player(weapon: &Item, armor: &Item, rings: Vec<&Item>) -> Player |
pub fn boss(hit_points: u32, damage: u32, armor: u32) -> Boss {
Boss::new(hit_points, damage, armor)
}
pub trait Character {
fn hit_points(&self) -> u32;
fn damage(&self) -> u32;
fn armor(&self) -> u32;
fn beats(&self, other: &Character) -> bool {
let win_after = turns_to_beat(self.damag... | {
Player::new(weapon, armor, rings)
} | identifier_body |
mod.rs | mod boss;
mod player;
use Item;
use num::integer::Integer;
pub use self::boss::Boss;
pub use self::player::Player;
pub fn player(weapon: &Item, armor: &Item, rings: Vec<&Item>) -> Player {
Player::new(weapon, armor, rings)
}
pub fn boss(hit_points: u32, damage: u32, armor: u32) -> Boss {
Boss::new(hit_poin... | fn damage(&self) -> u32;
fn armor(&self) -> u32;
fn beats(&self, other: &Character) -> bool {
let win_after = turns_to_beat(self.damage(), other.hit_points(), other.armor());
let lose_after = turns_to_beat(other.damage(), self.hit_points(), self.armor());
win_after <= lose_after
... | fn hit_points(&self) -> u32; | random_line_split |
delete.js | var accessToken="i7LM4k7JcSKs4ucCpxpgNPcs3i1kRbNKyUE8aPGKZzZWASagz9uZiuLgmgDgBJzY";
$(window).load(function() {
$('#pseudo_submit').click(function() {
NProgress.start();
$.ajax({
type: "POST",
url: "../db-app/signdown.php",
dataType: 'text',
data: ... | (id) {
NProgress.start();
var del_url = "https://api.whenhub.com/api/schedules/"+id+"?access_token="+accessToken;
$.ajax({
type: "DELETE",
url: del_url,
complete: function(xhr, statusText){
NProgress.done();
console.log(xhr.status+" "+statusText);
},... | delete_schedule | identifier_name |
delete.js | var accessToken="i7LM4k7JcSKs4ucCpxpgNPcs3i1kRbNKyUE8aPGKZzZWASagz9uZiuLgmgDgBJzY";
$(window).load(function() {
$('#pseudo_submit').click(function() {
NProgress.start();
$.ajax({
type: "POST",
url: "../db-app/signdown.php",
dataType: 'text',
data: ... | }
});
} | {
NProgress.start();
var del_url = "https://api.whenhub.com/api/schedules/"+id+"?access_token="+accessToken;
$.ajax({
type: "DELETE",
url: del_url,
complete: function(xhr, statusText){
NProgress.done();
console.log(xhr.status+" "+statusText);
},
... | identifier_body |
delete.js | var accessToken="i7LM4k7JcSKs4ucCpxpgNPcs3i1kRbNKyUE8aPGKZzZWASagz9uZiuLgmgDgBJzY";
$(window).load(function() {
$('#pseudo_submit').click(function() {
NProgress.start();
$.ajax({
type: "POST",
url: "../db-app/signdown.php",
dataType: 'text',
data: ... |
$.ajax({
type: "DELETE",
url: del_url,
complete: function(xhr, statusText){
NProgress.done();
console.log(xhr.status+" "+statusText);
},
success: function (data) {
console.log(data);
window.location.href = "account_deleted.php"... | random_line_split | |
delete.js | var accessToken="i7LM4k7JcSKs4ucCpxpgNPcs3i1kRbNKyUE8aPGKZzZWASagz9uZiuLgmgDgBJzY";
$(window).load(function() {
$('#pseudo_submit').click(function() {
NProgress.start();
$.ajax({
type: "POST",
url: "../db-app/signdown.php",
dataType: 'text',
data: ... |
}
});
});
});
function delete_schedule(id) {
NProgress.start();
var del_url = "https://api.whenhub.com/api/schedules/"+id+"?access_token="+accessToken;
$.ajax({
type: "DELETE",
url: del_url,
complete: function(xhr, statusText){
NProgress.done... | {
new PNotify({
title: 'Error :(',
text: "Something went wrong",
type: 'error',
styling: 'bootstrap3'
});
} | conditional_block |
iterable_differs.d.ts | import { ChangeDetectorRef } from '../change_detector_ref';
import { Provider } from 'angular2/src/core/di';
export interface IterableDiffer {
diff(object: Object): any;
onDestroy(): any;
}
/**
* Provides a factory for {@link IterableDiffer}.
*/
export interface IterableDifferFactory {
supports(... | {
factories: IterableDifferFactory[];
constructor(factories: IterableDifferFactory[]);
static create(factories: IterableDifferFactory[], parent?: IterableDiffers): IterableDiffers;
/**
* Takes an array of {@link IterableDifferFactory} and returns a provider used to extend the
* inherite... | IterableDiffers | identifier_name |
iterable_differs.d.ts | import { ChangeDetectorRef } from '../change_detector_ref';
import { Provider } from 'angular2/src/core/di';
export interface IterableDiffer {
diff(object: Object): any;
onDestroy(): any;
}
/**
* Provides a factory for {@link IterableDiffer}.
*/
export interface IterableDifferFactory {
supports(... | constructor(factories: IterableDifferFactory[]);
static create(factories: IterableDifferFactory[], parent?: IterableDiffers): IterableDiffers;
/**
* Takes an array of {@link IterableDifferFactory} and returns a provider used to extend the
* inherited {@link IterableDiffers} instance with the p... | * A repository of different iterable diffing strategies used by NgFor, NgClass, and others.
*/
export declare class IterableDiffers {
factories: IterableDifferFactory[];
| random_line_split |
parallel.rs | // Benchmark from https://github.com/lschmierer/ecs_bench
#![feature(test)]
extern crate test;
use calx_ecs::{build_ecs, Entity};
use serde::{Deserialize, Serialize};
use test::Bencher;
pub const N: usize = 10000;
#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct R {
pub x: f32,
}
#[d... |
#[bench]
fn bench_update(b: &mut Bencher) {
let mut ecs = build();
b.iter(|| {
let es: Vec<Entity> = ecs.r.ent_iter().cloned().collect();
for &e in &es {
let rx = ecs.r[e].x;
ecs.w1.get_mut(e).map(|w1| w1.x = rx);
}
for &e in &es {
let rx =... | { b.iter(build); } | identifier_body |
parallel.rs | // Benchmark from https://github.com/lschmierer/ecs_bench
#![feature(test)]
extern crate test;
use calx_ecs::{build_ecs, Entity};
use serde::{Deserialize, Serialize};
use test::Bencher;
| pub const N: usize = 10000;
#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct R {
pub x: f32,
}
#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct W1 {
pub x: f32,
}
#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct W2 {
pub x: ... | random_line_split | |
parallel.rs | // Benchmark from https://github.com/lschmierer/ecs_bench
#![feature(test)]
extern crate test;
use calx_ecs::{build_ecs, Entity};
use serde::{Deserialize, Serialize};
use test::Bencher;
pub const N: usize = 10000;
#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct R {
pub x: f32,
}
#[d... | (b: &mut Bencher) {
let mut ecs = build();
b.iter(|| {
let es: Vec<Entity> = ecs.r.ent_iter().cloned().collect();
for &e in &es {
let rx = ecs.r[e].x;
ecs.w1.get_mut(e).map(|w1| w1.x = rx);
}
for &e in &es {
let rx = ecs.r[e].x;
e... | bench_update | identifier_name |
mod.rs | #[macro_use]
pub mod macros;
/// Constants like memory locations
pub mod consts;
/// Debugging support
pub mod debug;
/// Devices
pub mod device;
/// Global descriptor table
pub mod gdt;
/// Graphical debug
#[cfg(feature = "graphical_debug")]
mod graphical_debug;
/// Interrupt instructions
#[macro_use]
pub mod in... | pub mod ipi;
/// Paging
pub mod paging;
/// Page table isolation
pub mod pti;
pub mod rmm;
/// Initialization and start function
pub mod start;
/// Stop function
pub mod stop;
pub use ::rmm::X8664Arch as CurrentRmmArch;
// Flags
pub mod flags {
pub const SHIFT_SINGLESTEP: usize = 8;
pub const FLAG_SINGLE... | /// Inter-processor interrupts | random_line_split |
moves-based-on-type-no-recursive-stack-closure.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | let mut x = Some("hello".to_string());
conspirator(|f, writer| {
if writer {
x = None;
} else {
match x {
Some(ref msg) => {
(f.c)(f, true);
//~^ ERROR: cannot borrow `*f` as mutable because
print... | }
fn innocent_looking_victim() { | random_line_split |
moves-based-on-type-no-recursive-stack-closure.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn conspirator(f: |&mut R, bool|) {
let mut r = R {c: f};
f(&mut r, false) //~ ERROR use of moved value
}
fn main() { innocent_looking_victim() }
| {
let mut x = Some("hello".to_string());
conspirator(|f, writer| {
if writer {
x = None;
} else {
match x {
Some(ref msg) => {
(f.c)(f, true);
//~^ ERROR: cannot borrow `*f` as mutable because
pri... | identifier_body |
moves-based-on-type-no-recursive-stack-closure.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
})
}
fn conspirator(f: |&mut R, bool|) {
let mut r = R {c: f};
f(&mut r, false) //~ ERROR use of moved value
}
fn main() { innocent_looking_victim() }
| {
match x {
Some(ref msg) => {
(f.c)(f, true);
//~^ ERROR: cannot borrow `*f` as mutable because
println!("{:?}", msg);
},
None => fail!("oops"),
}
} | conditional_block |
moves-based-on-type-no-recursive-stack-closure.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let mut x = Some("hello".to_string());
conspirator(|f, writer| {
if writer {
x = None;
} else {
match x {
Some(ref msg) => {
(f.c)(f, true);
//~^ ERROR: cannot borrow `*f` as mutable because
... | innocent_looking_victim | identifier_name |
query-generator.js |
return Utils._.template(query)(values).trim() + ';';
},
dropTableQuery: function(tableName, options) {
options = options || {};
var query = 'DROP TABLE IF EXISTS <%= table %><%= cascade %>;';
return Utils._.template(query)({
table: this.quoteTable(tableName),
cascade: options.cascade ... | {
values.attributes += ', PRIMARY KEY (' + pks + ')';
} | conditional_block | |
query-generator.js | .tableName;
}
// This is ARCANE!
var query = 'SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, ' +
'array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) ' +
'AS definition FROM pg_class t,... | var paramDef = [];
if (Utils._.has(curParam, 'type')) {
if (Utils._.has(curParam, 'direction')) { paramDef.push(curParam.direction); }
if (Utils._.has(curParam, 'name')) { paramDef.push(curParam.name); } | random_line_split | |
docs-mixin.js | /*
* docs-mixin: used by any page under /docs path
*/
import { updateMetaTOC, scrollTo, offsetTop } from '~/utils'
import { bvDescription, nav } from '~/content'
const TOC_CACHE = {}
// @vue/component
export default {
head() {
return {
title: this.headTitle,
meta: this.headMeta
}
},
comput... |
return [title, section, 'BootstrapVue'].filter(Boolean).join(' | ')
},
headMeta() {
const section = this.$route.name.split('-')[1]
const sectionMeta = section ? nav.find(n => n.base === `${section}/`) : null
const description =
this.meta && this.meta.description
? this... | {
section = 'Reference'
} | conditional_block |
docs-mixin.js | /*
* docs-mixin: used by any page under /docs path
*/
import { updateMetaTOC, scrollTo, offsetTop } from '~/utils'
import { bvDescription, nav } from '~/content'
const TOC_CACHE = {}
// @vue/component
export default {
head() {
return {
title: this.headTitle,
meta: this.headMeta
}
},
comput... | () {
const hash = this.$route.hash
this.$nextTick(() => {
let el
if (hash) {
// We use an attribute `querySelector()` rather than `getElementByID()`,
// as some auto-generated ID's are invalid or not unique
el = this.$el.querySelector(`[id="${hash.replace('#', '... | focusScroll | identifier_name |
docs-mixin.js | /*
* docs-mixin: used by any page under /docs path
*/
import { updateMetaTOC, scrollTo, offsetTop } from '~/utils'
import { bvDescription, nav } from '~/content'
const TOC_CACHE = {}
// @vue/component
export default {
head() {
return {
title: this.headTitle,
meta: this.headMeta
}
},
comput... | if (description) {
meta.push({
hid: 'description',
name: 'description',
content: description
})
meta.push({
hid: 'og:description',
name: 'og:description',
property: 'og:description',
content: description
})
... | }
] | random_line_split |
docs-mixin.js | /*
* docs-mixin: used by any page under /docs path
*/
import { updateMetaTOC, scrollTo, offsetTop } from '~/utils'
import { bvDescription, nav } from '~/content'
const TOC_CACHE = {}
// @vue/component
export default {
head() {
return {
title: this.headTitle,
meta: this.headMeta
}
},
comput... | ,
updated() {
this.clearScrollTimeout()
this.focusScroll()
},
beforeDestroy() {
this.clearScrollTimeout()
},
methods: {
clearScrollTimeout() {
clearTimeout(this.$_scrollTimeout)
this.$_scrollTimeout = null
},
focusScroll() {
const hash = this.$route.hash
this.$n... | {
this.clearScrollTimeout()
this.focusScroll()
} | identifier_body |
index.js | #!/usr/bin/env node
(function () {
var DirectoryLayout = require('../lib/index.js'),
program = require('commander'),
options;
program
.version('1.0.2')
.usage('[options] <path, ...>')
.option('-g, --generate <path> <output-directory-layout-file-path>', 'Generate directo... | options = {
output: program.args[0] || 'layout.md',
ignore: []
};
console.log('Generating layout for ' + program.generate + '... \n')
DirectoryLayout
.generate(program.generate, options)
.then(function() {
console.log('Lay... | .parse(process.argv);
if(program.generate) { | random_line_split |
bouncy_circles.rs | #![feature (test)]
#![feature (macro_vis_matcher)]
extern crate test;
#[macro_use]
extern crate time_steward;
#[macro_use]
extern crate glium;
extern crate nalgebra;
extern crate rand;
extern crate boolinator;
extern crate docopt;
extern crate serde;
#[macro_use]
extern crate serde_derive;
use test::Bencher;
use... | (bencher: &mut Bencher) {
bencher.iter(|| {
let mut steward: Steward = Steward::from_globals (make_globals());
steward.insert_fiat_event(0, DeterministicRandomId::new(&0), Initialize {}).unwrap();
for index in 1..10 {
steward.insert_fiat_event (index*SECOND, DeterministicRandomId::new (& index), Di... | bouncy_circles_disturbed | identifier_name |
bouncy_circles.rs | #![feature (test)]
#![feature (macro_vis_matcher)]
extern crate test;
#[macro_use]
extern crate time_steward;
#[macro_use]
extern crate glium;
extern crate nalgebra;
extern crate rand;
extern crate boolinator;
extern crate docopt;
extern crate serde;
#[macro_use]
extern crate serde_derive;
use test::Bencher;
use... |
/*
#[bench]
fn bouncy_circles_disturbed_retroactive (bencher: &mut Bencher) {
bencher.iter(|| {
let mut steward: amortized::Steward<Basics> = amortized::Steward::from_constants(());
steward.insert_fiat_event(0, DeterministicRandomId::new(&0), Initialize::new()).unwrap();
steward.snapshot_before(& (10*SEC... | {
bencher.iter(|| {
let mut steward: Steward = Steward::from_globals (make_globals());
steward.insert_fiat_event(0, DeterministicRandomId::new(&0), Initialize {}).unwrap();
for index in 1..10 {
steward.insert_fiat_event (index*SECOND, DeterministicRandomId::new (& index), Disturb{ coordinates: [AREN... | identifier_body |
bouncy_circles.rs | #![feature (test)]
#![feature (macro_vis_matcher)]
extern crate test;
#[macro_use]
extern crate time_steward;
#[macro_use]
extern crate glium;
extern crate nalgebra;
extern crate rand;
extern crate boolinator;
extern crate docopt;
extern crate serde;
#[macro_use]
extern crate serde_derive;
use test::Bencher;
use... | steward.insert_fiat_event(0, DeterministicRandomId::new(&0), Initialize {}).unwrap();
for index in 1..10 {
steward.insert_fiat_event (index*SECOND, DeterministicRandomId::new (& index), Disturb{ coordinates: [ARENA_SIZE/3,ARENA_SIZE/3]}).unwrap();
}
for index in 0..1000 {
let time = 10*SECON... | let mut steward: Steward = Steward::from_globals (make_globals()); | random_line_split |
logging-separate-lines.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... | {
let args = os::args();
let args = args.as_slice();
if args.len() > 1 && args[1].as_slice() == "child" {
debug!("foo");
debug!("bar");
return
}
let p = Command::new(args[0].as_slice())
.arg("child")
.spawn().unwrap().wait_with_output(... | identifier_body | |
logging-separate-lines.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... |
let p = Command::new(args[0].as_slice())
.arg("child")
.spawn().unwrap().wait_with_output().unwrap();
assert!(p.status.success());
let mut lines = str::from_utf8(p.error.as_slice()).unwrap().lines();
assert!(lines.next().unwrap().contains("foo"));
assert!(li... | {
debug!("foo");
debug!("bar");
return
} | conditional_block |
logging-separate-lines.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... | extern crate log;
use std::io::Command;
use std::os;
use std::str;
fn main() {
let args = os::args();
let args = args.as_slice();
if args.len() > 1 && args[1].as_slice() == "child" {
debug!("foo");
debug!("bar");
return
}
let p = Command::new(args[0].as_slice())
... | // ignore-android
// ignore-windows
// exec-env:RUST_LOG=debug
#[macro_use] | random_line_split |
logging-separate-lines.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... | () {
let args = os::args();
let args = args.as_slice();
if args.len() > 1 && args[1].as_slice() == "child" {
debug!("foo");
debug!("bar");
return
}
let p = Command::new(args[0].as_slice())
.arg("child")
.spawn().unwrap().wait_with_outp... | main | identifier_name |
constellation_msg.rs | , Eq, MallocSizeOf, PartialEq, Serialize)]
pub enum Key {
Space,
Apostrophe,
Comma,
Minus,
Period,
Slash,
Num0,
Num1,
Num2,
Num3,
Num4,
Num5,
Num6,
Num7,
Num8,
Num9,
Semicolon,
Equal,
A,
B,
C,
D,
E,
F,
G,
H,
I,
... | Up,
PageUp,
PageDown,
Home,
End,
CapsLock,
ScrollLock,
NumLock,
PrintScreen,
Pause,
F1,
F2,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
F10,
F11,
F12,
F13,
F14,
F15,
F16,
F17,
F18,
F19,
F20,
F21,
F22,
F23... | Down, | random_line_split |
constellation_msg.rs | Eq, MallocSizeOf, PartialEq, Serialize)]
pub enum Key {
Space,
Apostrophe,
Comma,
Minus,
Period,
Slash,
Num0,
Num1,
Num2,
Num3,
Num4,
Num5,
Num6,
Num7,
Num8,
Num9,
Semicolon,
Equal,
A,
B,
C,
D,
E,
F,
G,
H,
I,
... |
}
impl fmt::Display for PipelineId {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
let PipelineNamespaceId(namespace_id) = self.namespace_id;
let PipelineIndex(index) = self.index;
write!(fmt, "({},{})", namespace_id, index.get())
}
}
#[derive(Clone, Copy, Debug, Deserializ... | {
webrender_api::ClipAndScrollInfo::simple(self.root_scroll_node())
} | identifier_body |
constellation_msg.rs | Eq, MallocSizeOf, PartialEq, Serialize)]
pub enum Key {
Space,
Apostrophe,
Comma,
Minus,
Period,
Slash,
Num0,
Num1,
Num2,
Num3,
Num4,
Num5,
Num6,
Num7,
Num8,
Num9,
Semicolon,
Equal,
A,
B,
C,
D,
E,
F,
G,
H,
I,
... | (pipeline: webrender_api::PipelineId) -> PipelineId {
let webrender_api::PipelineId(namespace_id, index) = pipeline;
unsafe {
PipelineId {
namespace_id: PipelineNamespaceId(namespace_id),
index: PipelineIndex(NonZero::new_unchecked(index)),
}
... | from_webrender | identifier_name |
server.rs | extern crate music_server;
extern crate systray;
use music_server::*;
use std::{process, env, thread};
use std::io::{Read, Write};
use std::net::TcpListener;
use std::sync::{Arc, Mutex};
/// Listens on a TcpListener, parses the commands and add them to the queue.
fn start_server(listener: &TcpListener, queue: &Arc<Mu... |
}
},
Err(_) => println!("Error"),
}
}
}
/// Creates a library from /home/$USER/Music, creates a tray icon if the feature is enabled, and
/// starts the server and the event loop.
fn main() {
// Initialize library
let library_path = env::home_dir();
i... | {
let mut queue = queue.lock().unwrap();
queue.push(command.unwrap(), Some(stream));
} | conditional_block |
server.rs | extern crate music_server;
extern crate systray;
use music_server::*;
use std::{process, env, thread};
use std::io::{Read, Write};
use std::net::TcpListener;
use std::sync::{Arc, Mutex};
/// Listens on a TcpListener, parses the commands and add them to the queue.
fn start_server(listener: &TcpListener, queue: &Arc<Mu... |
if let Ok(listener) = listener {
thread::spawn(move || {
start_server(&listener, &queue_for_server);
});
library.borrow_mut().event_loop();
} else {
let _ = writeln!(&mut std::io::stderr(), "Error: could not start server");
process::exit(1);
}
} | // Initialize server
let listener = TcpListener::bind("127.0.0.1:5000"); | random_line_split |
server.rs | extern crate music_server;
extern crate systray;
use music_server::*;
use std::{process, env, thread};
use std::io::{Read, Write};
use std::net::TcpListener;
use std::sync::{Arc, Mutex};
/// Listens on a TcpListener, parses the commands and add them to the queue.
fn start_server(listener: &TcpListener, queue: &Arc<Mu... | let queue_for_tray = Arc::clone(&queue_for_server);
// Initialize tray icon
thread::spawn(move || {
tray::start_tray(&queue_for_tray);
});
// Initialize server
let listener = TcpListener::bind("127.0.0.1:5000");
if let Ok(listener) = listener {
thread::spawn(move || {
... | {
// Initialize library
let library_path = env::home_dir();
if library_path.is_none() {
let _ = writeln!(&mut std::io::stderr(), "Error: cannot read home dir");
process::exit(1);
}
let library_path = library_path.unwrap().join("Music");
let library = Library::new_rc(&library_... | identifier_body |
server.rs | extern crate music_server;
extern crate systray;
use music_server::*;
use std::{process, env, thread};
use std::io::{Read, Write};
use std::net::TcpListener;
use std::sync::{Arc, Mutex};
/// Listens on a TcpListener, parses the commands and add them to the queue.
fn start_server(listener: &TcpListener, queue: &Arc<Mu... | () {
// Initialize library
let library_path = env::home_dir();
if library_path.is_none() {
let _ = writeln!(&mut std::io::stderr(), "Error: cannot read home dir");
process::exit(1);
}
let library_path = library_path.unwrap().join("Music");
let library = Library::new_rc(&libra... | main | identifier_name |
conftest.py | # Calliope
# Copyright (C) 2017, 2018 Sam Thursfield <sam@afuera.me.uk>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later versio... | '''Fixture for testing through the `cpe` commandline interface.'''
return testutils.Cli() | identifier_body | |
conftest.py | # Calliope
# Copyright (C) 2017, 2018 Sam Thursfield <sam@afuera.me.uk>
#
# This program is free software: you can redistribute it and/or modify | # it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANT... | random_line_split | |
conftest.py | # Calliope
# Copyright (C) 2017, 2018 Sam Thursfield <sam@afuera.me.uk>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later versio... | ():
'''Fixture for testing through the `cpe` commandline interface.'''
return testutils.Cli()
| cli | identifier_name |
test_compat.py | """
Test cases adapted from the test_bsddb.py module in Python's
regression test suite.
"""
import sys, os, string
import unittest
import tempfile
from test_all import verbose
try:
# For Python 2.3
from bsddb import db, hashopen, btopen, rnopen
except ImportError:
# For earlier Pythons w/distutils pybsdd... | def test02_hashopen(self):
self.do_bthash_test(hashopen, 'hashopen')
def test03_rnopen(self):
data = string.split("The quick brown fox jumped over the lazy dog.")
if verbose:
print "\nTesting: rnopen"
f = rnopen(self.filename, 'c')
for x in range(len(data)):... |
def test01_btopen(self):
self.do_bthash_test(btopen, 'btopen')
| random_line_split |
test_compat.py | """
Test cases adapted from the test_bsddb.py module in Python's
regression test suite.
"""
import sys, os, string
import unittest
import tempfile
from test_all import verbose
try:
# For Python 2.3
from bsddb import db, hashopen, btopen, rnopen
except ImportError:
# For earlier Pythons w/distutils pybsdd... | (self):
self.filename = tempfile.mktemp()
def tearDown(self):
try:
os.remove(self.filename)
except os.error:
pass
def test01_btopen(self):
self.do_bthash_test(btopen, 'btopen')
def test02_hashopen(self):
self.do_bthash_test(hashopen, 'hasho... | setUp | identifier_name |
test_compat.py | """
Test cases adapted from the test_bsddb.py module in Python's
regression test suite.
"""
import sys, os, string
import unittest
import tempfile
from test_all import verbose
try:
# For Python 2.3
from bsddb import db, hashopen, btopen, rnopen
except ImportError:
# For earlier Pythons w/distutils pybsdd... |
def test03_rnopen(self):
data = string.split("The quick brown fox jumped over the lazy dog.")
if verbose:
print "\nTesting: rnopen"
f = rnopen(self.filename, 'c')
for x in range(len(data)):
f[x+1] = data[x]
getTest = (f[1], f[2], f[3])
if v... | self.do_bthash_test(hashopen, 'hashopen') | identifier_body |
test_compat.py | """
Test cases adapted from the test_bsddb.py module in Python's
regression test suite.
"""
import sys, os, string
import unittest
import tempfile
from test_all import verbose
try:
# For Python 2.3
from bsddb import db, hashopen, btopen, rnopen
except ImportError:
# For earlier Pythons w/distutils pybsdd... |
except db.DBError:
pass
else:
self.fail("Exception expected")
del f
if verbose:
print 'modification...'
f = factory(self.filename, 'w')
f['d'] = 'discovered'
if verbose:
print 'access...'
for key in f.key... | print "truth test: false" | conditional_block |
spot_launcher.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import boto.ec2
from boto.ec2.blockdevicemapping import BlockDeviceType
from boto.ec2.blockdevicemapping import BlockDeviceMapping
import time
import copy
import argparse
import sys
import pprint
import os
import yaml
BASE_PATH = os.path.dirname(os.path.abspath(__file__))... | (config):
if 'mapping' not in config:
return None
mapping = BlockDeviceMapping()
for ephemeral_name, device_path in config['mapping'].iteritems():
ephemeral = BlockDeviceType()
ephemeral.ephemeral_name = ephemeral_name
mapping[device_path] = ephemeral
return mapping
def ... | create_mapping | identifier_name |
spot_launcher.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import boto.ec2
from boto.ec2.blockdevicemapping import BlockDeviceType
from boto.ec2.blockdevicemapping import BlockDeviceMapping
import time
import copy
import argparse
import sys
import pprint
import os
import yaml
BASE_PATH = os.path.dirname(os.path.abspath(__file__))... | launch_from_config(conn, instance_config_name, config_file_name)
if __name__ == '__main__':
main() | instance_config_name = args.instance | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.