file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
token.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import mysql.connector
#from token find userId
#return 0 for error
def | (userToken, cnx):
userQuery = 'SELECT user_id FROM user_token WHERE user_token = %s'
try:
userCursor = cnx.cursor()
userCursor.execute(userQuery, (userToken, ))
return userCursor.fetchone()
#return 0 for db error
except mysql.connector.Error as err:
print('Something went ... | findUser | identifier_name |
client.js | var crypto = require('crypto');
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var pgPass = require('pgpass');
var TypeOverrides = require('./type-overrides');
var ConnectionParameters = require('./connection-parameters');
var Query = require('./query');
var defaults = require('./defaul... |
//password request handling
con.on('authenticationCleartextPassword', checkPgPass(function() {
con.password(self.password);
}));
//password request handling
con.on('authenticationMD5Password', checkPgPass(function(msg) {
var inner = Client.md5(self.password + self.user);
var outer = Client.md5(... | {
return function(msg) {
if (null !== self.password) {
cb(msg);
} else {
pgPass(self.connectionParameters, function(pass){
if (undefined !== pass) {
self.connectionParameters.password = self.password = pass;
}
cb(msg);
});
}
};
... | identifier_body |
client.js | var crypto = require('crypto');
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var pgPass = require('pgpass');
var TypeOverrides = require('./type-overrides');
var ConnectionParameters = require('./connection-parameters');
var Query = require('./query');
var defaults = require('./defaul... |
escaped += '"';
return escaped;
};
// Ported from PostgreSQL 9.2.4 source code in src/interfaces/libpq/fe-exec.c
Client.prototype.escapeLiteral = function(str) {
var hasBackslash = false;
var escaped = '\'';
for(var i = 0; i < str.length; i++) {
var c = str[i];
if(c === '\'') {
escaped += ... | {
var c = str[i];
if(c === '"') {
escaped += c + c;
} else {
escaped += c;
}
} | conditional_block |
client.js | var crypto = require('crypto');
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var pgPass = require('pgpass');
var TypeOverrides = require('./type-overrides');
var ConnectionParameters = require('./connection-parameters');
var Query = require('./query');
var defaults = require('./defaul... | (cb) {
return function(msg) {
if (null !== self.password) {
cb(msg);
} else {
pgPass(self.connectionParameters, function(pass){
if (undefined !== pass) {
self.connectionParameters.password = self.password = pass;
}
cb(msg);
});
}
... | checkPgPass | identifier_name |
client.js | var crypto = require('crypto');
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var pgPass = require('pgpass');
var TypeOverrides = require('./type-overrides');
var ConnectionParameters = require('./connection-parameters');
var Query = require('./query');
var defaults = require('./defaul... |
//delegate rowDescription to active query
con.on('rowDescription', function(msg) {
self.activeQuery.handleRowDescription(msg);
});
//delegate dataRow to active query
con.on('dataRow', function(msg) {
self.activeQuery.handleDataRow(msg);
});
//delegate portalSuspended to active... | //hook up query handling events to connection
//after the connection initially becomes ready for queries
con.once('readyForQuery', function() { | random_line_split |
cell-does-not-clone.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let x = Cell::new(Foo { x: 22 });
let _y = x.get();
let _z = x.clone();
} | identifier_body | |
cell-does-not-clone.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self) -> Foo {
// Using Cell in any way should never cause clone() to be
// invoked -- after all, that would permit evil user code to
// abuse `Cell` and trigger crashes.
panic!();
}
}
impl Copy for Foo {}
pub fn main() {
let x = Cell::new(Foo { x: 22 });
let _y = x.get(... | clone | identifier_name |
cell-does-not-clone.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | panic!();
}
}
impl Copy for Foo {}
pub fn main() {
let x = Cell::new(Foo { x: 22 });
let _y = x.get();
let _z = x.clone();
} | fn clone(&self) -> Foo {
// Using Cell in any way should never cause clone() to be
// invoked -- after all, that would permit evil user code to
// abuse `Cell` and trigger crashes.
| random_line_split |
arguments.rs | use std;
pub enum | {
Invalid,
Help,
Create(String, Vec<String>),
Extract(String),
List(String),
}
impl Arguments {
pub fn parseargs() -> Arguments {
enum Action { Create, Extract, List }
let mut action = None;
let mut archive: Option<String> = None;
let mut files: Vec<String> = Ve... | Arguments | identifier_name |
arguments.rs | use std;
pub enum Arguments {
Invalid,
Help,
Create(String, Vec<String>),
Extract(String),
List(String),
}
impl Arguments {
pub fn parseargs() -> Arguments {
enum Action { Create, Extract, List }
let mut action = None;
let mut archive: Option<String> = None;
let... | let archive = match archive {
None => return Arguments::Invalid,
Some(fname) => fname,
};
return match action {
None => Arguments::Invalid,
Some(Action::Create) => Arguments::Create(archive, files),
Some(Action::Extract) => Arguments::... | random_line_split | |
utils.py | #
# Utility stackables
#
from __future__ import print_function, absolute_import, unicode_literals, division
from stackable.stackable import Stackable, StackableError
import json, pickle
from time import sleep
from threading import Thread, Event
from datetime import datetime, timedelta
class StackablePickler(Stackable... | (self, interval=20, send=True, ping_string='__stack_ping', pong_string='__stack_pong'):
super(StackablePoker, self).__init__()
self.ping_string = ping_string.encode('utf-8')
self.pong_string = pong_string.encode('utf-8')
self.w = Event()
self.interval = interval
self.send = send
if self.send:
self.rese... | __init__ | identifier_name |
utils.py | #
# Utility stackables
#
from __future__ import print_function, absolute_import, unicode_literals, division
from stackable.stackable import Stackable, StackableError
import json, pickle
from time import sleep
from threading import Thread, Event
from datetime import datetime, timedelta
class StackablePickler(Stackable... |
# def poll(self):
# return self.fd.read()
class StackablePrinter(Stackable):
'''Prints all input and output, and returns it unmodified.
Useful for quick debugging of Stackables.'''
def __init__(self, printer=print):
'Takes a printing function as argument - defaults to print'
self.printer = printer
super(... | return data | identifier_body |
utils.py | #
# Utility stackables
#
from __future__ import print_function, absolute_import, unicode_literals, division
from stackable.stackable import Stackable, StackableError
import json, pickle
from time import sleep
from threading import Thread, Event
from datetime import datetime, timedelta
class StackablePickler(Stackable... |
return data
def process_input(self, data):
if data == self.pong_string:
self.reset()
return None
elif data == self.ping_string:
self._feed(self.pong_string)
return None
elif self.send and (datetime.now() - self.timestamp) > timedelta(seconds=30):
raise StackableError('Pong not received')
ret... | raise StackableError('Pong not received') | conditional_block |
utils.py | #
# Utility stackables
#
from __future__ import print_function, absolute_import, unicode_literals, division
from stackable.stackable import Stackable, StackableError
import json, pickle
from time import sleep
from threading import Thread, Event
from datetime import datetime, timedelta
class StackablePickler(Stackable... | self.ping_string = ping_string.encode('utf-8')
self.pong_string = pong_string.encode('utf-8')
self.w = Event()
self.interval = interval
self.send = send
if self.send:
self.reset()
def _detach(self):
super(StackablePoker, self)._detach()
self.w.set()
def reset(self):
self.timestamp = datetime.no... | random_line_split | |
rmm_diis_old.py | """Module defining ``Eigensolver`` classes."""
import numpy as np
from gpaw.utilities.blas import axpy
from gpaw.eigensolvers.eigensolver import Eigensolver
from gpaw import extra_parameters
class RMM_DIIS(Eigensolver):
"""RMM-DIIS eigensolver
It is expected that the trial wave functions are orthonormal
... | RdR_x = np.array([integrate(dR_G, R_G)
for R_G, dR_G in zip(R_xG, dR_xG)])
dRdR_x = np.array([integrate(dR_G, dR_G) for dR_G in dR_xG])
comm.sum(RdR_x)
comm.sum(dRdR_x)
lam_x = -RdR_x / dRdR_x
if extra_parameters.get(... | self.calculate_residuals(kpt, wfs, hamiltonian, dpsit_xG,
P_axi, kpt.eps_n[n_x], dR_xG, n_x,
calculate_change=True)
# Find lam that minimizes the norm of R'_G = R_G + lam dR_G | random_line_split |
rmm_diis_old.py | """Module defining ``Eigensolver`` classes."""
import numpy as np
from gpaw.utilities.blas import axpy
from gpaw.eigensolvers.eigensolver import Eigensolver
from gpaw import extra_parameters
class RMM_DIIS(Eigensolver):
"""RMM-DIIS eigensolver
It is expected that the trial wave functions are orthonormal
... | (a_G, b_G):
return np.real(wfs.integrate(a_G, b_G, global_integral=False))
comm = wfs.gd.comm
B = self.blocksize
dR_xG = wfs.empty(B, q=kpt.q)
P_axi = wfs.pt.dict(B)
error = 0.0
for n1 in range(0, wfs.bd.mynbands, B):
n2 = n1 + B
if n2... | integrate | identifier_name |
rmm_diis_old.py | """Module defining ``Eigensolver`` classes."""
import numpy as np
from gpaw.utilities.blas import axpy
from gpaw.eigensolvers.eigensolver import Eigensolver
from gpaw import extra_parameters
class RMM_DIIS(Eigensolver):
| """RMM-DIIS eigensolver
It is expected that the trial wave functions are orthonormal
and the integrals of projector functions and wave functions
``nucleus.P_uni`` are already calculated
Solution steps are:
* Subspace diagonalization
* Calculation of residuals
* Improvement of wave functio... | identifier_body | |
rmm_diis_old.py | """Module defining ``Eigensolver`` classes."""
import numpy as np
from gpaw.utilities.blas import axpy
from gpaw.eigensolvers.eigensolver import Eigensolver
from gpaw import extra_parameters
class RMM_DIIS(Eigensolver):
"""RMM-DIIS eigensolver
It is expected that the trial wave functions are orthonormal
... |
error += weight * integrate(R_xG[n - n1], R_xG[n - n1])
# Precondition the residual:
self.timer.start('precondition')
ekin_x = self.preconditioner.calculate_kinetic_energy(
psit_xG, kpt)
dpsit_xG = self.preconditioner(R_xG, kpt, ekin_x)
... | if wfs.bd.global_index(n) < self.nbands_converge:
weight = kpt.weight
else:
weight = 0.0 | conditional_block |
insert.rs | use database::Database;
use database::Errors;
use database::errors::log_n_wrap;
use database::Errors::{NotFound, Conflict};
use std::vec::Vec;
use serde_json::Value;
use serde_json;
use rand;
impl Database {
/// Inserts the record to the given path.
pub fn insert(&mut self, keys: &mut Vec<String>, value: Value... |
} | {
let data = &mut self.data;
if let Ok(obj) = Self::get_object(keys, data) {
// Path Found. It should be an array to accomplish an operation. Otherwise it must be an update not insert.
if let Some(ref mut array) = obj.as_array_mut() {
let mut id = rand::random();
... | identifier_body |
insert.rs | use database::Database;
use database::Errors;
use database::errors::log_n_wrap;
use database::Errors::{NotFound, Conflict};
use std::vec::Vec;
use serde_json::Value;
use serde_json;
use rand;
impl Database {
/// Inserts the record to the given path.
pub fn | (&mut self, keys: &mut Vec<String>, value: Value) -> Result<Value, Errors> {
let data = &mut self.data;
if let Ok(obj) = Self::get_object(keys, data) {
// Path Found. It should be an array to accomplish an operation. Otherwise it must be an update not insert.
if let Some(ref mut ... | insert | identifier_name |
insert.rs | use database::Database;
use database::Errors;
use database::errors::log_n_wrap;
use database::Errors::{NotFound, Conflict};
use std::vec::Vec;
use serde_json::Value;
use serde_json;
use rand;
impl Database {
/// Inserts the record to the given path.
pub fn insert(&mut self, keys: &mut Vec<String>, value: Value... | }
} | log_n_wrap(&self.logger,
NotFound(format!("Insert - Error {:?}. No record with the given path:",
keys)))
} | random_line_split |
insert.rs | use database::Database;
use database::Errors;
use database::errors::log_n_wrap;
use database::Errors::{NotFound, Conflict};
use std::vec::Vec;
use serde_json::Value;
use serde_json;
use rand;
impl Database {
/// Inserts the record to the given path.
pub fn insert(&mut self, keys: &mut Vec<String>, value: Value... |
let value_with_id = &mut value.clone();
if let Some(obj_id) = value_with_id.as_object_mut() {
obj_id.insert("id".to_string(), serde_json::to_value(id).unwrap());
}
// TODO: random id conflict must be resolved.
if let So... | {
if let Some(parsed) = id_value.as_i64() {
id = parsed;
}
} | conditional_block |
calendar.stories.ts | import { Component, LOCALE_ID, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { Meta, moduleMetadata, Story } from '@storybook/angular';
import { ALuDateAdapter, LuNativeDateAdapter, LuStringDateAdapter ... |
}
export default {
title: 'NG/Date/Calendar',
component: CalendarStories,
decorators: [
moduleMetadata({
entryComponents: [CalendarStories],
imports: [
LuDateModule,
BrowserAnimationsModule,
FormsModule,
],
providers: [
{ provide: LOCALE_ID, useValue: 'en-US' },
// { provide: LOCA... | {
this.date = new Date(this.date);
this.date.setDate(Math.ceil(Math.random() * 30));
} | identifier_body |
calendar.stories.ts | import { Component, LOCALE_ID, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { Meta, moduleMetadata, Story } from '@storybook/angular';
import { ALuDateAdapter, LuNativeDateAdapter, LuStringDateAdapter ... | implements OnInit {
date = new Date();
ngOnInit() {
// this.date.setFullYear(2016);
}
random() {
this.date = new Date(this.date);
this.date.setDate(Math.ceil(Math.random() * 30));
}
}
export default {
title: 'NG/Date/Calendar',
component: CalendarStories,
decorators: [
moduleMetadata({
entryCompone... | CalendarStories | identifier_name |
calendar.stories.ts | import { Component, LOCALE_ID, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { Meta, moduleMetadata, Story } from '@storybook/angular';
import { ALuDateAdapter, LuNativeDateAdapter, LuStringDateAdapter ... | })
class CalendarStories implements OnInit {
date = new Date();
ngOnInit() {
// this.date.setFullYear(2016);
}
random() {
this.date = new Date(this.date);
this.date.setDate(Math.ceil(Math.random() * 30));
}
}
export default {
title: 'NG/Date/Calendar',
component: CalendarStories,
decorators: [
moduleMe... |
@Component({
selector: 'date-calendar-stories',
templateUrl: './calendar.stories.html' | random_line_split |
Server.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const ServerOptions_1 = require("./ServerOptions");
const Http = require("http");
const Https = require("https");
const express = require("express");
const debug = require("debug");
const compression = require("compression");
const path = requ... |
appConfigure() {
this.app.disable('x-powered-by');
if (this.options.cors) {
this.app.use(cors());
}
this.app.use(compression());
if (this.options.behindProxy) {
this.app.enable('trust proxy');
}
if (this.options.verbose) {
... | {
if (this.isHttps()) {
Https.globalAgent.maxSockets = Infinity;
logInfo('Https max sockets set to %O', Https.globalAgent.maxSockets);
}
else {
Http.globalAgent.maxSockets = Infinity;
logInfo('Http max sockets set to %O', Http.globalAgent.maxSocket... | identifier_body |
Server.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const ServerOptions_1 = require("./ServerOptions");
const Http = require("http");
const Https = require("https");
const express = require("express");
const debug = require("debug");
const compression = require("compression");
const path = requ... |
this.app.use(compression());
if (this.options.behindProxy) {
this.app.enable('trust proxy');
}
if (this.options.verbose) {
this.app.use((req, res, next) => {
logInfo(this.options.name, datefmt(new Date(), this.options.dateformat), 'pid:', process.... | {
this.app.use(cors());
} | conditional_block |
Server.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const ServerOptions_1 = require("./ServerOptions");
const Http = require("http");
const Https = require("https");
const express = require("express");
const debug = require("debug");
const compression = require("compression");
const path = requ... | resolve();
});
});
}
}
exports.Server = Server;
//# sourceMappingURL=Server.js.map | random_line_split | |
Server.js | "use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const ServerOptions_1 = require("./ServerOptions");
const Http = require("http");
const Https = require("https");
const express = require("express");
const debug = require("debug");
const compression = require("compression");
const path = requ... | (pid, msg) {
process.send({ pid, msg });
}
startWorker() {
var self = this;
return new Promise((resolve, reject) => {
self.server = self.createServer();
self.server
.listen(self.options.port, self.options.ip, () => {
self.sendMaster... | sendMaster | identifier_name |
register.component.ts | import { Component, OnInit } from '@angular/core';
import { Response } from '@angular/http';
import { Router, ActivatedRoute } from '@angular/router';
import { RegisterModel } from '../../core/models/register-model';
import { AccountService } from '../../core/account/account.service';
import { ControlBase } fro... | label: 'Lastname',
placeholder: 'Lastname',
value: '',
type: 'textbox',
required: true,
order: 3
}),
new ControlTextbox({
key: 'email',
label: 'Email',
... | new ControlTextbox({
key: 'lastname',
| random_line_split |
register.component.ts | import { Component, OnInit } from '@angular/core';
import { Response } from '@angular/http';
import { Router, ActivatedRoute } from '@angular/router';
import { RegisterModel } from '../../core/models/register-model';
import { AccountService } from '../../core/account/account.service';
import { ControlBase } fro... | ublic accountService: AccountService, public router: Router, public route: ActivatedRoute) { }
public register(model: RegisterModel): void {
this.accountService.register(model)
.subscribe((res: Response) => {
this.router.navigate(['../registerconfirmation'], { relativeTo: t... | nstructor(p | identifier_name |
register.component.ts | import { Component, OnInit } from '@angular/core';
import { Response } from '@angular/http';
import { Router, ActivatedRoute } from '@angular/router';
import { RegisterModel } from '../../core/models/register-model';
import { AccountService } from '../../core/account/account.service';
import { ControlBase } fro... |
}
|
const controls: Array<ControlBase<any>> = [
new ControlTextbox({
key: 'username',
label: 'Username',
placeholder: 'Username',
value: '',
type: 'textbox',
required: true,
order: 1
... | identifier_body |
demo_ystockquote.py | # To make print working for Python2/3
from __future__ import print_function
import ystockquote as ysq
def _main():
for s in ["NA.TO", "XBB.TO", "NOU.V", "AP-UN.TO", "BRK-A", "AAPL"]:
print("=============================================")
print("s: {}".format(s))
print("get_name: {}".for... | print("get_price_earnings_ratio: {}".format(ysq.get_price_earnings_ratio(s)))
print("get_52_week_low: {}".format(ysq.get_52_week_low(s)))
print("get_52_week_high: {}".format(ysq.get_52_week_high(s)))
print("get_currency: {}".format(ysq.get_currency(s)))
if __name__ == '__main__':
... | print("get_dividend_yield: {}".format(ysq.get_dividend_yield(s))) | random_line_split |
demo_ystockquote.py | # To make print working for Python2/3
from __future__ import print_function
import ystockquote as ysq
def | ():
for s in ["NA.TO", "XBB.TO", "NOU.V", "AP-UN.TO", "BRK-A", "AAPL"]:
print("=============================================")
print("s: {}".format(s))
print("get_name: {}".format(ysq.get_name(s)))
print("get_price: {}".format(ysq.get_price(s)))
print("get_volume: {}".forma... | _main | identifier_name |
demo_ystockquote.py | # To make print working for Python2/3
from __future__ import print_function
import ystockquote as ysq
def _main():
for s in ["NA.TO", "XBB.TO", "NOU.V", "AP-UN.TO", "BRK-A", "AAPL"]:
print("=============================================")
print("s: {}".format(s))
print("get_name: {}".for... | _main() | conditional_block | |
demo_ystockquote.py | # To make print working for Python2/3
from __future__ import print_function
import ystockquote as ysq
def _main():
|
if __name__ == '__main__':
_main()
| for s in ["NA.TO", "XBB.TO", "NOU.V", "AP-UN.TO", "BRK-A", "AAPL"]:
print("=============================================")
print("s: {}".format(s))
print("get_name: {}".format(ysq.get_name(s)))
print("get_price: {}".format(ysq.get_price(s)))
print("get_volume: {}".format(ysq.get... | identifier_body |
__init__.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/thumbor/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com timehome@corp.globo.com
# Copyright (c) 2015 Wikimedia Foundation
# EXIF optimizer, aims to r... |
def should_run(self, image_extension, buffer):
good_extension = 'jpg' in image_extension or 'jpeg' in image_extension
return good_extension and self.runnable
def optimize(self, buffer, input_file, output_file):
exif_fields = self.exif_fields_to_keep
# TinyRGB is a lightweight... | super(Optimizer, self).__init__(context)
self.runnable = True
self.exiftool_path = self.context.config.EXIFTOOL_PATH
self.exif_fields_to_keep = self.context.config.EXIF_FIELDS_TO_KEEP
self.tinyrgb_path = self.context.config.EXIF_TINYRGB_PATH
self.tinyrgb_icc_replace = self.conte... | identifier_body |
__init__.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/thumbor/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com timehome@corp.globo.com
# Copyright (c) 2015 Wikimedia Foundation
# EXIF optimizer, aims to r... | self.exiftool_path,
'-DeviceModelDesc',
'-S',
'-T',
input_file
])
logger.debug("[EXIFTOOL] exiftool output: " + output)
if (output.rstrip().lower() == self.tinyrgb_icc_replace.lower()):
n... | output = subprocess.check_output([ | random_line_split |
__init__.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/thumbor/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com timehome@corp.globo.com
# Copyright (c) 2015 Wikimedia Foundation
# EXIF optimizer, aims to r... | (self, buffer, input_file, output_file):
exif_fields = self.exif_fields_to_keep
# TinyRGB is a lightweight sRGB swap-in replacement created by Facebook
# If the image is sRGB, swap the existing heavy profile for TinyRGB
# Only works if icc_profile is configured to be preserved in
... | optimize | identifier_name |
__init__.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/thumbor/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com timehome@corp.globo.com
# Copyright (c) 2015 Wikimedia Foundation
# EXIF optimizer, aims to r... |
# Strip all EXIF fields except the ones we want to
# explicitely copy over
command = [
self.exiftool_path,
input_file,
'-all=',
'-tagsFromFile',
'@'
]
command += ['-{0}'.format(i) for i in exif_fields]
command ... | new_icc = 'icc_profile<=%s' % (
self.tinyrgb_path
)
exif_fields = [
new_icc if i == 'icc_profile' else i for i in exif_fields
] | conditional_block |
lib.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn empty_block(&self) -> P<ast::Expr> {
quote_expr!(self.cx, {})
}
// Creates a match arm for the instruction at `pc` with the expression
// `body`.
fn arm_inst(&self, pc: usize, body: P<ast::Expr>) -> ast::Arm {
let pc_pat = self.cx.pat_lit(self.sp, quote_expr!(self.cx, $pc));
... | {
arms.push(self.wild_arm_expr(self.empty_block()));
self.cx.expr_match(self.sp, quote_expr!(self.cx, pc), arms)
} | identifier_body |
lib.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self, ranges: &[(char, char)]) -> P<ast::Expr> {
let mut arms = ranges.iter().map(|&(start, end)| {
let pat = self.cx.pat(
self.sp, ast::PatKind::Range(
quote_expr!(self.cx, $start), quote_expr!(self.cx, $end)));
self.cx.arm(self.sp, vec!(pat), quote... | match_class | identifier_name |
lib.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
return false;
})
}
// EmptyLook, Save, Jump, Split
_ => quote_expr!(self.cx, { return false; }),
};
self.arm_inst(pc, body)
}).collect::<Vec<ast::Arm>>();
self.m... | self.add(nlist, thread_caps, $nextpc, at_next);
} | random_line_split |
query19.rs | use timely::dataflow::*;
use timely::dataflow::operators::*;
use timely::dataflow::operators::probe::Handle as ProbeHandle;
use differential_dataflow::AsCollection;
use differential_dataflow::operators::*;
use differential_dataflow::lattice::Lattice;
// use differential_dataflow::difference::DiffPair;
use ::Collectio... | println!("TODO: query 19 could use some _u attention");
let lineitems =
collections
.lineitems()
.inner
.flat_map(|(x,t,d)|
if (starts_with(&x.ship_mode, b"AIR") || starts_with(&x.ship_mode, b"AIR REG")) && starts_with(&x.ship_instruct, b"DELIVER IN PERSON") {
... |
pub fn query<G: Scope>(collections: &mut Collections<G>) -> ProbeHandle<G::Timestamp>
where G::Timestamp: Lattice+Ord {
| random_line_split |
query19.rs | use timely::dataflow::*;
use timely::dataflow::operators::*;
use timely::dataflow::operators::probe::Handle as ProbeHandle;
use differential_dataflow::AsCollection;
use differential_dataflow::operators::*;
use differential_dataflow::lattice::Lattice;
// use differential_dataflow::difference::DiffPair;
use ::Collectio... |
else { None }
)
.as_collection();
let lines1 = lineitems.filter(|&(_, quant)| quant >= 1 && quant <= 11).map(|x| (x.0, ()));
let lines2 = lineitems.filter(|&(_, quant)| quant >= 10 && quant <= 20).map(|x| (x.0, ()));
let lines3 = lineitems.filter(|&(_, quant)| quant >= 20 && qu... | {
Some(((x.part_key, x.quantity), t, d * (x.extended_price * (100 - x.discount) / 100) as isize))
} | conditional_block |
query19.rs | use timely::dataflow::*;
use timely::dataflow::operators::*;
use timely::dataflow::operators::probe::Handle as ProbeHandle;
use differential_dataflow::AsCollection;
use differential_dataflow::operators::*;
use differential_dataflow::lattice::Lattice;
// use differential_dataflow::difference::DiffPair;
use ::Collectio... |
pub fn query<G: Scope>(collections: &mut Collections<G>) -> ProbeHandle<G::Timestamp>
where G::Timestamp: Lattice+Ord {
println!("TODO: query 19 could use some _u attention");
let lineitems =
collections
.lineitems()
.inner
.flat_map(|(x,t,d)|
if (starts_with(&x.shi... | {
source.len() >= query.len() && &source[..query.len()] == query
} | identifier_body |
query19.rs | use timely::dataflow::*;
use timely::dataflow::operators::*;
use timely::dataflow::operators::probe::Handle as ProbeHandle;
use differential_dataflow::AsCollection;
use differential_dataflow::operators::*;
use differential_dataflow::lattice::Lattice;
// use differential_dataflow::difference::DiffPair;
use ::Collectio... | <G: Scope>(collections: &mut Collections<G>) -> ProbeHandle<G::Timestamp>
where G::Timestamp: Lattice+Ord {
println!("TODO: query 19 could use some _u attention");
let lineitems =
collections
.lineitems()
.inner
.flat_map(|(x,t,d)|
if (starts_with(&x.ship_mode, b"AIR"... | query | identifier_name |
annotation.py | # -*- coding: utf-8 -*-
###############################################################################
#
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
#... |
class Annotation(models.Model):
_inherit = 'myo.annotation'
event_ids = fields.Many2many(
'myo.event',
'myo_event_annotation_rel',
'annotation_id',
'event_id',
'Events'
)
| _inherit = 'myo.event'
annotation_ids = fields.Many2many(
'myo.annotation',
'myo_event_annotation_rel',
'event_id',
'annotation_id',
'Annotations'
) | identifier_body |
annotation.py | # -*- coding: utf-8 -*-
###############################################################################
#
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
#... | 'Annotations'
)
class Annotation(models.Model):
_inherit = 'myo.annotation'
event_ids = fields.Many2many(
'myo.event',
'myo_event_annotation_rel',
'annotation_id',
'event_id',
'Events'
) | 'event_id',
'annotation_id', | random_line_split |
annotation.py | # -*- coding: utf-8 -*-
###############################################################################
#
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
#... | (models.Model):
_inherit = 'myo.event'
annotation_ids = fields.Many2many(
'myo.annotation',
'myo_event_annotation_rel',
'event_id',
'annotation_id',
'Annotations'
)
class Annotation(models.Model):
_inherit = 'myo.annotation'
event_ids = fields.Many2many(
... | Event | identifier_name |
kendo.culture.he.js | /*
* Kendo UI Web v2014.1.318 (http://kendoui.com)
* Copyright 2014 Telerik AD. All rights reserved.
*
* Kendo UI Web commercial licenses may be obtained at
* http://www.telerik.com/purchase/license-agreement/kendo-ui-web
* If you do not own a commercial license, this file shall be governed by the
* GNU General Public ... | decimals: 2,
",": ",",
".": ".",
groupSize: [3],
symbol: "%"
},
currency: {
pattern: ["$-n","$ n"],
decimals: 2,
",": ",",
".": ".",
gro... | pattern: ["-n%","n%"], | random_line_split |
date.ts | interface Date {
getNextWeekDay(): Date;
endOfDay(): Date;
getNextWeekDayAtMidday(): Date;
}
/**
* Sets the Date object to the next weekday
*/
Date.prototype.getNextWeekDay = function(): Date {
var dt: Date = new Date(this);
switch (this.getDay()) {
case 5:
dt.setUTCDate(this... |
/**
* Sets the date element of the Date object to the next
* weekday and sets the time element to 12:00:00:000
*/
Date.prototype.getNextWeekDayAtMidday = function () : Date {
var dt: Date = this.getNextWeekDay();
dt.setUTCHours(12);
dt.setUTCMinutes(0);
dt.setUTCSeconds(0);
dt.setUTCMillisecond... | }
} | random_line_split |
ReactPropTransferer.js | /**
* Copyright 2013-2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ... |
// Because elements are immutable we have to merge into the existing
// props object rather than clone it.
transferInto(element.props, this.props);
return element;
}
}
};
module.exports = ReactPropTransferer;
| {
if (!didWarn) {
didWarn = true;
("production" !== process.env.NODE_ENV ? warning(
false,
'transferPropsTo is deprecated. ' +
'See http://fb.me/react-transferpropsto for more information.'
) : null);
}
} | conditional_block |
ReactPropTransferer.js | /**
* Copyright 2013-2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ... | * @param {object} newProps new props to merge in
* @return {object} a new object containing both sets of props merged.
*/
mergeProps: function(oldProps, newProps) {
return transferInto(assign({}, oldProps), newProps);
},
/**
* @lends {ReactPropTransferer.prototype}
*/
Mixin: {
/**
... | * Merge two props objects using TransferStrategies.
*
* @param {object} oldProps original props (they take precedence) | random_line_split |
ReactPropTransferer.js | /**
* Copyright 2013-2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ... |
/**
* ReactPropTransferer are capable of transferring props to another component
* using a `transferPropsTo` method.
*
* @class ReactPropTransferer
*/
var ReactPropTransferer = {
TransferStrategies: TransferStrategies,
/**
* Merge two props objects using TransferStrategies.
*
* @param {object} old... | {
for (var thisKey in newProps) {
if (!newProps.hasOwnProperty(thisKey)) {
continue;
}
var transferStrategy = TransferStrategies[thisKey];
if (transferStrategy && TransferStrategies.hasOwnProperty(thisKey)) {
transferStrategy(props, thisKey, newProps[thisKey]);
} else if (!props.hasO... | identifier_body |
ReactPropTransferer.js | /**
* Copyright 2013-2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule ... | (mergeStrategy) {
return function(props, key, value) {
if (!props.hasOwnProperty(key)) {
props[key] = value;
} else {
props[key] = mergeStrategy(props[key], value);
}
};
}
var transferStrategyMerge = createTransferStrategy(function(a, b) {
// `merge` overrides the first object's (`props[k... | createTransferStrategy | identifier_name |
any_unique_aliases_generated.rs | // automatically generated by the FlatBuffers compiler, do not modify
extern crate flatbuffers;
use std::mem;
use std::cmp::Ordering;
use self::flatbuffers::{EndianScalar, Follow};
use super::*;
#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
pub cons... |
}
impl<'a> flatbuffers::Verifiable for AnyUniqueAliases {
#[inline]
fn run_verifier(
v: &mut flatbuffers::Verifier, pos: usize
) -> Result<(), flatbuffers::InvalidFlatbuffer> {
use self::flatbuffers::Verifiable;
u8::run_verifier(v, pos)
}
}
impl flatbuffers::SimpleToVerifyInSlice for AnyUniqueAli... | {
let b = u8::from_le(self.0);
Self(b)
} | identifier_body |
any_unique_aliases_generated.rs | // automatically generated by the FlatBuffers compiler, do not modify
extern crate flatbuffers;
use std::mem;
use std::cmp::Ordering;
use self::flatbuffers::{EndianScalar, Follow};
use super::*;
#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
pub cons... | (buf: &'a [u8], loc: usize) -> Self::Inner {
let b = unsafe {
flatbuffers::read_scalar_at::<u8>(buf, loc)
};
Self(b)
}
}
impl flatbuffers::Push for AnyUniqueAliases {
type Output = AnyUniqueAliases;
#[inline]
fn push(&self, dst: &mut [u8], _rest: &[u8]) {
unsafe { flatbuffers::e... | follow | identifier_name |
any_unique_aliases_generated.rs | // automatically generated by the FlatBuffers compiler, do not modify
extern crate flatbuffers;
use std::mem;
use std::cmp::Ordering;
use self::flatbuffers::{EndianScalar, Follow};
use super::*;
#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")]
pub cons... | ];
/// Returns the variant's name or "" if unknown.
pub fn variant_name(self) -> Option<&'static str> {
match self {
Self::NONE => Some("NONE"),
Self::M => Some("M"),
Self::TS => Some("TS"),
Self::M2 => Some("M2"),
_ => None,
}
}
}
impl std::fmt::Debug for AnyUniqueAliases ... | Self::M2, | random_line_split |
client.rs | //! The modules which contains CDRS Cassandra client.
use std::net;
use std::io;
use std::collections::HashMap;
use query::{Query, QueryParams, QueryBatch};
use frame::{Frame, Opcode, Flag};
use frame::frame_response::ResponseBody;
use IntoBytes;
use frame::parser::parse_frame;
use types::*;
use frame::events::SimpleSe... | pub struct Session<T: Authenticator, X: CDRSTransport> {
started: bool,
cdrs: CDRS<T, X>,
compressor: Compression,
}
impl<T: Authenticator, X: CDRSTransport> Session<T, X> {
/// Creates new session basing on CDRS instance.
pub fn start(cdrs: CDRS<T, X>) -> Session<T, X> {
let compressor = c... | /// The object that provides functionality for communication with Cassandra server. | random_line_split |
client.rs | //! The modules which contains CDRS Cassandra client.
use std::net;
use std::io;
use std::collections::HashMap;
use query::{Query, QueryParams, QueryBatch};
use frame::{Frame, Opcode, Flag};
use frame::frame_response::ResponseBody;
use IntoBytes;
use frame::parser::parse_frame;
use types::*;
use frame::events::SimpleSe... |
unimplemented!();
}
fn drop_connection(&mut self) -> error::Result<()> {
self.transport
.close(net::Shutdown::Both)
.map_err(|err| error::Error::Io(err))
}
}
/// The object that provides functionality for communication with Cassandra server.
pub struct Session<T: ... | {
let body = start_response.get_body()?;
let authenticator = body.get_authenticator().expect(
"Cassandra Server did communicate that it needed password
authentication but the auth schema was missing in the body response",
);
// This creat... | conditional_block |
client.rs | //! The modules which contains CDRS Cassandra client.
use std::net;
use std::io;
use std::collections::HashMap;
use query::{Query, QueryParams, QueryBatch};
use frame::{Frame, Opcode, Flag};
use frame::frame_response::ResponseBody;
use IntoBytes;
use frame::parser::parse_frame;
use types::*;
use frame::events::SimpleSe... | <'a>(mut self,
events: Vec<SimpleServerEvent>)
-> error::Result<(Listener<X>, EventStream)> {
let query_frame = Frame::new_req_register(events).into_cbytes();
try!(self.cdrs.transport.write(query_frame.as_slice()));
try!(parse_frame(&mut self.c... | listen_for | identifier_name |
manual_non_exhaustive.rs | use clippy_utils::attrs::is_doc_hidden;
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::source::snippet_opt;
use clippy_utils::{meets_msrv, msrvs};
use if_chain::if_chain;
use rustc_ast::ast::{FieldDef, Item, ItemKind, Variant, VariantData, VisibilityKind};
use rustc_errors::Applicability;
use rust... | (field: &FieldDef) -> bool {
matches!(field.vis.kind, VisibilityKind::Inherited)
}
fn is_non_exhaustive_marker(field: &FieldDef) -> bool {
is_private(field) && field.ty.kind.is_unit() && field.ident.map_or(true, |n| n.as_str().starts_with('_'))
}
fn find_header_span(cx: &EarlyContext<'... | is_private | identifier_name |
manual_non_exhaustive.rs | use clippy_utils::attrs::is_doc_hidden;
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::source::snippet_opt;
use clippy_utils::{meets_msrv, msrvs};
use if_chain::if_chain;
use rustc_ast::ast::{FieldDef, Item, ItemKind, Variant, VariantData, VisibilityKind};
use rustc_errors::Applicability;
use rust... | }
}
fn check_manual_non_exhaustive_struct(cx: &EarlyContext<'_>, item: &Item, data: &VariantData) {
fn is_private(field: &FieldDef) -> bool {
matches!(field.vis.kind, VisibilityKind::Inherited)
}
fn is_non_exhaustive_marker(field: &FieldDef) -> bool {
is_private(field) && field.ty.kind... | random_line_split | |
manual_non_exhaustive.rs | use clippy_utils::attrs::is_doc_hidden;
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::source::snippet_opt;
use clippy_utils::{meets_msrv, msrvs};
use if_chain::if_chain;
use rustc_ast::ast::{FieldDef, Item, ItemKind, Variant, VariantData, VisibilityKind};
use rustc_errors::Applicability;
use rust... | ,
_ => {},
}
}
extract_msrv_attr!(EarlyContext);
}
fn check_manual_non_exhaustive_enum(cx: &EarlyContext<'_>, item: &Item, variants: &[Variant]) {
fn is_non_exhaustive_marker(variant: &Variant) -> bool {
matches!(variant.data, VariantData::Unit(_))
&& variant.ident.... | {
if let VariantData::Unit(..) = variant_data {
return;
}
check_manual_non_exhaustive_struct(cx, item, variant_data);
} | conditional_block |
manual_non_exhaustive.rs | use clippy_utils::attrs::is_doc_hidden;
use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::source::snippet_opt;
use clippy_utils::{meets_msrv, msrvs};
use if_chain::if_chain;
use rustc_ast::ast::{FieldDef, Item, ItemKind, Variant, VariantData, VisibilityKind};
use rustc_errors::Applicability;
use rust... |
fn find_header_span(cx: &EarlyContext<'_>, item: &Item, data: &VariantData) -> Span {
let delimiter = match data {
VariantData::Struct(..) => '{',
VariantData::Tuple(..) => '(',
VariantData::Unit(_) => unreachable!("`VariantData::Unit` is already handled above"),
... | {
is_private(field) && field.ty.kind.is_unit() && field.ident.map_or(true, |n| n.as_str().starts_with('_'))
} | identifier_body |
view_ref.d.ts | import * as viewModule from './view';
import { ChangeDetectorRef } from '../change_detection/change_detector_ref';
import { RenderViewRef, RenderFragmentRef } from 'angular2/src/core/render/api';
export declare function internalView(viewRef: ViewRef): viewModule.AppView;
export declare function internalProtoView(protoV... | * <!-- ViewRef: outer-0 -->
* Count: 2
* <ul>
* <template view-container-ref></template>
* <!-- ViewRef: inner-1 --><li>first</li><!-- /ViewRef: inner-1 -->
* <!-- ViewRef: inner-2 --><li>second</li><!-- /ViewRef: inner-2 -->
* </ul>
* <!-- /ViewRef: outer-0 -->
* ```
*/
export declare abstract class Vi... | * ``` | random_line_split |
view_ref.d.ts | import * as viewModule from './view';
import { ChangeDetectorRef } from '../change_detection/change_detector_ref';
import { RenderViewRef, RenderFragmentRef } from 'angular2/src/core/render/api';
export declare function internalView(viewRef: ViewRef): viewModule.AppView;
export declare function internalProtoView(protoV... | extends ProtoViewRef {
constructor(_protoView: viewModule.AppProtoView);
}
| ProtoViewRef_ | identifier_name |
test_sync.rs | use std::sync::Arc;
use std::thread;
// use protobuf::CodedInputStream;
// use protobuf::Message;
use quick_protobuf::*;
use super::basic::*;
// test messages are sync
#[test]
fn test_sync() | {
let m = Arc::new({
let mut r = TestTypesSingular::default();
r.int32_field = Some(23);
r
});
let threads: Vec<_> = (0..4)
.map(|_| {
let m_copy = m.clone();
thread::spawn(move || {
let mut bytes = Vec::new();
{
... | identifier_body | |
test_sync.rs | use std::sync::Arc;
use std::thread;
// use protobuf::CodedInputStream;
// use protobuf::Message;
use quick_protobuf::*;
use super::basic::*;
// test messages are sync
#[test]
fn | () {
let m = Arc::new({
let mut r = TestTypesSingular::default();
r.int32_field = Some(23);
r
});
let threads: Vec<_> = (0..4)
.map(|_| {
let m_copy = m.clone();
thread::spawn(move || {
let mut bytes = Vec::new();
{
... | test_sync | identifier_name |
test_sync.rs | use std::sync::Arc;
use std::thread;
// use protobuf::CodedInputStream;
// use protobuf::Message;
use quick_protobuf::*;
use super::basic::*;
// test messages are sync
#[test]
fn test_sync() {
let m = Arc::new({
let mut r = TestTypesSingular::default();
r.int32_field = Some(23);
r
});... | let mut reader = BytesReader::from_bytes(&bytes);
let read = TestTypesSingular::from_reader(&mut reader, &bytes).unwrap();
read.int32_field
})
})
.collect();
let results = threads
.into_iter()
.map(|t| t.join().unwrap())
... | {
let mut writer = Writer::new(&mut bytes);
m_copy.write_message(&mut writer).unwrap();
} | random_line_split |
test_carrot.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compli... | (self):
"""Test that ConnectionPool recycles a single connection."""
conn1 = self.rpc.ConnectionPool.get()
self.rpc.ConnectionPool.put(conn1)
conn2 = self.rpc.ConnectionPool.get()
self.rpc.ConnectionPool.put(conn2)
self.assertEqual(conn1, conn2)
| test_connectionpool_single | identifier_name |
test_carrot.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compli... |
def test_connectionpool_single(self):
"""Test that ConnectionPool recycles a single connection."""
conn1 = self.rpc.ConnectionPool.get()
self.rpc.ConnectionPool.put(conn1)
conn2 = self.rpc.ConnectionPool.get()
self.rpc.ConnectionPool.put(conn2)
self.assertEqual(conn... | super(RpcCarrotTestCase, self).tearDown() | identifier_body |
test_carrot.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compli... | def tearDown(self):
super(RpcCarrotTestCase, self).tearDown()
def test_connectionpool_single(self):
"""Test that ConnectionPool recycles a single connection."""
conn1 = self.rpc.ConnectionPool.get()
self.rpc.ConnectionPool.put(conn1)
conn2 = self.rpc.ConnectionPool.get()... | class RpcCarrotTestCase(common._BaseRpcTestCase):
def setUp(self):
self.rpc = impl_carrot
super(RpcCarrotTestCase, self).setUp()
| random_line_split |
conf.py | # -*- coding: utf-8 -*-
#
# Phaser Editor documentation build configuration file, created by
# sphinx-quickstart on Thu May 25 08:35:14 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.... |
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The name of the Pygments (syntax highlighting) style to use.
# pyg... | # for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None | random_line_split |
Graph2d.js | var Emitter = require('emitter-component');
var Hammer = require('../module/hammer');
var moment = require('../module/moment');
var util = require('../util');
var DataSet = require('../DataSet');
var DataView = require('../DataView');
var Range = require('./Range');
var Core = require('./Core');
var TimeAxis = require(... | else if (util.hasParent(element, this.linegraph.legendLeft.dom.frame)) {what = 'legend';}
else if (util.hasParent(element, this.linegraph.legendRight.dom.frame)) {what = 'legend';}
else if (customTime != null) {what = 'custom-time';}
else if (util.hasParent(element, this.currentTime.bar)) ... | else if (this.timeAxis2 && util.hasParent(element, this.timeAxis2.dom.foreground)) {what = 'axis';}
else if (util.hasParent(element, this.linegraph.yAxisLeft.dom.frame)) {what = 'data-axis';}
else if (util.hasParent(element, this.linegraph.yAxisRight.dom.frame)) {what = 'data-axis';} | random_line_split |
Graph2d.js | var Emitter = require('emitter-component');
var Hammer = require('../module/hammer');
var moment = require('../module/moment');
var util = require('../util');
var DataSet = require('../DataSet');
var DataView = require('../DataView');
var Range = require('./Range');
var Core = require('./Core');
var TimeAxis = require(... |
// Extend the functionality from Core
Graph2d.prototype = new Core();
Graph2d.prototype.setOptions = function (options) {
// validate options
let errorFound = Validator.validate(options, allOptions);
if (errorFound === true) {
console.log('%cErrors have been found in the supplied options object.', printSty... | {
// if the third element is options, the forth is groups (optionally);
if (!(Array.isArray(groups) || groups instanceof DataSet || groups instanceof DataView) && groups instanceof Object) {
var forthArgument = options;
options = groups;
groups = forthArgument;
}
var me = this;
this.defaultOption... | identifier_body |
Graph2d.js | var Emitter = require('emitter-component');
var Hammer = require('../module/hammer');
var moment = require('../module/moment');
var util = require('../util');
var DataSet = require('../DataSet');
var DataView = require('../DataView');
var Range = require('./Range');
var Core = require('./Core');
var TimeAxis = require(... | (container, items, groups, options) {
// if the third element is options, the forth is groups (optionally);
if (!(Array.isArray(groups) || groups instanceof DataSet || groups instanceof DataView) && groups instanceof Object) {
var forthArgument = options;
options = groups;
groups = forthArgument;
}
... | Graph2d | identifier_name |
Graph2d.js | var Emitter = require('emitter-component');
var Hammer = require('../module/hammer');
var moment = require('../module/moment');
var util = require('../util');
var DataSet = require('../DataSet');
var DataView = require('../DataView');
var Range = require('./Range');
var Core = require('./Core');
var TimeAxis = require(... |
// draw for the first time
this._redraw();
}
// Extend the functionality from Core
Graph2d.prototype = new Core();
Graph2d.prototype.setOptions = function (options) {
// validate options
let errorFound = Validator.validate(options, allOptions);
if (errorFound === true) {
console.log('%cErrors have bee... | {
this.setItems(items);
} | conditional_block |
boost_query.rs | use crate::fastfield::AliveBitSet;
use crate::query::explanation::does_not_match;
use crate::query::{Explanation, Query, Scorer, Weight};
use crate::{DocId, DocSet, Score, Searcher, SegmentReader, Term};
use std::collections::BTreeMap;
use std::fmt;
/// `BoostQuery` is a wrapper over a query used to boost its score.
/... | }
fn query_terms(&self, terms: &mut BTreeMap<Term, bool>) {
self.query.query_terms(terms)
}
}
pub(crate) struct BoostWeight {
weight: Box<dyn Weight>,
boost: Score,
}
impl BoostWeight {
pub fn new(weight: Box<dyn Weight>, boost: Score) -> Self {
BoostWeight { weight, boost }
... | } else {
weight_without_boost
};
Ok(boosted_weight) | random_line_split |
boost_query.rs | use crate::fastfield::AliveBitSet;
use crate::query::explanation::does_not_match;
use crate::query::{Explanation, Query, Scorer, Weight};
use crate::{DocId, DocSet, Score, Searcher, SegmentReader, Term};
use std::collections::BTreeMap;
use std::fmt;
/// `BoostQuery` is a wrapper over a query used to boost its score.
/... |
let mut explanation =
Explanation::new(format!("Boost x{} of ...", self.boost), scorer.score());
let underlying_explanation = self.weight.explain(reader, doc)?;
explanation.add_detail(underlying_explanation);
Ok(explanation)
}
fn count(&self, reader: &SegmentReader)... | {
return Err(does_not_match(doc));
} | conditional_block |
boost_query.rs | use crate::fastfield::AliveBitSet;
use crate::query::explanation::does_not_match;
use crate::query::{Explanation, Query, Scorer, Weight};
use crate::{DocId, DocSet, Score, Searcher, SegmentReader, Term};
use std::collections::BTreeMap;
use std::fmt;
/// `BoostQuery` is a wrapper over a query used to boost its score.
/... |
fn size_hint(&self) -> u32 {
self.underlying.size_hint()
}
fn count(&mut self, alive_bitset: &AliveBitSet) -> u32 {
self.underlying.count(alive_bitset)
}
fn count_including_deleted(&mut self) -> u32 {
self.underlying.count_including_deleted()
}
}
impl<S: Scorer> Scor... | {
self.underlying.doc()
} | identifier_body |
boost_query.rs | use crate::fastfield::AliveBitSet;
use crate::query::explanation::does_not_match;
use crate::query::{Explanation, Query, Scorer, Weight};
use crate::{DocId, DocSet, Score, Searcher, SegmentReader, Term};
use std::collections::BTreeMap;
use std::fmt;
/// `BoostQuery` is a wrapper over a query used to boost its score.
/... | (&mut self) -> DocId {
self.underlying.advance()
}
fn seek(&mut self, target: DocId) -> DocId {
self.underlying.seek(target)
}
fn fill_buffer(&mut self, buffer: &mut [DocId]) -> usize {
self.underlying.fill_buffer(buffer)
}
fn doc(&self) -> u32 {
self.underlyin... | advance | identifier_name |
tab_group_test.ts | // Copyright 2020 The Chromium Authors. All rights reserved. |
import {TabGroupElement} from 'chrome://tab-strip.top-chrome/tab_group.js';
import {TabsApiProxyImpl} from 'chrome://tab-strip.top-chrome/tabs_api_proxy.js';
import {assertEquals} from 'chrome://webui-test/chai_assert.js';
import {TestTabsApiProxy} from './test_tabs_api_proxy.js';
suite('TabGroup', () => {
const... | // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'chrome://tab-strip.top-chrome/tab.js';
import 'chrome://tab-strip.top-chrome/tab_group.js'; | random_line_split |
comparator.rs | #[cfg(test)]
mod comparator {
use libc::c_char;
use utils::{tmpdir, db_put_simple};
use leveldb::database::{Database};
use leveldb::iterator::Iterable;
use leveldb::options::{Options,ReadOptions};
use leveldb::comparator::{Comparator,OrdComparator};
use std::cmp::Ordering;
struct ReverseComparator {}... | }
fn compare(&self, a: &[u8], b: &[u8]) -> Ordering {
b.cmp(a)
}
}
#[test]
fn test_comparator() {
let comparator: ReverseComparator = ReverseComparator {};
let mut opts = Options::new();
opts.create_if_missing = true;
let tmp = tmpdir("reverse_comparator");
let database =... |
fn name(&self) -> *const c_char {
"reverse".as_ptr() as *const c_char | random_line_split |
comparator.rs | #[cfg(test)]
mod comparator {
use libc::c_char;
use utils::{tmpdir, db_put_simple};
use leveldb::database::{Database};
use leveldb::iterator::Iterable;
use leveldb::options::{Options,ReadOptions};
use leveldb::comparator::{Comparator,OrdComparator};
use std::cmp::Ordering;
struct ReverseComparator {}... | () {
let comparator: ReverseComparator = ReverseComparator {};
let mut opts = Options::new();
opts.create_if_missing = true;
let tmp = tmpdir("reverse_comparator");
let database = &mut Database::open_with_comparator(tmp.path(), opts, comparator).unwrap();
db_put_simple(database, b"1", &[1]);
... | test_comparator | identifier_name |
PaginationDropdown.tsx | import { DropdownItem, DropdownMenu, DropdownToggle, UncontrolledDropdown } from 'reactstrap';
interface PaginationDropdownProps {
ranges: number[];
value: number;
setValue: (newValue: number) => void;
toggleClassName?: string;
}
const PaginationDropdown = ({ toggleClassName, ranges, value, setValue }: Pagina... | {ranges.map((itemsPerPage) => (
<DropdownItem key={itemsPerPage} active={itemsPerPage === value} onClick={() => setValue(itemsPerPage)}>
<b>{itemsPerPage}</b> items per page
</DropdownItem>
))}
<DropdownItem divider />
<DropdownItem disabled={value === Infinity} onClick... | Paginate
</DropdownToggle>
<DropdownMenu right> | random_line_split |
manticore_protocol_spdm_GetVersion__req_to_wire.rs | // Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details. | // !! DO NOT EDIT !!
// To regenerate this file, run `fuzz/generate_proto_tests.py`.
#![no_main]
#![allow(non_snake_case)]
use libfuzzer_sys::fuzz_target;
use manticore::protocol::Command;
use manticore::protocol::wire::ToWire;
use manticore::protocol::borrowed::AsStatic;
use manticore::protocol::borrowed::Borrowed;... | // SPDX-License-Identifier: Apache-2.0
| random_line_split |
ArrayUtils.ts | class ArrayUtils {
static CASEINSENSITIVE = 1;
static DESCENDING = 2;
static UNIQUESORT = 4;
static RETURNINDEXEDARRAY = 8;
static NUMERIC = 16;
/**
* Checks if an array contains a specific value
*/
public static inArray( array:any[], value:any ):boolean{
return (array.indexOf( value ) != -1);
}
/**
... |
/**
* Simple joins a Array to a String
*/
public static simpleJoin( array:any[], sort:boolean = true, pre:string = ' - ', post:string = '\n', empty:string = '(empty)' ):string{
if( !array ){
return '(null array)';
}
if( array.length == 0 ){
return empty;
}
if( sort ){
array = array.concat().s... | {
if( !array ) array = [];
for( var i:number = 0; i < amount; i++ ){
array.push( element );
}
return array;
} | identifier_body |
ArrayUtils.ts | class ArrayUtils {
static CASEINSENSITIVE = 1;
static DESCENDING = 2;
static UNIQUESORT = 4;
static RETURNINDEXEDARRAY = 8;
static NUMERIC = 16;
/**
* Checks if an array contains a specific value
*/
public static inArray( array:any[], value:any ):boolean{
return (array.indexOf( value ) != -1);
}
/**
... | ( array:any[], value:any ):boolean{
var len:number = array.length;
for( var i:number = len; i > -1; i-- ){
if( array[i] === value ){
array.splice( i, 1 );
return true;
}
}
return false;
}
/**
* Create a new array that only contains unique instances of objects
* in the specified array.
*
... | removeValueFromArrayOnce | identifier_name |
ArrayUtils.ts | class ArrayUtils {
static CASEINSENSITIVE = 1;
static DESCENDING = 2;
static UNIQUESORT = 4;
static RETURNINDEXEDARRAY = 8;
static NUMERIC = 16;
/**
* Checks if an array contains a specific value
*/
public static inArray( array:any[], value:any ):boolean{
return (array.indexOf( value ) != -1);
}
/**
... | if( array2.indexOf( array1[i] ) == -1 ) ret.push( array1[i] );
}
return ret;
}
/**
* Returs the items that are in both arrays
*/
public static intersect( array1:any[], array2:any[] ):any[]{
var ret:any[] = [];
var i:number;
for( i = 0; i < array1.length; i++ ){
if( array2.indexOf( array1[i] ) ... | */
public static getUniqueFirst( array1:any[], array2:any[] ):any[]{
var ret:any[] = [];
for( var i:number = 0; i < array1.length; i++ ){ | random_line_split |
receiver.js | let connectionIdx = 0;
let messageIdx = 0;
function addConnection(connection) {
connection.connectionId = ++connectionIdx;
addMessage('New connection #' + connectionIdx);
connection.addEventListener('message', function(event) {
messageIdx++;
const data = JSON.parse(event.data);
const logString = 'Me... | (message) {
const fruit = message.toLowerCase();
if (fruit in fruitEmoji) {
document.querySelector('#main').textContent = fruitEmoji[fruit];
}
};
document.addEventListener('DOMContentLoaded', function() {
if (navigator.presentation.receiver) {
navigator.presentation.receiver.connectionList.then(list =>... | maybeSetFruit | identifier_name |
receiver.js | let connectionIdx = 0;
let messageIdx = 0;
function addConnection(connection) {
connection.connectionId = ++connectionIdx;
addMessage('New connection #' + connectionIdx);
connection.addEventListener('message', function(event) {
messageIdx++;
const data = JSON.parse(event.data);
const logString = 'Me... |
document.addEventListener('DOMContentLoaded', function() {
if (navigator.presentation.receiver) {
navigator.presentation.receiver.connectionList.then(list => {
list.connections.map(connection => addConnection(connection));
list.addEventListener('connectionavailable', function(event) {
addConn... | random_line_split | |
receiver.js | let connectionIdx = 0;
let messageIdx = 0;
function addConnection(connection) {
connection.connectionId = ++connectionIdx;
addMessage('New connection #' + connectionIdx);
connection.addEventListener('message', function(event) {
messageIdx++;
const data = JSON.parse(event.data);
const logString = 'Me... | ;
function maybeSetFruit(message) {
const fruit = message.toLowerCase();
if (fruit in fruitEmoji) {
document.querySelector('#main').textContent = fruitEmoji[fruit];
}
};
document.addEventListener('DOMContentLoaded', function() {
if (navigator.presentation.receiver) {
navigator.presentation.receiver.co... | {
const listItem = document.createElement("li");
if (language) {
listItem.lang = language;
}
listItem.textContent = content;
document.querySelector("#message-list").appendChild(listItem);
} | identifier_body |
receiver.js | let connectionIdx = 0;
let messageIdx = 0;
function addConnection(connection) {
connection.connectionId = ++connectionIdx;
addMessage('New connection #' + connectionIdx);
connection.addEventListener('message', function(event) {
messageIdx++;
const data = JSON.parse(event.data);
const logString = 'Me... |
};
document.addEventListener('DOMContentLoaded', function() {
if (navigator.presentation.receiver) {
navigator.presentation.receiver.connectionList.then(list => {
list.connections.map(connection => addConnection(connection));
list.addEventListener('connectionavailable', function(event) {
add... | {
document.querySelector('#main').textContent = fruitEmoji[fruit];
} | conditional_block |
loader.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 ... |
use collections::{HashMap, HashSet};
use flate;
use time;
pub static MACOS_DLL_PREFIX: &'static str = "lib";
pub static MACOS_DLL_SUFFIX: &'static str = ".dylib";
pub static WIN32_DLL_PREFIX: &'static str = "";
pub static WIN32_DLL_SUFFIX: &'static str = ".dll";
pub static LINUX_DLL_PREFIX: &'static str = "lib";
pu... | random_line_split | |
loader.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 ... |
}
let data = lib.metadata.as_slice();
let crate_id = decoder::get_crate_id(data);
note_crateid_attr(self.sess.diagnostic(), &crate_id);
}
None
}
}
}
// Attempts to match the requ... | {} | conditional_block |
loader.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 ... | {
pub ident: ~str,
pub dylib: Option<Path>,
pub rlib: Option<Path>
}
impl CratePaths {
fn paths(&self) -> Vec<Path> {
match (&self.dylib, &self.rlib) {
(&None, &None) => vec!(),
(&Some(ref p), &None) |
(&None, &Some(ref p)) => vec!(p... | CratePaths | identifier_name |
loader.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 ... |
}
impl<'a> Context<'a> {
pub fn maybe_load_library_crate(&mut self) -> Option<Library> {
self.find_library_crate()
}
pub fn load_library_crate(&mut self) -> Library {
match self.find_library_crate() {
Some(t) => t,
None => {
self.report_load_errs();... | {
match (&self.dylib, &self.rlib) {
(&None, &None) => vec!(),
(&Some(ref p), &None) |
(&None, &Some(ref p)) => vec!(p.clone()),
(&Some(ref p1), &Some(ref p2)) => vec!(p1.clone(), p2.clone()),
}
} | identifier_body |
test_deprecations.py | import logging
import pytest
from traitlets.config import Config
from dockerspawner import DockerSpawner
def | (caplog):
cfg = Config()
cfg.DockerSpawner.image_whitelist = {"1.0": "jupyterhub/singleuser:1.0"}
log = logging.getLogger("testlog")
spawner = DockerSpawner(config=cfg, log=log)
assert caplog.record_tuples == [
(
log.name,
logging.WARNING,
'DockerSpawner.... | test_deprecated_config | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.