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 |
|---|---|---|---|---|
auth.service.ts | import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Moment } from 'moment/moment';
import * as moment from 'moment/moment';
import * as jwtDecode from 'jwt-decode';
import { DataService } from './data.service';
import { Credentia... | (): boolean {
return moment().isBefore(this.getExpiration());
}
/** Set auth JWT to local storage */
setToken(jwt: string): void {
// save token to local storage (set session)
localStorage.setItem('jwtComplex', jwt);
}
/** Find out expiration in JWT */
getExpiration(): ... | isLoggedIn | identifier_name |
auth.service.ts | import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Moment } from 'moment/moment';
import * as moment from 'moment/moment';
import * as jwtDecode from 'jwt-decode';
import { DataService } from './data.service';
import { Credentia... |
/** Check if user is logged in (if JWT is not expired) */
isLoggedIn(): boolean {
return moment().isBefore(this.getExpiration());
}
/** Set auth JWT to local storage */
setToken(jwt: string): void {
// save token to local storage (set session)
localStorage.setItem('jwtComp... | {
localStorage.removeItem('jwtComplex');
// redirect user (to login page)
this.router.navigate(['/login']);
} | identifier_body |
entity.py | """Base class for Tado entity."""
from homeassistant.helpers.entity import Entity
from .const import DEFAULT_NAME, DOMAIN, TADO_ZONE
class TadoDeviceEntity(Entity):
"""Base implementation for Tado device."""
def __init__(self, device_info):
"""Initialize a Tado device."""
super().__init__()
... | (self):
"""Do not poll."""
return False
| should_poll | identifier_name |
entity.py | """Base class for Tado entity."""
from homeassistant.helpers.entity import Entity
from .const import DEFAULT_NAME, DOMAIN, TADO_ZONE
class TadoDeviceEntity(Entity):
"""Base implementation for Tado device."""
def __init__(self, device_info):
"""Initialize a Tado device."""
super().__init__()
... |
@property
def device_info(self):
"""Return the device_info of the device."""
return {
"identifiers": {(DOMAIN, self._device_zone_id)},
"name": self.zone_name,
"manufacturer": DEFAULT_NAME,
"model": TADO_ZONE,
}
@property
def shou... | """Initialize a Tado zone."""
super().__init__()
self._device_zone_id = f"{home_id}_{zone_id}"
self.zone_name = zone_name | identifier_body |
entity.py | """Base class for Tado entity."""
from homeassistant.helpers.entity import Entity
from .const import DEFAULT_NAME, DOMAIN, TADO_ZONE
class TadoDeviceEntity(Entity):
"""Base implementation for Tado device."""
def __init__(self, device_info):
"""Initialize a Tado device."""
super().__init__()
... | return False | random_line_split | |
queryer.py | #! /usr/bin/env python
# --*-- coding:utf-8 --*--
import os
import sys
sys.path.append(os.path.split(os.path.split(os.path.abspath(sys.path[0]))[0])[0])
from CountMan.monitor.util import *
from CountMan.monitor.setting import *
class Queryer(object):
|
if __name__ == '__main__':
q = Queryer()
if ISDEBUG:
import cProfile
cProfile.run("q.set2db")
else:
q.set2db
| def __init__(self):
self.dao = DatabaseInterface()
self.dataSet = dict()
self.logger = getLogger('root')
def getData(self):
for queryKey in QUERYPARAM:
self.dataSet[queryKey] = getResponse(QUERYPARAM.get(queryKey))
@property
def set2db(self):
self.getDat... | identifier_body |
queryer.py | #! /usr/bin/env python
# --*-- coding:utf-8 --*--
import os
import sys
sys.path.append(os.path.split(os.path.split(os.path.abspath(sys.path[0]))[0])[0])
from CountMan.monitor.util import *
from CountMan.monitor.setting import *
class Queryer(object):
def __init__(self):
self.dao = DatabaseInterface()
... | q = Queryer()
if ISDEBUG:
import cProfile
cProfile.run("q.set2db")
else:
q.set2db | conditional_block | |
queryer.py | #! /usr/bin/env python
# --*-- coding:utf-8 --*--
import os
import sys
sys.path.append(os.path.split(os.path.split(os.path.abspath(sys.path[0]))[0])[0])
from CountMan.monitor.util import *
from CountMan.monitor.setting import *
class Queryer(object):
| def __init__(self):
self.dao = DatabaseInterface()
self.dataSet = dict()
self.logger = getLogger('root')
def getData(self):
for queryKey in QUERYPARAM:
self.dataSet[queryKey] = getResponse(QUERYPARAM.get(queryKey))
@property
def set2db(self):
self.ge... | random_line_split | |
queryer.py | #! /usr/bin/env python
# --*-- coding:utf-8 --*--
import os
import sys
sys.path.append(os.path.split(os.path.split(os.path.abspath(sys.path[0]))[0])[0])
from CountMan.monitor.util import *
from CountMan.monitor.setting import *
class Queryer(object):
def __init__(self):
self.dao = DatabaseInterface()
... | (self):
for queryKey in QUERYPARAM:
self.dataSet[queryKey] = getResponse(QUERYPARAM.get(queryKey))
@property
def set2db(self):
self.getData()
self.logger.info('get query data: {0} success'.format(self.dataSet))
self.dao.insertCollection(self.dataSet)
if __name__ == ... | getData | identifier_name |
fdyn.py | # Copyright (C) 1993-2002, by Peter I. Corke
# $Log: rtfddemo.m,v $
# Revision 1.4 2002/04/02 12:26:48 pic
# Handle figures better, control echo at end of each script.
# Fix bug in calling ctraj.
#
# Revision 1.3 2002/04/01 11:47:17 pic
# General cleanup of code: help comments, see also, copyright, remnant dh/dyn
... | pause % hit any key to continue
#
# This can be shown in animation also
clf
plot(p560, q)
pause % hit any key to continue
echo off | random_line_split | |
embed.js | /*
Sapling pagelink dialog
*/
CKEDITOR.dialog.add( 'embed', function( editor )
{
var plugin = CKEDITOR.plugins.embed;
var pagelink_plugin = CKEDITOR.plugins.pagelink;
return {
title : 'Embed media',
minWidth : 300,
minHeight : 150,
contents : [
{
id : 'info',
label : 'Embed media', | elements :
[
{
type : 'textarea',
id : 'code',
label : 'Paste the embed code below:',
required: true,
validate : function()
{
var dialog = this.getDialog();
var func = CKEDITOR.dialog.validate.notEmpty( 'Please enter the embed code' );
return func.ap... | title : 'Embed media', | random_line_split |
libstdc++.a-gdb.py | # -*- python -*-
# Copyright (C) 2009-2013 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later versio... | # beforehand.
if gdb.current_objfile () is not None:
# Update module path. We want to find the relative path from libdir
# to pythondir, and then we want to apply that relative path to the
# directory holding the objfile with which this file is associated.
# This preserves relocatability of the gcc tre... |
# This file might be loaded when there is no current objfile. This
# can happen if the user loads it manually. In this case we don't
# update sys.path; instead we just hope the user managed to do that | random_line_split |
libstdc++.a-gdb.py | # -*- python -*-
# Copyright (C) 2009-2013 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later versio... | sys.path.insert(0, dir_)
# Load the pretty-printers.
from libstdcxx.v6.printers import register_libstdcxx_printers
register_libstdcxx_printers (gdb.current_objfile ())
| pythondir = os.path.normpath (pythondir)
libdir = os.path.normpath (libdir)
prefix = os.path.commonprefix ([libdir, pythondir])
# In some bizarre configuration we might have found a match in the
# middle of a directory name.
if prefix[-1] != '/':
prefix = os.path.dirname (prefix) + '/'
... | conditional_block |
mod.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/. */
///
/// Example cUrl request:
/// curl -X PUT -d '[[[{"id":"setter:talk@link.mozilla.org"}], {"String": "hello wor... | <T> {
talk_setter_id: Id<Channel>,
engine: T
}
impl<T: TtsEngine> Adapter for TtsAdapter<T> {
fn id(&self) -> Id<AdapterId> {
adapter_id!(ADAPTER_ID)
}
fn name(&self) -> &str {
ADAPTER_NAME
}
fn vendor(&self) -> &str {
ADAPTER_VENDOR
}
fn version(&self) ->... | TtsAdapter | identifier_name |
mod.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/. */
///
/// Example cUrl request:
/// curl -X PUT -d '[[[{"id":"setter:talk@link.mozilla.org"}], {"String": "hello wor... |
let talk_setter_id = Id::new("setter:talk@link.mozilla.org");
try!(adapt.add_adapter(Arc::new(TtsAdapter {
talk_setter_id: talk_setter_id.clone(),
engine: engine
})));
let service_id = service_id!("espeak@link.mozilla.org");
let adapter_id = adapter_id!(ADAPTER_ID);
try!(adapt.... | {
warn!("eSpeak initialization failed!");
return Err(Error::InternalError(InternalError::GenericError("eSpeak initialization failed!".to_owned())));
} | conditional_block |
mod.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/. */
///
/// Example cUrl request:
/// curl -X PUT -d '[[[{"id":"setter:talk@link.mozilla.org"}], {"String": "hello wor... | } | random_line_split | |
mod.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/. */
///
/// Example cUrl request:
/// curl -X PUT -d '[[[{"id":"setter:talk@link.mozilla.org"}], {"String": "hello wor... |
fn vendor(&self) -> &str {
ADAPTER_VENDOR
}
fn version(&self) -> &[u32;4] {
&ADAPTER_VERSION
}
fn fetch_values(&self, mut set: Vec<Id<Channel>>, _: User) -> ResultMap<Id<Channel>, Option<Value>, Error> {
set.drain(..).map(|id| {
(id.clone(), Err(Error::Interna... | {
ADAPTER_NAME
} | identifier_body |
Counter.ts | import { typeName, isActionType, Action, Reducer } from 'redux-typed';
import { ActionCreator } from './';
// -----------------
// STATE - This defines the type of data maintained in the Redux store.
export interface CounterState {
count: number;
}
// -----------------
// ACTIONS - These are serializable (hence ... | // (or default initial state if none was supplied)
return state || { count: 0 };
}; | if (isActionType(action, IncrementCount)) {
return { count: state.count + 1 };
}
// For unrecognized actions (or in cases where actions have no effect), must return the existing state | random_line_split |
Counter.ts | import { typeName, isActionType, Action, Reducer } from 'redux-typed';
import { ActionCreator } from './';
// -----------------
// STATE - This defines the type of data maintained in the Redux store.
export interface CounterState {
count: number;
}
// -----------------
// ACTIONS - These are serializable (hence ... |
// For unrecognized actions (or in cases where actions have no effect), must return the existing state
// (or default initial state if none was supplied)
return state || { count: 0 };
};
| {
return { count: state.count + 1 };
} | conditional_block |
Counter.ts | import { typeName, isActionType, Action, Reducer } from 'redux-typed';
import { ActionCreator } from './';
// -----------------
// STATE - This defines the type of data maintained in the Redux store.
export interface CounterState {
count: number;
}
// -----------------
// ACTIONS - These are serializable (hence ... | extends Action {
}
// ----------------
// ACTION CREATORS - These are functions exposed to UI components that will trigger a state transition.
// They don't directly mutate state, but they can have external side-effects (such as loading data).
export const actionCreators = {
increment: (): ActionCreator => (disp... | IncrementCount | identifier_name |
lib.rs | #[macro_use] extern crate winreg;
#[macro_use] extern crate rustler;
#[macro_use] extern crate rustler_codegen;
#[macro_use] extern crate lazy_static;
use rustler::{NifEnv, NifTerm, NifResult, NifEncoder};
use winreg::RegKey;
use winreg::enums::*;
mod atoms {
rustler_atoms! {
atom ok;
//atom erro... | <'a>(env: NifEnv<'a>, args: &[NifTerm<'a>]) -> NifResult<NifTerm<'a>> {
let hklm = RegKey::predef(HKEY_LOCAL_MACHINE);
let file_system_key = hklm.open_subkey_with_flags("SYSTEM\\CurrentControlSet\\Control\\FileSystem", KEY_READ).unwrap();
let eight_dot_three_disabled: u32 = file_system_key.get_value("NtfsDi... | check_short_names | identifier_name |
lib.rs | #[macro_use] extern crate winreg;
#[macro_use] extern crate rustler;
#[macro_use] extern crate rustler_codegen;
#[macro_use] extern crate lazy_static;
use rustler::{NifEnv, NifTerm, NifResult, NifEncoder};
use winreg::RegKey;
use winreg::enums::*;
mod atoms {
rustler_atoms! {
atom ok;
//atom erro... |
fn check_short_names<'a>(env: NifEnv<'a>, args: &[NifTerm<'a>]) -> NifResult<NifTerm<'a>> {
let hklm = RegKey::predef(HKEY_LOCAL_MACHINE);
let file_system_key = hklm.open_subkey_with_flags("SYSTEM\\CurrentControlSet\\Control\\FileSystem", KEY_READ).unwrap();
let eight_dot_three_disabled: u32 = file_system... | {
let num1: i64 = try!(args[0].decode());
let num2: i64 = try!(args[1].decode());
Ok((atoms::ok(), num1 + num2).encode(env))
} | identifier_body |
lib.rs | #[macro_use] extern crate winreg;
#[macro_use] extern crate rustler;
#[macro_use] extern crate rustler_codegen;
#[macro_use] extern crate lazy_static;
use rustler::{NifEnv, NifTerm, NifResult, NifEncoder};
use winreg::RegKey;
use winreg::enums::*;
mod atoms {
rustler_atoms! {
atom ok;
//atom erro... | atom ntfs_create_short_names = "ntfs_create_short_names";
atom ntfs_never_create_short_names = "ntfs_never_create_short_names";
atom ntfs_create_short_per_volume = "ntfs_create_short_per_volume";
atom ntfs_create_short_only_on_system_volume = "ntfs_create_short_only_on_system_volume";
... | // atom __false__ = "false"; | random_line_split |
fileEvaluator.py | import os
import subprocess
import tempfile
import time
from config import dataDir
from scapetesting.fileEval.FileEvaluation import fileReportLoader, fileEval
__author__ = 'abr'
def fileRunner(reportfile):
|
tempdir = tempfile.mkdtemp()
csvReportfile = os.path.join(tempdir,"report.csv")
print csvReportfile
try:
time = fileRunner(csvReportfile)
fileReportLoader(csvReportfile)
pass
finally:
pass
os.remove(csvReportfile)
os.rmdir(tempdir)
print "Time spent analysing the entire archive: "+str(time... | with open(reportfile,"w") as fileThing:
start = time.time()
for dir, dirs, files in os.walk(dataDir):
if files:
for file in sorted(files):
startLocal = time.time()
subprocess.check_call(["file","-i",os.path.join(dir,file)],stdout=fileTh... | identifier_body |
fileEvaluator.py | import os
import subprocess
import tempfile
import time
from config import dataDir
from scapetesting.fileEval.FileEvaluation import fileReportLoader, fileEval
__author__ = 'abr'
def | (reportfile):
with open(reportfile,"w") as fileThing:
start = time.time()
for dir, dirs, files in os.walk(dataDir):
if files:
for file in sorted(files):
startLocal = time.time()
subprocess.check_call(["file","-i",os.path.join(dir,fi... | fileRunner | identifier_name |
fileEvaluator.py | import os
import subprocess | __author__ = 'abr'
def fileRunner(reportfile):
with open(reportfile,"w") as fileThing:
start = time.time()
for dir, dirs, files in os.walk(dataDir):
if files:
for file in sorted(files):
startLocal = time.time()
subprocess.check_cal... | import tempfile
import time
from config import dataDir
from scapetesting.fileEval.FileEvaluation import fileReportLoader, fileEval
| random_line_split |
fileEvaluator.py | import os
import subprocess
import tempfile
import time
from config import dataDir
from scapetesting.fileEval.FileEvaluation import fileReportLoader, fileEval
__author__ = 'abr'
def fileRunner(reportfile):
with open(reportfile,"w") as fileThing:
start = time.time()
for dir, dirs, files in os.walk(... |
end = time.time()
return end-start
tempdir = tempfile.mkdtemp()
csvReportfile = os.path.join(tempdir,"report.csv")
print csvReportfile
try:
time = fileRunner(csvReportfile)
fileReportLoader(csvReportfile)
pass
finally:
pass
os.remove(csvReportfile)
os.rmdir(tempdir)
print "Time... | for file in sorted(files):
startLocal = time.time()
subprocess.check_call(["file","-i",os.path.join(dir,file)],stdout=fileThing)
endLocal = time.time() | conditional_block |
recipeReport.js | var RecipeReport = (function () {
"use strict";
var standartThaaliCount = 100;
var sum = function(array, prop) {
return array.reduce( function(a, b){
return a + b[prop];
}, 0);
};
var recipeReport = function (data, fromDate, toDate, recipe) {
this.data = data;
this.fromDate = fr... | report[name].amount = report[name].amount || 0;
report[name].amount += ingredient.amount;
report[name].count = report[name].count || 0;
report[name].count++;
}
}
}
var finalReport = [];
for (var prop in report) {
finalReport.push({
"Ingred... | report[name].unit = ingredient.unit;
| random_line_split |
recipeReport.js | var RecipeReport = (function () {
"use strict";
var standartThaaliCount = 100;
var sum = function(array, prop) {
return array.reduce( function(a, b){
return a + b[prop];
}, 0);
};
var recipeReport = function (data, fromDate, toDate, recipe) {
this.data = data;
this.fromDate = fr... |
report[name].unit = ingredient.unit;
report[name].amount = report[name].amount || 0;
report[name].amount += ingredient.amount;
report[name].count = report[name].count || 0;
report[name].count++;
}
}
}
var finalReport = [];
for (var prop in r... | {
fault[ingredient.item.toLowerCase() + '-' + meal.date] = fault[ingredient.item.toLowerCase() + '-' + meal.date] || 0;
fault[ingredient.item.toLowerCase() + '-' + meal.date] += 1;
isFaulty = true;
} | conditional_block |
lib.rs | //! # The rusty-machine crate.
//!
//! A crate built for machine learning that works out-of-the-box.
//!
//! ---
//!
//! ## Structure
//!
//! The crate is made up of two primary modules: learning and linalg.
//!
//! ### learning
//!
//! The learning module contains all of the machine learning modules.
//! This means th... | //!
//! The linalg module reexports some structs and traits from the
//! [rulinalg](https://crates.io/crates/rulinalg) crate. This is to provide
//! easy access to common linear algebra tools within this library.
//!
//! ---
//!
//! ## Usage
//!
//! Specific usage of modules is described within the modules themselves. ... | //! ### linalg | random_line_split |
index.ts | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | function main() {
// check that the client instance can be created
const binauthzManagementServiceV1Beta1Client =
new BinauthzManagementServiceV1Beta1Client();
doStuffWithBinauthzManagementServiceV1Beta1Client(
binauthzManagementServiceV1Beta1Client
);
// check that the client instance can be created
... | random_line_split | |
index.ts | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
function doStuffWithSystemPolicyV1Beta1Client(
client: SystemPolicyV1Beta1Client
) {
client.close();
}
function main() {
// check that the client instance can be created
const binauthzManagementServiceV1Beta1Client =
new BinauthzManagementServiceV1Beta1Client();
doStuffWithBinauthzManagementServiceV1Bet... | {
client.close();
} | identifier_body |
index.ts | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | (
client: BinauthzManagementServiceV1Beta1Client
) {
client.close();
}
function doStuffWithSystemPolicyV1Beta1Client(
client: SystemPolicyV1Beta1Client
) {
client.close();
}
function main() {
// check that the client instance can be created
const binauthzManagementServiceV1Beta1Client =
new BinauthzMan... | doStuffWithBinauthzManagementServiceV1Beta1Client | identifier_name |
util.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub struct Stderr;
impl io::Writer for Stderr {
fn write(&mut self, data: &[u8]) -> IoResult<()> {
unsafe {
libc::write(libc::STDERR_FILENO,
data.as_ptr() as *libc::c_void,
data.len() as libc::size_t);
}
Ok(()) // yes, we're lyin... | {
match os::getenv("RUST_THREADS") {
Some(nstr) => {
let opt_n: Option<uint> = FromStr::from_str(nstr);
match opt_n {
Some(n) if n > 0 => n,
_ => rtabort!("`RUST_THREADS` is `{}`, should be a positive integer", nstr)
}
}
Non... | identifier_body |
util.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () -> bool {
(cfg!(target_os="macos")) && running_on_valgrind()
}
/// Get's the number of scheduler threads requested by the environment
/// either `RUST_THREADS` or `num_cpus`.
pub fn default_sched_threads() -> uint {
match os::getenv("RUST_THREADS") {
Some(nstr) => {
let opt_n: Option<uin... | limit_thread_creation_due_to_osx_and_valgrind | identifier_name |
util.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | limitless vacuum beyond all thought and entity. Perceptions of the most
maddeningly untransmissible sort thronged upon us; perceptions of infinity
which at the time convulsed us with joy, yet which are now partly lost to my
memory and partly incapable of presentation to others.",
_ => "You've met with a terribl... | There was a night when winds from unknown spaces whirled us irresistibly into | random_line_split |
json2.js | in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) r... |
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
... |
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return... | identifier_body |
json2.js | 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
*/
/*jslint evil: true, regexp: true */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
cal... | lk(h | identifier_name | |
json2.js | listed in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undef... | function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
if (typeof Date.prototype.toJSON !== 'function') {
Date.prototype.toJSON = function () {
return isFinite(this.valueOf())
? this.getUTCFullYear() + '-' +
... | random_line_split | |
index.js | var names = Alloy.Collections.name;
function green(str) { return '\x1B[32m' + str + '\x1B[39m'; }
function | (str) { return '\x1B[31m' + str + '\x1B[39m'; }
// show the info from the selected model
function showInfo(e) {
// get the model id from the list item
var modelId = e.section.getItemAt(e.itemIndex).properties.modelId;
// fetch a specific model based on the given id
var model = Alloy.createModel('info');
model.fe... | red | identifier_name |
index.js | var names = Alloy.Collections.name;
function green(str) { return '\x1B[32m' + str + '\x1B[39m'; }
function red(str) { return '\x1B[31m' + str + '\x1B[39m'; }
// show the info from the selected model
function showInfo(e) |
// fetch the data to update the UI
names.fetch();
// open the window
$.index.open(); | {
// get the model id from the list item
var modelId = e.section.getItemAt(e.itemIndex).properties.modelId;
// fetch a specific model based on the given id
var model = Alloy.createModel('info');
model.fetch({ id: modelId });
// assert we got the right data back
var pass = JSON.stringify(model.attributes) === J... | identifier_body |
index.js | var names = Alloy.Collections.name;
function green(str) { return '\x1B[32m' + str + '\x1B[39m'; }
function red(str) { return '\x1B[31m' + str + '\x1B[39m'; }
// show the info from the selected model
function showInfo(e) { | // fetch a specific model based on the given id
var model = Alloy.createModel('info');
model.fetch({ id: modelId });
// assert we got the right data back
var pass = JSON.stringify(model.attributes) === JSON.stringify({
id: modelId,
info: 'info ' + modelId
});
Ti.API.info('Assert single info model returned w... | // get the model id from the list item
var modelId = e.section.getItemAt(e.itemIndex).properties.modelId;
| random_line_split |
ComplexPrimitiveGraphics.js | /**
* @author Richard Davey <rich@photonstorm.com>
* @author Mat Groves (@Doormat23)
* @copyright 2016 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* New version of PIXI.ComplexPrimitiveShader
*
* @class Phaser.Renderer.Canvas... | * The vertex shader.
* @property vertexSrc
* @type Array
*/
this.fragmentSrc = [];
this.vertexSrc = [];
this.attributes = [];
// @type {WebGLUniformLocation }
this.projectionVector;
// @type {WebGLUniformLocation }
this.offsetVector;
// @type {WebGLUniformLocation... | */
this.program = null;
/** | random_line_split |
moves-based-on-type-exprs.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 ... | (cond: bool) {
let x = "hi".to_string();
let y = "ho".to_string();
let _y = match cond {
true => x,
false => y
};
touch(&x); //~ ERROR use of moved value: `x`
touch(&y); //~ ERROR use of moved value: `y`
}
fn f50(cond: bool) {
let x = "hi".to_string();
let y = "ho".to_st... | f40 | identifier_name |
moves-based-on-type-exprs.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 ... | else {
y
};
touch(&x); //~ ERROR use of moved value: `x`
touch(&y); //~ ERROR use of moved value: `y`
}
fn f40(cond: bool) {
let x = "hi".to_string();
let y = "ho".to_string();
let _y = match cond {
true => x,
false => y
};
touch(&x); //~ ERROR use of moved valu... | {
x
} | conditional_block |
moves-based-on-type-exprs.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 f10() {
let x = "hi".to_string();
let _y = Foo { f:x };
touch(&x); //~ ERROR use of moved value: `x`
}
fn f20() {
let x = "hi".to_string();
let _y = (x, 3i);
touch(&x); //~ ERROR use of moved value: `x`
}
fn f21() {
let x = vec!(1i, 2, 3);
let _y = (*x.get(0), 3i);
touch(&x);
... | {} | identifier_body |
moves-based-on-type-exprs.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 ... | touch(&x); //~ ERROR use of moved value: `x`
touch(&y); //~ ERROR use of moved value: `y`
}
fn f40(cond: bool) {
let x = "hi".to_string();
let y = "ho".to_string();
let _y = match cond {
true => x,
false => y
};
touch(&x); //~ ERROR use of moved value: `x`
touch(&y); //~... | random_line_split | |
TimeRange.py | ##
##
# File auto-generated against equivalent DynamicSerialize Java class. Then modified to add functionality
#
#
# SOFTWARE HISTORY
#
# Date Ticket# Engineer Description
# ------------ ---------- ----------- --------------------------
# ??/??/?? xxxxx... |
def getStart(self):
return self.start.utctimetuple()
def getStartInMillis(self):
return self._getInMillis(self.start)
def setStart(self, start, extraMicros=None):
self.start = self.__convertToDateTimeWithExtra(start, extraMicros)
def getEnd(self):
return self.end.utc... | if seconds < MAX_TIME:
rval = datetime.datetime.utcfromtimestamp(seconds)
else:
extraTime = datetime.timedelta(seconds=(seconds - MAX_TIME))
rval = datetime.datetime.utcfromtimestamp(MAX_TIME) + extraTime
return rval.replace(microsecond=micros) | identifier_body |
TimeRange.py | ##
##
# File auto-generated against equivalent DynamicSerialize Java class. Then modified to add functionality
#
#
# SOFTWARE HISTORY
#
# Date Ticket# Engineer Description
# ------------ ---------- ----------- --------------------------
# ??/??/?? xxxxx... |
elif isinstance(timeArg, int):
# seconds as integer
totalSecs = timeArg
return self.__convertSecsAndMicros(totalSecs, 0)
else:
return None
def __convertSecsAndMicros(self, seconds, micros):
if seconds < MAX_TIME:
rval = datetime.d... | totalSecs = int(timeArg)
micros = int((timeArg - totalSecs) * MICROS_IN_SECOND)
return self.__convertSecsAndMicros(totalSecs, micros) | conditional_block |
TimeRange.py | ##
##
# File auto-generated against equivalent DynamicSerialize Java class. Then modified to add functionality
#
#
# SOFTWARE HISTORY
#
# Date Ticket# Engineer Description
# ------------ ---------- ----------- --------------------------
# ??/??/?? xxxxx... | totalSecs = int(timeArg)
micros = int((timeArg - totalSecs) * MICROS_IN_SECOND)
return self.__convertSecsAndMicros(totalSecs, micros)
elif isinstance(timeArg, int):
# seconds as integer
totalSecs = timeArg
return self.__convertSecsAndMicros... | return datetime.datetime(*timeArg[:6])
elif isinstance(timeArg, float):
# seconds as float, should be avoided due to floating point errors | random_line_split |
TimeRange.py | ##
##
# File auto-generated against equivalent DynamicSerialize Java class. Then modified to add functionality
#
#
# SOFTWARE HISTORY
#
# Date Ticket# Engineer Description
# ------------ ---------- ----------- --------------------------
# ??/??/?? xxxxx... | (self):
return self._getInMillis(self.start)
def setStart(self, start, extraMicros=None):
self.start = self.__convertToDateTimeWithExtra(start, extraMicros)
def getEnd(self):
return self.end.utctimetuple()
def getEndInMillis(self):
return self._getInMillis(self.end)
d... | getStartInMillis | identifier_name |
cache_aligned.rs | use alloc::heap::{allocate, deallocate};
use std::fmt;
use std::mem::size_of;
use std::ops::{Deref, DerefMut};
use std::ptr::{self, Unique};
const CACHE_LINE_SIZE: usize = 64;
unsafe fn allocate_cache_line(size: usize) -> *mut u8 {
allocate(size, CACHE_LINE_SIZE)
}
pub struct CacheAligned<T: Sized> {
ptr: Uni... | (&self) -> &T {
unsafe { self.ptr.get() }
}
}
impl<T: Sized> DerefMut for CacheAligned<T> {
fn deref_mut(&mut self) -> &mut T {
unsafe { self.ptr.get_mut() }
}
}
impl<T: Sized> CacheAligned<T> {
pub fn allocate(src: T) -> CacheAligned<T> {
unsafe {
let alloc = alloc... | deref | identifier_name |
cache_aligned.rs | use alloc::heap::{allocate, deallocate};
use std::fmt;
use std::mem::size_of;
use std::ops::{Deref, DerefMut};
use std::ptr::{self, Unique};
const CACHE_LINE_SIZE: usize = 64;
unsafe fn allocate_cache_line(size: usize) -> *mut u8 {
allocate(size, CACHE_LINE_SIZE)
}
pub struct CacheAligned<T: Sized> {
ptr: Uni... |
}
| {
T::fmt(&*self, f)
} | identifier_body |
cache_aligned.rs | use alloc::heap::{allocate, deallocate}; | use std::fmt;
use std::mem::size_of;
use std::ops::{Deref, DerefMut};
use std::ptr::{self, Unique};
const CACHE_LINE_SIZE: usize = 64;
unsafe fn allocate_cache_line(size: usize) -> *mut u8 {
allocate(size, CACHE_LINE_SIZE)
}
pub struct CacheAligned<T: Sized> {
ptr: Unique<T>,
}
impl<T: Sized> Drop for CacheA... | random_line_split | |
fckcustom.js | // CHANGE FOR APPS HOSTED IN SUBDIRECTORY
FCKRelativePath = '';
// DON'T CHANGE THESE
FCKConfig.LinkBrowserURL = FCKConfig.BasePath + 'filemanager/browser/default/browser.html?Connector='+FCKRelativePath+'/fckeditor/command';
FCKConfig.ImageBrowserURL = FCKConfig.BasePath + 'filemanager/browser/default/browser.ht... | ['JustifyLeft','JustifyCenter','JustifyRight','JustifyFull'],
['Link','Unlink'],
'/',
['Image','Table','Rule','Smiley'],
['FontName','FontSize'],
['TextColor','BGColor'],
['-','About']
] ; | ['Bold','Italic','Underline','StrikeThrough','-','Subscript','Superscript'],
['OrderedList','UnorderedList','-','Outdent','Indent'],
| random_line_split |
app.module.ts | import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { RegisterCompo... | { }
| AppModule | identifier_name |
app.module.ts | import { BrowserModule } from '@angular/platform-browser'; | import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component';
import { HomeComponent } from './home/home.component';
import { routing } from './app.routing';
import... | import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms'; | random_line_split |
test_bea.py | # -*- coding: utf-8 -*-
import io
import os
from dlstats.fetchers.bea import BEA as Fetcher
import httpretty
from dlstats.tests.base import RESOURCES_DIR as BASE_RESOURCES_DIR
from dlstats.tests.fetchers.base import BaseFetcherTestCase
import unittest
from unittest import mock
RESOURCES_DIR = os.path.abspath(os.p... | (self):
return {
"nipa-section1-10101-a": {
'dataset_code': 'nipa-section1-10101-a',
'name': 'Table 1.1.1. Percent Change From Preceding Period in Real Gross Domestic Product - Annually',
'last_update': None,
'metadata': {
'filename': 'nipa-se... | _get_datasets_settings | identifier_name |
test_bea.py | # -*- coding: utf-8 -*-
import io
import os
from dlstats.fetchers.bea import BEA as Fetcher
import httpretty
from dlstats.tests.base import RESOURCES_DIR as BASE_RESOURCES_DIR
from dlstats.tests.fetchers.base import BaseFetcherTestCase
import unittest
from unittest import mock
RESOURCES_DIR = os.path.abspath(os.p... |
for series in series_list:
self.assertEquals(series["last_update_ds"], dataset["last_update"])
| search_k = "%s-a" % k
search_name = "%s - Annually" % v
self.assertTrue(search_k in series_keys, "%s not in series_keys" % search_k)
self.assertEquals(series_keys[search_k]["name"], search_name) | conditional_block |
test_bea.py | # -*- coding: utf-8 -*-
import io
import os
from dlstats.fetchers.bea import BEA as Fetcher
import httpretty
from dlstats.tests.base import RESOURCES_DIR as BASE_RESOURCES_DIR
from dlstats.tests.fetchers.base import BaseFetcherTestCase
import unittest
from unittest import mock
RESOURCES_DIR = os.path.abspath(os.p... |
@httpretty.activate
@unittest.skipUnless('FULL_TEST' in os.environ, "Skip - no full test")
def test_load_datasets_update(self):
dataset_code = "nipa-section1-10101-a"
self._load_files(dataset_code)
self.assertLoadDatasetsUpdate([dataset_code])
#@httpretty.activate
@u... | dataset_code = "nipa-section1-10101-a"
self._load_files(dataset_code)
self.assertLoadDatasetsFirst([dataset_code]) | identifier_body |
test_bea.py | # -*- coding: utf-8 -*-
import io
import os
from dlstats.fetchers.bea import BEA as Fetcher
import httpretty
from dlstats.tests.base import RESOURCES_DIR as BASE_RESOURCES_DIR
from dlstats.tests.fetchers.base import BaseFetcherTestCase
import unittest
from unittest import mock
RESOURCES_DIR = os.path.abspath(os.p... | 'key': 'A191RL1-A',
'name': 'Gross domestic product - Annually',
'frequency': 'A',
'last_update': None,
'first_value': {
'value': '3.1',
'period': '1969',
'attributes': None,
},
'last_value': {
'value': '2.4',
... | 'dataset_code': 'nipa-section1-10101-a', | random_line_split |
tpd_graph_xml2dot.py | ##############################################################################
# Copyright (c) 2000-2016 Ericsson Telecom AB
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available ... |
f.write("}\n")
f.close()
# use this to generate graph:
# > dot -Tpng project_hierarchy_graph.dot -o project_hierarchy_graph.png
| f.write(project.attrib['name'])
f.write(" -> ")
f.write(reference.attrib['name'])
f.write(";\n") | conditional_block |
tpd_graph_xml2dot.py | # All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
#
# Contributors:
# Balasko, Jeno
# Delic, Adam
#
########################... | ##############################################################################
# Copyright (c) 2000-2016 Ericsson Telecom AB | random_line_split | |
cacheWrapper.test.ts | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you... | cache = new Map<string, any>();
wrappedFn = cacheWrapper(fn, cache, (...args) => `key-${args[0]}`);
});
it('saves fn result in cache under generated key', () => {
wrappedFn(1, 2);
expect(cache.get('key-1')).toEqual(fnResult);
});
it('subsequent calls with same generated key cal... | describe('with custom keyFn', () => {
let cache: Map<string, any>;
beforeEach(() => { | random_line_split |
angular-locale_luo.js | 'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_pre... | "DAH",
"DAU",
"DAO",
"DAB",
"DOC",
"DAP",
"DGI",
"DAG"
],
"STANDALONEMONTH": [
"Dwe mar Achiel",
"Dwe mar Ariyo",
"Dwe mar Adek",
"Dwe mar Ang\u2019wen",
"Dwe mar Abich",
"Dwe mar Auchiel",
"Dwe mar Abiriyo",
"Dwe ma... | "DAR",
"DAD",
"DAN", | random_line_split |
angular-locale_luo.js | 'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function | (n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.... | getDecimals | identifier_name |
angular-locale_luo.js | 'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) |
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"OD",
"OT"
],
... | {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
} | identifier_body |
angular-locale_luo.js | 'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_pre... | return PLURAL_CATEGORY.OTHER;}
});
}]);
| { return PLURAL_CATEGORY.ONE; } | conditional_block |
xgb.py | # This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load in
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O... | sub = pd.read_csv('data/sample_submission.csv')
for c in sub.columns[sub.columns != 'ParcelId']:
sub[c] = p_test
sub.to_csv('out/xgb.csv', index=False, float_format='%.4f') |
del x_test; gc.collect()
print("Start write result ...") | random_line_split |
xgb.py | # This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load in
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O... |
df_train = train.merge(prop, how='left', on='parcelid')
x_train = df_train.drop(['parcelid', 'logerror', 'transactiondate', 'propertyzoningdesc', 'propertycountylandusecode'], axis=1)
y_train = df_train['logerror'].values
print(x_train.shape, y_train.shape)
train_columns = x_train.columns
for c in x_train.dtypes[x... | prop[c] = prop[c].astype(np.float32) | conditional_block |
docs.tsx | import React from 'react'
import {createUseStyles, useTheme, ThemeProvider} from 'react-jss'
/* -------------------- EXPLICIT EXAMPLE -------------------- */
// Define Component
type RuleNames = 'myButton' | 'myLabel'
interface ButtonProps {
children?: React.ReactNode
spacing?: number
fontWeight?: string
labe... | // Note: First occurence of data function must provide `Props` and `Theme`.
// It must also be defined at the `RuleNames` level.
const useStylesImplicitObj = createUseStyles({
myLabel: ({theme, ...props}: ButtonProps & {theme: CustomTheme}) => ({
display: 'block',
color: props.labelColor || 'red',
fontWei... | random_line_split | |
docs.tsx | import React from 'react'
import {createUseStyles, useTheme, ThemeProvider} from 'react-jss'
/* -------------------- EXPLICIT EXAMPLE -------------------- */
// Define Component
type RuleNames = 'myButton' | 'myLabel'
interface ButtonProps {
children?: React.ReactNode
spacing?: number
fontWeight?: string
labe... | ({children, ...props}: ButtonProps): React.ReactElement {
const theme = useTheme<CustomTheme>()
const classes = useStyles({...props, theme})
return (
<button className={classes.myButton}>
<span className={classes.myLabel}>{children}</span>
</button>
)
}
// Create App
const theme = {background: '... | Button | identifier_name |
docs.tsx | import React from 'react'
import {createUseStyles, useTheme, ThemeProvider} from 'react-jss'
/* -------------------- EXPLICIT EXAMPLE -------------------- */
// Define Component
type RuleNames = 'myButton' | 'myLabel'
interface ButtonProps {
children?: React.ReactNode
spacing?: number
fontWeight?: string
labe... |
// Create App
const theme = {background: 'black'}
function App(): React.ReactElement {
return (
<ThemeProvider theme={theme}>
<Button fontWeight="bold">Submit</Button>
</ThemeProvider>
)
}
/* -------------------- IMPLICIT EXAMPLES -------------------- */
// Note: `Theme` must be typed by the `them... | {
const theme = useTheme<CustomTheme>()
const classes = useStyles({...props, theme})
return (
<button className={classes.myButton}>
<span className={classes.myLabel}>{children}</span>
</button>
)
} | identifier_body |
issue-16272.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let status = Command::new(&env::current_exe().unwrap())
.arg("foo").arg("")
.status().unwrap();
assert!(status.success());
}
| test | identifier_name |
issue-16272.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 test() {
let status = Command::new(&env::current_exe().unwrap())
.arg("foo").arg("")
.status().unwrap();
assert!(status.success());
}
| {
assert_eq!(len, 3);
} | conditional_block |
issue-16272.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | let status = Command::new(&env::current_exe().unwrap())
.arg("foo").arg("")
.status().unwrap();
assert!(status.success());
} | }
fn test() { | random_line_split |
issue-16272.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let status = Command::new(&env::current_exe().unwrap())
.arg("foo").arg("")
.status().unwrap();
assert!(status.success());
} | identifier_body | |
lexer.rs | use lexeme::Lexeme;
/***
* Structure Lexer
* -> Lexical Analyzer structure used to analyze given source code
*/
#[allow(dead_code)]
pub struct Lexer<'a>{
index: usize,
errors: u32,
code: String,
whitespaces: String,
terminals: Vec<&'a str>,
lexemes: Vec<Lexeme>
}
#[allow(dead_code)]
impl<'a>... | (code: String) -> Lexer<'a> {
Lexer {
index: 0,
errors: 0,
code: code,
whitespaces: String::from(" \t"),
terminals: vec![
"let","for","while","do_while","if",
"else_if","else","continue","break","return",
... | new | identifier_name |
lexer.rs | use lexeme::Lexeme;
/***
* Structure Lexer
* -> Lexical Analyzer structure used to analyze given source code
*/
#[allow(dead_code)]
pub struct Lexer<'a>{
index: usize,
errors: u32,
code: String,
whitespaces: String,
terminals: Vec<&'a str>,
lexemes: Vec<Lexeme>
}
#[allow(dead_code)]
impl<'a>... |
}
| {
let mut s = String::new();
self.index += 1;
while self.getc() != '\"' {
s.push(self.getc());
self.index += 1;
}
self.index += 1;
Lexeme::StringLiteral(s)
} | identifier_body |
lexer.rs | use lexeme::Lexeme;
/***
* Structure Lexer
* -> Lexical Analyzer structure used to analyze given source code
*/
#[allow(dead_code)]
pub struct Lexer<'a>{
index: usize,
errors: u32,
code: String,
whitespaces: String,
terminals: Vec<&'a str>,
lexemes: Vec<Lexeme>
}
#[allow(dead_code)]
impl<'a>... |
}
if !construct {
if self.getc().is_numeric() {
lexemes.push(self.number());
} else if self.getc() == '\"' {
lexemes.push(self.string());
} else if self.getc().is_alphabetic() {
lexemes.p... | {
lexemes.push(self.lexemes[i].clone());
self.index += self.terminals[i].len();
construct = true;
break;
} | conditional_block |
lexer.rs | use lexeme::Lexeme;
/***
* Structure Lexer
* -> Lexical Analyzer structure used to analyze given source code
*/
#[allow(dead_code)]
pub struct Lexer<'a>{
index: usize,
errors: u32,
code: String,
whitespaces: String,
terminals: Vec<&'a str>,
lexemes: Vec<Lexeme>
}
#[allow(dead_code)]
impl<'a>... | if self.errors > 0 {
println!("Total Errors : {}", self.errors);
} else {
println!("Build Successful!");
println!("_________________");
}
lexemes
}
// returns number of errors
pub fn count_errors(&mut self) -> u32 {
self.errors
... | }
}
} | random_line_split |
serializeFormExt.jQuery.js | (function( $ ) {
$.fn.serializeFormExt = function(callback) {
| var ret = new FormData();
var loading = 0;
var xcallback = function () {
if (loading > 0)
setTimeout(xcallback, 250);
else
callback(ret);
};
var reader = {
file: function (fileObj) {
fileObj = $(f... | var form = $(this);
| random_line_split |
sphere.rs | use material::Material;
use vector::Vector4;
use ray::Ray;
use renderable::{ IntersectionRecord, Renderable };
use std::rc::Rc;
pub struct Sphere {
center: Vector4,
radius: f32,
material: Rc<Box<Material>>,
}
impl Sphere {
pub fn new<TMaterial: Material + 'static>(center: Vector4, radius: f32, materia... | (intersection_point - self.center) / self.radius,
self.material.clone(),
));
}
let distance = (-b + sqrt_discriminant) / a;
if distance < distance_max && distance > distance_min {
let intersection_po... | {
let o_minus_c = ray.origin() - self.center;
let a = ray.direction().dot3(ray.direction());
let b = o_minus_c.dot3(ray.direction());
let c = (o_minus_c).dot3(o_minus_c) - self.radius * self.radius;
let discriminant = b * b - a * c;
// Get the distance (d) value if a ... | identifier_body |
sphere.rs | use material::Material;
use vector::Vector4;
use ray::Ray;
use renderable::{ IntersectionRecord, Renderable };
use std::rc::Rc;
pub struct Sphere {
center: Vector4,
radius: f32,
material: Rc<Box<Material>>,
}
impl Sphere {
pub fn new<TMaterial: Material + 'static>(center: Vector4, radius: f32, materia... |
}
None
}
}
| {
let intersection_point = ray.point_at_distance(distance);
return Some(IntersectionRecord::new(
distance,
intersection_point,
(intersection_point - self.center) / self.radius,
self.material.c... | conditional_block |
sphere.rs | use material::Material;
use vector::Vector4;
use ray::Ray;
use renderable::{ IntersectionRecord, Renderable };
use std::rc::Rc;
pub struct Sphere {
center: Vector4,
radius: f32,
material: Rc<Box<Material>>,
}
impl Sphere {
pub fn new<TMaterial: Material + 'static>(center: Vector4, radius: f32, materia... | (&self, ray: &Ray, distance_min: f32, distance_max: f32)
-> Option<IntersectionRecord> {
let o_minus_c = ray.origin() - self.center;
let a = ray.direction().dot3(ray.direction());
let b = o_minus_c.dot3(ray.direction());
let c = (o_minus_c).dot3(o_minus_c) - self.radius * self.... | intersects | identifier_name |
sphere.rs | use material::Material;
use vector::Vector4;
use ray::Ray;
use renderable::{ IntersectionRecord, Renderable };
use std::rc::Rc;
pub struct Sphere {
center: Vector4,
radius: f32,
material: Rc<Box<Material>>,
}
impl Sphere {
pub fn new<TMaterial: Material + 'static>(center: Vector4, radius: f32, materia... | } | } | random_line_split |
widgets.py | from django import forms
from django.core.urlresolvers import reverse
from django.forms.widgets import RadioFieldRenderer
from django.utils.encoding import force_text
from django.utils.html import format_html
from django.utils.safestring import mark_safe
class BootstrapChoiceFieldRenderer(RadioFieldRenderer):
"""... | )
reg_form_widget = self.widgets[1]
reg_form_widget.choices = self.reg_form_choices
#reg_form_widget.attrs = {'size':'8'}
rendered_reg_form = self.render_widget(
reg_form_widget,
name, value, final_attrs,
1, id_
)
bind_reg_for... | 0, id_ | random_line_split |
widgets.py | from django import forms
from django.core.urlresolvers import reverse
from django.forms.widgets import RadioFieldRenderer
from django.utils.encoding import force_text
from django.utils.html import format_html
from django.utils.safestring import mark_safe
class BootstrapChoiceFieldRenderer(RadioFieldRenderer):
"""... |
if widget.__class__.__name__.lower() != 'select':
classes = final_attrs.get('class', None)
if classes:
classes = classes.split(' ')
classes.remove('form-control')
classes = ' '.join(classes)
final_attrs['class'] = classes
... | final_attrs = dict(attrs, id='%s_%s' % (id_, i)) | conditional_block |
widgets.py | from django import forms
from django.core.urlresolvers import reverse
from django.forms.widgets import RadioFieldRenderer
from django.utils.encoding import force_text
from django.utils.html import format_html
from django.utils.safestring import mark_safe
class BootstrapChoiceFieldRenderer(RadioFieldRenderer):
"""... | (self, attrs=None, reg_form_choices=None, event_id=None):
self.attrs = attrs
self.reg_form_choices = reg_form_choices
self.event_id = event_id
if not self.attrs:
self.attrs = {'id': 'use_custom_reg'}
self.widgets = (
forms.CheckboxInput(),
fo... | __init__ | identifier_name |
widgets.py | from django import forms
from django.core.urlresolvers import reverse
from django.forms.widgets import RadioFieldRenderer
from django.utils.encoding import force_text
from django.utils.html import format_html
from django.utils.safestring import mark_safe
class BootstrapChoiceFieldRenderer(RadioFieldRenderer):
"""... |
def render(self, name, value, attrs=None):
if not isinstance(value, list):
value = self.decompress(value)
final_attrs = self.build_attrs(attrs)
id_ = final_attrs.get('id', None)
use_custom_reg_form_widget = self.widgets[0]
rendered_use_custom_reg_form = self.re... | self.attrs = attrs
self.reg_form_choices = reg_form_choices
self.event_id = event_id
if not self.attrs:
self.attrs = {'id': 'use_custom_reg'}
self.widgets = (
forms.CheckboxInput(),
forms.Select(attrs={'class': 'form-control'}),
forms.Rad... | identifier_body |
pt-BR.js | export default {
cancel: 'Cancelar',
reply: 'Responder',
onMyWay: 'Estou a caminho',
customMessage: 'Mensagem personalizada',
callMeBackIn: 'Ligue de novo em',
willCallYouBackIn: 'Você pode ligar de novo em',
min: 'min.',
hours: 'horas',
days: 'dias',
};
| // @key: @#@"reply"@#@ @source: @#@"Reply"@#@
// @key: @#@"onMyWay"@#@ @source: @#@"On my way"@#@
// @key: @#@"customMessage"@#@ @source: @#@"Custom Message"@#@
// @key: @#@"callMeBackIn"@#@ @source: @#@"Call me back in"@#@
// @key: @#@"willCallYouBackIn"@#@ @source: @#@"Will call you back in"@#@
// @key: @#@"min"@#@ @... | // @key: @#@"cancel"@#@ @source: @#@"Cancel"@#@ | random_line_split |
ns.box.js | (updated, layout, params) {
var layoutViews = layout.views;
var layoutActive = {};
for (var id in layoutViews) {
var childViewLayout = layoutViews[id];
// Согласно новому layout'у здесь должен быть view с id/params.
// Создаем его (если он уже есть, он возьмется из this.views).
... | e = ns.View.prototype._getCommonTree;
ns.Box.prototype.isValidWithDesc = ns.View.prototype.isValidWithDesc;
ns.Box.prototype.isOk = no.true;
ns.Box.prototype.isLoading | conditional_block | |
ns.box.js | , params, type) {
var key = this._getViewKey(id, params, type);
return this.views[key];
};
/**
*
* @param {string} id
* @param {object} params
* @param {ns.L} type
* @returns {ns.View}
* @private
*/
ns.Box.prototype._addView = function(id, params, type) {
var view = this._getView(id, params, type);
... | random_line_split | ||
forconfig.py | #!/usr/bin/python3
#Copyright Xoristzatziki
import configparser
import os,sys
class MyConfigs():
def | (self,filename):
self.myconfigfilename = filename
def readconfigvalue(self, wichsection, wichoption, default):
try:
cp = configparser.ConfigParser()
cp.read(self.myconfigfilename)
return cp.get(wichsection,wichoption)
except configparser.NoSection... | __init__ | identifier_name |
forconfig.py | #!/usr/bin/python3
#Copyright Xoristzatziki
import configparser
import os,sys
class MyConfigs():
def __init__(self,filename):
self.myconfigfilename = filename
def readconfigvalue(self, wichsection, wichoption, default):
try:
cp = configparser.ConfigParser()
c... |
else:
cp.add_section(whichsection)
cp.set(whichsection, whichoption, whichvalue)
#cp.set('main','width',whichvalue)
with open(self.myconfigfilename, 'w') as f:
cp.write(f)
#print self.myconfigfilename
if __name__ == "__main__":
#print pygtk
#... | pass | conditional_block |
forconfig.py | #!/usr/bin/python3
#Copyright Xoristzatziki
import configparser
import os,sys
class MyConfigs():
def __init__(self,filename):
self.myconfigfilename = filename
def readconfigvalue(self, wichsection, wichoption, default):
try:
cp = configparser.ConfigParser()
c... | print("Exception: ", str(sys.exc_info()) )
return default
def writeconfigvalue(self, whichsection, whichoption, whichvalue):
b = os.path.split(self.myconfigfilename)
b = os.path.join(b[:-1])
if not os.path.isdir(b[0]):
os.makedirs(b[0])#self.... | except configparser.NoSectionError:
return default
except:#oops... | random_line_split |
forconfig.py | #!/usr/bin/python3
#Copyright Xoristzatziki
import configparser
import os,sys
class MyConfigs():
def __init__(self,filename):
self.myconfigfilename = filename
def readconfigvalue(self, wichsection, wichoption, default):
|
def writeconfigvalue(self, whichsection, whichoption, whichvalue):
b = os.path.split(self.myconfigfilename)
b = os.path.join(b[:-1])
if not os.path.isdir(b[0]):
os.makedirs(b[0])#self.myconfigfilename)
cp = configparser.ConfigParser()
cp.read(self.m... | try:
cp = configparser.ConfigParser()
cp.read(self.myconfigfilename)
return cp.get(wichsection,wichoption)
except configparser.NoSectionError:
return default
except:#oops...
print("Exception: ", str(sys.exc_info()) )
return default | identifier_body |
video-list.component.ts | //ng2
import {Component, Injectable, OnInit} from 'angular2/core'; //View
import {NgFor} from 'angular2/common';
import {HTTP_PROVIDERS} from 'angular2/http';
import {Router} from 'angular2/router';
import {VideoService} from '../video.services';
import {IVideo} from '../../../../shared/data-models/video.model.... |
} | {
this.selectedVideo = selection;
console.log('selected video with id: ' + selection.id);
this._router.navigate(['Video', { mode: 'watch', id: selection.id }]);
} | identifier_body |
video-list.component.ts | //ng2
import {Component, Injectable, OnInit} from 'angular2/core'; //View
import {NgFor} from 'angular2/common';
import {HTTP_PROVIDERS} from 'angular2/http';
import {Router} from 'angular2/router';
import {VideoService} from '../video.services';
import {IVideo} from '../../../../shared/data-models/video.model.... | (
private _router: Router,
private _videoService: VideoService) {
this._videoService.getVideos()
.subscribe(
res => this.videos.push(res),
error => console.log(error)
);
}
//from-code approach
onVideo... | constructor | identifier_name |
video-list.component.ts | //ng2
import {Component, Injectable, OnInit} from 'angular2/core'; //View
import {NgFor} from 'angular2/common';
import {HTTP_PROVIDERS} from 'angular2/http';
import {Router} from 'angular2/router';
import {VideoService} from '../video.services';
import {IVideo} from '../../../../shared/data-models/video.model.... | //from-code approach
onVideoSelected(selection: IVideo) {
this.selectedVideo = selection;
console.log('selected video with id: ' + selection.id);
this._router.navigate(['Video', { mode: 'watch', id: selection.id }]);
}
} | );
}
| random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.