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 |
|---|---|---|---|---|
validation-mapping.ts | import { Observable, Subject, Subscriber } from 'rxjs';
import {
ValidationResultCompose,
MakeValidationResult
} from '../validation';
import { AbstractSource } from '../sources';
import {
Behavior,
FormElementBehavior,
FormElement
} from '../common';
/**
* Подключение Lodash (не Underscore!)
* @... | identifier_body | ||
validation-mapping.ts | import { Observable, Subject, Subscriber } from 'rxjs';
import {
ValidationResultCompose,
MakeValidationResult
} from '../validation';
import { AbstractSource } from '../sources';
import {
Behavior,
FormElementBehavior,
FormElement
} from '../common';
/**
* Подключение Lodash (не Underscore!)
* @... | * @returns {boolean}
* @private
*/
private _checkValuesChanged(): boolean{
let result = false,
newValue = JSON.stringify(this.element.control.value);
// проверка изменений элемента
if(!this._prevValue || (newValue !== this._prevValue)){
result = true;
... | * Проверка: не изменялись ли с момента последней
* валдиации значение элемента и/или других элементов,
* от которого он зависит.
* | random_line_split |
exceptions.py | #---------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
#---------------------------------------------------------------------... | pass | identifier_body | |
exceptions.py | #---------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
#---------------------------------------------------------------------... | (Exception):
pass | InvalidLineException | identifier_name |
exceptions.py | #---------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
#---------------------------------------------------------------------... | #OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
#SOFTWARE.
#pylint: skip-file
class InvalidLineException(Exception):
pass | #THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#LIABILITY, WHETHER I... | random_line_split |
recentcontactsnew.js | See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The SF licenses this file
* to you 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
*
* ... | "sortOn" :"_lastModified",
"sortOrder":"desc"
};
$.ajax({
url: sakai.config.URL.POOLED_CONTENT_SPECIFIC_USER,
data: params,
success: function(latestContent){
if(latestContent.results.length > 0){
... | // get related content for group
var params = {
"userid" : newjson.profile.userid,
"page" : 0,
"items" : 1, | random_line_split |
recentcontactsnew.js | See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The SF licenses this file
* to you 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
*
* ... |
};
/**
* This function will replace all
* @param {String} term The search term that needs to be converted.
*/
var prepSearchTermForURL = function(term) {
// Filter out http:// as it causes the search feed to break
term = term.replace(/http:\/\... | {
$("#recentcontactsnew_no_results_container").show();
$(".recentcontactsnew_main").hide();
} | conditional_block |
reader.rs | macro_rules! impl_fastx_reader {
($multiline_fastq:expr, $DefaultPositionStore:ty, ($($mod_path:expr),*)) => {
impl_reader!(
Reader, crate::fastx::RefRecord<S>, crate::fastx::OwnedRecord,
crate::fastx::RecordSet<S>, crate::fastx::Error,
crate::core::QualRecordPosition, $DefaultPositionStore, true, $mul... | fn _new(reader: R, capacity: usize, policy: P) -> Self {
Reader {
inner: crate::core::CoreReader::new(reader, capacity, policy),
fasta: None,
}
}
#[inline]
fn _from_buf_reader(rdr: crate::core::BufReader<R, P>, byte_offset: usize, line_idx: u64) -> Self {
... | R: std::io::Read,
P: crate::policy::BufPolicy,
S: crate::core::QualRecordPosition,
{
#[inline] | random_line_split |
lib.rs | // Copyright (C) 2014 The 6502-rs Developers
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of ... | // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR... | random_line_split | |
1022000.js | , "2ndjob" : false, "3thJobI" : false, "3thJobC" : false};
job = 110;
function start() {
if (cm.getJobId() == 0) {
actionx["1stJob"] = true;
if (cm.getLevel() >= 10)
cm.sendNext("Do you want to become a Warrior? You need to meet some criteria in order to do so.#b You should be at least ... | (mode, type, selection) {
status++;
if (mode == 0 && type != 1)
status -= 2;
if (status == -1){
start();
return;
} else if (mode != 1 || status == 7 && type != 1 || (actionx["1stJob"] && status == 4) || (cm.haveItem(4031008) && status == 2) || (actionx["3thJob"] && status == 1)){... | action | identifier_name |
1022000.js | , "2ndjob" : false, "3thJobI" : false, "3thJobC" : false};
job = 110;
function start() {
if (cm.getJobId() == 0) {
actionx["1stJob"] = true;
if (cm.getLevel() >= 10)
cm.sendNext("Do you want to become a Warrior? You need to meet some criteria in order to do so.#b You should be at least ... |
} else if (cm.getLevel() >= 30 && cm.getJobId() == 100) {
actionx["2ndJob"] = true;
if (cm.haveItem(4031012))
cm.sendNext("Oh... you came back safe! I knew you'd breeze through. I'll admit, you are a strong, formidable Warrior! Alright, I'll make you an even stronger Warrior than you al... | {
cm.sendOk("Train a bit more and I can show you the way of the #rWarrior#k.");
cm.dispose();
} | conditional_block |
1022000.js | brought #b#t4031059##k to me. Good! this surely proves your strength. In terms of strength, you are ready to advance to 3th job. As I promised, I will give #b#t4031057##k to you. Give this necklace to #b#p2020008##k in Ossyria and you will be able to take second test of 3rd job advancement. Good Luck~");
} else {
... | /* 3th Job Part | random_line_split | |
1022000.js | , "2ndjob" : false, "3thJobI" : false, "3thJobC" : false};
job = 110;
function start() | cm.sendNext("I was waiting for you. Few days ago, I heard about you from #b#p2020008##k in Ossyria. Well... I'd like to test your strength. There is a secret passage near the ant tunnel. Nobody but you can go into that passage. If you go into the passage, you will meat my the other self. Beat him and bring #b#t... | {
if (cm.getJobId() == 0) {
actionx["1stJob"] = true;
if (cm.getLevel() >= 10)
cm.sendNext("Do you want to become a Warrior? You need to meet some criteria in order to do so.#b You should be at least in level 10, with at least 35 in STR#k. Let's see...");
else {
cm.se... | identifier_body |
column.js | import React from 'react';
import PropTypes from 'prop-types';
import { supportsPassiveEvents } from 'detect-passive-events';
import { scrollTop } from '../scroll';
export default class Column extends React.PureComponent {
static propTypes = {
children: PropTypes.node,
label: PropTypes.string,
bindToDoc... |
handleWheel = () => {
if (typeof this._interruptScrollAnimation !== 'function') {
return;
}
this._interruptScrollAnimation();
}
setRef = c => {
this.node = c;
}
componentDidMount () {
if (this.props.bindToDocument) {
document.addEventListener('wheel', this.handleWheel, sup... | {
const scrollable = this.props.bindToDocument ? document.scrollingElement : this.node.querySelector('.scrollable');
if (!scrollable) {
return;
}
this._interruptScrollAnimation = scrollTop(scrollable);
} | identifier_body |
column.js | import React from 'react';
import PropTypes from 'prop-types';
import { supportsPassiveEvents } from 'detect-passive-events';
import { scrollTop } from '../scroll';
export default class Column extends React.PureComponent {
static propTypes = {
children: PropTypes.node,
label: PropTypes.string,
bindToDoc... | else {
this.node.removeEventListener('wheel', this.handleWheel);
}
}
render () {
const { label, children } = this.props;
return (
<div role='region' aria-label={label} className='column' ref={this.setRef}>
{children}
</div>
);
}
}
| {
document.removeEventListener('wheel', this.handleWheel);
} | conditional_block |
column.js | import React from 'react';
import PropTypes from 'prop-types';
import { supportsPassiveEvents } from 'detect-passive-events';
import { scrollTop } from '../scroll';
export default class Column extends React.PureComponent {
static propTypes = {
children: PropTypes.node,
label: PropTypes.string,
bindToDoc... | () {
if (this.props.bindToDocument) {
document.removeEventListener('wheel', this.handleWheel);
} else {
this.node.removeEventListener('wheel', this.handleWheel);
}
}
render () {
const { label, children } = this.props;
return (
<div role='region' aria-label={label} className=... | componentWillUnmount | identifier_name |
column.js | import React from 'react';
import PropTypes from 'prop-types';
import { supportsPassiveEvents } from 'detect-passive-events';
import { scrollTop } from '../scroll';
export default class Column extends React.PureComponent {
static propTypes = {
children: PropTypes.node,
label: PropTypes.string,
bindToDoc... | );
}
} | {children}
</div> | random_line_split |
rhnCache.py | cache = Cache()
cache.delete(name)
def __get_cache(raw, compressed):
cache = Cache()
if compressed:
cache = CompressedCache(cache)
if not raw:
cache = ObjectCache(cache)
return cache
class UnreadableFileError(Exception):
pass
def _safe_create(fname, user, group, mode):
... | self.cache = cache | identifier_body | |
rhnCache.py | constant I'm not too happy about but one way or another we have
# to reserve our own shared memory space.
CACHEDIR = "/var/cache/rhn"
def cleanupPath(path):
"""take ~taw/../some/path/$MOUNT_POINT/blah and make it sensible."""
if path is None:
return None
return os.path.normpath(
os.path.e... |
# If we got here, it means the directory exists
# file does not exist, attempt to create it
# we pass most of the exceptions through
try:
fd = os.open(fname, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0644)
except OSError, e:
# The file may be already there
... | try:
#os.makedirs(dirname, 0755)
makedirs(dirname, mode, user, group)
except OSError, e:
# There is a window between the moment we check the disk and
# the one we try to create the directory
# We double-check the file existance ... | conditional_block |
rhnCache.py | import gzip
import cPickle
import fcntl
import sys
from stat import ST_MTIME
from errno import EEXIST
from rhnLib import timestamp
from spacewalk.common.fileutils import makedirs, setPermsPath
# this is a constant I'm not too happy about but one way or another we have
# to reserve our own shared memory space.
CACHED... |
import os | random_line_split | |
rhnCache.py | constant I'm not too happy about but one way or another we have
# to reserve our own shared memory space.
CACHEDIR = "/var/cache/rhn"
def cleanupPath(path):
"""take ~taw/../some/path/$MOUNT_POINT/blah and make it sensible."""
if path is None:
return None
return os.path.normpath(
os.path.e... | (self, name, modified=None):
fd = self.get_file(name, modified)
s = fd.read()
fd.close()
return s
def set(self, name, value, modified=None, user='root', group='root',
mode=0755):
fd = self.set_file(name, modified, user, group, mode)
fd.write(value)
... | get | identifier_name |
project.rs | // Evelyn: Your personal assistant, project manager and calendar
// Copyright (C) 2017 Gregory Jensen
//
// 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
//... | (
client: &Client,
project_id: &String,
user_id: &String,
user_groups: Vec<model::user_group::UserGroupsExternalModel>,
) -> Result<project_model::ProjectModel, EvelynDatabaseError> {
let collection = client.db("evelyn").collection("agile_project");
let mut filter = build_project_lookup_filter(... | lookup | identifier_name |
project.rs | // Evelyn: Your personal assistant, project manager and calendar
// Copyright (C) 2017 Gregory Jensen
//
// 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
//... | }
}
pub fn lookup_contributing_to(
client: &Client,
user_id: &String,
user_groups: Vec<model::user_group::UserGroupsExternalModel>,
) -> Result<Vec<project_model::ProjectPreviewModel>, EvelynDatabaseError> {
let collection = client.db("evelyn").collection("agile_project");
let filter = build_... | {
let collection = client.db("evelyn").collection("agile_project");
let ref project_id = user_group_contributor_model.project_id;
let filter = doc!("projectId" => project_id);
let mut update_query = Document::new();
let bson_user_group_contributor_model = bson::to_bson(&user_group_contributor_mode... | identifier_body |
project.rs | // Evelyn: Your personal assistant, project manager and calendar
// Copyright (C) 2017 Gregory Jensen
//
// 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
//... |
}
pub fn lookup_contributing_to(
client: &Client,
user_id: &String,
user_groups: Vec<model::user_group::UserGroupsExternalModel>,
) -> Result<Vec<project_model::ProjectPreviewModel>, EvelynDatabaseError> {
let collection = client.db("evelyn").collection("agile_project");
let filter = build_projec... | {
Some(EvelynDatabaseError::SerialisationFailed(EvelynBaseError::NothingElse))
} | conditional_block |
project.rs | // Evelyn: Your personal assistant, project manager and calendar
// Copyright (C) 2017 Gregory Jensen
//
// 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
//... |
let ref project_id = user_contributor_model.project_id;
let filter = doc!("projectId" => project_id);
let mut update_query = Document::new();
let bson_user_contributor_model = bson::to_bson(&user_contributor_model.user_contributor).unwrap();
if let bson::Bson::Document(document) = bson_user_contri... | ) -> Option<EvelynDatabaseError> {
let collection = client.db("evelyn").collection("agile_project"); | random_line_split |
remix.ts | export interface RemixRenderer {
(props: any): JSX.Element | null;
}
export class Remix<R extends RemixRenderer> {
public displayName: string | null;
public renderer: R;
constructor(renderer: R, displayName: string | null = null) {
this.displayName = displayName;
this.renderer = renderer;
}
}
expor... | <R extends RemixRenderer>(displayName: string | R, renderer?: R): Remix<R> {
if (typeof displayName === 'function') {
return new Remix<R>(displayName, (<any>displayName).name || 'AnonymousRemix');
}
if (typeof renderer === 'function') {
return new Remix<R>(renderer, <string>displayName || (<any>renderer).... | remix | identifier_name |
remix.ts | export interface RemixRenderer {
(props: any): JSX.Element | null;
}
export class Remix<R extends RemixRenderer> {
public displayName: string | null;
public renderer: R;
constructor(renderer: R, displayName: string | null = null) {
this.displayName = displayName;
this.renderer = renderer;
}
}
expor... |
if (typeof renderer === 'function') {
return new Remix<R>(renderer, <string>displayName || (<any>renderer).name || 'AnonymousRemix');
}
throw new TypeError('No renderer was provided.');
}
| {
return new Remix<R>(displayName, (<any>displayName).name || 'AnonymousRemix');
} | conditional_block |
remix.ts | export interface RemixRenderer {
(props: any): JSX.Element | null;
}
export class Remix<R extends RemixRenderer> {
public displayName: string | null;
public renderer: R;
constructor(renderer: R, displayName: string | null = null) {
this.displayName = displayName;
this.renderer = renderer;
}
}
expor... |
throw new TypeError('No renderer was provided.');
} | if (typeof renderer === 'function') {
return new Remix<R>(renderer, <string>displayName || (<any>renderer).name || 'AnonymousRemix');
} | random_line_split |
normalization.py | future__ import division
import numpy as np
from joblib import Parallel, delayed
from .extern.interpolate import SmoothSpline
def normalize_spectrum(wave, flux, norm_range, dwave,
p=(1E-6, 1E-6), q=0.5, ivar=None, eps=1e-10,
rsv_frac=1.):
""" A double smooth normali... |
else:
# default config is even weight
var = np.ones_like(flux)
# wave = wave[~mask]
# flux = flux[~mask]
# check q region
assert 0. < q < 1.
# n_iter = len(p)
n_bin = np.int(np.fix(np.diff(norm_range) / dwave) + 1)
wave1 = norm_range[0]
# SMOOTH 1
# print(wav... | ivar = np.where(np.logical_or(wave < norm_range[0],
wave > norm_range[1]), 0, ivar)
ivar = np.where(ivar <= eps, eps, ivar)
# mask = ivar <= eps
var = 1. / ivar | conditional_block |
normalization.py | __ import division
import numpy as np
from joblib import Parallel, delayed
from .extern.interpolate import SmoothSpline
def normalize_spectrum(wave, flux, norm_range, dwave,
p=(1E-6, 1E-6), q=0.5, ivar=None, eps=1e-10,
rsv_frac=1.):
""" A double smooth normalization... | (wave, flux_block, norm_range, dwave,
p=(1E-6, 1E-6), q=0.5, ivar_block=None, eps=1e-10,
rsv_frac=3., n_jobs=1, verbose=10):
""" normalize multiple spectra using the same configuration
This is specially designed for TheKeenan
Parameters
----------... | normalize_spectra_block | identifier_name |
normalization.py | __ import division
import numpy as np
from joblib import Parallel, delayed
from .extern.interpolate import SmoothSpline
def normalize_spectrum(wave, flux, norm_range, dwave,
p=(1E-6, 1E-6), q=0.5, ivar=None, eps=1e-10,
rsv_frac=1.):
""" A double smooth normalization... |
Converted from Chao Liu's normSpectrum.m
Updated by Bo Zhang
Parameters
----------
wave: ndarray (n_pix, )
wavelegnth array
flux: ndarray (n_pix, )
flux array
norm_range: tuple
a tuple consisting (wave_start, wave_stop)
dwave: float
binning width
p: ... | random_line_split | |
normalization.py | __ import division
import numpy as np
from joblib import Parallel, delayed
from .extern.interpolate import SmoothSpline
def normalize_spectrum(wave, flux, norm_range, dwave,
p=(1E-6, 1E-6), q=0.5, ivar=None, eps=1e-10,
rsv_frac=1.):
| percentile, between 0 and 1
ivar: ndarray (n_pix, ) | None
ivar array, default is None
eps: float
the ivar threshold
rsv_frac: float
the fraction of pixels reserved in terms of std. default is 3.
Returns
-------
flux_norm: ndarray
normalized flux
flux... | """ A double smooth normalization of a spectrum
Converted from Chao Liu's normSpectrum.m
Updated by Bo Zhang
Parameters
----------
wave: ndarray (n_pix, )
wavelegnth array
flux: ndarray (n_pix, )
flux array
norm_range: tuple
a tuple consisting (wave_start, wave_stop... | identifier_body |
tankipas.js |
/*
* grunt-tankipas
* https://github.com/Leny/grunt-tankipas
*
* Copyright (c) 2014 Leny
* Licensed under the MIT license.
*/
"use strict";
var chalk, error, spinner, tankipas;
tankipas = require("tankipas");
chalk = require("chalk");
error = chalk.bold.red;
(spinner = require("simple-spinner")).change_seque... | return grunt.registerTask("tankipas", "Compute approximate development time spent on a project, using logs from version control system.", tankipasTask);
}
};
| urn grunt.registerMultiTask("tankipas", "Compute approximate development time spent on a project, using logs from version control system.", tankipasTask);
} else {
| conditional_block |
tankipas.js | /*
* grunt-tankipas
* https://github.com/Leny/grunt-tankipas
*
* Copyright (c) 2014 Leny
* Licensed under the MIT license.
*/
"use strict";
var chalk, error, spinner, tankipas;
tankipas = require("tankipas");
chalk = require("chalk");
error = chalk.bold.red;
| (spinner = require("simple-spinner")).change_sequence(["◓", "◑", "◒", "◐"]);
module.exports = function(grunt) {
var tankipasTask;
tankipasTask = function() {
var fNext, oOptions;
fNext = this.async();
oOptions = this.options({
system: null,
gap: 120,
user: null,
branch: null,
... | random_line_split | |
date-display.js | /**
* Copyright 2019 The AMP HTML Authors. 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
* | * limitations under the License.
*/
import {useResourcesNotify} from '../../../src/preact/utils';
/** @const {string} */
const DEFAULT_LOCALE = 'en';
/** @const {number} */
const DEFAULT_OFFSET_SECONDS = 0;
/** @typedef {{
year: number,
month: number,
monthName: string,
monthNameShort: string,
day: numb... | * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and | random_line_split |
date-display.js | /**
* Copyright 2019 The AMP HTML Authors. 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 require... | else if (timestampMs) {
epoch = timestampMs;
} else if (timestampSeconds) {
epoch = timestampSeconds * 1000;
}
if (epoch === undefined) {
console /*OK*/
.error('One of datetime, timestamp-ms, or timestamp-seconds is required');
}
return epoch;
}
/**
* @param {number} input
* @return {s... | {
epoch = Date.parse(datetime);
if (isNaN(epoch)) {
console /*OK*/
.error(`Invalid date: ${datetime}`);
}
} | conditional_block |
date-display.js | /**
* Copyright 2019 The AMP HTML Authors. 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 require... | }),
'hour': date.getUTCHours(),
'minute': date.getUTCMinutes(),
'second': date.getUTCSeconds(),
'iso': date.toISOString(),
};
}
| {
return {
'year': date.getUTCFullYear(),
'month': date.getUTCMonth() + 1,
'monthName': date.toLocaleDateString(locale, {
month: 'long',
timeZone: 'UTC',
}),
'monthNameShort': date.toLocaleDateString(locale, {
month: 'short',
timeZone: 'UTC',
}),
'day': date.getUTCD... | identifier_body |
date-display.js | /**
* Copyright 2019 The AMP HTML Authors. 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 require... | (props) {
const {
displayIn = '',
locale = DEFAULT_LOCALE,
offsetSeconds = DEFAULT_OFFSET_SECONDS,
} = props;
const epoch = getEpoch(props);
const offset = offsetSeconds * 1000;
const date = new Date(epoch + offset);
const basicData =
displayIn.toLowerCase() === 'utc'
? getVariablesI... | getDataForTemplate | identifier_name |
hofstadter_q.rs | // http://rosettacode.org/wiki/Hofstadter_Q_sequence
// An iterable version.
// Define a struct which stores the state for the iterator.
struct | {
next: usize,
memoize_vec: Vec<usize>
}
impl HofstadterQ {
// Define a constructor for the struct.
fn new() -> HofstadterQ {
HofstadterQ { next: 1, memoize_vec: vec![1] }
}
}
// Implement the hofstadter q iteration sequence.
impl Iterator for HofstadterQ {
type Item = usize;
// Thi... | HofstadterQ | identifier_name |
hofstadter_q.rs | // http://rosettacode.org/wiki/Hofstadter_Q_sequence
// An iterable version.
// Define a struct which stores the state for the iterator.
struct HofstadterQ {
next: usize,
memoize_vec: Vec<usize>
}
impl HofstadterQ {
// Define a constructor for the struct.
fn new() -> HofstadterQ {
HofstadterQ { ... | for _ in 3..upto {
it.next();
}
assert_eq!(expected, it.next().unwrap());
} | random_line_split | |
test_wavsteg.py | import numpy as np
import os
from random import choice
from stego_lsb.WavSteg import hide_data, recover_data
import string
import unittest
import wave
class TestWavSteg(unittest.TestCase):
def write_random_wav(self, filename, num_channels, sample_width, framerate, num_frames):
if sample_width != 1 and sam... |
if __name__ == "__main__":
unittest.main()
| self.check_random_interleaving(byte_depth=2) | identifier_body |
test_wavsteg.py | import numpy as np
import os
from random import choice
from stego_lsb.WavSteg import hide_data, recover_data
import string
import unittest
import wave
class TestWavSteg(unittest.TestCase):
def write_random_wav(self, filename, num_channels, sample_width, framerate, num_frames):
if sample_width != 1 and sam... | np.random.seed(0)
for _ in range(num_trials):
num_channels = np.random.randint(1, 64)
num_frames = np.random.randint(1, 16384)
num_lsb = np.random.randint(1, 8 * byte_depth + 1)
payload_len = (num_frames * num_lsb * num_channels) // 8
self.wri... | wav_output_filename = filename + "_steg.wav"
payload_output_filename = filename + "_recovered.txt"
| random_line_split |
test_wavsteg.py | import numpy as np
import os
from random import choice
from stego_lsb.WavSteg import hide_data, recover_data
import string
import unittest
import wave
class TestWavSteg(unittest.TestCase):
def write_random_wav(self, filename, num_channels, sample_width, framerate, num_frames):
if sample_width != 1 and sam... | unittest.main() | conditional_block | |
test_wavsteg.py | import numpy as np
import os
from random import choice
from stego_lsb.WavSteg import hide_data, recover_data
import string
import unittest
import wave
class | (unittest.TestCase):
def write_random_wav(self, filename, num_channels, sample_width, framerate, num_frames):
if sample_width != 1 and sample_width != 2:
# WavSteg doesn't support higher sample widths
raise ValueError("File has an unsupported bit-depth")
file = wave.open(fil... | TestWavSteg | identifier_name |
data_loader.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/. */
extern crate hyper;
use ipc_channel::ipc;
use net_traits::LoadConsumer::Channel;
use net_traits::LoadData;
use ne... |
#[test]
fn base64_ct() {
assert_parse("data:application/octet-stream;base64,C62+7w==",
Some(ContentType(Mime(TopLevel::Application, SubLevel::Ext("octet-stream".to_string()), vec!()))),
None,
Some(vec!(0x0B, 0xAD, 0xBE, 0xEF)));
}
#[test]
fn base64_charset() {
assert_parse("data:text/... | {
assert_parse(
"data:;base64,C62+7w==",
Some(ContentType(Mime(TopLevel::Text,
SubLevel::Plain,
vec!((Attr::Charset, Value::Ext("us-ascii".to_owned())))))),
Some("US-ASCII".to_owned()), Some(vec!(0x0B, 0xAD, 0xBE, 0xEF)));
} | identifier_body |
data_loader.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/. */
extern crate hyper;
use ipc_channel::ipc;
use net_traits::LoadConsumer::Channel;
use net_traits::LoadData;
use ne... | () {
assert_parse(
"data:;base64,C62+7w==",
Some(ContentType(Mime(TopLevel::Text,
SubLevel::Plain,
vec!((Attr::Charset, Value::Ext("us-ascii".to_owned())))))),
Some("US-ASCII".to_owned()), Some(vec!(0x0B, 0xAD, 0xBE, 0xEF)));
}
#[t... | base64 | identifier_name |
data_loader.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/. */
extern crate hyper;
use ipc_channel::ipc;
use net_traits::LoadConsumer::Channel;
use net_traits::LoadData;
use ne... |
Some(dat) => {
assert_eq!(progress, Payload(dat));
assert_eq!(response.progress_port.recv().unwrap(), Done(Ok(())));
}
}
}
#[test]
fn empty_invalid() {
assert_parse("data:", None, None, None);
}
#[test]
fn plain() {
assert_parse(
"data:,hello%20world",
... | {
assert_eq!(progress, Done(Err("invalid data uri".to_string())));
} | conditional_block |
data_loader.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/. */
extern crate hyper;
use ipc_channel::ipc;
use net_traits::LoadConsumer::Channel;
use net_traits::LoadData;
use ne... | let classifier = Arc::new(MIMEClassifier::new());
load(LoadData::new(Url::parse(url).unwrap(), None),
Channel(start_chan),
classifier, CancellationListener::new(None));
let response = start_port.recv().unwrap();
assert_eq!(&response.metadata.content_type, &content_type);
assert_eq... |
let (start_chan, start_port) = ipc::channel().unwrap(); | random_line_split |
getCreationDates.js | var fs = require('fs');
var path = require('path');
var recursive = require('recursive-readdir-sync');
var git = require('simple-git');
var posts_data = __dirname + '/../data/posts_dates.json';
createFile(posts_data);
var listOfPosts = recursive(__dirname + '/../posts/');
var cleanedListOfPosts = listOfPosts.filter(... |
function writeToJsonFile(key, value, fileName) {
var file = require(fileName);
file[key] = value;
fs.writeFile(fileName, JSON.stringify(file, null, 2), function (err) {
if (err) return console.log(err);
console.log('writing ' + key + ' : ' + value + ' to ' + fileName);
});
}
| {
fs.open(filename,'r',function(err, fd){
if (err) {
fs.writeFileSync(filename, '{}');
console.log("The file was saved!");
} else {
console.log("The file exists!");
}
});
} | identifier_body |
getCreationDates.js | var fs = require('fs');
var path = require('path');
var recursive = require('recursive-readdir-sync');
var git = require('simple-git');
var posts_data = __dirname + '/../data/posts_dates.json';
createFile(posts_data);
var listOfPosts = recursive(__dirname + '/../posts/');
var cleanedListOfPosts = listOfPosts.filter(... | git().log(
['--diff-filter=A', '--follow', '--format=%aI', '--', file ],
function(err, data) {
writeToJsonFile(path.basename(file), data.latest.hash, posts_data);
});
});
function createFile(filename) {
fs.open(filename,'r',function(err, fd){
if (err) {
fs.writeFileSync(filename... | cleanedListOfPosts.forEach(function (file) { | random_line_split |
getCreationDates.js | var fs = require('fs');
var path = require('path');
var recursive = require('recursive-readdir-sync');
var git = require('simple-git');
var posts_data = __dirname + '/../data/posts_dates.json';
createFile(posts_data);
var listOfPosts = recursive(__dirname + '/../posts/');
var cleanedListOfPosts = listOfPosts.filter(... | (filename) {
fs.open(filename,'r',function(err, fd){
if (err) {
fs.writeFileSync(filename, '{}');
console.log("The file was saved!");
} else {
console.log("The file exists!");
}
});
}
function writeToJsonFile(key, value, fileName) {
var file = require(fileName);
file[key] = value;... | createFile | identifier_name |
AppointmentSchema.ts | import * as mongoose from "mongoose";
import { Model } from "mongoose";
import { Schema } from "mongoose";
var appointmentSchema: Schema = new mongoose.Schema({
description: {type: String, required: true}, | date: Date,
startTime: Number, // time as number from 0 - 1440
endTime: Number,
contactId: String,
saleId: String,
accountId: String,
userId: String,
adviserId: String,
createdAt: Date,
updatedAt: Date
})
interface IAppointmentModel extends IAppointment, mongoose.Document{
}
i... | appointmentType: String, | random_line_split |
EaselPlugin.js | typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = global || self, factory(global.window = global.window || {}));
}(this, (function (exports) { 'use strict';
/*!
* EaselPlugin 3.4.2
* https://greensock.com
*
* @license Copyright 2008-2020, GreenSock. All rights reserved.
... | typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : | random_line_split | |
EaselPlugin.js | {};
},
_warn = function _warn(message) {
return console.warn(message);
},
_cache = function _cache(target) {
var b = target.getBounds && target.getBounds();
if (!b) {
b = target.nominalBounds || {
x: 0,
y: 0,
width: 100,
height: 100
};
target.setBounds &... |
}
}
plugin._props.push("easel_colorFilter");
if (!target.cacheID) {
_cache(target);
}
},
_idMatrix = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0],
_lumR = 0.212671,
_lumG = 0.715160,
_lumB = 0.072169,
_applyMatrix = function _applyMatrix(m, m2) {
if ... | {
pt.op = "easel_colorFilter";
} | conditional_block |
metaDataProvider.js | import external from '../../../externalModules.js';
import getNumberValues from './getNumberValues.js';
import parseImageId from '../parseImageId.js';
import dataSetCacheManager from '../dataSetCacheManager.js';
import getImagePixelModule from './getImagePixelModule.js';
import getOverlayPlaneModule from './getOverlayP... | (type, imageId) {
const { dicomParser } = external;
const parsedImageId = parseImageId(imageId);
const dataSet = dataSetCacheManager.get(parsedImageId.url);
if (!dataSet) {
return;
}
if (type === 'generalSeriesModule') {
return {
modality: dataSet.string('x00080060'),
seriesInstanceUI... | metaDataProvider | identifier_name |
metaDataProvider.js | import external from '../../../externalModules.js';
import getNumberValues from './getNumberValues.js';
import parseImageId from '../parseImageId.js';
import dataSetCacheManager from '../dataSetCacheManager.js';
import getImagePixelModule from './getImagePixelModule.js';
import getOverlayPlaneModule from './getOverlayP... |
if (type === 'sopCommonModule') {
return {
sopClassUID: dataSet.string('x00080016'),
sopInstanceUID: dataSet.string('x00080018'),
};
}
if (type === 'petIsotopeModule') {
const radiopharmaceuticalInfo = dataSet.elements.x00540016;
if (radiopharmaceuticalInfo === undefined) {
r... | {
const modalityLUTOutputPixelRepresentation = getModalityLUTOutputPixelRepresentation(
dataSet
);
return {
windowCenter: getNumberValues(dataSet, 'x00281050', 1),
windowWidth: getNumberValues(dataSet, 'x00281051', 1),
voiLUTSequence: getLUTs(
modalityLUTOutputPixelRepresent... | conditional_block |
metaDataProvider.js | import external from '../../../externalModules.js';
import getNumberValues from './getNumberValues.js';
import parseImageId from '../parseImageId.js';
import dataSetCacheManager from '../dataSetCacheManager.js';
import getImagePixelModule from './getImagePixelModule.js';
import getOverlayPlaneModule from './getOverlayP... |
if (type === 'patientStudyModule') {
return {
patientAge: dataSet.intString('x00101010'),
patientSize: dataSet.floatString('x00101020'),
patientWeight: dataSet.floatString('x00101030'),
};
}
if (type === 'imagePlaneModule') {
const imageOrientationPatient = getNumberValues(dataSet,... | {
const { dicomParser } = external;
const parsedImageId = parseImageId(imageId);
const dataSet = dataSetCacheManager.get(parsedImageId.url);
if (!dataSet) {
return;
}
if (type === 'generalSeriesModule') {
return {
modality: dataSet.string('x00080060'),
seriesInstanceUID: dataSet.strin... | identifier_body |
metaDataProvider.js | import external from '../../../externalModules.js';
import getNumberValues from './getNumberValues.js';
import parseImageId from '../parseImageId.js';
import dataSetCacheManager from '../dataSetCacheManager.js';
import getImagePixelModule from './getImagePixelModule.js';
import getOverlayPlaneModule from './getOverlayP... |
if (type === 'overlayPlaneModule') {
return getOverlayPlaneModule(dataSet);
}
}
export default metaDataProvider; | 'x00181075'
),
},
};
} | random_line_split |
issue-23649-1.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | // 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.
use std::mem;
pub struct X([u8]);
fn _f(x: &X) -> usize { match *x { X(ref x) => { x.... | // http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | random_line_split |
issue-23649-1.rs | // Copyright 2015 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 b: &[u8] = &[11; 42];
let v: &X = unsafe { mem::transmute(b) };
assert_eq!(_f(v), 42);
}
| main | identifier_name |
issue-23649-1.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | } }
fn main() {
let b: &[u8] = &[11; 42];
let v: &X = unsafe { mem::transmute(b) };
assert_eq!(_f(v), 42);
}
| { x.len() } | conditional_block |
issue-23649-1.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn main() {
let b: &[u8] = &[11; 42];
let v: &X = unsafe { mem::transmute(b) };
assert_eq!(_f(v), 42);
}
| { match *x { X(ref x) => { x.len() } } } | identifier_body |
ui-interactions.reducer.ts | import * as local from '../actions/local.actions';
import { UiInteractions } from '../../types/';
const initialState: UiInteractions = {
selectedCategory: null,
selectedMonth: null,
columnFilters: []
};
export function uiInteractions(state: UiInteractions = initialState, action) | : (newState.columnFilters = [...newState.columnFilters, { columnName, filterValue }]);
return newState;
default:
return state;
}
}
| {
switch (action.type) {
case local.LOCAL_INSPECT_CATEGORY_DETAILS:
const newCategory = action.payload.category;
const newMonth = action.payload.month;
return newMonth === state.selectedMonth && newCategory === state.selectedCategory
? Object.assign({}, state, {
selectedCateg... | identifier_body |
ui-interactions.reducer.ts | import * as local from '../actions/local.actions';
import { UiInteractions } from '../../types/';
const initialState: UiInteractions = {
selectedCategory: null,
selectedMonth: null,
columnFilters: []
};
export function | (state: UiInteractions = initialState, action) {
switch (action.type) {
case local.LOCAL_INSPECT_CATEGORY_DETAILS:
const newCategory = action.payload.category;
const newMonth = action.payload.month;
return newMonth === state.selectedMonth && newCategory === state.selectedCategory
? Objec... | uiInteractions | identifier_name |
ui-interactions.reducer.ts | import * as local from '../actions/local.actions';
import { UiInteractions } from '../../types/';
const initialState: UiInteractions = {
selectedCategory: null,
selectedMonth: null,
columnFilters: []
}; | export function uiInteractions(state: UiInteractions = initialState, action) {
switch (action.type) {
case local.LOCAL_INSPECT_CATEGORY_DETAILS:
const newCategory = action.payload.category;
const newMonth = action.payload.month;
return newMonth === state.selectedMonth && newCategory === state.se... | random_line_split | |
xml-hint.js | (function () {
"use strict";
var Pos = CodeMirror.Pos;
function | (cm, options) {
var tags = options && options.schemaInfo;
var quote = (options && options.quoteChar) || '"';
if (!tags) return;// logO(tags, 'tags');//gets tags from schema (html in this case)
var cur = cm.getCursor(), token = cm.getTokenAt(cur);
var inner = CodeMir... | getHints | identifier_name |
xml-hint.js | (function () {
"use strict";
var Pos = CodeMirror.Pos;
function getHints(cm, options) {
var tags = options && options.schemaInfo;
| if (!tags) return;// logO(tags, 'tags');//gets tags from schema (html in this case)
var cur = cm.getCursor(), token = cm.getTokenAt(cur);
var inner = CodeMirror.innerMode(cm.getMode(), token.state);
if (inner.mode.name != "xml") return;//logO(inner.mode.name,'inner.mode.name'... | var quote = (options && options.quoteChar) || '"';
| random_line_split |
xml-hint.js | (function () {
"use strict";
var Pos = CodeMirror.Pos;
function getHints(cm, options) | }//end of my code
//logO(result, 'result');
if (!inner.state.tagName || isTag) { // Tag completion
if (isTag) {
prefix = token.string.slice(1);
replaceToken = true;
}
var cx = inner.state.context, curTag = cx && tags[cx... | {
var tags = options && options.schemaInfo;
var quote = (options && options.quoteChar) || '"';
if (!tags) return;// logO(tags, 'tags');//gets tags from schema (html in this case)
var cur = cm.getCursor(), token = cm.getTokenAt(cur);
var inner = CodeMirror.innerMode(... | identifier_body |
supplier.js | // Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt
frappe.ui.form.on("Supplier", {
before_load: function(frm) {
frappe.setup_language_field(frm);
},
refresh: function(frm) {
if(frappe.defaults.get_default("supp_master_name")!="Naming ... | } | random_line_split | |
supplier.js | // Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt
frappe.ui.form.on("Supplier", {
before_load: function(frm) {
frappe.setup_language_field(frm);
},
refresh: function(frm) {
if(frappe.defaults.get_default("supp_master_name")!="Naming ... | else {
erpnext.toggle_naming_series();
}
if(frm.doc.__islocal){
hide_field(['address_html','contact_html']);
erpnext.utils.clear_address_and_contact(frm);
}
else {
unhide_field(['address_html','contact_html']);
erpnext.utils.render_address_and_contact(frm);
}
},
});
cur_frm.fields_dict... | {
frm.toggle_display("naming_series", false);
} | conditional_block |
disc.rs | use crate::types::*;
use derive_more::From;
use futures::stream::BoxStream;
use std::{collections::HashMap, net::SocketAddr, task::Poll};
use tokio_stream::Stream;
#[cfg(feature = "discv4")]
mod v4;
#[cfg(feature = "discv4")]
pub use self::v4::{Discv4, Discv4Builder};
#[cfg(feature = "discv4")]
pub use discv4;
#[cfg... | }
}
} | random_line_split | |
disc.rs | use crate::types::*;
use derive_more::From;
use futures::stream::BoxStream;
use std::{collections::HashMap, net::SocketAddr, task::Poll};
use tokio_stream::Stream;
#[cfg(feature = "discv4")]
mod v4;
#[cfg(feature = "discv4")]
pub use self::v4::{Discv4, Discv4Builder};
#[cfg(feature = "discv4")]
pub use discv4;
#[cfg... |
}
| {
if let Some((&addr, &id)) = self.0.iter().next() {
Poll::Ready(Some(Ok(NodeRecord { id, addr })))
} else {
Poll::Ready(None)
}
} | identifier_body |
disc.rs | use crate::types::*;
use derive_more::From;
use futures::stream::BoxStream;
use std::{collections::HashMap, net::SocketAddr, task::Poll};
use tokio_stream::Stream;
#[cfg(feature = "discv4")]
mod v4;
#[cfg(feature = "discv4")]
pub use self::v4::{Discv4, Discv4Builder};
#[cfg(feature = "discv4")]
pub use discv4;
#[cfg... | (pub HashMap<SocketAddr, PeerId>);
impl Stream for Bootnodes {
type Item = anyhow::Result<NodeRecord>;
fn poll_next(
self: std::pin::Pin<&mut Self>,
_: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Self::Item>> {
if let Some((&addr, &id)) = self.0.iter().next() {
... | Bootnodes | identifier_name |
disc.rs | use crate::types::*;
use derive_more::From;
use futures::stream::BoxStream;
use std::{collections::HashMap, net::SocketAddr, task::Poll};
use tokio_stream::Stream;
#[cfg(feature = "discv4")]
mod v4;
#[cfg(feature = "discv4")]
pub use self::v4::{Discv4, Discv4Builder};
#[cfg(feature = "discv4")]
pub use discv4;
#[cfg... | else {
Poll::Ready(None)
}
}
}
| {
Poll::Ready(Some(Ok(NodeRecord { id, addr })))
} | conditional_block |
CasparCGSocketCommandEvent.ts | import { Event as BaseEventNS } from './BaseEvent'
import { Command as CommandNS } from '../AbstractCommand'
import IAMCPCommand = CommandNS.IAMCPCommand
import { AMCPUtil as AMCPUtilNS } from '../AMCP'
// AMCPUtilNS
import CasparCGSocketResponse = AMCPUtilNS.CasparCGSocketResponse
export namespace Event {
/**
*
... | extends BaseEventNS.BaseEvent {
static readonly RESPONSE = 'casparcgsocketresponseeventresponse'
static readonly INVALID_RESPONSE = 'casparcgsocketcommandeventresponseinvalid'
/**
*
*/
constructor(public response: CasparCGSocketResponse) {
super({ response })
}
/**
*
*/
valueOf(): Caspa... | CasparCGSocketResponseEvent | identifier_name |
CasparCGSocketCommandEvent.ts | import { Event as BaseEventNS } from './BaseEvent'
import { Command as CommandNS } from '../AbstractCommand'
import IAMCPCommand = CommandNS.IAMCPCommand
import { AMCPUtil as AMCPUtilNS } from '../AMCP'
// AMCPUtilNS
import CasparCGSocketResponse = AMCPUtilNS.CasparCGSocketResponse
export namespace Event {
/**
*
... |
}
/**
*
*/
export class CasparCGSocketResponseEvent extends BaseEventNS.BaseEvent {
static readonly RESPONSE = 'casparcgsocketresponseeventresponse'
static readonly INVALID_RESPONSE = 'casparcgsocketcommandeventresponseinvalid'
/**
*
*/
constructor(public response: CasparCGSocketResponse) {
... | {
return this.command
} | identifier_body |
CasparCGSocketCommandEvent.ts | import { Event as BaseEventNS } from './BaseEvent'
import { Command as CommandNS } from '../AbstractCommand'
import IAMCPCommand = CommandNS.IAMCPCommand
import { AMCPUtil as AMCPUtilNS } from '../AMCP'
// AMCPUtilNS
import CasparCGSocketResponse = AMCPUtilNS.CasparCGSocketResponse
export namespace Event {
/**
*
... | */
valueOf(): CasparCGSocketResponse {
return this.response
}
}
} | }
/**
* | random_line_split |
Main.js | // @Bind #menu1.#menuItem2.onClick
!function() {
dorado.MessageBox.alert("Dorado7.0 快速入门");
};
// @Bind #tree1.onDataRowClick
!function(self) {
// 定义Tab变量
var tab = {};
// self 代表事件所属的控件,此处指 Tree对象
// self.get("currentNode")表示获取当前被点击的节点。
with (self.get("currentNode")) {
// 制定当前的tab为IFrameTab
tab... | entTab;
} else {
// 获取ID为tabControl的对象,并添加一个新的Tab
// 设定ID为tabControl的对象的当前Tab为新创建的Tab
tab = addTab(tab);
}
// 设定当前的Tab为制定的tab
set("currentTab", tab);
}
}
}; | conditional_block | |
Main.js | // @Bind #menu1.#menuItem2.onClick
!function() {
dorado.MessageBox.alert("Dorado7.0 快速入门");
};
// @Bind #tree1.onDataRowClick
!function(self) {
// 定义Tab变量
var tab = {};
// self 代表事件所属的控件,此处指 Tree对象
// self.get("currentNode")表示获取当前被点击的节点。
with (self.get("currentNode")) {
// 制定当前的tab为IFrameTab
tab... | // 也就是刚才设定的 sample.chapter01.HelloWorld.d
tab.path = get("userData");
tab.name = get("label");
tab.closeable = true;
}
// 如果当前节点有指定的Path则打开新的tab
if (tab.path) {
with (view.get("#tabControl")) {
// 根据name查找是否已经打开过当前的Tab。
// 如果没有打开过,则需要添加一个新的Tab
var currentTab = getTab(tab.name);
if (c... | random_line_split | |
playlister.py | import os
import cPickle as pkl
from collections import namedtuple
import requests
from bs4 import BeautifulSoup
Song = namedtuple('Song', ['title', 'artist', 'album', 'length'])
class Playlist(object):
def __init__(self, title, url):
self.title = title
self.file_name = title.lower().replace(' ... |
else:
self.songs = []
def load_from_pickle(self):
with open(self.file_name, 'rb') as in_file:
self.songs = pkl.load(in_file)
def download_data(self):
url = self.url
resp = requests.get(url)
soup = BeautifulSoup(resp.text)
for song_elem... | self.load_from_pickle() | conditional_block |
playlister.py | import os
import cPickle as pkl
from collections import namedtuple
import requests
from bs4 import BeautifulSoup
Song = namedtuple('Song', ['title', 'artist', 'album', 'length'])
class Playlist(object):
def __init__(self, title, url):
self.title = title
self.file_name = title.lower().replace(' ... | def download_data(self):
url = self.url
resp = requests.get(url)
soup = BeautifulSoup(resp.text)
for song_elem in (soup.find(class_='songs')
.find_all(class_='media-body')):
title = song_elem.h4.text
ps = song_elem.find_all('p')... |
def load_from_pickle(self):
with open(self.file_name, 'rb') as in_file:
self.songs = pkl.load(in_file)
| random_line_split |
playlister.py | import os
import cPickle as pkl
from collections import namedtuple
import requests
from bs4 import BeautifulSoup
Song = namedtuple('Song', ['title', 'artist', 'album', 'length'])
class Playlist(object):
| for song_elem in (soup.find(class_='songs')
.find_all(class_='media-body')):
title = song_elem.h4.text
ps = song_elem.find_all('p')
artist, album = ps[0].text.split(u' \xb7 ')
length = ps[1].text
song = Song(title, artist,... | def __init__(self, title, url):
self.title = title
self.file_name = title.lower().replace(' ', '-') + '.pkl'
self.url = url
if os.path.isfile(self.file_name):
self.load_from_pickle()
else:
self.songs = []
def load_from_pickle(self):
with open... | identifier_body |
playlister.py | import os
import cPickle as pkl
from collections import namedtuple
import requests
from bs4 import BeautifulSoup
Song = namedtuple('Song', ['title', 'artist', 'album', 'length'])
class Playlist(object):
def __init__(self, title, url):
self.title = title
self.file_name = title.lower().replace(' ... | (self):
url = self.url
resp = requests.get(url)
soup = BeautifulSoup(resp.text)
for song_elem in (soup.find(class_='songs')
.find_all(class_='media-body')):
title = song_elem.h4.text
ps = song_elem.find_all('p')
artist, ... | download_data | identifier_name |
grid-images.component.ts | import { Component, Input } from '@angular/core';
@Component({
selector: 'grid-images',
templateUrl: './grid-images.component.html',
styleUrls: ['./grid-images.component.scss']
})
export class | {
@Input() horizontalAmount: number = 2;
@Input() images = [
'http://www.lorempixel.com/400/300/city/1',
'http://www.lorempixel.com/400/300/city/2',
'http://www.lorempixel.com/400/300/city/3',
'http://www.lorempixel.com/400/300/city/4',
'http://www.lorempixel.com/400/300/city/1',
'http:/... | GridImagesComponent | identifier_name |
grid-images.component.ts | import { Component, Input } from '@angular/core';
@Component({
selector: 'grid-images',
templateUrl: './grid-images.component.html',
styleUrls: ['./grid-images.component.scss']
})
export class GridImagesComponent{ | 'http://www.lorempixel.com/400/300/city/1',
'http://www.lorempixel.com/400/300/city/2',
'http://www.lorempixel.com/400/300/city/3',
'http://www.lorempixel.com/400/300/city/4',
'http://www.lorempixel.com/400/300/city/1',
'http://www.lorempixel.com/400/300/city/2',
'http://www.lorempixel.com/4... | @Input() horizontalAmount: number = 2;
@Input() images = [ | random_line_split |
main.ts | import '../imports/polyfills';
import '../imports/methods/todos';
import '../imports/publications/todos';
import { Meteor } from 'meteor/meteor';
import { WebApp, WebAppInternals } from 'meteor/webapp';
import {
enableProdMode,
PlatformRef,
ApplicationModule,
ApplicationRef
} from '@angular/core';
import { ... |
const platformState: PlatformState = appModuleRef.injector.get(PlatformState);
document = platformState.renderToString();
} catch (e) {
// Write errors to console
console.error('Angular SSR Error: ' + e.stack || e);
}finally{
//Make sure platform is destroyed before rendering... |
for (const callback of callbacks) {
try {
callback();
} catch (e) {
// Ignore exceptions.
console.warn('Ignoring BEFORE_APP_SERIALIZED Exception: ', e);
}
}
}
| conditional_block |
main.ts | import '../imports/polyfills';
import '../imports/methods/todos';
import '../imports/publications/todos';
import { Meteor } from 'meteor/meteor';
import { WebApp, WebAppInternals } from 'meteor/webapp';
import {
enableProdMode,
PlatformRef,
ApplicationModule,
ApplicationRef | } from '@angular/core';
import { ResourceLoader } from '@angular/compiler';
import { ɵgetDOM as getDOM } from '@angular/platform-browser';
import { platformDynamicServer, BEFORE_APP_SERIALIZED ,INITIAL_CONFIG, PlatformState } from '@angular/platform-server';
import { ServerAppModule } from '../imports/app/server-app.... | random_line_split | |
msgsend-ring-mutex-arcs.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn recv(p: &pipe) -> uint {
unsafe {
p.access_cond(|state, cond| {
while state.is_empty() {
cond.wait();
}
state.pop()
})
}
}
fn init() -> (pipe,pipe) {
let m = arc::MutexArc::new(~[]);
((&m).clone(), m)
}
fn thread_ring(i: uint, co... | {
unsafe {
p.access_cond(|state, cond| {
state.push(msg);
cond.signal();
})
}
} | identifier_body |
msgsend-ring-mutex-arcs.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (i: uint, count: uint, num_chan: pipe, num_port: pipe) {
let mut num_chan = Some(num_chan);
let mut num_port = Some(num_port);
// Send/Receive lots of messages.
for j in range(0u, count) {
//error!("task %?, iter %?", i, j);
let num_chan2 = num_chan.take_unwrap();
let num_port2 =... | thread_ring | identifier_name |
msgsend-ring-mutex-arcs.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | else {
args.clone()
};
let num_tasks = from_str::<uint>(args[1]).unwrap();
let msg_per_task = from_str::<uint>(args[2]).unwrap();
let (mut num_chan, num_port) = init();
let start = time::precise_time_s();
// create the ring
let mut futures = ~[];
for i in range(1u, num_task... | {
~[~"", ~"10", ~"100"]
} | conditional_block |
msgsend-ring-mutex-arcs.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | num_chan = Some(num_chan2);
let _n = recv(&num_port2);
//log(error, _n);
num_port = Some(num_port2);
};
}
fn main() {
let args = os::args();
let args = if os::getenv("RUST_BENCH").is_some() {
~[~"", ~"100", ~"10000"]
} else if args.len() <= 1u {
~[~"", ~"... | random_line_split | |
sample.layout.ts | import { Component, OnDestroy } from '@angular/core';
import {
NbMediaBreakpoint,
NbMediaBreakpointsService,
NbMenuItem,
NbMenuService,
NbSidebarService,
NbThemeService,
} from '@nebular/theme';
import { StateService } from '../../../@core/data/state.service';
import { Subscription } from 'rxjs/Subscripti... |
});
}
ngOnDestroy() {
this.layoutState$.unsubscribe();
this.sidebarState$.unsubscribe();
this.menuClick$.unsubscribe();
}
}
| {
this.sidebarService.collapse('menu-sidebar');
} | conditional_block |
sample.layout.ts | import { Component, OnDestroy } from '@angular/core';
import {
NbMediaBreakpoint,
NbMediaBreakpointsService,
NbMenuItem,
NbMenuService,
NbSidebarService,
NbThemeService,
} from '@nebular/theme';
import { StateService } from '../../../@core/data/state.service';
import { Subscription } from 'rxjs/Subscripti... | title: 'Tabs',
icon: 'ion ion-android-radio-button-off',
link: '/pages/ui-features/tabs',
},
];
layout: any = {};
sidebar: any = {};
protected layoutState$: Subscription;
protected sidebarState$: Subscription;
protected menuClick$: Subscription;
constructor(protected stateService: ... | random_line_split | |
sample.layout.ts | import { Component, OnDestroy } from '@angular/core';
import {
NbMediaBreakpoint,
NbMediaBreakpointsService,
NbMenuItem,
NbMenuService,
NbSidebarService,
NbThemeService,
} from '@nebular/theme';
import { StateService } from '../../../@core/data/state.service';
import { Subscription } from 'rxjs/Subscripti... | implements OnDestroy {
subMenu: NbMenuItem[] = [
{
title: 'PAGE LEVEL MENU',
group: true,
},
{
title: 'Buttons',
icon: 'ion ion-android-radio-button-off',
link: '/pages/ui-features/buttons',
},
{
title: 'Grid',
icon: 'ion ion-android-radio-button-off',
... | SampleLayoutComponent | identifier_name |
test_blogpost.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Interpreter version: python 2.7
#
import os.path
import pytest
import abclinuxuapi
from abclinuxuapi import shared
@pytest.fixture
def bp_url():
return "http://www.abclinuxu.cz/blog/bystroushaak/2015/2/bolest-proxy"
@pytest.fixture
def do_that_fucking_monkey_p... | assert len(blog.comments) == 0 | random_line_split | |
test_blogpost.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Interpreter version: python 2.7
#
import os.path
import pytest
import abclinuxuapi
from abclinuxuapi import shared
@pytest.fixture
def bp_url():
return "http://www.abclinuxu.cz/blog/bystroushaak/2015/2/bolest-proxy"
@pytest.fixture
def do_that_fucking_monkey_p... |
def test_get_uid(bpost):
assert bpost.uid == 400957
def test_get_rating(bpost):
assert bpost.rating
assert bpost.rating.rating == 100
assert bpost.rating.base == 15
def test_meta_parsing(bpost):
assert bpost.has_tux
assert bpost.created_ts == 1423587660.0
assert bpost.last_modified_ts ... | assert bpost.tags
assert "proxy" in bpost.tags
# try to add and remove tag
new_tag = abclinuxuapi.Tag("nábytek", "nabytek")
bpost.remove_tag(new_tag, throw=False)
assert new_tag not in bpost.tags
bpost.add_tag(new_tag)
assert new_tag in bpost.tags
bpost.remove_tag(new_tag, throw=Fals... | identifier_body |
test_blogpost.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Interpreter version: python 2.7
#
import os.path
import pytest
import abclinuxuapi
from abclinuxuapi import shared
@pytest.fixture
def bp_url():
return "http://www.abclinuxu.cz/blog/bystroushaak/2015/2/bolest-proxy"
@pytest.fixture
def do_that_fucking_monkey_p... | ():
"""
This may seem a little bit crazy, but this speeds up the testing 6x.
I don't need new object for each test.
"""
return BPOST
def test_constructor(bp_url):
bp = abclinuxuapi.Blogpost(bp_url)
assert bp.url == bp_url
assert bp.uid is None
assert bp.title is None
assert b... | bpost | identifier_name |
test_sphinxext_mockcoderefs.py | """Tests for documenteer.sphinext.mockcoderefs."""
from shutil import rmtree
from tempfile import mkdtemp
import pytest
from sphinx.application import Sphinx
import documenteer.sphinxext.mockcoderefs as mockcoderefs
try:
from unittest.mock import Mock
except ImportError:
from mock import Mock
@pytest.fix... |
request.addfinalizer(fin)
return app
@pytest.fixture()
def inliner(app):
return Mock(document=Mock(settings=Mock(env=Mock(app=app))))
@pytest.mark.parametrize(
"test_input,expected",
[
(("lmod", "lsst.afw"), "lsst.afw"),
(("lmod", "~lsst.afw"), "afw"),
(("lmod", "~lsst... | rmtree(dirname) | conditional_block |
test_sphinxext_mockcoderefs.py | """Tests for documenteer.sphinext.mockcoderefs."""
from shutil import rmtree
from tempfile import mkdtemp
import pytest
from sphinx.application import Sphinx
| try:
from unittest.mock import Mock
except ImportError:
from mock import Mock
@pytest.fixture()
def app(request):
src = mkdtemp()
doctree = mkdtemp()
confdir = mkdtemp()
outdir = mkdtemp()
Sphinx._log = lambda self, message, wfile, nonl=False: None
app = Sphinx(
srcdir=src,
... | import documenteer.sphinxext.mockcoderefs as mockcoderefs
| random_line_split |
test_sphinxext_mockcoderefs.py | """Tests for documenteer.sphinext.mockcoderefs."""
from shutil import rmtree
from tempfile import mkdtemp
import pytest
from sphinx.application import Sphinx
import documenteer.sphinxext.mockcoderefs as mockcoderefs
try:
from unittest.mock import Mock
except ImportError:
from mock import Mock
@pytest.fix... | ():
for dirname in (src, doctree, confdir, outdir):
rmtree(dirname)
request.addfinalizer(fin)
return app
@pytest.fixture()
def inliner(app):
return Mock(document=Mock(settings=Mock(env=Mock(app=app))))
@pytest.mark.parametrize(
"test_input,expected",
[
(("lmod", "ls... | fin | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.