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 |
|---|---|---|---|---|
check_txn_status.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use txn_types::{Key, Lock, TimeStamp, WriteType};
use crate::storage::{
mvcc::txn::MissingLockAction,
mvcc::{
metrics::MVCC_CHECK_TXN_STATUS_COUNTER_VEC, ErrorInner, LockType, MvccTxn, ReleasedLock,
Result, TxnCommitRecord,
... | txn.put_lock(primary_key, &lock);
MVCC_CHECK_TXN_STATUS_COUNTER_VEC.update_ts.inc();
}
// As long as the primary lock's min_commit_ts > caller_start_ts, locks belong to the same transaction
// can't block reading. Return MinCommitTsPushed result to the client to let it bypass locks.
let... | if lock.min_commit_ts < current_ts {
lock.min_commit_ts = current_ts;
}
| random_line_split |
check_txn_status.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use txn_types::{Key, Lock, TimeStamp, WriteType};
use crate::storage::{
mvcc::txn::MissingLockAction,
mvcc::{
metrics::MVCC_CHECK_TXN_STATUS_COUNTER_VEC, ErrorInner, LockType, MvccTxn, ReleasedLock,
Result, TxnCommitRecord,
... | }
.into());
}
if resolving_pessimistic_lock {
return Ok(TxnStatus::LockNotExistDoNothing);
}
let ts = txn.start_ts;
// collapse previous rollback if exist.
if txn.collapse_rollback {
... | {
MVCC_CHECK_TXN_STATUS_COUNTER_VEC.get_commit_info.inc();
match txn
.reader
.get_txn_commit_record(&primary_key, txn.start_ts)?
{
TxnCommitRecord::SingleRecord { commit_ts, write } => {
if write.write_type == WriteType::Rollback {
Ok(TxnStatus::RolledBac... | identifier_body |
check_txn_status.rs | // Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
use txn_types::{Key, Lock, TimeStamp, WriteType};
use crate::storage::{
mvcc::txn::MissingLockAction,
mvcc::{
metrics::MVCC_CHECK_TXN_STATUS_COUNTER_VEC, ErrorInner, LockType, MvccTxn, ReleasedLock,
Result, TxnCommitRecord,
... |
let ts = txn.start_ts;
// collapse previous rollback if exist.
if txn.collapse_rollback {
txn.collapse_prev_rollback(primary_key.clone())?;
}
if let (Some(l), None) = (mismatch_lock, overlapped_write.as_ref()) {
txn.mark_rol... | {
return Ok(TxnStatus::LockNotExistDoNothing);
} | conditional_block |
git.d.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | */
export interface LogOptions {
/** Max number of log entries to retrieve. If not specified, the default is 32. */
readonly maxEntries?: number;
}
export interface Repository {
readonly rootUri: Uri;
readonly inputBox: InputBox;
readonly state: RepositoryState;
readonly ui: RepositoryUIState;
getConfigs(): ... | * Log options. | random_line_split |
test.py | #!/usr/bin/env python3
'''Test for DDNS forwarding'''
from dnstest.test import Test
t = Test()
master = t.server("knot")
slave = t.server("knot")
zone = t.zone("example.com.")
t.link(zone, master, slave, ddns=True)
t.start() | update = slave.update(zone)
update.add("forwarded.example.com.", 1, "TXT", "forwarded")
update.send("NOERROR")
resp = master.dig("forwarded.example.com.", "TXT")
resp.check("forwarded")
slave.zones_wait(zone, seri)
t.xfr_diff(master, slave, zone)
# NAME out of zone
update = slave.update(zone)
update.add("forwarded.", ... |
master.zones_wait(zone)
seri = slave.zones_wait(zone)
# OK | random_line_split |
tree-view-demo.ts | import {Component, NgFor,NgIf} from 'angular2/angular2';
import {TreeView} from './tree-view';
import {Directory} from './directory';
@Component({
template: '<h1>Recursive TreeView</h1><tree-view [directories]="directories"></tree-view>' +
' <h4><a href="http://www.syntaxsuccess.com/viewarticle/recurs... | }
} | random_line_split | |
tree-view-demo.ts | import {Component, NgFor,NgIf} from 'angular2/angular2';
import {TreeView} from './tree-view';
import {Directory} from './directory';
@Component({
template: '<h1>Recursive TreeView</h1><tree-view [directories]="directories"></tree-view>' +
' <h4><a href="http://www.syntaxsuccess.com/viewarticle/recurs... | {
directories: Array<Directory>;
constructor(){
this.loadDirectories();
}
loadDirectories(){
const fall2014 = new Directory('Fall 2014',[],['image1.jpg','image2.jpg','image3.jpg']);
const summer2014 = new Directory('Summer 2014',[],['image10.jpg','image20.jpg','image30.jpg'])... | TreeViewDemo | identifier_name |
tree-view-demo.ts | import {Component, NgFor,NgIf} from 'angular2/angular2';
import {TreeView} from './tree-view';
import {Directory} from './directory';
@Component({
template: '<h1>Recursive TreeView</h1><tree-view [directories]="directories"></tree-view>' +
' <h4><a href="http://www.syntaxsuccess.com/viewarticle/recurs... |
} | {
const fall2014 = new Directory('Fall 2014',[],['image1.jpg','image2.jpg','image3.jpg']);
const summer2014 = new Directory('Summer 2014',[],['image10.jpg','image20.jpg','image30.jpg']);
const pics = new Directory('Pictures',[summer2014,fall2014],[]);
const music = new Directory('Music... | identifier_body |
app.js | (function() {
'use strict';
angular.module('ShoppingListCheckOff', [])
.controller('ToBuyController', ToBuyController)
.controller('AlreadyBoughtController', AlreadyBoughtController)
.service('ShoppingListCheckOffService', ShoppingListCheckOffService);
ToBuyController.$inject = ['ShoppingListCheckOffS... | }
}
})(); |
service.changeItem = function(index) {
boughtItems.push(toBuyItems[index]);
toBuyItems.splice(index, 1);
| random_line_split |
app.js | (function() {
'use strict';
angular.module('ShoppingListCheckOff', [])
.controller('ToBuyController', ToBuyController)
.controller('AlreadyBoughtController', AlreadyBoughtController)
.service('ShoppingListCheckOffService', ShoppingListCheckOffService);
ToBuyController.$inject = ['ShoppingListCheckOffS... | () {
var service = this;
var toBuyItems = [{ name: "cookies", quantity: 10 }, { name: "breads", quantity: 2 }, { name: "muffins", quantity: 3 }, { name: "steaks", quantity: 5 }, { name: "fruits", quantity: 20 }];
var boughtItems = [];
service.getToBuyItems = function() {
return toBuyItems;
};... | ShoppingListCheckOffService | identifier_name |
app.js | (function() {
'use strict';
angular.module('ShoppingListCheckOff', [])
.controller('ToBuyController', ToBuyController)
.controller('AlreadyBoughtController', AlreadyBoughtController)
.service('ShoppingListCheckOffService', ShoppingListCheckOffService);
ToBuyController.$inject = ['ShoppingListCheckOffS... |
})(); | {
var service = this;
var toBuyItems = [{ name: "cookies", quantity: 10 }, { name: "breads", quantity: 2 }, { name: "muffins", quantity: 3 }, { name: "steaks", quantity: 5 }, { name: "fruits", quantity: 20 }];
var boughtItems = [];
service.getToBuyItems = function() {
return toBuyItems;
};
... | identifier_body |
scene.rs | //! The Scene system is basically for transitioning between
//! *completely* different states that have entirely different game
//! loops and but which all share a state. It operates as a stack, with new
//! scenes getting pushed to the stack (while the old ones stay in
//! memory unchanged). Apparently this is basic... |
}
#[cfg(test)]
mod tests {
use super::*;
struct Thing {
scenes: Vec<SceneStack<u32, u32>>,
}
#[test]
fn test1() {
let x = Thing { scenes: vec![] };
}
}
| {
let current_scene = &mut **self
.scenes
.last_mut()
.expect("Tried to do input for empty scene stack");
current_scene.input(&mut self.world, event, started);
} | identifier_body |
scene.rs | //! The Scene system is basically for transitioning between
//! *completely* different states that have entirely different game
//! loops and but which all share a state. It operates as a stack, with new
//! scenes getting pushed to the stack (while the old ones stay in
//! memory unchanged). Apparently this is basic... |
}
}
// These functions must be on the SceneStack because otherwise
// if you try to get the current scene and the world to call
// update() on the current scene it causes a double-borrow. :/
pub fn update(&mut self, ctx: &mut ggez::Context) {
let next_scene = {
let cur... | {
let old_scene = self.pop();
self.push(s);
Some(old_scene)
} | conditional_block |
scene.rs | //! The Scene system is basically for transitioning between
//! *completely* different states that have entirely different game
//! loops and but which all share a state. It operates as a stack, with new
//! scenes getting pushed to the stack (while the old ones stay in
//! memory unchanged). Apparently this is basic... | pub fn push<S>(scene: S) -> Self
where
S: Scene<C, Ev> + 'static,
{
SceneSwitch::Push(Box::new(scene))
}
}
/// A stack of `Scene`'s, together with a context object.
pub struct SceneStack<C, Ev> {
pub world: C,
scenes: Vec<Box<Scene<C, Ev>>>,
}
impl<C, Ev> SceneStack<C, Ev> {
... | {
SceneSwitch::Replace(Box::new(scene))
}
/// Same as `replace()` but returns SceneSwitch::Push | random_line_split |
scene.rs | //! The Scene system is basically for transitioning between
//! *completely* different states that have entirely different game
//! loops and but which all share a state. It operates as a stack, with new
//! scenes getting pushed to the stack (while the old ones stay in
//! memory unchanged). Apparently this is basic... | (&mut self, next_scene: SceneSwitch<C, Ev>) -> Option<Box<Scene<C, Ev>>> {
match next_scene {
SceneSwitch::None => None,
SceneSwitch::Pop => {
let s = self.pop();
Some(s)
}
SceneSwitch::Push(s) => {
self.push(s);
... | switch | identifier_name |
gettext.py | # -*- coding: utf-8 -*-
"""
sphinx.builders.gettext
~~~~~~~~~~~~~~~~~~~~~~~
The MessageCatalogBuilder class.
:copyright: Copyright 2007-2015 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from __future__ import unicode_literals
from os import path, walk
from codecs ... | tmpl_abs_path = path.join(self.app.srcdir, template_path)
for dirpath, dirs, files in walk(tmpl_abs_path):
for fn in files:
if fn.endswith('.html'):
filename = path.join(dirpath, fn)
filename = filename.replace(p... | template_files = set()
for template_path in self.config.templates_path: | random_line_split |
gettext.py | # -*- coding: utf-8 -*-
"""
sphinx.builders.gettext
~~~~~~~~~~~~~~~~~~~~~~~
The MessageCatalogBuilder class.
:copyright: Copyright 2007-2015 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from __future__ import unicode_literals
from os import path, walk
from codecs ... | (object):
"""
Origin holder for Catalog message origin.
"""
def __init__(self, source, line):
self.source = source
self.line = line
self.uid = uuid4().hex
class I18nBuilder(Builder):
"""
General i18n builder.
"""
name = 'i18n'
versioning_method = 'text'
... | MsgOrigin | identifier_name |
gettext.py | # -*- coding: utf-8 -*-
"""
sphinx.builders.gettext
~~~~~~~~~~~~~~~~~~~~~~~
The MessageCatalogBuilder class.
:copyright: Copyright 2007-2015 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from __future__ import unicode_literals
from os import path, walk
from codecs ... |
ltz = LocalTimeZone()
class MessageCatalogBuilder(I18nBuilder):
"""
Builds gettext-style message catalogs (.pot files).
"""
name = 'gettext'
def init(self):
I18nBuilder.init(self)
self.create_template_bridge()
self.templates.init(self)
def _collect_templates(self):
... | def __init__(self, *args, **kw):
super(LocalTimeZone, self).__init__(*args, **kw)
self.tzdelta = tzdelta
def utcoffset(self, dt):
return self.tzdelta
def dst(self, dt):
return timedelta(0) | identifier_body |
gettext.py | # -*- coding: utf-8 -*-
"""
sphinx.builders.gettext
~~~~~~~~~~~~~~~~~~~~~~~
The MessageCatalogBuilder class.
:copyright: Copyright 2007-2015 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from __future__ import unicode_literals
from os import path, walk
from codecs ... |
# determine tzoffset once to remain unaffected by DST change during build
timestamp = time()
tzdelta = datetime.fromtimestamp(timestamp) - \
datetime.utcfromtimestamp(timestamp)
class LocalTimeZone(tzinfo):
def __init__(self, *args, **kw):
super(LocalTimeZone, self).__init__(*args, **kw)
s... | for m in split_index_msg(typ, msg):
if typ == 'pair' and m in pairindextypes.values():
# avoid built-in translated message was incorporated
# in 'sphinx.util.nodes.process_index_entry'
continue
... | conditional_block |
base.py | #!/usr/bin/env python
# The outputManager synchronizes the output display for all the various threads
#####################
import threading
class outputStruct():
def __init__( self ):
self.id = 0
self.updateObjSem = None
self.title = ""
self.numOfInc = 0
class outputManager( threading.Thread ):
def __in... | self.isAlive = False | identifier_body | |
base.py | #!/usr/bin/env python
# The outputManager synchronizes the output display for all the various threads
#####################
import threading
class outputStruct():
def __init__( self ):
self.id = 0
self.updateObjSem = None
self.title = ""
self.numOfInc = 0
class outputManager( threading.Thread ):
def __in... | self.isAlive = False | random_line_split | |
base.py | #!/usr/bin/env python
# The outputManager synchronizes the output display for all the various threads
#####################
import threading
class outputStruct():
def __init__( self ):
self.id = 0
self.updateObjSem = None
self.title = ""
self.numOfInc = 0
class | ( threading.Thread ):
def __init__( self ):
threading.Thread.__init__(self)
self.outputObjs = dict()
self.outputListLock = threading.Lock()
# Used to assign the next id for an output object
self.nextId = 0
self.isAlive = True
def createOutputObj( self, name, numberOfIncrements ):
raise NotImp... | outputManager | identifier_name |
Tools.js | if (!type) {
return obj !== undefined;
}
if (type == 'array' && Arr.isArray(obj)) {
return true;
}
return typeof obj == type;
};
/**
* Makes a name/object map out of an array with names.
*
* @method makeMap
* @param {Array/String} items Items ... | */
var is = function (obj, type) { | random_line_split | |
Tools.js | Arr.isArray(obj)) {
return true;
}
return typeof obj == type;
};
/**
* Makes a name/object map out of an array with names.
*
* @method makeMap
* @param {Array/String} items Items to make map out of.
* @param {String} delim Optional delimiter to split string by.
... |
walk(o, f, n, s);
});
}
};
/**
* Creates a namespace on a specific object.
*
* @method createNS
* @param {String} n Namespace to create for example a.b.c.d.
* @param {Object} o Optional object to add namespace to, defaults to window.
* @return {Object} Ne... | {
return false;
} | conditional_block |
printer.py | #!/usr/bin/python
"""
@author: Manuel F Martinez <manpaz@bashlinux.com>
@organization: Bashlinux
@copyright: Copyright (c) 2012 Bashlinux
@license: GNU GPL v3
"""
import usb.core
import usb.util
import serial
import socket
from .escpos import *
from .constants import *
from .exceptions import *
class Usb(Escpos):
... |
def _raw(self, msg):
""" Print any command sent in raw format """
if isinstance(msg, str):
self.device.send(msg.encode())
else:
self.device.send(msg)
def __del__(self):
""" Close TCP connection """
self.device.close()
def close(self):
... | print("Could not open socket for %s" % self.host) | conditional_block |
printer.py | #!/usr/bin/python
"""
@author: Manuel F Martinez <manpaz@bashlinux.com>
@organization: Bashlinux
@copyright: Copyright (c) 2012 Bashlinux
@license: GNU GPL v3
"""
import usb.core
import usb.util
import serial
import socket
from .escpos import *
from .constants import *
from .exceptions import *
class Usb(Escpos):
... |
def _raw(self, msg):
""" Print any command sent in raw format """
if isinstance(msg, str):
self.device.send(msg.encode())
else:
self.device.send(msg)
def __del__(self):
""" Close TCP connection """
self.device.close()
def close(self):
... | random_line_split | |
printer.py | #!/usr/bin/python
"""
@author: Manuel F Martinez <manpaz@bashlinux.com>
@organization: Bashlinux
@copyright: Copyright (c) 2012 Bashlinux
@license: GNU GPL v3
"""
import usb.core
import usb.util
import serial
import socket
from .escpos import *
from .constants import *
from .exceptions import *
class Usb(Escpos):
... | (self, msg):
""" Print any command sent in raw format """
self.device.write(msg)
def __del__(self):
""" Close Serial interface """
if self.device is not None:
self.device.close()
class Network(Escpos):
""" Define Network printer """
def __init__(self,host,po... | _raw | identifier_name |
printer.py | #!/usr/bin/python
"""
@author: Manuel F Martinez <manpaz@bashlinux.com>
@organization: Bashlinux
@copyright: Copyright (c) 2012 Bashlinux
@license: GNU GPL v3
"""
import usb.core
import usb.util
import serial
import socket
from .escpos import *
from .constants import *
from .exceptions import *
class Usb(Escpos):
... |
def open(self):
""" Search device on USB tree and set is as escpos device """
self.device = usb.core.find(idVendor=self.idVendor, idProduct=self.idProduct)
if self.device is None:
print("Cable isn't plugged in")
check_driver = None
try:
check_driv... | """
@param idVendor : Vendor ID
@param idProduct : Product ID
@param interface : USB device interface
@param in_ep : Input end point
@param out_ep : Output end point
"""
self.idVendor = idVendor
self.idProduct = idProduct
self.interface = ... | identifier_body |
app.component.ts | import { Component } from '@angular/core';
import { AngularFire, FirebaseRef, FirebaseObjectObservable, FirebaseListObservable } from 'angularfire2';
import {Observable} from 'Rxjs';
@Component({
selector: 'my-app',
template: `<h1>My First Angular 2 App</h1>
<ul>
<li class="text" *ngFor="let item of ziaFri... |
populateDB(){
let jsonObject = {
zia:
{
name: "Zia Khan",
friends: {
"inam": true,
"zeeshan": true
}
}
... | {
this.af = af;
this.users = af.database.object('users');
this.populateDB();
this.ziaFriends = af.database.list('users/zia/friends').map(function(value: any[]){
return value.map((val) => af.database.object('users/zia/friends/' + val));
}
} | identifier_body |
app.component.ts | import { Component } from '@angular/core';
import { AngularFire, FirebaseRef, FirebaseObjectObservable, FirebaseListObservable } from 'angularfire2';
import {Observable} from 'Rxjs';
@Component({
selector: 'my-app',
template: `<h1>My First Angular 2 App</h1>
<ul>
<li class="text" *ngFor="let item of ziaFri... | (af: AngularFire) {
this.af = af;
this.users = af.database.object('users');
this.populateDB();
this.ziaFriends = af.database.list('users/zia/friends').map(function(value: any[]){
return value.map((val) => af.database.object('users/zia/friends/' + val));
}
}
populateDB(){
let json... | constructor | identifier_name |
app.component.ts | import { Component } from '@angular/core';
import { AngularFire, FirebaseRef, FirebaseObjectObservable, FirebaseListObservable } from 'angularfire2';
import {Observable} from 'Rxjs';
@Component({
selector: 'my-app',
template: `<h1>My First Angular 2 App</h1>
<ul> | })
export class AppComponent {
af: AngularFire;
users: FirebaseObjectObservable<any>;
ziaFriends: Observable<any[]>;
constructor(af: AngularFire) {
this.af = af;
this.users = af.database.object('users');
this.populateDB();
this.ziaFriends = af.database.list('users/zia/friends').map(function(val... | <li class="text" *ngFor="let item of ziaFriends | async">
{{item.$value}}
</li>
</ul>
` | random_line_split |
setup.py | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="gabriel-server",
version="2.0.2",
author="Roger Iyengar",
author_email="ri@rogeriyengar.com",
description="Server for Wearable Cognitive Assistance Applications",
long_description=lo... | "gabriel-protocol==2.0.1",
"websockets==8.1",
"pyzmq==18.1",
],
) | python_requires=">=3.6",
install_requires=[ | random_line_split |
main.js | var game = new Phaser.Game(640, 480, Phaser.CANVAS, 'Ilegal');
//INITIALIZE HERE THE CANVAS AND OTHER STUFFS LIKE DEVICE TYPE AND RESOLUTION
var Boot = function(game){};
Boot.prototype = {
preload: function() {
this.load.image('preloaderBg', 'assets/preload/loading-bg.png');
this.load.image('preloaderBar', 'asset... | if (currentState == States.GAME) {
this.physics.arcade.collide(player, semaforo, this.onTrigger, null, player);
this.physics.arcade.collide(player, car, this.onDoorHitted, null, player);
player.body.velocity.x = 0;
velocity.setTo(0);
if (game.input.keyboard.isDown(Phaser.Keyboard.D))
{
... | update: function()
{ | random_line_split |
main.js | var game = new Phaser.Game(640, 480, Phaser.CANVAS, 'Ilegal');
//INITIALIZE HERE THE CANVAS AND OTHER STUFFS LIKE DEVICE TYPE AND RESOLUTION
var Boot = function(game){};
Boot.prototype = {
preload: function() {
this.load.image('preloaderBg', 'assets/preload/loading-bg.png');
this.load.image('preloaderBar', 'asset... |
if (currentState == States.END)
{
console.log('acelerando');
player.body.velocity.x = 0;
velocity.setTo(0);
velocity.x = 1;
velocity = Phaser.Point.normalize(velocity);
velocity.x *= playerSpeed;
player.body.velocity.x = velocity.x;
}
},
onTrigger: function(player)
{
console.log('trigg... | {
this.physics.arcade.collide(player, semaforo, this.onTrigger, null, player);
this.physics.arcade.collide(player, car, this.onDoorHitted, null, player);
player.body.velocity.x = 0;
velocity.setTo(0);
if (game.input.keyboard.isDown(Phaser.Keyboard.D))
{
velocity.x = 1;
}
... | conditional_block |
gandi_live.py | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... | # "cause": "No zone set.",
# "errors": [
# {
# "location": "body",
# "name": "zone_uuid",
# "description": "\"FAKEUUID\" is not a UUID"
# }
# ]
# }
class InvalidRequestError(GandiLiveBaseError):
pass
# Examples:
# {
# "code": 409,
# "message": "Zone Testing already exist... | # Example:
# {
# "code": 400,
# "message": "zone or zone_uuid must be set",
# "object": "HTTPBadRequest", | random_line_split |
gandi_live.py | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... |
else:
message = body
return message
class GandiLiveConnection(ConnectionKey):
"""
Connection class for the Gandi Live driver
"""
responseCls = GandiLiveResponse
host = API_HOST
def add_default_headers(self, headers):
"""
Returns default headers a... | err = body["errors"][0]
message = "%s (%s in %s: %s)" % (
message,
err.get("location"),
err.get("name"),
err.get("description"),
) | conditional_block |
gandi_live.py | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... | (ConnectionKey):
"""
Connection class for the Gandi Live driver
"""
responseCls = GandiLiveResponse
host = API_HOST
def add_default_headers(self, headers):
"""
Returns default headers as a dictionary.
"""
headers["Content-Type"] = "application/json"
head... | GandiLiveConnection | identifier_name |
gandi_live.py | # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... |
# Example:
# {
# "code": 404,
# "message": "Unknown zone",
# "object": "LocalizedHTTPNotFound",
# "cause": "Not Found"
# }
class ResourceNotFoundError(GandiLiveBaseError):
pass
# Example:
# {
# "code": 400,
# "message": "zone or zone_uuid must be set",
# "object": "HTTPBadRequest",
# "cause... | pass | identifier_body |
wsgi.py | """
WSGI config for sitefinder_project project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sitefinder_project.settings.... |
django.views.debug.technical_500_response = null_technical_500_response
application = DebuggedApplication(application, evalex=True)
except ImportError:
pass
| six.reraise(exc_type, exc_value, tb) | identifier_body |
wsgi.py | """
WSGI config for sitefinder_project project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sitefinder_project.settings.... | (request, exc_type, exc_value, tb):
six.reraise(exc_type, exc_value, tb)
django.views.debug.technical_500_response = null_technical_500_response
application = DebuggedApplication(application, evalex=True)
except ImportError:
pass
| null_technical_500_response | identifier_name |
wsgi.py | """
WSGI config for sitefinder_project project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sitefinder_project.settings.... | django.views.debug.technical_500_response = null_technical_500_response
application = DebuggedApplication(application, evalex=True)
except ImportError:
pass |
def null_technical_500_response(request, exc_type, exc_value, tb):
six.reraise(exc_type, exc_value, tb)
| random_line_split |
wsgi.py | """
WSGI config for sitefinder_project project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sitefinder_project.settings.... | try:
import django.views.debug
import six
from werkzeug.debug import DebuggedApplication
def null_technical_500_response(request, exc_type, exc_value, tb):
six.reraise(exc_type, exc_value, tb)
django.views.debug.technical_500_response = null_technical_500_response
... | conditional_block | |
treiber.rs | marker: PhantomData,
}
}
/// Pop an item from the stack.
// TODO: Change this return type.
pub fn pop(&self) -> Option<Guard<T>> {
// TODO: Use `catch {}` here when it lands.
// Read the head snapshot.
let mut snapshot = Guard::maybe_new(|| unsafe {
self.head... | for i in j {
i.join().unwrap();
}
assert_eq!(*stack.pop().unwrap(), 16 * 1000 * 1001 / 2);
}
#[test]
fn sum() {
let stack = Arc::new(Treiber::<i64>::new());
let mut j = Vec | {
let stack = Arc::new(Treiber::<u64>::new());
stack.push(0);
let mut j = Vec::new();
// 16 times, we add the numbers from 0 to 1000 to the only element in the stack.
for _ in 0..16 {
let s = stack.clone();
j.push(thread::spawn(move || {
f... | identifier_body |
treiber.rs | marker: PhantomData,
}
}
/// Pop an item from the stack.
// TODO: Change this return type.
pub fn pop(&self) -> Option<Guard<T>> {
// TODO: Use `catch {}` here when it lands.
// Read the head snapshot.
let mut snapshot = Guard::maybe_new(|| unsafe {
self.head... | stack.push(200);
stack.push(44);
assert_eq!(*stack.pop().unwrap(), 44);
assert_eq!(*stack.pop().unwrap(), 200);
assert_eq!(*stack.pop().unwrap(), 1);
assert!(stack.pop().is_none());
::gc();
}
#[test]
fn simple2() {
let stack = Treiber::new()... | #[test]
fn simple1() {
let stack = Treiber::new();
stack.push(1); | random_line_split |
treiber.rs | marker: PhantomData,
}
}
/// Pop an item from the stack.
// TODO: Change this return type.
pub fn pop(&self) -> Option<Guard<T>> {
// TODO: Use `catch {}` here when it lands.
// Read the head snapshot.
let mut snapshot = Guard::maybe_new(|| unsafe {
self.head... | () {
let stack = Arc::new(Treiber::new());
let mut j = Vec::new();
for _ in 0..16 {
let s = stack.clone();
j.push(thread::spawn(move || {
for _ in 0..1_000_000 {
s.push(23);
assert_eq!(*s.pop().unwrap(), 23);
... | push_pop | identifier_name |
treiber.rs | the tail of the head.
snapshot = Guard::maybe_new(|| unsafe {
self.head.compare_and_swap(
old.as_ptr() as *mut _,
old.next as *mut Node<T>,
atomic::Ordering::Release,
).as_ref()
});
// If it... | {
s.push(*a + 1);
s.push(*b - 1);
break;
} | conditional_block | |
validator.py | has
# the client previously registered this EXACT redirect uri.
client_dict = self.oauth2_api.get_consumer(client_id)
registered_uris = client_dict['redirect_uris']
return redirect_uri in registered_uris
def get_default_redirect_uri(self, client_id, request, *args, **kwargs):
... |
request.scopes = authorization_code['scopes']
request.state = authorization_code['state']
request.user = authorization_code['authorizing_user_id']
return True
def confirm_redirect_uri(self, client_id, code, redirect_uri, client, *args, **kwargs):
# You did save the redirect... | return False | conditional_block |
validator.py | has
# the client previously registered this EXACT redirect uri.
client_dict = self.oauth2_api.get_consumer(client_id)
registered_uris = client_dict['redirect_uris']
return redirect_uri in registered_uris
def get_default_redirect_uri(self, client_id, request, *args, **kwargs):
... | (self, client_id, request, *args, **kwargs):
# Scopes a client will authorize for if none are supplied in the
# authorization request.
# TODO(garcianavalon) implement
pass
def validate_response_type(self, client_id, response_type, client, request, *args, **kwargs):
# Clients... | get_default_scopes | identifier_name |
validator.py | has
# the client previously registered this EXACT redirect uri.
client_dict = self.oauth2_api.get_consumer(client_id)
registered_uris = client_dict['redirect_uris']
return redirect_uri in registered_uris
def get_default_redirect_uri(self, client_id, request, *args, **kwargs):
... | # u'refresh_token': u'02DTsL6oWgAibU7xenvXttwG80trJC'
# }
# TODO(garcinanavalon) create a custom TokenCreator instead of
# hacking the dictionary
if getattr(request, 'client', None):
consumer_id = request.client.client_id
else:
consumer_id = ... | # u'token_type': u'Bearer',
# u'state': u'yKxWeujbz9VUBncQNrkWvVcx8EXl1w',
# u'scope': u'basic_scope', | random_line_split |
validator.py |
def validate_redirect_uri(self, client_id, redirect_uri, request, *args, **kwargs):
# Is the client allowed to use the supplied redirect_uri? i.e. has
# the client previously registered this EXACT redirect uri.
client_dict = self.oauth2_api.get_consumer(client_id)
registered_uris =... | client_dict = self.oauth2_api.get_consumer(client_id)
if client_dict:
return True
# NOTE(garcianavalon) Currently the sql driver raises an exception
# if the consumer doesnt exist so we throw the Keystone NotFound
# 404 Not Found exception instead of the OAutlib InvalidClient... | identifier_body | |
setup.py | import os
from setuptools import setup, find_packages
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-email-subscription',
url='https://github.com/MagicSolutions/django-email-subscrip... | 'Topic :: Internet :: WWW/HTTP',
],
) | 'Framework :: Django',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7', | random_line_split |
main.rs | fn main() {
use std::env;
// these seem to return the same things
for (key, value) in env::vars_os() {
println!("{:?}: {:?}", key, value);
}
for (key, value) in env::vars() {
println!("{:?}: {:?}", key, value);
}
let key = "OS";
match env::var_os(key) {
Some(val) =... | }
match env::var("SWARMIP") {
Ok(val) => println!("{:?}", val),
Err(e) => println!("couldn't interpret {}", e),
}
let data = env::var_os("OS");
println!("{:?}", data);
match env::var("SWARMIP") {
Ok(mediakraken_ip) => {
println!("{:?}", mediakraken_ip);
},
... |
match env::var("PATH") {
Ok(val) => println!("{:?}", val),
Err(e) => println!("couldn't interpret {}", e), | random_line_split |
main.rs | fn | () {
use std::env;
// these seem to return the same things
for (key, value) in env::vars_os() {
println!("{:?}: {:?}", key, value);
}
for (key, value) in env::vars() {
println!("{:?}: {:?}", key, value);
}
let key = "OS";
match env::var_os(key) {
Some(val) => print... | main | identifier_name |
main.rs | fn main() | Err(e) => println!("couldn't interpret {}", e),
}
match env::var("SWARMIP") {
Ok(val) => println!("{:?}", val),
Err(e) => println!("couldn't interpret {}", e),
}
let data = env::var_os("OS");
println!("{:?}", data);
match env::var("SWARMIP") {
Ok(mediakraken_ip) =>... | {
use std::env;
// these seem to return the same things
for (key, value) in env::vars_os() {
println!("{:?}: {:?}", key, value);
}
for (key, value) in env::vars() {
println!("{:?}: {:?}", key, value);
}
let key = "OS";
match env::var_os(key) {
Some(val) => println!... | identifier_body |
dell-wsman-get-config-catalog-spec.js | // Copyright 2017 Dell Inc. or its subsidiaries. All Rights Reserved.
/* jshint node: true */
'use strict';
describe(require('path').basename(__filename), function() {
var schemaFileName = 'dell-wsman-get-config-catalog.json';
var canonical = {
serverIP: "1.1.1.1",
serverUsername: "root",
... | var SchemaUtHelper = require('./schema-ut-helper');
new SchemaUtHelper(schemaFileName, canonical).batchTest(
positiveSetParam, negativeSetParam, positiveUnsetParam, negativeUnsetParam
);
}); | random_line_split | |
index.js | var url = require('url');
var fs = require('fs');
var postcss = require('postcss');
var path = require('canonical-path');
module.exports = postcss.plugin('postcss-cachebuster', function (opts) {
opts = opts || {};
return function (css) {
var inputFile = css.source.input.file;
css.eachDecl(function(decl... | assetPath = assetPath+'/'+assetUrl.pathname;
assetPath = path.normalize(assetPath);
// cachebuster
var mtime = fs.statSync(assetPath).mtime;
var cachebuster = mtime.getTime().toString(16);
// complete url with cachebuster
if (assetUrl.search) {
assetUrl.search = asset... | if (inputPath.host) return;
if (assetUrl.pathname.indexOf('//') == 0) return;
// resolve path
var assetPath = path.dirname(inputPath.pathname) | random_line_split |
S11.9.4_A2.4_T3.js | // Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S11.9.4_A2.4_T3;
* @section: 11.9.4;
* @assertion: First expression is evaluated first, and then second expression;
* @description: Checking with undeclarated vari... |
}
//CHECK#2
if (!((y = 1) === y)) {
$ERROR('#2: (y = 1) === y');
}
| {
$ERROR('#1.2: x === (x = 1) throw ReferenceError. Actual: ' + (e));
} | conditional_block |
S11.9.4_A2.4_T3.js | // Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S11.9.4_A2.4_T3;
* @section: 11.9.4;
* @assertion: First expression is evaluated first, and then second expression;
* @description: Checking with undeclarated vari... | catch (e) {
if ((e instanceof ReferenceError) !== true) {
$ERROR('#1.2: x === (x = 1) throw ReferenceError. Actual: ' + (e));
}
}
//CHECK#2
if (!((y = 1) === y)) {
$ERROR('#2: (y = 1) === y');
} | x === (x = 1);
$ERROR('#1.1: x === (x = 1) throw ReferenceError. Actual: ' + (x === (x = 1)));
}
| random_line_split |
kv-grid-checkbox.js | /*!
* @package yii2-grid
* @author Kartik Visweswaran <kartikv2@gmail.com>
* @copyright Copyright © Kartik Visweswaran, Krajee.com, 2014 - 2015
* @version 3.0.1
*
* Client actions for yii2-grid CheckboxColumn
*
* Author: Kartik Visweswaran
* Copyright: 2015, Kartik Visweswaran, Krajee.com
* For m... |
});
})(window.jQuery);
}; | {
$grid.find(".kv-row-select").parents("tr").removeClass(css);
} | conditional_block |
kv-grid-checkbox.js | /*!
* @package yii2-grid
* @author Kartik Visweswaran <kartikv2@gmail.com>
* @copyright Copyright © Kartik Visweswaran, Krajee.com, 2014 - 2015
* @version 3.0.1
*
* Client actions for yii2-grid CheckboxColumn
*
* Author: Kartik Visweswaran
* Copyright: 2015, Kartik Visweswaran, Krajee.com
* For m... | })(window.jQuery);
}; | $grid.find(".kv-row-select").parents("tr").removeClass(css);
}
}); | random_line_split |
workernavigator.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::WorkerNavigatorBinding;
use dom::bindings::codegen::Bindings::WorkerNavigato... | self.permissions.or_init(|| Permissions::new(&self.global()))
}
} | random_line_split | |
workernavigator.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::WorkerNavigatorBinding;
use dom::bindings::codegen::Bindings::WorkerNavigato... | (&self) -> DOMString {
navigatorinfo::AppCodeName()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-platform
fn Platform(&self) -> DOMString {
navigatorinfo::Platform()
}
// https://html.spec.whatwg.org/multipage/#dom-navigator-useragent
fn UserAgent(&self) -> DOMStr... | AppCodeName | identifier_name |
BaseCard.tsx | /*
Copyright 2020 The Matrix.org Foundation C.I.C.
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 ... |
return (
<CardContext.Provider value={{ isCard: true }}>
<div className={classNames("mx_BaseCard", className)} ref={ref} onKeyDown={onKeyDown}>
<div className="mx_BaseCard_header">
{ backButton }
{ closeButton }
{ head... | {
children = <AutoHideScrollbar>
{ children }
</AutoHideScrollbar>;
} | conditional_block |
BaseCard.tsx | /*
Copyright 2020 The Matrix.org Foundation C.I.C.
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 ... |
import AutoHideScrollbar from "../../structures/AutoHideScrollbar";
import { _t } from "../../../languageHandler";
import AccessibleButton, { ButtonEvent } from "../elements/AccessibleButton";
import RightPanelStore from '../../../stores/right-panel/RightPanelStore';
import { backLabelForPhase } from '../../../stores/... | */
import React, { forwardRef, ReactNode, KeyboardEvent, Ref } from 'react';
import classNames from 'classnames'; | random_line_split |
ImageColor.py | , blue)``
"""
try:
rgb = colormap[color]
except KeyError:
try:
# fall back on case-insensitive lookup
rgb = colormap[color.lower()]
except KeyError:
rgb = None
# found color in cache
if rgb:
if isinstance(rgb, tuple):
re... | (color, mode):
"""
Same as :py:func:`~PIL.ImageColor.getrgb`, but converts the RGB value to a
greyscale value if the mode is not color or a palette image. If the string
cannot be parsed, this function raises a :py:exc:`ValueError` exception.
.. versionadded:: 1.1.4
:param color: A color string... | getcolor | identifier_name |
ImageColor.py | , blue)``
"""
try:
rgb = colormap[color]
except KeyError:
try:
# fall back on case-insensitive lookup
rgb = colormap[color.lower()]
except KeyError:
rgb = None
# found color in cache
if rgb:
if isinstance(rgb, tuple):
re... | if m:
return (
int(m.group(1)),
int(m.group(2)),
int(m.group(3)),
int(m.group(4))
)
raise ValueError("unknown color specifier: %r" % color)
def getcolor(color, mode):
"""
Same as :py:func:`~PIL.ImageColor.getrgb`, but converts the RGB ... | )
m = re.match("rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$", color) | random_line_split |
ImageColor.py | return rgb
colormap[color] = rgb = getrgb(rgb)
return rgb
# check for known string formats
m = re.match("#\w\w\w$", color)
if m:
return (
int(color[1]*2, 16),
int(color[2]*2, 16),
int(color[3]*2, 16)
)
m = re.match("#\w\... | """
Convert a color string to an RGB tuple. If the string cannot be parsed,
this function raises a :py:exc:`ValueError` exception.
.. versionadded:: 1.1.4
:param color: A color string
:return: ``(red, green, blue)``
"""
try:
rgb = colormap[color]
except KeyError:
try:... | identifier_body | |
ImageColor.py | , blue)``
"""
try:
rgb = colormap[color]
except KeyError:
try:
# fall back on case-insensitive lookup
rgb = colormap[color.lower()]
except KeyError:
rgb = None
# found color in cache
if rgb:
if isinstance(rgb, tuple):
|
colormap[color] = rgb = getrgb(rgb)
return rgb
# check for known string formats
m = re.match("#\w\w\w$", color)
if m:
return (
int(color[1]*2, 16),
int(color[2]*2, 16),
int(color[3]*2, 16)
)
m = re.match("#\w\w\w\w\w\w$", color)
... | return rgb | conditional_block |
mem.rs | // mem.rs
// AltOSRust
//
// Created by Daniel Seitz on 12/6/16
/*
#[no_mangle]
pub unsafe extern fn __aeabi_memclr4(dest: *mut u32, mut n: isize) {
while n > 0 {
n -= 1;
*dest.offset(n) = 0;
}
}
#[no_mangle]
// TODO: Implement this, right now we don't do any reallocations, so it should never get called,
... |
for i in 0..10 {
assert_eq!(block[i], 0x0);
}
}
} | random_line_split | |
mem.rs | // mem.rs
// AltOSRust
//
// Created by Daniel Seitz on 12/6/16
/*
#[no_mangle]
pub unsafe extern fn __aeabi_memclr4(dest: *mut u32, mut n: isize) {
while n > 0 {
n -= 1;
*dest.offset(n) = 0;
}
}
#[no_mangle]
// TODO: Implement this, right now we don't do any reallocations, so it should never get called,
... | () {
let mut block: [u32; 10] = [0xAAAAAAAA; 10];
for i in 0..10 {
assert_eq!(block[i], 0xAAAAAAAA);
}
unsafe { __aeabi_memclr4(block.as_mut_ptr(), 10) };
for i in 0..10 {
assert_eq!(block[i], 0x0);
}
}
}
| memclr | identifier_name |
mem.rs | // mem.rs
// AltOSRust
//
// Created by Daniel Seitz on 12/6/16
/*
#[no_mangle]
pub unsafe extern fn __aeabi_memclr4(dest: *mut u32, mut n: isize) {
while n > 0 {
n -= 1;
*dest.offset(n) = 0;
}
}
#[no_mangle]
// TODO: Implement this, right now we don't do any reallocations, so it should never get called,
... |
}
| {
let mut block: [u32; 10] = [0xAAAAAAAA; 10];
for i in 0..10 {
assert_eq!(block[i], 0xAAAAAAAA);
}
unsafe { __aeabi_memclr4(block.as_mut_ptr(), 10) };
for i in 0..10 {
assert_eq!(block[i], 0x0);
}
} | identifier_body |
paginate.js | var URL = require('url');
var Pagination = function(request, model){
this.request = request;
this.model = model;
this.paginate = function(query, limit, sort, selected, onDataReception){
var url = URL.parse(this.request.url).pathname;
var page = this.request.param('page');
page = page === undefined ? 0 : pag... | ;
onDataReception(paginatedMembers);
});
};
}
module.exports = function(request, model){
return new Pagination(request, model);
}
| {
prevPage = parseInt(page) - 1;
paginatedMembers["prev"] = url + "?page=" + prevPage;
} | conditional_block |
paginate.js | var URL = require('url');
var Pagination = function(request, model){
this.request = request;
this.model = model;
this.paginate = function(query, limit, sort, selected, onDataReception){
var url = URL.parse(this.request.url).pathname; | //Fetched more than the limit
members.splice(limit, 1);
var paginatedMembers = {
data : members
};
if(members.length >= limit ){
nextPage = parseInt(page) + 1;
paginatedMembers["next"] = url + "?page=" + nextPage;
}
if (page >= 1) {
prevPage = parseInt(page) - 1;
paginate... | var page = this.request.param('page');
page = page === undefined ? 0 : page;
this.model.find(query).sort(sort).skip(page*limit).limit( (limit + 1) ).select( selected ).exec(function(err, members){
| random_line_split |
UserInput.py | import os
import atexit
import string
import importlib
import threading
import socket
from time import sleep
def BYTE(message):
return bytes("%s\r\n" % message, "UTF-8") | parent = None
def __init__(self, bot):
super().__init__()
self.parent = bot
self.setDaemon(True)
self.isRunning = False
self.start()
def createMessage(self, message):
temp = ""
for i in range(len(message)):
if (i != len(message) - 1):
temp += message[i] + " "
else:
temp += message[i]
... |
class UserInput(threading.Thread):
isRunning = False | random_line_split |
UserInput.py | import os
import atexit
import string
import importlib
import threading
import socket
from time import sleep
def BYTE(message):
return bytes("%s\r\n" % message, "UTF-8")
class UserInput(threading.Thread):
isRunning = False
parent = None
def __init__(self, bot):
super().__init__()
self.parent = bot
self.set... |
else:
self.parent.leave(message[1], False)
if (len(self.parent.channels) > 0):
self.parent.focusedChannel = self.parent.channels[0]
print("Left %s. Focusing on %s" % (message[1], self.parent.focusedChannel))
else:
print("No channels left.")
else:
p... | for i in range(1, len(message)):
self.parent.leave(message[i], False)
if (len(self.parent.channels) > 0):
self.parent.focusedChannel = self.parent.channels[0]
print("Left channels. Focusing on %s" % self.parent.focusedChannel)
else:
print("No channels left.") | conditional_block |
UserInput.py | import os
import atexit
import string
import importlib
import threading
import socket
from time import sleep
def BYTE(message):
return bytes("%s\r\n" % message, "UTF-8")
class UserInput(threading.Thread):
isRunning = False
parent = None
def __init__(self, bot):
super().__init__()
self.parent = bot
self.set... | (self):
self.isRunning = True
while (self.isRunning):
try:
message = input()
message = message.split(" ")
if (message[0] != ""):
if (message[0] == "/r" or message[0] == "/reload"):
self.parent.reloadAll()
elif (message[0] == "/q" or message[0] == "/quit"):
print("Quitting.")
... | run | identifier_name |
UserInput.py | import os
import atexit
import string
import importlib
import threading
import socket
from time import sleep
def BYTE(message):
return bytes("%s\r\n" % message, "UTF-8")
class UserInput(threading.Thread):
isRunning = False
parent = None
def __init__(self, bot):
|
def createMessage(self, message):
temp = ""
for i in range(len(message)):
if (i != len(message) - 1):
temp += message[i] + " "
else:
temp += message[i]
return temp
def run(self):
self.isRunning = True
while (self.isRunning):
try:
message = input()
message = message.split(" ")
... | super().__init__()
self.parent = bot
self.setDaemon(True)
self.isRunning = False
self.start() | identifier_body |
process_partial_name.js | this["JST"] = this["JST"] || {};
Handlebars.registerPartial("partial", Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
this.compilerInfo = [3,'>= 1.0.0-rc.4'];
helpers = helpers || Handlebars.helpers; data = data || {};
return "<span>Canada</span>";
}));
this["JST"]["test/fixtures/... | if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "</p>";
return buffer;
}); | random_line_split | |
process_partial_name.js | this["JST"] = this["JST"] || {};
Handlebars.registerPartial("partial", Handlebars.template(function (Handlebars,depth0,helpers,partials,data) {
this.compilerInfo = [3,'>= 1.0.0-rc.4'];
helpers = helpers || Handlebars.helpers; data = data || {};
return "<span>Canada</span>";
}));
this["JST"]["test/fixtures/... |
buffer += escapeExpression(stack1)
+ ". I live in ";
stack1 = self.invokePartial(partials.partial, 'partial', depth0, helpers, partials, data);
if(stack1 || stack1 === 0) { buffer += stack1; }
buffer += "</p>";
return buffer;
}); | { stack1 = depth0.name; stack1 = typeof stack1 === functionType ? stack1.apply(depth0) : stack1; } | conditional_block |
journal-entry.model.ts | /**
* Copyright 2017 The Mifos Initiative.
*
* 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 agr... | } | random_line_split | |
test_auth.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
libG(oogle)Reader
Copyright (C) 2010 Matt Behrens <askedrelic@gmail.com> http://asktherelic.com
Python library for working with the unofficial Google Reader API.
Unit tests for oauth and ClientAuthMethod in libgreader.
"""
try:
import unittest2 as unittest
exc... | response1 = br.submit()
br.select_form(nr=0)
response2 = br.submit()
except Exception as e:
#watch for 40X exception on trying to load redirect page
pass
callback_url = br.geturl()
# split off the token in hackish fashion
return callback_url.split('code=')[1]
def... | br.open(url)
br.select_form(nr=0)
br["Email"] = username
br["Passwd"] = password
try: | random_line_split |
test_auth.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
libG(oogle)Reader
Copyright (C) 2010 Matt Behrens <askedrelic@gmail.com> http://asktherelic.com
Python library for working with the unofficial Google Reader API.
Unit tests for oauth and ClientAuthMethod in libgreader.
"""
try:
import unittest2 as unittest
exc... | (url):
#general process is:
# 1. assume user isn't logged in, so get redirected to google accounts
# login page. login using test account credentials
# 2. redirected back to oauth approval page. br.submit() should choose the
# first submit on that page, which is the "Accept" button
br = mechaniz... | automated_oauth_approval | identifier_name |
test_auth.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
libG(oogle)Reader
Copyright (C) 2010 Matt Behrens <askedrelic@gmail.com> http://asktherelic.com
Python library for working with the unofficial Google Reader API.
Unit tests for oauth and ClientAuthMethod in libgreader.
"""
try:
import unittest2 as unittest
exc... | unittest.main() | conditional_block | |
test_auth.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
libG(oogle)Reader
Copyright (C) 2010 Matt Behrens <askedrelic@gmail.com> http://asktherelic.com
Python library for working with the unofficial Google Reader API.
Unit tests for oauth and ClientAuthMethod in libgreader.
"""
try:
import unittest2 as unittest
exc... |
def test_full_auth_process_without_callback(self):
auth = OAuthMethod(oauth_key, oauth_secret)
auth.setRequestToken()
auth_url = auth.buildAuthUrl()
response = automated_oauth_approval(auth_url)
auth.setAccessToken()
reader = GoogleReader(auth)
info = reade... | auth = OAuthMethod(oauth_key, oauth_secret)
token, token_secret = auth.setAndGetRequestToken()
url = auth.buildAuthUrl()
response = automated_oauth_approval(url)
self.assertNotEqual(-1,response.get_data().find('You have successfully granted')) | identifier_body |
test_handler_locale.py | # Copyright (C) 2013 Hewlett-Packard Development Company, L.P.
#
# Author: Juerg Haefliger <juerg.haefliger@hp.com>
#
# Based on test_handler_set_hostname.py
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3, as
# ... | (self, distro):
self.patchUtils(self.new_root)
paths = helpers.Paths({})
cls = distros.fetch(distro)
d = cls(distro, {}, paths)
ds = DataSourceNoCloud.DataSourceNoCloud({}, d, paths)
cc = cloud.Cloud(ds, paths, {}, d, None)
return cc
def test_set_locale_sles... | _get_cloud | identifier_name |
test_handler_locale.py | # Copyright (C) 2013 Hewlett-Packard Development Company, L.P.
#
# Author: Juerg Haefliger <juerg.haefliger@hp.com>
#
# Based on test_handler_set_hostname.py
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3, as
# ... |
def _get_cloud(self, distro):
self.patchUtils(self.new_root)
paths = helpers.Paths({})
cls = distros.fetch(distro)
d = cls(distro, {}, paths)
ds = DataSourceNoCloud.DataSourceNoCloud({}, d, paths)
cc = cloud.Cloud(ds, paths, {}, d, None)
return cc
def ... | super(TestLocale, self).setUp()
self.new_root = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, self.new_root) | identifier_body |
test_handler_locale.py | # Copyright (C) 2013 Hewlett-Packard Development Company, L.P.
#
# Author: Juerg Haefliger <juerg.haefliger@hp.com>
# | # it under the terms of the GNU General Public License version 3, as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Se... | # Based on test_handler_set_hostname.py
#
# This program is free software: you can redistribute it and/or modify | random_line_split |
test-main.js | var tests = [];
for (var file in window.__karma__.files) {
if (/spec\//.test(file)) {
tests.push(file);
}
}
requirejs.config({
baseUrl: '/base/src',
paths: {
jquery: 'core/js/libraries/jquery',
underscore: 'core/js/libraries/underscore',
backbone: 'core/js/libraries/back... | shim: {
jquery: [],
backbone: {
deps: [
'underscore',
'jquery'
],
exports: 'Backbone'
},
underscore: {
exports: '_'
},
handlebars: {
exports: 'Handlebars'
}
},
... | spec: '../test/spec'
}, | random_line_split |
test-main.js | var tests = [];
for (var file in window.__karma__.files) {
if (/spec\//.test(file)) |
}
requirejs.config({
baseUrl: '/base/src',
paths: {
jquery: 'core/js/libraries/jquery',
underscore: 'core/js/libraries/underscore',
backbone: 'core/js/libraries/backbone',
modernizr: 'core/js/libraries/modernizr',
handlebars: 'core/js/libraries/handlebars',
imag... | {
tests.push(file);
} | conditional_block |
struct_with_packing.rs | /* automatically generated by rust-bindgen */
#![allow(
dead_code,
non_snake_case, | non_camel_case_types,
non_upper_case_globals
)]
#[repr(C, packed)]
#[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)]
pub struct a {
pub b: ::std::os::raw::c_char,
pub c: ::std::os::raw::c_short,
}
#[test]
fn bindgen_test_layout_a() {
assert_eq!(
::std::mem::size_of::<a>(),
... | random_line_split | |
struct_with_packing.rs | /* automatically generated by rust-bindgen */
#![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C, packed)]
#[derive(Debug, Default, Copy, Clone, Hash, PartialEq, Eq)]
pub struct | {
pub b: ::std::os::raw::c_char,
pub c: ::std::os::raw::c_short,
}
#[test]
fn bindgen_test_layout_a() {
assert_eq!(
::std::mem::size_of::<a>(),
3usize,
concat!("Size of: ", stringify!(a))
);
assert_eq!(
::std::mem::align_of::<a>(),
1usize,
concat!("Al... | a | identifier_name |
logf32.rs | #![feature(core, core_intrinsics, core_float)]
extern crate core;
#[cfg(test)]
mod tests {
use core::intrinsics::logf32;
use core::num::Float;
use core::f32;
use core::f32::consts::E;
// pub fn logf32(x: f32) -> f32;
#[test]
fn logf32_test1() {
let x: f32 = f32::nan();
let result: f32... |
#[test]
fn logf32_test4() {
let x: f32 = 1.0;
let result: f32 = unsafe { logf32(x) };
assert_eq!(result, 0.0);
}
#[test]
fn logf32_test5() {
let x: f32 = E;
let result: f32 = unsafe { logf32(x) };
assert_eq!(result, 0.99999994);
}
}
| {
let x: f32 = f32::neg_infinity();
let result: f32 = unsafe { logf32(x) };
assert_eq!(result.is_nan(), true);
} | identifier_body |
logf32.rs | #![feature(core, core_intrinsics, core_float)]
extern crate core;
#[cfg(test)]
mod tests {
use core::intrinsics::logf32;
use core::num::Float;
use core::f32;
use core::f32::consts::E;
// pub fn logf32(x: f32) -> f32;
#[test]
fn logf32_test1() {
let x: f32 = f32::nan();
let result: f32... | () {
let x: f32 = E;
let result: f32 = unsafe { logf32(x) };
assert_eq!(result, 0.99999994);
}
}
| logf32_test5 | identifier_name |
logf32.rs | #![feature(core, core_intrinsics, core_float)]
extern crate core;
#[cfg(test)]
mod tests {
use core::intrinsics::logf32;
use core::num::Float;
use core::f32;
use core::f32::consts::E;
// pub fn logf32(x: f32) -> f32;
#[test]
fn logf32_test1() {
let x: f32 = f32::nan();
let result: f32... |
#[test]
fn logf32_test3() {
let x: f32 = f32::neg_infinity();
let result: f32 = unsafe { logf32(x) };
assert_eq!(result.is_nan(), true);
}
#[test]
fn logf32_test4() {
let x: f32 = 1.0;
let result: f32 = unsafe { logf32(x) };
assert_eq!(result, 0.0);
}
#[test]
fn logf32_test5()... | let x: f32 = f32::infinity();
let result: f32 = unsafe { logf32(x) };
assert_eq!(result, f32::infinity());
} | random_line_split |
Matrix4.d.ts | import { Vector3 } from './Vector3';
import { Euler } from './Euler';
import { Quaternion } from './Quaternion';
import { BufferAttribute } from './../core/BufferAttribute';
import { Matrix } from './Matrix3';
/**
* A 4x4 Matrix.
*
* @example
* // Simple rig for rotating around 3 axes
* var m = new THREE.Matrix4()... | implements Matrix {
constructor();
/**
* Float32Array with matrix values.
*/
elements: Float32Array;
/**
* Sets all fields of this matrix.
*/
set(
n11: number,
n12: number,
n13: number,
n14: number,
n21: number,
n22: number,
n23: number,
n24: number,
n31: num... | Matrix4 | identifier_name |
Matrix4.d.ts | import { Vector3 } from './Vector3';
import { Euler } from './Euler';
import { Quaternion } from './Quaternion';
import { BufferAttribute } from './../core/BufferAttribute';
import { Matrix } from './Matrix3';
/**
* A 4x4 Matrix.
*
* @example
* // Simple rig for rotating around 3 axes
* var m = new THREE.Matrix4()... | applyToBufferAttribute(attribute: BufferAttribute): BufferAttribute;
/**
* Computes determinant of this matrix.
* Based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
*/
determinant(): number;
/**
* Transposes this matrix.
*/
transpose(): Matrix4;
/... | length?: number
): BufferAttribute;
| random_line_split |
beaglebone-black.py | #
# Get the pin which correlates with a given purpose.
#
# @param char array purpose
# The purpose to search by.
# @return int
# A pin which can be used for the given purpose.
#
def getPin(purpose):
purpose_collection = {
"i2c-data": 20
"i2c-clock": 19
"adc": 39
"adc0": 39
"adc-0": 39
... | "spi-clock": 31
}
if purpose in purpose_collection:
return purpose_collection[purpose]
else
return -1 | "spi-master-in-slave-out": 29 | random_line_split |
beaglebone-black.py | #
# Get the pin which correlates with a given purpose.
#
# @param char array purpose
# The purpose to search by.
# @return int
# A pin which can be used for the given purpose.
#
def getPin(purpose):
purpose_collection = {
"i2c-data": 20
"i2c-clock": 19
"adc": 39
"adc0": 39
"adc-0": 39
... |
else
return -1
| return purpose_collection[purpose] | conditional_block |
beaglebone-black.py | #
# Get the pin which correlates with a given purpose.
#
# @param char array purpose
# The purpose to search by.
# @return int
# A pin which can be used for the given purpose.
#
def getPin(purpose):
purpose_collection = {
"i2c-data": 20
"i2c-clock": |
}
if purpose in purpose_collection:
return purpose_collection[purpose]
else
return -1
| 19
"adc": 39
"adc0": 39
"adc-0": 39
"one-wire-data": 40
"adc1": 40
"adc-1": 40
"spi-slave-select": 28
"spi-master-out-slave-in": 30
"spi-master-in-slave-out": 29
"spi-clock": 31 | identifier_body |
beaglebone-black.py | #
# Get the pin which correlates with a given purpose.
#
# @param char array purpose
# The purpose to search by.
# @return int
# A pin which can be used for the given purpose.
#
def | (purpose):
purpose_collection = {
"i2c-data": 20
"i2c-clock": 19
"adc": 39
"adc0": 39
"adc-0": 39
"one-wire-data": 40
"adc1": 40
"adc-1": 40
"spi-slave-select": 28
"spi-master-out-slave-in": 30
"spi-master-in-slave-out": 29
"spi-clock": 31
}
if purpose i... | getPin | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.