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 |
|---|---|---|---|---|
15.2.3.6-3-141-1.js | /// Copyright (c) 2012 Ecma International. All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms"). Any redistribution of this code must retain the above
/// copyrigh... | () {
var obj = {};
try {
String.prototype.value = "String";
var strObj = new String("abc");
Object.defineProperty(obj, "property", strObj);
return obj.property === "String";
} finally {
delete String.prototype.value;
... | testcase | identifier_name |
15.2.3.6-3-141-1.js | /// Copyright (c) 2012 Ecma International. All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms"). Any redistribution of this code must retain the above
/// copyrigh... | }
}
runTestCase(testcase); | random_line_split | |
official.py | #!/usr/bin/python
#CHANGE ONLY, IF YOU KNOW, WHAT YOU DO!
#OPKMANAGER WILL CRASH IF YOUR OUTPUT IS INVALID!
import subprocess
import argparse
import time
import calendar
import string
import sys
class RegisterAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
print "Official... |
if string.find(part[i],'<div class="downloads_preview"') != -1:
image = part[i];
image = image.split("background-image: url('")[1].split("');")[0];
print "image_url: http://www.gcw-zero.com/" + image
if string.find(part[i],'<p class="more fade">') != -1:
long_description = part[i];
lon... | version = part[i+1]
version = version.split('>')[1]
version = version.split('<')[0]
t = time.strptime(version,"%A, %d %b %Y")
print "version: " + str(calendar.timegm(t)) #NEEDED!
found_version = 1 | conditional_block |
official.py | #!/usr/bin/python
#CHANGE ONLY, IF YOU KNOW, WHAT YOU DO!
#OPKMANAGER WILL CRASH IF YOUR OUTPUT IS INVALID!
import subprocess
import argparse
import time
import calendar
import string
import sys
class RegisterAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
|
class UpdateAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
process = subprocess.Popen('wget --timeout='+str(values[0])+' -qO- http://ziz.gp2x.de/gcw-repos/count.php',stdout=subprocess.PIPE,shell=True)
process = subprocess.Popen('wget --timeout='+str(values[0])+' -qO- ... | print "Official Repository" # Name
print "web" # Type (maybe web for web, or anything else for usb)
print "http://www.gcw-zero.com/files/upload/opk/" #URL
print "official.py --update" #Call for updating the list
print "O" #letter to show | identifier_body |
official.py | #!/usr/bin/python
#CHANGE ONLY, IF YOU KNOW, WHAT YOU DO!
#OPKMANAGER WILL CRASH IF YOUR OUTPUT IS INVALID!
import subprocess
import argparse
import time
import calendar
import string
import sys
class RegisterAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
print "Official... | ():
parser = argparse.ArgumentParser(description="Ziz's Repository script")
parser.add_argument('--register', nargs=0, action=RegisterAction)
parser.add_argument('--update', nargs=1, action=UpdateAction)
args = parser.parse_args()
if __name__ == "__main__":
main()
| main | identifier_name |
official.py | #!/usr/bin/python
#CHANGE ONLY, IF YOU KNOW, WHAT YOU DO!
#OPKMANAGER WILL CRASH IF YOUR OUTPUT IS INVALID!
import subprocess
import argparse
import time
import calendar
import string
import sys
class RegisterAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
print "Official... | def __call__(self, parser, namespace, values, option_string=None):
process = subprocess.Popen('wget --timeout='+str(values[0])+' -qO- http://ziz.gp2x.de/gcw-repos/count.php',stdout=subprocess.PIPE,shell=True)
process = subprocess.Popen('wget --timeout='+str(values[0])+' -qO- http://www.gcw-zero.com/downloads',stdo... | random_line_split | |
decorator.ts | module DecoratorModule {
export abstract class Component {
public abstract operation();
}
export class ConcreteComponent extends Component {
public operation() {
console.log("ConcreteComponent.Operation()");
}
}
export abstract class Decorator extends Component {
protected _component: ... |
public addedBehavior() {
}
}
}
//*********************************************
(function run() {
let c: DecoratorModule.ConcreteComponent = new DecoratorModule.ConcreteComponent();
let d1: DecoratorModule.ConcreteDecoratorA = new DecoratorModule.ConcreteDecoratorA();
let d2: DecoratorModule.ConcreteD... | {
super.operation();
this.addedBehavior();
console.log("ConcreteDecoratorB.Operation()");
} | identifier_body |
decorator.ts | module DecoratorModule {
export abstract class Component {
public abstract operation();
}
export class ConcreteComponent extends Component {
public operation() {
console.log("ConcreteComponent.Operation()");
}
}
export abstract class Decorator extends Component {
protected _component: ... | public operation() {
super.operation();
this.addedBehavior();
console.log("ConcreteDecoratorB.Operation()");
}
public addedBehavior() {
}
}
}
//*********************************************
(function run() {
let c: DecoratorModule.ConcreteComponent = new DecoratorModule.ConcreteC... | }
}
export class ConcreteDecoratorB extends Decorator { | random_line_split |
decorator.ts | module DecoratorModule {
export abstract class Component {
public abstract operation();
}
export class ConcreteComponent extends Component {
public operation() {
console.log("ConcreteComponent.Operation()");
}
}
export abstract class Decorator extends Component {
protected _component: ... | (component: Component) {
this._component = component;
}
public operation() {
if (this._component != null) {
this._component.operation();
}
}
}
export class ConcreteDecoratorA extends Decorator {
public operation() {
super.operation();
console.log("ConcreteDeco... | component | identifier_name |
decorator.ts | module DecoratorModule {
export abstract class Component {
public abstract operation();
}
export class ConcreteComponent extends Component {
public operation() {
console.log("ConcreteComponent.Operation()");
}
}
export abstract class Decorator extends Component {
protected _component: ... |
}
}
export class ConcreteDecoratorA extends Decorator {
public operation() {
super.operation();
console.log("ConcreteDecoratorA.Operation()");
}
}
export class ConcreteDecoratorB extends Decorator {
public operation() {
super.operation();
this.addedBehavior();
co... | {
this._component.operation();
} | conditional_block |
connect-history-api-fallback-tests.ts | import historyApiFallback = require('connect-history-api-fallback');
import express = require('express');
const app = express();
app.use(historyApiFallback());
historyApiFallback({
verbose: true
});
historyApiFallback({
logger: console.log.bind(console)
});
historyApiFallback({
rewrites: [
{ fro... | {
from: /^\/libs\/(.*)$/,
to(context) {
return './bower_components' + context.parsedUrl.pathname;
}
}
]
});
historyApiFallback({
rewrites: [
{
from: /\/app\/login/,
to: function onMatch(ctx) {
if... | htmlAcceptHeaders: ['text/html', 'application/xhtml+xml']
});
historyApiFallback({
rewrites: [ | random_line_split |
connect-history-api-fallback-tests.ts | import historyApiFallback = require('connect-history-api-fallback');
import express = require('express');
const app = express();
app.use(historyApiFallback());
historyApiFallback({
verbose: true
});
historyApiFallback({
logger: console.log.bind(console)
});
historyApiFallback({
rewrites: [
{ fro... |
return '/app/login/index.html';
}
}
]
});
historyApiFallback({
rewrites: [
{
from: /^\/libs\/(.*)$/,
to(context) {
return `/${context.match[2]}/${context.match[3]}`;
}
}
]
});
| {
return ctx.parsedUrl.href || '';
} | conditional_block |
connect-history-api-fallback-tests.ts | import historyApiFallback = require('connect-history-api-fallback');
import express = require('express');
const app = express();
app.use(historyApiFallback());
historyApiFallback({
verbose: true
});
historyApiFallback({
logger: console.log.bind(console)
});
historyApiFallback({
rewrites: [
{ fro... |
}
]
});
| {
return `/${context.match[2]}/${context.match[3]}`;
} | identifier_body |
connect-history-api-fallback-tests.ts | import historyApiFallback = require('connect-history-api-fallback');
import express = require('express');
const app = express();
app.use(historyApiFallback());
historyApiFallback({
verbose: true
});
historyApiFallback({
logger: console.log.bind(console)
});
historyApiFallback({
rewrites: [
{ fro... | (context) {
return `/${context.match[2]}/${context.match[3]}`;
}
}
]
});
| to | identifier_name |
os-spawn-example-2.py | '''
spawn º¯Êý»¹¿ÉÓÃÓÚÔÚºǫ́ÔËÐÐÒ»¸ö³ÌÐò. ÏÂÀýÖÐ ¸ø run º¯ÊýÌí¼ÓÁËÒ»¸ö¿ÉÑ¡µÄ mode ²ÎÊý;
µ±ÉèÖÃΪ os.P_NOWAIT ʱ, Õâ¸ö½Å±¾²»»áµÈ´ý×Ó³ÌÐò½áÊø, ĬÈÏÖµ os.P_WAIT ʱ spawn »áµÈ´ý×Ó½ø³Ì½áÊø.
ÆäËüµÄ±êÖ¾³£Á¿»¹ÓÐ os.P_OVERLAY ,ËüʹµÃ spawn µÄÐÐΪºÍ exec ÀàËÆ, ÒÔ¼° os.P_DETACH , ËüÔÚºǫ́ÔËÐÐ×Ó½ø³Ì, Ó뵱ǰ¿ØÖÆÌ¨ºÍ¼üÅ̽¹µã¸ôÀë.
''... | ,) + args)
except os.error:
pass
raise os.error, "cannot find executable"
run("python", "hello.py", mode=os.P_NOWAIT)
print "goodbye" | identifier_body | |
os-spawn-example-2.py |
import os
import string
def run(program, *args, **kw):
# find executable
mode = kw.get("mode", os.P_WAIT)
for path in string.split(os.environ["PATH"], os.pathsep):
file = os.path.join(path, program) + ".exe"
try:
return os.spawnv(mode, file, (file,) + args)
except os.er... | '''
spawn º¯Êý»¹¿ÉÓÃÓÚÔÚºǫ́ÔËÐÐÒ»¸ö³ÌÐò. ÏÂÀýÖÐ ¸ø run º¯ÊýÌí¼ÓÁËÒ»¸ö¿ÉÑ¡µÄ mode ²ÎÊý;
µ±ÉèÖÃΪ os.P_NOWAIT ʱ, Õâ¸ö½Å±¾²»»áµÈ´ý×Ó³ÌÐò½áÊø, ĬÈÏÖµ os.P_WAIT ʱ spawn »áµÈ´ý×Ó½ø³Ì½áÊø.
ÆäËüµÄ±êÖ¾³£Á¿»¹ÓÐ os.P_OVERLAY ,ËüʹµÃ spawn µÄÐÐΪºÍ exec ÀàËÆ, ÒÔ¼° os.P_DETACH , ËüÔÚºǫ́ÔËÐÐ×Ó½ø³Ì, Ó뵱ǰ¿ØÖÆÌ¨ºÍ¼üÅ̽¹µã¸ôÀë.
''... | random_line_split | |
os-spawn-example-2.py | '''
spawn º¯Êý»¹¿ÉÓÃÓÚÔÚºǫ́ÔËÐÐÒ»¸ö³ÌÐò. ÏÂÀýÖÐ ¸ø run º¯ÊýÌí¼ÓÁËÒ»¸ö¿ÉÑ¡µÄ mode ²ÎÊý;
µ±ÉèÖÃΪ os.P_NOWAIT ʱ, Õâ¸ö½Å±¾²»»áµÈ´ý×Ó³ÌÐò½áÊø, ĬÈÏÖµ os.P_WAIT ʱ spawn »áµÈ´ý×Ó½ø³Ì½áÊø.
ÆäËüµÄ±êÖ¾³£Á¿»¹ÓÐ os.P_OVERLAY ,ËüʹµÃ spawn µÄÐÐΪºÍ exec ÀàËÆ, ÒÔ¼° os.P_DETACH , ËüÔÚºǫ́ÔËÐÐ×Ó½ø³Ì, Ó뵱ǰ¿ØÖÆÌ¨ºÍ¼üÅ̽¹µã¸ôÀë.
''... |
run("python", "hello.py", mode=os.P_NOWAIT)
print "goodbye" | conditional_block | |
os-spawn-example-2.py | '''
spawn º¯Êý»¹¿ÉÓÃÓÚÔÚºǫ́ÔËÐÐÒ»¸ö³ÌÐò. ÏÂÀýÖÐ ¸ø run º¯ÊýÌí¼ÓÁËÒ»¸ö¿ÉÑ¡µÄ mode ²ÎÊý;
µ±ÉèÖÃΪ os.P_NOWAIT ʱ, Õâ¸ö½Å±¾²»»áµÈ´ý×Ó³ÌÐò½áÊø, ĬÈÏÖµ os.P_WAIT ʱ spawn »áµÈ´ý×Ó½ø³Ì½áÊø.
ÆäËüµÄ±êÖ¾³£Á¿»¹ÓÐ os.P_OVERLAY ,ËüʹµÃ spawn µÄÐÐΪºÍ exec ÀàËÆ, ÒÔ¼° os.P_DETACH , ËüÔÚºǫ́ÔËÐÐ×Ó½ø³Ì, Ó뵱ǰ¿ØÖÆÌ¨ºÍ¼üÅ̽¹µã¸ôÀë.
''... | ry:
return os.spawnv(mode, file, (file,) + args)
except os.error:
pass
raise os.error, "cannot find executable"
run("python", "hello.py", mode=os.P_NOWAIT)
print "goodbye" | t | identifier_name |
headerTemplateLoader.js | /**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v4.0.6
* @link http://www.ag-grid.com/
* @license MIT
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : ... | () {
}
HeaderTemplateLoader.prototype.createHeaderElement = function (column) {
var params = {
column: column,
colDef: column.getColDef,
context: this.gridOptionsWrapper.getContext(),
api: this.gridOptionsWrapper.getApi()
};
// option 1 - s... | HeaderTemplateLoader | identifier_name |
headerTemplateLoader.js | /**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v4.0.6
* @link http://www.ag-grid.com/
* @license MIT
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : ... |
HeaderTemplateLoader.prototype.createHeaderElement = function (column) {
var params = {
column: column,
colDef: column.getColDef,
context: this.gridOptionsWrapper.getContext(),
api: this.gridOptionsWrapper.getApi()
};
// option 1 - see if user... | {
} | identifier_body |
headerTemplateLoader.js | /**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v4.0.6
* @link http://www.ag-grid.com/
* @license MIT
*/
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : ... | return HeaderTemplateLoader;
})();
exports.HeaderTemplateLoader = HeaderTemplateLoader; | random_line_split | |
xmlhttprequesteventtarget.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull;
use dom::bindings::codegen::Bindin... | {
XMLHttpRequest,
XMLHttpRequestUpload,
}
#[dom_struct]
#[derive(HeapSizeOf)]
pub struct XMLHttpRequestEventTarget {
eventtarget: EventTarget,
}
impl XMLHttpRequestEventTarget {
pub fn new_inherited(type_id: XMLHttpRequestEventTargetTypeId) -> XMLHttpRequestEventTarget {
XMLHttpRequestEventTa... | XMLHttpRequestEventTargetTypeId | identifier_name |
xmlhttprequesteventtarget.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull;
use dom::bindings::codegen::Bindin... | XMLHttpRequest,
XMLHttpRequestUpload,
}
#[dom_struct]
#[derive(HeapSizeOf)]
pub struct XMLHttpRequestEventTarget {
eventtarget: EventTarget,
}
impl XMLHttpRequestEventTarget {
pub fn new_inherited(type_id: XMLHttpRequestEventTargetTypeId) -> XMLHttpRequestEventTarget {
XMLHttpRequestEventTarge... | #[derive(JSTraceable, Copy, Clone, PartialEq, HeapSizeOf)]
pub enum XMLHttpRequestEventTargetTypeId { | random_line_split |
xmlhttprequesteventtarget.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull;
use dom::bindings::codegen::Bindin... |
}
impl<'a> XMLHttpRequestEventTargetMethods for &'a XMLHttpRequestEventTarget {
event_handler!(loadstart, GetOnloadstart, SetOnloadstart);
event_handler!(progress, GetOnprogress, SetOnprogress);
event_handler!(abort, GetOnabort, SetOnabort);
event_handler!(error, GetOnerror, SetOnerror);
event_ha... | {
match *self.type_id() {
EventTargetTypeId::XMLHttpRequestEventTarget(_) => true,
_ => false
}
} | identifier_body |
View.tsx | import React, { FC } from 'react'
import Speaker from '@/components/Speaker'
import {
WebsterLearnerResult,
WebsterLearnerResultLex,
WebsterLearnerResultRelated
} from './engine'
import { ViewPorps } from '@/components/dictionaries/helpers'
import { StrElm } from '@/components/StrElm'
export const DictWebsterLea... | return renderRelated(result)
default:
return null
}
}
function renderLex(result: WebsterLearnerResultLex) {
return (
<>
{result.items.map(entry => (
<section key={entry.title} className="dictWebsterLearner-Entry">
<header className="dictWebsterLearner-Header">
... | random_line_split | |
treeAndTable.js | /**
* @author: * @date: 2016/1/21
*/
define(["core/js/layout/Panel"],
function (Panel) {
var view = Panel.extend({
/*Panel的配置项 start*/
title:"表单-",
help:"内容",
brief:"摘要",
/*Panel 配置 End*/
oninitialized:function(triggerEvent){
... | arr.push(moduleName);
if(va&&va.deps&&va.deps.length>0){
tree.children = [];
tree.folder=true;
for(var i=0;i<va.deps.length;i++){
var newTree = this.getModuleTree(va.deps[i],arr);
... | if(_.contains(arr,moduleName)){
return false;
}
} | random_line_split |
treeAndTable.js | /**
* @author: * @date: 2016/1/21
*/
define(["core/js/layout/Panel"],
function (Panel) {
var view = Panel.extend({
/*Panel的配置项 start*/
title:"表单-",
help:"内容",
brief:"摘要",
/*Panel 配置 End*/
oninitialized:function(triggerEvent){
... | }
}
}
return tree;
}
});
return view;
});
| }
tree.count++;
| conditional_block |
store.service.spec.ts | // import 'localforage-getitems';
import { async, TestBed } from '@angular/core/testing';
import { StoreService } from './store.service';
// import * as localForage from 'localforage';
// import { extendPrototype as extendGetitems } from 'localforage-getitems';
import { Base } from '../services/base';
import { noop, Su... | /*
it('removeObjectsWithKey should remove resources with the passed id from indexeddb', async () => {
await (store_service as any).allstore.setItem('0', { cache_last_update: 123456 }).then(item => {
expect(item).toBeTruthy();
});
await store_service.removeObjectsWithKey('0');... | expect(item.cache_last_update).toBeFalsy();
});
});
*/
| random_line_split |
L0SecureFile.ts | import ma = require('vsts-task-lib/mock-answer');
import tmrm = require('vsts-task-lib/mock-run');
import path = require('path');
import fs = require('fs');
let taskPath = path.join(__dirname, '..', 'preinstallprovprofile.js');
let tr: tmrm.TaskMockRunner = new tmrm.TaskMockRunner(taskPath);
tr.setInput('provProfileS... | "rm": "/bin/rm",
"cp": "/bin/cp"
},
"checkPath": {
"/usr/bin/security": true,
"/usr/libexec/PlistBuddy": true,
"/bin/rm": true,
"/bin/cp": true
},
"exist": {
"/build/temp/mySecureFileId.filename": true
},
"exec": {
"/usr/bin/securit... | "/usr/libexec/PlistBuddy": "/usr/libexec/PlistBuddy", | random_line_split |
real-life-problem-domain.test.ts | import {
calculatePaymentAmount,
CashPayment,
CreditCardPayment,
Payment
} from './real-life-problem-domain';
const creditCardPayment = new CreditCardPayment(100, 0.02);
const cashPayment = new CashPayment(100, 42);
describe('Real Life Problem Domain:', () => {
describe('PaymentPattern', () => {
it('sho... |
expect(cardSpy).not.toHaveBeenCalled();
expect(cashSpy).toHaveBeenCalledWith(cashPayment);
});
});
describe('calculatePaymentAmount()', () => {
it('should add fees multiplied with amount to amount for credit card payments', () => {
const finalAmount =
creditCardPayment.amount +
... | cashPayment.match({
CreditCard: cardSpy,
Cash: cashSpy
}); | random_line_split |
escape.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
_ => {}
}
}
if last < s.len() {
fmt.buf.write(pile_o_bits.slice_from(last).as_bytes());
}
}
}
| {
// Because the internet is always right, turns out there's not that many
// characters to escape: http://stackoverflow.com/questions/7381974
let Escape(s) = *s;
let pile_o_bits = s.as_slice();
let mut last = 0;
for (i, ch) in s.bytes().enumerate() {
match ch... | identifier_body |
escape.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <'a>(&'a str);
impl<'a> fmt::Default for Escape<'a> {
fn fmt(s: &Escape<'a>, fmt: &mut fmt::Formatter) {
// Because the internet is always right, turns out there's not that many
// characters to escape: http://stackoverflow.com/questions/7381974
let Escape(s) = *s;
let pile_o_bits =... | Escape | identifier_name |
escape.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | impl<'a> fmt::Default for Escape<'a> {
fn fmt(s: &Escape<'a>, fmt: &mut fmt::Formatter) {
// Because the internet is always right, turns out there's not that many
// characters to escape: http://stackoverflow.com/questions/7381974
let Escape(s) = *s;
let pile_o_bits = s.as_slice();
... |
/// Wrapper struct which will emit the HTML-escaped version of the contained
/// string when passed to a format string.
pub struct Escape<'a>(&'a str);
| random_line_split |
ad_parameter_error.py | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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... | (proto.Enum):
r"""Enum describing possible ad parameter errors."""
UNSPECIFIED = 0
UNKNOWN = 1
AD_GROUP_CRITERION_MUST_BE_KEYWORD = 2
INVALID_INSERTION_TEXT_FORMAT = 3
__all__ = tuple(sorted(__protobuf__.manifest))
| AdParameterError | identifier_name |
ad_parameter_error.py | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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... |
__all__ = tuple(sorted(__protobuf__.manifest))
| r"""Container for enum describing possible ad parameter errors.
"""
class AdParameterError(proto.Enum):
r"""Enum describing possible ad parameter errors."""
UNSPECIFIED = 0
UNKNOWN = 1
AD_GROUP_CRITERION_MUST_BE_KEYWORD = 2
INVALID_INSERTION_TEXT_FORMAT = 3 | identifier_body |
ad_parameter_error.py | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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... | #
import proto # type: ignore
__protobuf__ = proto.module(
package="google.ads.googleads.v9.errors",
marshal="google.ads.googleads.v9",
manifest={"AdParameterErrorEnum",},
)
class AdParameterErrorEnum(proto.Message):
r"""Container for enum describing possible ad parameter errors.
"""
class... | # See the License for the specific language governing permissions and
# limitations under the License. | random_line_split |
dom.rs | .is_element() || self.is_text_node() }
}
/// A node iterator that only returns node that don't need layout.
pub struct | <T>(pub T);
impl<T, I> Iterator for LayoutIterator<T>
where T: Iterator<Item=I>,
I: NodeInfo,
{
type Item = I;
fn next(&mut self) -> Option<I> {
loop {
// Filter out nodes that layout should ignore.
let n = self.0.next();
if n.is_none() || n.as_ref().un... | LayoutIterator | identifier_name |
dom.rs | .is_element() || self.is_text_node() }
}
/// A node iterator that only returns node that don't need layout.
pub struct LayoutIterator<T>(pub T);
impl<T, I> Iterator for LayoutIterator<T>
where T: Iterator<Item=I>,
I: NodeInfo,
{
type Item = I;
fn next(&mut self) -> Option<I> {
loop {
... |
/// While doing a reflow, the element at the root has no parent, as far as we're
/// concerned. This method returns `None` at the reflow root.
fn layout_parent_element(self, reflow_root: OpaqueNode) -> Option<Self> {
if self.as_node().opaque() == reflow_root {
None
} else {
... | random_line_split | |
dom.rs | .is_element() || self.is_text_node() }
}
/// A node iterator that only returns node that don't need layout.
pub struct LayoutIterator<T>(pub T);
impl<T, I> Iterator for LayoutIterator<T>
where T: Iterator<Item=I>,
I: NodeInfo,
{
type Item = I;
fn next(&mut self) -> Option<I> {
loop {
... |
/// A debug id, only useful, mm... for debugging.
fn debug_id(self) -> usize;
/// Get this node as an element, if it's one.
fn as_element(&self) -> Option<Self::ConcreteElement>;
/// Whether this node needs to be laid out on viewport size change.
fn needs_dirty_on_viewport_size_changed(&self... | {
self.parent_node().and_then(|n| n.as_element())
} | identifier_body |
run_suite.py | #!/usr/bin/env python
import datetime
from run_utils import *
class TestSuite(object):
def __init__(self, options, cache):
self.options = options
self.cache = cache
self.nameprefix = "opencv_" + self.options.mode + "_"
self.tests = self.cache.gatherTests(self.nameprefix + "*", self... | (self, short = False, main = False):
if len(self.tests) == 0:
raise Err("No tests found")
for t in self.tests:
if short:
t = self.getAlias(t)
if not main or self.cache.isMainModule(t):
log.info("%s", t)
def getAlias(self, fname):
... | listTests | identifier_name |
run_suite.py | #!/usr/bin/env python
import datetime
from run_utils import *
class TestSuite(object): | self.nameprefix = "opencv_" + self.options.mode + "_"
self.tests = self.cache.gatherTests(self.nameprefix + "*", self.isTest)
def getOS(self):
return getPlatformVersion() or self.cache.getOS()
def getHardware(self):
res = []
if self.cache.getArch() in ["x86", "x64"] and... | def __init__(self, options, cache):
self.options = options
self.cache = cache | random_line_split |
run_suite.py | #!/usr/bin/env python
import datetime
from run_utils import *
class TestSuite(object):
def __init__(self, options, cache):
self.options = options
self.cache = cache
self.nameprefix = "opencv_" + self.options.mode + "_"
self.tests = self.cache.gatherTests(self.nameprefix + "*", self... |
def getHardware(self):
res = []
if self.cache.getArch() in ["x86", "x64"] and self.cache.withCuda():
res.append("CUDA")
return res
def getLogName(self, app, timestamp):
app = self.getAlias(app)
rev = self.cache.getGitVersion()
if isinstance(timestam... | return getPlatformVersion() or self.cache.getOS() | identifier_body |
run_suite.py | #!/usr/bin/env python
import datetime
from run_utils import *
class TestSuite(object):
def __init__(self, options, cache):
self.options = options
self.cache = cache
self.nameprefix = "opencv_" + self.options.mode + "_"
self.tests = self.cache.gatherTests(self.nameprefix + "*", self... |
return l + ".xml"
def listTests(self, short = False, main = False):
if len(self.tests) == 0:
raise Err("No tests found")
for t in self.tests:
if short:
t = self.getAlias(t)
if not main or self.cache.isMainModule(t):
log.in... | pieces = [app, self.cache.getOS(), self.cache.getArch()] + self.getHardware() + [rev, timestamp]
lname = "_".join([p for p in pieces if p])
lname = re.sub(r'[\(\)\[\]\s,]', '_', lname)
l = re.sub(r'_+', '_', lname) | conditional_block |
Handler.ts | HandlerOptions>) {
if (!opts.containerSelector) {
throw new Error(
"[WoltLabSuite/Core/Ui/Reaction/Handler] Expected a non-empty string for option 'containerSelector'.",
);
}
this._objectType = objectType;
this._popover = null;
this._popoverContent = null;
this._options = ... | // the "first" button is displayed at the bottom and thus farthest away. Reversing
// the display order will restore the logic by placing the "first" button as close
// to the react button as possible.
const inverseOrder = popover.style.getPropertyValue("bottom") === "auto";
if (inverseOrder) {
... | {
if (this._popoverCurrentObjectId !== 0) {
this._closePopover();
}
this._popoverCurrentObjectId = objectId;
UiAlignment.set(this._getPopover(), element, {
pointer: true,
horizontal: this._options.isButtonGroupNavigation ? "left" : "center",
vertical: UiScreen.is("screen-xs") ?... | identifier_body |
Handler.ts | {
elementData.reactButton = element.querySelector(this._options.buttonSelector) as HTMLElement;
}
if (elementData.reactButton === null) {
// The element may have no react button.
return;
}
if (availableReactions.length === 1) {
const reaction = availableReactions[0];
ele... | random_line_split | ||
Handler.ts | HandlerOptions>) {
if (!opts.containerSelector) {
throw new Error(
"[WoltLabSuite/Core/Ui/Reaction/Handler] Expected a non-empty string for option 'containerSelector'.",
);
}
this._objectType = objectType;
this._popover = null;
this._popoverContent = null;
this._options = ... | (element: HTMLElement, elementData: ElementData): void {
if (this._options.isSingleItem) {
elementData.reactButton = document.querySelector(this._options.buttonSelector) as HTMLElement;
} else {
elementData.reactButton = element.querySelector(this._options.buttonSelector) as HTMLElement;
}
... | _initReactButton | identifier_name |
Handler.ts | react button.
*/
_initReactButton(element: HTMLElement, elementData: ElementData): void {
if (this._options.isSingleItem) {
elementData.reactButton = document.querySelector(this._options.buttonSelector) as HTMLElement;
} else {
elementData.reactButton = element.querySelector(this._options.butt... | {
popoverContent.classList.remove("overflowTop");
} | conditional_block | |
ftp.py | v defined in the rfc's?
ENTERING_EPSV_MODE: '229 Entering Extended Passive Mode (|||%s|).',
USR_LOGGED_IN_PROCEED: '230 User logged in, proceed',
GUEST_LOGGED_IN_PROCEED: '230 Anonymous login ok, access restrictions apply.',
#i.e. CWD completed ok
REQ_FILE_ACT... |
else:
logger.warn("no dtp on %s:%i <-> %s:%i!" %
(self.dtp.remote.host, self.dtp.remote.port,
self.dtp.local.host, self.dtp.local.port))
else:
return (FILE_NOT_FOUND, p)
def ftp_STOR(self, p):
if not p... | logger.warn("dtp state %s %s:%i <-> %s:%i!" %
(self.dtp.status,
self.dtp.remote.host, self.dtp.remote.port,
self.dtp.local.host, self.dtp.local.port)) | conditional_block |
ftp.py | epsv defined in the rfc's?
ENTERING_EPSV_MODE: '229 Entering Extended Passive Mode (|||%s|).',
USR_LOGGED_IN_PROCEED: '230 User logged in, proceed',
GUEST_LOGGED_IN_PROCEED: '230 Anonymous login ok, access restrictions apply.',
#i.e. CWD completed ok
REQ_FILE... | return USR_LOGGED_IN_PROCEED
def ftp_FEAT(self):
self.send('211-Features:\r\n' +
' PASV\r\n' +
' PORT\r\n' +
'211 End\r\n')
return None
def ftp_PORT(self, address):
if self.dtf:
self.dtf.close()
s... | return GUEST_LOGGED_IN_PROCEED
else: | random_line_split |
ftp.py | .find(b' ')
if space != -1:
cmd = line[:space]
args = (line[space + 1:],)
else:
cmd = line
args = ()
logger.warn("cmd '%s'" % cmd)
r = self.processcmd(cmd, args)
if isinstance(r,tuple):
... | connection.__init__(self,'tcp')
self.ctrl = ctrl
self.mode = None | identifier_body | |
ftp.py | v defined in the rfc's?
ENTERING_EPSV_MODE: '229 Entering Extended Passive Mode (|||%s|).',
USR_LOGGED_IN_PROCEED: '230 User logged in, proceed',
GUEST_LOGGED_IN_PROCEED: '230 Anonymous login ok, access restrictions apply.',
#i.e. CWD completed ok
REQ_FILE_ACT... | (self, cmd, args):
logger.debug("cmd '%s'" % cmd)
l = [i.decode() for i in args]
cmd = cmd.upper()
if self.state == self.UNAUTH:
if cmd != b'USER':
return NOT_LOGGED_IN
self.ftp_USER(*args)
elif self.state == self.INAUTH:
if cm... | processcmd | identifier_name |
zenoControllerTest.js | 'use strict';
| var scope, $httpBackend, ctrl, rootScope, location, zenoService;
var list = {
host : "{@alias}.google.com",
envs : [
{alias: "dev", server : "dev.", port: 8080},
{alias: "prod", server: ""}
],
desktop : [
{url: "@host/search", name: "search"},
... | describe('Zeno Controller', function() {
| random_line_split |
actions.js | 'use strict';
var EventDispatcher = createjs.EventDispatcher
, EaselEvent = createjs.Event;
var controls = {
37: 'moveleft',
39: 'moveright',
38: 'moveup',
40: 'movedown',
32: 'fire1'
};
var currentActions = {};
var actionService = module.exports = {
init: actions_init,
get: actions... | () {
return currentActions;
}
function onKeyDown(event) {
var keyEvent = processEvent(event, 'down');
if (keyEvent)
currentActions[keyEvent.type] = keyEvent.data;
}
function onKeyUp(event) {
var keyEvent = processEvent(event, 'up');
if (keyEvent)
delete currentActions[keyEvent.ty... | actions_get | identifier_name |
actions.js | 'use strict';
var EventDispatcher = createjs.EventDispatcher
, EaselEvent = createjs.Event;
var controls = {
37: 'moveleft',
39: 'moveright',
38: 'moveup',
40: 'movedown',
32: 'fire1'
};
var currentActions = {};
var actionService = module.exports = {
init: actions_init,
get: actions... |
function processEvent(event, phase) {
var generalEvent = prepareEvent(event, phase, 'key');
if (!generalEvent) return;
var specificEvent = prepareEvent(event, phase);
actionService.dispatchEvent(generalEvent);
actionService.dispatchEvent(specificEvent);
return specificEvent;
}
function pr... | {
var canvasEl = stage && stage.canvas;
if (!canvasEl) return;
// May need to be more complex depending
var canvasXPos = canvasEl.offsetLeft;
var canvasYPos = canvasEl.offsetTop;
currentActions.mouse = {
winX: event.clientX,
winY: event.clientY,
stageX: event.clientX - ... | identifier_body |
actions.js | 'use strict';
var EventDispatcher = createjs.EventDispatcher
, EaselEvent = createjs.Event;
var controls = {
37: 'moveleft',
39: 'moveright',
38: 'moveup', | 40: 'movedown',
32: 'fire1'
};
var currentActions = {};
var actionService = module.exports = {
init: actions_init,
get: actions_get
}
var stage;
function actions_init(win, stage2) {
stage = stage2;
EventDispatcher.initialize(actionService);
win.addEventListener('keydown', onKeyDown);
... | random_line_split | |
collector.py | Optional[Link]
"""
Convert an anchor element in a simple repository page to a Link.
"""
href = anchor.get("href")
if not href:
return None
url = _clean_link(urllib_parse.urljoin(base_url, href))
pyrequire = anchor.get('data-requires-python')
pyrequire = unescape(pyrequire) if p... | """
Encapsulates the return value of a call to LinkCollector.collect_links().
The return value includes both URLs to project pages containing package
links, as well as individual package Link objects collected from other
sources.
This info is stored separately as:
(1) links from the configure... | identifier_body | |
collector.py | str, PipSession) -> Response
"""Access an HTML page with GET, and return the response.
This consists of three parts:
1. If the URL looks suspiciously like an archive, send a HEAD first to
check the Content-Type is HTML, to avoid downloading a large file.
Raise `_NotHTTP` if the content type ... |
return None
def _determine_base_url(document, page_url):
# type: (HTMLElement, str) -> str
"""Determine the HTML document's base URL.
This looks for a ``<base>`` tag in the HTML document. If present, its href
attribute denotes the base URL of anchor tags in the document. If there is
no such ... | return params['charset'] | conditional_block |
collector.py | (self, content_type, request_desc):
# type: (str, str) -> None
super(_NotHTML, self).__init__(content_type, request_desc)
self.content_type = content_type
self.request_desc = request_desc
def _ensure_html_header(response):
# type: (Response) -> None
"""Check the Content-Type he... | __init__ | identifier_name | |
collector.py | (str, PipSession) -> Response
"""Access an HTML page with GET, and return the response.
This consists of three parts:
1. If the URL looks suspiciously like an archive, send a HEAD first to
check the Content-Type is HTML, to avoid downloading a large file.
Raise `_NotHTTP` if the content typ... | return page_url
def _clean_url_path_part(part):
# type: (str) -> str
"""
Clean a "part" of a URL path (i.e. after splitting on "@" characters).
"""
# We unquote prior to quoting to make sure nothing is double quoted.
return urllib_parse.quote(urllib_parse.unquote(part))
def _clean_file_u... | href = base.get("href")
if href is not None:
return href | random_line_split |
goto.py | # goto_assignments command tests are different in syntax
definition = 3
#! 0 ['a = definition']
a = definition
#! []
b
#! ['a = definition']
a
b = a
c = b
#! ['c = b']
c
cd = 1
#! 1 ['cd = c']
cd = c
#! 0 ['cd = e']
cd = e
#! ['module math']
import math
#! ['import math']
math
#! ['import math']
b = math
#! ['b =... | (t=None):
#! 9 ['t = None']
t = t or 1
# -----------------
# imports
# -----------------
#! ['module import_tree']
import import_tree
#! ["a = ''"]
import_tree.a
#! ['module mod1']
import import_tree.mod1
#! ['a = 1']
import_tree.mod1.a
#! ['module pkg']
import import_tree.pkg
#! ['a = list']
import_tree.pk... | f | identifier_name |
goto.py | # goto_assignments command tests are different in syntax
definition = 3
#! 0 ['a = definition']
a = definition
#! []
b
#! ['a = definition']
a
b = a
c = b
#! ['c = b']
c
cd = 1
#! 1 ['cd = c']
cd = c
#! 0 ['cd = e']
cd = e
#! ['module math']
import math
#! ['import math']
math
#! ['import math']
b = math
#! ['b =... |
for i in []:
#! ['for i in []: i']
i
| key | conditional_block |
goto.py | # goto_assignments command tests are different in syntax
definition = 3
#! 0 ['a = definition']
a = definition
#! []
b
#! ['a = definition']
a
b = a
c = b
#! ['c = b']
c
cd = 1
#! 1 ['cd = c']
cd = c
#! 0 ['cd = e']
cd = e
#! ['module math']
import math
#! ['import math']
math
#! ['import math']
b = math
#! ['b =... | mod1.a
#! ['a = 1.0']
from import_tree.pkg.mod1 import a
#! ['import os']
from .imports import os
#! ['some_variable = 1']
from . import some_variable
# -----------------
# anonymous classes
# -----------------
def func():
class A():
def b(self):
return 1
return A()
#! 8 ['def b']
func(... | mod1.a
#! ['module mod1']
from import_tree import mod1
#! ['a = 1'] | random_line_split |
goto.py | # goto_assignments command tests are different in syntax
definition = 3
#! 0 ['a = definition']
a = definition
#! []
b
#! ['a = definition']
a
b = a
c = b
#! ['c = b']
c
cd = 1
#! 1 ['cd = c']
cd = c
#! 0 ['cd = e']
cd = e
#! ['module math']
import math
#! ['import math']
math
#! ['import math']
b = math
#! ['b =... |
return A()
#! 8 ['def b']
func().b()
# -----------------
# on itself
# -----------------
#! 7 ['class ClassDef']
class ClassDef():
""" abc """
pass
# -----------------
# params
# -----------------
param = ClassDef
#! 8 ['param']
def ab1(param): pass
#! 9 ['param']
def ab2(param): pass
#! 11 ['param = ... | def b(self):
return 1 | identifier_body |
rechteck.py | import numpy as np
import uncertainties.unumpy as unp
from uncertainties.unumpy import (nominal_values as noms, std_devs as stds)
import matplotlib.pyplot as plt
import matplotlib as mpl
from scipy.optimize import curve_fit
plt.rcParams['figure.figsize'] = (12, 8)
plt.rcParams['font.size'] = 13
plt.rcParams['lines.line... | (x, a, b):
return a * x + b
params, covariance = curve_fit(f, x, y)
errors = np.sqrt(np.diag(covariance))
print('a =', params[0], '+-', errors[0])
print('b =', params[1], '+-', errors[1])
# a =-1.19204784746 +- 0.0898910034039
# b = 0.326461420388 +- 0.123423011824
# mit ungeraden Oberwellen:
# a = -0.90924790... | f | identifier_name |
rechteck.py | import numpy as np
import uncertainties.unumpy as unp
from uncertainties.unumpy import (nominal_values as noms, std_devs as stds)
import matplotlib.pyplot as plt
import matplotlib as mpl
from scipy.optimize import curve_fit
plt.rcParams['figure.figsize'] = (12, 8)
plt.rcParams['font.size'] = 13
plt.rcParams['lines.line... | # a =-1.19204784746 +- 0.0898910034039
# b = 0.326461420388 +- 0.123423011824
# mit ungeraden Oberwellen:
# a = -0.909247906044 +- 0.0770070259187
# b = 0.409244475522 +- 0.144772240047
x_plot = np.linspace(min(x), max(x))
plt.plot(x_plot, f(x_plot, *params), 'b-', label='linearer Fit')
plt.plot(x, y, 'rx', label='M... | random_line_split | |
rechteck.py | import numpy as np
import uncertainties.unumpy as unp
from uncertainties.unumpy import (nominal_values as noms, std_devs as stds)
import matplotlib.pyplot as plt
import matplotlib as mpl
from scipy.optimize import curve_fit
plt.rcParams['figure.figsize'] = (12, 8)
plt.rcParams['font.size'] = 13
plt.rcParams['lines.line... |
params, covariance = curve_fit(f, x, y)
errors = np.sqrt(np.diag(covariance))
print('a =', params[0], '+-', errors[0])
print('b =', params[1], '+-', errors[1])
# a =-1.19204784746 +- 0.0898910034039
# b = 0.326461420388 +- 0.123423011824
# mit ungeraden Oberwellen:
# a = -0.909247906044 +- 0.0770070259187
# b = 0... | return a * x + b | identifier_body |
yahoo.py | ('country')]}),
BrightcoveNewIE.ie_key())
# Look for Brightcove New Studio embeds
bc_url = BrightcoveNewIE._extract_url(self, webpage)
if bc_url:
return brightcove_url_result(bc_url)
brightcove_iframe = self._search_regex(
r'(<iframe[^>]+data-vid... | .yahoo\.co\.jp/(? | identifier_name | |
yahoo.py | ailer-173000497.html',
'info_dict': {
'id': '071c4013-ce30-3a93-a5b2-e0413cd4a9d1',
'ext': 'mp4',
'title': "'True Story' Trailer",
'description': 'True Story',
},
'params': {
'skip_download': True,
... | pdate({
'protocol': 'm3u8_native',
'ext': 'mp4',
})
else:
fmt = format_info['ext'] = determine_ext(path)
format_url = compat_urlparse.urljoin(host, path)
format_info['url'] = format_ur... | conditional_block | |
yahoo.py | \.html\?format=embed.*?)"', webpage)
for idx, iframe_url in enumerate(iframe_urls):
entries.append(self.url_result(host + iframe_url, 'Yahoo'))
if entries:
return self.playlist_result(entries, page_id)
# Look for NBCSports iframes
nbc_sports_url = NBCSportsVPlaye... | for pagenum in itertools.count(0):
result_url = 'http://video.search.yahoo.com/search/?p=%s&fr=screen&o=js&gs=0&b=%d' % (compat_urllib_parse.quote_plus(query), pagenum * 30)
info = self._download_json(result_url, query,
note='Downloading results pag... | random_line_split | |
yahoo.py | /galactic-2016',
'md5': 'dac0c72d502bc5facda80c9e6d5c98db',
'info_dict': {
'id': 'a6015640-e9e5-3efb-bb60-05589a183919',
'ext': 'mp4',
'description': 'Galactic',
'title': 'Dolla Diva (feat. Maggie Koerner)',
},
... | get('id')
if not meta:
msg = info['status'].get('msg')
if msg:
raise ExtractorError(
'%s returned error: %s' % (self.IE_NAME, msg), expected=True)
raise ExtractorError('Unable to extract media object meta')
formats = []
fo... | identifier_body | |
lib.rs | #![feature(type_ascription)]
#![feature(static_recursion)]
#![allow(dead_code)]
#![deny(warnings)]
#[macro_use]
extern crate log;
extern crate env_logger;
// macro_rules! debug {
// ($($exp:expr),*) => {
// if cfg!(debug_assertions) {
// println!($($exp),*);
// } else {}
// } | //
macro_rules! bug {
($exp: expr) => {
panic!(concat!("internal error: ", $exp, "
This is a bug in RustyScheme. Please report it \
at https://github.com/DemiMarie/rusty_scheme/issues"))
};
($exp: expr, $($exps: tt)+) => {
panic!(concat!("internal error: ", $exp, "
This is a bug in... | // } | random_line_split |
lib.rs | #![feature(type_ascription)]
#![feature(static_recursion)]
#![allow(dead_code)]
#![deny(warnings)]
#[macro_use]
extern crate log;
extern crate env_logger;
// macro_rules! debug {
// ($($exp:expr),*) => {
// if cfg!(debug_assertions) {
// println!($($exp),*);
// } else {}
// }
// }
//
macro_rules! bug {
($exp: exp... | () {}
}
| it_works | identifier_name |
lib.rs | #![feature(type_ascription)]
#![feature(static_recursion)]
#![allow(dead_code)]
#![deny(warnings)]
#[macro_use]
extern crate log;
extern crate env_logger;
// macro_rules! debug {
// ($($exp:expr),*) => {
// if cfg!(debug_assertions) {
// println!($($exp),*);
// } else {}
// }
// }
//
macro_rules! bug {
($exp: exp... |
}
| {} | identifier_body |
index.ts | // All in one file example
import { Component, getStyle, Actions, StyleGroup, run, Inputs } from '../core'
import { h, View, viewHandler } from '../interfaces/view'
import { styleHandler } from '../groups/style'
// Component
const state = {
count: 0,
}
type S = typeof state
const inputs: Inputs<S> = (s, F) => ({
... |
const actions: Actions<S> = {
Inc: () => s => {
s.count++
},
}
const view: View<S> = async (s, F) => {
const style = getStyle(F)
return h('div', {
class: style('base'),
on: { click: F.in('inc') },
}, 'Count ' + s.count)
}
const style: StyleGroup = {
base: {
color: 'green',
fontSize: '... | F.toIn('inc')
})
},
}) | random_line_split |
bin.rs | DNS_LOOKUP_TIMEOUT);
let connect_timeout = format!("{}", constants::CONNECT_TIMEOUT);
let request_timeout = format!("{}", constants::REQUEST_TIMEOUT);
let read_timeout = format!("{}", constants::READ_TIMEOUT);
let number_of_redirect = format!("{}", constants::NUMBER_OF_REDIRECT);
let matches = App... | {
// the first time write is called, all headers are sent
// in the buffer. there is no need to parse it again.
if log_enabled!(Info) || self_.verbose {
self_.display_headers(&buf);
}
self_.header_read = true;
Poll::Ready(Ok(0))
... | conditional_block | |
bin.rs | index(1)
.required(true)
.help("URL to request"),
)
.arg(
Arg::with_name("REQUEST")
.short("X")
.long("request")
.default_value("GET")
.help("Specify request command to use"),
)
.a... | poll_flush | identifier_name | |
bin.rs | ::CabotResult;
macro_rules! parse_int {
($name:expr, $typ:ty, $matches:ident) => {
<$typ>::from_str_radix($matches.value_of($name).unwrap(), 10)
.expect(format!("{} must be an integer", $name).as_str())
};
}
pub async fn run() -> CabotResult<()> {
let user_agent: String = constants::us... | Arg::with_name("FILE")
.short("o")
.long("output")
.takes_value(true)
.help("Write to FILE instead of stdout"),
)
.arg(
Arg::with_name("VERBOSE")
.short("v")
.long("verbose")
... | )
.arg( | random_line_split |
lambda.ts | // used to encrypt request ip
import { transformRequest, transformResponse } from 'hapi-lambda'
import { APIGatewayEvent } from 'aws-lambda'
// import { DynamoDB } from 'aws-sdk'
// import { IItemListing } from '../graphql-types'
import { getApi } from './common-api'
// const docClient = new DynamoDB.DocumentClient({... | // return record
// }
return await getApi({} /*, getRecordFn*/)
}
// TODO: remove hapi part, and convert to pure function with shared code with normal server?
let _server // cached server instance
export async function handler(event: APIGatewayEvent) {
if (!_server) {
_server = await init()
}
con... | // (r: IItemListing) => r.link === link
// )[0]
// } | random_line_split |
lambda.ts | // used to encrypt request ip
import { transformRequest, transformResponse } from 'hapi-lambda'
import { APIGatewayEvent } from 'aws-lambda'
// import { DynamoDB } from 'aws-sdk'
// import { IItemListing } from '../graphql-types'
import { getApi } from './common-api'
// const docClient = new DynamoDB.DocumentClient({... | () {
// const getRecordFn = async (itemType, subType, vendor, link) => {
// const docs = await docClient
// .batchGet({
// RequestItems: {
// ammobinItems: {
// ExpressionAttributeNames: {
// '#1': vendor.name,
// },
// ProjectionExpression... | init | identifier_name |
lambda.ts | // used to encrypt request ip
import { transformRequest, transformResponse } from 'hapi-lambda'
import { APIGatewayEvent } from 'aws-lambda'
// import { DynamoDB } from 'aws-sdk'
// import { IItemListing } from '../graphql-types'
import { getApi } from './common-api'
// const docClient = new DynamoDB.DocumentClient({... | // !docs.Responses[`ammobinItems`][0][vendor.name]
// ) {
// console.warn('no dynamodb record found')
// } else {
// record = docs.Responses[`ammobinItems`][0][vendor.name].filter(
// (r: IItemListing) => r.link === link
// )[0]
// }
// return record
// }
return awai... | {
// const getRecordFn = async (itemType, subType, vendor, link) => {
// const docs = await docClient
// .batchGet({
// RequestItems: {
// ammobinItems: {
// ExpressionAttributeNames: {
// '#1': vendor.name,
// },
// ProjectionExpression: '... | identifier_body |
lambda.ts | // used to encrypt request ip
import { transformRequest, transformResponse } from 'hapi-lambda'
import { APIGatewayEvent } from 'aws-lambda'
// import { DynamoDB } from 'aws-sdk'
// import { IItemListing } from '../graphql-types'
import { getApi } from './common-api'
// const docClient = new DynamoDB.DocumentClient({... |
const request = transformRequest(event)
// handle cors here if needed
request.headers['Access-Control-Allow-Origin'] = '*'
const response = await _server.inject(request)
return transformResponse(response)
}
| {
_server = await init()
} | conditional_block |
vhtml-tests.ts | /**
* Tests for Hyperscript
*/
import h = require('vhtml');
// Empty element
// $ExpectType string
h('div');
// $ExpectType string
h('span', null, 'Hello, world!');
// $ExpectType string
h(
'section',
{ id: 'some-id' },
h('h1', null, 'Title'),
'List of items:',
h('ol', null, h('li', null, 'Fir... | ({ prop1, prop2 }: { prop1: string; prop2?: number }): string {
return h('div', { id: prop1 }, prop2);
}
// $ExpectType string
h(Component, { prop1: 'foo', prop2: 125 });
// $ExpectType string
h('body', null, h(Component, { prop1: 'foo', prop2: 125 }));
// Missing required prop
// $ExpectError
h(Component, { prop... | Component | identifier_name |
vhtml-tests.ts | /**
* Tests for Hyperscript
*/
import h = require('vhtml');
// Empty element
// $ExpectType string
h('div');
// $ExpectType string
h('span', null, 'Hello, world!');
// $ExpectType string
h(
'section',
{ id: 'some-id' },
h('h1', null, 'Title'),
'List of items:',
h('ol', null, h('li', null, 'Fir... |
// $ExpectType string
h(Component, { prop1: 'foo', prop2: 125 });
// $ExpectType string
h('body', null, h(Component, { prop1: 'foo', prop2: 125 }));
// Missing required prop
// $ExpectError
h(Component, { prop2: 125 });
// Incorrect prop type
// $ExpectError
h(Component, { prop1: 250 });
| {
return h('div', { id: prop1 }, prop2);
} | identifier_body |
vhtml-tests.ts | /**
* Tests for Hyperscript
*/
import h = require('vhtml');
// Empty element
// $ExpectType string
h('div');
// $ExpectType string
h('span', null, 'Hello, world!');
// $ExpectType string
h(
'section',
{ id: 'some-id' },
h('h1', null, 'Title'),
'List of items:',
h('ol', null, h('li', null, 'Fir... |
// -------- Special attributes -------- //
// Both htmlFor and for are supported
// $ExpectType string
h('label', { htmlFor: 'foo' });
// $ExpectType string
h('label', { for: 'foo' });
// Both className and class are supported
// $ExpectType string
h('button', { className: 'bar' });
// $ExpectType string
h('button',... | h('div', { class: 1, 'data-value': 1, 'data-value-2': 'asdf' });
// Unknown tags can have arbitrary attributes
// $ExpectType string
h('mytag', { foo: 1, bar: true }); | random_line_split |
connect-tests.ts | import * as http from "http";
import connect = require("connect");
const app = connect();
// log all requests
app.use((req: http.IncomingMessage, res: http.ServerResponse, next: connect.NextFunction) => {
console.log(req, res);
next();
});
// "Throw" an Error
app.use((req: http.IncomingMessage, res: http.Ser... |
next();
});
// Use legacy `Function` for `next` parameter.
app.use((req: http.IncomingMessage, res: http.ServerResponse, next: Function) => {
next();
});
// respond to all requests
app.use((req: http.IncomingMessage, res: http.ServerResponse) => {
res.end("Hello from Connect!\n");
});
//create node.js ... | {
return res.end(`Error: ${err}`);
} | conditional_block |
connect-tests.ts | import * as http from "http";
import connect = require("connect");
const app = connect();
// log all requests | app.use((req: http.IncomingMessage, res: http.ServerResponse, next: connect.NextFunction) => {
console.log(req, res);
next();
});
// "Throw" an Error
app.use((req: http.IncomingMessage, res: http.ServerResponse, next: connect.NextFunction) => {
next(new Error("Something went wrong!"));
});
// "Throw" a nu... | random_line_split | |
local_ptr.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
// XXX: The boundary between the running runtime and the testing runtime
// seems to be fuzzy at the moment, and trying to use two different keys
// results in disaster. This should not be necessary.
#[inline]
#[cfg(test)]
pub fn maybe_tls_key() -> Option<tls::Key> {
unsafe { ::cast::transmute(::realstd::rt::shou... | {
unsafe {
// NB: This is a little racy because, while the key is
// initalized under a mutex and it's assumed to be initalized
// in the Scheduler ctor by any thread that needs to use it,
// we are not accessing the key under a mutex. Threads that
// are not using the new S... | identifier_body |
local_ptr.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
void_ptr as *mut T
}
pub unsafe fn try_unsafe_borrow<T>() -> Option<*mut T> {
match maybe_tls_key() {
Some(key) => {
let void_ptr = tls::get(key);
if void_ptr.is_null() {
None
} else {
Some(void_ptr as *mut T)
}
}
... | {
rtabort!("thread-local pointer is null. bogus!");
} | conditional_block |
local_ptr.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license | // except according to those terms.
//! Access to a single thread-local pointer.
//!
//! The runtime will use this for storing ~Task.
//!
//! XXX: Add runtime checks for usage of inconsistent pointer types.
//! and for overwriting an existing pointer.
use libc::c_void;
use cast;
use ptr;
use cell::Cell;
use option::{... | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed | random_line_split |
local_ptr.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <T>() -> Option<*mut T> {
match maybe_tls_key() {
Some(key) => {
let void_ptr = tls::get(key);
if void_ptr.is_null() {
None
} else {
Some(void_ptr as *mut T)
}
}
None => None
}
}
#[inline]
fn tls_key() -> tl... | try_unsafe_borrow | identifier_name |
binary_sensor.py | """Binary sensor support for Wireless Sensor Tags."""
import logging
import voluptuous as vol
from homeassistant.components.binary_sensor import (
PLATFORM_SCHEMA, BinarySensorDevice)
from homeassistant.const import CONF_MONITORED_CONDITIONS, STATE_OFF, STATE_ON
from homeassistant.core import callback
import home... |
# Sensor types: Name, device_class, push notification type representing 'on',
# attr to check
SENSOR_TYPES = {
SENSOR_PRESENCE: 'Presence',
SENSOR_MOTION: 'Motion',
SENSOR_DOOR: 'Door',
SENSOR_COLD: 'Cold',
SENSOR_HEAT: 'Heat',
SENSOR_DRY: 'Too dry',
SENSOR_WET: 'Too wet',
SENSOR_LIGHT:... | SENSOR_MOISTURE = 'moisture'
# On means tag battery is low, Off means normal
SENSOR_BATTERY = 'battery' | random_line_split |
binary_sensor.py | """Binary sensor support for Wireless Sensor Tags."""
import logging
import voluptuous as vol
from homeassistant.components.binary_sensor import (
PLATFORM_SCHEMA, BinarySensorDevice)
from homeassistant.const import CONF_MONITORED_CONDITIONS, STATE_OFF, STATE_ON
from homeassistant.core import callback
import home... |
@property
def device_class(self):
"""Return the class of the binary sensor."""
return self._sensor_type
@property
def event(self):
"""Binary event of tag."""
return self._tag.event[self._sensor_type]
@property
def principal_value(self):
"""Return value... | """Return True if the binary sensor is on."""
return self._state == STATE_ON | identifier_body |
binary_sensor.py | """Binary sensor support for Wireless Sensor Tags."""
import logging
import voluptuous as vol
from homeassistant.components.binary_sensor import (
PLATFORM_SCHEMA, BinarySensorDevice)
from homeassistant.const import CONF_MONITORED_CONDITIONS, STATE_OFF, STATE_ON
from homeassistant.core import callback
import home... | (self):
"""Register callbacks."""
tag_id = self.tag_id
event_type = self.device_class
mac = self.tag_manager_mac
async_dispatcher_connect(
self.hass,
SIGNAL_BINARY_EVENT_UPDATE.format(tag_id, event_type, mac),
self._on_binary_event_callback)
... | async_added_to_hass | identifier_name |
binary_sensor.py | """Binary sensor support for Wireless Sensor Tags."""
import logging
import voluptuous as vol
from homeassistant.components.binary_sensor import (
PLATFORM_SCHEMA, BinarySensorDevice)
from homeassistant.const import CONF_MONITORED_CONDITIONS, STATE_OFF, STATE_ON
from homeassistant.core import callback
import home... |
add_entities(sensors, True)
hass.add_job(platform.install_push_notifications, sensors)
class WirelessTagBinarySensor(WirelessTagBaseSensor, BinarySensorDevice):
"""A binary sensor implementation for WirelessTags."""
def __init__(self, api, tag, sensor_type):
"""Initialize a binary sensor fo... | allowed_sensor_types = tag.supported_binary_events_types
for sensor_type in config.get(CONF_MONITORED_CONDITIONS):
if sensor_type in allowed_sensor_types:
sensors.append(WirelessTagBinarySensor(platform, tag,
sensor_type)) | conditional_block |
6739.js | { | var HTMLElement = scope.wrappers.HTMLElement;
var registerWrapper = scope.registerWrapper;
var unwrap = scope.unwrap;
var rewrap = scope.rewrap;
var OriginalHTMLImageElement = window.HTMLImageElement;
function HTMLImageElement(node) {
HTMLElement.call(this, node);
}
HTMLImageElement.prototype = Ob... | ("use strict");
| random_line_split |
6739.js | {
("use strict");
var HTMLElement = scope.wrappers.HTMLElement;
var registerWrapper = scope.registerWrapper;
var unwrap = scope.unwrap;
var rewrap = scope.rewrap;
var OriginalHTMLImageElement = window.HTMLImageElement;
function | (node) {
HTMLElement.call(this, node);
}
HTMLImageElement.prototype = Object.create(HTMLElement.prototype);
registerWrapper(
OriginalHTMLImageElement,
HTMLImageElement,
document.createElement("img")
);
function Image(width, height) {
if (!(this instanceof Image)) {
throw new TypeEr... | HTMLImageElement | identifier_name |
6739.js | {
("use strict");
var HTMLElement = scope.wrappers.HTMLElement;
var registerWrapper = scope.registerWrapper;
var unwrap = scope.unwrap;
var rewrap = scope.rewrap;
var OriginalHTMLImageElement = window.HTMLImageElement;
function HTMLImageElement(node) {
HTMLElement.call(this, node);
}
HTMLImageE... |
Image.prototype = HTMLImageElement.prototype;
scope.wrappers.HTMLImageElement = HTMLImageElement;
scope.wrappers.Image = Image;
}
| {
if (!(this instanceof Image)) {
throw new TypeError(
"DOM object constructor cannot be called as a function."
);
}
var node = unwrap(document.createElement("img"));
HTMLElement.call(this, node);
rewrap(node, this);
if (width !== undefined) node.width = width;
if (heigh... | identifier_body |
autocomplete-n.component.ts | import {Component, ElementRef, EventEmitter, Input, OnInit, Output, ViewChild} from '@angular/core';
import {AutocompleteResult} from 'model/AutocompleteResult';
import {AppConfig} from 'app/app.config';
import {map} from 'rxjs/operators';
import {HttpClient} from '@angular/common/http';
@Component({
selector: 'ap... | })
export class AutocompleteNComponent implements OnInit {
selected: string;
downArrowPressed: Boolean = false;
@Output() submit = new EventEmitter();
@ViewChild('txtInput') txtInput: ElementRef;
@Input()
searchText: string;
constructor(private http: HttpClient, public appConfig: AppConfi... | random_line_split | |
autocomplete-n.component.ts | import {Component, ElementRef, EventEmitter, Input, OnInit, Output, ViewChild} from '@angular/core';
import {AutocompleteResult} from 'model/AutocompleteResult';
import {AppConfig} from 'app/app.config';
import {map} from 'rxjs/operators';
import {HttpClient} from '@angular/common/http';
@Component({
selector: 'ap... |
private extractData(res: Object): string[] {
const body = res;
// return body || { };
let searchResult: AutocompleteResult;
searchResult = (body || {}) as AutocompleteResult;
return searchResult.items.map(x => x.name);
}
keydown(event) {
switch (event.keyCo... | {
return this.http.get(this.appConfig.getAutocompleteUrl(keyword))
.pipe(map(this.extractData));
} | identifier_body |
autocomplete-n.component.ts | import {Component, ElementRef, EventEmitter, Input, OnInit, Output, ViewChild} from '@angular/core';
import {AutocompleteResult} from 'model/AutocompleteResult';
import {AppConfig} from 'app/app.config';
import {map} from 'rxjs/operators';
import {HttpClient} from '@angular/common/http';
@Component({
selector: 'ap... | (res: Object): string[] {
const body = res;
// return body || { };
let searchResult: AutocompleteResult;
searchResult = (body || {}) as AutocompleteResult;
return searchResult.items.map(x => x.name);
}
keydown(event) {
switch (event.keyCode) {
case 40... | extractData | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.