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 |
|---|---|---|---|---|
delayed_gcode.py | # A simple timer for executing gcode templates
#
# Copyright (C) 2019 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import logging
class DelayedGcode:
def __init__(self, config):
self.printer = config.get_printer()
self.reactor =... | self.duration = gcmd.get_float('DURATION', minval=0.)
if self.inside_timer:
self.repeat = (self.duration != 0.)
else:
waketime = self.reactor.NEVER
if self.duration:
waketime = self.reactor.monotonic() + self.duration
self.reactor.u... | nextwake = eventtime + self.duration
self.inside_timer = self.repeat = False
return nextwake
cmd_UPDATE_DELAYED_GCODE_help = "Update the duration of a delayed_gcode"
def cmd_UPDATE_DELAYED_GCODE(self, gcmd): | random_line_split |
wines.reducer.ts | import { WinecellarActions, ActionTypes } from '../actions';
import { Wine } from '../../stock/types/Wine';
export function winesReducer(state: Wine[] = [], action: WinecellarActions): Wine[] {
switch (action.type) {
case ActionTypes.WINES_ADD:
return [...state, action.payload.wine];
case ActionTypes.W... | return state.map(item => item._id === action.payload.id ? {...item, myRating: action.payload.myRating} : item);
case ActionTypes.WINES_UPDATE_STOCK:
return state.map(item => item._id === action.payload.id ? {...item, inStock: action.payload.inStock} : item);
default:
return state;
}
} | random_line_split | |
wines.reducer.ts | import { WinecellarActions, ActionTypes } from '../actions';
import { Wine } from '../../stock/types/Wine';
export function winesReducer(state: Wine[] = [], action: WinecellarActions): Wine[] | {
switch (action.type) {
case ActionTypes.WINES_ADD:
return [...state, action.payload.wine];
case ActionTypes.WINES_SET_ALL:
return [...action.payload.wines];
case ActionTypes.WINES_REMOVE:
return state.filter(item => item._id !== action.payload.id);
case ActionTypes.WINES_UPDATE:
... | identifier_body | |
wines.reducer.ts | import { WinecellarActions, ActionTypes } from '../actions';
import { Wine } from '../../stock/types/Wine';
export function | (state: Wine[] = [], action: WinecellarActions): Wine[] {
switch (action.type) {
case ActionTypes.WINES_ADD:
return [...state, action.payload.wine];
case ActionTypes.WINES_SET_ALL:
return [...action.payload.wines];
case ActionTypes.WINES_REMOVE:
return state.filter(item => item._id !== a... | winesReducer | identifier_name |
pyembedpg.py | obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for... | (port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
return sock.connect_ex(('127.0.0.1', port)) != 0
self.running_port = next((port for port in ports if can_connect(port)), None)
if self.running_port is None:
raise PyEmbedPgException('Cannot run postgres... | can_connect | identifier_name |
pyembedpg.py | may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License... | import tarfile
import tempfile
import time
from contextlib import closing
from distutils import spawn
from os.path import expanduser
from subprocess import Popen
import psycopg2
import requests
from psycopg2._psycopg import OperationalError
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
logger = logging.g... | random_line_split | |
pyembedpg.py | obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for... |
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.shutdown()
def create_user(self, username, password):
"""Create a user
:param username:
:type username: basestring
:param password:
:type password: basestring
... | raise PyEmbedPgException('Cannot start postgres after {timeout} seconds'.format(timeout=DatabaseRunner.TIMEOUT)) | conditional_block |
pyembedpg.py | obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for... |
def check_version_present(self):
"""
Check if the version is present in the cache
:return: True if the version has already been downloaded and build, False otherwise
"""
return os.path.exists(self._version_path)
def download_and_unpack(self):
# if the version w... | """
Return the latest version on the Postgres FTP server
:return: latest version installed locally on the Postgres FTP server
"""
response = requests.get(PyEmbedPg.DOWNLOAD_BASE_URL)
last_version_match = list(re.finditer('>v(?P<version>[^<]+)<', response.content.decode()))[-1]
... | identifier_body |
mod.rs | // Copyright 2012-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-MI... | match tname.get() {
"Clone" => expand!(clone::expand_deriving_clone),
"Hash" => expand!(hash::expand_deriving_hash),
"Encodable" => expand!(encodable::expand_deriving_encodable),
"De... | {
match mitem.node {
MetaNameValue(_, ref l) => {
cx.span_err(l.span, "unexpected value in `deriving`");
}
MetaWord(_) => {
cx.span_warn(mitem.span, "empty trait list in `deriving`");
}
MetaList(_, ref titems) if titems.len() == 0 => {
cx.s... | identifier_body |
mod.rs | // Copyright 2012-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-MI... | (cx: &mut ExtCtxt,
_span: Span,
mitem: @MetaItem,
item: @Item,
push: |@Item|) {
match mitem.node {
MetaNameValue(_, ref l) => {
cx.span_err(l.span, "unexpected value in `deriving`");
... | expand_meta_deriving | identifier_name |
mod.rs | // Copyright 2012-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-MI... | pub mod default;
pub mod primitive;
#[path="cmp/eq.rs"]
pub mod eq;
#[path="cmp/totaleq.rs"]
pub mod totaleq;
#[path="cmp/ord.rs"]
pub mod ord;
#[path="cmp/totalord.rs"]
pub mod totalord;
pub mod generic;
pub fn expand_meta_deriving(cx: &mut ExtCtxt,
_span: Span,
... | pub mod decodable;
pub mod hash;
pub mod rand;
pub mod show;
pub mod zero; | random_line_split |
tmdrv.py | #!/usr/bin/env python3
# Copyright 2016, 2017 Andrew Conrad
#
# 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 3 of the License, or
# (at your option) any later version.
#
# This ... | value,
index,
data,
)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-d', '--device', default='thrustmaster_tx',
help='Specify device to use')
parser.add_argument('-D', '--supported-devices', action='store_true',
help='List all supported devices')
a... | handle.controlWrite(
request_type,
request, | random_line_split |
tmdrv.py | #!/usr/bin/env python3
# Copyright 2016, 2017 Andrew Conrad
#
# 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 3 of the License, or
# (at your option) any later version.
#
# This ... | m['index'],
m['data'],
)
except usb1.USBErrorNotFound:
print('Error getting handle for device {:0=4x}:{:0=4x} ({} Step {}).'.format(device.idVendor, device.idProduct[m['step']-1], device.name, m['step']))
raise
except usb1.USBErrorNoDevice:
# Caught when device switches modes
pass
except us... | try:
device = import_module('tmdrv_devices.' + device_name)
except ModuleNotFoundError:
print('Device name "' + device_name + '" is invalid.')
raise
try:
device
except UnboundLocalError:
print('Device name "' + device_name + '" is invalid.')
raise
# Send all control packets for initialization
for m i... | identifier_body |
tmdrv.py | #!/usr/bin/env python3
# Copyright 2016, 2017 Andrew Conrad
#
# 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 3 of the License, or
# (at your option) any later version.
#
# This ... | (idVendor, idProduct, request_type, request, value, index, data):
handle = _context.openByVendorIDAndProductID(
idVendor, idProduct,
)
if handle is None:
raise usb1.USBErrorNotFound('Device not found or wrong permissions')
handle.setAutoDetachKernelDriver(True)
handle.claimInterface(0)
# Send control packet ... | _control_init | identifier_name |
tmdrv.py | #!/usr/bin/env python3
# Copyright 2016, 2017 Andrew Conrad
#
# 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 3 of the License, or
# (at your option) any later version.
#
# This ... |
handle.setAutoDetachKernelDriver(True)
handle.claimInterface(0)
# Send control packet that will switch modes
handle.controlWrite(
request_type,
request,
value,
index,
data,
)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-d', '--device', defaul... | raise usb1.USBErrorNotFound('Device not found or wrong permissions') | conditional_block |
CanvasLayerOptions.js | /**
* Copyright 2012 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applic... | () {}
/**
* If true, updateHandler will be called repeatedly, once per frame. If false,
* updateHandler will only be called when a map property changes that could
* require the canvas content to be redrawn.
* @type {boolean}
*/
CanvasLayerOptions.prototype.animate;
/**
* Map on which to overlay the canvas.
* @... | CanvasLayerOptions | identifier_name |
CanvasLayerOptions.js | /**
* Copyright 2012 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applic... |
/**
* If true, updateHandler will be called repeatedly, once per frame. If false,
* updateHandler will only be called when a map property changes that could
* require the canvas content to be redrawn.
* @type {boolean}
*/
CanvasLayerOptions.prototype.animate;
/**
* Map on which to overlay the canvas.
* @type ... | {} | identifier_body |
CanvasLayerOptions.js | /**
* Copyright 2012 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applic... | * buffer down, or to support high DPI devices by scaling it up (by e.g.
* window.devicePixelRatio).
* @type {number}
*/
CanvasLayerOptions.prototype.resolutionScale;
/**
* A function that is called when a repaint of the canvas is required.
* @type {function}
*/
CanvasLayerOptions.prototype.updateHandler; |
/**
* A value for scaling the CanvasLayer resolution relative to the CanvasLayer
* display size. This can be used to save computation by scaling the backing | random_line_split |
setup.py | from distutils.core import setup
setup(
name='megad-mqtt-gw',
version='0.3',
description='Gateway between MQTT queue and MegaD devices (http://ab-log.ru)',
author='rs',
author_email='repalov@gmail.com',
url='https://github.com/repalov/megad-mqtt-gw',
license='Apache License',
classifier... | install_requires=['aiohttp>=3.4.4', 'paho-mqtt>=1.4', 'netifaces>=0.10.7'],
data_files=[('/etc', ['megad-mqtt-gw.homeassistant.conf', 'megad-mqtt-gw.wirenboard.conf']),
('/lib/systemd/system', ['megad-mqtt-gw.service'])
],
entry_points={'console_scripts': ['megad-mqtt-gw=mega... | packages=['megad'], | random_line_split |
__init__.py | # -*- coding: utf-8 -*-
#
# Copyright (C) 2017 European Synchrotron Radiation Facility, Grenoble, France
#
# Principal author: Wout De Nolf (wout.de_nolf@esrf.eu)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software")... | #
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOS... | # furnished to do so, subject to the following conditions: | random_line_split |
healthkit.js | var page;
var healthStore;
var weightType;
function pageLoaded(args) {
page = args.object;
weightType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass);
healthStore = HKHealthStore.new();
requestPermissions(healthStore, [weightType], [weightType]);
}
exports.pageLoaded = pageLoa... |
});
}
function getHealthKitValue(healthStore, quantityType, callback) {
var endDateSortDescriptor = NSSortDescriptor.alloc().initWithKeyAscending(HKSampleSortIdentifierEndDate, false);
var query = HKSampleQuery.alloc().initWithSampleTypePredicateLimitSortDescriptorsResultsHandler(quantityType, null, 1, [en... | {
} | conditional_block |
healthkit.js | var page;
var healthStore;
var weightType;
function pageLoaded(args) {
page = args.object;
weightType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass);
healthStore = HKHealthStore.new();
requestPermissions(healthStore, [weightType], [weightType]);
}
exports.pageLoaded = pageLoa... |
exports.setWeightButtonTap = setWeightButtonTap;
function hideKeyboard() {
var textField = page.getViewById("weightTextView");
textField.ios.resignFirstResponder();
}
function requestPermissions(healthStore, writeTypes, readTypes) {
var writeDataTypes = NSSet.setWithArray(writeTypes);
var readDataTypes... | {
hideKeyboard();
var textField = page.getViewById("weightTextView");
var weight = parseFloat(textField.text);
setHalthKitValue(healthStore, weightType, HKQuantity.quantityWithUnitDoubleValue(HKUnit.poundUnit(), weight));
} | identifier_body |
healthkit.js | var page;
var healthStore;
var weightType;
function pageLoaded(args) {
page = args.object;
weightType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass);
healthStore = HKHealthStore.new();
requestPermissions(healthStore, [weightType], [weightType]);
}
exports.pageLoaded = pageLoa... | if (quantitySample) {
callback(quantitySample.quantity);
}
else {
alert("Error!");
}
}
else {
alert("Error!");
}
});
healthStore.executeQuery(query);
}
function setHalthKitValue(healthStore, quant... | random_line_split | |
healthkit.js | var page;
var healthStore;
var weightType;
function pageLoaded(args) {
page = args.object;
weightType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierBodyMass);
healthStore = HKHealthStore.new();
requestPermissions(healthStore, [weightType], [weightType]);
}
exports.pageLoaded = pageLoa... | (args) {
hideKeyboard();
var textField = page.getViewById("weightTextView");
var weight = parseFloat(textField.text);
setHalthKitValue(healthStore, weightType, HKQuantity.quantityWithUnitDoubleValue(HKUnit.poundUnit(), weight));
}
exports.setWeightButtonTap = setWeightButtonTap;
function hideKeyboard() ... | setWeightButtonTap | identifier_name |
Fieldset.tsx | import {
CSSProperties,
FieldsetHTMLAttributes,
forwardRef,
ReactNode,
} from "react";
import cn from "classnames";
import { bem } from "@react-md/utils";
export interface FieldsetProps
extends FieldsetHTMLAttributes<HTMLFieldSetElement> {
/**
* The legend to display. This is required since a fieldset l... | ref={ref}
className={cn(block({ unstyled }), className)}
>
<legend
style={legendStyle}
className={cn(
block("legend", { "sr-only": legendSROnly }),
legendClassName
)}
>
{legend}
</legend>
{children}
... | return (
<fieldset
{...props} | random_line_split |
getNumberOfReminders.js | var mongoose = require('mongoose'),
_ = require('lodash'),
moment = require('moment');
module.exports = function (req, res) {
var connectionDB = mongoose.connection.db;
var today = moment().startOf('day');
var tomorrow = moment(today).add(1, 'days');
var dayAfterTomorrow = moment(today).add(2, ... |
if (a.sentReminderEmail === undefined
&& a.sentReminderEmail !== 'sent'
&& a.customer.email !== ''
&& a.sendEmail){
appointmentsEmail.push(a);
... | {
console.log('here');
appointmentsPhone.push(a);
} | conditional_block |
getNumberOfReminders.js | var mongoose = require('mongoose'),
_ = require('lodash'),
moment = require('moment');
module.exports = function (req, res) {
var connectionDB = mongoose.connection.db;
var today = moment().startOf('day');
var tomorrow = moment(today).add(1, 'days');
var dayAfterTomorrow = moment(today).add(2, ... | console.log(err)
} else {
var appointmentsPhone = [];
var appointmentsEmail = [];
cursor.toArray(function (err, result) {
if (err) {
console.log(err);
} else {
... | }, function(err, cursor){
if (err) { | random_line_split |
expander.ts | import {BaseException} from '../facade/exceptions';
import {HtmlAst, HtmlAstVisitor, HtmlAttrAst, HtmlCommentAst, HtmlElementAst, HtmlExpansionAst, HtmlExpansionCaseAst, HtmlTextAst, htmlVisitAll} from '../html_ast';
import {ParseError} from '../parse_util';
import {I18nError} from './shared';
// http://cldr.unicode.o... |
const expansionResult = expandNodes(c.expression);
errors.push(...expansionResult.errors);
return new HtmlElementAst(
`template`, [new HtmlAttrAst('ngPluralCase', `${c.value}`, c.valueSourceSpan)],
expansionResult.nodes, c.sourceSpan, c.sourceSpan, c.sourceSpan);
});
const switchAttr ... | {
errors.push(new I18nError(
c.valueSourceSpan,
`Plural cases should be "=<number>" or one of ${PLURAL_CASES.join(", ")}`));
} | conditional_block |
expander.ts | import {BaseException} from '../facade/exceptions';
import {HtmlAst, HtmlAstVisitor, HtmlAttrAst, HtmlCommentAst, HtmlElementAst, HtmlExpansionAst, HtmlExpansionCaseAst, HtmlTextAst, htmlVisitAll} from '../html_ast';
import {ParseError} from '../parse_util';
import {I18nError} from './shared';
// http://cldr.unicode.o... |
}
/**
* Expand expansion forms (plural, select) to directives
*
* @internal
*/
class _Expander implements HtmlAstVisitor {
isExpanded: boolean = false;
errors: ParseError[] = [];
visitElement(ast: HtmlElementAst, context: any): any {
return new HtmlElementAst(
ast.name, ast.attrs, htmlVisitAll(... | {} | identifier_body |
expander.ts | import {BaseException} from '../facade/exceptions';
import {HtmlAst, HtmlAstVisitor, HtmlAttrAst, HtmlCommentAst, HtmlElementAst, HtmlExpansionAst, HtmlExpansionCaseAst, HtmlTextAst, htmlVisitAll} from '../html_ast';
import {ParseError} from '../parse_util';
import {I18nError} from './shared';
// http://cldr.unicode.o... | {
constructor(public nodes: HtmlAst[], public expanded: boolean, public errors: ParseError[]) {}
}
/**
* Expand expansion forms (plural, select) to directives
*
* @internal
*/
class _Expander implements HtmlAstVisitor {
isExpanded: boolean = false;
errors: ParseError[] = [];
visitElement(ast: HtmlElement... | ExpansionResult | identifier_name |
expander.ts | import {BaseException} from '../facade/exceptions';
import {HtmlAst, HtmlAstVisitor, HtmlAttrAst, HtmlCommentAst, HtmlElementAst, HtmlExpansionAst, HtmlExpansionCaseAst, HtmlTextAst, htmlVisitAll} from '../html_ast';
import {ParseError} from '../parse_util';
import {I18nError} from './shared';
// http://cldr.unicode.o... | }
visitAttr(ast: HtmlAttrAst, context: any): any { return ast; }
visitText(ast: HtmlTextAst, context: any): any { return ast; }
visitComment(ast: HtmlCommentAst, context: any): any { return ast; }
visitExpansion(ast: HtmlExpansionAst, context: any): any {
this.isExpanded = true;
return ast.type ==... | visitElement(ast: HtmlElementAst, context: any): any {
return new HtmlElementAst(
ast.name, ast.attrs, htmlVisitAll(this, ast.children), ast.sourceSpan, ast.startSourceSpan,
ast.endSourceSpan); | random_line_split |
urls.py | """core URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based... | urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^test_app/companies/', test_app_views.companies_list_view),
] | from test_app import views as test_app_views
| random_line_split |
init-res-into-things.rs | // Copyright 2012 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 ... | () {
test_box();
test_rec();
test_tag();
test_tup();
test_unique();
test_box_rec();
}
| main | identifier_name |
init-res-into-things.rs | // Copyright 2012 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 |
// Resources can't be copied, but storing into data structures counts
// as a move unless the stored thing is used afterwards.
struct r {
i: @mut int,
}
struct Box { x: r }
#[unsafe_destructor]
impl Drop for r {
fn finalize(&self) {
unsafe {
*(self.i) = *(self.i) + 1;
}
}
}
fn... | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms. | random_line_split |
init-res-into-things.rs | // Copyright 2012 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 ... |
fn test_box() {
let i = @mut 0;
{
let a = @r(i);
}
assert!(*i == 1);
}
fn test_rec() {
let i = @mut 0;
{
let a = Box {x: r(i)};
}
assert!(*i == 1);
}
fn test_tag() {
enum t {
t0(r),
}
let i = @mut 0;
{
let a = t0(r(i));
}
asser... | {
r {
i: i
}
} | identifier_body |
logic.js | ["dojox.dtl.tag.logic"]){
dojo._hasResource["dojox.dtl.tag.logic"]=true;
dojo.provide("dojox.dtl.tag.logic");
dojo.require("dojox.dtl._base");
(function(){
var dd=dojox.dtl;
var _1=dd.text;
var _2=dd.tag.logic;
_2.IfNode=dojo.extend(function(_3,_4,_5,_6){
this.bools=_3;
this.trues=_4;
this.falses=_5;
this.type=_6;
},{r... | else{
_2a=_28;
}
var _2b=_24.forloop={parentloop:_24.get("forloop",{})};
var j=0;
for(i=0;i<_2a.length;i++){
var _2c=_2a[i];
_2b.counter0=j;
_2b.counter=j+1;
_2b.revcounter0=_2a.length-j-1;
_2b.revcounter=_2a.length-j;
_2b.first=!j;
_2b.last=(j==_2a.length-1);
if(_27.length>1&&dojo.isArrayLike(_2c)){
if(!_26){
_26=true... | {
for(var key in _28){
_2a.push(_28[key]);
}
} | conditional_block |
logic.js | Resource["dojox.dtl.tag.logic"]){
dojo._hasResource["dojox.dtl.tag.logic"]=true;
dojo.provide("dojox.dtl.tag.logic");
dojo.require("dojox.dtl._base");
(function(){
var dd=dojox.dtl;
var _1=dd.text;
var _2=dd.tag.logic;
_2.IfNode=dojo.extend(function(_3,_4,_5,_6){
this.bools=_3;
this.trues=_4;
this.falses=_5;
this.type=... | var _29=dojo.isObject(_28)&&!dojo.isArrayLike(_28);
var _2a=[];
if(_29){
for(var key in _28){
_2a.push(_28[key]);
}
}else{
_2a=_28;
}
var _2b=_24.forloop={parentloop:_24.get("forloop",{})};
var j=0;
for(i=0;i<_2a.length;i++){
var _2c=_2a[i];
_2b.counter0=j;
_2b.counter=j+1;
_2b.revcounter0=_2a.length-j-1;
_2b.revcounte... | random_line_split | |
test_type_error.rs | /*
* Copyright 2021 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 agreed to ... |
}
| {
compile("type_error", "test_inputs", "test_outputs", "");
} | identifier_body |
test_type_error.rs | /*
* Copyright 2021 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 agreed to ... | () {
compile("type_error", "test_inputs", "test_outputs", "");
}
}
| test_type_error | identifier_name |
test_type_error.rs | *
* 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 agreed to in writing, software
* distribut... | /*
* Copyright 2021 Google LLC. | random_line_split | |
pyminer.py | #!/usr/bin/python
#
# Copyright (c) 2011 The VirtaCoin developers
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
import time
import json
import pprint
import hashlib
import struct
import re
import base64
import httplib
impo... | l = long(hash_str, 16)
# proof-of-work test: hash < target
if l < target:
print time.asctime(), "PROOF-OF-WORK found: %064x" % (l,)
return (nonce + 1, nonce_bin)
else:
print time.asctime(), "PROOF-OF-WORK false positive %064x" % (l,)
# return (nonce + 1, nonce_bin)
return (nonce + 1, Non... | hash_str = hash.encode('hex') | random_line_split |
pyminer.py | #!/usr/bin/python
#
# Copyright (c) 2011 The VirtaCoin developers
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
import time
import json
import pprint
import hashlib
import struct
import re
import base64
import httplib
impo... | :
def __init__(self, id):
self.id = id
self.max_nonce = MAX_NONCE
def work(self, datastr, targetstr):
# decode work data hex string to binary
static_data = datastr.decode('hex')
static_data = bufreverse(static_data)
# the first 76b of 80b do not change
blk_hdr = static_data[:76]
# decode 256-bit ta... | Miner | identifier_name |
pyminer.py | #!/usr/bin/python
#
# Copyright (c) 2011 The VirtaCoin developers
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
import time
import json
import pprint
import hashlib
import struct
import re
import base64
import httplib
impo... |
while True:
self.iterate(rpc)
def miner_thread(id):
miner = Miner(id)
miner.loop()
if __name__ == '__main__':
if len(sys.argv) != 2:
print "Usage: pyminer.py CONFIG-FILE"
sys.exit(1)
f = open(sys.argv[1])
for line in f:
# skip comment lines
m = re.search('^\s*#', line)
if m:
continue
# pa... | return | conditional_block |
pyminer.py | #!/usr/bin/python
#
# Copyright (c) 2011 The VirtaCoin developers
# Distributed under the MIT/X11 software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
import time
import json
import pprint
import hashlib
import struct
import re
import base64
import httplib
impo... |
def iterate(self, rpc):
work = rpc.getwork()
if work is None:
time.sleep(ERR_SLEEP)
return
if 'data' not in work or 'target' not in work:
time.sleep(ERR_SLEEP)
return
time_start = time.time()
(hashes_done, nonce_bin) = self.work(work['data'],
work['target'])
time_end = time.time... | nonce_bin = bufreverse(nonce_bin)
nonce = nonce_bin.encode('hex')
solution = original_data[:152] + nonce + original_data[160:256]
param_arr = [ solution ]
result = rpc.getwork(param_arr)
print time.asctime(), "--> Upstream RPC result:", result | identifier_body |
test_regions.py | from contextlib import contextmanager
from mpconstants.countries import COUNTRY_DETAILS
from nose.tools import eq_, ok_
from tower import activate
import mkt.constants.regions as regions
from mkt.site.tests import TestCase
class TestRegions(TestCase):
def test_no_missing_region(self):
"""Test that we hav... |
class TestRegionContentRatings(TestCase):
@contextmanager
def tower_activate(self, region):
try:
activate(region)
yield
finally:
activate('en-US')
def test_region_to_ratings_body(self):
region_to_body = regions.REGION_TO_RATINGS_BODY()
... | ok_(issubclass(region, regions.REGION))
# Make sure we can find each region in the regions module locals.
eq_(getattr(regions, region.__name__), region)
# Make sure the name is a lazy unicode object - encoding it to
# utf-8 it should work.
ok_(region.name.en... | conditional_block |
test_regions.py | from contextlib import contextmanager
from mpconstants.countries import COUNTRY_DETAILS
from nose.tools import eq_, ok_
from tower import activate
import mkt.constants.regions as regions
from mkt.site.tests import TestCase
class TestRegions(TestCase):
def test_no_missing_region(self):
|
def test_regions_dict(self):
eq_(regions.REGIONS_DICT['restofworld'], regions.RESTOFWORLD)
eq_(regions.REGIONS_DICT['us'], regions.USA)
for region in regions.REGIONS_DICT.values():
# Make sure the regions dict contains region objects.
ok_(issubclass(region, regions.... | """Test that we haven't forgotten to add some regions to the lookup
dictionary."""
defined_regions = regions.REGION_LOOKUP.keys()
available_regions = {c['slug'] for c in COUNTRY_DETAILS.values()}
eq_(list(available_regions.difference(defined_regions)), []) | identifier_body |
test_regions.py | from contextlib import contextmanager
from mpconstants.countries import COUNTRY_DETAILS
from nose.tools import eq_, ok_
from tower import activate
import mkt.constants.regions as regions
from mkt.site.tests import TestCase
class TestRegions(TestCase):
def test_no_missing_region(self):
"""Test that we hav... | ok_(region_names_fr.index(regions.USA.name) <
region_names_fr.index(regions.GBR.name)) | region_names_fr = [unicode(r[1]) for r in
regions.REGIONS_CHOICES_SORTED_BY_NAME()]
ok_(region_names_fr.index(regions.ESP.name) <
region_names_fr.index(regions.USA.name)) | random_line_split |
test_regions.py | from contextlib import contextmanager
from mpconstants.countries import COUNTRY_DETAILS
from nose.tools import eq_, ok_
from tower import activate
import mkt.constants.regions as regions
from mkt.site.tests import TestCase
class TestRegions(TestCase):
def test_no_missing_region(self):
"""Test that we hav... | (self, region):
try:
activate(region)
yield
finally:
activate('en-US')
def test_region_to_ratings_body(self):
region_to_body = regions.REGION_TO_RATINGS_BODY()
eq_(region_to_body['br'], 'classind')
eq_(region_to_body['es'], 'pegi')
... | tower_activate | identifier_name |
unread.js |
'use strict';
var async = require('async');
var nconf = require('nconf');
var querystring = require('querystring');
var meta = require('../meta');
var pagination = require('../pagination');
var user = require('../user');
var topics = require('../topics');
var plugins = require('../plugins');
var helpers = require('.... |
async.parallel({
watchedCategories: function (next) {
helpers.getWatchedCategories(req.uid, cid, next);
},
settings: function (next) {
user.getSettings(req.uid, next);
},
}, _next);
},
function (_results, next) {
results = _results;
settings = results.settings;
var start =... | {
return next();
} | conditional_block |
unread.js | 'use strict';
var async = require('async');
var nconf = require('nconf');
var querystring = require('querystring');
var meta = require('../meta');
var pagination = require('../pagination');
var user = require('../user');
var topics = require('../topics');
var plugins = require('../plugins');
var helpers = require('./... | async.parallel({
watchedCategories: function (next) {
helpers.getWatchedCategories(req.uid, cid, next);
},
settings: function (next) {
user.getSettings(req.uid, next);
},
}, _next);
},
function (_results, next) {
results = _results;
settings = results.settings;
var start = M... | if (!data.filters[filter]) {
return next();
}
| random_line_split |
win_file.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2015, Jon Hawkesworth (@jhawkesworth) <figs@unity.demon.co.uk>
#
# This file is part of Ansible
#
# Ansible 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, eith... |
ANSIBLE_METADATA = {'status': ['stableinterface'],
'supported_by': 'core',
'version': '1.0'}
DOCUMENTATION = r'''
---
module: win_file
version_added: "1.9.2"
short_description: Creates, touches or removes files or directories.
description:
- Creates (empty) files, updates ... | random_line_split | |
lib.rs | // Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable... |
fn handle_request(&mut self, mut ctx: RpcCtx, method: &str, params: &Value) ->
Result<Value, Value> {
match Request::from_json(method, params) {
Ok(req) => {
let result = self.handle_req(req, &mut ctx);
result.ok_or_else(|| json!("return value missing"))... | {
match Request::from_json(method, params) {
Ok(req) => {
if let Some(_) = self.handle_req(req, &mut ctx) {
print_err!("Unexpected return value for notification {}", method)
}
}
Err(e) => print_err!("Error {} decoding RPC re... | identifier_body |
lib.rs | // Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable... | print_err!("Error {} decoding RPC request {}", e, method);
Err(json!("error decoding request"))
}
}
}
fn idle(&mut self, _ctx: RpcCtx, _token: usize) {
self.tabs.handle_idle();
}
}
impl MainState {
fn handle_req(&mut self, request: Request, r... | Err(e) => { | random_line_split |
lib.rs | // Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable... | (&mut self, request: Request, rpc_ctx: &mut RpcCtx) ->
Option<Value> {
match request {
Request::CoreCommand { core_command } => self.tabs.do_rpc(core_command, rpc_ctx)
}
}
}
| handle_req | identifier_name |
randinterq.py | import os
import sys
import errno
import random
import glob
import tkinter
from tkinter import filedialog
import pyautogui
import time
import configparser
root = tkinter.Tk()
root.withdraw()
#Setting current Dir
dir_path = os.path.dirname(os.path.realpath(__file__))
#Move mouse to upper left screen to kill in case ... |
if len(sys.argv) == 1:
print("\nWelcome to the Apollo.rip Interviewer Companion app!")
choosedir = input("\nWould you like to change the location of the question folders? (y/n): ")
if choosedir == 'y':
qpath = filedialog.askdirectory(initialdir='.')
makedir = input("Do you wish to make some di... | os.chdir(dir_path)
config['Default'] = {}
config['Default']['ahkdir'] = ahkpath
config['Default']['autokeydir'] = autokeypath
config['Default']['qdir'] = qpath
with open('config.ini', 'w') as configfile:
config.write(configfile)
print("\nFor normal use of this program, please pass the nu... | identifier_body |
randinterq.py | import os
import sys
import errno
import random
import glob
import tkinter
from tkinter import filedialog
import pyautogui
import time
import configparser
root = tkinter.Tk()
root.withdraw()
#Setting current Dir
dir_path = os.path.dirname(os.path.realpath(__file__))
#Move mouse to upper left screen to kill in case ... | ahktemplate = ("""
::{0}::
SetWorkingDir, {1}
Run %comspec% /c ""{2}" "{3}"",,hide
return
""")
config = configparser.ConfigParser()
ahkpath = 'none'
autokeypath = 'None'
qpath = dir_path
if os.path.isfile('config.ini'):
config.sections()
config.read('config.ini')
ahkpath = config['Default']['ahkdir']
... | random_line_split | |
randinterq.py | import os
import sys
import errno
import random
import glob
import tkinter
from tkinter import filedialog
import pyautogui
import time
import configparser
root = tkinter.Tk()
root.withdraw()
#Setting current Dir
dir_path = os.path.dirname(os.path.realpath(__file__))
#Move mouse to upper left screen to kill in case ... | ():
numq = None
print("\nI recommend using question 0 as the intro of your interview script."
"It will be created along with the other questions.")
numq = int(input("\nPlease enter the number of questions you have: "))
a = 0
os.chdir(ahkpath)
filename = os.path.splitext(os.path.basenam... | genahk | identifier_name |
randinterq.py | import os
import sys
import errno
import random
import glob
import tkinter
from tkinter import filedialog
import pyautogui
import time
import configparser
root = tkinter.Tk()
root.withdraw()
#Setting current Dir
dir_path = os.path.dirname(os.path.realpath(__file__))
#Move mouse to upper left screen to kill in case ... |
file.write(ahktemplate.format('pass', dir_path, '%s.exe' % filename, 'pass'))
file.write(ahktemplate.format('fail', dir_path, '%s.exe' % filename, 'fail'))
leaving()
def leaving():
os.chdir(dir_path)
config['Default'] = {}
config['Default']['ahkdir'] = ahkpath
config['Default']['au... | file.write(ahktemplate.format('q%s' % a, dir_path, '%s.exe' % filename, a))
a = a + 1 | conditional_block |
en-ca.js | // moment.js language configuration
// language : canadian english (en-ca)
// author : Jonathan Abourbih : https://github.com/jonbca
(function (factory) {
if (typeof define === 'function' && define.amd) {
define(['moment'], factory); // AMD
} else if (typeof exports === 'object') {
module.expor... | } else {
factory(window.moment); // Browser global
}
}(function (moment) {
return moment.lang('en-ca', {
months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split(... | random_line_split | |
en-ca.js | // moment.js language configuration
// language : canadian english (en-ca)
// author : Jonathan Abourbih : https://github.com/jonbca
(function (factory) {
if (typeof define === 'function' && define.amd) {
define(['moment'], factory); // AMD
} else if (typeof exports === 'object') {
module.expor... |
}(function (moment) {
return moment.lang('en-ca', {
months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"),
monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),
weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_F... | {
factory(window.moment); // Browser global
} | conditional_block |
CommonProps.d.ts | import * as React from 'react';
interface ReactWidgetsCommonProps<C> extends React.Props<C> {
/**
* Disable the widget, if an Array of values is passed in only those values will be disabled.
* @default false
*/
disabled?: boolean | any[];
/**
* Place the widget in a read-only m... | }
interface ReactWidgetsCommonDropdownProps<C> extends ReactWidgetsCommonProps<C> {
/**
* Show "drop up" not "drop down"
* @default false
*/
dropUp?: boolean;
} | export interface AutoFocus {
/**
* Pass focus to component when it mounts.
*/
autoFocus?: boolean;
| random_line_split |
PackageListView.js | /*
* Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
*/
define([
"underscore",
"contrail-view",
"contrail-list-model",
"sm-constants",
"sm-labels",
"sm-utils"
], function (_, ContrailView, ContrailListModel, smwc, smwl, smwu) {
var PackageListView = ContrailView.extend({
... | app: cowc.APP_CONTRAIL_SM,
viewConfig: {pagerOptions: { options: { pageSize: 25, pageSizeSelect: [25, 50, 100] } }}
}
]
}
]
}
};
};
return ... | title: smwl.TITLE_PACKAGES,
view: "PackageGridView", | random_line_split |
facebook.py | (object):
"""A client for the Facebook Graph API.
See http://developers.facebook.com/docs/api for complete
documentation for the API.
The Graph API is made up of the objects in Facebook (e.g., people,
pages, events, photos) and the connections between them (e.g.,
friends, photo tags, and event RSVPs). Thi... | GraphAPI | identifier_name | |
facebook.py | init__(self, access_token=None, timeout=None):
self.access_token = access_token
self.timeout = timeout
def get_object(self, id, **args):
"""Fetchs the given object from the graph."""
return self.request(id, args)
def get_objects(self, ids, **args):
"""Fetchs al... |
else:
args["access_token"] = self.access_token
post_data = None if post_args is None else urllib.urlencode(post_args)
try:
file = urllib2.urlopen("https://graph.facebook.com/" + path + "?" +
urllib.urlencode(args),
... | post_args["access_token"] = self.access_token | conditional_block |
facebook.py | init__(self, access_token=None, timeout=None):
self.access_token = access_token
self.timeout = timeout
def get_object(self, id, **args):
"""Fetchs the given object from the graph."""
return self.request(id, args)
def get_objects(self, ids, **args):
"""Fetchs al... |
def delete_request(self, user_id, request_id):
"""Deletes the Request with the given ID for the given user."""
conn = httplib.HTTPSConnection('graph.facebook.com')
url = '/%s_%s?%s' % (
request_id,
user_id,
urllib.urlencode({'access_token': sel... | """Deletes the object with the given ID from the graph."""
self.request(id, post_args={"method": "delete"}) | identifier_body |
facebook.py | def request(self, path, args=None, post_args=None):
"""Fetches the given path in the Graph API.
We translate args to a valid query string. If post_args is
given, we send a POST request to the given path with the given
arguments.
"""
args = args or {}
if self.access_token:
... | random_line_split | ||
nok.rs | use std::marker::PhantomData;
/// `Nok` contains the content of an error response from the CouchDB server.
///
/// # Summary
///
/// * `Nok` has public members instead of accessor methods because there are no
/// invariants restricting the data.
///
/// * `Nok` implements `Deserialize`.
///
/// # Remarks
///
/// Whe... | ub error: String,
pub reason: String,
#[serde(default = "PhantomData::default")]
_private_guard: PhantomData<()>,
}
| p | identifier_name |
nok.rs | use std::marker::PhantomData;
/// `Nok` contains the content of an error response from the CouchDB server.
///
/// # Summary
///
/// * `Nok` has public members instead of accessor methods because there are no
/// invariants restricting the data.
///
/// * `Nok` implements `Deserialize`.
///
/// # Remarks
///
/// Whe... | ///
/// `Nok` contains a dummy private member in order to prevent applications from
/// directly constructing a `Nok` instance. This allows new fields to be added
/// to `Nok` in future releases without it being a breaking change.
///
#[derive(Clone, Debug, Default, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd)]
p... | /// ```
///
/// # Compatibility | random_line_split |
rupture.py | # -*- coding: utf-8 -*-
'''
Rupture
version 1.4.0
build 5
'''
from bs4 import BeautifulSoup
import datetime
import requests
import socket
import pickle
import time
import ssl
from .utils import six
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.poolmanager import PoolManager
cl... | (self):
if not hasattr(self, '_soup'):
start_time = datetime.datetime.now()
from_encoding = None if self.encoding == 'utf-8' else self.encoding
if isinstance(self.text, six.text_type):
from_encoding = None # Prevent UserWarning
... | get_soup | identifier_name |
rupture.py | # -*- coding: utf-8 -*-
'''
Rupture
version 1.4.0
build 5
'''
from bs4 import BeautifulSoup
import datetime
import requests
import socket
import pickle
import time
import ssl
from .utils import six
from requests.adapters import HTTPAdapter | class Rupture(object):
parser = None # None or html.parser or lxml
encoding = None
def __init__(self, proxies=None, parser='html.parser', timeout=None, headers=None):
self.session = requests.Session()
if headers:
self.session.headers.update(headers)
self.proxies = pr... | from requests.packages.urllib3.poolmanager import PoolManager
| random_line_split |
rupture.py | # -*- coding: utf-8 -*-
'''
Rupture
version 1.4.0
build 5
'''
from bs4 import BeautifulSoup
import datetime
import requests
import socket
import pickle
import time
import ssl
from .utils import six
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.poolmanager import PoolManager
cl... |
return self._soup
def get__repr__(self):
if hasattr(self, 'text'):
return '<Response [%s]: %s>' % (self.status_code, self.text)
return '<Response [%s]>' % (self.status_code)
obj.__class__.parser = parser
obj.__class__.soup = property(g... | import lxml
lxml.etree.clear_error_log() | conditional_block |
rupture.py | # -*- coding: utf-8 -*-
'''
Rupture
version 1.4.0
build 5
'''
from bs4 import BeautifulSoup
import datetime
import requests
import socket
import pickle
import time
import ssl
from .utils import six
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.poolmanager import PoolManager
cl... |
def _wrap_response(self, obj, parser):
def get_soup(self):
if not hasattr(self, '_soup'):
start_time = datetime.datetime.now()
from_encoding = None if self.encoding == 'utf-8' else self.encoding
if isinstance(self.text, six.text_type):
... | self.session = requests.Session()
if headers:
self.session.headers.update(headers)
self.proxies = proxies
self.parser = parser
self.timeout = timeout | identifier_body |
helloworld.rs | extern crate redis;
use std::thread;
use redis::{RedisResult, Value as RedisValue, Commands};
fn main() | let connection = client.get_connection().expect("Couldn't open connection");
let thread_handle = thread::spawn(move || {
for _ in 0..10 {
let msgs = [
format!("message 1 from producer {}", consumer_num),
format!("message 2 from produce... | {
// connect to local host, default port
let queue_name = "my_queue";
let get_timeout = 5;
let get_count = 2;
let client = redis::Client::open("redis://127.0.0.1:9797/").unwrap();
let mut thread_handles = Vec::new();
let connection = client.get_connection().expect("Couldn't open connection")... | identifier_body |
helloworld.rs | extern crate redis;
use std::thread;
use redis::{RedisResult, Value as RedisValue, Commands};
fn | () {
// connect to local host, default port
let queue_name = "my_queue";
let get_timeout = 5;
let get_count = 2;
let client = redis::Client::open("redis://127.0.0.1:9797/").unwrap();
let mut thread_handles = Vec::new();
let connection = client.get_connection().expect("Couldn't open connectio... | main | identifier_name |
helloworld.rs | extern crate redis;
use std::thread;
use redis::{RedisResult, Value as RedisValue, Commands};
fn main() {
// connect to local host, default port
let queue_name = "my_queue";
let get_timeout = 5;
let get_count = 2;
let client = redis::Client::open("redis://127.0.0.1:9797/").unwrap();
let mut th... | let maybe_result: RedisResult<Vec<Vec<RedisValue>>> =
redis::cmd("HMGET")
.arg(queue_name).arg(channel_name).arg(get_count).arg(get_timeout)
.query(&connection);
let result = match maybe_result {
Err(_) => m... | let thread_handle = thread::spawn(move || {
loop { | random_line_split |
get-solr-download-url.py | #!/usr/bin/env python
# encoding: utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
import sys
import requests
# Try to import urljoin from the Python 3 reorganized stdlib first:
try:
from urllib.parse import urljoin
except ImportError:
from urlparse import urljoin
i... | if len(sys.argv) != 2:
print('Usage: %s SOLR_VERSION' % sys.argv[0], file=sys.stderr)
sys.exit(1)
solr_version = sys.argv[1]
tarball = 'solr-{0}.tgz'.format(solr_version)
dist_path = 'lucene/solr/{0}/{1}'.format(solr_version, tarball)
download_url = urljoin('http://archive.apache.org/d... | conditional_block | |
get-solr-download-url.py | #!/usr/bin/env python
# encoding: utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
import sys
import requests
# Try to import urljoin from the Python 3 reorganized stdlib first:
try:
from urllib.parse import urljoin
except ImportError:
from urlparse import urljoin
i... |
print(download_url) | random_line_split | |
PreferencesStore.js | /*
* Copyright (C) 2015 Actor LLC. <https://actor.im>
*/
import { ReduceStore } from 'flux/utils';
import Dispatcher from '../dispatcher/ActorAppDispatcher';
import { ActionTypes, AsyncActionStates, PreferencesTabTypes } from '../constants/ActorAppConstants';
import ActorClient from '../utils/ActorClient';
class P... |
getTerminateState() {
return this.getState().terminateState;
}
}
export default new PreferencesStore(Dispatcher);
| {
return this.getState().currentTab;
} | identifier_body |
PreferencesStore.js | /*
* Copyright (C) 2015 Actor LLC. <https://actor.im>
*/
import { ReduceStore } from 'flux/utils';
import Dispatcher from '../dispatcher/ActorAppDispatcher';
import { ActionTypes, AsyncActionStates, PreferencesTabTypes } from '../constants/ActorAppConstants';
import ActorClient from '../utils/ActorClient';
class P... | () {
return ActorClient.isSoundEffectsEnabled();
}
isShowNotificationsTextEnabled() {
return ActorClient.isShowNotificationsTextEnabled();
}
isAnimationAutoPlayEnabled() {
return ActorClient.isAnimationAutoPlayEnabled();
}
getSessions() {
return this.getState().sessions;
}
getCurrent... | isSoundEffectsEnabled | identifier_name |
PreferencesStore.js | /*
* Copyright (C) 2015 Actor LLC. <https://actor.im>
*/
import { ReduceStore } from 'flux/utils';
import Dispatcher from '../dispatcher/ActorAppDispatcher';
import { ActionTypes, AsyncActionStates, PreferencesTabTypes } from '../constants/ActorAppConstants';
import ActorClient from '../utils/ActorClient';
class P... |
case ActionTypes.PREFERENCES_SESSION_TERMINATE:
state.terminateState[action.id] = AsyncActionStates.PROCESSING;
return state;
case ActionTypes.PREFERENCES_SESSION_TERMINATE_SUCCESS:
delete state.terminateState[action.id];
return state;
case ActionTypes.PREFERENCES_SESS... | currentTab: action.tab
} | random_line_split |
module.ts | import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { ColorPickerModule } from 'angular2-color-picker... | { } | Module | identifier_name |
module.ts | import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { ColorPickerModule } from 'angular2-color-picker... | // services
import { IpcRendererService } from './services/ipcRender';
import { StorageService } from './services/storage';
import { ComponentService } from './services/componentService';
// directives
import { WebviewDirective } from './directives/webview';
// routes
import { appRoutes } from './routes';
@NgModule(... | // pipes
import { SVGPipe } from './pipes/SVGPipe';
| random_line_split |
test_md5mesh.rs | use implement::file::md5common;
use implement::file::md5mesh;
#[test]
fn test_parse_md5mesh(){
let file_content = md5common::file_open( "core/asset/md5/qshambler.md5mesh" ).expect("file open invalid");
println!("file content length: {}", file_content.len() );
let _mesh_root = md5mesh::parse( &file_content ... | // for j in i._weights.iter() {
// println!("weight index: {}, joint index: {}, weight bias: {}, pos: {:?}", j._index, j._joint_index, j._weight_bias, j._pos );
// }
// println!( "}}" );
// }
} | // }
// println!( "numweights: {}", i._numweights ); | random_line_split |
test_md5mesh.rs | use implement::file::md5common;
use implement::file::md5mesh;
#[test]
fn test_parse_md5mesh() | // println!( "numweights: {}", i._numweights );
// for j in i._weights.iter() {
// println!("weight index: {}, joint index: {}, weight bias: {}, pos: {:?}", j._index, j._joint_index, j._weight_bias, j._pos );
// }
// println!( "}}" );
// }
}
| {
let file_content = md5common::file_open( "core/asset/md5/qshambler.md5mesh" ).expect("file open invalid");
println!("file content length: {}", file_content.len() );
let _mesh_root = md5mesh::parse( &file_content ).expect("parse unsuccessful");
// for i in mesh_root._joints.iter() {
// println... | identifier_body |
test_md5mesh.rs | use implement::file::md5common;
use implement::file::md5mesh;
#[test]
fn | (){
let file_content = md5common::file_open( "core/asset/md5/qshambler.md5mesh" ).expect("file open invalid");
println!("file content length: {}", file_content.len() );
let _mesh_root = md5mesh::parse( &file_content ).expect("parse unsuccessful");
// for i in mesh_root._joints.iter() {
// print... | test_parse_md5mesh | identifier_name |
m_1_2_01.rs | // M_1_2_01
//
// Generative Gestaltung – Creative Coding im Web
// ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018
// Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni
// with contributions by Joey Lee and Niels Poldervaart
// Copyright 2018
//
// http://www.generative-gestaltung.de... | }
} | fn key_pressed(app: &App, _model: &mut Model, key: Key) {
if key == Key::S {
app.main_window()
.capture_frame(app.exe_name().unwrap() + ".png"); | random_line_split |
m_1_2_01.rs | // M_1_2_01
//
// Generative Gestaltung – Creative Coding im Web
// ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018
// Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni
// with contributions by Joey Lee and Niels Poldervaart
// Copyright 2018
//
// http://www.generative-gestaltung.de... | app.main_window()
.capture_frame(app.exe_name().unwrap() + ".png");
}
}
| conditional_block | |
m_1_2_01.rs | // M_1_2_01
//
// Generative Gestaltung – Creative Coding im Web
// ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018
// Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni
// with contributions by Joey Lee and Niels Poldervaart
// Copyright 2018
//
// http://www.generative-gestaltung.de... | p: &App, _model: &mut Model, key: Key) {
if key == Key::S {
app.main_window()
.capture_frame(app.exe_name().unwrap() + ".png");
}
}
| _pressed(ap | identifier_name |
m_1_2_01.rs | // M_1_2_01
//
// Generative Gestaltung – Creative Coding im Web
// ISBN: 978-3-87439-902-9, First Edition, Hermann Schmidt, Mainz, 2018
// Benedikt Groß, Hartmut Bohnacker, Julia Laub, Claudius Lazzeroni
// with contributions by Joey Lee and Niels Poldervaart
// Copyright 2018
//
// http://www.generative-gestaltung.de... | draw.ellipse().x_y(x, y).w_h(11.0, 11.0).rgb8(0, 130, 163);
}
// Write to the window frame.
draw.to_frame(app, &frame).unwrap();
}
f
n mouse_pressed(_app: &App, model: &mut Model, _button: MouseButton) {
model.act_random_seed = (random_f32() * 100000.0) as u64;
}
fn key_pressed(app: &App, _mo... | let draw = app.draw();
let win = app.window_rect();
draw.background().color(WHITE);
let fader_x = map_range(app.mouse.x, win.left(), win.right(), 0.0, 1.0);
let mut rng = StdRng::seed_from_u64(model.act_random_seed);
let angle = deg_to_rad(360.0 / model.count as f32);
for i in 0..model.co... | identifier_body |
stream.rs | Cst) { return Err(t) }
match self.do_send(Data(t)) {
UpSuccess | UpDisconnected => {},
UpWoke(token) => { token.signal(); }
}
Ok(())
}
pub fn | (&mut self, up: Receiver<T>) -> UpgradeResult {
// If the port has gone away, then there's no need to proceed any
// further.
if self.port_dropped.load(Ordering::SeqCst) { return UpDisconnected }
self.do_send(GoUp(up))
}
fn do_send(&mut self, t: Message<T>) -> UpgradeResult {
... | upgrade | identifier_name |
stream.rs | use thread;
use sync::atomic::{AtomicIsize, AtomicUsize, Ordering, AtomicBool};
use sync::mpsc::Receiver;
use sync::mpsc::blocking::{self, SignalToken};
use sync::mpsc::spsc_queue as spsc;
const DISCONNECTED: isize = isize::MIN;
#[cfg(test)]
const MAX_STEALS: isize = 5;
#[cfg(not(test))]
const MAX_STEALS: isize = 1 <... | use core::prelude::*;
use core::cmp;
use core::isize; | random_line_split | |
stream.rs | Cst) { return Err(t) }
match self.do_send(Data(t)) {
UpSuccess | UpDisconnected => {},
UpWoke(token) => { token.signal(); }
}
Ok(())
}
pub fn upgrade(&mut self, up: Receiver<T>) -> UpgradeResult {
// If the port has gone away, then there's no need to pro... | self.steals -= 1;
data
}
data => data,
}
}
pub fn try_recv(&mut self) -> Result<T, Failure<T>> {
match self.queue.pop() {
// If we stole some data, record to that effect (this will be
// factored into cnt later on... | {
// Optimistic preflight check (scheduling is expensive).
match self.try_recv() {
Err(Empty) => {}
data => return data,
}
// Welp, our channel has no data. Deschedule the current task and
// initiate the blocking protocol.
let (wait_token, signal... | identifier_body |
poWithReceiversDateRange.js | import '../../../../css/rpt/styles.global.css';
import styles from '../../../css/rpt/styles.css';
import React, { Component, PropTypes } from 'react';
import 'react-widgets/lib/less/react-widgets.less';
import DateTimePicker from 'react-widgets/lib/DateTimePicker';
import Multiselect from 'react-widgets/lib/Multiselect... |
var pageNoClass = classNames(
'pagination','hidden-xs', 'pull-left'
);
var dateHeader;
var dateStyle;
if(this.props.ProdRpt.openPOWithReceivers.dateHeader.valid){
dateHeader=<h3 style={{textAlign:'center'}}>{this.props.ProdRpt.poWithReceivers.dateHeader.text}</h3>
dateStyle='def... | {
runAndBackBtn =
<Row>
<Col xs={4} > </Col>
<Col xs={2}><Button onClick={()=>this.props.poWithReceivers()} bsSize="large" bsStyle="info" >Run</Button></Col>
<Col xs={1}><Button onClick={()=>this.props.setState(STATE.NOT_STARTED)} bsSize="large" bsStyle="warning">Back</Butt... | conditional_block |
poWithReceiversDateRange.js | import '../../../../css/rpt/styles.global.css';
import styles from '../../../css/rpt/styles.css';
import React, { Component, PropTypes } from 'react';
import 'react-widgets/lib/less/react-widgets.less';
import DateTimePicker from 'react-widgets/lib/DateTimePicker';
import Multiselect from 'react-widgets/lib/Multiselect... | </Col>
<Col xs={8} xsOffset={1} style={{}}>
<DateTimePicker
onChange={(name,value)=>{
this.state.test(name,this.props.ProdRpt.poWithReceivers.dateStart,this.props.ProdRpt.openPOWithReceivers.dateEnd);
this.props.setPOWithReceiver... | <Panel bsStyle={dateStyle} header={dateHeader}>
<Row>
<Col xs={1} >
<h1 style={{marginTop:0}}><Label bsStyle="primary">Start</Label></h1> | random_line_split |
poWithReceiversDateRange.js | import '../../../../css/rpt/styles.global.css';
import styles from '../../../css/rpt/styles.css';
import React, { Component, PropTypes } from 'react';
import 'react-widgets/lib/less/react-widgets.less';
import DateTimePicker from 'react-widgets/lib/DateTimePicker';
import Multiselect from 'react-widgets/lib/Multiselect... | (props) {
super(props);
this.state = {
test:this.test.bind(this)
};
if ('development'==process.env.NODE_ENV) {
}
}
test(dt,dateStart,dateEnd){
console.log(`dt: ${dt}`);
var dtStart = dateFormat(new Date(dt), "mm-dd-yyyy hh:MM:ss");
if ('development'==process.env.NODE_ENV) {
cons... | constructor | identifier_name |
sort.d.ts | /**
* @license
* Copyright Google Inc. 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 { EventEmitter } from '@angular/core';
import { SortDirection } from './sort-direction';
export interface MdSo... | * The direction to set when an MdSortable is initially sorted.
* May be overriden by the MdSortable's sort start.
*/
start: 'asc' | 'desc';
/** The sort direction of the currently active MdSortable. */
direction: SortDirection;
/**
* Whether to disable the user from clearing the sort... | /** Collection of all registered sortables that this directive manages. */
sortables: Map<string, MdSortable>;
/** The id of the most recently sorted MdSortable. */
active: string;
/** | random_line_split |
sort.d.ts | /**
* @license
* Copyright Google Inc. 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 { EventEmitter } from '@angular/core';
import { SortDirection } from './sort-direction';
export interface MdSo... | {
/** Collection of all registered sortables that this directive manages. */
sortables: Map<string, MdSortable>;
/** The id of the most recently sorted MdSortable. */
active: string;
/**
* The direction to set when an MdSortable is initially sorted.
* May be overriden by the MdSortable's ... | MdSort | identifier_name |
mockmessageevent.js | /**
* @license
* Copyright The Closure Library Authors.
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @fileoverview A simple mock class for imitating HTML5 MessageEvents.
*/
goog.setTestOnly('goog.testing.messaging.MockMessageEvent');
goog.provide('goog.testing.messaging.MockMessageEvent');
goog.require('goog... | 'use strict';
return new goog.events.BrowserEvent(
new goog.testing.messaging.MockMessageEvent(
data, opt_origin, opt_lastEventId, opt_source, opt_ports));
}; | */
goog.testing.messaging.MockMessageEvent.wrap = function(
data, opt_origin, opt_lastEventId, opt_source, opt_ports) { | random_line_split |
setup.py | #!/usr/bin/env python3
import sys
import os
from distutils.core import run_setup
# build_ext is subclassed, so we import it with a _ to avoid a collision
from distutils.command.build_ext import build_ext as _build_ext
from setuptools import setup, Extension, find_packages
PKG_NAME = "piqueserver"
extra_args = sys.a... |
self.extensions = cythonize(self.extensions, compiler_directives=compiler_directives)
_build_ext.run(self)
run_setup(os.path.join(os.getcwd(), "setup.py"),
['build_py'] + extra_args)
setup(
name=PKG_NAME,
packages=find_packages(exclude=("tests", "tests.*")),
v... | compiler_directives['linetrace'] = True | conditional_block |
setup.py | #!/usr/bin/env python3
import sys
import os
from distutils.core import run_setup
# build_ext is subclassed, so we import it with a _ to avoid a collision
from distutils.command.build_ext import build_ext as _build_ext
from setuptools import setup, Extension, find_packages
PKG_NAME = "piqueserver"
extra_args = sys.a... | (self):
from Cython.Build import cythonize
if USE_ASAN:
from Cython.Compiler import Options
# make asan/valgrind's memory leak results better
Options.generate_cleanup_code = True
compiler_directives = {'language_level': 3, 'embedsignature': True}
if... | run | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.