file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
bindings.js | // The default deployment object. createDeployment overwrites this.
var deployment = new Deployment({});
// The label used by the QRI to denote connections with public internet.
var publicInternetLabel = "public";
// Overwrite the deployment object with a new one.
function createDeployment(deploymentOpts) {
deplo... | }
// setQuiltIDs deterministically sets the id field of objects based on
// their attributes. The _refID field is required to differentiate between multiple
// references to the same object, and multiple instantiations with the exact
// same attributes.
function setQuiltIDs(objs) {
// The refIDs for each identical... | return JSON.stringify(keyObj); | random_line_split |
bindings.js | // The default deployment object. createDeployment overwrites this.
var deployment = new Deployment({});
// The label used by the QRI to denote connections with public internet.
var publicInternetLabel = "public";
// Overwrite the deployment object with a new one.
function createDeployment(deploymentOpts) {
deplo... |
function LabelRule(exclusive, otherService) {
this.exclusive = exclusive;
this.otherLabel = otherService.name;
}
function MachineRule(exclusive, optionalArgs) {
this.exclusive = exclusive;
if (optionalArgs.provider) {
this.provider = optionalArgs.provider;
}
if (optionalArgs.size) {
... | {
return function() {
// Convert the arguments object into a real array. We can't simply use
// Array.from because it isn't defined in Otto.
var nodes = [];
var i;
for (i = 0 ; i < arguments.length ; i++) {
nodes.push(arguments[i]);
}
return {
... | identifier_body |
bindings.js | // The default deployment object. createDeployment overwrites this.
var deployment = new Deployment({});
// The label used by the QRI to denote connections with public internet.
var publicInternetLabel = "public";
// Overwrite the deployment object with a new one.
function createDeployment(deploymentOpts) {
deplo... |
}
function Connection(ports, to) {
this.minPort = ports.min;
this.maxPort = ports.max;
this.to = to;
}
function Range(min, max) {
this.min = min;
this.max = max;
}
function Port(p) {
return new PortRange(p, p);
}
var PortRange = Range;
| {
this.floatingIp = optionalArgs.floatingIp;
} | conditional_block |
bindings.js | // The default deployment object. createDeployment overwrites this.
var deployment = new Deployment({});
// The label used by the QRI to denote connections with public internet.
var publicInternetLabel = "public";
// Overwrite the deployment object with a new one.
function createDeployment(deploymentOpts) {
deplo... | (ports, to) {
this.minPort = ports.min;
this.maxPort = ports.max;
this.to = to;
}
function Range(min, max) {
this.min = min;
this.max = max;
}
function Port(p) {
return new PortRange(p, p);
}
var PortRange = Range;
| Connection | identifier_name |
test-ae-rbm.py | import os
from rbm import RBM
from au import AutoEncoder
import tensorflow as tf
import input_data
from utilsnn import show_image, min_max_scale
import matplotlib.pyplot as plt
flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_string('data_dir', '/tmp/data/', 'Directory for storing data')
flags.DEFINE_integer('epo... |
print(rbmobject3.compute_cost(rbmobject2.transform(rbmobject1.transform(trX))))
show_image("out/3rbm.jpg", rbmobject3.n_w, (25, 20), (25, 10))
rbmobject3.save_weights('./out/rbmw3.chp')
# Train Third RBM
print('fourth rbm')
for i in range(FLAGS.epochs):
for j in range(iterations):
batch_xs, batch_ys = mnist... | batch_xs, batch_ys = mnist.train.next_batch(FLAGS.batchsize)
batch_xs = rbmobject1.transform(batch_xs)
batch_xs = rbmobject2.transform(batch_xs)
rbmobject3.partial_fit(batch_xs) | conditional_block |
test-ae-rbm.py | import os
from rbm import RBM
from au import AutoEncoder
import tensorflow as tf
import input_data
from utilsnn import show_image, min_max_scale
import matplotlib.pyplot as plt
flags = tf.app.flags
FLAGS = flags.FLAGS
flags.DEFINE_string('data_dir', '/tmp/data/', 'Directory for storing data')
flags.DEFINE_integer('epo... |
# Train Second RBM2
print('second rbm')
for i in range(FLAGS.epochs):
for j in range(iterations):
batch_xs, batch_ys = mnist.train.next_batch(FLAGS.batchsize)
# Transform features with first rbm for second rbm
batch_xs = rbmobject1.transform(batch_xs)
rbmobject2.partial_fit(batch_xs)
print(rbmobjec... | rbmobject1.partial_fit(batch_xs)
print(rbmobject1.compute_cost(trX))
show_image("out/1rbm.jpg", rbmobject1.n_w, (28, 28), (30, 30))
rbmobject1.save_weights('./out/rbmw1.chp') | random_line_split |
run_and_gather_logs.py | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | (unused_args):
test_name = FLAGS.test_name
test_args = FLAGS.test_args
test_results, _ = run_and_gather_logs_lib.run_and_gather_logs(
test_name, test_args)
# Additional bits we receive from bazel
test_results.build_configuration.CopyFrom(gather_build_configuration())
serialized_test_results = text_f... | main | identifier_name |
run_and_gather_logs.py | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | output_path = os.path.abspath(FLAGS.test_log_output)
tf.gfile.GFile(output_path, "w").write(serialized_test_results)
tf.logging.info("Test results written to: %s" % output_path)
if __name__ == "__main__":
tf.app.run() | output_path = os.path.join(tmpdir, FLAGS.test_log_output)
else: | random_line_split |
run_and_gather_logs.py | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
if FLAGS.test_log_output_use_tmpdir:
tmpdir = tf.test.get_temp_dir()
output_path = os.path.join(tmpdir, FLAGS.test_log_output)
else:
output_path = os.path.abspath(FLAGS.test_log_output)
tf.gfile.GFile(output_path, "w").write(serialized_test_results)
tf.logging.info("Test results written to: %s" % ... | print(serialized_test_results)
return | conditional_block |
run_and_gather_logs.py | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
if __name__ == "__main__":
tf.app.run()
| test_name = FLAGS.test_name
test_args = FLAGS.test_args
test_results, _ = run_and_gather_logs_lib.run_and_gather_logs(
test_name, test_args)
# Additional bits we receive from bazel
test_results.build_configuration.CopyFrom(gather_build_configuration())
serialized_test_results = text_format.MessageToSt... | identifier_body |
models.py | import django.db.models as models
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from django.db.models.signals import post_save
class | (models.Model):
"""
parameters we can get from gigya:
birthMonth,isLoggedIn,city,UID,zip,birthYear,state,provider,email,
UIDSig,photoURL,timestamp,loginProviderUID,signature,isSiteUID,proxiedEmail
,thumbnailURL,nickname,firstName,loginProvider,gender,lastName,profileURL
birthDay,country,isS... | Profile | identifier_name |
models.py | import django.db.models as models
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from django.db.models.signals import post_save
class Profile(models.Model):
"""
parameters we can get from gigya:
birthMonth,isLoggedIn,city,UID,zip,birthYear,state,pro... |
profile, created = Profile.objects.get_or_create(user=instance)
post_save.connect(create_profile, sender=User) | return | conditional_block |
models.py | import django.db.models as models | from django.utils.translation import ugettext_lazy as _
from django.db.models.signals import post_save
class Profile(models.Model):
"""
parameters we can get from gigya:
birthMonth,isLoggedIn,city,UID,zip,birthYear,state,provider,email,
UIDSig,photoURL,timestamp,loginProviderUID,signature,isSiteUI... | from django.contrib.auth.models import User | random_line_split |
models.py | import django.db.models as models
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from django.db.models.signals import post_save
class Profile(models.Model):
"""
parameters we can get from gigya:
birthMonth,isLoggedIn,city,UID,zip,birthYear,state,pro... |
post_save.connect(create_profile, sender=User) | if instance is None:
return
profile, created = Profile.objects.get_or_create(user=instance) | identifier_body |
size_of.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use selectors;
use servo_arc::Arc;
use style;
use style::applicable_declarations::ApplicableDeclarationBlock;
use ... | if cfg!(rustc_has_pr45225) { 40 } else { 48 });
size_of_test!(test_size_of_specified_image_layer, specified::image::ImageLayer,
if cfg!(rustc_has_pr45225) { 40 } else { 48 }); | random_line_split | |
form.element.view.hidden.js | /*
* Copyright (c) 2011-2013 Lp digital system
*
* This file is part of BackBee.
*
* BackBee 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 l... |
}
});
},
/**
* Render the template into the DOM with the Renderer
* @returns {String} html
*/
render: function () {
return Renderer.render(this.template, {element: this.element});
}
});
return HiddenView;
}); | {
span.text('');
} | conditional_block |
form.element.view.hidden.js | /*
* Copyright (c) 2011-2013 Lp digital system
*
* This file is part of BackBee.
*
* BackBee 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 l... | *
* You should have received a copy of the GNU General Public License
* along with BackBee. If not, see <http://www.gnu.org/licenses/>.
*/
define(['Core', 'Core/Renderer', 'BackBone'], function (Core, Renderer, Backbone) {
'use strict';
var HiddenView = Backbone.View.extend({
initialize: function... | * BackBee 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 for more details. | random_line_split |
Score.py | # coding: utf-8
import pygame
import os
from color import *
from pygame.locals import *
class Score(pygame.sprite.Sprite):
def __init__(self, score, player, width, height):
super(pygame.sprite.Sprite).__init__(Score)
self.score = int(score)
self.color = None
self.player = player
... | return "<Score de ", str(self.player), "= ", str(self.score) | random_line_split | |
Score.py | # coding: utf-8
import pygame
import os
from color import *
from pygame.locals import *
class Score(pygame.sprite.Sprite):
def __init__(self, score, player, width, height):
super(pygame.sprite.Sprite).__init__(Score)
self.score = int(score)
self.color = None
self.player = player
... |
else:
self.color = lime
self.size = 100
def updateScore(self, score):
self.score = score
def __repr__(self):
return "<Score de ", str(self.player), "= ", str(self.score)
| self.color = blueGreen | conditional_block |
Score.py | # coding: utf-8
import pygame
import os
from color import *
from pygame.locals import *
class Score(pygame.sprite.Sprite):
def __init__(self, score, player, width, height):
super(pygame.sprite.Sprite).__init__(Score)
self.score = int(score)
self.color = None
self.player = player
... | return "<Score de ", str(self.player), "= ", str(self.score) | identifier_body | |
Score.py | # coding: utf-8
import pygame
import os
from color import *
from pygame.locals import *
class Score(pygame.sprite.Sprite):
def | (self, score, player, width, height):
super(pygame.sprite.Sprite).__init__(Score)
self.score = int(score)
self.color = None
self.player = player
self.bossHeight = height
self.bossWidth = width
self.size = 70
self.update()
def update(self):
s... | __init__ | identifier_name |
OrganizationListItem.tsx | import * as React from "react";
import { ListGroupItem } from "react-bootstrap";
import { Organization } from "../State/Organization";
interface IOrganizationListItemProps
{
organization: Organization;
}
export class OrganizationListItem extends React.Component<IOrganizationListItemProps, {}>
{
public render()
... | >{this.props.organization.email}</a></p>;
}
let phone;
if (this.props.organization.phone)
{
phone = <p>Phone: <a href={`tel:${this.props.organization.phone}`}>{this.props.organization.phone}</a></p>;
}
let address;
if (this.props.organization.address)
{
address = <p>Address: ... | {
email = <p>Email: <a href={`mailto:${this.props.organization.email}`} | conditional_block |
OrganizationListItem.tsx | import * as React from "react";
import { ListGroupItem } from "react-bootstrap";
import { Organization } from "../State/Organization";
interface IOrganizationListItemProps
{
organization: Organization;
}
export class OrganizationListItem extends React.Component<IOrganizationListItemProps, {}>
{
public render()
... | (this.props.organization.address)
{
address = <p>Address: {this.props.organization.address}</p>;
}
return (
<ListGroupItem>
<h3>{this.props.organization.name}</h3>
<p>{this.props.organization.description}</p>
{email}
{phone}
{address}
... | if | identifier_name |
OrganizationListItem.tsx | import * as React from "react"; | import { ListGroupItem } from "react-bootstrap";
import { Organization } from "../State/Organization";
interface IOrganizationListItemProps
{
organization: Organization;
}
export class OrganizationListItem extends React.Component<IOrganizationListItemProps, {}>
{
public render()
{
let email;
if (this.pr... | random_line_split | |
OrganizationListItem.tsx | import * as React from "react";
import { ListGroupItem } from "react-bootstrap";
import { Organization } from "../State/Organization";
interface IOrganizationListItemProps
{
organization: Organization;
}
export class OrganizationListItem extends React.Component<IOrganizationListItemProps, {}>
{
public render()
... |
return (
<ListGroupItem>
<h3>{this.props.organization.name}</h3>
<p>{this.props.organization.description}</p>
{email}
{phone}
{address}
</ListGroupItem>
);
}
}
| {
address = <p>Address: {this.props.organization.address}</p>;
} | identifier_body |
main.rs | use rand::Rng;
use std::cmp::Ordering;
use std::io;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1..101);
println!("The secret number is: {}", secret_number);
loop {
println!("Please input your guess.");
let mut guess = String::new();
... | let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
// ANCHOR_END: ch19
println!("You guessed: {}", guess);
// --snip--
// ANCHOR_END: here
match guess.cmp(&secret_number) {
Ordering::Less => ... |
// ANCHOR: ch19 | random_line_split |
main.rs | use rand::Rng;
use std::cmp::Ordering;
use std::io;
fn main() | {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1..101);
println!("The secret number is: {}", secret_number);
loop {
println!("Please input your guess.");
let mut guess = String::new();
// ANCHOR: here
// --snip--
io::stdin(... | identifier_body | |
main.rs | use rand::Rng;
use std::cmp::Ordering;
use std::io;
fn | () {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1..101);
println!("The secret number is: {}", secret_number);
loop {
println!("Please input your guess.");
let mut guess = String::new();
// ANCHOR: here
// --snip--
io::std... | main | identifier_name |
single_thread_download.py | #!/usr/bin/python3
# -*- coding: UTF-8 -*-
# single_thread_download.py
import os
import urllib.request
import urllib.error
import shutil
# 单线程
def single_thread_download(url, file_name=None, overwrite=False):
# 如果文件名为空,则从 URL 中获取文件名
if file_name is None:
file_name = ur | l.rpartition('/')[-1]
# 潜在 bug:如果不覆盖己有文件,而已有文件不完整(eg. 没下载全),会有潜在影响
if os.path.exists(file_name) and (not overwrite):
return
try:
with urllib.request.urlopen(url) as response, open(file_name, 'wb') as out_stream:
shutil.copyfileobj(response, out_stream)
except urllib.error.URLError as e:
print(e.errno, '\n'... | identifier_body | |
single_thread_download.py | #!/usr/bin/python3
# -*- coding: UTF-8 -*-
# single_thread_download.py
import os
import urllib.request
import urllib.error
import shutil
# 单线程
def single | file_name=None, overwrite=False):
# 如果文件名为空,则从 URL 中获取文件名
if file_name is None:
file_name = url.rpartition('/')[-1]
# 潜在 bug:如果不覆盖己有文件,而已有文件不完整(eg. 没下载全),会有潜在影响
if os.path.exists(file_name) and (not overwrite):
return
try:
with urllib.request.urlopen(url) as response, open(file_name, 'wb') as out_stream:
... | _thread_download(url, | identifier_name |
single_thread_download.py | #!/usr/bin/python3
# -*- coding: UTF-8 -*-
# single_thread_download.py
import os
import urllib.request
import urllib.error
import shutil
# 单线程
def single_thread_download(url, file_name=None, overwrite=False):
# 如果文件名为空,则从 URL 中获取文件名
if file_name is None:
file_name = url.rpartition('/')[-1]
# 潜在 bug:如果不覆盖己有文件,而... | fileobj(response, out_stream)
except urllib.error.URLError as e:
print(e.errno, '\n', e.reason, '\n')
# single_thread_download("http://screencasts.b0.upaiyun.com/podcasts/nil_podcast_1.m4a")
| l.copy | conditional_block |
single_thread_download.py | #!/usr/bin/python3
# -*- coding: UTF-8 -*-
# single_thread_download.py
import os
import urllib.request
import urllib.error | # 单线程
def single_thread_download(url, file_name=None, overwrite=False):
# 如果文件名为空,则从 URL 中获取文件名
if file_name is None:
file_name = url.rpartition('/')[-1]
# 潜在 bug:如果不覆盖己有文件,而已有文件不完整(eg. 没下载全),会有潜在影响
if os.path.exists(file_name) and (not overwrite):
return
try:
with urllib.request.urlopen(url) as response, op... | import shutil
| random_line_split |
environment.ts | // Angular 2
// rc2 workaround
import {enableDebugTools, disableDebugTools} from "@angular/platform-browser";
import {enableProdMode, ApplicationRef} from "@angular/core";
// Environment Providers
let PROVIDERS = [
// common env directives
];
// Angular debug tools in the dev console
// https://github.com/angular/ang... | else {
_decorateModuleRef = (modRef: any) => {
var appRef = modRef.injector.get(ApplicationRef);
var cmpRef = appRef.components[0];
let _ng = (<any>window).ng;
enableDebugTools(cmpRef);
(<any>window).ng.probe = _ng.probe;
(<any>window).ng.coreTokens = _ng.coreTokens;
return modRef
};
// Development... | {
// Production
//disableDebugTools();
enableProdMode();
PROVIDERS = [
...PROVIDERS,
// custom providers in production
];
} | conditional_block |
environment.ts | // Angular 2
// rc2 workaround
import {enableDebugTools, disableDebugTools} from "@angular/platform-browser";
import {enableProdMode, ApplicationRef} from "@angular/core";
// Environment Providers
let PROVIDERS = [
// common env directives
];
// Angular debug tools in the dev console
// https://github.com/angular/ang... | }
export const decorateModuleRef = _decorateModuleRef;
export const ENV_PROVIDERS = [
...PROVIDERS
]; | // custom providers in development
];
| random_line_split |
conv2d.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... | """Schedule for Conv2d NHWC operator."""
s = tvm.te.create_schedule([x.op for x in outs])
return s | identifier_body | |
conv2d.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... | (outs):
"""Schedule for Conv2d NHWC operator."""
s = tvm.te.create_schedule([x.op for x in outs])
return s
| schedule_conv2d_nhwc | identifier_name |
conv2d.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... | # http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing p... | # | random_line_split |
query.py | from .utils import DslBase, BoolMixin, _make_dsl_class
from .function import SF, ScoreFunction
__all__ = [
'Q', 'Bool', 'Boosting', 'Common', 'ConstantScore', 'DisMax', 'Filtered',
'FunctionScore', 'Fuzzy', 'FuzzyLikeThis', 'FuzzyLikeThisField',
'GeoShape', 'HasChild', 'HasParent', 'Ids', 'Indices', 'Match... |
# register this as Bool for Query
Query._bool = Bool
class FunctionScore(Query):
name = 'function_score'
_param_defs = {
'query': {'type': 'query'},
'filter': {'type': 'filter'},
'functions': {'type': 'score_function', 'multi': True},
}
def __init__(self, **kwargs):
if... | name = 'bool'
_param_defs = {
'must': {'type': 'query', 'multi': True},
'should': {'type': 'query', 'multi': True},
'must_not': {'type': 'query', 'multi': True},
}
def __and__(self, other):
q = self._clone()
if isinstance(other, self.__class__):
q.must +=... | identifier_body |
query.py | from .utils import DslBase, BoolMixin, _make_dsl_class
from .function import SF, ScoreFunction
__all__ = [
'Q', 'Bool', 'Boosting', 'Common', 'ConstantScore', 'DisMax', 'Filtered',
'FunctionScore', 'Fuzzy', 'FuzzyLikeThis', 'FuzzyLikeThisField',
'GeoShape', 'HasChild', 'HasParent', 'Ids', 'Indices', 'Match... |
# not all of them are required, use it and remember min_should_match
elif not q.should:
q.minimum_should_match = min_should_match
q.should = qx.should
# not all are required, add a should list to the must with proper min_should_mat... | q.must.extend(qx.should) | conditional_block |
query.py | from .utils import DslBase, BoolMixin, _make_dsl_class
from .function import SF, ScoreFunction
__all__ = [
'Q', 'Bool', 'Boosting', 'Common', 'ConstantScore', 'DisMax', 'Filtered',
'FunctionScore', 'Fuzzy', 'FuzzyLikeThis', 'FuzzyLikeThisField',
'GeoShape', 'HasChild', 'HasParent', 'Ids', 'Indices', 'Match... | return self
__ror__ = __or__
EMPTY_QUERY = MatchAll()
class Bool(BoolMixin, Query):
name = 'bool'
_param_defs = {
'must': {'type': 'query', 'multi': True},
'should': {'type': 'query', 'multi': True},
'must_not': {'type': 'query', 'multi': True},
}
def __and__(self, ... | def __add__(self, other):
return other._clone()
__and__ = __rand__ = __radd__ = __add__
def __or__(self, other): | random_line_split |
query.py | from .utils import DslBase, BoolMixin, _make_dsl_class
from .function import SF, ScoreFunction
__all__ = [
'Q', 'Bool', 'Boosting', 'Common', 'ConstantScore', 'DisMax', 'Filtered',
'FunctionScore', 'Fuzzy', 'FuzzyLikeThis', 'FuzzyLikeThisField',
'GeoShape', 'HasChild', 'HasParent', 'Ids', 'Indices', 'Match... | (self, other):
return other._clone()
__and__ = __rand__ = __radd__ = __add__
def __or__(self, other):
return self
__ror__ = __or__
EMPTY_QUERY = MatchAll()
class Bool(BoolMixin, Query):
name = 'bool'
_param_defs = {
'must': {'type': 'query', 'multi': True},
'should'... | __add__ | identifier_name |
request-tests.ts | import FormData = require('form-data');
import fs = require('fs');
import http = require('http');
import path = require('path');
import qs = require('querystring');
import request = require('request');
import stream = require('stream');
import urlModule = require('url');
let value: any;
let str: string;
let strOrUndef... | (error: any, response: http.IncomingMessage, body: string) {
if (!error && response.statusCode === 200) {
const info = JSON.parse(body);
console.log(info.stargazers_count + " Stars");
console.log(info.forks_count + " Forks");
}
}
request(options, callback);
// OAuth1.0 - 3-legged server side flow (Twi... | callback | identifier_name |
request-tests.ts | import FormData = require('form-data');
import fs = require('fs');
import http = require('http');
import path = require('path');
import qs = require('querystring');
import request = require('request');
import stream = require('stream');
import urlModule = require('url');
let value: any;
let str: string;
let strOrUndef... |
request(options, callback);
// OAuth1.0 - 3-legged server side flow (Twitter example)
// step 1
const CONSUMER_KEY = 'key';
const CONSUMER_SECRET = 'secret';
oauth = {
callback: 'http://mysite.com/callback/',
consumer_key: CONSUMER_KEY,
consumer_secret: CONSUMER_SECRET,
transport_method: 'hea... | {
if (!error && response.statusCode === 200) {
const info = JSON.parse(body);
console.log(info.stargazers_count + " Stars");
console.log(info.forks_count + " Forks");
}
} | identifier_body |
request-tests.ts | import FormData = require('form-data');
import fs = require('fs');
import http = require('http');
import path = require('path');
import qs = require('querystring');
import request = require('request');
import stream = require('stream');
import urlModule = require('url');
let value: any;
let str: string;
let strOrUndef... | 'User-Agent': 'request'
}
};
function callback(error: any, response: http.IncomingMessage, body: string) {
if (!error && response.statusCode === 200) {
const info = JSON.parse(body);
console.log(info.stargazers_count + " Stars");
console.log(info.forks_count + " Forks");
}
}
request(options, cal... | options = {
url: 'https://api.github.com/repos/request/request',
headers: { | random_line_split |
request-tests.ts | import FormData = require('form-data');
import fs = require('fs');
import http = require('http');
import path = require('path');
import qs = require('querystring');
import request = require('request');
import stream = require('stream');
import urlModule = require('url');
let value: any;
let str: string;
let strOrUndef... |
if (response.timingPhases) {
num = response.timingPhases.wait;
num = response.timingPhases.dns;
num = response.timingPhases.tcp;
num = response.timingPhases.firstByte;
num = response.timingPhases.download;
num = response.timingPhases.total;
}
})
.pipe(request.put('http://another.com/another... | {
num = response.timings.socket;
num = response.timings.lookup;
num = response.timings.connect;
num = response.timings.response;
num = response.timings.end;
} | conditional_block |
all_11.js | var searchData=
[
['wait_5ffor_5fcal_132',['wait_for_cal',['../class_a_d_c___module.html#a4fb69b5b2d07c3fc8f5f0bbbf05dfa2a',1,'ADC_Module']]],
['waituntilstable_133',['waitUntilStable',['../namespace_v_r_e_f.html#a108f7c1b5a2073bc092eafcae58575b0',1,'VREF']]], | ['wrong_5fadc_134',['WRONG_ADC',['../namespace_a_d_c___error.html#ad050c44d1f3422d02e5f9726edeee8f0a52df2c8ae830ed21e0c2fc269087b3ec',1,'ADC_Error']]],
['wrong_5fpin_135',['WRONG_PIN',['../namespace_a_d_c___error.html#ad050c44d1f3422d02e5f9726edeee8f0ab578c19f4fab8e2bfeddc85fa17b5acf',1,'ADC_Error']]]
]; | random_line_split | |
systemjs.config.1.js | // #docregion
(function(global) {
// map tells the System loader where to look for things
var map = {
'app': 'app', // 'dist',
'rxjs': 'node_modules/rxjs',
'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
'@angular': ... |
System.config(config);
})(this);
| { global.filterSystemConfig(config); } | conditional_block |
systemjs.config.1.js | // #docregion
(function(global) {
// map tells the System loader where to look for things
var map = {
'app': 'app', // 'dist',
'rxjs': 'node_modules/rxjs', |
// packages tells the System loader how to load when no filename and/or no extension
var packages = {
'app': { main: 'main.js', defaultExtension: 'js' },
'rxjs': { defaultExtension: 'js' },
'angular2-in-memory-web-api': { defaultExtension: 'js' },
};
v... | 'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
'@angular': 'node_modules/@angular'
}; | random_line_split |
Checkbox.js | /*
* Copyright (C) 2010 Google Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions ... | if (listener)
listener(event);
event.consume();
return true;
}
this._inputElement.addEventListener("click", listenerWrapper, false);
this.element.addEventListener("click", listenerWrapper, false);
}
} | function listenerWrapper(event)
{ | random_line_split |
Checkbox.js | /*
* Copyright (C) 2010 Google Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions ... |
this._inputElement.addEventListener("click", listenerWrapper, false);
this.element.addEventListener("click", listenerWrapper, false);
}
}
| {
if (listener)
listener(event);
event.consume();
return true;
} | identifier_body |
Checkbox.js | /*
* Copyright (C) 2010 Google Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions ... | (checked)
{
this._inputElement.checked = checked;
},
get checked()
{
return this._inputElement.checked;
},
addEventListener: function(listener)
{
function listenerWrapper(event)
{
if (listener)
listener(event);
event.c... | checked | identifier_name |
RegressionTree.py | # regression tree
# input is a dataframe of features
# the corresponding y value(called labels here) is the scores for each document
import pandas as pd
import numpy as np
from multiprocessing import Pool
from itertools import repeat
import scipy
import scipy.optimize
node_id = 0
def get_splitting_points(args):
#... | pool = Pool()
splitting_data = [self.training_data.iloc[:,col].tolist() for col in xrange(self.training_data.shape[1])]
cols = [col for col in xrange(self.training_data.shape[1])]
for dat, col in pool.map(get_splitting_points, zip(splitting_data, cols)):
all_pos_split[col] = dat
pool.close()
self.tree = ... | all_pos_split = {} | random_line_split |
RegressionTree.py | # regression tree
# input is a dataframe of features
# the corresponding y value(called labels here) is the scores for each document
import pandas as pd
import numpy as np
from multiprocessing import Pool
from itertools import repeat
import scipy
import scipy.optimize
node_id = 0
def get_splitting_points(args):
#... | (data, label, key, split):
left_index = [index for index in xrange(len(data.iloc[:,key])) if data.iloc[index,key] < split]
right_index = [index for index in xrange(len(data.iloc[:,key])) if data.iloc[index,key] >= split]
left_data = data.iloc[left_index,:]
right_data = data.iloc[right_index,:]
left_label = [label[... | split_children | identifier_name |
RegressionTree.py | # regression tree
# input is a dataframe of features
# the corresponding y value(called labels here) is the scores for each document
import pandas as pd
import numpy as np
from multiprocessing import Pool
from itertools import repeat
import scipy
import scipy.optimize
node_id = 0
def get_splitting_points(args):
#... |
if __name__ == '__main__':
#read in data, label
data = pd.read_excel("mlr06.xls")
test = [[478, 184, 40, 74, 11, 31], [1000,10000,10000,10000,10000,1000,100000]]
label = data['X7']
del data['X7']
model = RegressionTree(data, label)
model.fit()
print model.predict(test)
| prediction = np.array([make_prediction(self.tree, x) for x in test])
return prediction | identifier_body |
RegressionTree.py | # regression tree
# input is a dataframe of features
# the corresponding y value(called labels here) is the scores for each document
import pandas as pd
import numpy as np
from multiprocessing import Pool
from itertools import repeat
import scipy
import scipy.optimize
node_id = 0
def get_splitting_points(args):
#... |
return least_square(data1) + least_square(data2)
def make_prediction(tree, x, annotate = False):
if tree['is_leaf']:
if annotate:
print "At leaf, predicting %s" % tree['value']
return tree['value']
else:
# the splitting value of x.
split_feature_value = x[tree['splitting_feature'][0]]
if annotate: ... | temp_dat = data[i]
if temp_dat <= split_point:
data1.append(label[i])
else:
data2.append(label[i]) | conditional_block |
example.js | #!/usr/bin/env babel-node --harmony
// import firequeue from 'firequeue'
import firequeue from './src'
import { concat, throughSync } from 'stream-util'
import parallel from 'concurrent-transform'
const queue = firequeue.init('https://firequeue-test.firebaseio.com')
const logger = (fn) => throughSync(function(data) ... | // log task: task1, job: job1, state: cleaned
// log task: task1, job: job2, state: cleaned
// ...
// 30sec later...
setTimeout(() => {
queue.stop().then(() => {
console.log('queue was stopped successfuly')
})
}, 30000) | .pipe(queue.clean('completed'))
.pipe(logger(({ task, key, state }) => `task: ${task}, job: ${key}, state: ${state}`))
| random_line_split |
fuzzing.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
constants,
peer::Peer,
protocols::wire::{
handshake::v1::{MessagingProtocolVersion, SupportedProtocols},
messaging::v1::{NetworkMessage, NetworkMessageSink},
},
testutils::fake_socket::Re... | // for all network notifs to drain out and finish.
drop(peer_reqs_tx);
peer_notifs_rx.collect::<Vec<_>>().await;
});
}
#[test]
fn test_peer_fuzzers() {
let mut value_gen = ValueGenerator::deterministic();
for _ in 0..50 {
let corpus = generate_corpus(&mut value_gen);
... | // ACK the "remote" d/c and drop our handle to the Peer actor. Then wait | random_line_split |
fuzzing.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
constants,
peer::Peer,
protocols::wire::{
handshake::v1::{MessagingProtocolVersion, SupportedProtocols},
messaging::v1::{NetworkMessage, NetworkMessageSink},
},
testutils::fake_socket::Re... |
/// Fuzz the `Peer` actor's inbound message handling.
///
/// For each fuzzer iteration, we spin up a new `Peer` actor and pipe the raw
/// fuzzer data into it. This mostly tests that the `Peer` inbound message handling
/// doesn't panic or leak memory when reading, deserializing, and handling messages
/// from remot... | {
let network_msgs = gen.generate(vec(any::<NetworkMessage>(), 1..20));
let (write_socket, mut read_socket) = MemorySocket::new_pair();
let mut writer = NetworkMessageSink::new(write_socket, constants::MAX_FRAME_SIZE, None);
// Write the `NetworkMessage`s to a fake socket
let f_send = async move {... | identifier_body |
fuzzing.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
constants,
peer::Peer,
protocols::wire::{
handshake::v1::{MessagingProtocolVersion, SupportedProtocols},
messaging::v1::{NetworkMessage, NetworkMessageSink},
},
testutils::fake_socket::Re... | () {
let mut value_gen = ValueGenerator::deterministic();
for _ in 0..50 {
let corpus = generate_corpus(&mut value_gen);
fuzz(&corpus);
}
}
| test_peer_fuzzers | identifier_name |
config_flow.py | """Config flow for the Daikin platform."""
import asyncio
import logging
from uuid import uuid4
from aiohttp import ClientError, web_exceptions
from async_timeout import timeout
from pydaikin.daikin_base import Appliance
from pydaikin.discovery import Discovery
import voluptuous as vol
from homeassistant import confi... | (self, host, mac, key=None, uuid=None, password=None):
"""Register new entry."""
if not self.unique_id:
await self.async_set_unique_id(mac)
self._abort_if_unique_id_configured()
return self.async_create_entry(
title=host,
data={
CONF_H... | _create_entry | identifier_name |
config_flow.py | """Config flow for the Daikin platform."""
import asyncio
import logging
from uuid import uuid4
from aiohttp import ClientError, web_exceptions
from async_timeout import timeout
from pydaikin.daikin_base import Appliance
from pydaikin.discovery import Discovery
import voluptuous as vol
from homeassistant import confi... |
try:
with timeout(TIMEOUT):
device = await Appliance.factory(
host,
self.hass.helpers.aiohttp_client.async_get_clientsession(),
key=key,
uuid=uuid,
password=password,
... | password = None | conditional_block |
config_flow.py | """Config flow for the Daikin platform."""
import asyncio
import logging
from uuid import uuid4
from aiohttp import ClientError, web_exceptions
from async_timeout import timeout
from pydaikin.daikin_base import Appliance
from pydaikin.discovery import Discovery
import voluptuous as vol
from homeassistant import confi... | """Handle a config flow."""
VERSION = 1
def __init__(self):
"""Initialize the Daikin config flow."""
self.host = None
@property
def schema(self):
"""Return current schema."""
return vol.Schema(
{
vol.Required(CONF_HOST, default=self.host): s... | identifier_body | |
config_flow.py | """Config flow for the Daikin platform."""
import asyncio
import logging
from uuid import uuid4
from aiohttp import ClientError, web_exceptions
from async_timeout import timeout
from pydaikin.daikin_base import Appliance
from pydaikin.discovery import Discovery
import voluptuous as vol
from homeassistant import confi... | return await self._create_device(
user_input[CONF_HOST],
user_input.get(CONF_API_KEY),
user_input.get(CONF_PASSWORD),
)
async def async_step_zeroconf(self, discovery_info):
"""Prepare configuration for a discovered Daikin device."""
_LOGGER.debug(... | return self.async_show_form(step_id="user", data_schema=self.schema) | random_line_split |
try-catch-before-try.js | // Copyright (C) 2015 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es6id: 25.3.1.3
description: >
When a generator is paused before a `try..catch` statement, `return` should
interrupt control flow as if a `return` statement had appeare... | assert.sameValue(result.value, 45, 'Result `value` following `return`');
assert.sameValue(result.done, true, 'Result `done` flag following `return`');
result = iter.next();
assert.sameValue(result.value,
undefined, 'Result `value` is undefined when complete'
);
assert.sameValue(
result.done, true, 'Result `done` f... |
iter.next();
result = iter.return(45); | random_line_split |
owned_slice.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
#![allow(unsafe_code)]
//! A replacement for `Box<[T]>` that cbindgen can understand.
use malloc_size_of::{Mall... | (mut b: Box<[T]>) -> Self {
let len = b.len();
let ptr = unsafe { NonNull::new_unchecked(b.as_mut_ptr()) };
mem::forget(b);
Self {
len,
ptr,
_phantom: PhantomData,
}
}
}
impl<T> From<Vec<T>> for OwnedSlice<T> {
#[inline]
fn from(b:... | from | identifier_name |
owned_slice.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
#![allow(unsafe_code)]
//! A replacement for `Box<[T]>` that cbindgen can understand.
use malloc_size_of::{Mall... |
}
impl<T> From<Box<[T]>> for OwnedSlice<T> {
#[inline]
fn from(mut b: Box<[T]>) -> Self {
let len = b.len();
let ptr = unsafe { NonNull::new_unchecked(b.as_mut_ptr()) };
mem::forget(b);
Self {
len,
ptr,
_phantom: PhantomData,
}
}
... | {
unsafe { slice::from_raw_parts_mut(self.ptr.as_ptr(), self.len) }
} | identifier_body |
owned_slice.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
| use malloc_size_of::{MallocShallowSizeOf, MallocSizeOf, MallocSizeOfOps};
use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};
use std::ptr::NonNull;
use std::{fmt, iter, mem, slice};
use to_shmem::{SharedMemoryBuilder, ToShmem};
/// A struct that basically replaces a `Box<[T]>`, but which cbindgen can
/// u... | #![allow(unsafe_code)]
//! A replacement for `Box<[T]>` that cbindgen can understand.
| random_line_split |
owned_slice.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
#![allow(unsafe_code)]
//! A replacement for `Box<[T]>` that cbindgen can understand.
use malloc_size_of::{Mall... |
}
}
unsafe impl<T: Sized + Send> Send for OwnedSlice<T> {}
unsafe impl<T: Sized + Sync> Sync for OwnedSlice<T> {}
impl<T: Clone> Clone for OwnedSlice<T> {
#[inline]
fn clone(&self) -> Self {
Self::from_slice(&**self)
}
}
impl<T: fmt::Debug> fmt::Debug for OwnedSlice<T> {
fn fmt(&self, fo... | {
let _ = mem::replace(self, Self::default()).into_vec();
} | conditional_block |
lib.rs | #[macro_use]
extern crate prodbg_api;
use prodbg_api::*;
struct Line {
opcode: String,
regs_write: String,
regs_read: String,
address: u64,
}
///
/// Breakpoint
///
struct Breakpoint {
address: u64,
}
///
/// Holds colors use for the disassembly view. This should be possible to configure later o... |
// need to fetch more data here also
if pos >= self.lines.len() as i32 {
return;
}
self.cursor = self.lines[pos as usize].address;
return;
}
}
}
fn render_arrow(ui: &Ui, pos_x: f32, pos_y:... | {
return;
} | conditional_block |
lib.rs | #[macro_use]
extern crate prodbg_api;
use prodbg_api::*;
struct Line {
opcode: String,
regs_write: String,
regs_read: String,
address: u64,
}
///
/// Breakpoint
///
struct Breakpoint {
address: u64,
}
///
/// Holds colors use for the disassembly view. This should be possible to configure later o... | (&mut self, writer: &mut Writer) {
let address = self.cursor;
for i in (0..self.breakpoints.len()).rev() {
if self.breakpoints[i].address == address {
writer.event_begin(EVENT_DELETE_BREAKPOINT as u16);
writer.write_u64("address", address);
wr... | toggle_breakpoint | identifier_name |
lib.rs | #[macro_use]
extern crate prodbg_api;
| opcode: String,
regs_write: String,
regs_read: String,
address: u64,
}
///
/// Breakpoint
///
struct Breakpoint {
address: u64,
}
///
/// Holds colors use for the disassembly view. This should be possible to configure later on.
///
/*
struct Colors {
breakpoint: Color,
step_cursor: Color,
... | use prodbg_api::*;
struct Line { | random_line_split |
lib.rs | #[macro_use]
extern crate prodbg_api;
use prodbg_api::*;
struct Line {
opcode: String,
regs_write: String,
regs_read: String,
address: u64,
}
///
/// Breakpoint
///
struct Breakpoint {
address: u64,
}
///
/// Holds colors use for the disassembly view. This should be possible to configure later o... | {
define_view_plugin!(PLUGIN, b"Disassembly2 View", DisassemblyView);
plugin_handler.register_view(&PLUGIN);
} | identifier_body | |
yhAlert.js | /*
* @author paper
*/
function YHAlert(arg) | {
var obj = arg ||{},
msg = obj.msg || '你没有写提示内容!',
bd = document.getElementsByTagName('body')[0],
time = obj.time || 2000,
way = obj.way == 'leftToRight' ? 'left' : 'top',
$ = function(id){
return typeof id == 'string' ? document.getElementById(id) : id;
},
html = '<div id="YHAlert" st... | identifier_body | |
yhAlert.js | /*
* @author paper
*/
function YHAlert(arg){
var obj = arg ||{},
msg = obj.msg || '你没有写提示内容!',
bd = document.getElementsByTagName('body')[0],
time = obj.time || 2000,
way = obj.way == 'leftToRight' ? 'left' : 'top',
$ = function(id){
return typeof id == 'string' ? document.getElementById(i... |
setStyle(YHAlert_in, {
'borderRadius': '5px',
'MozBorderRadius': '5px',
'WebkitBorderRadius': '5px',
'backgroundColor':'#fefefe',
'padding':'15px 10px'
});
setStyle(YHAlert_p, {
'textAlign': 'left',
'f... | random_line_split | |
yhAlert.js | /*
* @author paper
*/
function | (arg){
var obj = arg ||{},
msg = obj.msg || '你没有写提示内容!',
bd = document.getElementsByTagName('body')[0],
time = obj.time || 2000,
way = obj.way == 'leftToRight' ? 'left' : 'top',
$ = function(id){
return typeof id == 'string' ? document.getElementById(id) : id;
},
html = '<div id="YHAler... | YHAlert | identifier_name |
account.rs | extern crate meg;
extern crate log;
use log::*;
use std::env;
use std::clone::Clone;
use turbo::util::{CliResult, Config};
use self::meg::ops::meg_account_create as Act;
use self::meg::ops::meg_account_show as Show;
#[derive(RustcDecodable, Clone)]
pub struct Options {
pub flag_create: String,
pub flag_show: boo... |
} | }
}
return Ok(None) | random_line_split |
account.rs | extern crate meg;
extern crate log;
use log::*;
use std::env;
use std::clone::Clone;
use turbo::util::{CliResult, Config};
use self::meg::ops::meg_account_create as Act;
use self::meg::ops::meg_account_show as Show;
#[derive(RustcDecodable, Clone)]
pub struct | {
pub flag_create: String,
pub flag_show: bool,
pub flag_verbose: bool,
}
pub const USAGE: &'static str = "
Usage:
meg account [options]
Options:
-h, --help Print this message
--create EMAIL Provide an email to create a new account
--show View your account d... | Options | identifier_name |
static-file-route.ts | import { createHash } from "crypto";
import * as etag from "etag";
import { compressSync as brotliCompress } from "iltorb";
import * as zlib from "zlib";
export interface StaticFileRoute {
path: string;
foreverPath: string;
etag: string;
integrity: string;
buffer: Buffer;
string?: string;
gzipped?: Buffer;
br... |
return result;
}
export function stringFromRoute(route: StaticFileRoute) {
// Convert buffer to string on demand
return typeof route.string === "string" ? route.string : route.buffer.toString();
}
export function gzippedBufferFromRoute(route: StaticFileRoute) {
// Apply GZIP compression on demand
return route.g... | {
result.string = contents;
} | conditional_block |
static-file-route.ts | import { createHash } from "crypto";
import * as etag from "etag";
import { compressSync as brotliCompress } from "iltorb";
import * as zlib from "zlib";
export interface StaticFileRoute {
path: string;
foreverPath: string;
etag: string;
integrity: string;
buffer: Buffer;
string?: string;
gzipped?: Buffer;
br... | (route: StaticFileRoute) {
// Convert buffer to string on demand
return typeof route.string === "string" ? route.string : route.buffer.toString();
}
export function gzippedBufferFromRoute(route: StaticFileRoute) {
// Apply GZIP compression on demand
return route.gzipped || (route.gzipped = zlib.gzipSync(route.buff... | stringFromRoute | identifier_name |
static-file-route.ts | import { createHash } from "crypto";
import * as etag from "etag";
import { compressSync as brotliCompress } from "iltorb";
import * as zlib from "zlib";
export interface StaticFileRoute {
path: string;
foreverPath: string;
etag: string;
integrity: string;
buffer: Buffer;
string?: string;
gzipped?: Buffer;
br... |
export function gzippedBufferFromRoute(route: StaticFileRoute) {
// Apply GZIP compression on demand
return route.gzipped || (route.gzipped = zlib.gzipSync(route.buffer, {
level: zlib.constants.Z_BEST_COMPRESSION,
}));
}
export function brotliedBufferFromRoute(route: StaticFileRoute) {
// Apply brotli compress... | {
// Convert buffer to string on demand
return typeof route.string === "string" ? route.string : route.buffer.toString();
} | identifier_body |
static-file-route.ts | import { createHash } from "crypto";
import * as etag from "etag";
import { compressSync as brotliCompress } from "iltorb";
import * as zlib from "zlib";
export interface StaticFileRoute {
path: string;
foreverPath: string;
etag: string;
integrity: string;
buffer: Buffer;
string?: string;
gzipped?: Buffer;
br... | path,
foreverPath: path.replace(/\.((?!.*\.))/, "." + integrity.replace(/\//g, "_").replace(/\+/g, "-").replace(/=/g, "").substring(0, 16) + "."),
etag: etag(buffer),
integrity: "sha256-" + integrity,
buffer,
};
if (typeof contents === "string") {
result.string = contents;
}
return result;
}
export fun... | random_line_split | |
fields.py | from django.db import models
# Django doesn't support big auto fields out of the box, see
# https://code.djangoproject.com/ticket/14286.
# This is a stripped down version of the BoundedBigAutoField from Sentry.
class BigAutoField(models.AutoField):
description = "Big Integer"
def db_type(self, connection):
... |
class FlexibleForeignKey(models.ForeignKey):
def db_type(self, connection):
# This is required to support BigAutoField
rel_field = self.related_field
if hasattr(rel_field, 'get_related_db_type'):
return rel_field.get_related_db_type(connection)
return super(FlexibleFore... | return models.BigIntegerField().db_type(connection)
def get_internal_type(self):
return "BigIntegerField" | random_line_split |
fields.py | from django.db import models
# Django doesn't support big auto fields out of the box, see
# https://code.djangoproject.com/ticket/14286.
# This is a stripped down version of the BoundedBigAutoField from Sentry.
class BigAutoField(models.AutoField):
description = "Big Integer"
def db_type(self, connection):
... | (models.ForeignKey):
def db_type(self, connection):
# This is required to support BigAutoField
rel_field = self.related_field
if hasattr(rel_field, 'get_related_db_type'):
return rel_field.get_related_db_type(connection)
return super(FlexibleForeignKey, self).db_type(conn... | FlexibleForeignKey | identifier_name |
fields.py | from django.db import models
# Django doesn't support big auto fields out of the box, see
# https://code.djangoproject.com/ticket/14286.
# This is a stripped down version of the BoundedBigAutoField from Sentry.
class BigAutoField(models.AutoField):
description = "Big Integer"
def db_type(self, connection):
... |
else:
raise NotImplemented
def get_related_db_type(self, connection):
return models.BigIntegerField().db_type(connection)
def get_internal_type(self):
return "BigIntegerField"
class FlexibleForeignKey(models.ForeignKey):
def db_type(self, connection):
# This ... | return "bigserial" | conditional_block |
fields.py | from django.db import models
# Django doesn't support big auto fields out of the box, see
# https://code.djangoproject.com/ticket/14286.
# This is a stripped down version of the BoundedBigAutoField from Sentry.
class BigAutoField(models.AutoField):
description = "Big Integer"
def db_type(self, connection):
... |
def get_related_db_type(self, connection):
return models.BigIntegerField().db_type(connection)
def get_internal_type(self):
return "BigIntegerField"
class FlexibleForeignKey(models.ForeignKey):
def db_type(self, connection):
# This is required to support BigAutoField
rel... | engine = connection.settings_dict['ENGINE']
if 'mysql' in engine:
return "bigint AUTO_INCREMENT"
elif 'postgres' in engine:
return "bigserial"
else:
raise NotImplemented | identifier_body |
pso.py | """
Copyright (C) 2012 Alan J Lockett
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute,... |
if initialize:
self.upperv = self._positions.max(axis=0)
self.lowerv = self._positions.min(axis=0)
self.updateVelocity()
class ParticleSwarmOptimization(PopulationDistribution):
"""Particle Swarm Optimization.
Config parameters
* omega -- ... | lower, upper = self.config.space.extent()
self._positions = np.maximum(self._positions, lower)
self._positions = np.minimum(self._positions, upper) | conditional_block |
pso.py | """
Copyright (C) 2012 Alan J Lockett
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute,... |
def updateVelocity(self):
popSize = self.config.populationSize
if self._velocities is None:
if self.config.initial is None:
self._velocities = np.array([self.config.space.random()
for i in xrange(popSize)])
elif (inspect.isclass(sel... | return self._positions | identifier_body |
pso.py | """
Copyright (C) 2012 Alan J Lockett
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute,... | (self):
popSize = self.config.populationSize
if self._velocities is None:
if self.config.initial is None:
self._velocities = np.array([self.config.space.random()
for i in xrange(popSize)])
elif (inspect.isclass(self.config.initial) and
... | updateVelocity | identifier_name |
pso.py | """
Copyright (C) 2012 Alan J Lockett
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute,... | rg = np.outer(np.random.random_sample(popSize),
np.ones(self.config.dim))
#print shape(rp), shape(self.bestLocal), shape(self.bestGlobal), shape(self.positions), shape(self.velocities)
bestLocal = np.array([x for x,s in self.localBestPop])
bestGlobal = self.best()[0]
... | np.ones(self.config.dim)) | random_line_split |
tbody.module.js | var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(d... |
return TBodyModule;
}());
TBodyModule = __decorate([
NgModule({
imports: [
CommonModule,
FormsModule,
CellModule,
],
declarations: TBODY_COMPONENTS.slice(),
exports: TBODY_COMPONENTS.slice(),
})
], TBodyModule);
export { TBodyModule };
//#... | {
} | identifier_body |
tbody.module.js | var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(d... | () {
}
return TBodyModule;
}());
TBodyModule = __decorate([
NgModule({
imports: [
CommonModule,
FormsModule,
CellModule,
],
declarations: TBODY_COMPONENTS.slice(),
exports: TBODY_COMPONENTS.slice(),
})
], TBodyModule);
export { TBodyMod... | TBodyModule | identifier_name |
tbody.module.js | var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(d... | TbodyCustomComponent,
Ng2SmartTableTbodyComponent
];
var TBodyModule = (function () {
function TBodyModule() {
}
return TBodyModule;
}());
TBodyModule = __decorate([
NgModule({
imports: [
CommonModule,
FormsModule,
CellModule,
],
declar... | var TBODY_COMPONENTS = [
TbodyCreateCancelComponent,
TbodyEditDeleteComponent, | random_line_split |
abstractmoduleloader.d.ts | declare module goog.module {
/**
* An interface that loads JavaScript modules.
* @interface
*/
interface AbstractModuleLoader {
/**
* Loads a list of JavaScript modules.
*
* @param {Array<string>} ids The module ids in dependency order.
* @par... | *
* @param {string} id The module id.
* @param {!goog.module.ModuleInfo} moduleInfo The module info.
*/
prefetchModule(id: string, moduleInfo: goog.module.ModuleInfo): void;
}
} | random_line_split | |
lib.rs | #![feature(core)]
/// Generate a new iterable witn a list comprehension. This macro tries to follow the syntax of | /// Python's list comprehensions. This is a very flexable macro that allows the generation of any
/// iterable that implements `std::iter::FromIterator`. The resulting type will be determined by
/// the type of the variable that you are attempting to assign to. You can create a `Vec`:
///
/// ```ignore
/// let x: Vec<i... | random_line_split | |
executive.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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 lat... | use machine::EthereumMachine as Machine;
#[derive(Debug, PartialEq, Clone)]
struct CallCreate {
data: Bytes,
destination: Option<Address>,
gas_limit: U256,
value: U256
}
impl From<ethjson::vm::Call> for CallCreate {
fn from(c: ethjson::vm::Call) -> Self {
let dst: Option<ethjson::hash::Address> = c.destination... | use rlp::RlpStream;
use hash::keccak; | random_line_split |
executive.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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 lat... | ;
macro_rules! try_fail {
($e: expr) => {
match $e {
Ok(x) => x,
Err(e) => {
let msg = format!("Internal error: {}", e);
fail_unless(false, &msg);
continue
}
}
}
}
let out_of_gas = vm.out_of_gas();
let mut state = get_temp_state();
state.populate_from(From::fro... | {
failed.push(format!("[{}] {}: {}", vm_type, name, s));
fail = true
} | conditional_block |
executive.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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 lat... | (&self, address: &Address) -> vm::Result<usize> {
self.ext.extcodesize(address)
}
fn log(&mut self, topics: Vec<H256>, data: &[u8]) -> vm::Result<()> {
self.ext.log(topics, data)
}
fn ret(self, gas: &U256, data: &ReturnData, apply_state: bool) -> Result<U256, vm::Error> {
self.ext.ret(gas, data, apply_state... | extcodesize | identifier_name |
executive.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity 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 lat... |
fn env_info(&self) -> &EnvInfo {
self.ext.env_info()
}
fn depth(&self) -> usize {
0
}
fn is_static(&self) -> bool {
false
}
fn inc_sstore_clears(&mut self) {
self.ext.inc_sstore_clears()
}
}
fn do_json_test(json_data: &[u8]) -> Vec<String> {
let vms = VMType::all();
vms
.iter()
.flat_map(|vm... | {
self.ext.schedule()
} | identifier_body |
preloader.js | 'use strict';
angular.module('mpApp')
.factory(
'preloader',
function($q, $rootScope) {
// I manage the preloading of image objects. Accepts an array of image URLs.
function Preloader(imageLocations) {
// I am the image SRC values to preload.
this.imageLocations = imageLocations... |
this.state = this.states.LOADING;
for (var i = 0; i < this.imageCount; i++) {
this.loadImageLocation(this.imageLocations[i]);
}
// Return the deferred promise for the load event.
return (this.promise);
},
// ---
// PRIVATE ME... | {
return (this.promise);
} | conditional_block |
preloader.js | 'use strict';
angular.module('mpApp')
.factory(
'preloader',
function($q, $rootScope) {
// I manage the preloading of image objects. Accepts an array of image URLs.
function Preloader(imageLocations) {
// I am the image SRC values to preload.
this.imageLocations = imageLocations... |
}
};
// Return the factory instance.
return (Preloader);
}
); | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.