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 |
|---|---|---|---|---|
fs.ts | import path from "path";
import fs from "fs";
import { ResolverSource } from "../source";
export class FS implements ResolverSource {
workingDirectory: string;
contractsBuildDirectory: string;
constructor(workingDirectory: string, contractsBuildDirectory: string) {
this.workingDirectory = workingDirectory;... | (importPath: string, importedFrom: string) {
importedFrom = importedFrom || "";
const possiblePaths = [
importPath,
path.join(path.dirname(importedFrom), importPath)
];
let body, filePath;
for (const possiblePath of possiblePaths) {
try {
const resolvedSource = fs.readFile... | resolve | identifier_name |
fs.ts | import path from "path";
import fs from "fs";
import { ResolverSource } from "../source";
export class FS implements ResolverSource {
workingDirectory: string;
contractsBuildDirectory: string;
constructor(workingDirectory: string, contractsBuildDirectory: string) {
this.workingDirectory = workingDirectory;... | }
return { body, filePath };
}
// Here we're resolving from local files to local files, all absolute.
resolveDependencyPath(importPath: string, dependencyPath: string) {
if (
!(dependencyPath.startsWith("./") || dependencyPath.startsWith("../"))
) {
//if it's *not* a relative path, ... | {
importedFrom = importedFrom || "";
const possiblePaths = [
importPath,
path.join(path.dirname(importedFrom), importPath)
];
let body, filePath;
for (const possiblePath of possiblePaths) {
try {
const resolvedSource = fs.readFileSync(possiblePath, {
encoding: "u... | identifier_body |
app.js | /*
setInterval(function() {
console.log(document.activeElement);
}, 1000);
*/
/*
* Notes regarding app state/modes, activeElements, focusing etc.
* ==============================================================
*
* 1) There is always exactly one item selected. All executed commands
* operate on this item.
... | }
} | random_line_split | |
standard.ie.js | /**
* Template JS for Internet Explorer 8 and lower - mainly workaround for missing selectors
*/
(function($)
{
// Standard template setup for IE
$.fn.addTemplateSetup(function()
{
// Clean existing classes
this.find('.first-child').removeClass('first-child');
this.find('.last-child').removeClass... |
});
$('input[type=radio].mini-switch, input[type=checkbox].mini-switch').click(function() {
if (!this.checked)
{
$(this).next('.mini-switch-replace').addClass('mini-switch-replace-checked');
}
else
{
$(this).next('.mini-switch-replace').removeClass('mini-switch-replace-checked'... | {
$(this).next('.switch-replace').removeClass('switch-replace-checked');
} | conditional_block |
standard.ie.js | /**
| {
// Standard template setup for IE
$.fn.addTemplateSetup(function()
{
// Clean existing classes
this.find('.first-child').removeClass('first-child');
this.find('.last-child').removeClass('last-child');
this.find('.last-of-type').removeClass('last-of-type');
this.find('.even').removeClass('even');
... | * Template JS for Internet Explorer 8 and lower - mainly workaround for missing selectors
*/
(function($)
| random_line_split |
table_caption.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/. */
//! CSS table formatting contexts.
#![deny(unsafe_block)]
use block::BlockFlow;
use construct::FlowConstructor;
... | (&mut self, block_position: Au) {
self.block_flow.update_late_computed_block_position_if_necessary(block_position)
}
fn build_display_list(&mut self, layout_context: &LayoutContext) {
debug!("build_display_list_table_caption: same process as block flow");
self.block_flow.build_display_l... | update_late_computed_block_position_if_necessary | identifier_name |
table_caption.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/. */
//! CSS table formatting contexts.
#![deny(unsafe_block)]
use block::BlockFlow;
use construct::FlowConstructor;
... |
fn bubble_inline_sizes(&mut self) {
self.block_flow.bubble_inline_sizes();
}
fn assign_inline_sizes(&mut self, ctx: &LayoutContext) {
debug!("assign_inline_sizes({}): assigning inline_size for flow", "table_caption");
self.block_flow.assign_inline_sizes(ctx);
}
fn assign_... | {
&mut self.block_flow
} | identifier_body |
table_caption.rs | * 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/. */
//! CSS table formatting contexts.
#![deny(unsafe_block)]
use block::BlockFlow;
use construct::FlowConstructor;
use context::LayoutContext;
use flow::{TableCaptionFlowClass, FlowClass... | /* This Source Code Form is subject to the terms of the Mozilla Public | random_line_split | |
log.py | import logging
import terminal
INFO = logging.INFO
# between info and debug
VERBOSE = (logging.INFO + logging.DEBUG) / 2
DEBUG = logging.DEBUG
log = logging.getLogger('rdopkg')
log.setLevel(logging.INFO)
if len(log.handlers) < 1:
formatter = logging.Formatter(fmt='%(message)s')
handler = logging.StreamHandl... | (*args, **kwargs):
log.log(VERBOSE, *args, **kwargs)
def debug(*args, **kwargs):
log.debug(*args, **kwargs)
def command(*args, **kwargs):
log.info(*args, **kwargs)
| verbose | identifier_name |
log.py | import logging
import terminal
INFO = logging.INFO
# between info and debug
VERBOSE = (logging.INFO + logging.DEBUG) / 2
DEBUG = logging.DEBUG
log = logging.getLogger('rdopkg')
log.setLevel(logging.INFO)
if len(log.handlers) < 1:
formatter = logging.Formatter(fmt='%(message)s')
handler = logging.StreamHandl... | def warn(*args, **kwargs):
if args:
largs = list(args)
largs[0] = term.warn(args[0])
args = tuple(largs)
log.warning(*args, **kwargs)
def success(*args, **kwargs):
if args:
largs = list(args)
largs[0] = term.good(args[0])
args = tuple(largs)
log.info(*ar... | log.error(*args, **kwargs)
| random_line_split |
log.py | import logging
import terminal
INFO = logging.INFO
# between info and debug
VERBOSE = (logging.INFO + logging.DEBUG) / 2
DEBUG = logging.DEBUG
log = logging.getLogger('rdopkg')
log.setLevel(logging.INFO)
if len(log.handlers) < 1:
formatter = logging.Formatter(fmt='%(message)s')
handler = logging.StreamHandl... |
term = LogTerminal()
def set_colors(colors):
global term
if colors == 'yes':
if not terminal.COLOR_TERMINAL:
return False
term = LogTerminal(force_styling=True)
return True
elif colors == 'no':
if not terminal.COLOR_TERMINAL:
return True
t... | return self.cyan | identifier_body |
log.py | import logging
import terminal
INFO = logging.INFO
# between info and debug
VERBOSE = (logging.INFO + logging.DEBUG) / 2
DEBUG = logging.DEBUG
log = logging.getLogger('rdopkg')
log.setLevel(logging.INFO)
if len(log.handlers) < 1:
formatter = logging.Formatter(fmt='%(message)s')
handler = logging.StreamHandl... |
elif colors == 'no':
if not terminal.COLOR_TERMINAL:
return True
term = LogTerminal(force_styling=None)
return True
elif colors == 'auto':
term = LogTerminal()
return True
return False
def error(*args, **kwargs):
if args:
largs = list(args)
... | if not terminal.COLOR_TERMINAL:
return False
term = LogTerminal(force_styling=True)
return True | conditional_block |
db.py | import pymysql.cursors
from model.group import Group
from model.contact import Contact
class DbFixture:
def __init__(self, host, name, user, password):
self.host = host
self.name = name
self.user = user
self.password = password
self.connection = pymysql.connect(host=host, ... |
finally:
cursor.close()
return list
def get_contact_list(self):
list = []
cursor = self.connection.cursor()
try:
cursor.execute("SELECT id, firstname, middlename, lastname, nickname, title, company, address, "
"home, mobile... | (ident, name, header, footer) = row
list.append(Group(ident=str(ident), name=name, header=header, footer=footer)) | conditional_block |
db.py | import pymysql.cursors
from model.group import Group
from model.contact import Contact
class DbFixture:
def | (self, host, name, user, password):
self.host = host
self.name = name
self.user = user
self.password = password
self.connection = pymysql.connect(host=host, database=name, user=user, password=password)
self.connection.autocommit(True)
def get_group_list(self):
... | __init__ | identifier_name |
db.py | import pymysql.cursors
from model.group import Group
from model.contact import Contact
class DbFixture:
def __init__(self, host, name, user, password):
self.host = host
self.name = name
self.user = user
self.password = password
self.connection = pymysql.connect(host=host, ... | self.connection.close() | identifier_body | |
db.py | import pymysql.cursors
from model.group import Group
from model.contact import Contact
class DbFixture:
def __init__(self, host, name, user, password):
self.host = host
self.name = name
self.user = user
self.password = password
self.connection = pymysql.connect(host=host, ... | "phone2, notes FROM addressbook WHERE deprecated='0000-00-00 00:00:00'")
for row in cursor:
(ident, firstname, middlename, lastname, nickname, title, company, company_address,
homephone, mobilephone, workphone, telephone_fax, email, email2, email3,... | list = []
cursor = self.connection.cursor()
try:
cursor.execute("SELECT id, firstname, middlename, lastname, nickname, title, company, address, "
"home, mobile, work, fax, email, email2, email3, homepage, byear, ayear, address2, " | random_line_split |
crispyforms.py | #
# Copyright (C) 2013 Uninett AS
#
# This file is part of Network Administration Visualized (NAV).
#
# NAV is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License version 3 as published by
# the Free Software Foundation.
#
# This program is distributed in the hope... | (Field):
"""Field that displays an icon with tooltip as helptext"""
template = 'custom_crispy_templates/field_helptext_as_icon.html'
class NumberInput(forms.TextInput):
"""Input widget with type set to number"""
input_type = 'number'
class NumberField(forms.IntegerField):
"""Input field with t... | HelpField | identifier_name |
crispyforms.py | #
# Copyright (C) 2013 Uninett AS
#
# This file is part of Network Administration Visualized (NAV).
#
# NAV is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License version 3 as published by
# the Free Software Foundation.
#
# This program is distributed in the hope... | class HelpField(Field):
"""Field that displays an icon with tooltip as helptext"""
template = 'custom_crispy_templates/field_helptext_as_icon.html'
class NumberInput(forms.TextInput):
"""Input widget with type set to number"""
input_type = 'number'
class NumberField(forms.IntegerField):
"""Inp... | """Checkbox suited for the NAV layout"""
template = 'custom_crispy_templates/horizontal_checkbox.html'
| random_line_split |
crispyforms.py | #
# Copyright (C) 2013 Uninett AS
#
# This file is part of Network Administration Visualized (NAV).
#
# NAV is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License version 3 as published by
# the Free Software Foundation.
#
# This program is distributed in the hope... |
class NumberInput(forms.TextInput):
"""Input widget with type set to number"""
input_type = 'number'
class NumberField(forms.IntegerField):
"""Input field with type set to number"""
widget = NumberInput
| """Field that displays an icon with tooltip as helptext"""
template = 'custom_crispy_templates/field_helptext_as_icon.html' | identifier_body |
breadcrumbs.component.spec.ts | /* tslint:disable:no-unused-variable */
import { async, ComponentFixture, TestBed, inject } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { BreadcrumbsComponent } from './breadcrumbs.component';
import { BreadcrumbsService, Breadcrumb... |
});
| {
let element = fixture.debugElement.query(By.css(selector));
return element && element.nativeElement;
} | identifier_body |
breadcrumbs.component.spec.ts | /* tslint:disable:no-unused-variable */
import { async, ComponentFixture, TestBed, inject } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { BreadcrumbsComponent } from './breadcrumbs.component';
import { BreadcrumbsService, Breadcrumb... |
fixture.detectChanges();
expect(getByCss('span div').innerText).toBe(title);
expect(getByCss('span a')).toBeNull();
});
function getByCss(selector: string) {
let element = fixture.debugElement.query(By.css(selector));
return element && element.nativeElement;
}
}); | breadcrumbsService.addBreadcrumbs(new BreadcrumbsItem(title)); | random_line_split |
breadcrumbs.component.spec.ts | /* tslint:disable:no-unused-variable */
import { async, ComponentFixture, TestBed, inject } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { BreadcrumbsComponent } from './breadcrumbs.component';
import { BreadcrumbsService, Breadcrumb... | (selector: string) {
let element = fixture.debugElement.query(By.css(selector));
return element && element.nativeElement;
}
});
| getByCss | identifier_name |
main.py | """
Python implementation of the matrix information measurement examples from the
StackExchange answer written by WilliamAHuber for
"Measuring entropy/ information/ patterns of a 2d binary matrix"
http://stats.stackexchange.com/a/17556/43909
Copyright 2014 Cosmo Harrigan
This program is free software, distributed unde... |
pyplot.show() | print("Profile:\n{0}\n".format(profile(matrices))) | random_line_split |
main.py | """
Python implementation of the matrix information measurement examples from the
StackExchange answer written by WilliamAHuber for
"Measuring entropy/ information/ patterns of a 2d binary matrix"
http://stats.stackexchange.com/a/17556/43909
Copyright 2014 Cosmo Harrigan
This program is free software, distributed unde... |
print("Profile:\n{0}\n".format(profile(matrices)))
pyplot.show()
| output_matrix = moving_window_filter(matrix=active_matrix,
f=F,
neighborhood_size=n)
matrices.append(output_matrix)
subplot = pyplot.subplot(5, 4, m * 4 + n)
pyplot.axis('off')
pyplot.imshow(output_... | conditional_block |
es5_extract_plugin.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {PathManipulation} from '@angular/compiler-cli/private/localize';
import {ɵParsedMessage, ɵparseMessage} from '... | }
}
}
};
}
| throw e;
}
| conditional_block |
es5_extract_plugin.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {PathManipulation} from '@angular/compiler-cli/private/localize'; |
import {buildCodeFrameError, getLocation, isBabelParseError, isGlobalIdentifier, isNamedIdentifier, unwrapMessagePartsFromLocalizeCall, unwrapSubstitutionsFromLocalizeCall} from '../../source_file_utils';
export function makeEs5ExtractPlugin(
fs: PathManipulation, messages: ɵParsedMessage[], localizeName = '$loca... | import {ɵParsedMessage, ɵparseMessage} from '@angular/localize';
import {NodePath, PluginObj, types as t} from '../../babel_core'; | random_line_split |
es5_extract_plugin.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {PathManipulation} from '@angular/compiler-cli/private/localize';
import {ɵParsedMessage, ɵparseMessage} from '... | llPath: NodePath<t.CallExpression>) {
try {
const calleePath = callPath.get('callee');
if (isNamedIdentifier(calleePath, localizeName) && isGlobalIdentifier(calleePath)) {
const [messageParts, messagePartLocations] =
unwrapMessagePartsFromLocalizeCall(callPath, fs... | lExpression(ca | identifier_name |
es5_extract_plugin.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {PathManipulation} from '@angular/compiler-cli/private/localize';
import {ɵParsedMessage, ɵparseMessage} from '... | // by Babel parsing a TaggedTemplateExpression.
throw buildCodeFrameError(fs, callPath, e);
} else {
throw e;
}
}
}
}
};
}
| return {
visitor: {
CallExpression(callPath: NodePath<t.CallExpression>) {
try {
const calleePath = callPath.get('callee');
if (isNamedIdentifier(calleePath, localizeName) && isGlobalIdentifier(calleePath)) {
const [messageParts, messagePartLocations] =
... | identifier_body |
malformed-param-list.rs | #![feature(plugin)]
#![plugin(rocket_codegen)]
#[get("/><")] //~ ERROR malformed
fn get() -> &'static str { "hi" }
#[get("/<name><")] //~ ERROR malformed
fn get1(name: &str) -> &'static str { "hi" }
#[get("/<<<<name><")] //~ ERROR malformed
fn get2(name: &str) -> &'static str { "hi" }
#[get("/<!>")] //~ ERROR ident... |
#[get("/<>")] //~ ERROR empty
fn get8() -> &'static str { "hi" }
fn main() { }
| { "hi" } | identifier_body |
malformed-param-list.rs | #![feature(plugin)]
#![plugin(rocket_codegen)]
#[get("/><")] //~ ERROR malformed
fn get() -> &'static str { "hi" }
#[get("/<name><")] //~ ERROR malformed
fn get1(name: &str) -> &'static str { "hi" }
#[get("/<<<<name><")] //~ ERROR malformed
fn get2(name: &str) -> &'static str { "hi" }
#[get("/<!>")] //~ ERROR ident... |
#[get("/<>")] //~ ERROR empty
fn get8() -> &'static str { "hi" }
fn main() { } | #[get("/<>name><")] //~ ERROR malformed
fn get6() -> &'static str { "hi" }
#[get("/<name>:<id>")] //~ ERROR identifiers
fn get7() -> &'static str { "hi" } | random_line_split |
malformed-param-list.rs | #![feature(plugin)]
#![plugin(rocket_codegen)]
#[get("/><")] //~ ERROR malformed
fn | () -> &'static str { "hi" }
#[get("/<name><")] //~ ERROR malformed
fn get1(name: &str) -> &'static str { "hi" }
#[get("/<<<<name><")] //~ ERROR malformed
fn get2(name: &str) -> &'static str { "hi" }
#[get("/<!>")] //~ ERROR identifiers
fn get3() -> &'static str { "hi" }
#[get("/<_>")] //~ ERROR ignored
fn get4() ->... | get | identifier_name |
address_resolver.py | # Rekall Memory Forensics
# Copyright 2014 Google Inc. All Rights Reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or (at
# your option) any later ver... |
# Insert a psuedo module for the kernel
self.AddModule(KernelModule(session=self.session))
# Add LKMs.
for kmod in self.session.plugins.lsmod().get_module_list():
self.AddModule(LKMModule(kmod, session=self.session))
self._initialized = True
| return | conditional_block |
address_resolver.py | # Rekall Memory Forensics
# Copyright 2014 Google Inc. All Rights Reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or (at
# your option) any later ver... | (self):
if self._initialized:
return
# Insert a psuedo module for the kernel
self.AddModule(KernelModule(session=self.session))
# Add LKMs.
for kmod in self.session.plugins.lsmod().get_module_list():
self.AddModule(LKMModule(kmod, session=self.session))
... | _EnsureInitialized | identifier_name |
address_resolver.py | # Rekall Memory Forensics
# Copyright 2014 Google Inc. All Rights Reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or (at
# your option) any later ver... | class LKMModule(address_resolver.Module):
"""A Linux kernel module."""
def __init__(self, module, **kwargs):
self.module = module
super(LKMModule, self).__init__(
name=unicode(module.name),
start=module.base,
end=module.end,
**kwargs)
class Kern... | from rekall import obj
from rekall.plugins.common import address_resolver
from rekall.plugins.linux import common
| random_line_split |
address_resolver.py | # Rekall Memory Forensics
# Copyright 2014 Google Inc. All Rights Reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or (at
# your option) any later ver... |
class KernelModule(address_resolver.Module):
"""A Fake object which makes the kernel look like a module.
This removes the need to treat kernel addresses any different from module
addresses, and allows them to be resolved by this module.
"""
def __init__(self, session=None, **kwargs):
su... | """A Linux kernel module."""
def __init__(self, module, **kwargs):
self.module = module
super(LKMModule, self).__init__(
name=unicode(module.name),
start=module.base,
end=module.end,
**kwargs) | identifier_body |
Gruntfile.js | module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
browserify: {
control: {
src: ['src/L.Realtime.js'], | [
'browserify-shim',
{
'leaflet': 'global:L'
}
],
],
browserifyOptions: {
standalone: 'L.Realtime'
}
}
}
},
uglify: {
options: {
banner: '/*! <%= pkg.name %> - v<%= pkg.version %> - ' +
'<%= grunt.template.today("yyyy-mm-dd") %> */\n\n'... | dest: 'dist/leaflet-realtime.js',
options: {
transform: [ | random_line_split |
px-validation-custom-tests.js | // This is the wrapper for custom tests, called upon web components ready state
function | () {
// Place any setup steps like variable declaration and initialization here
// This is the placeholder suite to place custom tests in
// Use testCase(options) for a more convenient setup of the test cases
suite('Custom Automation Tests for px-validation', function() {
var px_validation = document.getEl... | runCustomTests | identifier_name |
px-validation-custom-tests.js | // This is the wrapper for custom tests, called upon web components ready state
function runCustomTests() {
// Place any setup steps like variable declaration and initialization here
// This is the placeholder suite to place custom tests in
// Use testCase(options) for a more convenient setup of the test cases
... | });
test('Integer isNumber validation returns true', function() {
assert.isTrue(px_validation.validate(2).passedValidation);
});
test('String representation of number via isNumber validation returns true', function() {
assert.isTrue(px_validation.validate('2').passedValidation);
});
})... | });
test('Check there is a single px-validator child defined on test fixture', function(){
assert.lengthOf(Polymer.dom(px_validation).children, 1); | random_line_split |
px-validation-custom-tests.js | // This is the wrapper for custom tests, called upon web components ready state
function runCustomTests() | test('String representation of number via isNumber validation returns true', function() {
assert.isTrue(px_validation.validate('2').passedValidation);
});
});
}
| {
// Place any setup steps like variable declaration and initialization here
// This is the placeholder suite to place custom tests in
// Use testCase(options) for a more convenient setup of the test cases
suite('Custom Automation Tests for px-validation', function() {
var px_validation = document.getEleme... | identifier_body |
wasm32_experimental_emscripten.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 ... | target_c_int_width: "32".to_string(),
target_os: "emscripten".to_string(),
target_env: String::new(),
target_vendor: "unknown".to_string(),
data_layout: "e-m:e-p:32:32-i64:64-n32:64-S128".to_string(),
arch: "wasm32".to_string(),
linker_flavor: LinkerFlavor::Em,
... | target_endian: "little".to_string(),
target_pointer_width: "32".to_string(), | random_line_split |
wasm32_experimental_emscripten.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 ... | obj_is_bitcode: true,
is_like_emscripten: true,
max_atomic_width: Some(32),
post_link_args,
target_family: Some("unix".to_string()),
.. Default::default()
};
Ok(Target {
llvm_target: "wasm32-unknown-unknown".to_string(),
target_endian: "little".to_... | {
let mut post_link_args = LinkArgs::new();
post_link_args.insert(LinkerFlavor::Em,
vec!["-s".to_string(),
"WASM=1".to_string(),
"-s".to_string(),
"ASSERTIONS=1".to_string(),
... | identifier_body |
wasm32_experimental_emscripten.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 ... | () -> Result<Target, String> {
let mut post_link_args = LinkArgs::new();
post_link_args.insert(LinkerFlavor::Em,
vec!["-s".to_string(),
"WASM=1".to_string(),
"-s".to_string(),
"ASSERTIONS=1".to... | target | identifier_name |
lib.rs | #[derive(serde::Deserialize, Debug)]
struct HasuraError {
error: HasuraInfo,
}
#[derive(serde::Deserialize, Debug)]
struct HasuraInfo {
description: Option<String>,
exec_status: String,
hint: Option<String>,
message: String,
status_code: String,
}
#[cfg(test)]
mod tests {
#[test]
fn it... | ) -> Result<D, Vec<String>> {
let data = req.send().await.map_err(|e| vec![format!("{:?}", e)])?;
let decode: reqwest::Result<graphql_client::Response<D>> = data.json().await;
let body = decode.map_err(|e| vec![format!("{:?}", e)])?;
match body.data {
Some(d) => Ok(d),
None => Err(mat... | /// [GraphQL Spec](http://spec.graphql.org/draft/#sec-Errors)
pub async fn graphql_request<D: serde::de::DeserializeOwned>(
req: reqwest::RequestBuilder, | random_line_split |
lib.rs | #[derive(serde::Deserialize, Debug)]
struct HasuraError {
error: HasuraInfo,
}
#[derive(serde::Deserialize, Debug)]
struct HasuraInfo {
description: Option<String>,
exec_status: String,
hint: Option<String>,
message: String,
status_code: String,
}
#[cfg(test)]
mod tests {
#[test]
fn it... |
None => e.message,
}
})
.collect()
}
| {
format!("{}\n{:?}", e.message, h_err)
} | conditional_block |
lib.rs | #[derive(serde::Deserialize, Debug)]
struct HasuraError {
error: HasuraInfo,
}
#[derive(serde::Deserialize, Debug)]
struct HasuraInfo {
description: Option<String>,
exec_status: String,
hint: Option<String>,
message: String,
status_code: String,
}
#[cfg(test)]
mod tests {
#[test]
fn it... | (errors: Vec<graphql_client::Error>) -> Vec<String> {
errors
.into_iter()
.map(|e| {
let internal = e
.extensions
.as_ref()
.and_then(|ext| ext.get("internal"))
.and_then(|v| serde_json::from_value::<HasuraError>(v.clone()).... | parse_errors | identifier_name |
lib.rs | #[derive(serde::Deserialize, Debug)]
struct HasuraError {
error: HasuraInfo,
}
#[derive(serde::Deserialize, Debug)]
struct HasuraInfo {
description: Option<String>,
exec_status: String,
hint: Option<String>,
message: String,
status_code: String,
}
#[cfg(test)]
mod tests {
#[test]
fn it... |
fn parse_errors(errors: Vec<graphql_client::Error>) -> Vec<String> {
errors
.into_iter()
.map(|e| {
let internal = e
.extensions
.as_ref()
.and_then(|ext| ext.get("internal"))
.and_then(|v| serde_json::from_value::<HasuraE... | {
let req = client
.post(graphql_endpoint.as_str())
.header("x-hasura-admin-secret", hasura_admin_secret.as_bytes())
.json(&body);
graphql_request(req).await
} | identifier_body |
object-one-type-two-traits.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | self as Box<Any+'static>
}
}
fn is<T:Any>(x: &Any) -> bool {
x.is::<T>()
}
fn main() {
let x = box 22isize as Box<Wrap>;
println!("x={}", x.get());
let y = x.wrap();
} | impl Wrap for isize {
fn get(&self) -> isize {
*self
}
fn wrap(self: Box<isize>) -> Box<Any+'static> { | random_line_split |
object-one-type-two-traits.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let x = box 22isize as Box<Wrap>;
println!("x={}", x.get());
let y = x.wrap();
} | identifier_body | |
object-one-type-two-traits.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <T:Any>(x: &Any) -> bool {
x.is::<T>()
}
fn main() {
let x = box 22isize as Box<Wrap>;
println!("x={}", x.get());
let y = x.wrap();
}
| is | identifier_name |
emr_terminate_job_flow_operator.py | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""This module is deprecated. Please use `airflow.providers.amazon.aws.operators.emr_terminate_job_flow`."""
import warning... | # http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an | random_line_split |
wcst.py | # -*- coding: utf-8 -*-
"""Programa baseado no Teste Wisconsin
Autor: Neno Henrique Albernaz
Criado em Junho de 2008"""
########################################################################
class Carta:
# Definição dos itens de uma carta.
_numeros = [(u"Um", u"Uma"),
(u"Dois", u"D... | listaCategorias = criaListaCategorias()
numCartasResposta = 64 | ########################################################################
# Inicializa as variaveis.
listaCartasResposta = criaListaResposta()
listaCartasEstimulo = criaListaEstimulo()
| random_line_split |
wcst.py | # -*- coding: utf-8 -*-
"""Programa baseado no Teste Wisconsin
Autor: Neno Henrique Albernaz
Criado em Junho de 2008"""
########################################################################
class Carta:
# Definição dos itens de uma carta.
_numeros = [(u"Um", u"Uma"),
(u"Dois", u"D... | ##############################################################
def instrucoes_teste():
"""Imprimi na tela as instruções do teste. """
return u"""Este é um teste um pouco diferente, porque eu não posso lhe
dizer muito a respeito do que fazer. Você vai ser solicitado a associar
cada uma das carta... | ta de categorias.
Cria a lista com as três categorias: cor, forma e numero. Repete
devido ao teste passar duas vezes nas categorias."""
return ["cor", "forma", "numero", "cor", "forma", "numero"]
########## | identifier_body |
wcst.py | # -*- coding: utf-8 -*-
"""Programa baseado no Teste Wisconsin
Autor: Neno Henrique Albernaz
Criado em Junho de 2008"""
########################################################################
class Carta:
# Definição dos itens de uma carta.
_numeros = [(u"Um", u"Uma"),
(u"Dois", u"D... | eturn True
########################################################################
def criaListaEstimulo():
"""Cria a lista de cartas estimulo. O conteudo de cada item da lista é uma carta."""
return [Carta(1, 0, 0),
Carta(2, 1, 1),
Carta(3, 2, 2),
Carta(4, 3, 3)]... | e
r | conditional_block |
wcst.py | # -*- coding: utf-8 -*-
"""Programa baseado no Teste Wisconsin
Autor: Neno Henrique Albernaz
Criado em Junho de 2008"""
########################################################################
class Carta:
# Definição dos itens de uma carta.
_numeros = [(u"Um", u"Uma"),
(u"Dois", u"D... | ria a lista de categorias.
Cria a lista com as três categorias: cor, forma e numero. Repete
devido ao teste passar duas vezes nas categorias."""
return ["cor", "forma", "numero", "cor", "forma", "numero"]
########################################################################
def instrucoes_te... | gorias():
"""C | identifier_name |
client.py | # Copyright 2012 OpenStack Foundation
# 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 requ... |
def get_cached_images(self, **kwargs):
"""
Returns a list of images stored in the image cache.
"""
res = self.do_request("GET", "/cached_images")
data = json.loads(res.read())['cached_images']
return data
def get_queued_images(self, **kwargs):
"""
... | """
Delete a specified image from the cache
"""
self.do_request("DELETE", "/cached_images/%s" % image_id)
return True | identifier_body |
client.py | # Copyright 2012 OpenStack Foundation
# 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 requ... | (self):
"""
Delete all queued images
"""
res = self.do_request("DELETE", "/queued_images")
data = json.loads(res.read())
num_deleted = data['num_deleted']
return num_deleted
def get_client(host, port=None, timeout=None, use_ssl=False, username=None,
... | delete_all_queued_images | identifier_name |
client.py | # Copyright 2012 OpenStack Foundation
# 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 requ... |
else:
force_strategy = None
creds = {
'username': username or
os.getenv('OS_AUTH_USER', os.getenv('OS_USERNAME')),
'password': password or
os.getenv('OS_AUTH_KEY', os.getenv('OS_PASSWORD')),
'tenant': tenant or
os.getenv('OS_AUTH_TENANT', os.getenv('OS_T... | force_strategy = 'keystone' | conditional_block |
client.py | # Copyright 2012 OpenStack Foundation
# 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 requ... |
def delete_all_cached_images(self):
"""
Delete all cached images
"""
res = self.do_request("DELETE", "/cached_images")
data = json.loads(res.read())
num_deleted = data['num_deleted']
return num_deleted
def queue_image_for_caching(self, image_id):
... | """
res = self.do_request("GET", "/queued_images")
data = json.loads(res.read())['queued_images']
return data | random_line_split |
BezierEasing.ts | const NEWTON_ITERATIONS = 4;
const NEWTON_MIN_SLOPE = 1e-3;
const SUBDIVISION_PRECISION = 1e-7;
const SUBDIVISION_MAX_ITERATIONS = 10;
const kSplineTableSize = 11;
const kSampleStepSize = 1 / (kSplineTableSize - 1);
const isFloat32ArraySupported = typeof Float32Array === 'function';
function A(aA1: number, aA2: number... |
/** Returns dx/dt given t, x1, and x2, or dy/dt given t, y1, and y2. */
function getSlope(aT: number, aA1: number, aA2: number) {
return 3 * A(aA1, aA2) * aT * aT + 2 * B(aA1, aA2) * aT + C(aA1);
}
function binarySubdivide(aX: number, aA: number, aB: number, mX1: number, mX2: number) {
let currentX;
let curren... | {
return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT;
} | identifier_body |
BezierEasing.ts | const NEWTON_ITERATIONS = 4;
const NEWTON_MIN_SLOPE = 1e-3;
const SUBDIVISION_PRECISION = 1e-7;
const SUBDIVISION_MAX_ITERATIONS = 10;
const kSplineTableSize = 11;
const kSampleStepSize = 1 / (kSplineTableSize - 1);
const isFloat32ArraySupported = typeof Float32Array === 'function';
function A(aA1: number, aA2: number... | (aA1: number, aA2: number) {
return 3 * aA2 - 6 * aA1;
}
function C(aA1: number) {
return 3 * aA1;
}
/** Returns x(t) given t, x1, and x2, or y(t) given t, y1, and y2. */
function calcBezier(aT: number, aA1: number, aA2: number) {
return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT;
}
/** Returns dx/d... | B | identifier_name |
BezierEasing.ts | const NEWTON_ITERATIONS = 4;
const NEWTON_MIN_SLOPE = 1e-3;
const SUBDIVISION_PRECISION = 1e-7;
const SUBDIVISION_MAX_ITERATIONS = 10;
const kSplineTableSize = 11;
const kSampleStepSize = 1 / (kSplineTableSize - 1);
const isFloat32ArraySupported = typeof Float32Array === 'function';
function A(aA1: number, aA2: number... | return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT;
}
/** Returns dx/dt given t, x1, and x2, or dy/dt given t, y1, and y2. */
function getSlope(aT: number, aA1: number, aA2: number) {
return 3 * A(aA1, aA2) * aT * aT + 2 * B(aA1, aA2) * aT + C(aA1);
}
function binarySubdivide(aX: number, aA: number, aB:... | return 3 * aA1;
}
/** Returns x(t) given t, x1, and x2, or y(t) given t, y1, and y2. */
function calcBezier(aT: number, aA1: number, aA2: number) { | random_line_split |
puxaTweets.py | #-*- coding: utf8 -*-
import pymongo, time as T, threading as t, sys
from twython import TwythonStreamer
from twython import Twython
from maccess import TW, mdc
HTAG=["#aao0","#arenaNETmundial","#Participabr"]
HTAG_=[i.replace("#","H") for i in HTAG]
class MyStreamer(TwythonStreamer):
def on_success(self, data):
... | tweets=tweets_antes+self.ttweets+tweets_depois
self.mdb.drop_collection(self.collection)
self.mongo_collection.insert(tweets)
elif len(tweets_depois):
self.mongo_collection.insert(tweets_depois)
elif 'ttweets' in dir(self):
self.mongo_collectio... | if self.mongo_collection.count():
self.ttweets=[i for i in self.query] | random_line_split |
puxaTweets.py | #-*- coding: utf8 -*-
import pymongo, time as T, threading as t, sys
from twython import TwythonStreamer
from twython import Twython
from maccess import TW, mdc
HTAG=["#aao0","#arenaNETmundial","#Participabr"]
HTAG_=[i.replace("#","H") for i in HTAG]
class MyStreamer(TwythonStreamer):
def on_success(self, data):
... |
class AcompanhaTweet(t.Thread):
def __init__(self,hashtag="#aao0",connection_specs=TW[0],mongo_uri=mdc.u1,collection=None):
t.Thread.__init__(self)
self.hashtag=hashtag
if collection==None:
collection=hashtag.replace("#","HH")
self.collection=collection
self.mon... | print status_code | identifier_body |
puxaTweets.py | #-*- coding: utf8 -*-
import pymongo, time as T, threading as t, sys
from twython import TwythonStreamer
from twython import Twython
from maccess import TW, mdc
HTAG=["#aao0","#arenaNETmundial","#Participabr"]
HTAG_=[i.replace("#","H") for i in HTAG]
class MyStreamer(TwythonStreamer):
def on_success(self, data):
... | (self, status_code, data):
print status_code
class AcompanhaTweet(t.Thread):
def __init__(self,hashtag="#aao0",connection_specs=TW[0],mongo_uri=mdc.u1,collection=None):
t.Thread.__init__(self)
self.hashtag=hashtag
if collection==None:
collection=hashtag.replace("#","HH")... | on_error | identifier_name |
puxaTweets.py | #-*- coding: utf8 -*-
import pymongo, time as T, threading as t, sys
from twython import TwythonStreamer
from twython import Twython
from maccess import TW, mdc
HTAG=["#aao0","#arenaNETmundial","#Participabr"]
HTAG_=[i.replace("#","H") for i in HTAG]
class MyStreamer(TwythonStreamer):
def on_success(self, data):
... | print "puxados todos os tweets de antes ",self.hashtag
return tweets[::-1]
def buscaRetroativa(self,max_id):
tweets=self.twitter_connection.search(q=self.hashtag,count=100,max_id=max_id-1,result_type="recent")["statuses"]
print "puxado retroativo",len(tweets),self.hashtag
return tw... | =tweets_
T.sleep(60)
tweets_=self.buscaRetroativa(max_id=tweets[-1]["id"])
| conditional_block |
EditorCommands.js | undefined);
editor.nodeChanged();
}
function storeSelection(type) {
bookmark = selection.getBookmark(type);
}
function restoreSelection() {
selection.moveToBookmark(bookmark);
}
// Add execCommand overrides
addCommands({
// Ignore these, added for compatibility
'mceResetDesignMode,mceBe... | } else if (!hasSiblingText('nextSibling')) {
html = html.replace(/( | )(<br>|)$/, ' ');
}
}
return html;
}
// Check for whitespace before/after value
if (/^ | $/.test(value)) {
value = trimOrPaddLeftRight(value);
}
// Setup parser and serializer
pa... | {
var rng, container, offset;
rng = selection.getRng(true);
container = rng.startContainer;
offset = rng.startOffset;
function hasSiblingText(siblingName) {
return container[siblingName] && container[siblingName].nodeType == 3;
}
if (container.nodeType == 3) {
if (offse... | identifier_body |
EditorCommands.js | (command, ui, value) {
var func;
command = command.toLowerCase();
if ((func = commands.exec[command])) {
func(command, ui, value);
return TRUE;
}
return FALSE;
}
/**
* Queries the current state for a command for example if the current selection is "bold".
*
* @method queryCommandS... | execCommand | identifier_name | |
EditorCommands.js |
return FALSE;
}
/**
* Queries the current state for a command for example if the current selection is "bold".
*
* @method queryCommandState
* @param {String} command Command to check the state of.
* @return {Boolean/Number} true/false if the selected contents is bold or not, -1 if it's not foun... | {
func(command, ui, value);
return TRUE;
} | conditional_block | |
EditorCommands.js | : undefined);
editor.nodeChanged();
}
function storeSelection(type) {
bookmark = selection.getBookmark(type);
}
function restoreSelection() {
selection.moveToBookmark(bookmark);
}
// Add execCommand overrides
addCommands({
// Ignore these, added for compatibility
'mceResetDesignMode,mce... | if (/^(H[1-6]|P|ADDRESS|PRE)$/.test(listParent.nodeName)) {
storeSelection();
dom.split(listParent, listElm);
restoreSelection();
}
}
},
// Override commands to use the text formatter engine
'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': function(command) {
to... | listElm = dom.getParent(selection.getNode(), 'ol,ul');
if (listElm) {
listParent = listElm.parentNode;
// If list is within a text block then split that block | random_line_split |
enum_and_vtable_mangling.rs | /* automatically generated by rust-bindgen */
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
pub const match_: _bindgen_ty_1 = _bindgen_ty_1::match_;
pub const whatever_else: _bindgen_ty_1 = _bindgen_ty_1::whatever_else;
#[repr(u32)]
#[derive(Debug, Copy, Clone, P... | );
assert_eq!(
unsafe { &(*(::std::ptr::null::<C>())).i as *const _ as usize },
8usize,
concat!("Offset of field: ", stringify!(C), "::", stringify!(i))
);
}
impl Default for C {
fn default() -> Self {
unsafe { ::std::mem::zeroed() }
}
}
extern "C" {
#[link_name =... | 8usize,
concat!("Alignment of ", stringify!(C)) | random_line_split |
enum_and_vtable_mangling.rs | /* automatically generated by rust-bindgen */
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
pub const match_: _bindgen_ty_1 = _bindgen_ty_1::match_;
pub const whatever_else: _bindgen_ty_1 = _bindgen_ty_1::whatever_else;
#[repr(u32)]
#[derive(Debug, Copy, Clone, P... | () {
assert_eq!(
::std::mem::size_of::<C>(),
16usize,
concat!("Size of: ", stringify!(C))
);
assert_eq!(
::std::mem::align_of::<C>(),
8usize,
concat!("Alignment of ", stringify!(C))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<C>())).i as *co... | bindgen_test_layout_C | identifier_name |
dimension.py | # coding=utf-8
# --------------------------------------------------------------------------
# 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 ... | _attribute_map = {
'name': {'key': 'name', 'type': 'str'},
'display_name': {'key': 'displayName', 'type': 'str'},
'internal_name': {'key': 'internalName', 'type': 'str'},
'to_be_exported_for_shoebox': {'key': 'toBeExportedForShoebox', 'type': 'bool'},
}
def __init__(self, na... | :type internal_name: str
:param to_be_exported_for_shoebox:
:type to_be_exported_for_shoebox: bool
"""
| random_line_split |
dimension.py | # coding=utf-8
# --------------------------------------------------------------------------
# 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 ... | (Model):
"""Dimension of a resource metric. For e.g. instance specific HTTP requests
for a web app,
where instance name is dimension of the metric HTTP request.
:param name:
:type name: str
:param display_name:
:type display_name: str
:param internal_name:
:type internal_name: str
... | Dimension | identifier_name |
dimension.py | # coding=utf-8
# --------------------------------------------------------------------------
# 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 ... | super(Dimension, self).__init__()
self.name = name
self.display_name = display_name
self.internal_name = internal_name
self.to_be_exported_for_shoebox = to_be_exported_for_shoebox | identifier_body | |
websocket_teleop.js | import STORE from 'store';
import Worker from 'utils/webworker.js';
export default class TeleopWebSocketEndpoint {
constructor(serverAddr) {
this.serverAddr = serverAddr;
this.websocket = null;
this.worker = new Worker();
}
initialize() {
try {
this.websocket = new WebSocket(this.serverAdd... |
}
executeCommand(command) {
this.websocket.send(JSON.stringify({
type: command,
}));
}
}
| {
this.websocket.onclose = undefined;
this.websocket.close();
} | conditional_block |
websocket_teleop.js | import STORE from 'store';
import Worker from 'utils/webworker.js';
export default class TeleopWebSocketEndpoint {
constructor(serverAddr) {
this.serverAddr = serverAddr;
this.websocket = null;
this.worker = new Worker();
}
initialize() {
try {
this.websocket = new WebSocket(this.serverAdd... | () {
clearInterval(this.timer);
if (this.websocket) {
this.websocket.onclose = undefined;
this.websocket.close();
}
}
executeCommand(command) {
this.websocket.send(JSON.stringify({
type: command,
}));
}
}
| close | identifier_name |
websocket_teleop.js | import STORE from 'store';
import Worker from 'utils/webworker.js';
export default class TeleopWebSocketEndpoint {
constructor(serverAddr) {
this.serverAddr = serverAddr;
this.websocket = null;
this.worker = new Worker();
}
initialize() {
try {
this.websocket = new WebSocket(this.serverAdd... |
executeCommand(command) {
this.websocket.send(JSON.stringify({
type: command,
}));
}
}
| {
clearInterval(this.timer);
if (this.websocket) {
this.websocket.onclose = undefined;
this.websocket.close();
}
} | identifier_body |
websocket_teleop.js | import STORE from 'store';
import Worker from 'utils/webworker.js';
export default class TeleopWebSocketEndpoint {
constructor(serverAddr) {
this.serverAddr = serverAddr;
this.websocket = null;
this.worker = new Worker();
}
initialize() {
try {
this.websocket = new WebSocket(this.serverAdd... |
this.websocket.onmessage = (event) => {
this.worker.postMessage({
source: 'teleop',
data: event.data,
});
};
this.websocket.onclose = (event) => {
console.log(`WebSocket connection closed with code: ${event.code}`);
this.initialize();
};
this.worker.onmessag... | random_line_split | |
order.service.ts | import {Injectable, Inject} from "@angular/core";
import {AppConfig} from "../../app.module";
import {Http, Headers, Response} from "@angular/http";
import {Observable} from "rxjs";
interface auth {
username:string,
password:string
}
@Injectable()
export class OrderService {
constructor(@Inject ('APP_CONFIG_TOKE... |
} | {
return this.http.get(
`http://192.168.222.13:8095/api/salesorder?client=` + id,
//`api/salesorder?client=` + id,
{
headers:new Headers({
'authorization':window.sessionStorage.getItem("authorization")
}
)
}
)
} | identifier_body |
order.service.ts | import {Injectable, Inject} from "@angular/core";
import {AppConfig} from "../../app.module";
import {Http, Headers, Response} from "@angular/http";
import {Observable} from "rxjs";
interface auth {
username:string,
password:string
}
@Injectable()
export class OrderService {
constructor(@Inject ('APP_CONFIG_TOKE... | ():Observable<Response>{
return this.http.get(
`http://192.168.222.13:8095/api/salesorder`,
//`api/salesorder`,
{
headers:new Headers({
'authorization':window.sessionStorage.getItem("authorization")
}
)
}
)
}
getOrderDetail(id):Observable<Response>{
... | getOrder | identifier_name |
order.service.ts | import {Injectable, Inject} from "@angular/core";
import {AppConfig} from "../../app.module";
import {Http, Headers, Response} from "@angular/http";
import {Observable} from "rxjs";
interface auth {
username:string,
password:string
}
@Injectable()
export class OrderService {
constructor(@Inject ('APP_CONFIG_TOKE... | }
getOrderByClientId(id):Observable<Response>{
return this.http.get(
`http://192.168.222.13:8095/api/salesorder?client=` + id,
//`api/salesorder?client=` + id,
{
headers:new Headers({
'authorization':window.sessionStorage.getItem("authorization")
}
)
... | }
) | random_line_split |
__openerp__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
# Copyright (C) 2010-2012 ChriCar Beteiligungs- und Beratungs- GmbH (<http://www.camptocamp.at>) | #
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero ... | #
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version. | random_line_split |
notifications-add-interval.js | var builder = require("botbuilder");
var botbuilder_azure = require("botbuilder-azure");
const notUtils = require('./notifications-utils.js');
module.exports = [
function (session) {
session.beginDialog('notifications-common-symbol');
},
function (session, results) {
var pair = results.res... | function (session, results) {
var sub = notUtils.getBaseNotification('interval', session.message.address);
sub.symbol = session.dialogData.symbol;
sub.interval = session.dialogData.interval;
sub.previousprice = 0;
sub.isfirstun = true;
sub.name = results.response;
... | function (session, results) {
session.dialogData.interval = results.response;
builder.Prompts.text(session, "What name would you like to give to this notification?");
}, | random_line_split |
harbour-papocchio-hu.ts | <?xml version="1.0" ?><!DOCTYPE TS><TS language="hu" version="2.1">
<context>
<name>CoverPage</name>
<message>
<location filename="../qml/cover/CoverPage.qml" line="25"/>
<source>Draw!</source>
<translation>Rajzolhatsz!</translation>
</message>
</context>
<context>
<name>MainPage... | <source>Saving the canvas…</source>
<translation type="unfinished"/>
</message>
<message>
<location filename="../qml/pages/MainPage.qml" line="112"/>
<source>Clearing the canvas…</source>
<translation type="unfinished"/>
</message>
<message>
<location file... | <message>
<location filename="../qml/pages/MainPage.qml" line="76"/> | random_line_split |
cache.py | # -*- coding: utf-8 -*-
# pylint: disable=not-context-manager,useless-object-inheritance
# NOTE: The pylint not-content-manager warning is disabled pending the fix of
# a bug in pylint https://github.com/PyCQA/pylint/issues/782
# NOTE: useless-object-inheritance needed for Python 2.x compatability
"""This module con... | Items are expired from the cache after a given period of time.
Example:
>>> from time import sleep
>>> cache = TimedCache()
>>> cache.put("item", 'some', kw='args', timeout=3)
>>> # Fetch the item again, by providing the same args and kwargs.
>>> assert cache.get('some',... | The cache key is generated by from the given ``*args`` and ``**kwargs``. | random_line_split |
cache.py | # -*- coding: utf-8 -*-
# pylint: disable=not-context-manager,useless-object-inheritance
# NOTE: The pylint not-content-manager warning is disabled pending the fix of
# a bug in pylint https://github.com/PyCQA/pylint/issues/782
# NOTE: useless-object-inheritance needed for Python 2.x compatability
"""This module con... | (self, *args, **kwargs):
"""Delete an item from the cache for this combination of args and
kwargs."""
cache_key = self.make_key(args, kwargs)
with self._cache_lock:
try:
del self._cache[cache_key]
except KeyError:
pass
def clea... | delete | identifier_name |
cache.py | # -*- coding: utf-8 -*-
# pylint: disable=not-context-manager,useless-object-inheritance
# NOTE: The pylint not-content-manager warning is disabled pending the fix of
# a bug in pylint https://github.com/PyCQA/pylint/issues/782
# NOTE: useless-object-inheritance needed for Python 2.x compatability
"""This module con... |
# Nothing found
return None
def put(self, item, *args, **kwargs):
"""Put an item into the cache, for this combination of args and kwargs.
Args:
*args: any arguments.
**kwargs: any keyword arguments. If ``timeout`` is specified as one
of the... | del self._cache[cache_key] | conditional_block |
cache.py | # -*- coding: utf-8 -*-
# pylint: disable=not-context-manager,useless-object-inheritance
# NOTE: The pylint not-content-manager warning is disabled pending the fix of
# a bug in pylint https://github.com/PyCQA/pylint/issues/782
# NOTE: useless-object-inheritance needed for Python 2.x compatability
"""This module con... |
class NullCache(_BaseCache):
"""A cache which does nothing.
Useful for debugging.
"""
def put(self, item, *args, **kwargs):
"""Put an item into the cache."""
def get(self, *args, **kwargs):
"""Get an item from the cache."""
return None
def delete(self, *args, **kw... | """Empty the whole cache."""
raise NotImplementedError | identifier_body |
gaussian_bump.py | #!/usr/bin/env python
##########################################################################
#
# QGIS-meshing plugins.
#
# Copyright (C) 2012-2013 Imperial College London and others.
#
# Please see the AUTHORS file in the main source directory for a
# full list of copyright holders.
#
# Dr Adam S. Can... | parser.add_argument(
'-b',
'--bumpheight',
help="Distance between seabed and top of bump. Default is 100m",
default=100,
type=float
)
parser.add_argument(
'-r',
'--resolution',
help="Resolution of output ... | parser = argparse.ArgumentParser(
prog="gaussian_bump",
description="""Create a Gaussian bump in a netcdf file"""
)
parser.add_argument(
'-v',
'--verbose',
action='store_true',
help="Verbose output: mainly progress reports.",
... | identifier_body |
gaussian_bump.py | #!/usr/bin/env python
##########################################################################
#
# QGIS-meshing plugins.
#
# Copyright (C) 2012-2013 Imperial College London and others.
#
# Please see the AUTHORS file in the main source directory for a
# full list of copyright holders.
#
# Dr Adam S. Can... | ():
parser = argparse.ArgumentParser(
prog="gaussian_bump",
description="""Create a Gaussian bump in a netcdf file"""
)
parser.add_argument(
'-v',
'--verbose',
action='store_true',
help="Verbose output: mainly progress reports.",
... | main | identifier_name |
gaussian_bump.py | #!/usr/bin/env python
##########################################################################
#
# QGIS-meshing plugins.
#
# Copyright (C) 2012-2013 Imperial College London and others.
#
# Please see the AUTHORS file in the main source directory for a
# full list of copyright holders.
#
# Dr Adam S. Can... | help="Distance between seabed and top of bump. Default is 100m",
default=100,
type=float
)
parser.add_argument(
'-r',
'--resolution',
help="Resolution of output netcdf file. Default is 10m",
default=10.0,
typ... | '-b',
'--bumpheight', | random_line_split |
gaussian_bump.py | #!/usr/bin/env python
##########################################################################
#
# QGIS-meshing plugins.
#
# Copyright (C) 2012-2013 Imperial College London and others.
#
# Please see the AUTHORS file in the main source directory for a
# full list of copyright holders.
#
# Dr Adam S. Can... |
# generate regular grid
X, Y = numpy.meshgrid(numpy.linspace(0.0, domain_size, nPoints), numpy.linspace(0.0, domain_size, nPoints))
Z = numpy.zeros((nPoints,nPoints))
#for each point calculate the Gaussian
centre = domain_size/2.0
for i in range(0,len(X)):
for j in range(0,len(X[0]... | print nPoints, shift | conditional_block |
Generic.py | # This file is part of pybliographer
#
# Copyright (C) 1998-2004 Frederic GOBRY
# Email : gobry@pybliographer.org
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of t... |
else:
honorific, first, last, lineage = aut [0].format (fmt)
parts = string.split (last, ' ')
if len (parts) == 1:
key = parts [0][0:3]
else:
key = string.join (map (lambda x: x [0], parts), '')
else:
key = rc (entry.... | if len (aut) > 3:
key = key + '+'
break | conditional_block |
Generic.py | # This file is part of pybliographer
#
# Copyright (C) 1998-2004 Frederic GOBRY
# Email : gobry@pybliographer.org
#
# This program is free software; you can redistribute it and/or | # as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See t... | # modify it under the terms of the GNU General Public License | random_line_split |
Generic.py | # This file is part of pybliographer
#
# Copyright (C) 1998-2004 Frederic GOBRY
# Email : gobry@pybliographer.org
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of t... | (entry, coding):
return author_desc (entry, coding, 1, -1)
def last_first_initials_authors (entry, coding):
return author_desc (entry, coding, 1, 1)
Autoload.register ('style', 'Generic', {
'first_last_full_authors' : first_last_full_authors,
'last_first_full_authors' : last_first_full_autho... | first_last_initials_authors | identifier_name |
Generic.py | # This file is part of pybliographer
#
# Copyright (C) 1998-2004 Frederic GOBRY
# Email : gobry@pybliographer.org
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of t... |
def last_first_full_authors (entry, coding):
return author_desc (entry, coding, 0, 1)
def first_last_full_authors (entry, coding):
return author_desc (entry, coding, 0, -1)
def full_authors (entry, coding):
return author_desc (entry, coding, 0, 0)
def initials_authors (entry, coding):
return auth... | (text, month, day) = entry.format (coding)
if month: text = "%s/%s" % (month, text)
if day : text = "%s/%s" % (day, text)
return text | identifier_body |
solve.py | #!/usr/bin/env python3
lines = []
with open('input.txt', 'r') as f:
lines = f.read().splitlines()
#--- challenge 1
def get_trees(lines, right, down):
|
trees = get_trees(lines, 3, 1)
print("Solution to challenge 1: {}".format(trees))
#--- challenge 2
tree_list = []
sequences = [[1,1], [3,1], [5,1], [7,1], [1,2]]
for check in sequences:
tree_list.append(get_trees(lines, check[0], check[1]))
product = 1
for trees in tree_list:
product *= trees
print("Solution ... | trees = 0
pos = 0
line_len = len(lines[0])
for line in lines[down::down]:
if (pos + right) >= line_len:
pos = right - (line_len - pos)
else:
pos += right
if line[pos] == '#':
trees += 1
return trees | identifier_body |
solve.py | #!/usr/bin/env python3
lines = []
with open('input.txt', 'r') as f:
lines = f.read().splitlines()
#--- challenge 1
def get_trees(lines, right, down):
trees = 0
pos = 0
line_len = len(lines[0])
for line in lines[down::down]:
if (pos + right) >= line_len:
|
else:
pos += right
if line[pos] == '#':
trees += 1
return trees
trees = get_trees(lines, 3, 1)
print("Solution to challenge 1: {}".format(trees))
#--- challenge 2
tree_list = []
sequences = [[1,1], [3,1], [5,1], [7,1], [1,2]]
for check in sequences:
tree_list.append(get_trees(lines, chec... | pos = right - (line_len - pos) | conditional_block |
solve.py | #!/usr/bin/env python3
lines = []
with open('input.txt', 'r') as f:
lines = f.read().splitlines()
#--- challenge 1
def get_trees(lines, right, down):
trees = 0
pos = 0
line_len = len(lines[0])
for line in lines[down::down]:
if (pos + right) >= line_len:
pos = right - (line_len - pos)
else:... | return trees
trees = get_trees(lines, 3, 1)
print("Solution to challenge 1: {}".format(trees))
#--- challenge 2
tree_list = []
sequences = [[1,1], [3,1], [5,1], [7,1], [1,2]]
for check in sequences:
tree_list.append(get_trees(lines, check[0], check[1]))
product = 1
for trees in tree_list:
product *= trees
pr... | random_line_split | |
solve.py | #!/usr/bin/env python3
lines = []
with open('input.txt', 'r') as f:
lines = f.read().splitlines()
#--- challenge 1
def | (lines, right, down):
trees = 0
pos = 0
line_len = len(lines[0])
for line in lines[down::down]:
if (pos + right) >= line_len:
pos = right - (line_len - pos)
else:
pos += right
if line[pos] == '#':
trees += 1
return trees
trees = get_trees(lines, 3, 1)
print("Solution to c... | get_trees | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.