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 |
|---|---|---|---|---|
record.rs | use std::ops::Deref;
use config::gobjects::GObject;
use env::Env;
use library;
use nameutil::*;
use super::*;
use super::imports::Imports;
use super::info_base::InfoBase;
use traits::*;
#[derive(Default)]
pub struct Info {
pub base: InfoBase,
}
impl Deref for Info {
type Target = InfoBase;
fn deref(&sel... | let record: &library::Record = match type_.maybe_ref() {
Some(record) => record,
None => return None,
};
let mut imports = Imports::new();
imports.add("glib::translate::*", None);
imports.add("ffi", None);
let mut functions = functions::analyze(env, &record.functions, record_ti... | let type_ = env.type_(record_tid);
let name: String = split_namespace_name(&full_name).1.into();
| random_line_split |
g.py | # coding=utf-8
"""g[ravity] class."""
from foamfile import FoamFile, foam_file_from_file
from collections import OrderedDict
class | (FoamFile):
"""G (gravity) class."""
# set default valus for this class
__default_values = OrderedDict()
__default_values['dimensions'] = '[0 1 -2 0 0 0 0]'
__default_values['#include'] = None
__default_values['value'] = '(0 0 -9.81)'
def __init__(self, values=None):
"""Init class.... | G | identifier_name |
g.py | # coding=utf-8
"""g[ravity] class."""
from foamfile import FoamFile, foam_file_from_file
from collections import OrderedDict
class G(FoamFile):
"""G (gravity) class."""
# set default valus for this class
__default_values = OrderedDict()
__default_values['dimensions'] = '[0 1 -2 0 0 0 0]'
__defaul... |
@classmethod
def from_file(cls, filepath):
"""Create a FoamFile from a file.
Args:
filepath: Full file path to dictionary.
"""
return cls(values=foam_file_from_file(filepath, cls.__name__))
@property
def dimensions(self):
return self.values['dimens... | """Init class."""
FoamFile.__init__(self, name='g',
cls='uniformDimensionedVectorField',
location='constant',
default_values=self.__default_values,
values=values) | identifier_body |
g.py | # coding=utf-8
"""g[ravity] class."""
from foamfile import FoamFile, foam_file_from_file
from collections import OrderedDict
class G(FoamFile):
"""G (gravity) class."""
# set default valus for this class
__default_values = OrderedDict()
__default_values['dimensions'] = '[0 1 -2 0 0 0 0]'
__defaul... | return cls(values=foam_file_from_file(filepath, cls.__name__))
@property
def dimensions(self):
return self.values['dimensions']
@property
def value(self):
"""Gravity vector."""
return eval(self.values['value'].replace(' ', ','))
@value.setter
def value(self, ve... |
Args:
filepath: Full file path to dictionary.
""" | random_line_split |
test_logistic_regression.py | (3, 62000, 0), (4, 71000, 0), (2.4, 61000, 0),
(7.5, 75000, 0), (9.7, 81000, 1), (3.2, 62000, 0),
(7.9, 88000, 0), (4.7, 44000, 1), (2.5, 55000, 0),
(1.6, 41000, 0), (6.7, 64000, 1), (6.9, 66000, 1),
(7.9, 78000, 1), (8.1, 102000, 0), (5.3, 48000, 1),
... | tuples = [
(0.7, 48000, 1), (1.9, 48000, 0), (2.5, 60000, 1),
(4.2, 63000, 0), (6, 76000, 0), (6.5, 69000, 0),
(7.5, 76000, 0), (8.1, 88000, 0), (8.7, 83000, 1),
(10, 83000, 1), (0.8, 43000, 0), (1.8, 60000, 0),
(10, 79000, 1), (6.1, 76000, 0), (1.4, 50000, 0)... | identifier_body | |
test_logistic_regression.py | 00, 1), (4.2, 70000, 0), (7.7, 98000, 0),
(8.2, 85000, 0), (5.4, 88000, 0), (0.1, 46000, 0),
(1.5, 37000, 0), (6.3, 86000, 0), (3.7, 57000, 0),
(8.4, 85000, 0), (2, 42000, 0), (5.8, 69000, 1),
(2.7, 64000, 0), (3.1, 63000, 0), (1.9, 48000, 0),
(10, 72000, 1), ... | true_positives += 1 | conditional_block | |
test_logistic_regression.py | 0, 0), (5.3, 48000, 1),
(8.5, 66000, 1), (0.2, 56000, 0), (6, 69000, 0),
(7.5, 77000, 0), (8, 86000, 0), (4.4, 68000, 0),
(4.9, 75000, 0), (1.5, 60000, 0), (2.2, 50000, 0),
(3.4, 49000, 1), (4.2, 70000, 0), (7.7, 98000, 0),
(8.2, 85000, 0), (5.4, 88000, 0), (0... |
rescaled = munge.rescale(x)
| random_line_split | |
test_logistic_regression.py | (self):
tuples = [
(0.7, 48000, 1), (1.9, 48000, 0), (2.5, 60000, 1),
(4.2, 63000, 0), (6, 76000, 0), (6.5, 69000, 0),
(7.5, 76000, 0), (8.1, 88000, 0), (8.7, 83000, 1),
(10, 83000, 1), (0.8, 43000, 0), (1.8, 60000, 0),
(10, 79000, 1), (6.1, 76000, 0),... | setUp | identifier_name | |
list.js | define(['summernote/core/func'], function (func) {
/**
* list utils
*/
var list = (function () {
/**
* returns the first element of an array.
* @param {Array} array
*/
var head = function (array) {
return array[0];
};
/**
* returns the last element of an array.
... | var idx = array.indexOf(item);
if (idx === -1) { return null; }
return array[idx - 1];
};
var all = function (array, pred) {
for (var idx = 0, len = array.length; idx < len; idx ++) {
if (!pred(array[idx])) {
return false;
}
}
return true;
};... | var prev = function (array, item) { | random_line_split |
list.js | define(['summernote/core/func'], function (func) {
/**
* list utils
*/
var list = (function () {
/**
* returns the first element of an array.
* @param {Array} array
*/
var head = function (array) {
return array[0];
};
/**
* returns the last element of an array.
... |
return memo;
}, [[head(array)]]);
};
/**
* returns a copy of the array with all falsy values removed
* @param {Array} array - array
* @param {Function} fn - predicate function for cluster rule
*/
var compact = function (array) {
var aResult = [];
for (var id... | {
memo[memo.length] = [v];
} | conditional_block |
get_message_events.rs | //! [GET /_matrix/client/r0/rooms/{roomId}/messages](https://matrix.org/docs/spec/client_server/r0.6.0#get-matrix-client-r0-rooms-roomid-messages)
use js_int::UInt;
use ruma_api::ruma_api;
use ruma_events::{
collections::all::{RoomEvent, StateEvent},
EventJson,
};
use ruma_identifiers::RoomId;
use serde::{Dese... | () {
let room_id = RoomId::try_from("!roomid:example.org").unwrap();
let req = Request {
room_id,
from: "token".into(),
to: Some("token2".into()),
dir: Direction::Backward,
limit: Some(UInt::from(0u32)),
filter: Some(RoomEventFilter... | test_serialize_default_room_event_filter | identifier_name |
get_message_events.rs | //! [GET /_matrix/client/r0/rooms/{roomId}/messages](https://matrix.org/docs/spec/client_server/r0.6.0#get-matrix-client-r0-rooms-roomid-messages)
use js_int::UInt;
use ruma_api::ruma_api;
use ruma_events::{
collections::all::{RoomEvent, StateEvent},
EventJson,
};
use ruma_identifiers::RoomId;
use serde::{Dese... |
}
| {
let room_id = RoomId::try_from("!roomid:example.org").unwrap();
let req = Request {
room_id,
from: "token".into(),
to: Some("token2".into()),
dir: Direction::Backward,
limit: Some(UInt::from(0u32)),
filter: Some(RoomEventFilter::d... | identifier_body |
get_message_events.rs | //! [GET /_matrix/client/r0/rooms/{roomId}/messages](https://matrix.org/docs/spec/client_server/r0.6.0#get-matrix-client-r0-rooms-roomid-messages)
use js_int::UInt;
use ruma_api::ruma_api;
use ruma_events::{
collections::all::{RoomEvent, StateEvent},
EventJson,
};
use ruma_identifiers::RoomId;
use serde::{Dese... | /// returned by a previous request to this endpoint.
#[ruma_api(query)]
pub from: String,
/// The token to stop returning events at.
///
/// This token can be obtained from a prev_batch
/// token returned for each room by the sync endpoint, or from a start or end... |
/// The token to start returning events from.
///
/// This token can be obtained from a
/// prev_batch token returned for each room by the sync API, or from a start or end token | random_line_split |
lock.py | # -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
#
# 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... |
def acquire_for(pid_dir, num_available=1):
"""
Makes sure the process is only run once at the same time with the same name.
Notice that we since we check the process name, different parameters to the same
command can spawn multiple processes at the same time, i.e. running
"/usr/bin/my_process" d... | if my_pid is None:
my_pid = os.getpid()
my_cmd = getpcmd(my_pid)
if six.PY3:
cmd_hash = my_cmd.encode('utf8')
else:
cmd_hash = my_cmd
pid_file = os.path.join(pid_dir, hashlib.md5(cmd_hash).hexdigest()) + '.pid'
return my_pid, my_cmd, pid_file | identifier_body |
lock.py | # -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
#
# 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... |
pid_cmds[str(my_pid)] = my_cmd
# Write pids
pids.add(str(my_pid))
with open(pid_file, 'w') as f:
f.writelines('%s\n' % (pid, ) for pid in filter(pid_cmds.__getitem__, pids))
# Make the file writable by all
if os.name == 'nt':
pass
else:
s = os.stat(pid_file)
... | pass | conditional_block |
lock.py | # -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
#
# 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... | "/usr/bin/my_process" does not prevent anyone from launching
"/usr/bin/my_process --foo bar".
"""
my_pid, my_cmd, pid_file = get_info(pid_dir)
# Check if there is a pid file corresponding to this name
if not os.path.exists(pid_dir):
os.mkdir(pid_dir)
os.chmod(pid_dir, 0o777)
... |
Notice that we since we check the process name, different parameters to the same
command can spawn multiple processes at the same time, i.e. running | random_line_split |
lock.py | # -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
#
# 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... | (pid_dir, num_available=1):
"""
Makes sure the process is only run once at the same time with the same name.
Notice that we since we check the process name, different parameters to the same
command can spawn multiple processes at the same time, i.e. running
"/usr/bin/my_process" does not prevent an... | acquire_for | identifier_name |
Collection.js | /**
* A utility class to help make it easier to access the data stores
* @extends {Map}
*/
class Collection extends Map {
/**
* Returns an ordered array of the values of this collection.
* @returns {array}
* @example
* // identical to:
* Array.from(collection.values());
*/
array() {
return ... |
/**
* If the items in this collection have a delete method (e.g. messages), invoke
* the delete method. Returns an array of promises
* @returns {Promise[]}
*/
deleteAll() {
const returns = [];
for (const item of this.values()) {
if (item.delete) returns.push(item.delete());
}
ret... | {
const arr = this.array();
return arr[Math.floor(Math.random() * arr.length)];
} | identifier_body |
Collection.js | /**
* A utility class to help make it easier to access the data stores
* @extends {Map}
*/
class Collection extends Map {
/**
* Returns an ordered array of the values of this collection.
* @returns {array}
* @example
* // identical to:
* Array.from(collection.values());
*/
array() {
return ... | * @param {string} key The key to filter by
* @param {*} value The expected value
* @returns {array}
* @example
* collection.getAll('username', 'Bob');
*/
findAll(key, value) {
if (typeof key !== 'string') throw new TypeError('key must be a string');
if (typeof value === 'undefined') throw ne... |
/**
* Returns an array of items where `item[key] === value` of the collection | random_line_split |
Collection.js | /**
* A utility class to help make it easier to access the data stores
* @extends {Map}
*/
class Collection extends Map {
/**
* Returns an ordered array of the values of this collection.
* @returns {array}
* @example
* // identical to:
* Array.from(collection.values());
*/
array() {
return ... | (...args) {
return this.array().map(...args);
}
}
module.exports = Collection;
| map | identifier_name |
server.js | var express = require('express');
var app = express();
var path = require('path');
var session = require('express-session');
var bodyParser = require('body-parser')
var fs = require('fs');
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json... | // do not clear the list
if (req.body.length==0) {
resp.end();
}
// this should be used only for reordering
db.sections.remove({}, function(err, res) {
if (err) console.log(err);
db.sections.insert(req.body, function(err, res) {
if (err) console.log("err after insert",err);
resp.end();
});
});
});
... | random_line_split | |
server.js | var express = require('express');
var app = express();
var path = require('path');
var session = require('express-session');
var bodyParser = require('body-parser')
var fs = require('fs');
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json... |
});
app.post("/sections/replace", function(req,resp) {
// do not clear the list
if (req.body.length==0) {
resp.end();
}
// this should be used only for reordering
db.sections.remove({}, function(err, res) {
if (err) console.log(err);
db.sections.insert(req.body, function(err, res) {
if (err) console.lo... | {
res.send(false);
} | conditional_block |
flavors_extraspecs.py | # Copyright 2010 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | raise webob.exc.HTTPConflict(explanation=e.format_message())
except exception.FlavorNotFound as e:
raise webob.exc.HTTPNotFound(explanation=e.format_message())
return body
@extensions.expected_errors((400, 404, 409))
@validation.schema(flavors_extraspecs.update)
def ... | flavor = objects.Flavor.get_by_flavor_id(context, flavor_id)
flavor.extra_specs = dict(flavor.extra_specs, **specs)
flavor.save()
except exception.FlavorExtraSpecUpdateCreateFailed as e: | random_line_split |
flavors_extraspecs.py | # Copyright 2010 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... |
@extensions.expected_errors(())
def index(self, req, flavor_id):
"""Returns the list of extra specs for a given flavor."""
context = req.environ['nova.context']
authorize(context, action='index')
return self._get_extra_specs(context, flavor_id)
# NOTE(gmann): Here should b... | for key, value in specs.iteritems():
try:
if isinstance(value, (six.integer_types, float)):
value = six.text_type(value)
utils.check_string_length(value, 'extra_specs value',
max_length=255)
exc... | identifier_body |
flavors_extraspecs.py | # Copyright 2010 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... | (self, req, flavor_id, id, body):
context = req.environ['nova.context']
authorize(context, action='update')
self._check_extra_specs_value(body)
if id not in body:
expl = _('Request body and URI mismatch')
raise webob.exc.HTTPBadRequest(explanation=expl)
t... | update | identifier_name |
flavors_extraspecs.py | # Copyright 2010 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requ... |
except exception.InvalidInput as error:
raise webob.exc.HTTPBadRequest(
explanation=error.format_message())
@extensions.expected_errors(())
def index(self, req, flavor_id):
"""Returns the list of extra specs for a given flavor."""
context =... | value = six.text_type(value)
utils.check_string_length(value, 'extra_specs value',
max_length=255) | conditional_block |
test_LD_X_decr.py | #! /usr/bin/env python
###############################################################################
#
# simulavr - A simulator for the Atmel AVR family of microcontrollers.
# Copyright (C) 2001, 2002 Theodore A. Roth
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of th... |
def analyze_results(self):
self.reg_changed.extend( [self.Rd, Reg.R26, Reg.R27] )
# check that result is correct
expect = self.Vd
got = self.anal_regs[self.Rd]
if expect != got:
self.fail('LD_X_decr: expect=%02x, got=%02x' % (expect, got))
# check that X was decremented
expect = self.X - 1
... | self.setup_regs[self.Rd] = 0
self.setup_regs[Reg.R26] = (self.X & 0xff)
self.setup_regs[Reg.R27] = ((self.X >> 8) & 0xff)
# set up the val in memory (memory is read after X is decremented,
# thus we need to write to memory _at_ X - 1)
self.mem_byte_write( self.X - 1, self.Vd )
# Return the raw opcode
re... | identifier_body |
test_LD_X_decr.py | #! /usr/bin/env python
###############################################################################
#
# simulavr - A simulator for the Atmel AVR family of microcontrollers.
# Copyright (C) 2001, 2002 Theodore A. Roth
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of th... | (base_test.opcode_test):
"""Generic test case for testing LD_X_decr opcode.
LD_X_decr - Load Indirect from data space to Register using index X and
pre decrement X.
Operation: X <- X - 1 then Rd <- (X)
opcode is '1001 000d dddd 1110' where 0 <= d <= 31 and d != {26,27}
Only registers PC, R26, R27 and Rd shoul... | base_LD_X_decr | identifier_name |
test_LD_X_decr.py | #! /usr/bin/env python
###############################################################################
#
# simulavr - A simulator for the Atmel AVR family of microcontrollers.
# Copyright (C) 2001, 2002 Theodore A. Roth
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of th... |
exec code
| for x in (0x10f, 0x1ff):
for v in (0xaa, 0x55):
args = (d,x,v)*4
code += template % args | conditional_block |
test_LD_X_decr.py | #! /usr/bin/env python
###############################################################################
#
# simulavr - A simulator for the Atmel AVR family of microcontrollers.
# Copyright (C) 2001, 2002 Theodore A. Roth
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of th... | code += template % args
exec code | code = ''
for d in range(0,26)+range(28,32):
for x in (0x10f, 0x1ff):
for v in (0xaa, 0x55):
args = (d,x,v)*4 | random_line_split |
navbar.ts | // source: pages/nodes.ts
/// <reference path="../external/mithril/mithril.d.ts" />
/// <reference path="../../typings/lodash/lodash.d.ts" />
/// <reference path="../util/property.ts" />
// Author: Matt Tracy (matt@cockroachlabs.com)
module Components {
"use strict";
/**
* NavigationBar is a general purpose c... | } | )
));
}
} | random_line_split |
navbar.ts | // source: pages/nodes.ts
/// <reference path="../external/mithril/mithril.d.ts" />
/// <reference path="../../typings/lodash/lodash.d.ts" />
/// <reference path="../util/property.ts" />
// Author: Matt Tracy (matt@cockroachlabs.com)
module Components {
"use strict";
/**
* NavigationBar is a general purpose c... |
}
}
| {
return m("ul.navigation", _.map(ts.targets(), (t: Target) =>
m("li",
{
className: ts.isActive(t) ? "active" : ""
},
m("a",
{
config: m.route,
href: ts.baseRoute + t.route
},
t.title)
)
... | identifier_body |
navbar.ts | // source: pages/nodes.ts
/// <reference path="../external/mithril/mithril.d.ts" />
/// <reference path="../../typings/lodash/lodash.d.ts" />
/// <reference path="../util/property.ts" />
// Author: Matt Tracy (matt@cockroachlabs.com)
module Components {
"use strict";
/**
* NavigationBar is a general purpose c... | (ts: TargetSet): any {}
export function view(ctrl: any, ts: TargetSet): _mithril.MithrilVirtualElement {
return m("ul.navigation", _.map(ts.targets(), (t: Target) =>
m("li",
{
className: ts.isActive(t) ? "active" : ""
},
m("a",
{
con... | controller | identifier_name |
checkbox-as-radio.component.ts | import { ChangeDetectionStrategy, Component, OnInit, ViewChild } from '@angular/core'; | selector: 'app-checkbox-as-radio',
templateUrl: './checkbox-as-radio.component.html',
styleUrls: ['./checkbox-as-radio.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CheckboxAsRadioComponent implements OnInit {
public configuration: Config;
public columns: Columns[];
pub... | import { Company, data } from '../../../assets/data';
import { API, APIDefinition, Columns, Config, DefaultConfig } from 'ngx-easy-table';
@Component({ | random_line_split |
checkbox-as-radio.component.ts | import { ChangeDetectionStrategy, Component, OnInit, ViewChild } from '@angular/core';
import { Company, data } from '../../../assets/data';
import { API, APIDefinition, Columns, Config, DefaultConfig } from 'ngx-easy-table';
@Component({
selector: 'app-checkbox-as-radio',
templateUrl: './checkbox-as-radio.compone... | ($event: { event: string; value: { rowId: number } }): void {
switch ($event.event) {
case 'onCheckboxSelect':
this.table.apiEvent({
type: API.toggleCheckbox,
value: this.selected,
});
this.selected = $event.value.rowId;
this.table.apiEvent({
type:... | eventEmitted | identifier_name |
checkbox-as-radio.component.ts | import { ChangeDetectionStrategy, Component, OnInit, ViewChild } from '@angular/core';
import { Company, data } from '../../../assets/data';
import { API, APIDefinition, Columns, Config, DefaultConfig } from 'ngx-easy-table';
@Component({
selector: 'app-checkbox-as-radio',
templateUrl: './checkbox-as-radio.compone... |
eventEmitted($event: { event: string; value: { rowId: number } }): void {
switch ($event.event) {
case 'onCheckboxSelect':
this.table.apiEvent({
type: API.toggleCheckbox,
value: this.selected,
});
this.selected = $event.value.rowId;
this.table.apiEvent({... | {
this.configuration = { ...DefaultConfig };
this.configuration.checkboxes = true;
this.columns = [
{ key: 'name', title: 'Name' },
{ key: 'company', title: 'Company' },
{ key: 'name', title: 'Name' },
{ key: 'phone', title: 'Phone' },
];
this.data = data;
} | identifier_body |
Component.js | class.constructor.call(this);
if(this.baseAction){
this.baseAction.addComponent(this);
}
this.initComponent();
if(this.plugins){
if(Ext.isArray(this.plugins)){
for(var i = 0, len = this.plugins.length; i < len; i++){
this.plugins[i].init(this);
... |
}
if(this.stateful !== false){
this.initState(config);
}
if(this.applyTo){
this.applyToMarkup(this.applyTo);
delete this.applyTo;
}else if(this.renderTo){
this.render(this.renderTo);
delete this.renderTo;
}
};
// private
Ext.Component.AUTO_ID = 1000;
... | {
this.plugins.init(this);
} | conditional_block |
Component.js | be
* useful for adding customized styles to the container or any of its children using standard CSS rules.
*/
/**
* @cfg {Object/Array} plugins
* An object or array of objects that will provide custom functionality for this component. The only
* requirement for a valid plugin is that it c... | } | random_line_split | |
test-gui-Gtk.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'zappyk'
import sys, subprocess
from gi.repository import Gtk, Gio
from gi.repository import GLib
###############################################################################
class MyWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__... | (self, widget):
widget.inset
pass
def on_window1_delete_event(self, *args):
Gtk.main_quit(*args)
###############################################################################
class CommandTextView(Gtk.TextView):
''' NICE TEXTVIEW THAT READS THE OUTPUT OF A COMMAND SYNCRONOUSLY '''
... | on_textview1_add | identifier_name |
test-gui-Gtk.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'zappyk'
import sys, subprocess
from gi.repository import Gtk, Gio
from gi.repository import GLib
###############################################################################
class MyWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__... | win.connect("delete-event", lambda wid, event: Gtk.main_quit()) # DEFINING CALLBACKS WITH LAMBDAS
win.set_size_request(200,300)
win.add(cmd)
win.show_all()
cmd.run()
Gtk.main()
#______________________________________________________________________________
#
def test_3():
cmd = CommandTextV... |
win = Gtk.Window() | random_line_split |
test-gui-Gtk.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'zappyk'
import sys, subprocess
from gi.repository import Gtk, Gio
from gi.repository import GLib
###############################################################################
class MyWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__... |
#______________________________________________________________________________
#
def test_2():
cmd = CommandTextView("find")
win = Gtk.Window()
win.connect("delete-event", lambda wid, event: Gtk.main_quit()) # DEFINING CALLBACKS WITH LAMBDAS
win.set_size_request(200,300)
win.add(cmd)
win.show... | return False # RAISED AN ERROR: EXIT AND I DON'T WANT TO SEE YOU ANYMORE | conditional_block |
test-gui-Gtk.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'zappyk'
import sys, subprocess
from gi.repository import Gtk, Gio
from gi.repository import GLib
###############################################################################
class MyWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__... |
button = Gtk.Button()
button.add(Gtk.Arrow(Gtk.ArrowType.LEFT, Gtk.ShadowType.NONE))
box.add(button)
button = Gtk.Button()
button.add(Gtk.Arrow(Gtk.ArrowType.RIGHT, Gtk.ShadowType.NONE))
box.add(button)
#hb.pack_start(box)
self.add(Gtk.TextView())
#__... | def __init__(self):
Gtk.Window.__init__(self, title="Stack Demo")
#CZ#Gtk.Window.__init__(self, title="Stack Demo", type=Gtk.WINDOW_TOPLEVEL)
self.set_border_width(10)
self.set_default_size(400, 200)
#CZ#self.has_toplevel_focus()
#hb = Gtk.HeaderBar()
#hb.props.show_clos... | identifier_body |
servicesNotificacoes.js | angular.module('abastecimentoApp.servicesNotificacoes', []).factory('Notificacao', function ($resource, $http, constantService) {
return {
query: query,
get:get
}
function query(callback) {
$http.get(constantService.baseURL + '/notificacoes')
.then(function (response) {
... | ;
return this.resource;
}).service('popupService', function ($window) {
this.showPopup = function (message) {
return $window.confirm(message);
}
}).service('constantService', function () {
return {
baseURL: 'http://localhost:3000/api'
}
}); | {
$http.get(constantService.baseURL + '/notificacoes/' + id)
.then(function (response) {
if (callback) {
callback(response.data);
}
});
} | identifier_body |
servicesNotificacoes.js | angular.module('abastecimentoApp.servicesNotificacoes', []).factory('Notificacao', function ($resource, $http, constantService) {
return {
query: query,
get:get
}
function | (callback) {
$http.get(constantService.baseURL + '/notificacoes')
.then(function (response) {
if (callback) {
callback(response.data);
}
});
};
function get(id, callback) {
$http.get(constantService.baseURL + '/notifica... | query | identifier_name |
servicesNotificacoes.js | angular.module('abastecimentoApp.servicesNotificacoes', []).factory('Notificacao', function ($resource, $http, constantService) {
return {
query: query,
get:get
}
function query(callback) { | if (callback) {
callback(response.data);
}
});
};
function get(id, callback) {
$http.get(constantService.baseURL + '/notificacoes/' + id)
.then(function (response) {
if (callback) {
callback(... | $http.get(constantService.baseURL + '/notificacoes')
.then(function (response) { | random_line_split |
servicesNotificacoes.js | angular.module('abastecimentoApp.servicesNotificacoes', []).factory('Notificacao', function ($resource, $http, constantService) {
return {
query: query,
get:get
}
function query(callback) {
$http.get(constantService.baseURL + '/notificacoes')
.then(function (response) {
... |
});
};
function get(id, callback) {
$http.get(constantService.baseURL + '/notificacoes/' + id)
.then(function (response) {
if (callback) {
callback(response.data);
}
});
};
return this.resource;
}).service... | {
callback(response.data);
} | conditional_block |
sphericalHarmonics.py | # ------------------- Information --------------------- #
# Author: Joey Dumont <joey.dumont@gmail.com> #
# Date created: October 18th, 2013 #
# Date mod. October 18th, 2013 #
# Description: We plot the times it took to compute #
# sets of Wigner symbols of different #
# sizes. #
# ---------------------------... | prec = loadtxt("precisionSph.dat")
# ------------------ Plotting data -------------------- #
fig1 = figure(figsize=(7,3))
ax1 = fig1.add_subplot(111)
ax1.plot(prec[:,0],prec[:,1], 'b-')
ax1.plot(prec[:,0],prec[:,2], 'r')
ax1.plot(prec[:,0],prec[:,3], 'k')
minorLocator = AutoMinorLocator()
ax1.xaxis.set_minor_locat... | # ----------------- Data Importation ------------------ # | random_line_split |
pd.py | ##
## This file is part of the libsigrokdecode project.
##
## Copyright (C) 2012 Iztok Jeras <iztok.jeras@gmail.com>
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the... | self.bit_cnt = 0
return 1
else:
return 0 | self.data_n = self.data_n & ((1 << length) - 1)
self.data = self.data & ((1 << length) - 1)
self.search = 'P' | random_line_split |
pd.py | ##
## This file is part of the libsigrokdecode project.
##
## Copyright (C) 2012 Iztok Jeras <iztok.jeras@gmail.com>
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the... |
else:
self.putx([0, ['ROM command: 0x%02x \'%s\''
% (self.data, 'unrecognized')]])
self.state = 'COMMAND ERROR'
elif self.state == 'GET ROM':
# A 64 bit device address is selected.
# Family code (1 byte) + serial numb... | self.putx([0, ['ROM command: 0x%02x \'%s\''
% (self.data, command[self.data][0])]])
self.state = command[self.data][1] | conditional_block |
pd.py | ##
## This file is part of the libsigrokdecode project.
##
## Copyright (C) 2012 Iztok Jeras <iztok.jeras@gmail.com>
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the... |
def start(self):
self.out_python = self.register(srd.OUTPUT_PYTHON)
self.out_ann = self.register(srd.OUTPUT_ANN)
def putx(self, data):
# Helper function for most annotations.
self.put(self.beg, self.end, self.out_ann, data)
def puty(self, data):
# Helper function ... | self.beg = 0
self.end = 0
self.state = 'COMMAND'
self.bit_cnt = 0
self.search = 'P'
self.data_p = 0x0
self.data_n = 0x0
self.data = 0x0
self.rom = 0x0000000000000000 | identifier_body |
pd.py | ##
## This file is part of the libsigrokdecode project.
##
## Copyright (C) 2012 Iztok Jeras <iztok.jeras@gmail.com>
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the... | (srd.Decoder):
api_version = 2
id = 'onewire_network'
name = '1-Wire network layer'
longname = '1-Wire serial communication bus (network layer)'
desc = 'Bidirectional, half-duplex, asynchronous serial bus.'
license = 'gplv2+'
inputs = ['onewire_link']
outputs = ['onewire_network']
an... | Decoder | identifier_name |
numbers.js | // Math.extend v0.5.0
// Copyright (c) 2008-2009 Laurent Fortin
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, ... |
Object.extend(Number.prototype, {
isNaN: function() {
return isNaN(this);
},
isNull: function() {
return this == 0;
},
isEven: function() {
if(!this.isInteger()) return false;
return(this % 2 ? false : true);
},
isOdd: function() {
if(!this.isInteger()) return false;
... | random_line_split | |
Base_Logging.py | """
Qxf2 Services: A plug-n-play class for logging.
This class wraps around Python's loguru module.
"""
import os, inspect
import pytest,logging
from loguru import logger
from pytest_reportportal import RPLogger, RPLogHandler
class Base_Logging():
"A plug-n-play class for logging"
def __init__(self,log_file_na... |
elif level.lower()== 'warn' or level.lower()=='warning':
self.rp_logger.warning(msg)
elif level.lower()== 'error':
self.rp_logger.error(msg)
elif level.lower()== 'critical':
self.rp_logger.critical(msg)
else:
... | self.rp_logger.info(msg) | conditional_block |
Base_Logging.py | """
Qxf2 Services: A plug-n-play class for logging.
This class wraps around Python's loguru module.
"""
import os, inspect
import pytest,logging
from loguru import logger
from pytest_reportportal import RPLogger, RPLogHandler
class Base_Logging():
"A plug-n-play class for logging"
def | (self,log_file_name=None,level="DEBUG",format="{time:YYYY-MM-DD HH:mm:ss} | {level} | {module} | {message}"):
"Constructor for the logging class"
self.log_file_name=log_file_name
self.log_file_dir = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','log'))
self.level=level
... | __init__ | identifier_name |
Base_Logging.py | """
Qxf2 Services: A plug-n-play class for logging.
This class wraps around Python's loguru module.
"""
import os, inspect
import pytest,logging
from loguru import logger
from pytest_reportportal import RPLogger, RPLogHandler
class Base_Logging():
"A plug-n-play class for logging"
def __init__(self,log_file_na... |
calling_filename = calling_file.split(os.sep)
#This logic bought to you by windows + cygwin + git bash
if len(calling_filename) == 1: #Needed for
calling_filename = calling_file.split('/')
self.calling_module = calling_filename[-1].split('.')[0]
return self.callin... | calling_file = inspect.stack()[-1][1]
if 'runpy' in calling_file:
calling_file = inspect.stack()[4][1] | random_line_split |
Base_Logging.py | """
Qxf2 Services: A plug-n-play class for logging.
This class wraps around Python's loguru module.
"""
import os, inspect
import pytest,logging
from loguru import logger
from pytest_reportportal import RPLogger, RPLogHandler
class Base_Logging():
"A plug-n-play class for logging"
def __init__(self,log_file_na... |
def get_calling_module(self):
"Get the name of the calling module"
calling_file = inspect.stack()[-1][1]
if 'runpy' in calling_file:
calling_file = inspect.stack()[4][1]
calling_filename = calling_file.split(os.sep)
#This logic bought to you by windows + cygw... | "Add an handler sending log messages to a sink"
if test_module_name is None:
test_module_name = self.get_calling_module()
if not os.path.exists(self.log_file_dir):
os.makedirs(self.log_file_dir)
if log_file_name is None:
log_file_name = self.log_file_dir + os.... | identifier_body |
AdvancedPage.js | // @flow
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { Redirect } from 'react-router';
import { connect } from 'react-redux';
import { Button, Header, Icon, Menu, Modal, Segment, Table } from 'semantic-ui-react';
import AccountsCustomJson from '../components/Accounts/Cu... | };
}
export default connect(mapStateToProps, mapDispatchToProps)(AccountsPage); | actions: bindActionCreators({
...AccountActions,
...KeyActions,
...ProcessingActions,
}, dispatch) | random_line_split |
AdvancedPage.js | // @flow
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { Redirect } from 'react-router';
import { connect } from 'react-redux';
import { Button, Header, Icon, Menu, Modal, Segment, Table } from 'semantic-ui-react';
import AccountsCustomJson from '../components/Accounts/Cu... |
const { activeItem } = this.state;
let activeTab = <AccountsCustomJson {...this.props} />;
switch (activeItem) {
default: {
activeTab = <AccountsCustomJson {...this.props} />;
break;
}
}
return (
<ContentBar>
<Segment basic padded attached secondary>
... | {
return <Redirect to="/" />;
} | conditional_block |
AdvancedPage.js | // @flow
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { Redirect } from 'react-router';
import { connect } from 'react-redux';
import { Button, Header, Icon, Menu, Modal, Segment, Table } from 'semantic-ui-react';
import AccountsCustomJson from '../components/Accounts/Cu... | (dispatch) {
return {
actions: bindActionCreators({
...AccountActions,
...KeyActions,
...ProcessingActions,
}, dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(AccountsPage);
| mapDispatchToProps | identifier_name |
user_published.tsx | import styled from 'styled-components'
import Img from '@/Img'
import { theme } from '@/utils/themes'
import css from '@/utils/css'
// import { Wrapper as CommentBlock } from '../desktop_view'
export { HeaderBaseInfo, BaseInfo, FloorNum } from './index'
export const Avatar = styled(Img)<{ avatarSize: number }>`
$... | color: ${theme('comment.floor')};
font-size: 12px;
opacity: 0.8;
margin-top: 5px;
` | ${css.cutRest('200px')};
`};
`
export const CreateDate = styled.div`
${css.flex('align-center')}; | random_line_split |
layout_debug.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/. */
//! Supports writing a trace file created during each layout scope
//! that can be viewed by an external tool to m... | ;
#[macro_export]
macro_rules! layout_debug_scope(
($($arg:tt)*) => (
if cfg!(not(ndebug)) {
layout_debug::Scope::new(format!($($arg)*))
} else {
layout_debug::Scope
}
)
);
#[derive(RustcEncodable)]
struct ScopeData {
name: String,
pre: String,
post:... | Scope | identifier_name |
layout_debug.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/. */
//! Supports writing a trace file created during each layout scope
//! that can be viewed by an external tool to m... | };
*r.borrow_mut() = Some(state);
});
}
/// End the debug layout trace. This will write the layout
/// trace to disk in the current directory. The output
/// file can then be viewed with an external tool.
pub fn end_trace() {
let mut task_state = STATE_KEY.with(|ref r| r.borrow_mut().take().unw... | STATE_KEY.with(|ref r| {
let flow_trace = json::encode(&flow::base(&*flow_root)).unwrap();
let state = State {
scope_stack: vec![box ScopeData::new("root".to_owned(), flow_trace)],
flow_root: flow_root.clone(), | random_line_split |
layout_debug.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/. */
//! Supports writing a trace file created during each layout scope
//! that can be viewed by an external tool to m... |
}
});
}
}
/// Generate a unique ID. This is used for items such as Fragment
/// which are often reallocated but represent essentially the
/// same data.
#[allow(unsafe_blocks)]
pub fn generate_unique_debug_id() -> u16 {
unsafe { DEBUG_ID_COUNTER.fetch_add(1, Ordering::SeqCst) as u16 }
}
/... | {} | conditional_block |
hashing_analyzer.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the Hashing analyzer."""
import unittest
from plaso.containers import analyzer_result
from plaso.analyzers import hashing_analyzer
from plaso.analyzers.hashers import manager
from tests import test_lib as shared_test_lib
from tests.analyzers.hashers import ... | def testHashFile(self):
"""Tests that results are produced correctly."""
analyzer = hashing_analyzer.HashingAnalyzer()
analyzer.SetHasherNames('testhash')
analyzer.Analyze('test data')
results = analyzer.GetResults()
first_result = results[0]
self.assertIsInstance(first_result, analyzer_re... | """Test the Hashing analyzer."""
# pylint: disable=protected-access
@classmethod
def setUpClass(cls):
"""Makes preparations before running any of the tests."""
manager.HashersManager.RegisterHasher(manager_test.TestHasher)
@classmethod
def tearDownClass(cls):
"""Cleans up after running all test... | identifier_body |
hashing_analyzer.py | #!/usr/bin/env python3 | """Tests for the Hashing analyzer."""
import unittest
from plaso.containers import analyzer_result
from plaso.analyzers import hashing_analyzer
from plaso.analyzers.hashers import manager
from tests import test_lib as shared_test_lib
from tests.analyzers.hashers import manager as manager_test
class HashingAnalyzer... | # -*- coding: utf-8 -*- | random_line_split |
hashing_analyzer.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the Hashing analyzer."""
import unittest
from plaso.containers import analyzer_result
from plaso.analyzers import hashing_analyzer
from plaso.analyzers.hashers import manager
from tests import test_lib as shared_test_lib
from tests.analyzers.hashers import ... | (self):
"""Test the creation of the analyzer, and the enabling of hashers."""
analyzer = hashing_analyzer.HashingAnalyzer()
analyzer.SetHasherNames('testhash')
self.assertEqual(len(analyzer._hashers), 1)
def testHashFile(self):
"""Tests that results are produced correctly."""
analyzer = hashi... | testHasherInitialization | identifier_name |
hashing_analyzer.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the Hashing analyzer."""
import unittest
from plaso.containers import analyzer_result
from plaso.analyzers import hashing_analyzer
from plaso.analyzers.hashers import manager
from tests import test_lib as shared_test_lib
from tests.analyzers.hashers import ... | unittest.main() | conditional_block | |
simpleAttributesDao.ts | /**
* SimpleAttributesDao module.
* @module extension/relatedTables
*/
import { UserDao } from '../../user/userDao';
import { SimpleAttributesTable } from './simpleAttributesTable';
import { SimpleAttributesRow } from './simpleAttributesRow';
import { GeoPackage } from '../../geoPackage';
import { DBValue } from '..... |
}
return simpleAttributesRows;
}
static readTable(geoPackage: GeoPackage, tableName: string) {
return geoPackage.relatedTablesExtension.getSimpleAttributesDao(tableName);
}
}
| {
simpleAttributesRows.push(row as SimpleAttributesRow);
} | conditional_block |
simpleAttributesDao.ts | /**
* SimpleAttributesDao module.
* @module extension/relatedTables
*/
import { UserDao } from '../../user/userDao';
import { SimpleAttributesTable } from './simpleAttributesTable';
import { SimpleAttributesRow } from './simpleAttributesRow';
import { GeoPackage } from '../../geoPackage';
import { DBValue } from '..... | <T extends SimpleAttributesRow> extends UserDao<SimpleAttributesRow> {
constructor(geoPackage: GeoPackage, table: SimpleAttributesTable) {
super(geoPackage, table);
}
/**
* Create a new {module:extension/relatedTables~SimpleAttributesRow} with the column types and values
* @param {module:db/geoPackageD... | SimpleAttributesDao | identifier_name |
simpleAttributesDao.ts | /**
* SimpleAttributesDao module.
* @module extension/relatedTables
*/
import { UserDao } from '../../user/userDao';
import { SimpleAttributesTable } from './simpleAttributesTable';
import { SimpleAttributesRow } from './simpleAttributesRow';
import { GeoPackage } from '../../geoPackage';
import { DBValue } from '..... |
/**
* Get the simple attributes rows from this table by ids
* @param {Number[]} ids array of ids
* @return {module:extension/relatedTables~SimpleAttributesRow[]}
*/
getRows(ids: number[]): SimpleAttributesRow[] {
const simpleAttributesRows = [];
for (let i = 0; i < ids.length; i++) {
con... | {
return this._table as SimpleAttributesTable;
} | identifier_body |
simpleAttributesDao.ts | /**
* SimpleAttributesDao module.
* @module extension/relatedTables
*/
import { UserDao } from '../../user/userDao';
import { SimpleAttributesTable } from './simpleAttributesTable';
import { SimpleAttributesRow } from './simpleAttributesRow';
import { GeoPackage } from '../../geoPackage';
import { DBValue } from '..... | * @class
* @extends UserDao
* @param {module:db/geoPackageConnection~GeoPackageConnection} connection connection
* @param {string} table table name
*/
export class SimpleAttributesDao<T extends SimpleAttributesRow> extends UserDao<SimpleAttributesRow> {
constructor(geoPackage: GeoPackage, table: SimpleA... | * User Simple Attributes DAO for reading user simple attributes data tables | random_line_split |
site_settings_mixin.ts | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview Behavior common to Site Settings classes.
*/
// clang-format off
import {dedupingMixin, PolymerElement} from 'chrome://resources/po... |
/**
* Ensures the URL has a scheme (assumes http if omitted).
* @param url The URL with or without a scheme.
* @return The URL with a scheme, or an empty string.
*/
ensureUrlHasScheme(url: string): string {
if (url.length === 0) {
return url;
... | {
super(...args);
/**
* The browser proxy used to retrieve and change information about
* site settings categories and the sites within.
*/
this.browserProxy = SiteSettingsPrefsBrowserProxyImpl.getInstance();
} | identifier_body |
site_settings_mixin.ts | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview Behavior common to Site Settings classes.
*/
// clang-format off
import {dedupingMixin, PolymerElement} from 'chrome://resources/po... | else if (exception.source === SiteSettingSource.POLICY) {
controlledBy = chrome.settingsPrivate.ControlledBy.USER_POLICY;
}
return {
category: this.category,
embeddingOrigin: embeddingOrigin,
incognito: exception.incognito,
isEmbargoed: e... | {
controlledBy = chrome.settingsPrivate.ControlledBy.EXTENSION;
} | conditional_block |
site_settings_mixin.ts | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview Behavior common to Site Settings classes.
*/
// clang-format off
import {dedupingMixin, PolymerElement} from 'chrome://resources/po... | (...args: any[]) {
super(...args);
/**
* The browser proxy used to retrieve and change information about
* site settings categories and the sites within.
*/
this.browserProxy = SiteSettingsPrefsBrowserProxyImpl.getInstance();
}
/**
... | constructor | identifier_name |
site_settings_mixin.ts | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview Behavior common to Site Settings classes.
*/
// clang-format off
import {dedupingMixin, PolymerElement} from 'chrome://resources/po... | computeIsSettingEnabled(setting: ContentSetting): boolean {
return setting !== ContentSetting.BLOCK;
}
/**
* Converts a string origin/pattern to a URL.
* @param originOrPattern The origin/pattern to convert to URL.
* @return The URL to return (or null if ori... | /**
* @return true if the passed content setting is considered 'enabled'.
*/ | random_line_split |
Uuid.js | /*!
Math.uuid.js (v1.4)
http://www.broofa.com | Dual licensed under the MIT and GPL licenses.
*/
/*
* Generate a random uuid.
*
* USAGE: Math.uuid(length, radix)
* length - the desired number of characters
* radix - the number of allowable values for each character.
*
* EXAMPLES:
* // No arguments - returns RFC4122, version 4 ID
* >>> Math.uuid... | mailto:robert@broofa.com
Copyright (c) 2010 Robert Kieffer | random_line_split |
Uuid.js | /*!
Math.uuid.js (v1.4)
http://www.broofa.com
mailto:robert@broofa.com
Copyright (c) 2010 Robert Kieffer
Dual licensed under the MIT and GPL licenses.
*/
/*
* Generate a random uuid.
*
* USAGE: Math.uuid(length, radix)
* length - the desired number of characters
* radix - the number of allowable value... |
exports.get = math.uuid;
exports.getNoSign = function () {
return replaceSign(math.uuid.apply(this, arguments));
};
exports.getFast = math.uuidFast;
exports.getFastNoSign = function () {
return replaceSign(math.uuidFast.apply(this, arguments));
};
exports.getCompact = math.uuidCompact;
exports.getCompactNoS... | {
return rs.replace(/\-/g, '');
} | identifier_body |
Uuid.js | /*!
Math.uuid.js (v1.4)
http://www.broofa.com
mailto:robert@broofa.com
Copyright (c) 2010 Robert Kieffer
Dual licensed under the MIT and GPL licenses.
*/
/*
* Generate a random uuid.
*
* USAGE: Math.uuid(length, radix)
* length - the desired number of characters
* radix - the number of allowable value... |
}
return uuid.join('');
},
uuidFast: function () {
var chars = CHARS, uuid = new Array(36), rnd = 0, r;
for (var i = 0; i < 36; i++) {
if (i == 8 || i == 13 || i == 18 || i == 23) {
uuid[i] = '-';
} else if (i == 14) {
uui... | {
if (!uuid[i]) {
r = 0 | Math.random() * 16;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
}
} | conditional_block |
Uuid.js | /*!
Math.uuid.js (v1.4)
http://www.broofa.com
mailto:robert@broofa.com
Copyright (c) 2010 Robert Kieffer
Dual licensed under the MIT and GPL licenses.
*/
/*
* Generate a random uuid.
*
* USAGE: Math.uuid(length, radix)
* length - the desired number of characters
* radix - the number of allowable value... | (rs)
{
return rs.replace(/\-/g, '');
}
exports.get = math.uuid;
exports.getNoSign = function () {
return replaceSign(math.uuid.apply(this, arguments));
};
exports.getFast = math.uuidFast;
exports.getFastNoSign = function () {
return replaceSign(math.uuidFast.apply(this, arguments));
};
exports.getCompact... | replaceSign | identifier_name |
setup.py | #!/usr/bin/env python
"""zip source directory tree"""
import argparse
import fnmatch
import logging
import os
import re
import subprocess
import zipfile
def | ():
command = ['git', 'describe', '--tags', '--dirty', '--always']
return subprocess.check_output(command).decode('utf-8')
def source_walk(root):
root = os.path.abspath(root)
regex = re.compile(fnmatch.translate('*.py[co]'))
for path, _, files in os.walk(root):
files[:] = [f for f in files if... | get_version | identifier_name |
setup.py | #!/usr/bin/env python
"""zip source directory tree"""
import argparse
import fnmatch
import logging
import os
import re
import subprocess
import zipfile
| return subprocess.check_output(command).decode('utf-8')
def source_walk(root):
root = os.path.abspath(root)
regex = re.compile(fnmatch.translate('*.py[co]'))
for path, _, files in os.walk(root):
files[:] = [f for f in files if regex.match(f) is None]
for filename in files:
fullpath ... | def get_version():
command = ['git', 'describe', '--tags', '--dirty', '--always'] | random_line_split |
setup.py | #!/usr/bin/env python
"""zip source directory tree"""
import argparse
import fnmatch
import logging
import os
import re
import subprocess
import zipfile
def get_version():
command = ['git', 'describe', '--tags', '--dirty', '--always']
return subprocess.check_output(command).decode('utf-8')
def source_walk(r... | return
if args.output is None:
args.output = args.source + '.zip'
with zipfile.ZipFile(args.output, 'w', zipfile.ZIP_DEFLATED) as fzip:
fzip.writestr('version.txt', get_version())
for path, relpath in source_walk(args.source):
fzip.write(path, relpath)
if __name__ == '__main... | argparser = argparse.ArgumentParser(description=__doc__)
argparser.add_argument(
'-d', '--debug',
action='store_true',
help='print debug information')
argparser.add_argument(
'-o',
metavar='zipfile',
dest='output',
help='output file name')
argparser.ad... | identifier_body |
setup.py | #!/usr/bin/env python
"""zip source directory tree"""
import argparse
import fnmatch
import logging
import os
import re
import subprocess
import zipfile
def get_version():
command = ['git', 'describe', '--tags', '--dirty', '--always']
return subprocess.check_output(command).decode('utf-8')
def source_walk(r... |
if __name__ == '__main__':
setup()
| fzip.write(path, relpath) | conditional_block |
static_request.d.ts | import { RequestMethod } from './enums';
import { RequestArgs } from './interfaces';
import { Headers } from './headers';
/**
* Creates `Request` instances from provided values.
*
* The Request's interface is inspired by the Request constructor defined in the [Fetch
* Spec](https://fetch.spec.whatwg.org/#req... | * import {Injectable, Injector} from 'angular2/core';
* import {HTTP_PROVIDERS, Http, Request, RequestMethod} from 'angular2/http';
*
* @Injectable()
* class AutoAuthenticator {
* constructor(public http:Http) {}
* request(url:string) {
* return this.http.request(new Request({
* method: R... | *
* ```typescript
| random_line_split |
static_request.d.ts | import { RequestMethod } from './enums';
import { RequestArgs } from './interfaces';
import { Headers } from './headers';
/**
* Creates `Request` instances from provided values.
*
* The Request's interface is inspired by the Request constructor defined in the [Fetch
* Spec](https://fetch.spec.whatwg.org/#req... | {
/**
* Http method with which to perform the request.
*/
method: RequestMethod;
/**
* {@link Headers} instance
*/
headers: Headers;
/** Url of the remote resource */
url: string;
private _body;
constructor(requestOptions: RequestArgs);
/**
* R... | Request | identifier_name |
recipe-189745.py | class Obfuscator:
""" A simple obfuscator class using repeated xor """
def __init__(self, data):
self._string = data
def obfuscate(self):
"""Obfuscate a string by using repeated xor"""
out = ""
data = self._string
a0=ord(data[0])
a1=ord(data... | main() | conditional_block | |
recipe-189745.py | class Obfuscator:
""" A simple obfuscator class using repeated xor """
def __init__(self, data):
self._string = data
def obfuscate(self):
"""Obfuscate a string by using repeated xor"""
out = ""
data = self._string
a0=ord(data[0])
a1=ord(data... |
if __name__=="__main__":
main()
| testString="Python obfuscator"
obfuscator = Obfuscator(testString)
testStringObf = obfuscator.obfuscate()
print testStringObf
obfuscator = Obfuscator(testStringObf)
testString = obfuscator.unobfuscate()
print testString | identifier_body |
recipe-189745.py | class Obfuscator:
""" A simple obfuscator class using repeated xor """
def __init__(self, data):
self._string = data
def obfuscate(self):
"""Obfuscate a string by using repeated xor"""
out = ""
data = self._string
a0=ord(data[0])
a1=ord(data... |
a1=chr(ord(a2)^ord(e2))
a1 += out
out = a1
#first character
e1=out[0]
a1=data[0]
a0=chr(ord(a1)^ord(e1))
a0 += out
out = a0
return out
def main():
testString="Python obfuscator"
obfuscator = Obfu... | a2=data[1] | random_line_split |
recipe-189745.py | class Obfuscator:
""" A simple obfuscator class using repeated xor """
def __init__(self, data):
self._string = data
def obfuscate(self):
"""Obfuscate a string by using repeated xor"""
out = ""
data = self._string
a0=ord(data[0])
a1=ord(data... | (self):
""" Reverse of obfuscation """
out = ""
data = self._string
x=len(data) - 2
while x>1:
apos=data[x]
aprevpos=data[x-2]
epos=chr(ord(apos)^ord(aprevpos))
out += epos
x -= 2
#r... | unobfuscate | identifier_name |
tools.py | def cartesian_product(sequences):
# This isn't actually a proper cartesian product because we
# concatenate lists, rather than forming sequences of atomic elements.
if not sequences:
yield []
else:
temp = list(cartesian_product(sequences[1:]))
for item in sequences[0]:
for sequence in temp:
... | c = [0] * N
d = [1] * N
while True:
yield alist
s = 0
for j in xrange(N - 1, -1, -1):
q = c[j] + d[j]
if q == j + 1:
if j == 0:
return
s += 1
elif q >= 0:
index1, index2 = j - c[j] + s, j - q + s
alist[index1], alist[i... | conditional_block | |
tools.py | def cartesian_product(sequences):
# This isn't actually a proper cartesian product because we
# concatenate lists, rather than forming sequences of atomic elements.
|
def permutations(alist):
# Note: The list is changed in place as the algorithm is performed.
# The original value is restored when we are done.
# Since this is a generator, the caller must be aware
# of this side effect and copy the input parameter if necessary.
# This is Knuth's "Algorith... | if not sequences:
yield []
else:
temp = list(cartesian_product(sequences[1:]))
for item in sequences[0]:
for sequence in temp:
yield item + sequence | identifier_body |
tools.py | def cartesian_product(sequences):
# This isn't actually a proper cartesian product because we
# concatenate lists, rather than forming sequences of atomic elements.
if not sequences:
yield []
else:
temp = list(cartesian_product(sequences[1:]))
for item in sequences[0]:
for sequence in temp:
... | d = [1] * N
while True:
yield alist
s = 0
for j in xrange(N - 1, -1, -1):
q = c[j] + d[j]
if q == j + 1:
if j == 0:
return
s += 1
elif q >= 0:
index1, index2 = j - c[j] + s, j - q + s
alist[index1], alist[index2] = ali... | c = [0] * N | random_line_split |
tools.py | def cartesian_product(sequences):
# This isn't actually a proper cartesian product because we
# concatenate lists, rather than forming sequences of atomic elements.
if not sequences:
yield []
else:
temp = list(cartesian_product(sequences[1:]))
for item in sequences[0]:
for sequence in temp:
... | (alist):
# Note: The list is changed in place as the algorithm is performed.
# The original value is restored when we are done.
# Since this is a generator, the caller must be aware
# of this side effect and copy the input parameter if necessary.
# This is Knuth's "Algorithm P" ("plain chang... | permutations | identifier_name |
webhooks.js | const router = require('express').Router() // eslint-disable-line new-cap
const log = require('winston')
const debug = require('debug')('streamInfo:routes:webhooks')
const request = require('snekfetch')
const config = require('../config')
const twitchAPI = require('../bin/twitchAPI')
const moment = require('moment')
c... | module.exports = router | random_line_split | |
switcher.js | define(function (require) {
'use strict';
/**
* Module dependencies
*/
var defineComponent = require('flight/lib/component');
/**
* Module exports
*/
return defineComponent(switcher);
/**
* Module function
*/
function | () {
this.defaultAttrs({
onClass: 'btn-primary'
});
this.turnOn = function() {
// 1) add class `this.attr.onClass`
// 2) trigger 'buttonOn' event
};
this.turnOff = function() {
// 3) remove class `this.attr.onClass`
// 4) trigger 'buttonOff' event
};
this.tog... | switcher | identifier_name |
switcher.js | define(function (require) {
'use strict';
/**
* Module dependencies
*/
var defineComponent = require('flight/lib/component');
/**
* Module exports
*/
return defineComponent(switcher);
/**
* Module function
*/
function switcher() | // 6) listen for 'click' event and call `this.toggle`
});
}
});
| {
this.defaultAttrs({
onClass: 'btn-primary'
});
this.turnOn = function() {
// 1) add class `this.attr.onClass`
// 2) trigger 'buttonOn' event
};
this.turnOff = function() {
// 3) remove class `this.attr.onClass`
// 4) trigger 'buttonOff' event
};
this.toggle... | identifier_body |
switcher.js | define(function (require) {
'use strict';
/**
* Module dependencies
*/
var defineComponent = require('flight/lib/component');
/**
* Module exports
*/
return defineComponent(switcher);
/**
* Module function
*/
function switcher() {
this.defaultAttrs({
onClass: 'btn-primar... | this.toggle = function() {
// 5) if `this.attr.onClass` is present call `turnOff` otherwise call `turnOn`
}
this.after('initialize', function () {
// 6) listen for 'click' event and call `this.toggle`
});
}
}); | // 4) trigger 'buttonOff' event
};
| random_line_split |
issue-13853-5.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | // option. This file may not be copied, modified, or distributed
// except according to those terms.
trait Deserializer<'a> { }
trait Deserializable {
fn deserialize_token<'a, D: Deserializer<'a>>(_: D, _: &'a str) -> Self;
}
impl<'a, T: Deserializable> Deserializable for &'a str {
//~^ ERROR type parameter ... | // 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 http://opensource.org/licenses/MIT>, at your | random_line_split |
issue-13853-5.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 main() {}
| {
} | identifier_body |
issue-13853-5.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 ... | () {}
| main | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.