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 |
|---|---|---|---|---|
test_result.rs | mod checked {
#[derive(Debug)]
pub enum MathError {
DivisionByZero,
NonPositiveLogarithm,
NegativeSquareRoot,
}
pub type MathResult = Result<f64, MathError>;
pub fn div(x: f64, y: f64) -> MathResult {
if y == 0.0 {
Err(MathError::DivisionByZero)
} els... | () {
println!("{}", op(1.0, 10.0));
}
| main | identifier_name |
describe.py | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | (parser):
"""Register flags for this command."""
parser.add_argument(
'name', help='The name of the function to describe.',
type=util.ValidateFunctionNameOrRaise)
@util.CatchHTTPErrorRaiseHTTPException
def Run(self, args):
"""This is what gets called when the user runs this command.
... | Args | identifier_name |
describe.py | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | args.name, params={'projectsId': project, 'locationsId': args.region},
collection='cloudfunctions.projects.locations.functions')
# TODO(user): Use resources.py here after b/21908671 is fixed.
return client.projects_locations_functions.Get(
messages.CloudfunctionsProjectsLocationsFunctio... | project = properties.VALUES.core.project.Get(required=True)
registry = self.context['registry']
function_ref = registry.Parse( | random_line_split |
describe.py | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | name=function_ref.RelativeName()))
| """This is what gets called when the user runs this command.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
The specified function with its description and configured filter.
"""
client = self.context['functions_client']... | identifier_body |
client.rs | use hyper::{body::Body, Client};
use opentelemetry::{
global,
sdk::export::trace::stdout,
sdk::trace as sdktrace,
trace::{TraceContextExt, Tracer},
Context, KeyValue,
};
use opentelemetry_aws::XrayPropagator;
use opentelemetry_http::HeaderInjector;
fn init_tracer() -> sdktrace::Tracer |
#[tokio::main]
async fn main() -> std::result::Result<(), Box<dyn std::error::Error + Send + Sync + 'static>> {
let _tracer = init_tracer();
let client = Client::new();
let span = global::tracer("example/client").start("say hello");
let cx = Context::current_with_span(span);
let mut req = hyper:... | {
global::set_text_map_propagator(XrayPropagator::new());
// Install stdout exporter pipeline to be able to retrieve the collected spans.
// For the demonstration, use `Sampler::AlwaysOn` sampler to sample all traces. In a production
// application, use `Sampler::ParentBased` or `Sampler::TraceIdRatioB... | identifier_body |
client.rs | use hyper::{body::Body, Client};
use opentelemetry::{
global,
sdk::export::trace::stdout,
sdk::trace as sdktrace,
trace::{TraceContextExt, Tracer},
Context, KeyValue,
};
use opentelemetry_aws::XrayPropagator;
use opentelemetry_http::HeaderInjector;
fn | () -> sdktrace::Tracer {
global::set_text_map_propagator(XrayPropagator::new());
// Install stdout exporter pipeline to be able to retrieve the collected spans.
// For the demonstration, use `Sampler::AlwaysOn` sampler to sample all traces. In a production
// application, use `Sampler::ParentBased` or ... | init_tracer | identifier_name |
client.rs | use hyper::{body::Body, Client};
use opentelemetry::{
global,
sdk::export::trace::stdout,
sdk::trace as sdktrace, | trace::{TraceContextExt, Tracer},
Context, KeyValue,
};
use opentelemetry_aws::XrayPropagator;
use opentelemetry_http::HeaderInjector;
fn init_tracer() -> sdktrace::Tracer {
global::set_text_map_propagator(XrayPropagator::new());
// Install stdout exporter pipeline to be able to retrieve the collected... | random_line_split | |
view_supplier.js | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
function | ()
{
//var info = 'id=' + checkedvalue;
//var jsonString = JSON.stringify(checkedvalue);
//alert(checkedvalue[0]);
var file1="viewsupplier";
if(confirm("Are you sure you want to delete all records...?"))
{
$.ajax({
type: "POST",
url: "deleteall.php",
data: {data : file1},
cache: false,
success: functio... | deleteall | identifier_name |
view_supplier.js | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
function deleteall()
{
//var info = 'id=' + checkedvalue;
//var jsonString = JSON.stringify(checkedvalue);
//alert(checkedvalue[0]... | var agree = confirm("Are you sure you wish to Delete Selected Record.?");
if (agree)
{
var file1="viewsupplier";
$.ajax({
type: "POST",
url: "deleterecords.php",
data: {data : checkedvalue,file : file1},
cache: false,
success: function(){
sessionStorage... | {
var retrievedData = sessionStorage.getItem("checked-checkboxesviewsupplier");
var checkedvalue = JSON.parse(retrievedData);
var flag =checkedvalue.length;
// alert(flag);
/*var field = document.forms.deletefiles;
for (i = 0; i < field.length; i++) {
... | identifier_body |
view_supplier.js | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
function deleteall()
{
//var info = 'id=' + checkedvalue;
//var jsonString = JSON.stringify(checkedvalue);
//alert(checkedvalue[0]... | messages: {
name: {
required: "Informe o nome",
minlength: "supplier must consist of at least 3 characters"
},
address: {
minlength: "supplier Address must be at least 3 ch... | random_line_split | |
progress_linear.ts | import {Component, onChange, View, Attribute} from 'angular2/angular2';
import {isPresent, isBlank} from 'angular2/src/facade/lang';
import {Math} from 'angular2/src/facade/math';
@Component({
selector: 'md-progress-linear',
lifecycle: [onChange],
properties: ['value', 'bufferValue'],
host: {
'[attr.role]... | () {
return this.value_;
}
set value(v) {
if (isPresent(v)) {
this.value_ = MdProgressLinear.clamp(v);
}
}
onChange(_) {
// If the mode does not use a value, or if there is no value, do nothing.
if (this.mode == Mode['QUERY'] || this.mode == Mode['INDETERMINATE'] || isBlank(this.valu... | value | identifier_name |
progress_linear.ts | import {Component, onChange, View, Attribute} from 'angular2/angular2';
import {isPresent, isBlank} from 'angular2/src/facade/lang';
import {Math} from 'angular2/src/facade/math';
@Component({
selector: 'md-progress-linear',
lifecycle: [onChange],
properties: ['value', 'bufferValue'],
host: {
'[attr.role]... | 'QUERY': 'query'
}; | random_line_split | |
progress_linear.ts | import {Component, onChange, View, Attribute} from 'angular2/angular2';
import {isPresent, isBlank} from 'angular2/src/facade/lang';
import {Math} from 'angular2/src/facade/math';
@Component({
selector: 'md-progress-linear',
lifecycle: [onChange],
properties: ['value', 'bufferValue'],
host: {
'[attr.role]... |
}
onChange(_) {
// If the mode does not use a value, or if there is no value, do nothing.
if (this.mode == Mode['QUERY'] || this.mode == Mode['INDETERMINATE'] || isBlank(this.value)) {
return;
}
this.primaryBarTransform = this.transformForValue(this.value);
// The bufferValue is only u... | {
this.value_ = MdProgressLinear.clamp(v);
} | conditional_block |
progress_linear.ts | import {Component, onChange, View, Attribute} from 'angular2/angular2';
import {isPresent, isBlank} from 'angular2/src/facade/lang';
import {Math} from 'angular2/src/facade/math';
@Component({
selector: 'md-progress-linear',
lifecycle: [onChange],
properties: ['value', 'bufferValue'],
host: {
'[attr.role]... |
/** Clamps a value to be between 0 and 100. */
static clamp(v) {
return Math.max(0, Math.min(100, v));
}
}
/** @enum {string} Progress-linear modes. */
var Mode = {
'DETERMINATE': 'determinate',
'INDETERMINATE': 'indeterminate',
'BUFFER': 'buffer',
'QUERY': 'query'
};
| {
// TODO(jelbourn): test perf gain of caching these, since there are only 101 values.
var scale = value / 100;
var translateX = (value - 100) / 2;
return `translateX(${translateX}%) scale(${scale}, 1)`;
} | identifier_body |
server.py | # -*- coding: utf-8 -*-
"""
tornado websocket proxy for WF worker daemons
"""
# Copyright (C) 2015 ZetaOps Inc.
#
# This file is licensed under the GNU General Public License v3
# (GPLv3). See LICENSE.txt for details.
import json
import os, sys
import traceback
from uuid import uuid4
from tornado import websocket, we... |
@web.asynchronous
def post(self, view_name):
"""
login handler
"""
sess_id = None
input_data = {}
# try:
self._handle_headers()
# handle input
input_data = json_decode(self.request.body) if self.request.body else {}
input_data['p... | """
only used to display login form
Args:
view_name: should be "login"
"""
self.post(view_name) | identifier_body |
server.py | # -*- coding: utf-8 -*-
"""
tornado websocket proxy for WF worker daemons
"""
# Copyright (C) 2015 ZetaOps Inc.
#
# This file is licensed under the GNU General Public License v3
# (GPLv3). See LICENSE.txt for details.
import json
import os, sys
import traceback
from uuid import uuid4
from tornado import websocket, we... |
def on_message(self, message):
"""
called on new websocket message,
"""
log.debug("WS MSG for %s: %s" % (self._get_sess_id(), message))
self.application.pc.redirect_incoming_message(self._get_sess_id(), message, self.request)
def on_close(self):
"""
remo... | random_line_split | |
server.py | # -*- coding: utf-8 -*-
"""
tornado websocket proxy for WF worker daemons
"""
# Copyright (C) 2015 ZetaOps Inc.
#
# This file is licensed under the GNU General Public License v3
# (GPLv3). See LICENSE.txt for details.
import json
import os, sys
import traceback
from uuid import uuid4
from tornado import websocket, we... |
self.set_header('Access-Control-Allow-Credentials', "true")
self.set_header('Access-Control-Allow-Headers', 'Content-Type')
self.set_header('Access-Control-Allow-Methods', 'OPTIONS')
self.set_header('Content-Type', 'application/json')
@web.asynchronous
def get(self, view_name):... | self.set_header('Access-Control-Allow-Origin', origin or '*') | conditional_block |
server.py | # -*- coding: utf-8 -*-
"""
tornado websocket proxy for WF worker daemons
"""
# Copyright (C) 2015 ZetaOps Inc.
#
# This file is licensed under the GNU General Public License v3
# (GPLv3). See LICENSE.txt for details.
import json
import os, sys
import traceback
from uuid import uuid4
from tornado import websocket, we... | (self):
"""
remove connection from pool on connection close.
"""
self.application.pc.unregister_websocket(self._get_sess_id())
# noinspection PyAbstractClass
class HttpHandler(web.RequestHandler):
"""
login handler class
"""
def _handle_headers(self):
"""
... | on_close | identifier_name |
0003_datalogger.py | # Generated by Django 2.0.5 on 2018-05-07 09:24
from django.conf import settings
import django.contrib.gis.db.models.fields
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import endpoints.models
class Migration(migrations.Migration):
| ('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL, verbose_name='Owner')),
],
),
]
| dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('endpoints', '0002_request_user'),
]
operations = [
migrations.CreateModel(
name='Datalogger',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, seria... | identifier_body |
0003_datalogger.py | # Generated by Django 2.0.5 on 2018-05-07 09:24
from django.conf import settings
import django.contrib.gis.db.models.fields
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import endpoints.models
|
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('endpoints', '0002_request_user'),
]
operations = [
migrations.CreateModel(
name='Datalogger',
fields=[
('id', models.AutoFie... | random_line_split | |
0003_datalogger.py | # Generated by Django 2.0.5 on 2018-05-07 09:24
from django.conf import settings
import django.contrib.gis.db.models.fields
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import endpoints.models
class | (migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('endpoints', '0002_request_user'),
]
operations = [
migrations.CreateModel(
name='Datalogger',
fields=[
('id', models.AutoField(auto_created=... | Migration | identifier_name |
builder.rs | : SelectorImpl> SelectorBuilder<Impl> {
/// Pushes a simple selector onto the current compound selector.
#[inline(always)]
pub fn push_simple_selector(&mut self, ss: Component<Impl>) {
assert!(!ss.is_combinator());
self.simple_selectors.push(ss);
self.current_len += 1;
}
///... | specificity.id_selectors += 1;
},
| conditional_block | |
builder.rs | is encountered
/// (from left to right). Once the process is complete, callers should invoke
/// build(), which transforms the contents of the SelectorBuilder into a heap-
/// allocated Selector and leaves the builder in a drained state.
#[derive(Debug)]
pub struct SelectorBuilder<Impl: SelectorImpl> {
/// The ent... | x_selector_specificity<Impl> | identifier_name | |
builder.rs | //! * We store the top-level compound selectors from right to left, i.e. in
//! matching order.
//! * We store the simple selectors for each combinator from left to right, so
//! that we match the cheaper simple selectors first.
//!
//! Meeting all these constraints without extra memmove traffic during parsing
//! ... | //! as Component instances. | random_line_split | |
geojsonsource.js | goog.provide('ol.source.GeoJSON');
goog.require('ol.format.GeoJSON');
goog.require('ol.source.StaticVector');
/**
* @classdesc
* Static vector source in GeoJSON format
*
* @constructor
* @extends {ol.source.StaticVector}
* @fires ol.source.VectorEvent
* @param {olx.source.GeoJSONOptions=} opt_o... | * @api
*/
ol.source.GeoJSON = function(opt_options) {
var options = goog.isDef(opt_options) ? opt_options : {};
goog.base(this, {
attributions: options.attributions,
extent: options.extent,
format: new ol.format.GeoJSON({
defaultDataProjection: options.defaultProjection
}),
... | random_line_split | |
conftest.py | # (C) British Crown Copyright 2020, Met Office
#
# This file is part of cartopy.
#
# cartopy is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any la... |
def pytest_configure(config):
# Register additional markers.
config.addinivalue_line('markers',
'natural_earth: mark tests that use Natural Earth '
'data, and the network, if not cached.')
config.addinivalue_line('markers',
... | random_line_split | |
conftest.py | # (C) British Crown Copyright 2020, Met Office
#
# This file is part of cartopy.
#
# cartopy is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any la... | (config):
# Register additional markers.
config.addinivalue_line('markers',
'natural_earth: mark tests that use Natural Earth '
'data, and the network, if not cached.')
config.addinivalue_line('markers',
'network: mark tests... | pytest_configure | identifier_name |
conftest.py | # (C) British Crown Copyright 2020, Met Office
#
# This file is part of cartopy.
#
# cartopy is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option) any la... | config.addinivalue_line('markers',
'natural_earth: mark tests that use Natural Earth '
'data, and the network, if not cached.')
config.addinivalue_line('markers',
'network: mark tests that use the network.') | identifier_body | |
app.ts | #!/usr/bin/env node
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*-------------------------------------------... | () {
const autorestArgs = process.argv.slice(2);
try {
const autorestExe = spawn(
path.join(homedir(), ".autorest", "frameworks", "dotnet"),
[path.join(__dirname, "../../AutoRest.dll"), ...autorestArgs]);
autorestExe.stdout.pipe(process.stdout);
autorestExe.stderr.pipe(process.stderr);
c... | main | identifier_name |
app.ts | #!/usr/bin/env node
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*-------------------------------------------... |
main(); | {
const autorestArgs = process.argv.slice(2);
try {
const autorestExe = spawn(
path.join(homedir(), ".autorest", "frameworks", "dotnet"),
[path.join(__dirname, "../../AutoRest.dll"), ...autorestArgs]);
autorestExe.stdout.pipe(process.stdout);
autorestExe.stderr.pipe(process.stderr);
cons... | identifier_body |
app.ts | * Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// start of autorest-ng
// the console app starts for real here... | #!/usr/bin/env node
/*--------------------------------------------------------------------------------------------- | random_line_split | |
PBX_Base.py | from .PBXResolver import *
from .PBX_Constants import *
class PBX_Base(object):
def __init__(self, lookup_func, dictionary, project, identifier):
# default 'name' property of a PBX object is the type
self.name = self.__class__.__name__;
# this is the identifier for this object
... |
else:
self.referencedIdentifiers.add(dict_item);
return self.fetchObjectFromProject(lookup_func, dict_item, project);
| property_list = [];
for item in dict_item:
self.referencedIdentifiers.add(item);
find_object = self.fetchObjectFromProject(lookup_func, item, project);
property_list.append(find_object);
return property_list; | conditional_block |
PBX_Base.py | from .PBXResolver import *
from .PBX_Constants import *
class | (object):
def __init__(self, lookup_func, dictionary, project, identifier):
# default 'name' property of a PBX object is the type
self.name = self.__class__.__name__;
# this is the identifier for this object
self.identifier = str(identifier);
# set of any referenced ide... | PBX_Base | identifier_name |
PBX_Base.py | from .PBXResolver import *
from .PBX_Constants import *
class PBX_Base(object):
def __init__(self, lookup_func, dictionary, project, identifier):
# default 'name' property of a PBX object is the type
self.name = self.__class__.__name__;
# this is the identifier for this object
... | return '(%s : %s : %s)' % (type(self), self.name, self.identifier);
def __eq__(self, other):
return isinstance(other, type(self)) and self.identifier == other.identifier;
def __hash__(self):
return hash(self.__attrs());
def resolve(self, type, item_list):
retur... | random_line_split | |
PBX_Base.py | from .PBXResolver import *
from .PBX_Constants import *
class PBX_Base(object):
def __init__(self, lookup_func, dictionary, project, identifier):
# default 'name' property of a PBX object is the type
self.name = self.__class__.__name__;
# this is the identifier for this object
... |
def __repr__(self):
return '(%s : %s : %s)' % (type(self), self.name, self.identifier);
def __eq__(self, other):
return isinstance(other, type(self)) and self.identifier == other.identifier;
def __hash__(self):
return hash(self.__attrs());
def resolve(self, t... | return (self.identifier); | identifier_body |
tempdir.js | var common = require('./common');
var os = require('os');
var fs = require('fs');
// Returns false if 'dir' is not a writeable directory, 'dir' otherwise
function writeableDir(dir) {
if (!dir || !fs.existsSync(dir))
return false;
if (!fs.statSync(dir).isDirectory())
return false; |
var testFile = dir+'/'+common.randomFileName();
try {
fs.writeFileSync(testFile, ' ');
common.unlinkSync(testFile);
return dir;
} catch (e) {
return false;
}
}
//@
//@ ### tempdir()
//@
//@ Examples:
//@
//@ ```javascript
//@ var tmp = tempdir(); // "/tmp" for most *nix platforms
//@ ```
//@
... | random_line_split | |
tempdir.js | var common = require('./common');
var os = require('os');
var fs = require('fs');
// Returns false if 'dir' is not a writeable directory, 'dir' otherwise
function writeableDir(dir) {
if (!dir || !fs.existsSync(dir))
return false;
if (!fs.statSync(dir).isDirectory())
return false;
var testFile = dir+'/'... | return state.tempDir;
}
module.exports = _tempDir;
| {
var state = common.state;
if (state.tempDir)
return state.tempDir; // from cache
state.tempDir = writeableDir(os.tmpdir && os.tmpdir()) || // node 0.10+
writeableDir(os.tmpDir && os.tmpDir()) || // node 0.8+
writeableDir(process.env['TMPDIR']) ||
writea... | identifier_body |
tempdir.js | var common = require('./common');
var os = require('os');
var fs = require('fs');
// Returns false if 'dir' is not a writeable directory, 'dir' otherwise
function writeableDir(dir) {
if (!dir || !fs.existsSync(dir))
return false;
if (!fs.statSync(dir).isDirectory())
return false;
var testFile = dir+'/'... | () {
var state = common.state;
if (state.tempDir)
return state.tempDir; // from cache
state.tempDir = writeableDir(os.tmpdir && os.tmpdir()) || // node 0.10+
writeableDir(os.tmpDir && os.tmpDir()) || // node 0.8+
writeableDir(process.env['TMPDIR']) ||
wri... | _tempDir | identifier_name |
mainThreadFileSystem.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | $onFileSystemChange(handle: number, changes: IFileChange[]): void {
this._provider.get(handle).$onFileSystemChange(changes);
}
$reportFileChunk(handle: number, resource: URI, chunk: number[]): void {
this._provider.get(handle).reportFileChunk(resource, chunk);
}
// --- search
$handleSearchProgress(handle: ... | }
| random_line_split |
mainThreadFileSystem.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
const id = ++this._searchesIdPool;
const matches: IFileMatch[] = [];
return new PPromise((resolve, reject, report) => {
this._proxy.$fileFiles(this._handle, id, query.filePattern).then(() => {
this._searches.delete(id);
resolve({
results: matches,
stats: undefined
});
}, reject);
... | {
return PPromise.as<ISearchComplete>({ results: [], stats: undefined });
} | conditional_block |
mainThreadFileSystem.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
$onDidAddFileSystemRoot(uri: URI): void {
this._workspaceEditingService.addFolders([{ uri }], true).done(null, onUnexpectedError);
}
$onFileSystemChange(handle: number, changes: IFileChange[]): void {
this._provider.get(handle).$onFileSystemChange(changes);
}
$reportFileChunk(handle: number, resource: URI,... | {
dispose(this._provider.get(handle));
this._provider.delete(handle);
} | identifier_body |
mainThreadFileSystem.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (handle: number, resource: URI, chunk: number[]): void {
this._provider.get(handle).reportFileChunk(resource, chunk);
}
// --- search
$handleSearchProgress(handle: number, session: number, resource: URI): void {
this._provider.get(handle).handleSearchProgress(session, resource);
}
}
class RemoteFileSystemPro... | $reportFileChunk | identifier_name |
ControllerContext.tsx | ServerUpdateType,
PatcherAlert,
} from 'gql/interfaces';
export interface ControllerContextQuery {
shardCharacters: SimpleCharacter[];
connectedServices: {
servers: ServerModel[];
};
}
export enum ServerType {
CUGAME,
CUBE,
CHANNEL,
UNKNOWN,
HIDDEN,
}
// Server interface which the Controller w... |
return utils.merge({
name: server.name,
available: server.playerMaximum > 0,
type: ServerType.CUGAME,
channelStatus: channel ? channel.channelStatus : ChannelStatus.NotInstalled,
apiHost: server.apiHost,
mode: channel ? channel.mode : PatchChannelMode.Automatic,
}, server);
}
function getS... |
export function webAPIServerToPatcherServer(server: webAPI.ServerModel): PatcherServer {
const channels = patcher.getAllChannels();
const channelIndex = utils.findIndexWhere(channels, c => c.channelID === server.channelID);
const channel = channels[channelIndex]; | random_line_split |
ControllerContext.tsx | ServerUpdateType,
PatcherAlert,
} from 'gql/interfaces';
export interface ControllerContextQuery {
shardCharacters: SimpleCharacter[];
connectedServices: {
servers: ServerModel[];
};
}
export enum ServerType {
CUGAME,
CUBE,
CHANNEL,
UNKNOWN,
HIDDEN,
}
// Server interface which the Controller w... |
export function webAPIServerToPatcherServer(server: webAPI.ServerModel): PatcherServer {
const channels = patcher.getAllChannels();
const channelIndex = utils.findIndexWhere(channels, c => c.channelID === server.channelID);
const channel = channels[channelIndex];
return utils.merge({
name: server.name,
... | {
const gqlAccessLevel = gqlServerModel.accessLevel;
const server = {
...gqlServerModel,
accessLevel: webAPI.AccessType[gqlAccessLevel],
};
return server;
} | identifier_body |
ControllerContext.tsx | ServerUpdateType,
PatcherAlert,
} from 'gql/interfaces';
export interface ControllerContextQuery {
shardCharacters: SimpleCharacter[];
connectedServices: {
servers: ServerModel[];
};
}
export enum ServerType {
CUGAME,
CUBE,
CHANNEL,
UNKNOWN,
HIDDEN,
}
// Server interface which the Controller ... | (props: Props) {
super(props);
this.state = {
...defaultControllerContextState,
onUpdateState: this.onUpdateState,
updateChannels: this.updateChannels,
};
}
public render() {
return (
<ControllerContext.Provider value={this.state}>
{this.props.loggedIn &&
<... | constructor | identifier_name |
local_gpus.py | import os
from cosmos.api import Cosmos, py_call
from cosmos.util.helpers import environment_variables
def use_cuda_device(some_arg, num_gpus):
assert "CUDA_VISIBLE_DEVICES" in os.environ
print(("some_arg", some_arg))
print(("CUDA_VISIBLE_DEVICES", os.environ["CUDA_VISIBLE_DEVICES"])) |
def main():
cosmos = Cosmos().initdb()
workflow = cosmos.start("gpu", skip_confirm=True)
for i, num_gpus in enumerate([1, 1, 2, 2, 3]):
task = workflow.add_task(
use_cuda_device, dict(some_arg=i, num_gpus=num_gpus), gpu_req=num_gpus, uid=str(i),
)
workflow.run(
ma... | assert len(os.environ["CUDA_VISIBLE_DEVICES"].split(",")) == num_gpus | random_line_split |
local_gpus.py | import os
from cosmos.api import Cosmos, py_call
from cosmos.util.helpers import environment_variables
def use_cuda_device(some_arg, num_gpus):
assert "CUDA_VISIBLE_DEVICES" in os.environ
print(("some_arg", some_arg))
print(("CUDA_VISIBLE_DEVICES", os.environ["CUDA_VISIBLE_DEVICES"]))
assert len(os.e... |
if __name__ == "__main__":
with environment_variables(COSMOS_LOCAL_GPU_DEVICES="0,1,3"):
main()
| cosmos = Cosmos().initdb()
workflow = cosmos.start("gpu", skip_confirm=True)
for i, num_gpus in enumerate([1, 1, 2, 2, 3]):
task = workflow.add_task(
use_cuda_device, dict(some_arg=i, num_gpus=num_gpus), gpu_req=num_gpus, uid=str(i),
)
workflow.run(
max_gpus=len(os.envi... | identifier_body |
local_gpus.py | import os
from cosmos.api import Cosmos, py_call
from cosmos.util.helpers import environment_variables
def | (some_arg, num_gpus):
assert "CUDA_VISIBLE_DEVICES" in os.environ
print(("some_arg", some_arg))
print(("CUDA_VISIBLE_DEVICES", os.environ["CUDA_VISIBLE_DEVICES"]))
assert len(os.environ["CUDA_VISIBLE_DEVICES"].split(",")) == num_gpus
def main():
cosmos = Cosmos().initdb()
workflow = cosmos.sta... | use_cuda_device | identifier_name |
local_gpus.py | import os
from cosmos.api import Cosmos, py_call
from cosmos.util.helpers import environment_variables
def use_cuda_device(some_arg, num_gpus):
assert "CUDA_VISIBLE_DEVICES" in os.environ
print(("some_arg", some_arg))
print(("CUDA_VISIBLE_DEVICES", os.environ["CUDA_VISIBLE_DEVICES"]))
assert len(os.e... |
workflow.run(
max_gpus=len(os.environ["COSMOS_LOCAL_GPU_DEVICES"].split(",")), cmd_wrapper=py_call,
)
if __name__ == "__main__":
with environment_variables(COSMOS_LOCAL_GPU_DEVICES="0,1,3"):
main()
| task = workflow.add_task(
use_cuda_device, dict(some_arg=i, num_gpus=num_gpus), gpu_req=num_gpus, uid=str(i),
) | conditional_block |
Fixture.ts | import { MetaPopulation } from '@allors/meta/system';
import { Meta, PullFactory, TreeFactory, FetchFactory, data } from '@allors/meta/generated';
import { Workspace } from '@allors/domain/system';
import '@allors/meta/core';
import { extend as extendDomain } from '@allors/domain/custom';
import { Context, AxiosHttp,... | (user: string) {
await this.http.login('TestAuthentication/Token', user);
}
}
| login | identifier_name |
Fixture.ts | import { MetaPopulation } from '@allors/meta/system';
import { Meta, PullFactory, TreeFactory, FetchFactory, data } from '@allors/meta/generated';
import { Workspace } from '@allors/domain/system';
import '@allors/meta/core';
import { extend as extendDomain } from '@allors/domain/custom';
import { Context, AxiosHttp,... | await this.login('administrator');
await this.http.get('Test/Setup', { population });
const database = new Database(this.http);
this.ctx = new Context(database, workspace);
this.tree = new TreeFactory(this.m);
this.fetch = new FetchFactory(this.m);
this.pull = new PullFactory(this.m);
}
... | this.metaPopulation = new MetaPopulation(data);
this.m = this.metaPopulation as Meta;
const workspace = new Workspace(this.metaPopulation);
extendDomain(workspace);
| random_line_split |
excellon.py | #!/usr/bin/python
import os
import re
from lxml import etree as et
import pcbmode.config as config
from . import messages as msg
# pcbmode modules
from . import utils
from .point import Point
def makeExcellon(manufacturer='default'):
"""
"""
ns = {'pcbmode':config.cfg['ns']['pcbmode'],
'svg... | (self):
"""
"""
ex = []
ex.append('M30\n') # End of Program, rewind
return ex
def _getLocation(self, path):
"""
Returns the location of a path, factoring in all the transforms of
its ancestors, and its own transform
"""
location = P... | _createPostamble | identifier_name |
excellon.py | #!/usr/bin/python
import os
import re
from lxml import etree as et
| from . import messages as msg
# pcbmode modules
from . import utils
from .point import Point
def makeExcellon(manufacturer='default'):
"""
"""
ns = {'pcbmode':config.cfg['ns']['pcbmode'],
'svg':config.cfg['ns']['svg']}
# Open the board's SVG
svg_in = utils.openBoardSVG()
drills_... | import pcbmode.config as config | random_line_split |
excellon.py | #!/usr/bin/python
import os
import re
from lxml import etree as et
import pcbmode.config as config
from . import messages as msg
# pcbmode modules
from . import utils
from .point import Point
def makeExcellon(manufacturer='default'):
"""
"""
ns = {'pcbmode':config.cfg['ns']['pcbmode'],
'svg... | drills_dict[diameter]['locations'].append(location)
self._preamble = self._createPreamble()
self._content = self._createContent(drills_dict)
self._postamble = self._createPostamble()
def getExcellon(self):
return (self._preamble+
self._content+
... | """
"""
self._svg = svg
self._ns = {'pcbmode':config.cfg['ns']['pcbmode'],
'svg':config.cfg['ns']['svg']}
# Get all drill paths except for the ones used in the
# drill-index
drill_paths = self._svg.findall(".//svg:g[@pcbmode:type='component-shapes'... | identifier_body |
excellon.py | #!/usr/bin/python
import os
import re
from lxml import etree as et
import pcbmode.config as config
from . import messages as msg
# pcbmode modules
from . import utils
from .point import Point
def makeExcellon(manufacturer='default'):
"""
"""
ns = {'pcbmode':config.cfg['ns']['pcbmode'],
'svg... |
class Excellon():
"""
"""
def __init__(self, svg):
"""
"""
self._svg = svg
self._ns = {'pcbmode':config.cfg['ns']['pcbmode'],
'svg':config.cfg['ns']['svg']}
# Get all drill paths except for the ones used in the
# drill-index
... | f.write(line) | conditional_block |
lights_controller.py | #!/usr/bin/python
import sys
import remote_core as core
import radio_lights
def main(argv):
config = core.load_config()
lights_config_names = {"1":"door_light", "2":"desk_light", "3": "shelf_light"}
if len(argv) == 1 and len(argv[0]) == 2:
if argv[0] == "an":
argv = ["1n", "2n", "3n"]
elif argv[0] == "af"... |
core.write_config(config)
if __name__ == "__main__":
main(sys.argv[1:])
| if item[-1:] == 'n':
radio_lights.turn_on_single(config["lights"][lights_config_names[item[:1]]])
elif item[-1:] == 'f':
radio_lights.turn_off_single(config["lights"][lights_config_names[item[:1]]]) | conditional_block |
lights_controller.py | #!/usr/bin/python
import sys
import remote_core as core
import radio_lights
def main(argv):
config = core.load_config()
lights_config_names = {"1":"door_light", "2":"desk_light", "3": "shelf_light"}
if len(argv) == 1 and len(argv[0]) == 2:
if argv[0] == "an":
argv = ["1n", "2n", "3n"]
elif argv[0] == "af"... | if item[-1:] == 'n':
radio_lights.turn_on_single(config["lights"][lights_config_names[item[:1]]])
elif item[-1:] == 'f':
radio_lights.turn_off_single(config["lights"][lights_config_names[item[:1]]])
core.write_config(config)
if __name__ == "__main__":
main(sys.argv[1:]) | random_line_split | |
lights_controller.py | #!/usr/bin/python
import sys
import remote_core as core
import radio_lights
def main(argv):
|
if __name__ == "__main__":
main(sys.argv[1:])
| config = core.load_config()
lights_config_names = {"1":"door_light", "2":"desk_light", "3": "shelf_light"}
if len(argv) == 1 and len(argv[0]) == 2:
if argv[0] == "an":
argv = ["1n", "2n", "3n"]
elif argv[0] == "af":
argv = ["1f", "2f", "3f"]
for item in argv:
if item[-1:] == 'n':
radio_lights.tur... | identifier_body |
lights_controller.py | #!/usr/bin/python
import sys
import remote_core as core
import radio_lights
def | (argv):
config = core.load_config()
lights_config_names = {"1":"door_light", "2":"desk_light", "3": "shelf_light"}
if len(argv) == 1 and len(argv[0]) == 2:
if argv[0] == "an":
argv = ["1n", "2n", "3n"]
elif argv[0] == "af":
argv = ["1f", "2f", "3f"]
for item in argv:
if item[-1:] == 'n':
radio_l... | main | identifier_name |
package.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class | (MakefilePackage):
"""Voro++ is a open source software library for the computation of the
Voronoi diagram, a widely-used tessellation that has applications in many
scientific fields."""
homepage = "http://math.lbl.gov/voro++/about.html"
url = "http://math.lbl.gov/voro++/download/dir/voro++-0.4... | Voropp | identifier_name |
package.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Voropp(MakefilePackage):
"""Voro++ is a open source software library for the computation o... |
filter_file(r'CFLAGS=.*',
'CFLAGS={0}'.format(cflags),
'config.mk')
| cflags += self.compiler.cc_pic_flag | conditional_block |
package.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Voropp(MakefilePackage):
"""Voro++ is a open source software library for the computation o... | 'CFLAGS={0}'.format(cflags),
'config.mk') | random_line_split | |
package.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Voropp(MakefilePackage):
"""Voro++ is a open source software library for the computation o... | filter_file(r'CC=g\+\+',
'CC={0}'.format(self.compiler.cxx),
'config.mk')
filter_file(r'PREFIX=/usr/local',
'PREFIX={0}'.format(self.prefix),
'config.mk')
# We can safely replace the default CFLAGS which are:
# CFLAG... | identifier_body | |
xmlcsv2xy.py | from sys import argv
from xml.dom import minidom
import csv
stem = argv[1][:-4] if argv[1].endswith('.xml') else argv[1]
xmldoc = minidom.parse('%s.xml'%stem)
labellist = xmldoc.getElementsByTagName('label')
labels = [l.attributes['name'].value for l in labellist]
labelset = set(labels)
for split in 'train','test':
... | with open('%s-%s.csv'%(stem,split), 'rb') as csvfile:
reader = csv.DictReader(csvfile)
features = [f for f in reader.fieldnames if f not in labelset]
x = open('%s-%s.x.txt'%(stem,split), 'w')
y = open('%s-%s.y.txt'%(stem,split), 'w')
for row in reader:
xbuf = ' '.join... | conditional_block | |
xmlcsv2xy.py | from sys import argv
from xml.dom import minidom
import csv
stem = argv[1][:-4] if argv[1].endswith('.xml') else argv[1]
xmldoc = minidom.parse('%s.xml'%stem)
labellist = xmldoc.getElementsByTagName('label') | reader = csv.DictReader(csvfile)
features = [f for f in reader.fieldnames if f not in labelset]
x = open('%s-%s.x.txt'%(stem,split), 'w')
y = open('%s-%s.y.txt'%(stem,split), 'w')
for row in reader:
xbuf = ' '.join([row[f] for f in features])
ybuf = ' '.jo... | labels = [l.attributes['name'].value for l in labellist]
labelset = set(labels)
for split in 'train','test':
with open('%s-%s.csv'%(stem,split), 'rb') as csvfile: | random_line_split |
AICharacter.py | import os
import sys
import random
import pygame
from Engine import *
from Montag import *
from Character import Character
from pygame.locals import *
class AICharacter(Character):
def __init__(self, screen, **kwargs):
super().__init__(screen, **kwargs)
self.enemy = kwargs.get("enemy", None)
... | current_time = pygame.time.get_ticks()
clock.tick(60)
screen.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == VIDEORESIZE:
screen_size = event.dict["size"]
... | conditional_block | |
AICharacter.py | import os
import sys
import random
import pygame
from Engine import *
from Montag import *
from Character import Character
from pygame.locals import *
class AICharacter(Character):
| def click(self):
if self.dialog:
self.dialogmanager.start_dialog(self.dialog)
def hold_position(self):
self.movement_state = None
def update(self, current_time=None, event=None):
if not current_time:
current_time = pygame.time.get_ticks()
if self.state... | def __init__(self, screen, **kwargs):
super().__init__(screen, **kwargs)
self.enemy = kwargs.get("enemy", None)
self.movement_state = kwargs.get("movement_state", None)
self.waypoints = kwargs.get("waypoints", None)
self.area = kwargs.get("random_walk_area", None)
self.ob... | identifier_body |
AICharacter.py | import os
import sys
import random
import pygame
from Engine import *
from Montag import *
from Character import Character
from pygame.locals import *
class AICharacter(Character):
def __init__(self, screen, **kwargs):
super().__init__(screen, **kwargs)
self.enemy = kwargs.get("enemy", None)
... | if not self.walk_to_points and self.pause_time_passed >= self.pause_time:
if self.movement_state == "random_walk":
self.walk_to_points = self.pathfinding_grid.find_path(self.grid_pos, [
random.uniform(self.area[0], self.area[0] + self.a... | self.pause_time_passed += time_change
else:
self.pause_time_passed = 0
if not self.dead:
if not self.movement_temporarily_suppressed: | random_line_split |
AICharacter.py | import os
import sys
import random
import pygame
from Engine import *
from Montag import *
from Character import Character
from pygame.locals import *
class | (Character):
def __init__(self, screen, **kwargs):
super().__init__(screen, **kwargs)
self.enemy = kwargs.get("enemy", None)
self.movement_state = kwargs.get("movement_state", None)
self.waypoints = kwargs.get("waypoints", None)
self.area = kwargs.get("random_walk_area", None... | AICharacter | identifier_name |
xrwebglsubimage.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 crate::dom::bindings::codegen::Bindings::XRWebGLSubImageBinding::XRWebGLSubImageBinding::XRWebGLSubImageMetho... |
/// https://immersive-web.github.io/layers/#dom-xrwebglsubimage-imageindex
fn GetImageIndex(&self) -> Option<u32> {
self.image_index
}
/// https://immersive-web.github.io/layers/#dom-xrwebglsubimage-texturewidth
fn TextureWidth(&self) -> u32 {
self.size.width
}
/// https:... | {
self.depth_stencil_texture.as_deref().map(DomRoot::from_ref)
} | identifier_body |
xrwebglsubimage.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 crate::dom::bindings::codegen::Bindings::XRWebGLSubImageBinding::XRWebGLSubImageBinding::XRWebGLSubImageMetho... | (&self) -> u32 {
self.size.width
}
/// https://immersive-web.github.io/layers/#dom-xrwebglsubimage-textureheight
fn TextureHeight(&self) -> u32 {
self.size.height
}
}
| TextureWidth | identifier_name |
xrwebglsubimage.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 crate::dom::bindings::codegen::Bindings::XRWebGLSubImageBinding::XRWebGLSubImageBinding::XRWebGLSubImageMetho... | /// https://immersive-web.github.io/layers/#dom-xrwebglsubimage-texturewidth
fn TextureWidth(&self) -> u32 {
self.size.width
}
/// https://immersive-web.github.io/layers/#dom-xrwebglsubimage-textureheight
fn TextureHeight(&self) -> u32 {
self.size.height
}
} | random_line_split | |
font.rs | to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
... | {
let (il, it, ir, ib) = self.char_coords[&c];
let t = vec![
Vec2 { x: il, y: it },
Vec2 { x: ir, y: it },
Vec2 { x: ir, y: ib },
Vec2 { x: il, y: ib },
];
let i1 = self.thre... | conditional_block | |
font.rs |
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name o... | Vec2 { x: ir, y: it },
Vec2 { x: ir, y: ib },
Vec2 { x: il, y: ib },
];
let i1 = self.thread_data.add_vertex_st_f2f2(&v[0], &t[0]);
let i2 = self.thread_data.add_vertex_st_f2f2(&v[1], &t[1]);
let... | if self.char_coords.contains_key(&c) {
let (il, it, ir, ib) = self.char_coords[&c];
let t = vec![
Vec2 { x: il, y: it }, | random_line_split |
font.rs | BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
// OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
// AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABI... | {
write!(f, "{:?}", self.texture)
} | identifier_body | |
font.rs |
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name o... | (&mut self, renderer: &Box<Renderer>, resource_manager: &Arc<Mutex<Box<ResourceManager>>>) {
if self.shader.check_for_rebuild(
None,
renderer,
resource_manager,
)
{
self.reconfigure_shaders();
}
// Turn off shader warnings until th... | check_for_shader_rebuild | identifier_name |
EaselPlugin.js | _setSaturation = function(m, n) {
if (isNaN(n)) {
return m;
}
var inv = 1 - n,
r = inv * _lumR,
g = inv * _lumG,
b = inv * _lumB;
return _applyMatrix([r + n, g, b, 0, 0, r, g + n, b, 0, 0, r, g, b + n, 0, 0, 0, 0, 0, 1, 0], m);
},
_colorize = function(m, color, amount) {
if (isNaN(a... | {
pt.t[pt.p] = val;
} | conditional_block | |
EaselPlugin.js | *
* @author: Jack Doyle, jack@greensock.com
**/
var _gsScope = (typeof(module) !== "undefined" && module.exports && typeof(global) !== "undefined") ? global : this || window; //helps ensure compatibility with AMD/RequireJS and CommonJS/Node
(_gsScope._gsQueue || (_gsScope._gsQueue = [])).push( function() {
"use s... | * This work is subject to the terms at http://greensock.com/standard-license or for
* Club GreenSock members, the software agreement that was issued with your membership. | random_line_split | |
dns_resolver.rs | //! Replacement of service's DNS resolver
use std::{
io::{self, ErrorKind},
net::SocketAddr,
};
use async_trait::async_trait;
use futures::future;
use log::{debug, trace};
use trust_dns_resolver::proto::{
op::{Message, Query},
rr::{DNSClass, Name, RData, RecordType},
};
use shadowsocks::{config::Mode... | {
let mut vaddr = Vec::new();
for record in res.answers() {
match *record.rdata() {
RData::A(addr) => vaddr.push(SocketAddr::new(addr.into(), port)),
RData::AAAA(addr) => vaddr.push(SocketAddr::new(addr.into(), port)),
ref rdata => {
trace!("skipped rd... | identifier_body | |
dns_resolver.rs | //! Replacement of service's DNS resolver
use std::{
io::{self, ErrorKind},
net::SocketAddr,
};
use async_trait::async_trait;
use futures::future;
use log::{debug, trace};
use trust_dns_resolver::proto::{
op::{Message, Query},
rr::{DNSClass, Name, RData, RecordType},
};
use shadowsocks::{config::Mode... | }
impl DnsResolver {
pub fn new(ns: NameServerAddr) -> DnsResolver {
DnsResolver {
ns,
client_cache: DnsClientCache::new(5),
mode: Mode::UdpOnly,
ipv6_first: false,
connect_opts: ConnectOpts::default(),
attempts: 2,
}
}
... | mode: Mode,
ipv6_first: bool,
connect_opts: ConnectOpts,
attempts: usize, | random_line_split |
dns_resolver.rs | //! Replacement of service's DNS resolver
use std::{
io::{self, ErrorKind},
net::SocketAddr,
};
use async_trait::async_trait;
use futures::future;
use log::{debug, trace};
use trust_dns_resolver::proto::{
op::{Message, Query},
rr::{DNSClass, Name, RData, RecordType},
};
use shadowsocks::{config::Mode... | (ns: NameServerAddr) -> DnsResolver {
DnsResolver {
ns,
client_cache: DnsClientCache::new(5),
mode: Mode::UdpOnly,
ipv6_first: false,
connect_opts: ConnectOpts::default(),
attempts: 2,
}
}
pub fn set_mode(&mut self, mode: M... | new | identifier_name |
base.js | define(['exports', './utils', './exception'], function (exports, _utils, _exception) {
'use strict';
var _interopRequire = function (obj) { return obj && obj.__esModule ? obj['default'] : obj; };
exports.__esModule = true;
exports.HandlebarsEnvironment = HandlebarsEnvironment;
exports.createFrame = createFr... |
});
instance.registerHelper('unless', function (conditional, options) {
return instance.helpers['if'].call(this, conditional, { fn: options.inverse, inverse: options.fn, hash: options.hash });
});
instance.registerHelper('with', function (context, options) {
if (isFunction(context)) {
... | {
return options.fn(this);
} | conditional_block |
base.js | define(['exports', './utils', './exception'], function (exports, _utils, _exception) {
'use strict';
var _interopRequire = function (obj) { return obj && obj.__esModule ? obj['default'] : obj; };
exports.__esModule = true;
exports.HandlebarsEnvironment = HandlebarsEnvironment;
exports.createFrame = createFr... | (object) {
var frame = _utils.extend({}, object);
frame._parent = object;
return frame;
}
});
/* [args, ]options */ | createFrame | identifier_name |
base.js | define(['exports', './utils', './exception'], function (exports, _utils, _exception) {
'use strict';
var _interopRequire = function (obj) { return obj && obj.__esModule ? obj['default'] : obj; };
exports.__esModule = true;
exports.HandlebarsEnvironment = HandlebarsEnvironment;
exports.createFrame = createFr... | INFO: 1,
WARN: 2,
ERROR: 3,
level: 1,
// Can be overridden in the host environment
log: function log(level, message) {
if (typeof console !== 'undefined' && logger.level <= level) {
var method = logger.methodMap[level];
(console[method] || console.log).call(console, messag... | methodMap: { 0: 'debug', 1: 'info', 2: 'warn', 3: 'error' },
// State enum
DEBUG: 0, | random_line_split |
base.js | define(['exports', './utils', './exception'], function (exports, _utils, _exception) {
'use strict';
var _interopRequire = function (obj) { return obj && obj.__esModule ? obj['default'] : obj; };
exports.__esModule = true;
exports.HandlebarsEnvironment = HandlebarsEnvironment;
exports.createFrame = createFr... |
});
/* [args, ]options */ | {
var frame = _utils.extend({}, object);
frame._parent = object;
return frame;
} | identifier_body |
order-by.ts | /*
* Example use
* Basic Array of single type: *ngFor="#todo of todoService.todos | orderBy : '-'"
* Multidimensional Array Sort on single column: *ngFor="#todo of todoService.todos | orderBy : ['-status']"
* Multidimensional Array Sort on multiple columns: *ngFor="#todo of todoService.todos | orderBy : ['status... | propertyToCheck.substr(0, 1) == '-'
? propertyToCheck.substr(1)
: propertyToCheck;
return input.sort((a, b) => {
if (a[property] && b[property]) {
return !desc
? OrderByPipe._orderByComparator(a[property], b[property])
: -Order... | {
if (!Array.isArray(input)) return input;
if (
!Array.isArray(config) ||
(Array.isArray(config) && config.length == 1)
) {
var propertyToCheck: string = !Array.isArray(config) ? config : config[0];
var desc = propertyToCheck.substr(0, 1) == '-';
// Basic array
if (
... | identifier_body |
order-by.ts | /*
* Example use
* Basic Array of single type: *ngFor="#todo of todoService.todos | orderBy : '-'"
* Multidimensional Array Sort on single column: *ngFor="#todo of todoService.todos | orderBy : ['-status']"
* Multidimensional Array Sort on multiple columns: *ngFor="#todo of todoService.todos | orderBy : ['status... | );
} else return 0;
});
}
} else {
// Loop over property of the array in order and sort
return input.sort((a, b) => {
for (var i: number = 0; i < config.length; i++) {
let comparison = 0;
var desc = config[i].substr(0, 1) == '-';
... | a.value[property],
b.value[property] | random_line_split |
order-by.ts | /*
* Example use
* Basic Array of single type: *ngFor="#todo of todoService.todos | orderBy : '-'"
* Multidimensional Array Sort on single column: *ngFor="#todo of todoService.todos | orderBy : ['-status']"
* Multidimensional Array Sort on multiple columns: *ngFor="#todo of todoService.todos | orderBy : ['status... | (a, b): number {
if (
isNaN(parseFloat(a)) ||
!isFinite(a) ||
isNaN(parseFloat(b)) ||
!isFinite(b)
) {
// Isn't a number so lowercase the string to properly compare
if (a.toLowerCase() < b.toLowerCase()) return -1;
if (a.toLowerCase() > b.toLowerCase()) return 1;
} ... | _orderByComparator | identifier_name |
Header.tsx | /*
* 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/.
*/
import * as React from 'react';
import { styled } from '@csegames/linaria/react';
import { MID_SCALE, HD_SCALE... | &.Melee {
filter: hue-rotate(110deg);
}
&.Archery {
filter: hue-rotate(-75deg);
}
&.Shout {
filter: hue-rotate(135deg);
}
&.Throwing {
filter: hue-rotate(-135deg);
}
@media (max-width: 1920px) {
background-image: url(../images/abilitybuilder/hd/title-ability-builder-overlay.png... | z-index: -1;
| random_line_split |
Header.tsx | /*
* 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/.
*/
import * as React from 'react';
import { styled } from '@csegames/linaria/react';
import { MID_SCALE, HD_SCALE... |
private getClassType = () => {
switch (game.selfPlayerState.classID) {
case Archetype.BlackKnight:
case Archetype.Mjolnir:
case Archetype.Fianna: {
return 'Melee';
}
case Archetype.Blackguard:
case Archetype.WintersShadow:
case Archetype.ForestStalker: {
... | {
const className = this.props.selectedType ? this.props.selectedType.name : this.getClassType();
return (
<Container>
<Overlay className={className} />
<Text className={className}>{this.props.title}</Text>
</Container>
);
} | identifier_body |
Header.tsx | /*
* 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/.
*/
import * as React from 'react';
import { styled } from '@csegames/linaria/react';
import { MID_SCALE, HD_SCALE... | () {
const className = this.props.selectedType ? this.props.selectedType.name : this.getClassType();
return (
<Container>
<Overlay className={className} />
<Text className={className}>{this.props.title}</Text>
</Container>
);
}
private getClassType = () => {
switch (game... | render | identifier_name |
dashboard.js | /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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.... | var dashboard = '' +
'<div class="col-xs-12 col-md-12 col-lg-12" data-toggle="tooltip" title="' + dashboards[i].title + '">' +
'<a class="block-anch" href="' + url + ' " onclick="return ' + isAvailable +'" target="_blank">' +
'<div class="block-monitoring wrap... | {
var dashboards = dashboardProperties.dashboards;
var dashboard_list = '';
for (var i=0; i<dashboards.length; i++) {
var showDashboard = false;
if (dashboards[i].runtimes[0] == "all") {
showDashboard = true;
} else {
for (var j=0; j<dashboards[i].runtimes.le... | identifier_body |
dashboard.js | /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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.... | () {
var dashboards = dashboardProperties.dashboards;
var dashboard_list = '';
for (var i=0; i<dashboards.length; i++) {
var showDashboard = false;
if (dashboards[i].runtimes[0] == "all") {
showDashboard = true;
} else {
for (var j=0; j<dashboards[i].runtimes... | loadDashboards | identifier_name |
dashboard.js | /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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.... | return "/t/" + tenantDomain + "/dashboards/esb-analytics/?shared=true&timeFrom=" + prevTime + "&timeTo=" + currentTime;
}; | ESBAnalyticsDashboardTypeUtil.prototype.getQueryString = function () {
var currentTime = new Date().getTime();
var prevTime = currentTime - 3600000; | random_line_split |
dashboard.js | /*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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.... |
dashboard += '<h3 class="ellipsis"><i class="fw fw-dashboard fw-lg icon"></i>' + dashboards[i].title + '</h3>' +
'</div>' +
'</a>' +
'</div>';
dashboard_list += dashboard;
}
}
$("#dashboards").html(dashboard_list);
}
// Dashboard... | {
dashboard += '<div class="ribbon-wrapper"><div class="ribbon">Available Soon</div></div>';
} | conditional_block |
settings.js | var Promise = require('bluebird');
var jobConstants = require('../../../engine/constants');
module.exports = function(deps){
var schedulerHelper = require('../helpers/scheduler')(deps);
var authHelper = require('../helpers/auth')(deps);
return {
savePreferences(req, res, next) | email_verified
}, {new: true})
.exec()
.then(
u => {
//Reschedule job if email frequency changed
if(frequency_changed){
schedulerHelper.cancelJob({name: jobConstant... | {
const {email, digest_frequency} = req.body;
const {user} = req;
const currentEmail = user.email;
const currentFrequency = user.digest_frequency;
let email_verified = false;
let frequency_changed = false;
if(email && curr... | identifier_body |
settings.js | var Promise = require('bluebird');
var jobConstants = require('../../../engine/constants');
module.exports = function(deps){
var schedulerHelper = require('../helpers/scheduler')(deps);
var authHelper = require('../helpers/auth')(deps);
return {
savePreferences(req, res, next){
const... | email_verified
}, {new: true})
.exec()
.then(
u => {
//Reschedule job if email frequency changed
if(frequency_changed){
schedulerHelper.cancelJob({name: jobConstant... | random_line_split | |
settings.js | var Promise = require('bluebird');
var jobConstants = require('../../../engine/constants');
module.exports = function(deps){
var schedulerHelper = require('../helpers/scheduler')(deps);
var authHelper = require('../helpers/auth')(deps);
return {
savePreferences(req, res, next){
const... | (req, res, next){
const userid = req.user._id;
deps.models.User.findByIdAndRemove(userid).exec()
.then(() => deps.models.Watchlist.remove({ user_id: userid}).exec())
.then(() => deps.models.Report.remove({ user_id: userid}).exec())
.then(() => sche... | deleteAccount | identifier_name |
sortmerna.py | # -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... | artifact_id = parameters['input']
del parameters['input']
# Get the artifact filepath information
artifact_info = qclient.get("/qiita_db/artifacts/%s/" % artifact_id)
fps = artifact_info['files']
# Get the artifact metadata
prep_info = qclient.get('/qiita_db/prep_template/%s/'
... | """Run Sortmerna with the given parameters
Parameters
----------
qclient : tgp.qiita_client.QiitaClient
The Qiita server client
job_id : str
The job id
parameters : dict
The parameter values
out_dir : str
The path to the job's output directory
Returns
--... | identifier_body |
sortmerna.py | # -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
ainfo = []
# Generates 2 artifacts: one for the ribosomal
# reads and other for the non-ribosomal reads
# Step 4 generating artifacts for Nonribosomal reads
msg = ("Step 4 of 5: Generating artifacts "
"for Nonribosomal reads (%d/{0})").format(len_cmd)
suffixes = ['%s.nonribosomal.... | return False, None, msg | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.