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 |
|---|---|---|---|---|
truncated_type.rs | #[derive(Clone, Debug, PartialEq)]
pub enum TruncatedType {
Length,
Time,
Disconnect,
Unspecified,
Unknown(String),
}
impl ToString for TruncatedType {
fn to_string(&self) -> String {
let stringified = match *self {
TruncatedType::Length => "length",
TruncatedTyp... | impl<S: AsRef<str>> From<S> for TruncatedType {
fn from(string: S) -> Self {
let lower: String = string.as_ref().to_lowercase();
match lower.as_str() {
"length" => TruncatedType::Length,
"time" => TruncatedType::Time,
"disconnect" => TruncatedType::Disconnect,
... | }
| random_line_split |
truncated_type.rs | #[derive(Clone, Debug, PartialEq)]
pub enum TruncatedType {
Length,
Time,
Disconnect,
Unspecified,
Unknown(String),
}
impl ToString for TruncatedType {
fn to_string(&self) -> String {
let stringified = match *self {
TruncatedType::Length => "length",
TruncatedTyp... |
}
| {
let lower: String = string.as_ref().to_lowercase();
match lower.as_str() {
"length" => TruncatedType::Length,
"time" => TruncatedType::Time,
"disconnect" => TruncatedType::Disconnect,
"unspecified" => TruncatedType::Unspecified,
_ => Truncate... | identifier_body |
truncated_type.rs | #[derive(Clone, Debug, PartialEq)]
pub enum TruncatedType {
Length,
Time,
Disconnect,
Unspecified,
Unknown(String),
}
impl ToString for TruncatedType {
fn | (&self) -> String {
let stringified = match *self {
TruncatedType::Length => "length",
TruncatedType::Time => "time",
TruncatedType::Disconnect => "disconnect",
TruncatedType::Unspecified => "unspecified",
TruncatedType::Unknown(ref val) => val.as_ref(... | to_string | identifier_name |
kinds.ts | /*!
* Copyright (c) 2017-2018 by The Funfix Project Developers.
* Some 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-... | *
* Example:
*
* ```typescript
* class NumBox { constructor(public num: number) {} }
* class GenBox<A> { constructor(public a: A) {} }
*
* function getDefault<F>(ref: Constructor<F>): Option<F> {
* if ((ref as any)._default) return Some(ref._default)
* return None
* }
*
* (NumBox as any)._default = new... | random_line_split | |
entities.ts | empEntEvent): boolean;
}
type TickNumber = number & { readonly __tag: unique symbol };
/**
* Represents all entities that are transmitting (i.e. within PVS) in a given frame.
*/
export type TransmitEntities = immutable.Set<number>;
type MutableTransmitEntities = TransmitEntities & {
readonly __tag: unique symbol;... | (handle: number): boolean {
return handle !== consts.INVALID_NETWORKED_EHANDLE_VALUE;
}
/**
* Returns the entity specified by a particular handle.
* @param {number} handle - Networked entity handle value
* @returns {Entity|null} Entity referenced by the handle. `null` if no matching entity.
*/
pu... | isHandleSet | identifier_name |
entities.ts | number} handle - Networked entity handle value
* @returns {Entity|null} Entity referenced by the handle. `null` if no matching entity.
*/
public getByHandle(handle: EntityHandle): Networkable | null {
if (!handle.isValid) {
return null;
}
const ent = this.entities.get(handle.index);
if (e... | {
existingEntity.props = props;
return existingEntity;
} | conditional_block | |
entities.ts | unknown) as Player;
}
public getSingleton<
TServerClass,
TEntityClass extends Networkable<TServerClass>
>(serverClass: string): TEntityClass {
const existing = this._singletonEnts[serverClass];
if (existing) {
return (existing as unknown) as TEntityClass;
}
const result = find(
... | {
const serverClass = this.serverClasses[classId]!;
const newWay = entityBitBuffer.readOneBit();
let lastIndex = -1;
const fieldIndices: number[] = [];
// eslint-disable-next-line no-constant-condition
while (true) {
lastIndex = readFieldIndex(entityBitBuffer, lastIndex, newWay);
i... | identifier_body | |
entities.ts | empEntEvent): boolean;
}
type TickNumber = number & { readonly __tag: unique symbol };
/**
* Represents all entities that are transmitting (i.e. within PVS) in a given frame.
*/
export type TransmitEntities = immutable.Set<number>;
type MutableTransmitEntities = TransmitEntities & {
readonly __tag: unique symbol;... | }
});
}
/**
* Determines whether handle is set.
* This function does not determine whether the handle points to a valid entity.
* @param {number} handle - Networked entity handle value
* @returns {boolean} true if handle is set
*/
public isHandleSet(handle: number): boolean {
return ... | this.emit("remove", { index });
}
this.markedForDeletion.length = 0; | random_line_split |
TransitionPushUp.ts | import BaseTransition = require('BaseTransition');
import ITransition = require('../../interface/ITransition');
import DisplayObjectContainer = require('../../display/DisplayObjectContainer');
import DOMElement = require('../../display/DOMElement');
class | extends BaseTransition
{
/**
* TODO: YUIDoc_comment
*
* @class TransitionPushUp
* @extends BaseTransition
* @module StructureJS
* @submodule controller
* @constructor
* @author Robert S. (www.codeBelt.com)
* @version 0.1.0
*/
constructor()
{
super()... | TransitionPushUp | identifier_name |
TransitionPushUp.ts | import BaseTransition = require('BaseTransition');
import ITransition = require('../../interface/ITransition');
import DisplayObjectContainer = require('../../display/DisplayObjectContainer');
import DOMElement = require('../../display/DOMElement');
class TransitionPushUp extends BaseTransition
{
/**
* TODO: ... |
}
export = TransitionPushUp; | {
super.destroy();
} | identifier_body |
TransitionPushUp.ts | import BaseTransition = require('BaseTransition');
import ITransition = require('../../interface/ITransition');
import DisplayObjectContainer = require('../../display/DisplayObjectContainer');
import DOMElement = require('../../display/DOMElement');
class TransitionPushUp extends BaseTransition
{
/**
* TODO: ... |
/**
* @overridden EventDispatcher.destroy
*/
public destroy():void
{
super.destroy();
}
}
export = TransitionPushUp; | } | random_line_split |
component.js | import Ember from 'ember';
export default Ember.Component.extend({
colorMap: {
running: 'green',
waiting: 'orange',
terminated: 'red'
},
getStatusByName(name) {
let retval = null;
Ember.$.each(this.get('containerStatuses'), (i, containerStatus) => {
if (name === containerStatus.name) |
});
return retval;
},
items: Ember.computed('containers', 'containerStatuses', function() {
let items = [];
this.get('containers').map((container) => {
let status = this.getStatusByName(container.name);
let state = Object.keys(status.state)[0],
stateLabel = state.capitalize()... | {
retval = containerStatus;
return;
} | conditional_block |
component.js | import Ember from 'ember';
export default Ember.Component.extend({
colorMap: {
running: 'green',
waiting: 'orange',
terminated: 'red'
},
getStatusByName(name) | ,
items: Ember.computed('containers', 'containerStatuses', function() {
let items = [];
this.get('containers').map((container) => {
let status = this.getStatusByName(container.name);
let state = Object.keys(status.state)[0],
stateLabel = state.capitalize(),
stateColor = this.c... | {
let retval = null;
Ember.$.each(this.get('containerStatuses'), (i, containerStatus) => {
if (name === containerStatus.name) {
retval = containerStatus;
return;
}
});
return retval;
} | identifier_body |
component.js | import Ember from 'ember';
export default Ember.Component.extend({
colorMap: {
running: 'green',
waiting: 'orange',
terminated: 'red'
},
getStatusByName(name) {
let retval = null;
Ember.$.each(this.get('containerStatuses'), (i, containerStatus) => {
if (name === containerStatus.name) {... | });
return retval;
},
items: Ember.computed('containers', 'containerStatuses', function() {
let items = [];
this.get('containers').map((container) => {
let status = this.getStatusByName(container.name);
let state = Object.keys(status.state)[0],
stateLabel = state.capitalize(),... | } | random_line_split |
component.js | import Ember from 'ember';
export default Ember.Component.extend({
colorMap: {
running: 'green',
waiting: 'orange',
terminated: 'red'
},
| (name) {
let retval = null;
Ember.$.each(this.get('containerStatuses'), (i, containerStatus) => {
if (name === containerStatus.name) {
retval = containerStatus;
return;
}
});
return retval;
},
items: Ember.computed('containers', 'containerStatuses', function() {
let ... | getStatusByName | identifier_name |
f64.rs | use std::ops::{Add, Div, Mul, Sub};
use traits::{Simd, Vector};
use f64x2;
impl Simd for f64 {
type Vector = f64x2;
}
impl Add for f64x2 {
type Output = f64x2;
fn add(self, rhs: f64x2) -> f64x2 {
self + rhs
}
}
impl Div for f64x2 {
type Output = f64x2;
fn div(self, rhs: f64x2) -> ... |
}
| {
self.0 + self.1
} | identifier_body |
f64.rs | use std::ops::{Add, Div, Mul, Sub};
use traits::{Simd, Vector};
use f64x2;
impl Simd for f64 {
type Vector = f64x2;
}
impl Add for f64x2 {
type Output = f64x2;
fn add(self, rhs: f64x2) -> f64x2 {
self + rhs |
impl Div for f64x2 {
type Output = f64x2;
fn div(self, rhs: f64x2) -> f64x2 {
self / rhs
}
}
impl Mul for f64x2 {
type Output = f64x2;
fn mul(self, rhs: f64x2) -> f64x2 {
self * rhs
}
}
impl Sub for f64x2 {
type Output = f64x2;
fn sub(self, rhs: f64x2) -> f64x2 {
... | }
} | random_line_split |
f64.rs | use std::ops::{Add, Div, Mul, Sub};
use traits::{Simd, Vector};
use f64x2;
impl Simd for f64 {
type Vector = f64x2;
}
impl Add for f64x2 {
type Output = f64x2;
fn add(self, rhs: f64x2) -> f64x2 {
self + rhs
}
}
impl Div for f64x2 {
type Output = f64x2;
fn | (self, rhs: f64x2) -> f64x2 {
self / rhs
}
}
impl Mul for f64x2 {
type Output = f64x2;
fn mul(self, rhs: f64x2) -> f64x2 {
self * rhs
}
}
impl Sub for f64x2 {
type Output = f64x2;
fn sub(self, rhs: f64x2) -> f64x2 {
self - rhs
}
}
impl Vector for f64x2 {
type... | div | identifier_name |
rest_server.py | import threading
import pprint
import json
from bottle import route, run, Bottle
class Rest_Server(Bottle):
'''The REST front end'''
def __init__(self, core):
super(Rest_Server, self).__init__()
self._core = core
self.route('/plms', callback=self.list_plms)
def st... | **Example request**:
.. sourcecode:: http
GET /plms HTTP/1.1
Host: example.com
Accept: application/json
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Vary: Accept
Content-Type: application/json
{
"20F5F5": {
"dev_cat": 3,
"firmw... | def list_plms(self):
'''
Returns an object containin all of the plms.
| random_line_split |
rest_server.py | import threading
import pprint
import json
from bottle import route, run, Bottle
class Rest_Server(Bottle):
| Host: example.com
Accept: application/json
**Example response**:
.. sourcecode:: http
HTTP/1.1 200 OK
Vary: Accept
Content-Type: application/json
{
"20F5F5": {
"dev_cat": 3,
"firmware": 155,
"port": "/dev/serial/by-id/usb-FTDI_FT232R_USB... | '''The REST front end'''
def __init__(self, core):
super(Rest_Server, self).__init__()
self._core = core
self.route('/plms', callback=self.list_plms)
def start(self):
threading.Thread(target=self.run, kwargs=dict(
host='localhost', port=8080, debug=True)).s... | identifier_body |
rest_server.py | import threading
import pprint
import json
from bottle import route, run, Bottle
class Rest_Server(Bottle):
'''The REST front end'''
def __init__(self, core):
super(Rest_Server, self).__init__()
self._core = core
self.route('/plms', callback=self.list_plms)
def st... |
return self.jsonify(ret)
def jsonify(self, data):
return json.dumps(data, indent=4, sort_keys=True)
| ret[plm.dev_addr_str] = {
'dev_cat': plm.dev_cat,
'sub_cat': plm.sub_cat,
'firmware': plm.firmware,
'port': plm.port,
'port_active': plm.port_active
} | conditional_block |
rest_server.py | import threading
import pprint
import json
from bottle import route, run, Bottle
class Rest_Server(Bottle):
'''The REST front end'''
def | (self, core):
super(Rest_Server, self).__init__()
self._core = core
self.route('/plms', callback=self.list_plms)
def start(self):
threading.Thread(target=self.run, kwargs=dict(
host='localhost', port=8080, debug=True)).start()
def list_plms(self):
... | __init__ | identifier_name |
c-style-enum-in-composite.rs | // Copyright 2013-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-MI... | (&mut self) {()}
}
fn main() {
let tuple_interior_padding = (0_i16, OneHundred);
// It will depend on the machine architecture if any padding is actually involved here
let tuple_padding_at_end = ((1_u64, OneThousand), 2_u64);
let tuple_different_enums = (OneThousand, MountainView, OneMillion, Vienna);... | drop | identifier_name |
c-style-enum-in-composite.rs | // Copyright 2013-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-MI... | {()} | identifier_body | |
c-style-enum-in-composite.rs | // Copyright 2013-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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-android: FIXME(#10381)
// compile-flags:-g
// gdb-command:rbreak zzz
// gdb-command:run
// gdb-command:finish
// gdb-command:print tuple_inter... | random_line_split | |
lang.js | var
utils = require('enyo/utils'),
kind = require('enyo/kind');
describe('language', function () {
describe('usage', function () {
describe('Callee', function () {
var dn = '';
var fn = function() {
dn = arguments.callee.displayName;
};
it('should have proper callee', function () {
fn.displ... | expect(AClass).to.be.a('function')
});
});
describe('isString', function () {
var iframe;
before(function () {
var iframeDoc;
// Create alternate window context to write vars from
iframe = document.createElement("iframe"),
document.body.appendChild(iframe);
iframeDoc = iframe.con... | after(function () {
AClass = null;
});
it('should be a function', function () { | random_line_split |
angular-deckgrid.js | /*! angular-deckgrid (v0.1.1) - Copyright: 2013, André König (andre.koenig@posteo.de) - MIT */
/*
* angular-deckgrid
*
* Copyright(c) 2013 Andre Koenig <akoenig@posteo.de>
* MIT Licensed
*
*/
/**
* @author André König (akoenig@posteo.de)
*
*/
angular.module('akoenig.deckgrid', []);
angular.module('akoenig.d... | //
watcher = this.$$scope.$watch('model', this.$$onModelChange.bind(this), true);
this.$$watchers.push(watcher);
//
// Register window resize change event.
//
watcher = angular.element($window).on('resize', self.$$onWindowResize.bind(s... | var self = this,
watcher;
this.$$elem = element;
this.$$watchers = [];
this.$$scope = scope;
this.$$scope.columns = [];
//
// The layout configuration will be parsed from
// the pseudo "before element." There yo... | identifier_body |
angular-deckgrid.js | /*! angular-deckgrid (v0.1.1) - Copyright: 2013, André König (andre.koenig@posteo.de) - MIT */
/*
* angular-deckgrid
*
* Copyright(c) 2013 Andre Koenig <akoenig@posteo.de>
* MIT Licensed
*
*/
/**
* @author André König (akoenig@posteo.de)
*
*/
angular.module('akoenig.deckgrid', []);
angular.module('akoenig.d... | this.restrict = 'AE';
this.template = '<div data-ng-repeat="column in columns" class="{{layout.classList}}">' +
'<div data-ng-repeat="card in column" data-ng-include="cardTemplate"></div>' +
'</div>';
this.scope = {
... | ptor () {
| identifier_name |
angular-deckgrid.js | /*! angular-deckgrid (v0.1.1) - Copyright: 2013, André König (andre.koenig@posteo.de) - MIT */
/*
* angular-deckgrid
*
* Copyright(c) 2013 Andre Koenig <akoenig@posteo.de>
* MIT Licensed
*
*/
/**
* @author André König (akoenig@posteo.de)
*
*/
angular.module('akoenig.deckgrid', []);
angular.module('akoenig.d... | };
/**
* Destroys the directive. Takes care of cleaning all
* watchers and event handlers.
*
*/
Deckgrid.prototype.destroy = function destroy () {
var i = this.$$watchers.length - 1;
for (i; i >= 0; i = i - 1) {
this.$$watche... | self.$$createColumns();
}
| conditional_block |
angular-deckgrid.js | /*! angular-deckgrid (v0.1.1) - Copyright: 2013, André König (andre.koenig@posteo.de) - MIT */
/*
* angular-deckgrid
*
* Copyright(c) 2013 Andre Koenig <akoenig@posteo.de>
* MIT Licensed
*
*/
/**
* @author André König (akoenig@posteo.de)
*
*/
angular.module('akoenig.deckgrid', []);
angular.module('akoenig.d... | */
angular.module('akoenig.deckgrid').factory('DeckgridDescriptor', [
'Deckgrid',
function initialize (Deckgrid) {
'use strict';
/**
* This is a wrapper around the AngularJS
* directive description object.
*
*/
function Descriptor () {
... |
/**
* @author André König (akoenig@posteo.de)
* | random_line_split |
gauge.rs | use super::*;
/// A gauge metric for floating point values with helper methods
/// for incrementing and decrementing it's value
///
/// Internally uses a `Metric<f64>` with `Semantics::Instant`,
/// `Count::One` scale, and `1` count dimension
pub struct Gauge {
metric: Metric<f64>,
init_val: f64
}
impl Gauge ... | pub fn set(&mut self, val: f64) -> io::Result<()> {
self.metric.set_val(val)
}
/// Increments the gauge by the given value
pub fn inc(&mut self, increment: f64) -> io::Result<()> {
let val = self.metric.val();
self.metric.set_val(val + increment)
}
/// Decrements the ga... |
/// Sets the value of the gauge | random_line_split |
gauge.rs | use super::*;
/// A gauge metric for floating point values with helper methods
/// for incrementing and decrementing it's value
///
/// Internally uses a `Metric<f64>` with `Semantics::Instant`,
/// `Count::One` scale, and `1` count dimension
pub struct Gauge {
metric: Metric<f64>,
init_val: f64
}
impl Gauge ... | (name: &str, init_val: f64, shorthelp_text: &str, longhelp_text: &str) -> Result<Self, String> {
let metric = Metric::new(
name,
init_val,
Semantics::Instant,
Unit::new().count(Count::One, 1)?,
shorthelp_text,
longhelp_text
)?;
... | new | identifier_name |
util.js | 'blueviolet':[138,43,226],
'brown':[165,42,42],
'burlywood':[222,184,135],
'cadetblue':[95,158,160],
'chartreuse':[127,255,0],
'chocolate':[210,105,30],
'coral':[255,127,80],
'cornflowerblue':[100,149,237],
'cornsilk':[255,248,220],
'crimson':[220... | 'khaki':[240,230,140],
'lavender':[230,230,250],
'lavenderblush':[255,240,245],
'lawngreen':[124,252,0],
'lemonchiffon':[255,250,205],
'lightblue':[173,216,230],
'lightcoral':[240,128,128],
'lightcyan':[224,255,255],
'lightgoldenrodyellow':[250,250... | 'hotpink':[255,105,180],
'indianred':[205,92,92],
'indigo':[75,0,130],
'ivory':[255,255,240], | random_line_split |
yaxis.js | const alter = require('../lib/alter.js');
const Chainable = require('../lib/classes/chainable');
module.exports = new Chainable('yaxis', {
args: [
{
name: 'inputSeries',
types: ['seriesList']
},
{
name: 'yaxis',
types: ['number', 'null'],
help: 'The numbered y-axis to plot t... |
eachSeries.yaxis = yaxis;
eachSeries._global = eachSeries._global || {};
eachSeries._global.yaxes = eachSeries._global.yaxes || [];
eachSeries._global.yaxes[yaxis - 1] = eachSeries._global.yaxes[yaxis - 1] || {};
const myAxis = eachSeries._global.yaxes[yaxis - 1];
myAxis.position ... | return alter(args, function (eachSeries, yaxis, min, max, position, label, color) {
yaxis = yaxis || 1; | random_line_split |
DataBase.ts | import {Vereador} from "../Modelors/Vereador";
import {Propositura} from "../Modelors/Propositura";
import {Sessao} from "../Modelors/Sessao";
import {SessaoVereadores} from "../Modelors/SessaoVereadores";
/**
* Created by Bruno Melo on 10/06/17.
*/
export class DataBase {
private _vereadores: Vereador[] = [];
... |
get proposituras(): Propositura[] {
return this._proposituras;
}
set proposituras(value: Propositura[]) {
this._proposituras = value;
}
get sessao(): Sessao[] {
return this._sessao;
}
set sessao(value: Sessao[]) {
this._sessao = value;
}
get sessaoVereadores(): SessaoVereadores[]... | {
this._vereadores = value;
} | identifier_body |
DataBase.ts | import {Vereador} from "../Modelors/Vereador";
import {Propositura} from "../Modelors/Propositura";
import {Sessao} from "../Modelors/Sessao";
import {SessaoVereadores} from "../Modelors/SessaoVereadores";
/**
* Created by Bruno Melo on 10/06/17.
*/
export class DataBase {
private _vereadores: Vereador[] = [];
... |
set sessaoVereadores(value: SessaoVereadores[]) {
this._sessaoVereadores = value;
}
} | random_line_split | |
DataBase.ts | import {Vereador} from "../Modelors/Vereador";
import {Propositura} from "../Modelors/Propositura";
import {Sessao} from "../Modelors/Sessao";
import {SessaoVereadores} from "../Modelors/SessaoVereadores";
/**
* Created by Bruno Melo on 10/06/17.
*/
export class DataBase {
private _vereadores: Vereador[] = [];
... | (value: Vereador[]) {
this._vereadores = value;
}
get proposituras(): Propositura[] {
return this._proposituras;
}
set proposituras(value: Propositura[]) {
this._proposituras = value;
}
get sessao(): Sessao[] {
return this._sessao;
}
set sessao(value: Sessao[]) {
this._sessao = v... | vereadores | identifier_name |
index.d.ts | // Type definitions for node-libtidy v0.3
// Project: node-libtidy / https://github.com/gagern/node-libtidy
// Definitions by: Wang Guan <momocraft@gmail.com>
// vim: shiftwidth=2
export const tidyBuffer: TidyBufferStatic
export const TidyDoc: TidyDocConstructor
export const compat: TidyCompat
/// <reference types="n... | callback: TidyCallback): void
(document: string | Buffer, callback: TidyCallback): void
}
export class TidyOption {
// creation of TidyOption is not exposed
private constructor()
readonly name: string
readonly type: "boolean" | "integer" | "doctype" | "string"
readonly readOnly: boolean
readonly pic... | interface TidyBufferStatic {
(document: string | Buffer, options: Generated.OptionDict, | random_line_split |
index.d.ts | // Type definitions for node-libtidy v0.3
// Project: node-libtidy / https://github.com/gagern/node-libtidy
// Definitions by: Wang Guan <momocraft@gmail.com>
// vim: shiftwidth=2
export const tidyBuffer: TidyBufferStatic
export const TidyDoc: TidyDocConstructor
export const compat: TidyCompat
/// <reference types="n... | {
// creation of TidyOption is not exposed
private constructor()
readonly name: string
readonly type: "boolean" | "integer" | "doctype" | "string"
readonly readOnly: boolean
readonly pickList: string[]
readonly id: number
readonly category: string
toString(): string
}
type TidyOptionKey = TidyOption... | TidyOption | identifier_name |
cloneGraph_BFS.py | class UndirectedGraphNode:
def __init__(self, x):
self.label = x
self.neighbors = []
#using DFS
class | :
# @param node, a undirected graph node
# @return a undirected graph node
def cloneGraph(self, node):
seen={}
visited=[]
seen[None] = None
head = UndirectedGraphNode(node.label)
seen[node] = head
visited.append(node)
while len(visited) != 0:
... | Solution | identifier_name |
cloneGraph_BFS.py | class UndirectedGraphNode:
def __init__(self, x):
self.label = x
self.neighbors = []
#using DFS
class Solution:
# @param node, a undirected graph node
# @return a undirected graph node
def cloneGraph(self, node):
seen={}
visited=[]
seen[None] = None
hea... | A=UndirectedGraphNode(2)
B=UndirectedGraphNode(3)
C=UndirectedGraphNode(4)
A.neighbors.append(B)
A.neighbors.append(C)
B.neighbors.append(C)
N=Solution()
for i in N.cloneGraph(A).neighbors:
print i.label | random_line_split | |
cloneGraph_BFS.py | class UndirectedGraphNode:
def __init__(self, x):
self.label = x
self.neighbors = []
#using DFS
class Solution:
# @param node, a undirected graph node
# @return a undirected graph node
def cloneGraph(self, node):
seen={}
visited=[]
seen[None] = None
hea... |
return head
A=UndirectedGraphNode(2)
B=UndirectedGraphNode(3)
C=UndirectedGraphNode(4)
A.neighbors.append(B)
A.neighbors.append(C)
B.neighbors.append(C)
N=Solution()
for i in N.cloneGraph(A).neighbors:
print i.label
| refNode = visited.pop()
for n in refNode.neighbors:
if n not in seen:
neighBorNode = UndirectedGraphNode(n.label)
seen[refNode].neighbors.append(neighBorNode)
seen[n] = neighBorNode
visited.append(n)
... | conditional_block |
cloneGraph_BFS.py | class UndirectedGraphNode:
def __init__(self, x):
self.label = x
self.neighbors = []
#using DFS
class Solution:
# @param node, a undirected graph node
# @return a undirected graph node
|
A=UndirectedGraphNode(2)
B=UndirectedGraphNode(3)
C=UndirectedGraphNode(4)
A.neighbors.append(B)
A.neighbors.append(C)
B.neighbors.append(C)
N=Solution()
for i in N.cloneGraph(A).neighbors:
print i.label
| def cloneGraph(self, node):
seen={}
visited=[]
seen[None] = None
head = UndirectedGraphNode(node.label)
seen[node] = head
visited.append(node)
while len(visited) != 0:
refNode = visited.pop()
for n in refNode.neighbors:
if ... | identifier_body |
mod.rs | // Copyright 2016 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By ... | (name: XorName, tag: u64) -> Self {
DataId::Mutable(MutableDataId(name, tag))
}
/// Get name of this identifier.
pub fn name(&self) -> &XorName {
match *self {
DataId::Immutable(ref id) => id.name(),
DataId::Mutable(ref id) => id.name(),
}
}
}
| mutable | identifier_name |
mod.rs | // Copyright 2016 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By ... |
impl DataId {
/// Create `DataId` for immutable data.
pub fn immutable(name: XorName) -> Self {
DataId::Immutable(ImmutableDataId(name))
}
/// Create `DataId` for mutable data.
pub fn mutable(name: XorName, tag: u64) -> Self {
DataId::Mutable(MutableDataId(name, tag))
}
//... | random_line_split | |
math.rs | use std::ops::{Add, Div, Sub};
pub fn min<T>(nums: &Vec<T>) -> Option<T>
where
T: Ord + Copy,
{
nums.iter().fold(None, |min, x| match min {
None => Some(*x),
Some(y) => Some(if *x < y { *x } else { y }),
})
}
pub fn max<T>(nums: &Vec<T>) -> Option<T>
where
T: Ord + Copy,
{
nums.iter... | (nums: &Vec<u64>) -> Option<u64> {
if nums.len() > 0 {
let count = nums.len() as u64;
//let max_num = max(nums).unwrap();
let min_num = min(nums).unwrap();
let sum: u64 = nums.iter().sum();
let mid_abs = (sum - (min_num * count)) / count;
return Some(min_num + mid_abs... | avg_scale | identifier_name |
math.rs | use std::ops::{Add, Div, Sub};
pub fn min<T>(nums: &Vec<T>) -> Option<T>
where
T: Ord + Copy,
{
nums.iter().fold(None, |min, x| match min {
None => Some(*x),
Some(y) => Some(if *x < y { *x } else { y }),
})
}
pub fn max<T>(nums: &Vec<T>) -> Option<T>
where
T: Ord + Copy,
{
nums.iter... | })
}
pub fn avg_scale(nums: &Vec<u64>) -> Option<u64> {
if nums.len() > 0 {
let count = nums.len() as u64;
//let max_num = max(nums).unwrap();
let min_num = min(nums).unwrap();
let sum: u64 = nums.iter().sum();
let mid_abs = (sum - (min_num * count)) / count;
retu... | random_line_split | |
math.rs | use std::ops::{Add, Div, Sub};
pub fn min<T>(nums: &Vec<T>) -> Option<T>
where
T: Ord + Copy,
|
pub fn max<T>(nums: &Vec<T>) -> Option<T>
where
T: Ord + Copy,
{
nums.iter().fold(None, |max, x| match max {
None => Some(*x),
Some(y) => Some(if *x > y { *x } else { y }),
})
}
pub fn avg_scale(nums: &Vec<u64>) -> Option<u64> {
if nums.len() > 0 {
let count = nums.len() as u64;... | {
nums.iter().fold(None, |min, x| match min {
None => Some(*x),
Some(y) => Some(if *x < y { *x } else { y }),
})
} | identifier_body |
api.d.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { ParseSourceSpan } from '@angular/compiler';
import * as ts from 'typescript';
export declare enum Diagnostic... | span?: ParseSourceSpan;
category: DiagnosticCategory;
}
export interface CompilerOptions extends ts.CompilerOptions {
genDir?: string;
basePath?: string;
skipMetadataEmit?: boolean;
strictMetadataEmit?: boolean;
skipTemplateCodegen?: boolean;
flatModuleOutFile?: string;
flatModuleId?... | Message = 2,
}
export interface Diagnostic {
message: string; | random_line_split |
test_haskell_comments.py | #!/usr/bin/env python3
# testHaskellComments.py
""" Test line counter for the Haskell programmig language. """
import unittest
from argparse import Namespace
from pysloc import count_lines_double_dash, MapHolder
class TestHaskellComments(unittest.TestCase):
""" Test line counter for the Haskell programmig langu... | lines, sloc = count_lines_double_dash(test_file, options, 'occ')
self.assertEqual(lines, 27)
self.assertEqual(sloc, 10)
if __name__ == '__main__':
unittest.main() | options.ex_re = None
options.map_holder = MapHolder()
options.verbose = False
| random_line_split |
test_haskell_comments.py | #!/usr/bin/env python3
# testHaskellComments.py
""" Test line counter for the Haskell programmig language. """
import unittest
from argparse import Namespace
from pysloc import count_lines_double_dash, MapHolder
class | (unittest.TestCase):
""" Test line counter for the Haskell programmig language. """
def setUp(self):
pass
def tearDown(self):
pass
# utility functions #############################################
# actual unit tests #############################################
def test_nam... | TestHaskellComments | identifier_name |
test_haskell_comments.py | #!/usr/bin/env python3
# testHaskellComments.py
""" Test line counter for the Haskell programmig language. """
import unittest
from argparse import Namespace
from pysloc import count_lines_double_dash, MapHolder
class TestHaskellComments(unittest.TestCase):
""" Test line counter for the Haskell programmig langu... |
# utility functions #############################################
# actual unit tests #############################################
def test_name_to_func_map(self):
"""
Verify line counts returned from known Haskell file are correct.
"""
test_file = 'tests/commentsForHask... | pass | identifier_body |
test_haskell_comments.py | #!/usr/bin/env python3
# testHaskellComments.py
""" Test line counter for the Haskell programmig language. """
import unittest
from argparse import Namespace
from pysloc import count_lines_double_dash, MapHolder
class TestHaskellComments(unittest.TestCase):
""" Test line counter for the Haskell programmig langu... | unittest.main() | conditional_block | |
mc_send.py | #!/usr/bin/python
import socket
import struct
import sys
message = 'very important data'
multicast_group = ('224.3.29.71', 10000)
# Create the datagram socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Set a timeout so the socket does not block indefinitely when trying
# to receive data.
sock.settime... | print >>sys.stderr, 'sending "%s"' % message
sent = sock.sendto(message, multicast_group)
# Look for responses from all recipients
while True:
print >>sys.stderr, 'waiting to receive'
try:
data, server = sock.recvfrom(16)
except socket.timeout:
print >>sy... |
try:
# Send data to the multicast group | random_line_split |
mc_send.py | #!/usr/bin/python
import socket
import struct
import sys
message = 'very important data'
multicast_group = ('224.3.29.71', 10000)
# Create the datagram socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Set a timeout so the socket does not block indefinitely when trying
# to receive data.
sock.settime... |
finally:
print >>sys.stderr, 'closing socket'
sock.close()
| print >>sys.stderr, 'received "%s" from %s' % (data, server) | conditional_block |
progressbar.py | # Copyright 2013 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, size_read):
if self._show_progress:
self._percent += size_read / self._totalsize
# Output something like this: [==========> ] 49%
sys.stdout.write('\r[{0:<30}] {1:.0%}'.format(
'=' * int(round(self._percent * 29)) + '>', self._percent
... | _display_progress_bar | identifier_name |
progressbar.py | # Copyright 2013 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... |
def __getattr__(self, attr):
# Forward other attribute access to the wrapped object.
return getattr(self._wrapped, attr)
class VerboseFileWrapper(_ProgressBarBase):
"""
A file wrapper that show and advance a progress bar whenever file's read
method is called.
"""
def read(se... | if self._show_progress:
self._percent += size_read / self._totalsize
# Output something like this: [==========> ] 49%
sys.stdout.write('\r[{0:<30}] {1:.0%}'.format(
'=' * int(round(self._percent * 29)) + '>', self._percent
))
sys.st... | identifier_body |
progressbar.py | # Copyright 2013 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... | # Break to a new line from the progress bar for incoming
# output.
sys.stdout.write('\n')
return data
class VerboseIteratorWrapper(_ProgressBarBase):
"""
An iterator wrapper that show and advance a progress bar whenever
data is consumed from the iter... | data = self._wrapped.read(*args, **kwargs)
if data:
self._display_progress_bar(len(data))
else:
if self._show_progress: | random_line_split |
progressbar.py | # Copyright 2013 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... |
def __getattr__(self, attr):
# Forward other attribute access to the wrapped object.
return getattr(self._wrapped, attr)
class VerboseFileWrapper(_ProgressBarBase):
"""
A file wrapper that show and advance a progress bar whenever file's read
method is called.
"""
def read(se... | self._percent += size_read / self._totalsize
# Output something like this: [==========> ] 49%
sys.stdout.write('\r[{0:<30}] {1:.0%}'.format(
'=' * int(round(self._percent * 29)) + '>', self._percent
))
sys.stdout.flush() | conditional_block |
smartTables.component.ts | import {Component, ViewEncapsulation,ViewChild} from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { RestService } from './rest.service';
import { Ng2SmartTableModule } from 'ng2-smart-table';
import { LocalDataSource } from 'ng2-smart-table';
// import { ServerDataSource } from 'ng... | {
//public pagenum: number = 10;
//public num : 10;
rowPerPage = myGlobals.row_per_page;
query: string = '';
public filteredcount;
public input: string = '<input _ngcontent-bbl-39="" type="checkbox" value="Check 1">';
settings = {
hideHeader: false,
doEmit: true,
silent: true,
actions: ... | SmartTables | identifier_name |
smartTables.component.ts | import {Component, ViewEncapsulation,ViewChild} from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { RestService } from './rest.service';
import { Ng2SmartTableModule } from 'ng2-smart-table';
import { LocalDataSource } from 'ng2-smart-table';
// import { ServerDataSource } from 'ng... |
onDeleteConfirm(event): void {
if (window.confirm('Are you sure you want to delete?')) {
event.confirm.resolve();
} else {
event.confirm.reject();
}
}
// onChangePage(event): void{
// this.source.setPaging(1,event.page, true);
// this.source.refresh();
// }
}
| {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(this.items);
}, 2000);
});
} | identifier_body |
smartTables.component.ts | import {Component, ViewEncapsulation,ViewChild} from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { RestService } from './rest.service';
import { Ng2SmartTableModule } from 'ng2-smart-table';
import { LocalDataSource } from 'ng2-smart-table';
// import { ServerDataSource } from 'ng... | status: {
title: myGlobals.label_Status,
type: 'number'
}
// request: {
// title: myGlobals.label_Request,
// type: 'string'
// }
}
};
source: LocalDataSource;
public items = [];
constructor(protected service: RestService,private _sanitizer: DomSanit... | random_line_split | |
smartTables.component.ts | import {Component, ViewEncapsulation,ViewChild} from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { RestService } from './rest.service';
import { Ng2SmartTableModule } from 'ng2-smart-table';
import { LocalDataSource } from 'ng2-smart-table';
// import { ServerDataSource } from 'ng... |
}
// onChangePage(event): void{
// this.source.setPaging(1,event.page, true);
// this.source.refresh();
// }
}
| {
event.confirm.reject();
} | conditional_block |
material_module.ts | // Copyright 2018 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable... | import {MatButtonModule} from '@angular/material/button';
import {MatDialogModule} from '@angular/material/dialog';
import {MatSliderModule} from '@angular/material/slider';
const MATERIAL_MODULES = [
MatButtonModule,
MatDialogModule,
MatSliderModule,
];
@NgModule({
imports: MATERIAL_MODULES,
exports: MATER... | import {NgModule} from '@angular/core'; | random_line_split |
material_module.ts | // Copyright 2018 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable... | {
}
| MaterialModule | identifier_name |
15_3sum.ts | function threeSum(nums: number[]): number[][] | }
}
idx++;
while (nums[idx] === nums[idx - 1] && idx < len - 2) idx++;
}
return ret;
}
let case1 = [-1, 0, 1, 2, -1, -4, -2, -3, 3, 0, 4];
console.log(threeSum(case1));
| {
let ret = [];
nums.sort((a, b) => a - b);
let len = nums.length;
for (let idx = 0; idx < len - 2; ) {
let target = -nums[idx];
let left = idx + 1;
let right = len - 1;
while (left < right) {
if (nums[left] + nums[right] > target) {
right--;
} else if (nums[left] + nums[r... | identifier_body |
15_3sum.ts | function | (nums: number[]): number[][] {
let ret = [];
nums.sort((a, b) => a - b);
let len = nums.length;
for (let idx = 0; idx < len - 2; ) {
let target = -nums[idx];
let left = idx + 1;
let right = len - 1;
while (left < right) {
if (nums[left] + nums[right] > target) {
right--;
}... | threeSum | identifier_name |
15_3sum.ts | function threeSum(nums: number[]): number[][] {
let ret = [];
nums.sort((a, b) => a - b); | for (let idx = 0; idx < len - 2; ) {
let target = -nums[idx];
let left = idx + 1;
let right = len - 1;
while (left < right) {
if (nums[left] + nums[right] > target) {
right--;
} else if (nums[left] + nums[right] < target) {
left++;
} else {
ret.push([nums[idx... |
let len = nums.length;
| random_line_split |
helpers.js | /* exported addEvent, removeEvent, getChildren, setAttributes, addClass, removeClass, forEach */
/**
* Add Event
* fn arg can be an object or a function, thanks to handleEvent
* read more at: http://www.thecssninja.com/javascript/handleevent
*
* @param {element} element
* @param {event} event
* @param {F... | // Store all children in array
var children = [];
// Loop through children and store in array if child != TextNode
for (var i = 0; i < e.children.length; i++) {
if (e.children[i].nodeType === 1) {
children.push(e.children[i]);
}
}
return children;
},
/**
* Sets multip... | } | random_line_split |
helpers.js | /* exported addEvent, removeEvent, getChildren, setAttributes, addClass, removeClass, forEach */
/**
* Add Event
* fn arg can be an object or a function, thanks to handleEvent
* read more at: http://www.thecssninja.com/javascript/handleevent
*
* @param {element} element
* @param {event} event
* @param {F... |
},
/**
* Get the children of any element
*
* @param {element}
* @return {array} Returns matching elements in an array
*/
getChildren = function (e) {
if (e.children.length < 1) {
throw new Error("The Nav container has no containing elements");
}
// Store all children in array
... | {
if (typeof fn === "object" && fn.handleEvent) {
el.detachEvent("on" + evt, function () {
fn.handleEvent.call(fn);
});
} else {
el.detachEvent("on" + evt, fn);
}
} | conditional_block |
createWhiteningValues.py | #!/usr/bin/python2
import collections
import os
from loranode import RN2483Controller
# from ../_examplify.py import Examplify
import os
os.sys.path.append(os.path.dirname(os.path.abspath('.')))
from _examplify import Examplify
import lora, pmt, osmosdr
from gnuradio import gr, blocks
class ReceiveWhitening:
de... |
def captureSequence(self, inputFile):
self.inputFile = inputFile
if os.path.isfile(self.inputFile):
self.tb = gr.top_block()
self.file_source = blocks.file_source(gr.sizeof_gr_complex*1, self.inputFile, False) # Repeat input: True/False
self.lora_lora... | self.target_freq = 868.1e6
self.sf = sf
self.samp_rate = 1e6
self.capture_freq = 868.0e6
self.offset = -(self.capture_freq - self.target_freq)
self.inputFile = './'
self.outputFile = output_file
self.tempFile =... | identifier_body |
createWhiteningValues.py | #!/usr/bin/python2
import collections
import os
from loranode import RN2483Controller
# from ../_examplify.py import Examplify
import os
os.sys.path.append(os.path.dirname(os.path.abspath('.')))
from _examplify import Examplify
import lora, pmt, osmosdr
from gnuradio import gr, blocks
class ReceiveWhitening:
de... | examplifr = Examplify(settings[0], settings[1], gains = [32, 38, 38])
whitening = ReceiveWhitening(settings[0], dataf)
for i in range(8):
print("Sample {0:d} of 16".format(i))
examplifr.transmitToFile(['0' * 256] * 4, ofile)
whitening.captureSequence(ofile)
... | out = open(dataf, 'a')
out.close()
| random_line_split |
createWhiteningValues.py | #!/usr/bin/python2
import collections
import os
from loranode import RN2483Controller
# from ../_examplify.py import Examplify
import os
os.sys.path.append(os.path.dirname(os.path.abspath('.')))
from _examplify import Examplify
import lora, pmt, osmosdr
from gnuradio import gr, blocks
class ReceiveWhitening:
de... | (self, sf = 7, output_file = './test_out.csv'):
self.target_freq = 868.1e6
self.sf = sf
self.samp_rate = 1e6
self.capture_freq = 868.0e6
self.offset = -(self.capture_freq - self.target_freq)
self.inputFile = './'
self.outp... | __init__ | identifier_name |
createWhiteningValues.py | #!/usr/bin/python2
import collections
import os
from loranode import RN2483Controller
# from ../_examplify.py import Examplify
import os
os.sys.path.append(os.path.dirname(os.path.abspath('.')))
from _examplify import Examplify
import lora, pmt, osmosdr
from gnuradio import gr, blocks
class ReceiveWhitening:
de... |
examplifr = None
whitening = None
| ofile = '/tmp/tmp_whitening.cfile'
testset = [ (7, "4/6"), (7, "4/7"), (8, "4/5"), (12, "4/6"), (9, "4/5"), (10, "4/5"), (11, "4/5"), (6, "4/5")]
for settings in testset:
dataf = './test_out_SF{0:d}_CR{1:s}.csv'.format(settings[0], '-'.join(settings[1].split('/')))
out = open(dataf, 'a')
... | conditional_block |
coin-board-block-chain-info.component.spec.ts | /* tslint:disable max-line-length */
import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { Observable } from 'rxjs/Observable';
import { HttpHeaders, HttpResponse } from '@angular/common/http';
import { BlockchainTestModule } from '../../../test.module';
import { CoinBoardBlockChainInfoCom... | TestBed.configureTestingModule({
imports: [BlockchainTestModule],
declarations: [CoinBoardBlockChainInfoComponent],
providers: [
CoinBoardBlockChainInfoService
]
})
.overrideTemplate(CoinBoardBlockCha... | random_line_split | |
admin.js | $(function() {
$('.api-call form').each(function() {
$(this).submit(function() {
var urlparams = {}
$(this).siblings('.urlparam').each(function() {
urlparams[$(this).attr('name')] = $(this).val();
});
var resultsPre = $(this).siblings('.api-cal... | var form_params = OAuth.decodeForm($(this).serialize());
for (var p = 0; p < form_params.length; p++) {
oauth_params[form_params[p][0]] = form_params[p][1];
}
oauth_params.oauth_version = '1.0';
oauth_params.oauth_consumer_key = $('#oauth-consu... | var oauth_params = {}; | random_line_split |
admin.js | $(function() {
$('.api-call form').each(function() {
$(this).submit(function() {
var urlparams = {}
$(this).siblings('.urlparam').each(function() {
urlparams[$(this).attr('name')] = $(this).val();
});
var resultsPre = $(this).siblings('.api-cal... |
resultsPre.html(prettyResults);
},
headers: {
'Authorization': OAuth.getAuthorizationHeader('', oauth_message.parameters),
},
};
if (method == 'POST') {
options.dataType = 'json';
... | {
var url = link[1];
prettyResults = prettyResults.replace(url, '<a href="' + url.replace(/\\\//g, '/') + '" target="_blank">' + url + '</a>');
link = regex.exec(results);
} | conditional_block |
nrg_test.py | # Standard imports
import os
import sys
import pickle
# Third party imports
import nose
# Local imports
from pypub.scrapers import nature_nrg as nrg
from pypub.paper_info import PaperInfo
class TestNature(object):
def __init__(self):
self.curpath = str(os.path.dirname(os.path.abspath(__file__)))
... |
assert True
def test_nature_pdf_link(self):
if self.pi.pdf_link != self.saved_pi.pdf_link:
assert False
else:
assert True
if __name__ == '__main__':
module_name = sys.modules[__name__].__file__
result = nose.run(argv=[sys.argv[0], module_name, '-v'])
| saved_ref_dict = self.saved_pi.references[y].__dict__
live_ref_dict = self.pi.references[y].__dict__
for x in live_ref_dict.keys():
if saved_ref_dict[x] != saved_ref_dict[x]:
print('\nDifference found.')
print('Key: ' + str(x))
... | conditional_block |
nrg_test.py | # Standard imports
import os
import sys
import pickle
# Third party imports
import nose
# Local imports
from pypub.scrapers import nature_nrg as nrg
from pypub.paper_info import PaperInfo
class TestNature(object):
def __init__(self):
self.curpath = str(os.path.dirname(os.path.abspath(__file__)))
... | (self):
assert type(self.pi.references) is list
def test_reflist_type(self):
assert type(self.pi.references[0]) is nrg.NatureRef
# Testing scraped soup against saved site version
def test_nature_saved_entry(self):
for x in self.saved_entry_dict.keys():
if x == 'authors'... | test_references_type | identifier_name |
nrg_test.py | # Standard imports
import os
import sys
import pickle
# Third party imports
import nose
# Local imports
from pypub.scrapers import nature_nrg as nrg
from pypub.paper_info import PaperInfo
class TestNature(object):
def __init__(self):
self.curpath = str(os.path.dirname(os.path.abspath(__file__)))
... |
def test_references_type(self):
assert type(self.pi.references) is list
def test_reflist_type(self):
assert type(self.pi.references[0]) is nrg.NatureRef
# Testing scraped soup against saved site version
def test_nature_saved_entry(self):
for x in self.saved_entry_dict.keys():... | assert type(self.pi.entry) is nrg.NatureEntry | identifier_body |
nrg_test.py | # Standard imports
import os
import sys
import pickle
# Third party imports
import nose
# Local imports
from pypub.scrapers import nature_nrg as nrg
from pypub.paper_info import PaperInfo
class TestNature(object):
def __init__(self):
self.curpath = str(os.path.dirname(os.path.abspath(__file__)))
... | else:
self.pi = pi
self.entry_dict = self.pi.entry.__dict__
# Load saved version of the PaperInfo object
saved_dir = os.path.join(self.curpath, 'saved_info')
saved_file_path = os.path.join(saved_dir, 'sp_info.txt')
self.saved_pi = pickle.load(open(saved_f... | pi = PaperInfo(url=self.link, doi=self.doi, scraper_obj='nature')
pi.populate_info()
except Exception:
self.pi = None
self.entry_dict = None | random_line_split |
FileDataView.py | # -*- coding: utf-8 -*-
from PyQt4 import QtCore, QtGui
from acq4.util.DataManager import *
#import acq4.Manager as Manager
import acq4.pyqtgraph as pg
#from acq4.pyqtgraph.MultiPlotWidget import MultiPlotWidget
#from acq4.pyqtgraph.ImageView import ImageView
from acq4.util.DictView import *
import acq4.util.metaarray... |
def clear(self):
for w in self.widgets:
w.close()
w.setParent(None)
self.widgets = []
self.dictWidget = None
| if self.dictWidget is None:
w = DictView(data._info)
self.dictWidget = w
#w.setText(str(data._info[-1]))
self.addWidget(w)
self.widgets.append(w)
h = self.size().height()
self.setSizes([h*0.8, h*0.2])
... | conditional_block |
FileDataView.py | # -*- coding: utf-8 -*-
from PyQt4 import QtCore, QtGui
from acq4.util.DataManager import *
#import acq4.Manager as Manager
import acq4.pyqtgraph as pg
#from acq4.pyqtgraph.MultiPlotWidget import MultiPlotWidget
#from acq4.pyqtgraph.ImageView import ImageView
from acq4.util.DictView import *
import acq4.util.metaarray... | (self):
for w in self.widgets:
w.close()
w.setParent(None)
self.widgets = []
self.dictWidget = None
| clear | identifier_name |
FileDataView.py | # -*- coding: utf-8 -*-
from PyQt4 import QtCore, QtGui
from acq4.util.DataManager import *
#import acq4.Manager as Manager
import acq4.pyqtgraph as pg
#from acq4.pyqtgraph.MultiPlotWidget import MultiPlotWidget
#from acq4.pyqtgraph.ImageView import ImageView
from acq4.util.DictView import *
import acq4.util.metaarray... | data = file.read()
if typ == 'ImageFile':
image = True
elif typ == 'MetaArray':
if data.ndim == 2 and not data.axisHasColumns(0) and not data.axisHasColumns(1):
image = True
elif data... | if file is self.current:
return
## What if we just want to update the data display?
#self.clear()
if file is None:
self.current = None
return
if file.isDir():
## Sequence or not?
return
... | identifier_body |
FileDataView.py | # -*- coding: utf-8 -*-
from PyQt4 import QtCore, QtGui
from acq4.util.DataManager import *
#import acq4.Manager as Manager
import acq4.pyqtgraph as pg
#from acq4.pyqtgraph.MultiPlotWidget import MultiPlotWidget
#from acq4.pyqtgraph.ImageView import ImageView
from acq4.util.DictView import *
import acq4.util.metaarray... |
#self.plots = [weakref.ref(p[0]) for p in w.mPlotItem.plots]
if (hasattr(data, 'implements') and data.implements('MetaArray')):
if self.dictWidget is None:
w = DictView(data._info)
self.dictWidget = w
#w.setTex... | w.plot(data)
self.currentType = 'plot'
self.widgets.append(w)
#print "add mplot:", w.mPlotItem.plots | random_line_split |
index.ts | 'use strict'
const path: any = require('path')
const fs: any = require('fs')
const fileUtil: any = require('../util/file-util')
const j5require: any = fileUtil.json5Require
import config from './config'
const Print: {
update(input: string): void,
} = require('../util/print')
const extend: any = require('node.exten... | ) {
return
}
const basename: string = page.entry.slice(1).replace(/\//g, '.')
const ftlMockFilePath: string = path.join(pPath, basename || 'index')
const ftlMockFilePath1: string = ftlMockFilePath + '.json'
const ftlMockFilePath2: string = ftlMockFilePath + '.json5'
extend(page.syncData... | if (!pPath | identifier_name |
index.ts | 'use strict'
const path: any = require('path')
const fs: any = require('fs')
const fileUtil: any = require('../util/file-util')
const j5require: any = fileUtil.json5Require
import config from './config'
const Print: {
update(input: string): void,
} = require('../util/print')
const extend: any = require('node.exten... | if (paths.pageAsync) {
paths.aPath = path.resolve(paths.pageAsync)
} else {
errors.push('Page async mock data not found.')
}
errors.forEach((error: string): void => {
console.error(error)
})
return paths
}
function mock(page: Page): {} {
page.syncData = {}
page.t... | } | random_line_split |
index.ts | 'use strict'
const path: any = require('path')
const fs: any = require('fs')
const fileUtil: any = require('../util/file-util')
const j5require: any = fileUtil.json5Require
import config from './config'
const Print: {
update(input: string): void,
} = require('../util/print')
const extend: any = require('node.exten... | paths.pPath = path.resolve(paths.pageSync)
} else {
errors.push('Page ftl mock data not found.')
}
if (paths.commonAsync) {
paths.commonAsync = path.resolve(paths.commonAsync)
} else {
errors.push('Common async mock data not found')
}
if (paths.pageAsync) {
... | p: false,
commonSync: false,
pageSync: false,
commonAsync: false,
async: false,
}, config.dataPath)
const errors: string[] = []
if (paths.urlMap) {
paths.uPath = path.resolve(paths.urlMap)
} else {
console.error('URLMap not found!')
process.exit(1... | identifier_body |
SaxParser.js | parent element from being processed.
*
* @private
* @method findEndTag
* @param {tinymce.html.Schema} schema Schema instance to use to match short ended elements.
* @param {String} html HTML string to find the end tag in.
* @param {Number} startIndex Indext to start searching at should be... | () { }
settings = settings || {};
self.schema = schema = schema || new Schema();
if (settings.fix_self_closing !== false) {
settings.fix_self_closing = true;
}
// Add handler functions from settings and setup default handlers
each('comment cdata text start end pi doctype'.... | noop | identifier_name |
SaxParser.js | parent element from being processed.
*
* @private
* @method findEndTag
* @param {tinymce.html.Schema} schema Schema instance to use to match short ended elements.
* @param {String} html HTML string to find the end tag in.
* @param {Number} startIndex Indext to start searching at should be... | if (count === 0) {
break;
}
}
return index;
}
/**
* Constructs a new SaxParser instance.
*
* @constructor
* @method SaxParser
* @param {Object} settings Name/value collection of settings. comment, cdata, text, start and end are callbacks.
* ... | {
var count = 1, index, matches, tokenRegExp, shortEndedElements;
shortEndedElements = schema.getShortEndedElements();
tokenRegExp = /<([!?\/])?([A-Za-z0-9\-_\:\.]+)((?:\s+[^"\'>]+(?:(?:"[^"]*")|(?:\'[^\']*\')|[^>]*))*|\/|\s+)>/g;
tokenRegExp.lastIndex = index = startIndex;
while ((match... | identifier_body |
SaxParser.js | (pos--) {
if (stack[pos].name === name) {
break;
}
}
// Found parent
if (pos >= 0) {
// Close all the open elements
for (i = stack.length - 1; i >= pos; i--) {
name = stack[i];
if (name.valid) {
... |
self.end(value);
} | random_line_split | |
SaxParser.js | matches, tokenRegExp, shortEndedElements;
shortEndedElements = schema.getShortEndedElements();
tokenRegExp = /<([!?\/])?([A-Za-z0-9\-_\:\.]+)((?:\s+[^"\'>]+(?:(?:"[^"]*")|(?:\'[^\']*\')|[^>]*))*|\/|\s+)>/g;
tokenRegExp.lastIndex = index = startIndex;
while ((matches = tokenRegExp.exec(html)))... | {
isValidElement = true;
// Grab attributes map and patters when validation is enabled
if (validate) {
validAttributesMap = elementRule.attributes;
validAttributePatterns = elementRule.attributePatterns;
}
// Parse a... | conditional_block | |
blog.py | import pymongo
from bson.objectid import ObjectId
from eve.utils import date_to_str
from html5lib.html5parser import ParseError
from lxml.html.html5parser import fragments_fromstring, HTMLParser
from superdesk.utc import utcnow
from superdesk import get_resource_service
from liveblog.posts.mixins import AuthorsMixin... | results = self._posts_service.find(lookup)
total = results.count()
# Get sorting direction.
sort = pymongo.DESCENDING
if sort == 'asc':
sort = pymongo.ASCENDING
# Fetch posts, do pagination and sorting.
skip = limit * (page - 1)
results = res... | """
Builds a query with the given parameters and hit mongodb to retrive the data
Uses `find` method from resource service. If wrap parameter is provided, the return
value it's a dictionary ala `python-eve` style data structure
Supported kwargs: sticky, highlight, ordering, page, limit, ... | identifier_body |
blog.py | import pymongo
from bson.objectid import ObjectId
from eve.utils import date_to_str
from html5lib.html5parser import ParseError
from lxml.html.html5parser import fragments_fromstring, HTMLParser
from superdesk.utc import utcnow
from superdesk import get_resource_service
from liveblog.posts.mixins import AuthorsMixin... |
filters.append({'published_date': {'$lte': date_to_str(utcnow())}})
if sticky:
filters.append({'sticky': True})
else:
filters.append({'sticky': False})
if highlight:
filters.append({'lb_highlight': True})
if len(tags) > 0:
... | filters.append({'deleted': False}) | conditional_block |
blog.py | import pymongo
from bson.objectid import ObjectId
from eve.utils import date_to_str
from html5lib.html5parser import ParseError
from lxml.html.html5parser import fragments_fromstring, HTMLParser
from superdesk.utc import utcnow
from superdesk import get_resource_service
from liveblog.posts.mixins import AuthorsMixin... | total = results.count()
# Get sorting direction.
sort = pymongo.DESCENDING
if sort == 'asc':
sort = pymongo.ASCENDING
# Fetch posts, do pagination and sorting.
skip = limit * (page - 1)
results = results.skip(skip).limit(limit).sort(order_by, sort)
... | random_line_split | |
blog.py | import pymongo
from bson.objectid import ObjectId
from eve.utils import date_to_str
from html5lib.html5parser import ParseError
from lxml.html.html5parser import fragments_fromstring, HTMLParser
from superdesk.utc import utcnow
from superdesk import get_resource_service
from liveblog.posts.mixins import AuthorsMixin... | (html):
try:
fragments_fromstring(html.encode('utf-8'), parser=HTMLParser(strict=True))
except ParseError:
return False
return True
class Blog(AuthorsMixin):
"""
Utility class to fetch blog data directly from mongo collections.
"""
order_by = ('_updated', '_created', 'orde... | is_valid_html | identifier_name |
track_sampling.py | """
Sampling along tracks
---------------------
The :func:`pygmt.grdtrack` function samples a raster grid's value along specified
points. We will need to input a 2D raster to ``grid`` which can be an
:class:`xarray.DataArray`. The argument passed to the ``points`` parameter can be a
:class:`pandas.DataFrame` table whe... | color=(track.bathymetry - track.bathymetry.mean()) / track.bathymetry.std(),
)
fig.show() | random_line_split | |
test-process-raw-debug.js | 'use strict';
var common = require('../common');
var assert = require('assert');
var os = require('os');
switch (process.argv[2]) {
case 'child':
return child();
case undefined:
return parent();
default:
throw new Error('wtf? ' + process.argv[2]);
}
function parent() | });
}
function child() {
// even when all hope is lost...
process.nextTick = function() {
throw new Error('No ticking!');
};
var stderr = process.stderr;
stderr.write = function() {
throw new Error('No writing to stderr!');
};
process._rawDebug('I can still %s!', 'debug');
}
| {
var spawn = require('child_process').spawn;
var child = spawn(process.execPath, [__filename, 'child']);
var output = '';
child.stderr.on('data', function(c) {
output += c;
});
child.stderr.setEncoding('utf8');
child.stderr.on('end', function() {
assert.equal(output, 'I can still debug!' + os... | identifier_body |
test-process-raw-debug.js | 'use strict';
var common = require('../common');
var assert = require('assert');
var os = require('os');
switch (process.argv[2]) {
case 'child':
return child();
case undefined:
return parent();
default:
throw new Error('wtf? ' + process.argv[2]);
}
function parent() {
var spawn = require('child_p... | process._rawDebug('I can still %s!', 'debug');
} | };
| random_line_split |
test-process-raw-debug.js | 'use strict';
var common = require('../common');
var assert = require('assert');
var os = require('os');
switch (process.argv[2]) {
case 'child':
return child();
case undefined:
return parent();
default:
throw new Error('wtf? ' + process.argv[2]);
}
function parent() {
var spawn = require('child_p... | () {
// even when all hope is lost...
process.nextTick = function() {
throw new Error('No ticking!');
};
var stderr = process.stderr;
stderr.write = function() {
throw new Error('No writing to stderr!');
};
process._rawDebug('I can still %s!', 'debug');
}
| child | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.