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 |
|---|---|---|---|---|
ResourceTreeModel_test.ts | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import * as SDK from '../../../../../front_end/core/sdk/sdk.js';
import * as Protocol from '../../../../../front_end/generated/protocol.js';
import {creat... |
const clearRequests = sinon.stub(networkManager, 'clearRequests');
dispatchEvent(target, 'Page.frameNavigated', {
frame: {
id: 'main',
loaderId: 'foo',
url: 'http://example.com',
domainAndRegistry: 'example.com',
securityOrigin: 'http://example.com',
mimeTy... | {
throw new Error('No networkManager');
} | conditional_block |
index.test.js | /* global expect */
import { forumLocation } from '../../../../../config/env.json';
const { getGuideUrl } = require('./');
describe('index', () => {
describe('getGuideUrl', () => {
it('should use forum topic url when forumTopicId is supplied', () => {
const value = getGuideUrl({
forumTopicId: 123... |
it('should use search endpoint when no forumTopicId is supplied', () => {
const value = getGuideUrl({
title: '& a sample title?'
});
expect(value).toEqual(
`${forumLocation}/search?q=%26%20a%20sample%20title%3F%20in%3Atitle%20order%3Aviews`
);
});
});
}); | expect(value).toEqual(`${forumLocation}/t/12345`);
}); | random_line_split |
dstr-obj-id-init-assignment-missing.js | // This file was procedurally generated from the following sources:
// - src/dstr-assignment/obj-id-init-assignment-missing.case
// - src/dstr-assignment/default/assignment-expr.template
/*---
description: If the Initializer is present and v is undefined, the Initializer should be evaluated and the result assigned to t... | flags: [generated]
info: |
VariableDeclaration : BindingPattern Initializer
1. Let rhs be the result of evaluating Initializer.
2. Let rval be GetValue(rhs).
3. ReturnIfAbrupt(rval).
4. Return the result of performing BindingInitialization for
BindingPattern passing rval and undefined as arg... | es6id: 13.3.2.4
features: [destructuring-binding] | random_line_split |
comments.js | player_id = $("#"+this.id+' .comment-player a').attr("href").substr(9);
$("#"+this.id + ' .comment-body div').after('<div id="comment-sig' + player_id + '"><a target="__new" href="http://getdotastats.com/sig/' + player_id + '.png"><img style="margin:auto; margin-bottom:20px; display:block;" src="http://getdotastat... | $('.comment').each(function(){
if(this.id.length > 0){ | random_line_split | |
comments.js | $('.comment').each(function(){
if(this.id.length > 0) |
}); | {
player_id = $("#"+this.id+' .comment-player a').attr("href").substr(9);
$("#"+this.id + ' .comment-body div').after('<div id="comment-sig' + player_id + '"><a target="__new" href="http://getdotastats.com/sig/' + player_id + '.png"><img style="margin:auto; margin-bottom:20px; display:block;" src="http://getdotast... | conditional_block |
speed_mixture.py | '''
testing speedup of code
Created on Sep 17, 2016
@author: jonaswallin
'''
from Mixture.density import mNIG
from Mixture.density.purepython import mNIG as pmNIG
from Mixture import mixOneDims
import numpy as np
import numpy.random as npr
import timeit
# most speed here is used startup (iteration = 500, n = 1000)
# ... | paramMat_true = [np.array([[1.1, 1.12, 0.1, 0],
[-1, 0,2 , -4] ]),
np.array([[-2, 0, 0.3, 0],
[1, 0, 2 , -4] ])]
alpha_true = [0]
mixObj.set_paramMat(alpha = alpha_true,paramMat = paramMat_true)
Y = mixObj.samp... | mixObj.set_densites([pmNIG(d=d) for k in range(K)]) # @UnusedVariable
else:
mixObj.set_densites([mNIG(d=d) for k in range(K)]) # @UnusedVariable | random_line_split |
speed_mixture.py | '''
testing speedup of code
Created on Sep 17, 2016
@author: jonaswallin
'''
from Mixture.density import mNIG
from Mixture.density.purepython import mNIG as pmNIG
from Mixture import mixOneDims
import numpy as np
import numpy.random as npr
import timeit
# most speed here is used startup (iteration = 500, n = 1000)
# ... | (pure_python=False, precompute = True):
K = 2
d = 2
iteration = 500
mixObj = mixOneDims(K=K, d=d)
if pure_python:
mixObj.set_densites([pmNIG(d=d) for k in range(K)]) # @UnusedVariable
else:
mixObj.set_densites([mNIG(d=d) for k in range(K)]) # @UnusedVariable
paramMat_... | speed_python | identifier_name |
speed_mixture.py | '''
testing speedup of code
Created on Sep 17, 2016
@author: jonaswallin
'''
from Mixture.density import mNIG
from Mixture.density.purepython import mNIG as pmNIG
from Mixture import mixOneDims
import numpy as np
import numpy.random as npr
import timeit
# most speed here is used startup (iteration = 500, n = 1000)
# ... |
else:
mixObj.set_densites([mNIG(d=d) for k in range(K)]) # @UnusedVariable
paramMat_true = [np.array([[1.1, 1.12, 0.1, 0],
[-1, 0,2 , -4] ]),
np.array([[-2, 0, 0.3, 0],
[1, 0, 2 , -4] ])]
alpha_true = [0]
mixOb... | mixObj.set_densites([pmNIG(d=d) for k in range(K)]) # @UnusedVariable | conditional_block |
speed_mixture.py | '''
testing speedup of code
Created on Sep 17, 2016
@author: jonaswallin
'''
from Mixture.density import mNIG
from Mixture.density.purepython import mNIG as pmNIG
from Mixture import mixOneDims
import numpy as np
import numpy.random as npr
import timeit
# most speed here is used startup (iteration = 500, n = 1000)
# ... |
mixObj.set_data(Y)
paramMat = [npr.randn(2,4),npr.randn(2,4)]
paramMat[0][0,0] = 1.1
paramMat[1][0,0] = -2
alpha = np.array(alpha_true)
for i in range(iteration): # @UnusedVariable
p, alpha, paramMat = mixObj.EMstep(alpha = alpha, paramMat = paramMat , precompute = precompute... | K = 2
d = 2
iteration = 500
mixObj = mixOneDims(K=K, d=d)
if pure_python:
mixObj.set_densites([pmNIG(d=d) for k in range(K)]) # @UnusedVariable
else:
mixObj.set_densites([mNIG(d=d) for k in range(K)]) # @UnusedVariable
paramMat_true = [np.array([[1.1, 1.12, 0.1, 0],
... | identifier_body |
single_page_checkout_with_login_and_register_conf.py | # This file is part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from django.conf import settings
from django.conf.urls import include, url
from django.con... |
urlpatterns = [
url(r'^checkout/$', SinglePageCheckoutViewWithLoginAndRegister.as_view(), name='checkout'),
url(r'^checkout/(?P<phase>.+)/$', SinglePageCheckoutViewWithLoginAndRegister.as_view(), name='checkout'),
url(r'^admin/', include(admin.site.urls)),
url(r'^sa/', include('shuup.admin.urls', nam... | initial_phase = "checkout_method"
phase_specs = [
"shuup.front.checkout.checkout_method:CheckoutMethodPhase",
"shuup.front.checkout.checkout_method:RegisterPhase",
"shuup.front.checkout.addresses:AddressesPhase",
"shuup.front.checkout.methods:MethodsPhase",
"shuup.front.check... | identifier_body |
single_page_checkout_with_login_and_register_conf.py | # This file is part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from django.conf import settings
from django.conf.urls import include, url
from django.con... | url(r'^checkout/(?P<phase>.+)/$', SinglePageCheckoutViewWithLoginAndRegister.as_view(), name='checkout'),
url(r'^admin/', include(admin.site.urls)),
url(r'^sa/', include('shuup.admin.urls', namespace="shuup_admin", app_name="shuup_admin")),
url(r'^api/', include('shuup.api.urls')),
url(r'^', include... |
urlpatterns = [
url(r'^checkout/$', SinglePageCheckoutViewWithLoginAndRegister.as_view(), name='checkout'), | random_line_split |
single_page_checkout_with_login_and_register_conf.py | # This file is part of Shuup.
#
# Copyright (c) 2012-2017, Shoop Commerce Ltd. All rights reserved.
#
# This source code is licensed under the OSL-3.0 license found in the
# LICENSE file in the root directory of this source tree.
from django.conf import settings
from django.conf.urls import include, url
from django.con... | (SinglePageCheckoutView):
initial_phase = "checkout_method"
phase_specs = [
"shuup.front.checkout.checkout_method:CheckoutMethodPhase",
"shuup.front.checkout.checkout_method:RegisterPhase",
"shuup.front.checkout.addresses:AddressesPhase",
"shuup.front.checkout.methods:MethodsPhas... | SinglePageCheckoutViewWithLoginAndRegister | identifier_name |
file_loader.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 mime_classifier::MIMEClassifier;
use net_traits::ProgressMsg::{Payload, Done};
use net_traits::{LoadData, Meta... | let progress_chan = start_sending_sniffed(senders, metadata,
classifier, &buf);
progress_chan.send(Payload(buf)).unwrap();
(read_all(reader, &progress... | let (res, progress_chan) = match res {
Ok(ReadStatus::Partial(buf)) => { | random_line_split |
file_loader.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 mime_classifier::MIMEClassifier;
use net_traits::ProgressMsg::{Payload, Done};
use net_traits::{LoadData, Meta... | (load_data: LoadData, senders: LoadConsumer, classifier: Arc<MIMEClassifier>) {
let url = load_data.url;
assert!(&*url.scheme == "file");
spawn_named("file_loader".to_owned(), move || {
let metadata = Metadata::default(url.clone());
let file_path: Result<PathBuf, ()> = url.to_file_path();
... | factory | identifier_name |
file_loader.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 mime_classifier::MIMEClassifier;
use net_traits::ProgressMsg::{Payload, Done};
use net_traits::{LoadData, Meta... |
Ok(ReadStatus::EOF) | Err(_) =>
(res.map(|_| ()), start_sending(senders, metadata)),
};
progress_chan.send(Done(res)).unwrap();
}
Err(e) => {
let p... | {
let progress_chan = start_sending_sniffed(senders, metadata,
classifier, &buf);
progress_chan.send(Payload(buf)).unwrap();
(read_all(reader, &progre... | conditional_block |
file_loader.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 mime_classifier::MIMEClassifier;
use net_traits::ProgressMsg::{Payload, Done};
use net_traits::{LoadData, Meta... | };
progress_chan.send(Done(res)).unwrap();
}
Err(e) => {
let progress_chan = start_sending(senders, metadata);
progress_chan.send(Done(Err(e.description().to_string()))).unwrap();
... | {
let url = load_data.url;
assert!(&*url.scheme == "file");
spawn_named("file_loader".to_owned(), move || {
let metadata = Metadata::default(url.clone());
let file_path: Result<PathBuf, ()> = url.to_file_path();
match file_path {
Ok(file_path) => {
match F... | identifier_body |
repository.ts | import * as Path from 'path'
import { GitHubRepository, ForkedGitHubRepository } from './github-repository'
import { IAheadBehind } from './branch'
import {
WorkflowPreferences,
ForkContributionTarget,
} from './workflow-preferences'
import { assertNever, fatalError } from '../lib/fatal-error'
import { createEqual... | * Returns the owner/name alias if associated with a GitHub repository,
* otherwise the folder name that contains the repository
*/
export function nameOf(repository: Repository) {
const { gitHubRepository } = repository
return gitHubRepository !== null ? gitHubRepository.fullName : repository.name
}
/**
* Get... | /** | random_line_split |
repository.ts | import * as Path from 'path'
import { GitHubRepository, ForkedGitHubRepository } from './github-repository'
import { IAheadBehind } from './branch'
import {
WorkflowPreferences,
ForkContributionTarget,
} from './workflow-preferences'
import { assertNever, fatalError } from '../lib/fatal-error'
import { createEqual... | (repository: Repository) {
const { gitHubRepository } = repository
return gitHubRepository !== null ? gitHubRepository.fullName : repository.name
}
/**
* Get the GitHub html URL for a repository, if it has one.
* Will return the parent GitHub repository's URL if it has one.
* Otherwise, returns null.
*/
expor... | nameOf | identifier_name |
repository.ts | import * as Path from 'path'
import { GitHubRepository, ForkedGitHubRepository } from './github-repository'
import { IAheadBehind } from './branch'
import {
WorkflowPreferences,
ForkContributionTarget,
} from './workflow-preferences'
import { assertNever, fatalError } from '../lib/fatal-error'
import { createEqual... |
/**
* Attempts to honor the Repository's workflow preference for GitHubRepository contributions.
* Falls back to returning the GitHubRepository when a non-fork repository
* is passed, returns the parent GitHubRepository otherwise.
*/
export function getNonForkGitHubRepository(
repository: RepositoryWithGitHubRe... | {
if (!isRepositoryWithGitHubRepository(repository)) {
return null
}
return getNonForkGitHubRepository(repository).htmlURL
} | identifier_body |
repository.ts | import * as Path from 'path'
import { GitHubRepository, ForkedGitHubRepository } from './github-repository'
import { IAheadBehind } from './branch'
import {
WorkflowPreferences,
ForkContributionTarget,
} from './workflow-preferences'
import { assertNever, fatalError } from '../lib/fatal-error'
import { createEqual... |
return baseName
}
/** Base type for a directory you can run git commands successfully */
export type WorkingTree = {
readonly path: string
}
/** A local repository. */
export class Repository {
public readonly name: string
/**
* The main working tree (what we commonly
* think of as the repository's wo... | {
// the repository is at the root of the drive
// -> show the full path here to show _something_
return path
} | conditional_block |
blindsdevice-change.component.ts | import {Component, OnInit} from '@angular/core';
import {IBlindsDevice} from '../../../../../../server/entities/device.interface';
import {Subscription} from 'rxjs/Subscription';
import {BlindsDeviceCacheService} from '../../../cache/service/blinds-device.cache.service';
import {ActivatedRoute, Router} from '@angular/r... | }));
}
getPortName(port: Port): string {
return portName(port);
}
ngOnDestroy() {
this.subscriptions.forEach(sub => sub.unsubscribe);
}
submit(blind: IBlindsDevice) {
if (this.blind.id) {
blind.id = this.blind.id;
this.blindsCacheService.updateDevice(blind).subscribe(updatedBl... |
this.title = 'Neuer Rollladen anlegen';
}
| conditional_block |
blindsdevice-change.component.ts | import {Component, OnInit} from '@angular/core';
import {IBlindsDevice} from '../../../../../../server/entities/device.interface';
import {Subscription} from 'rxjs/Subscription';
import {BlindsDeviceCacheService} from '../../../cache/service/blinds-device.cache.service';
import {ActivatedRoute, Router} from '@angular/r... |
constructor(private blindsCacheService: BlindsDeviceCacheService,
private route: ActivatedRoute,
private router: Router,
private notificationService: NotificationService,
private digitalPortService: DigitalPortService) {
}
ngOnInit() {
this.unusedInput... | private backlink = '..';
unusedInputPortHandler: PortHandler;
unusedOutputPortHandler: PortHandler; | random_line_split |
blindsdevice-change.component.ts | import {Component, OnInit} from '@angular/core';
import {IBlindsDevice} from '../../../../../../server/entities/device.interface';
import {Subscription} from 'rxjs/Subscription';
import {BlindsDeviceCacheService} from '../../../cache/service/blinds-device.cache.service';
import {ActivatedRoute, Router} from '@angular/r... | blind: IBlindsDevice) {
if (this.blind.id) {
blind.id = this.blind.id;
this.blindsCacheService.updateDevice(blind).subscribe(updatedBlind => {
this.notificationService.info('Rollladen aktualisiert');
this.router.navigate(['../..'], {relativeTo: this.route});
}, error => {
t... | ubmit( | identifier_name |
print_MODFLOW_inputs_res_NWT.py | # -*- coding: utf-8 -*-
"""
Created on Sun Sep 17 22:06:52 2017
Based on: print_MODFLOW_inputs_res_NWT.m
@author: gcng
"""
# print_MODFLOW_inputs
import numpy as np
import MODFLOW_NWT_lib as mf # functions to write individual MODFLOW files
import os # os functions
from ConfigParser import SafeConfigParser
parser ... |
infile_pre = 'test2lay_py';
NLAY = 2;
DZ = [100, 50] # [NLAYx1] [m] ***testing
# DZ = [350, 100] # [NLAYx1] [m] ***testing
# length of transient stress period (follows 1-day steady-state period) [d]
# perlen_tr = 365; # [d], ok if too long
# perlen_tr = 365*5 + ceil(365*5/4); # [d], includes leap years; ok if too l... | GSFLOW_indir = GSFLOW_DIR + '/inputs/MODFLOW_NWT/'
# MODFLOW output files
GSFLOW_outdir = GSFLOW_DIR + '/outputs/MODFLOW_NWT/' | conditional_block |
print_MODFLOW_inputs_res_NWT.py | # -*- coding: utf-8 -*-
"""
Created on Sun Sep 17 22:06:52 2017
Based on: print_MODFLOW_inputs_res_NWT.m
@author: gcng
"""
# print_MODFLOW_inputs
import numpy as np
import MODFLOW_NWT_lib as mf # functions to write individual MODFLOW files
import os # os functions
from ConfigParser import SafeConfigParser
parser ... |
# for various files: ba6, dis, uzf, lpf
surfz_fil = GIS_indir + 'topo.asc'
# surfz_fil = GIS_indir + 'SRTM_new_20161208.asc'
# for various files: ba6, uzf
mask_fil = GIS_indir + 'basinmask_dischargept.asc'
# for sfr
reach_fil = GIS_indir + 'reach_data.txt'
segment_fil_all = [GIS_indir + 'segment_data_4A_INFORMATION_M... |
# use restart file as initial cond (empty string to not use restart file)
fil_res_in = '' # empty string to not use restart file
#fil_res_in = '/home/gcng/workspace/Pfil_res_inrojectFiles/AndesWaterResources/GSFLOW/outputs/MODFLOW/test2lay_melt_30yr.out' % empty string to not use restart file | random_line_split |
movies.js | /**
* Venobo App
*
* @author Marcus S. Abildskov
*/
import mongoose from 'mongoose'
import loadClass from 'mongoose-class-wrapper'
import MovieSchema from './schemas/movies'
class MovieModel {
static getByTmdb(id: String, callback: Function) {
this.findOne({tmdb: id}, callback)
}
static quickSearch(ke... |
static sortByLatest(limit: Number = 20, callback: Function) {
this.find(callback).sort({added: -1}).limit(limit)
}
}
MovieSchema.plugin(loadClass, MovieModel)
export default mongoose.model('Movies', MovieSchema)
| {
this.find({}, callback)
} | identifier_body |
movies.js | /**
* Venobo App
*
* @author Marcus S. Abildskov
*/
import mongoose from 'mongoose'
import loadClass from 'mongoose-class-wrapper'
import MovieSchema from './schemas/movies'
class MovieModel {
static getByTmdb(id: String, callback: Function) { | }
static quickSearch(keyword: String, callback: Function) {
this.find({$text: {$search: keyword}}, callback)
}
static search(data: Object, callback: Function) {
var query = {}
if (data.genres !== 'all') { query.genres = new RegExp(`^${data.genres}$`, 'i') }
if (data.quality !== 'all') { query... | this.findOne({tmdb: id}, callback) | random_line_split |
movies.js | /**
* Venobo App
*
* @author Marcus S. Abildskov
*/
import mongoose from 'mongoose'
import loadClass from 'mongoose-class-wrapper'
import MovieSchema from './schemas/movies'
class MovieModel {
static getByTmdb(id: String, callback: Function) {
this.findOne({tmdb: id}, callback)
}
static quickSearch(ke... | (callback: Function) {
this.find({}, callback)
}
static sortByLatest(limit: Number = 20, callback: Function) {
this.find(callback).sort({added: -1}).limit(limit)
}
}
MovieSchema.plugin(loadClass, MovieModel)
export default mongoose.model('Movies', MovieSchema)
| getAll | identifier_name |
movies.js | /**
* Venobo App
*
* @author Marcus S. Abildskov
*/
import mongoose from 'mongoose'
import loadClass from 'mongoose-class-wrapper'
import MovieSchema from './schemas/movies'
class MovieModel {
static getByTmdb(id: String, callback: Function) {
this.findOne({tmdb: id}, callback)
}
static quickSearch(ke... |
if (data.quality !== 'all') { query.torrents = {$exists: data.quality} }
if (data.rating !== '0') { query.rating = {$gt: data.rating} }
if (data.keyword !== '') { query.$text = {$search: data.keyword} }
var orderBy = {
year: {year: 1},
rating: {rating: 1},
views: {views: 1},
li... | { query.genres = new RegExp(`^${data.genres}$`, 'i') } | conditional_block |
tests_verifier.py | import os
from verifier import Verifier
import verifier
import unittest
# Verification tests
import json
import codecs
TASK_FILE = '201606231548.json'
with codecs.open(TASK_FILE, mode='r', encoding='utf-8') as file: | class TestVerifer(unittest.TestCase):
def test_handle_errors(self):
l1 = verifier.send_to_retry
verifier.handle_errors()
l2 = verifier.send_to_retry
self.assertGreater(len(l1), len(l2))
self.assertEqual(len(l2), len(l1) + len(run_info['error_list']))
def test_get_path_fr... | run_info = json.load(file)
v = Verifier()
| random_line_split |
tests_verifier.py | import os
from verifier import Verifier
import verifier
import unittest
# Verification tests
import json
import codecs
TASK_FILE = '201606231548.json'
with codecs.open(TASK_FILE, mode='r', encoding='utf-8') as file:
run_info = json.load(file)
v = Verifier()
class TestVerifer(unittest.TestCase):
def test_han... | (self):
path = v.get_path_from_url('http://staging.osf.io/mst3k')
self.assertTrue(os.path.exists(path))
def test_generate_page_dictionary(self):
d1 = v.generate_page_dictionary('wiki/')
self.assertGreater(len(d1), 0)
if __name__ == '__main__':
unittest.main()
| test_get_path_from_url | identifier_name |
tests_verifier.py | import os
from verifier import Verifier
import verifier
import unittest
# Verification tests
import json
import codecs
TASK_FILE = '201606231548.json'
with codecs.open(TASK_FILE, mode='r', encoding='utf-8') as file:
run_info = json.load(file)
v = Verifier()
class TestVerifer(unittest.TestCase):
def test_han... | unittest.main() | conditional_block | |
tests_verifier.py | import os
from verifier import Verifier
import verifier
import unittest
# Verification tests
import json
import codecs
TASK_FILE = '201606231548.json'
with codecs.open(TASK_FILE, mode='r', encoding='utf-8') as file:
run_info = json.load(file)
v = Verifier()
class TestVerifer(unittest.TestCase):
def test_han... |
def test_get_path_from_url(self):
path = v.get_path_from_url('http://staging.osf.io/mst3k')
self.assertTrue(os.path.exists(path))
def test_generate_page_dictionary(self):
d1 = v.generate_page_dictionary('wiki/')
self.assertGreater(len(d1), 0)
if __name__ == '__main__':
u... | l1 = verifier.send_to_retry
verifier.handle_errors()
l2 = verifier.send_to_retry
self.assertGreater(len(l1), len(l2))
self.assertEqual(len(l2), len(l1) + len(run_info['error_list'])) | identifier_body |
tests.rs | #![deny(warnings)]
#![allow(unstable)]
extern crate cargo;
extern crate flate2;
extern crate git2;
extern crate hamcrest;
extern crate serialize;
extern crate tar;
extern crate term;
extern crate url;
#[macro_use]
extern crate log;
mod support;
macro_rules! test {
($name:ident $expr:expr) => (
#[test]
... | mod test_cargo_search;
mod test_cargo_test;
mod test_cargo_version;
mod test_shell; | mod test_cargo_publish;
mod test_cargo_registry;
mod test_cargo_run; | random_line_split |
exists_movie.py | from __future__ import unicode_literals, division, absolute_import
import os
import re
import logging
from path import path
from flexget import plugin
from flexget.event import event
from flexget.config_schema import one_or_more
from flexget.plugin import get_plugin_by_name
from flexget.utils.tools import TimedDict
... | ():
plugin.register(FilterExistsMovie, 'exists_movie', groups=['exists'], api_ver=2)
| register_plugin | identifier_name |
exists_movie.py | from __future__ import unicode_literals, division, absolute_import
import os
import re
import logging
from path import path
from flexget import plugin
from flexget.event import event
from flexget.config_schema import one_or_more
from flexget.plugin import get_plugin_by_name
from flexget.utils.tools import TimedDict
... |
else:
key = 'movie_name'
if not entry.get('movie_name', eval_lazy=False):
movie = get_plugin_by_name('parsing').instance.parse_movie(entry['title'])
entry['movie_name'] = movie.name
# actual filtering
if entry... | key = 'imdb_id'
if not entry.get('imdb_id', eval_lazy=False):
try:
imdb_lookup.lookup(entry)
except plugin.PluginError as e:
log.trace('entry %s imdb failed (%s)' % (entry['title'], e.value))
... | conditional_block |
exists_movie.py | from __future__ import unicode_literals, division, absolute_import
import os
import re
import logging
from path import path
from flexget import plugin
from flexget.event import event
from flexget.config_schema import one_or_more
from flexget.plugin import get_plugin_by_name
from flexget.utils.tools import TimedDict
... | plugin.register(FilterExistsMovie, 'exists_movie', groups=['exists'], api_ver=2) | identifier_body | |
exists_movie.py | from __future__ import unicode_literals, division, absolute_import
import os
import re
import logging
from path import path
from flexget import plugin
from flexget.event import event
from flexget.config_schema import one_or_more
from flexget.plugin import get_plugin_by_name
from flexget.utils.tools import TimedDict
... | try:
imdb_id = imdb_lookup.imdb_id_lookup(movie_title=movie.name,
raw_title=item,
session=task.session)
if imdb_id in path_ids:
... | movie = get_plugin_by_name('parsing').instance.parse_movie(item)
if config.get('lookup') == 'imdb': | random_line_split |
tunnelFactory.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
this._register(tunnelService.setTunnelProvider({
forwardPort: async (tunnelOptions: TunnelOptions, tunnelCreationOptions: TunnelCreationOptions): Promise<RemoteTunnel | undefined> => {
let tunnelPromise: Promise<ITunnel> | undefined;
try {
tunnelPromise = tunnelFactory(tunnelOptions, tunnelCrea... | {
privacyOptions = [
{
id: 'private',
label: nls.localize('tunnelPrivacy.private', "Private"),
themeIcon: 'lock'
},
{
id: 'public',
label: nls.localize('tunnelPrivacy.public', "Public"),
themeIcon: 'eye'
}
];
} | conditional_block |
tunnelFactory.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | }
}));
const tunnelInformation = environmentService.options?.tunnelProvider?.features ?
{
features: {
elevation: !!environmentService.options?.tunnelProvider?.features?.elevation,
public: !!environmentService.options?.tunnelProvider?.features?.public,
privacyOptions
}
} : u... | privacy: tunnel.privacy ?? (tunnel.public ? TunnelPrivacyId.Public : TunnelPrivacyId.Private),
protocol: tunnel.protocol ?? TunnelProtocol.Http,
dispose: async () => { await tunnel.dispose(); }
};
return remoteTunnel; | random_line_split |
tunnelFactory.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
this._register(tunnelService.setTunnelProvider({
forwardPort: async (tunnelOptions: TunnelOptions, tunnelCreationOptions: TunnelCreationOptions): Promise<RemoteTunnel | undefined> => {
let tunnelPromise: Promise<ITunnel> | undefined;
try {
tunnelPromise = tunnelFactory(tunnelOptions, tunnelCreat... | {
super();
const tunnelFactory = environmentService.options?.tunnelProvider?.tunnelFactory;
if (tunnelFactory) {
let privacyOptions = environmentService.options?.tunnelProvider?.features?.privacyOptions ?? [];
if (environmentService.options?.tunnelProvider?.features?.public
&& (privacyOptions.length ===... | identifier_body |
tunnelFactory.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (
@ITunnelService tunnelService: ITunnelService,
@IBrowserWorkbenchEnvironmentService environmentService: IBrowserWorkbenchEnvironmentService,
@IOpenerService private openerService: IOpenerService,
@IRemoteExplorerService remoteExplorerService: IRemoteExplorerService,
@ILogService logService: ILogService
) {... | constructor | identifier_name |
compreseguros_com_spider.py | import datetime, time
import logging
# Remove below package when publishing
from scrapy.utils.response import open_in_browser
class CompresegurosComSpider(scrapy.Spider):
name = "compreseguros_com_spider"
start_urls = ['https://www.compreseguros.com/']
handle_httpstatus_list = [302]
#custom_settings = {'DOWNLOA... |
import json, re, collections | random_line_split | |
compreseguros_com_spider.py | Content-Type'] = 'application/x-www-form-urlencoded'
headers['Cache-Control:'] = "max-age=0"
headers['Accept'] = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"
headers['Accept-Encoding'] = "gzip, deflate, br"
def __init__(self, categories=None, *args, **kwargs):
super(CompresegurosC... | convert | identifier_name | |
compreseguros_com_spider.py | Spider(scrapy.Spider):
name = "compreseguros_com_spider"
start_urls = ['https://www.compreseguros.com/']
handle_httpstatus_list = [302]
#custom_settings = {'DOWNLOAD_DELAY' : 10}
headers = {}
headers['Upgrade-Insecure-Requests'] = "1"
headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWeb... |
# CHEVROLET---AGILE*1.4*LS*L/14---2016---40---12---163---120462---LA*PAMPA---LOS*OLIVOS---8203
def parse(self, response):
logging.info("I am called from parse method")
for index, param in enumerate(self.sub_urls):
print param
url = "https://www.compreseguros.com/seguros-de-autos"
formdata = {}
... | super(CompresegurosComSpider, self).__init__(*args, **kwargs)
#pass
if not categories:
raise CloseSpider('Received no categories!')
else:
self.categories = categories
self.sub_urls = loads(self.categories).keys() | identifier_body |
compreseguros_com_spider.py | "1"
headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'
headers['Content-Type'] = 'application/x-www-form-urlencoded'
headers['Cache-Control:'] = "max-age=0"
headers['Accept'] = "text/html,application/xhtml+xml,application/xml... | return "La Holando" | conditional_block | |
instructor-course-enroll-page.component.spec.ts | import { HttpClientTestingModule } from '@angular/common/http/testing';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { HotTableModule } from '@handsontable/angular';
import { AjaxLoadingModule } from '../../components/aja... | imports: [
HttpClientTestingModule,
HotTableModule,
RouterTestingModule,
AjaxPreloadModule,
AjaxLoadingModule,
StatusMessageModule,
LoadingSpinnerModule,
LoadingRetryModule,
PanelChevronModule,
],
})
.compileComponents();
}));... | let fixture: ComponentFixture<InstructorCourseEnrollPageComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [InstructorCourseEnrollPageComponent], | random_line_split |
resource.js | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'... | extends models['BaseResource'] {
/**
* Create a Resource.
* @member {string} [id] The resource identifier.
* @member {string} [name] The resource name.
* @member {string} [type] The resource type.
* @member {string} [location] The resource location.
* @member {object} [tags] The resource tags.
*... | Resource | identifier_name |
resource.js | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'... | type: {
name: 'String'
}
},
type: {
required: false,
readOnly: true,
serializedName: 'type',
type: {
name: 'String'
}
},
location: {
required: false,
... | {
return {
required: false,
serializedName: 'Resource',
type: {
name: 'Composite',
className: 'Resource',
modelProperties: {
id: {
required: false,
readOnly: true,
serializedName: 'id',
type: {
name: 'S... | identifier_body |
resource.js | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'... | readOnly: true,
serializedName: 'name',
type: {
name: 'String'
}
},
type: {
required: false,
readOnly: true,
serializedName: 'type',
type: {
name: 'String'
}
... | name: {
required: false, | random_line_split |
util-sha1.js | /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* SHA-1 implementation in JavaScript (c) Chris Veness 2002-2014 / MIT Licence */
/* */
/* - see http://... | H2 = (H2+c) & 0xffffffff;
H3 = (H3+d) & 0xffffffff;
H4 = (H4+e) & 0xffffffff;
}
return Sha1.toHexStr(H0) + Sha1.toHexStr(H1) + Sha1.toHexStr(H2) +
Sha1.toHexStr(H3) + Sha1.toHexStr(H4);
};
/**
* Function 'f' [§4.1.1].
* @private
*/
Sha1.f = function(s, x, y, z) {
sw... | H1 = (H1+b) & 0xffffffff; | random_line_split |
util-sha1.js | /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* SHA-1 implementation in JavaScript (c) Chris Veness 2002-2014 / MIT Licence */
/* */
/* - see http://... | - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
if (typeof module != 'undefined' && module.exports) module.exports = Sha1; // CommonJs export
if (typeof define == 'function' && define.amd) define([], function() { return Sha1; }); // AMD | .prototype.utf8Decode = function() {
try {
return decodeURIComponent( escape( this ) );
} catch (e) {
return this; // invalid UTF-8? return as-is
}
};
}
/* - - - | conditional_block |
__init__.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from .. import config as _config
class Conf(_config.ConfigNamespace):
| )
replace_inplace = _config.ConfigItem(
False,
'Always use in-place update of a table column when using setitem, '
"e.g. t['a'] = value. This overrides the default behavior of "
"replacing the column entirely with the new value when possible. "
"This configuration op... | """
Configuration parameters for `astropy.table`.
"""
auto_colname = _config.ConfigItem(
'col{0}',
'The template that determines the name of a column if it cannot be '
'determined. Uses new-style (format method) string formatting.',
aliases=['astropy.table.column.auto_colnam... | identifier_body |
__init__.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from .. import config as _config
class Conf(_config.ConfigNamespace):
"""
Configuration parameters for `astropy.table`.
"""
auto_colname = _config.ConfigItem(
'col{0}',
'The template that determines the name of a column ... | ['slice'],
'List of conditions for issuing a warning when replacing a table '
"column using setitem, e.g. t['a'] = value. Allowed options are "
"'always', 'slice', 'refcount', 'attributes'.",
'list',
)
replace_inplace = _config.ConfigItem(
False,
'Alw... | 'table-striped table-bordered table-condensed',
'The table class to be used in Jupyter notebooks when displaying '
'tables (and not overridden). See <http://getbootstrap.com/css/#tables '
'for a list of useful bootstrap classes.')
replace_warnings = _config.ConfigItem( | random_line_split |
__init__.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
from .. import config as _config
class | (_config.ConfigNamespace):
"""
Configuration parameters for `astropy.table`.
"""
auto_colname = _config.ConfigItem(
'col{0}',
'The template that determines the name of a column if it cannot be '
'determined. Uses new-style (format method) string formatting.',
aliases=['a... | Conf | identifier_name |
difference.js | var baseDifference = require('../internal/baseDifference'),
baseFlatten = require('../internal/baseFlatten'),
isArguments = require('../lang/isArguments'),
isArray = require('../lang/isArray'),
restParam = require('../function/restParam');
/**
* Creates an array excluding all values of the prov... | * @memberOf _
* @category Array
* @param {Array} array The array to inspect.
* @param {...Array} [values] The arrays of values to exclude.
* @returns {Array} Returns the new array of filtered values.
* @example
*
* _.difference([1, 2, 3], [4, 2]);
* // => [1, 3]
*/
var difference = restParam(functio... | random_line_split | |
searchNReplace.benchmark.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | replaceSuite.run();
} | }
});
}
| random_line_split |
searchNReplace.benchmark.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | else {
const chunk = generateRandomChunkWithLF(64 * 1000, 64 * 1000);
// try to avoid OOM
for (let j = 0; j < chunkCnt; j++) {
chunks.push(Buffer.from(chunk + j).toString());
}
}
const replaceSuite = new BenchmarkSuite({
name: `File Size: ${fileSize}Byte`,
iterations: 10
});
const edits = generate... | {
chunks.push(generateRandomChunkWithLF(fileSize, fileSize));
} | conditional_block |
setup.py | # -*- coding:utf-8 -*-
from setuptools import setup
setup(
name = "mobileclick",
description = "mobileclick provides baseline methods and utility scripts for the NTCIR-12 MobileClick-2 task",
author = "Makoto P. Kato",
author_email = "kato@dl.kuis.kyoto-u.ac.jp",
license = "MIT Lice... | entry_points = {
'console_scripts': [
'mobileclick_download_training_data=mobileclick.scripts.mobileclick_download_training_data:main',
'mobileclick_download_test_data=mobileclick.scripts.mobileclick_download_test_data:main',
'mobileclick_random_ranking_method=mobileclick... | 'nltk>=3.1',
'numpy'], | random_line_split |
calendar-sk-utf8.js | // Calendar SK language
// Author: Peter Valach (pvalach@gmx.net)
// Encoding: utf-8
// Last update: 2003/10/29
// full day names
Calendar._DN = new Array
("NedeÄľa",
"Pondelok",
"Utorok",
"Streda",
"Ĺ tvrtok",
"Piatok",
"Sobota",
"NedeÄľa");
// short day names
Calendar._SDN = new Array
("Ned",
"Pon",
"Uto",... | "Mar",
"Apr",
"Máj",
"JĂşn",
"JĂşl",
"Aug",
"Sep",
"Okt",
"Nov",
"Dec");
// tooltips
Calendar._TT = {};
Calendar._TT["INFO"] = "O kalendári";
Calendar._TT["ABOUT"] =
"DHTML Date/Time Selector\n" +
"(c) dynarch.com 2002-2005 / Author: Mihai Bazon\n" +
"Poslednú verziu nájdete na: http://www.dynarch.com/p... | "Feb", | random_line_split |
setup.py | import os
from setuptools import find_packages, setup
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='orgwolf',
version='0... | author='Your Name',
author_email='yourname@example.com',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Framework :: Django :: X.Y', # replace "X.Y" as appropriate
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License', ... | random_line_split | |
parviewer.rs | /*!
# ParView
*/
#![deny(non_camel_case_types)]
#![deny(unused_parens)]
#![deny(non_upper_case_globals)]
#![deny(unused_qualifications)]
#![deny(missing_docs)]
#![deny(unused_results)]
extern crate docopt;
extern crate parview;
extern crate serde;
use docopt::Docopt;
use serde::Deserialize;
use std::error::Error;
us... | let (frames, palette): (Vec<Frame>, Palette) = if args.flag_generate {
let frames = misc::generate_frame(path)?;
let palette = match args.flag_palette {
None => Default::default(),
Some(fname) => {
let palette_path: &Path = Path::new(&fname[..]);
... | {
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.deserialize())
.unwrap_or_else(|e| e.exit());
let toml_config: TomlConfig = match args.flag_config {
None => Default::default(),
Some(ref fname) => {
let path: &Path = Path::new(&fname[..]);
misc::load_... | identifier_body |
parviewer.rs | /*!
# ParView
*/
#![deny(non_camel_case_types)]
#![deny(unused_parens)]
#![deny(non_upper_case_globals)]
#![deny(unused_qualifications)]
#![deny(missing_docs)]
#![deny(unused_results)]
extern crate docopt;
extern crate parview;
extern crate serde;
use docopt::Docopt;
use serde::Deserialize;
use std::error::Error;
us... | None => "test_frame.json",
};
let path: &Path = Path::new(fname);
let (frames, palette): (Vec<Frame>, Palette) = if args.flag_generate {
let frames = misc::generate_frame(path)?;
let palette = match args.flag_palette {
None => Default::default(),
Some(fname) ... | let fname: &str = match args.arg_file {
Some(ref s) => s, | random_line_split |
parviewer.rs | /*!
# ParView
*/
#![deny(non_camel_case_types)]
#![deny(unused_parens)]
#![deny(non_upper_case_globals)]
#![deny(unused_qualifications)]
#![deny(missing_docs)]
#![deny(unused_results)]
extern crate docopt;
extern crate parview;
extern crate serde;
use docopt::Docopt;
use serde::Deserialize;
use std::error::Error;
us... | () -> Result<(), Box<dyn Error>> {
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.deserialize())
.unwrap_or_else(|e| e.exit());
let toml_config: TomlConfig = match args.flag_config {
None => Default::default(),
Some(ref fname) => {
let path: &Path = Path::new(&fn... | run | identifier_name |
common.js | If set, checks if there are at least flags.minlength number of characters.
// flags.maxlength If set, checks if there are at most flags.maxlength number of characters.
flags = (typeof flags == "object") ? flags : {};
// test for text
if(/^\s*$/.test(value)){ return false; } // Boolean
// length test... | assign default values to missing paramters
flags = (typeof flags == "object") ? flags : {};
var max = (typeof flags.max == "number") ? flags.max : Infinity;
var min = (typeof flags.min == "number") ? flags.min : -Infinity;
var dec = (typeof flags.decimal == "string") ? flags.decimal : ".";
// splice out an... | eturn false; // Boolean
}
// | conditional_block |
common.js | If set, checks if there are at least flags.minlength number of characters.
// flags.maxlength If set, checks if there are at most flags.maxlength number of characters.
flags = (typeof flags == "object") ? flags : {};
// test for text
if(/^\s*$/.test(value)){ return false; } // Boolean
// length test... | // flags.signed The leading plus-or-minus sign. Can be true, false, or [true, false].
// Default is [true, false], (i.e. sign is optional).
// flags.symbol A currency symbol such as Yen "�", Pound "�", or the Euro sign "�".
// Default is "$". For more than one symbol use an array, e.g. ["$", ""... | // summary:
// Validates whether a string denotes a monetary value.
// value: A string
// flags: {signed:Boolean|[true,false], symbol:String, placement:String, separator:String,
// fractional:Boolean|[true,false], decimal:String}
| random_line_split |
todoCtrl.js | /*global angular */
/**
* The main controller for the app. The controller:
* - retrieves and persists the model via the todoStorage service
* - exposes the model to the template and provides event handlers
*/
angular.module('todomvc')
.controller('TodoCtrl', function TodoCtrl($scope, $routeParams, $filter, store)... | $scope.allChecked = !$scope.remainingCount;
}, true);
// Monitor the current route for changes and adjust the filter accordingly.
$scope.$on('$routeChangeSuccess', function () {
var status = $scope.status = $routeParams.status || '';
$scope.statusFilter = (status === 'active') ?
{ completed: false ... |
$scope.$watch('todos', function () {
$scope.remainingCount = $filter('filter')(todos, { completed: false }).length;
$scope.completedCount = todos.length - $scope.remainingCount; | random_line_split |
todoCtrl.js | /*global angular */
/**
* The main controller for the app. The controller:
* - retrieves and persists the model via the todoStorage service
* - exposes the model to the template and provides event handlers
*/
angular.module('todomvc')
.controller('TodoCtrl', function TodoCtrl($scope, $routeParams, $filter, store)... |
$scope.saving = true;
store.insert(newTodo)
.then(function success() {
$scope.newTodo = '';
})
.finally(function () {
$scope.saving = false;
});
};
$scope.editTodo = function (todo) {
$scope.editedTodo = todo;
// Clone the original todo to restore it on demand.
$scope.ori... | {
return;
} | conditional_block |
autocomplete.js | $(document).ready(function(e) {
$(".list-item #add-city").click(function(e){
e.preventDefault();
$('#autocomplete').css('display','block');
$('.tt-input').focus();
});
$("#filters").on('click', 'a.remove-city', function(e) {
e.preventDefault();
var gid = $(this).closest('.list-item').find('a').... | // add the city to the nav and blank/hide the autocomplete form
$('#city-list .list-item:last-child').before(place_div);
$('#autocomplete').css('display','none');
$('#name').typeahead('val', '');
$('#city-list .list-item:last').prev().find('a.active').trigger('click');
// save user location pre... | {
if (place.properties.layer == 'borough') {
place_name = place.properties.borough;
place_gid = place.properties.borough_gid;
} else if (place.properties.layer == 'localadmin') {
place_name = place.properties.localadmin;
place_gid = place.properties.localadmin_gid;
} else if (place.p... | identifier_body |
autocomplete.js | $(document).ready(function(e) {
$(".list-item #add-city").click(function(e){
e.preventDefault();
$('#autocomplete').css('display','block');
$('.tt-input').focus();
});
$("#filters").on('click', 'a.remove-city', function(e) {
e.preventDefault();
var gid = $(this).closest('.list-item').find('a').... | ($e, place) {
if (place.properties.layer == 'borough') {
place_name = place.properties.borough;
place_gid = place.properties.borough_gid;
} else if (place.properties.layer == 'localadmin') {
place_name = place.properties.localadmin;
place_gid = place.properties.localadmin_gid;
} else... | onSelected | identifier_name |
autocomplete.js | $(document).ready(function(e) {
$(".list-item #add-city").click(function(e){
e.preventDefault();
$('#autocomplete').css('display','block');
$('.tt-input').focus();
});
$("#filters").on('click', 'a.remove-city', function(e) {
e.preventDefault();
var gid = $(this).closest('.list-item').find('a').... | } else if (place.properties.layer == 'region') {
place_name = place.properties.region;
place_gid = place.properties.region_gid;
} else {
place_name = place.properties.locality;
place_gid = place.properties.locality_gid;
}
var place_div = '<div class="list-item">'
+ '<a... | place_name = place.properties.borough;
place_gid = place.properties.borough_gid;
} else if (place.properties.layer == 'localadmin') {
place_name = place.properties.localadmin;
place_gid = place.properties.localadmin_gid; | random_line_split |
autocomplete.js | $(document).ready(function(e) {
$(".list-item #add-city").click(function(e){
e.preventDefault();
$('#autocomplete').css('display','block');
$('.tt-input').focus();
});
$("#filters").on('click', 'a.remove-city', function(e) {
e.preventDefault();
var gid = $(this).closest('.list-item').find('a').... | else {
place_name = place.properties.locality;
place_gid = place.properties.locality_gid;
}
var place_div = '<div class="list-item">'
+ '<a href="#" data-cat="gid" data-filter="' + place_gid + '" class="active"> '
+ place_name + '</a> '
+ '<a href="#" class="remove-ci... | {
place_name = place.properties.region;
place_gid = place.properties.region_gid;
} | conditional_block |
gschemas.py | import glob
import os
from distutils.dep_util import newer
from distutils.core import Command
from distutils.spawn import find_executable
from distutils.util import change_root
class build_gschemas(Command):
"""build message catalog files
Build message catalog (.mo) files from .po files using xgettext
... |
def run(self):
if not self.skip_build:
self.run_command('build_gschemas')
src = os.path.join(self.build_base, 'share', 'glib-2.0', 'schemas')
dest = os.path.join(self.install_base, 'share', 'glib-2.0', 'schemas')
if self.root != None:
dest = change_root(self... | self.set_undefined_options('build', ('build_base', 'build_base'))
self.set_undefined_options(
'install',
('root', 'root'),
('install_base', 'install_base'),
('skip_build', 'skip_build')) | identifier_body |
gschemas.py | import glob
import os
from distutils.dep_util import newer
from distutils.core import Command
from distutils.spawn import find_executable
from distutils.util import change_root
class build_gschemas(Command):
"""build message catalog files
Build message catalog (.mo) files from .po files using xgettext
... |
src = os.path.join(self.build_base, 'share', 'glib-2.0', 'schemas')
dest = os.path.join(self.install_base, 'share', 'glib-2.0', 'schemas')
if self.root != None:
dest = change_root(self.root, dest)
self.copy_tree(src, dest)
self.spawn(['glib-compile-schemas', dest])
... | self.run_command('build_gschemas') | conditional_block |
gschemas.py | import glob
import os
from distutils.dep_util import newer
from distutils.core import Command
from distutils.spawn import find_executable
from distutils.util import change_root
class build_gschemas(Command):
"""build message catalog files
Build message catalog (.mo) files from .po files using xgettext
... | ('skip_build', 'skip_build'))
def run(self):
if not self.skip_build:
self.run_command('build_gschemas')
src = os.path.join(self.build_base, 'share', 'glib-2.0', 'schemas')
dest = os.path.join(self.install_base, 'share', 'glib-2.0', 'schemas')
if self.root != ... | ('root', 'root'),
('install_base', 'install_base'), | random_line_split |
gschemas.py | import glob
import os
from distutils.dep_util import newer
from distutils.core import Command
from distutils.spawn import find_executable
from distutils.util import change_root
class build_gschemas(Command):
"""build message catalog files
Build message catalog (.mo) files from .po files using xgettext
... | (self):
self.gschemas_directory = self.distribution.gschemas
self.set_undefined_options('build', ('build_base', 'build_base'))
def run(self):
if find_executable("glib-compile-schemas") is None:
raise SystemExit("Error: 'glib-compile-schemas' not found.")
basepath = os.pa... | finalize_options | identifier_name |
test.py | #!/usr/bin/env python
# Copyright (c) 2006 Damien Miller <djm@mindrot.org>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED ... |
if __name__ == '__main__':
main()
| unittest.main() | identifier_body |
test.py | #!/usr/bin/env python
# Copyright (c) 2006 Damien Miller <djm@mindrot.org>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED ... | (self):
for b, a, score in test_vectors:
self.assertEqual(editdist.distance(a, b), score)
def test_02__fuzz(self):
for i in range(0, 32) + range(128, 1024, 128):
for j in range(0, 32):
a = randstring(i)
b = randstring(j)
dist = editdist.distance(a, b)
self.assert_(dist >= 0)
def main():
un... | test_01__reversed_test_vectors | identifier_name |
test.py | #!/usr/bin/env python
# Copyright (c) 2006 Damien Miller <djm@mindrot.org>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED ... | ( 'abc', 'abc', 0 ),
( 'abc', 'ab', 1 ),
( 'abc', 'abcd', 1 ),
( 'abc', 'bc', 1 ),
( 'abc', 'a', 2 ),
( 'abc', '', 3 ),
( '', '', 0 ),
( 'abc', 'acx', 2 ),
( 'abc', 'acxx', 3 ),
( 'abc', 'bcd', 2 ),
( 'a' * 1000, 'a' * 1000, 0 ),
( 'a' * 1000, 'b' * 1000, 1000),
)
def randstring(l):
a = "abcd... | test_vectors = ( | random_line_split |
test.py | #!/usr/bin/env python
# Copyright (c) 2006 Damien Miller <djm@mindrot.org>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED ... |
def test_01__reversed_test_vectors(self):
for b, a, score in test_vectors:
self.assertEqual(editdist.distance(a, b), score)
def test_02__fuzz(self):
for i in range(0, 32) + range(128, 1024, 128):
for j in range(0, 32):
a = randstring(i)
b = randstring(j)
dist = editdist.distance(a, b)
sel... | self.assertEqual(editdist.distance(a, b), score) | conditional_block |
model.py | """
Implementation of model
"""
import numpy as np
import numpy.random as npr
from scipy import ndimage
from configuration import get_config
config = get_config()
class LatticeState(object):
""" Treat 1D list as 2D lattice and handle coupled system
This helps with simply passing this object to scipy's... | )
for j in range(self.width):
for i in range(self.height):
next_camp[i, j] = -config.gamma * camp[i, j] \
+ config.r * self.state_matrix[i, j] \
+ config.D * laplacian_conv[i, j]
if exci[i, j] < config.e_max:
... | """ Return corresponding ODE
Structure:
[
camp00, camp01, .. ,camp0m, camp10, .., campnm
...
exci00, exci01, .. ,exci0m, exci10, .., excinm
]
"""
# parse ODE state
camp, exci = self._state_vec2camp_exci(state)
... | identifier_body |
model.py | """
Implementation of model
"""
import numpy as np
import numpy.random as npr
from scipy import ndimage
from configuration import get_config
config = get_config()
class LatticeState(object):
""" Treat 1D list as 2D lattice and handle coupled system
This helps with simply passing this object to scipy's... | (self, i, j):
""" Handle cell where state_matrix == 1
"""
self.tau_matrix[i, j] += config.dt
if self.tau_matrix[i, j] >= 0: # end of firing reached
self.state_matrix[i, j] = 0
self.tau_matrix[i, j] = -config.t_arp
def handle_off_cell(self, i, j, camp, exci):... | handle_on_cell | identifier_name |
model.py | """
Implementation of model
"""
import numpy as np
import numpy.random as npr
from scipy import ndimage
from configuration import get_config
config = get_config()
class LatticeState(object):
""" Treat 1D list as 2D lattice and handle coupled system
This helps with simply passing this object to scipy's... |
def handle_on_cell(self, i, j):
""" Handle cell where state_matrix == 1
"""
self.tau_matrix[i, j] += config.dt
if self.tau_matrix[i, j] >= 0: # end of firing reached
self.state_matrix[i, j] = 0
self.tau_matrix[i, j] = -config.t_arp
def handle_off_cell(... | for i in range(self.height):
if self.state_matrix[i, j] == 0: # not firing
self.handle_off_cell(i, j, camp, exci)
else: # firing
self.handle_on_cell(i, j) | conditional_block |
model.py | """
Implementation of model
"""
import numpy as np
import numpy.random as npr
from scipy import ndimage
from configuration import get_config
config = get_config()
class LatticeState(object):
""" Treat 1D list as 2D lattice and handle coupled system
This helps with simply passing this object to scipy's... | """
# parse ODE state
camp, exci = self._state_vec2camp_exci(state)
# compute next iteration
self._update_state_matrix(camp, exci)
next_camp = np.zeros((self.width, self.height))
next_exci = np.zeros((self.width, self.height))
laplacian_conv = ndimage.c... | [
camp00, camp01, .. ,camp0m, camp10, .., campnm
...
exci00, exci01, .. ,exci0m, exci10, .., excinm
] | random_line_split |
tac.rs | #[macro_use]
mod common;
use common::util::*;
static UTIL_NAME: &'static str = "tac";
#[test]
fn test_stdin_default() {
let (_, mut ucmd) = testing(UTIL_NAME);
let result = ucmd.run_piped_stdin("100\n200\n300\n400\n500");
assert_eq!(result.stdout, "500400\n300\n200\n100\n");
}
#[test]
fn test_stdin_non_... | let (at, mut ucmd) = testing(UTIL_NAME);
let result = ucmd.args(&["-s", ":", "delimited_primes.txt"]).run();
assert_eq!(result.stdout, at.read("delimited_primes.expected"));
}
#[test]
fn test_single_non_newline_separator_before() {
let (at, mut ucmd) = testing(UTIL_NAME);
let result = ucmd.args(&["... | random_line_split | |
tac.rs | #[macro_use]
mod common;
use common::util::*;
static UTIL_NAME: &'static str = "tac";
#[test]
fn test_stdin_default() {
let (_, mut ucmd) = testing(UTIL_NAME);
let result = ucmd.run_piped_stdin("100\n200\n300\n400\n500");
assert_eq!(result.stdout, "500400\n300\n200\n100\n");
}
#[test]
fn test_stdin_non_... |
#[test]
fn test_single_default() {
let (at, mut ucmd) = testing(UTIL_NAME);
let result = ucmd.arg("prime_per_line.txt").run();
assert_eq!(result.stdout, at.read("prime_per_line.expected"));
}
#[test]
fn test_single_non_newline_separator() {
let (at, mut ucmd) = testing(UTIL_NAME);
let result = uc... | {
let (_, mut ucmd) = testing(UTIL_NAME);
let result = ucmd.args(&["-b", "-s", ":"]).run_piped_stdin("100:200:300:400:500");
assert_eq!(result.stdout, "500:400:300:200:100");
} | identifier_body |
tac.rs | #[macro_use]
mod common;
use common::util::*;
static UTIL_NAME: &'static str = "tac";
#[test]
fn test_stdin_default() {
let (_, mut ucmd) = testing(UTIL_NAME);
let result = ucmd.run_piped_stdin("100\n200\n300\n400\n500");
assert_eq!(result.stdout, "500400\n300\n200\n100\n");
}
#[test]
fn test_stdin_non_... | () {
let (at, mut ucmd) = testing(UTIL_NAME);
let result = ucmd.args(&["-s", ":", "delimited_primes.txt"]).run();
assert_eq!(result.stdout, at.read("delimited_primes.expected"));
}
#[test]
fn test_single_non_newline_separator_before() {
let (at, mut ucmd) = testing(UTIL_NAME);
let result = ucmd.arg... | test_single_non_newline_separator | identifier_name |
Babel.py | import sublime
import sublime_plugin
import json
from os.path import dirname, realpath, join
from .node_bridge import node_bridge
# monkeypatch `Region` to be iterable
sublime.Region.totuple = lambda self: (self.a, self.b)
sublime.Region.__iter__ = lambda self: self.totuple().__iter__()
BIN_PATH = join(sublime.packa... |
return selected_text
def has_selection(self):
for sel in self.view.sel():
start, end = sel
if start != end:
return True
return False
def get_setting(self, key):
settings = self.view.settings().get('Babel')
if settings is None:
settings = sublime.load_settings('Babel.sublime-settings')
retu... | selected_text = selected_text + self.view.substr(region) + '\n' | conditional_block |
Babel.py | import sublime
import sublime_plugin | # monkeypatch `Region` to be iterable
sublime.Region.totuple = lambda self: (self.a, self.b)
sublime.Region.__iter__ = lambda self: self.totuple().__iter__()
BIN_PATH = join(sublime.packages_path(), dirname(realpath(__file__)), 'babel-transform.js')
class BabelCommand(sublime_plugin.TextCommand):
def run(self, edit)... | import json
from os.path import dirname, realpath, join
from .node_bridge import node_bridge
| random_line_split |
Babel.py | import sublime
import sublime_plugin
import json
from os.path import dirname, realpath, join
from .node_bridge import node_bridge
# monkeypatch `Region` to be iterable
sublime.Region.totuple = lambda self: (self.a, self.b)
sublime.Region.__iter__ = lambda self: self.totuple().__iter__()
BIN_PATH = join(sublime.packa... |
def get_text(self):
if not self.has_selection():
region = sublime.Region(0, self.view.size())
return self.view.substr(region)
selected_text = ''
for region in self.view.sel():
selected_text = selected_text + self.view.substr(region) + '\n'
return selected_text
def has_selection(self):
for sel i... | try:
return node_bridge(data, BIN_PATH, [json.dumps({
'filename': self.view.file_name(),
'debug': self.get_setting('debug'),
'ensure_newline_at_eof': self.get_setting('ensure_newline_at_eof'),
'use_local_babel': self.get_setting('use_local_babel'),
'node_modules': self.get_setting('node_modules')... | identifier_body |
Babel.py | import sublime
import sublime_plugin
import json
from os.path import dirname, realpath, join
from .node_bridge import node_bridge
# monkeypatch `Region` to be iterable
sublime.Region.totuple = lambda self: (self.a, self.b)
sublime.Region.__iter__ = lambda self: self.totuple().__iter__()
BIN_PATH = join(sublime.packa... | (sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
selected_text = self.get_text()
code = self.babelify(selected_text)
if code:
w = sublime.Window.new_file(view.window())
w.settings().set('default_extension', 'js')
w.set_syntax_file(view.settings().get('syntax'))
w.set_scratch(Tr... | BabelCommand | identifier_name |
issue-28871.rs | // Copyright 2015 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 ... | type T = S;
}
trait T2 {
type T: Iterator<Item=<S as T>::T>;
}
fn main() { } | random_line_split | |
issue-28871.rs | // Copyright 2015 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 ... | () { }
| main | identifier_name |
lib.rs | #![recursion_limit = "1024"]
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate chrono;
extern crate crypto;
extern crate env_logger;
extern crate hex;
extern crate migrant_lib;
extern crate postgres;
extern crate r2d2;
extern crate r2d2_postgres;
extern crate ring;
extern crate ron;
ex... | () -> Result<std::path::PathBuf> {
Ok(std::env::var("CONFIG_DIR")
.map(std::path::PathBuf::from)
.unwrap_or_else(|_| std::env::current_dir().expect("unable to get current_dir")))
}
| config_dir | identifier_name |
lib.rs | #![recursion_limit = "1024"] | extern crate chrono;
extern crate crypto;
extern crate env_logger;
extern crate hex;
extern crate migrant_lib;
extern crate postgres;
extern crate r2d2;
extern crate r2d2_postgres;
extern crate ring;
extern crate ron;
extern crate serde;
extern crate uuid;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern cra... |
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log; | random_line_split |
lib.rs | #![recursion_limit = "1024"]
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate chrono;
extern crate crypto;
extern crate env_logger;
extern crate hex;
extern crate migrant_lib;
extern crate postgres;
extern crate r2d2;
extern crate r2d2_postgres;
extern crate ring;
extern crate ron;
ex... | {
Ok(std::env::var("CONFIG_DIR")
.map(std::path::PathBuf::from)
.unwrap_or_else(|_| std::env::current_dir().expect("unable to get current_dir")))
} | identifier_body | |
CompileLessCommand.ts | import * as vscode from "vscode";
import * as path from "path";
import * as Configuration from "./Configuration";
import * as LessCompiler from "./LessCompiler";
import * as StatusBarMessage from "./StatusBarMessage";
import { StatusBarMessageTypes } from "./StatusBarMessageTypes";
const RANGE_EOL = 4096;
export def... | (
private document: vscode.TextDocument,
private lessDiagnosticCollection: vscode.DiagnosticCollection
) {}
public async execute() {
StatusBarMessage.hideError();
const globalOptions: Configuration.EasyLessOptions = Configuration.getGlobalOptions(
this.document
);
const compilingMess... | constructor | identifier_name |
CompileLessCommand.ts | import * as vscode from "vscode";
import * as path from "path";
import * as Configuration from "./Configuration";
import * as LessCompiler from "./LessCompiler";
import * as StatusBarMessage from "./StatusBarMessage";
import { StatusBarMessageTypes } from "./StatusBarMessageTypes";
const RANGE_EOL = 4096;
export def... | StatusBarMessageTypes.INDEFINITE
);
const startTime: number = Date.now();
try {
await LessCompiler.compile(this.document.fileName, this.document.getText(), globalOptions);
const elapsedTime: number = Date.now() - startTime;
compilingMessage.dispose();
this.lessDiagnosticCollect... | );
const compilingMessage = StatusBarMessage.show(
"$(zap) Compiling less --> css", | random_line_split |
CompileLessCommand.ts | import * as vscode from "vscode";
import * as path from "path";
import * as Configuration from "./Configuration";
import * as LessCompiler from "./LessCompiler";
import * as StatusBarMessage from "./StatusBarMessage";
import { StatusBarMessageTypes } from "./StatusBarMessageTypes";
const RANGE_EOL = 4096;
export def... |
// hello world
/*
*/
private getErrorMessageAndRange(
error: any
): { message: string; range: vscode.Range | undefined } {
if (error.code) {
// fs errors
const fileSystemError = <vscode.FileSystemError & { path: string }>error;
switch (fileSystemError.code) {
... | {
let affectedUri: vscode.Uri | undefined;
if (error.filename) {
affectedUri = vscode.Uri.file(error.filename);
const isCurrentDocument =
!error.filename.includes("/") &&
!error.filename.includes("\\") &&
error.filename === path.basename(this.document.fileName);
if (i... | identifier_body |
climate.py | well's servers
_LOGGER.warning(
"Unable to connect with the vendor's server. "
"Check your network and the vendor's status page."
)
except requests.exceptions.HTTPError:
if err.response.status_code == HTTP_SERVICE_UNAVAILABLE:
... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.