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 |
|---|---|---|---|---|
main.rs | #![feature(globs)]
extern crate graphics;
extern crate piston;
// extern crate sdl2_game_window;
extern crate glfw_game_window;
// use Window = sdl2_game_window::GameWindowSDL2;
use Window = glfw_game_window::GameWindowGLFW;
use piston::{
Game,
GameIteratorSettings,
GameWindowSettings,
UpdateArgs,
... |
fn key_release(&mut self, _args: &KeyReleaseArgs) {}
fn mouse_press(&mut self, _args: &MousePressArgs) {}
fn mouse_release(&mut self, _args: &MouseReleaseArgs) {}
fn mouse_move(&mut self, _args: &MouseMoveArgs) {}
/// Moved mouse relative, not bounded by cursor.
fn mouse_relative_move(&mut sel... | {} | identifier_body |
main.rs | #![feature(globs)]
extern crate graphics;
extern crate piston;
// extern crate sdl2_game_window;
extern crate glfw_game_window;
// use Window = sdl2_game_window::GameWindowSDL2;
use Window = glfw_game_window::GameWindowGLFW;
use piston::{
Game,
GameIteratorSettings,
GameWindowSettings,
UpdateArgs,
... | () {
let mut window = Window::new(
GameWindowSettings {
title: "NanoMorph Demo".to_string(),
size: [300, 300],
fullscreen: false,
exit_on_esc: true,
}
);
let mut app = App::new();
let game_iter_settings = GameIteratorSettings {
... | main | identifier_name |
make.py | #!/usr/bin/env python
import subprocess
import os
class | (Exception):
pass
def swapExt(path, current, replacement):
path, ext = os.path.splitext(path)
if ext == current:
path += replacement
return path
else:
raise MakeException(
"swapExt: expected file name ending in %s, got file name ending in %s" % \
(cur... | MakeException | identifier_name |
make.py | #!/usr/bin/env python
import subprocess
import os | path, ext = os.path.splitext(path)
if ext == current:
path += replacement
return path
else:
raise MakeException(
"swapExt: expected file name ending in %s, got file name ending in %s" % \
(current, replacement))
headerFiles = [
'benc.h',
'bencode.... |
class MakeException(Exception):
pass
def swapExt(path, current, replacement): | random_line_split |
make.py | #!/usr/bin/env python
import subprocess
import os
class MakeException(Exception):
pass
def swapExt(path, current, replacement):
path, ext = os.path.splitext(path)
if ext == current:
path += replacement
return path
else:
raise MakeException(
"swapExt: expected file ... |
subprocess.check_call(['gcc'] + args)
def compile(codeFile, cflags=[]):
objectFile = swapExt(codeFile, '.c', '.o')
gcc(cflags, '-c', ('-o', objectFile), codeFile)
return objectFile
def link(programFile, objectFiles, cflags=[]):
gcc(cflags, ('-o', programFile), objectFiles)
if __name__ == '__main... | args.append(arg) | conditional_block |
make.py | #!/usr/bin/env python
import subprocess
import os
class MakeException(Exception):
pass
def swapExt(path, current, replacement):
|
headerFiles = [
'benc.h',
'bencode.h',
]
codeFiles = [
'benc_int.c',
'benc_bstr.c',
'benc_list.c',
'benc_dict.c',
'bencode.c',
'bcopy.c',
]
cflags = ['-g']
programFile = 'bcopy'
def gcc(*packedArgs):
args = []
for arg in packedArgs:
if isinstance(arg, list):
... | path, ext = os.path.splitext(path)
if ext == current:
path += replacement
return path
else:
raise MakeException(
"swapExt: expected file name ending in %s, got file name ending in %s" % \
(current, replacement)) | identifier_body |
forms.py | # -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2016 OSGeo
#
# 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 ... | class PocForm(forms.Form):
contact = forms.ModelChoiceField(label="New point of contact",
queryset=get_user_model().objects.all())
class ProfileForm(forms.ModelForm):
keywords = taggit.forms.TagField(
label=_("Keywords"),
required=False,
help_text=_... | random_line_split | |
forms.py | # -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2016 OSGeo
#
# 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 ... |
def clean_username(self):
# Since User.username is unique, this check is redundant,
# but it sets a nicer error message than the ORM. See #13147.
username = self.cleaned_data["username"]
try:
get_user_model().objects.get(username=username)
except get_user_model(... | model = get_user_model()
fields = ("username",) | identifier_body |
forms.py | # -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2016 OSGeo
#
# 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 ... | (forms.ModelForm):
class Meta:
model = ContactRole
exclude = ('contact', 'layer')
class PocForm(forms.Form):
contact = forms.ModelChoiceField(label="New point of contact",
queryset=get_user_model().objects.all())
class ProfileForm(forms.ModelForm):
k... | RoleForm | identifier_name |
Geo.tsx | import {getConfig} from "../../helpers/getConfig";
import {Post} from "../facebook/Post";
import {getQuestionTitleByType} from "../../helpers/getQuestionTitleByType";
import * as Model from "../../../common/models/questions/geolocation/Marker";
import {Button} from "react-bootstrap";
import {QuestionProps} from "./Ques... | else {
markers[0].latitude = lat;
markers[0].longitude = lng;
}
this.setState({
latitude: center.lat(),
longitude: center.lng(),
markers: markers,
zoom: zoom
});
}
}
}
| {
markers.push(new Marker(lat, lng));
} | conditional_block |
Geo.tsx | import {getConfig} from "../../helpers/getConfig";
import {Post} from "../facebook/Post";
import {getQuestionTitleByType} from "../../helpers/getQuestionTitleByType";
import * as Model from "../../../common/models/questions/geolocation/Marker";
import {Button} from "react-bootstrap";
import {QuestionProps} from "./Ques... | (suggestion: GeoNameEntity) {
return `${suggestion.name}, ${suggestion.countryCode}`;
}
renderSuggestion(suggestion: GeoNameEntity) {
return (
<span className="location-suggestion">{suggestion.name}, <span className="admin">{suggestion.countryCode}</span></span>
);
}
onSuggestionSelected(... | getSuggestionValue | identifier_name |
Geo.tsx | import {getConfig} from "../../helpers/getConfig";
import {Post} from "../facebook/Post";
import {getQuestionTitleByType} from "../../helpers/getQuestionTitleByType";
import * as Model from "../../../common/models/questions/geolocation/Marker";
import {Button} from "react-bootstrap";
import {QuestionProps} from "./Ques... | selectedSuggestion?: GeoNameEntity;
locationText?: string;
zoom?: number;
markers?: Model.Marker[];
map?: google.maps.Map;
}
const selectedZoomlevel = 12;
const fullyZoomedOut = 1;
export class Geo extends React.Component<GeoProps, GeoState> {
private userMarker: Model.Marker;
private conf: Configuration... | suggestions?: GeoNameEntity[];
isLoading?: boolean;
latitude?: number;
longitude?: number; | random_line_split |
Geo.tsx | import {getConfig} from "../../helpers/getConfig";
import {Post} from "../facebook/Post";
import {getQuestionTitleByType} from "../../helpers/getQuestionTitleByType";
import * as Model from "../../../common/models/questions/geolocation/Marker";
import {Button} from "react-bootstrap";
import {QuestionProps} from "./Ques... |
}
onMapClick(lat: number, lng: number, zoom: number, center: google.maps.LatLng) {
//if the user hasn't answered the question yet we create or move the marker on the map
if (!this.props.userAnswer) {
const markers = this.state.markers;
if (markers.length == 0) {
markers.push(new Marke... | {
const marker = this.state.markers[0];
this.props.onDone(new Location(marker.latitude, marker.longitude));
this.setState({
markers: [],
value: ''
});
} | identifier_body |
editorTabs-de.ts | import { EditorTabsTranslations } from './definitions';
export const editorTabsTranslationsDE: EditorTabsTranslations = {
tabsNames: {
Tester: 'Tester',
Variables: 'Variablen',
'State Machine': 'Zustandsmaschine',
'Variable Properties': 'Eigenschaften Variablen',
Files: 'Dateien',
Scripts: 'S... | newPage: 'Neue Seite',
pageName: 'Seitenname',
folderName: 'Ordnername',
itemMustName: item =>
`${item ? item : 'Das Element'} muss einen Namen haben.`,
page: 'Die Seite',
folder: 'Der Ordner',
openFile: 'Datei öffnen',
changeType: (fromFileType, toFileType) =>
`Sind Sie sich... | random_line_split | |
trait_def.rs | _data_structures::stable_hasher::{HashStable, StableHasher};
use rustc_errors::ErrorReported;
use rustc_macros::HashStable;
/// A trait's definition with type information.
#[derive(HashStable)]
pub struct TraitDef {
// We already have the def_path_hash below, no need to hash it twice
#[stable_hasher(ignore)]
... | {
continue;
} | conditional_block | |
trait_def.rs | PathHash;
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
use rustc_errors::ErrorReported;
use rustc_macros::HashStable;
/// A trait's definition with type information.
#[derive(HashStable)]
pub struct TraitDef {
// We already have the def_path_hash ... |
pub fn ancestors(
&self,
tcx: TyCtxt<'tcx>,
of_impl: DefId,
) -> Result<specialization_graph::Ancestors<'tcx>, ErrorReported> {
specialization_graph::ancestors(tcx, self.def_id, of_impl)
}
}
impl<'tcx> TyCtxt<'tcx> {
pub fn for_each_impl<F: FnMut(DefId)>(self, def_id: ... | {
TraitDef {
def_id,
unsafety,
paren_sugar,
has_auto_impl,
is_marker,
skip_array_during_method_dispatch,
specialization_kind,
def_path_hash,
}
} | identifier_body |
trait_def.rs | PathHash;
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
use rustc_errors::ErrorReported;
use rustc_macros::HashStable;
/// A trait's definition with type information.
#[derive(HashStable)]
pub struct TraitDef {
// We already have the def_path_hash ... | if let result @ Some(_) = f(impl_def_id) {
return result;
}
}
// simplify_type(.., false) basically replaces type parameters and
// projections with infer-variables. This is, of course, done on
// the impl trait-ref when it is instantiated, but no... | random_line_split | |
trait_def.rs | PathHash;
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
use rustc_errors::ErrorReported;
use rustc_macros::HashStable;
/// A trait's definition with type information.
#[derive(HashStable)]
pub struct TraitDef {
// We already have the def_path_hash ... | (
def_id: DefId,
unsafety: hir::Unsafety,
paren_sugar: bool,
has_auto_impl: bool,
is_marker: bool,
skip_array_during_method_dispatch: bool,
specialization_kind: TraitSpecializationKind,
def_path_hash: DefPathHash,
) -> TraitDef {
TraitDef {
... | new | identifier_name |
package.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
import glob
import os.path
class Xbraid(MakefilePackage):
"""XBraid: Parallel time integration w... | (self, spec, prefix):
# Install headers
mkdirp(prefix.include)
headers = glob.glob('*.h')
for f in headers:
install(f, join_path(prefix.include, os.path.basename(f)))
# Install library
mkdirp(prefix.lib)
library = 'libbraid.a'
install(library,... | install | identifier_name |
package.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
import glob
import os.path | class Xbraid(MakefilePackage):
"""XBraid: Parallel time integration with Multigrid"""
homepage = "https://computing.llnl.gov/projects/parallel-time-integration-multigrid/software"
url = "https://github.com/XBraid/xbraid/archive/v2.2.0.tar.gz"
version('2.2.0', sha256='082623b2ddcd2150b3ace65b96c1e... | random_line_split | |
package.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
import glob
import os.path
class Xbraid(MakefilePackage):
"""XBraid: Parallel time integration w... |
# Install library
mkdirp(prefix.lib)
library = 'libbraid.a'
install(library, join_path(prefix.lib, library))
# Install other material (e.g., examples, tests, docs)
mkdirp(prefix.share)
install('makefile.inc', prefix.share)
install_tree('examples', prefi... | install(f, join_path(prefix.include, os.path.basename(f))) | conditional_block |
package.py | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
import glob
import os.path
class Xbraid(MakefilePackage):
"""XBraid: Parallel time integration w... | return find_libraries('libbraid', root=self.prefix,
shared=False, recursive=True) | identifier_body | |
logging_test.py | from pathlib import Path
import pytest
from loguru import logger
from libretime_shared.logging import (
DEBUG,
INFO,
create_task_logger,
level_from_name,
setup_logger,
)
@pytest.mark.parametrize(
"name,level_name,level_no",
[
("error", "error", 40),
("warning", "warning",... |
def test_level_from_name_invalid():
with pytest.raises(ValueError):
level_from_name("invalid")
def test_setup_logger(tmp_path: Path):
log_filepath = tmp_path / "test.log"
extra_log_filepath = tmp_path / "extra.log"
setup_logger(INFO, log_filepath)
extra_logger = create_task_logger(DEB... | level = level_from_name(name)
assert level.name == level_name
assert level.no == level_no | identifier_body |
logging_test.py | from pathlib import Path
import pytest
from loguru import logger
from libretime_shared.logging import (
DEBUG,
INFO,
create_task_logger,
level_from_name,
setup_logger,
)
@pytest.mark.parametrize(
"name,level_name,level_no",
[
("error", "error", 40),
("warning", "warning",... | (tmp_path: Path):
log_filepath = tmp_path / "test.log"
extra_log_filepath = tmp_path / "extra.log"
setup_logger(INFO, log_filepath)
extra_logger = create_task_logger(DEBUG, extra_log_filepath, True)
logger.info("test info")
extra_logger.info("extra info")
logger.debug("test debug")
e... | test_setup_logger | identifier_name |
logging_test.py | from pathlib import Path
import pytest
from loguru import logger
from libretime_shared.logging import ( | create_task_logger,
level_from_name,
setup_logger,
)
@pytest.mark.parametrize(
"name,level_name,level_no",
[
("error", "error", 40),
("warning", "warning", 30),
("info", "info", 20),
("debug", "debug", 10),
("trace", "trace", 5),
],
)
def test_level_from... | DEBUG,
INFO, | random_line_split |
fixture.rs | use std::rc::Rc;
use std::cell::RefCell;
use ::collision::{BroadPhase, Shape, PolygonShape, Aabb};
use ::common::Transform2d;
use super::BodyHandleWeak;
use cgmath::*;
pub type FixtureHandle<'a> = Rc<RefCell<Fixture<'a>>>;
pub struct FixtureConfig {
pub friction: f32,
pub restitution: f32,
pub density: f3... | let aabb2 = self.shape.compute_aabb(transform2);
let proxy_aabb = Aabb::combine(&aabb1, &aabb2);
let displacement = transform2.position - transform1.position;
broad_phase.move_proxy(proxy_id, &proxy_aabb, displacement);
}
}
pub fn get_mass_data(&self) ... | if let Some(proxy_id) = self.proxy_id {
// Compute an Aabb that covers the swept shape (may miss some rotation effect).
let aabb1 = self.shape.compute_aabb(transform1); | random_line_split |
fixture.rs | use std::rc::Rc;
use std::cell::RefCell;
use ::collision::{BroadPhase, Shape, PolygonShape, Aabb};
use ::common::Transform2d;
use super::BodyHandleWeak;
use cgmath::*;
pub type FixtureHandle<'a> = Rc<RefCell<Fixture<'a>>>;
pub struct FixtureConfig {
pub friction: f32,
pub restitution: f32,
pub density: f3... |
}
pub fn get_mass_data(&self) -> (f32, Vector2<f32>, f32) {
self.shape.compute_mass(self.density)
}
/*pub fn get_shape(&self) -> &PolygonShape {
&self.shape
}*/
}
| {
// Compute an Aabb that covers the swept shape (may miss some rotation effect).
let aabb1 = self.shape.compute_aabb(transform1);
let aabb2 = self.shape.compute_aabb(transform2);
let proxy_aabb = Aabb::combine(&aabb1, &aabb2);
let displacement = transform2.... | conditional_block |
fixture.rs | use std::rc::Rc;
use std::cell::RefCell;
use ::collision::{BroadPhase, Shape, PolygonShape, Aabb};
use ::common::Transform2d;
use super::BodyHandleWeak;
use cgmath::*;
pub type FixtureHandle<'a> = Rc<RefCell<Fixture<'a>>>;
pub struct FixtureConfig {
pub friction: f32,
pub restitution: f32,
pub density: f3... | () -> FixtureConfig {
FixtureConfig {
friction: 0.2,
restitution: 0.0,
density: 0.0,
is_sensor: false,
}
}
}
pub struct Fixture<'a> {
pub body: BodyHandleWeak<'a>,
pub shape: Shape,
pub friction: f32,
pub restitution: f32,
pub dens... | default | identifier_name |
fixture.rs | use std::rc::Rc;
use std::cell::RefCell;
use ::collision::{BroadPhase, Shape, PolygonShape, Aabb};
use ::common::Transform2d;
use super::BodyHandleWeak;
use cgmath::*;
pub type FixtureHandle<'a> = Rc<RefCell<Fixture<'a>>>;
pub struct FixtureConfig {
pub friction: f32,
pub restitution: f32,
pub density: f3... |
/*pub fn get_shape(&self) -> &PolygonShape {
&self.shape
}*/
}
| {
self.shape.compute_mass(self.density)
} | identifier_body |
profiles.ts | import {JSONAPI_HEADERS} from "../constants";
import {RSAA, HTTPVerb, RSAAction} from "redux-api-middleware";
import {
encodeJSONAPIChildIndexParameters, RSAAChildIndexActionRequest,
RSAAIndexActionResponse
} from "../../json-api";
import {InstalledApplication} from "../../models";
export type PROFILES_REQUES... | export const profiles = encodeJSONAPIChildIndexParameters((device_id: string, queryParameters: Array<String>) => {
const rsaa: RSAAction<PROFILES_REQUEST, PROFILES_SUCCESS, PROFILES_FAILURE> = {
[RSAA]: {
endpoint: `/api/v1/devices/${device_id}/installed_profiles?${queryParameters.join('&')}`,
... | export type InstalledProfilesActionRequest = RSAAChildIndexActionRequest<PROFILES_REQUEST, PROFILES_SUCCESS, PROFILES_FAILURE>;
export type InstalledProfilesActionResponse = RSAAIndexActionResponse<PROFILES_REQUEST, PROFILES_SUCCESS, PROFILES_FAILURE, InstalledApplication>;
| random_line_split |
conftest.py | import pytest
import tempfile
import os
import ConfigParser
def getConfig(optionname,thedefault,section,configfile):
"""read an option from a config file or set a default
send 'thedefault' as the data class you want to get a string back
i.e. 'True' will return a string
True will return a bool... |
return options
@pytest.fixture()
def cleandir():
newpath = tempfile.mkdtemp()
os.chdir(newpath)
def pytest_report_header(config):
if config.option.verbose > 0:
return ["reporting verbose test output"]
#def pytest_addoption(parser):
#parser.addoption("--esserver",
#action="sto... | options["verbose"]=False | conditional_block |
conftest.py | import pytest
import tempfile
import os
import ConfigParser
def getConfig(optionname,thedefault,section,configfile):
"""read an option from a config file or set a default
send 'thedefault' as the data class you want to get a string back
i.e. 'True' will return a string
True will return a bool... |
#def pytest_addoption(parser):
#parser.addoption("--esserver",
#action="store",
#default="localhost:9200",
#help="elastic search servers to use for testing")
#parser.addoption("--mozdefserver",
#action="store",
#default="localhost:8080",
#help="mozdef serv... | if config.option.verbose > 0:
return ["reporting verbose test output"] | identifier_body |
conftest.py | import pytest
import tempfile
import os
import ConfigParser
def getConfig(optionname,thedefault,section,configfile):
"""read an option from a config file or set a default
send 'thedefault' as the data class you want to get a string back
i.e. 'True' will return a string
True will return a bool... | (config):
if config.option.verbose > 0:
return ["reporting verbose test output"]
#def pytest_addoption(parser):
#parser.addoption("--esserver",
#action="store",
#default="localhost:9200",
#help="elastic search servers to use for testing")
#parser.addoption("--mozdefserve... | pytest_report_header | identifier_name |
conftest.py | import pytest
import tempfile
import os
import ConfigParser
def getConfig(optionname,thedefault,section,configfile):
"""read an option from a config file or set a default
send 'thedefault' as the data class you want to get a string back
i.e. 'True' will return a string
True will return a bool | opttype=type(thedefault)
if os.path.isfile(configfile):
config = ConfigParser.ConfigParser()
config.readfp(open(configfile))
if config.has_option(section,optionname):
if opttype==bool:
retvalue=config.getboolean(section,optionname)
elif opttype==in... | 1 will return an int
"""
#getConfig('something','adefaultvalue')
retvalue=thedefault | random_line_split |
MappedSQLStringQuery.ts | /**
* Created by Papa on 10/28/2016.
*/
import {PHJsonMappedQSLQuery} from "../ph/PHMappedSQLQuery";
import {SQLDialect, QueryResultType} from "../../SQLStringQuery";
import {IQEntity} from "../../../../core/entity/Entity";
import {EntityRelationRecord} from "../../../../core/entity/Relation";
import {NonEntitySQLSt... | if (selectSqlFragment) {
throw `Mapped query must have fields in sub-select clause`;
} else {
return '*';
}
}
// For {} select causes or if '*' is present, retrieve the entire object
if (retrieveAllOwnFields) {
throw `'*' operator isn't yet implemented in mapped queries`;
}
for (let prop... | {
{
let distinctClause = <JSONClauseField>selectClauseFragment;
if (distinctClause.objectType == JSONClauseObjectType.DISTINCT_FUNCTION) {
let distinctSelect = this.getSELECTFragment(selectSqlFragment, distinctClause.__appliedFunctions__[0].parameters[0]);
return `DISTINCT ${distinctSelect}`;
}
}
... | identifier_body |
MappedSQLStringQuery.ts | /**
* Created by Papa on 10/28/2016.
*/
import {PHJsonMappedQSLQuery} from "../ph/PHMappedSQLQuery";
import {SQLDialect, QueryResultType} from "../../SQLStringQuery";
import {IQEntity} from "../../../../core/entity/Entity";
import {EntityRelationRecord} from "../../../../core/entity/Relation";
import {NonEntitySQLSt... | extends NonEntitySQLStringQuery<PHJsonMappedQSLQuery> {
protected queryParser: MappedQueryResultParser = new MappedQueryResultParser();
constructor(
phJsonQuery: PHJsonMappedQSLQuery,
qEntityMapByName: {[entityName: string]: IQEntity},
entitiesRelationPropertyMap: {[entityName: string]: {[propertyName: strin... | MappedSQLStringQuery | identifier_name |
MappedSQLStringQuery.ts | /**
* Created by Papa on 10/28/2016.
*/
import {PHJsonMappedQSLQuery} from "../ph/PHMappedSQLQuery";
import {SQLDialect, QueryResultType} from "../../SQLStringQuery";
import {IQEntity} from "../../../../core/entity/Entity";
import {EntityRelationRecord} from "../../../../core/entity/Relation";
import {NonEntitySQLSt... | else if (lastResult !== parsedResult) {
lastResult = parsedResult;
parsedResults.push(parsedResult);
}
this.queryParser.flushRow();
});
return parsedResults;
}
protected parseQueryResult(
selectClauseFragment: any,
resultRow: any,
nextFieldIndex: number[],
aliasCache: AliasCache,
entity... | {
parsedResults.push(parsedResult);
} | conditional_block |
MappedSQLStringQuery.ts | /**
* Created by Papa on 10/28/2016.
*/
import {PHJsonMappedQSLQuery} from "../ph/PHMappedSQLQuery";
import {SQLDialect, QueryResultType} from "../../SQLStringQuery";
import {IQEntity} from "../../../../core/entity/Entity";
import {EntityRelationRecord} from "../../../../core/entity/Relation";
import {NonEntitySQLSt... | ): any {
// Return blanks, primitives and Dates directly
if (!resultRow || !(resultRow instanceof Object) || resultRow instanceof Date) {
return resultRow;
}
{
let distinctClause = <JSONClauseField>selectClauseFragment;
if (distinctClause.objectType == JSONClauseObjectType.DISTINCT_FUNCTION) {
ret... | resultRow: any,
nextFieldIndex: number[],
aliasCache: AliasCache,
entityAlias: string | random_line_split |
parser.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/. */
//! The context within which CSS code is parsed.
use cssparser::{Parser, SourcePosition};
use error_reporting::Pa... | ;
#[cfg(feature = "gecko")]
pub struct ParserContextExtraData {
pub base: Option<GeckoArcURI>,
pub referrer: Option<GeckoArcURI>,
pub principal: Option<GeckoArcPrincipal>,
}
impl ParserContextExtraData {
#[cfg(not(feature = "gecko"))]
pub fn default() -> ParserContextExtraData {
ParserCont... | ParserContextExtraData | identifier_name |
parser.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/. */
//! The context within which CSS code is parsed.
use cssparser::{Parser, SourcePosition};
use error_reporting::Pa... | /// to log CSS parse errors to stderr.
pub fn log_css_error(input: &mut Parser, position: SourcePosition, message: &str, parsercontext: &ParserContext) {
parsercontext.error_reporter.report_error(input, position, message);
} | /// Set a `RUST_LOG=style::errors` environment variable | random_line_split |
parser.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/. */
//! The context within which CSS code is parsed.
use cssparser::{Parser, SourcePosition};
use error_reporting::Pa... |
pub fn new(stylesheet_origin: Origin, base_url: &'a Url, error_reporter: Box<ParseErrorReporter + Send>)
-> ParserContext<'a> {
let extra_data = ParserContextExtraData::default();
ParserContext::new_with_extra_data(stylesheet_origin, base_url, error_reporter, extra_data)
}
}
i... | {
let mut selector_context = SelectorParserContext::new();
selector_context.in_user_agent_stylesheet = stylesheet_origin == Origin::UserAgent;
ParserContext {
stylesheet_origin: stylesheet_origin,
base_url: base_url,
selector_context: selector_context,
... | identifier_body |
app.tsx | export function __reload(m) { if (m.app.state) app.setState(m.app.state); }
// style imports
import './app.css!';
// lib imports
import * as React from 'react';
import * as ReactDOM from 'react-dom';
// components imports
import {TrainingStore, TrainingModel} from './components/training-store';
import {TrainingHeader}... | );
}
}
export let app: any = ReactDOM.render(<App />, document.getElementById('app-container')); | </div> | random_line_split |
app.tsx | export function __reload(m) { if (m.app.state) app.setState(m.app.state); }
// style imports
import './app.css!';
// lib imports
import * as React from 'react';
import * as ReactDOM from 'react-dom';
// components imports
import {TrainingStore, TrainingModel} from './components/training-store';
import {TrainingHeader}... |
}
export let app: any = ReactDOM.render(<App />, document.getElementById('app-container'));
| {
return (
<div className="container">
<TrainingHeader onAdd={this.handleAdd} />
<TrainingList store={this.state.trainingStore} onRemove={this.handleRemove} />
</div>
);
} | identifier_body |
app.tsx | export function | (m) { if (m.app.state) app.setState(m.app.state); }
// style imports
import './app.css!';
// lib imports
import * as React from 'react';
import * as ReactDOM from 'react-dom';
// components imports
import {TrainingStore, TrainingModel} from './components/training-store';
import {TrainingHeader} from './components/trai... | __reload | identifier_name |
popupEditorWrapper.ts | import {Component} from "../../widgets/component";
import {ICellEditor} from "./iCellEditor";
export class PopupEditorWrapper extends Component implements ICellEditor {
private cellEditor: ICellEditor;
private params: any;
private getGuiCalledOnChild = false;
constructor(cellEditor: ICellEditor) ... |
}
public afterGuiAttached(): void {
if (this.cellEditor.afterGuiAttached) {
this.cellEditor.afterGuiAttached();
}
}
public getValue(): any {
return this.cellEditor.getValue();
}
public isPopup(): boolean {
return true;
}
} | {
this.cellEditor.init(params);
} | conditional_block |
popupEditorWrapper.ts | import {Component} from "../../widgets/component";
import {ICellEditor} from "./iCellEditor";
export class | extends Component implements ICellEditor {
private cellEditor: ICellEditor;
private params: any;
private getGuiCalledOnChild = false;
constructor(cellEditor: ICellEditor) {
super('<div class="ag-popup-editor"/>');
this.cellEditor = cellEditor;
this.addDes... | PopupEditorWrapper | identifier_name |
popupEditorWrapper.ts | import {Component} from "../../widgets/component";
import {ICellEditor} from "./iCellEditor";
export class PopupEditorWrapper extends Component implements ICellEditor {
private cellEditor: ICellEditor;
private params: any;
private getGuiCalledOnChild = false;
constructor(cellEditor: ICellEditor) ... |
public init(params: any): void {
this.params = params;
if (this.cellEditor.init) {
this.cellEditor.init(params);
}
}
public afterGuiAttached(): void {
if (this.cellEditor.afterGuiAttached) {
this.cellEditor.afterGuiAttached();
}
}
... | {
// we call getGui() on child here (rather than in the constructor)
// as we should wait for 'init' to be called on child first.
if (!this.getGuiCalledOnChild) {
this.appendChild(this.cellEditor.getGui());
this.getGuiCalledOnChild = true;
}
... | identifier_body |
popupEditorWrapper.ts | import {Component} from "../../widgets/component";
import {ICellEditor} from "./iCellEditor";
export class PopupEditorWrapper extends Component implements ICellEditor {
private cellEditor: ICellEditor;
private params: any;
private getGuiCalledOnChild = false;
constructor(cellEditor: ICellEditor) ... |
public getGui(): HTMLElement {
// we call getGui() on child here (rather than in the constructor)
// as we should wait for 'init' to be called on child first.
if (!this.getGuiCalledOnChild) {
this.appendChild(this.cellEditor.getGui());
this.getGuiCalledOnChi... | }
private onKeyDown(event: KeyboardEvent): void {
this.params.onKeyDown(event);
} | random_line_split |
test_client_authorize.py | import collections
import json
import unittest
import responses
from requests import HTTPError
from mock import patch
from batfish import Client
from batfish.__about__ import __version__
class TestClientAuthorize(unittest.TestCase):
def setUp(self):
with patch('batfish.client.read_token_from_conf',
... | url = "https://api.digitalocean.com/v2/actions"
responses.add(responses.GET, url,
body='{"error": "something"}', status=200,
content_type="application/json")
auth = self.cli.authorize("test_token")
self.assertEquals(auth, "OK")
self.assertEqual... | identifier_body | |
test_client_authorize.py | import collections
import json
import unittest
import responses
from requests import HTTPError
from mock import patch
from batfish import Client
from batfish.__about__ import __version__
class | (unittest.TestCase):
def setUp(self):
with patch('batfish.client.read_token_from_conf',
return_value=None):
self.cli = Client()
@responses.activate
def test_authorize_error(self):
url = "https://api.digitalocean.com/v2/actions"
responses.add(responses... | TestClientAuthorize | identifier_name |
test_client_authorize.py | import collections
import json
import unittest
import responses
from requests import HTTPError
from mock import patch
from batfish import Client
from batfish.__about__ import __version__
class TestClientAuthorize(unittest.TestCase):
def setUp(self):
with patch('batfish.client.read_token_from_conf',
... | def test_authorize_unauthorized(self):
url = "https://api.digitalocean.com/v2/actions"
responses.add(responses.GET, url,
body='{"error": "something"}', status=200,
content_type="application/json")
auth = self.cli.authorize("test_token")
sel... |
@responses.activate | random_line_split |
Newsletter.js | import React from 'react'
import { StyleSheet, Text, View } from 'react-native'
import PropTypes from 'prop-types'
import Slider from './Slider'
import { TextDescriptionCard } from '@components'
const styles = StyleSheet.create( {
container: {
backgroundColor: '#fff',
flexDirection: 'column',
paddingTop... | marginBottom: 15,
marginTop: 15,
paddingLeft: 20,
paddingRight: 20,
},
rowTitle: {
flexDirection: 'row',
marginTop: 28,
paddingLeft: 20,
paddingRight: 20,
},
titleText: {
fontSize: 14,
fontWeight: 'bold',
},
} )
const NewsLetter = ( { newsletter: { description, title, ... | },
detailsView: { | random_line_split |
BayesInference.py | __author__ = 'Varun Nayyar'
from Utils.MFCCArrayGen import emotions, speakers, getCorpus
from MCMC import MCMCRun
from emailAlerter import alertMe
def main2(numRuns = 100000, numMixtures = 8, speakerIndex = 6):
import time
for emotion in emotions:
start = time.ctime()
Xpoints = getCor... | for i in xrange(len(speakers)):
main2(numMixtures=8, speakerIndex=i) | conditional_block | |
BayesInference.py | __author__ = 'Varun Nayyar'
from Utils.MFCCArrayGen import emotions, speakers, getCorpus
from MCMC import MCMCRun
from emailAlerter import alertMe
def | (numRuns = 100000, numMixtures = 8, speakerIndex = 6):
import time
for emotion in emotions:
start = time.ctime()
Xpoints = getCorpus(emotion, speakers[speakerIndex])
message = MCMCRun(Xpoints, emotion+"-"+speakers[speakerIndex], numRuns, numMixtures)
message += "Start ... | main2 | identifier_name |
BayesInference.py | __author__ = 'Varun Nayyar'
from Utils.MFCCArrayGen import emotions, speakers, getCorpus | import time
for emotion in emotions:
start = time.ctime()
Xpoints = getCorpus(emotion, speakers[speakerIndex])
message = MCMCRun(Xpoints, emotion+"-"+speakers[speakerIndex], numRuns, numMixtures)
message += "Start time: {}\nEnd Time: {}\n".format(start, time.ctime())
... | from MCMC import MCMCRun
from emailAlerter import alertMe
def main2(numRuns = 100000, numMixtures = 8, speakerIndex = 6): | random_line_split |
BayesInference.py | __author__ = 'Varun Nayyar'
from Utils.MFCCArrayGen import emotions, speakers, getCorpus
from MCMC import MCMCRun
from emailAlerter import alertMe
def main2(numRuns = 100000, numMixtures = 8, speakerIndex = 6):
|
if __name__ == "__main__":
for i in xrange(len(speakers)):
main2(numMixtures=8, speakerIndex=i) | import time
for emotion in emotions:
start = time.ctime()
Xpoints = getCorpus(emotion, speakers[speakerIndex])
message = MCMCRun(Xpoints, emotion+"-"+speakers[speakerIndex], numRuns, numMixtures)
message += "Start time: {}\nEnd Time: {}\n".format(start, time.ctime())
... | identifier_body |
release.js | /*******************************
Release Config
*******************************/
var
requireDotFile = require('require-dot-file'),
config,
npmPackage,
version
;
/*******************************
Derived Values
*******************************/
try {
config = requireDotFile('pegaMultiselect... | }
catch(error) {
// generate fake package
npmPackage = {
name: 'Unknown',
version: 'x.x'
};
}
// looks for version in config or package.json (whichever is available)
version = (npmPackage && npmPackage.version !== undefined && npmPackage.name == 'Multiselect-Pega')
? npmPackage.version
: config.versi... | npmPackage = require('../../../package.json'); | random_line_split |
gcc.rs | For reference, see:
// https://github.com/gcc-mirror/gcc/blob/master/libstdc++-v3/libsupc++/eh_personality.cc
// https://github.com/gcc-mirror/gcc/blob/trunk/libgcc/unwind-c.c
// The personality routine for most of our targets, except ARM, which has a slightly different ABI
// (however, iOS goes here as it uses SjLj ... | rust_eh_unregister_frames | identifier_name | |
gcc.rs | branch in the function body, the "landing pad", which invokes destructors,
//! frees memory, etc. At the end of the landing pad, control is transferred
//! back to the unwinder and unwinding resumes.
//!
//! Once stack has been unwound down to the handler frame level, unwinding stops
//! and the last personality rout... |
pub unsafe fn cleanup(ptr: *mut u8) -> Box<dyn Any + Send> {
let my_ep = ptr as *mut Exception;
let cause = (*my_ep).cause.take();
uw::_Unwind_DeleteException(ptr as *mut _);
cause.unwrap()
}
// Rust's exception class identifier. This is used by personality routines to
// determine whether the excep... | {
ptr::null_mut()
} | identifier_body |
gcc.rs | branch in the function body, the "landing pad", which invokes destructors,
//! frees memory, etc. At the end of the landing pad, control is transferred
//! back to the unwinder and unwinding resumes.
//!
//! Once stack has been unwound down to the handler frame level, unwinding stops
//! and the last personality rout... |
#[cfg(target_arch = "x86_64")]
const UNWIND_DATA_REG: (i32, i32) = (0, 1); // RAX, RDX
#[cfg(any(target_arch = "arm", target_arch = "aarch64"))]
const UNWIND_DATA_REG: (i32, i32) = (0, 1); // R0, R1 / X0, X1
#[cfg(any(target_arch = "mips", target_arch = "mips64"))]
const UNWIND_DATA_REG: (i32, i32) = (4, 5); // A0, ... | random_line_split | |
column-click.component.ts | import { Component, ViewChild } from '@angular/core';
import {
GenericTableComponent,
GtConfig,
GtRow
} from '@angular-generic-table/core';
export interface RowData extends GtRow {
order: number;
name: string;
lucky_number: number;
}
@Component({
selector: 'app-column-click',
templateUrl: './column-click.compo... | (row: any, up: boolean = true) {
if (up) {
this.configObject.data[row.order - 2].order += 1; // update row above clicked row
row.order -= 1; // update clicked row
} else {
this.configObject.data[row.order].order -= 1; // update row below clicked row
row.order += 1; // update clicked row
}
this.myTab... | move | identifier_name |
column-click.component.ts | import { Component, ViewChild } from '@angular/core';
import {
GenericTableComponent,
GtConfig,
GtRow
} from '@angular-generic-table/core';
export interface RowData extends GtRow {
order: number;
name: string;
lucky_number: number;
}
@Component({
selector: 'app-column-click',
templateUrl: './column-click.compo... | lucky_number: 23
},
{
order: 27,
name: 'Harold',
lucky_number: 66
},
{
order: 28,
name: 'William',
lucky_number: 57
},
{
order: 29,
name: 'Harry',
lucky_number: 14
},
{
order: 30,
name: 'Dennis',
lucky_number: 9
}
]
... | order: 26,
name: 'Michael', | random_line_split |
column-click.component.ts | import { Component, ViewChild } from '@angular/core';
import {
GenericTableComponent,
GtConfig,
GtRow
} from '@angular-generic-table/core';
export interface RowData extends GtRow {
order: number;
name: string;
lucky_number: number;
}
@Component({
selector: 'app-column-click',
templateUrl: './column-click.compo... |
this.myTable.redraw(); // update table order
}
}
| {
this.configObject.data[row.order].order -= 1; // update row below clicked row
row.order += 1; // update clicked row
} | conditional_block |
gc_util.py | #!/usr/bin/env python
#------------------------------------------------------------------------------
# Copyright (C) 2013 Albert Simenon
#
# 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... | "--password","-p",
required=True,
help="Geocaching.com password")
parser.add_argument(
"--output","-o",
default="",
help="output directory")
args = parser.parse_args()
return args
def main():
""" Obviously the main routine """
args ... | """ Argument parser """
parser = argparse.ArgumentParser()
parser.formatter_class = argparse.RawDescriptionHelpFormatter
parser.description = "%s, version %s by %s (%s)\n\n%s" \
% (__filename__,__version__,__author__,__email__,__purpose__)
parser.add_argument(
"--browser","-b",
... | identifier_body |
gc_util.py | #!/usr/bin/env python
#------------------------------------------------------------------------------
# Copyright (C) 2013 Albert Simenon
#
# 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... | :
""" Geocaching.com web browser class """
BASE_URL = "http://www.geocaching.com"
LOGIN_URL = "%s/login" % (BASE_URL)
POCKET_QUERY_URL = "%s/pocket" % (BASE_URL)
CHUNK_SIZE = 1024
XPATH_DOWNLOADPQ = "//a[contains(@href,'downloadpq')]"
def __init__(self, driver, args):
self.driver = ... | GCSite | identifier_name |
gc_util.py | #!/usr/bin/env python
#------------------------------------------------------------------------------
# Copyright (C) 2013 Albert Simenon
#
# 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... |
pbar.finish()
def download_pocket_queries(self):
""" Download all pocket queries on geocaching.com """
self.driver.get(self.POCKET_QUERY_URL)
elements = self.driver.find_elements_by_xpath(self.XPATH_DOWNLOADPQ)
if elements:
for element in elements:
... | data = fhandle.read(self.CHUNK_SIZE)
if not data:
break
foutput.write(data)
pbar.update(foutput.tell()) | conditional_block |
gc_util.py | #!/usr/bin/env python
#------------------------------------------------------------------------------
# Copyright (C) 2013 Albert Simenon
#
# 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... | #
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#------------------------------------------------------------------------------
""" Gecoaching.com python ut... | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. | random_line_split |
note-parser.ts | remarkable';
import { escapeHtml, replaceEntities, unescapeMd } from 'remarkable/lib/common/utils';
import { Note, NoteMetadata, NoteSnippetTypes } from '../../../core/note';
import { WorkspaceService } from '../../shared';
import { NoteContent, NoteSnippetContent } from '../note-editor';
import { NoteContentParseResul... |
let str = '';
let startLine: number;
let endLine: number;
const nl = EOL;
const lineSpacing = numToArray(opts.lineSpacing)
.reduce(sum => `${sum}${nl}`, nl);
// Add front matter to note content raw value if exists.
if (metadataLines) {
st... | {
const opts = {
...(new NoteContentParsingOptions()),
...options,
} as NoteContentParsingOptions;
let metadataLines: string[];
if (opts.metadata) {
const metadata = yaml.safeDump(opts.metadata, {
indent: opts.indent,
});
... | identifier_body |
note-parser.ts | 'remarkable';
import { escapeHtml, replaceEntities, unescapeMd } from 'remarkable/lib/common/utils';
import { Note, NoteMetadata, NoteSnippetTypes } from '../../../core/note';
import { WorkspaceService } from '../../shared';
import { NoteContent, NoteSnippetContent } from '../note-editor';
import { NoteContentParseRes... | (contentRawValue: string): NoteContentRawValueParseResult {
const snippets = [];
const lines = contentRawValue.split('\n');
const tokens = this.markdownParser.parse(contentRawValue, { breaks: true });
for (const snippet of parseTokens(lines, tokens)) {
snippets.push(snippet)... | parseNoteContentRawValue | identifier_name |
note-parser.ts | 'remarkable';
import { escapeHtml, replaceEntities, unescapeMd } from 'remarkable/lib/common/utils';
import { Note, NoteMetadata, NoteSnippetTypes } from '../../../core/note';
import { WorkspaceService } from '../../shared';
import { NoteContent, NoteSnippetContent } from '../note-editor';
import { NoteContentParseRes... | endLine += 1; // Add 1 line.
}
str += snippet.value;
endLine += snippet.value.split(EOL).length - 1;
if (snippet.type === NoteSnippetTypes.CODE) {
str += '\n```';
endLine += 1;
}
parsedSnippets.pus... | random_line_split | |
note-parser.ts | remarkable';
import { escapeHtml, replaceEntities, unescapeMd } from 'remarkable/lib/common/utils';
import { Note, NoteMetadata, NoteSnippetTypes } from '../../../core/note';
import { WorkspaceService } from '../../shared';
import { NoteContent, NoteSnippetContent } from '../note-editor';
import { NoteContentParseResul... |
}
}
function overrideMarkdownParseToAdaptLink(md: Remarkable, assetDir: string): void {
md.renderer.rules.image = (tokens, idx, options /*, env */) => {
const srcUrl = path.resolve(assetDir, path.basename(tokens[idx].src));
const src = ' src="' + escapeHtml(srcUrl) + '"';
const title... | {
end = i;
if (i === tokens.length - 1) {
startLine = tokens[start].lines[0];
endLine = tokens[end].lines[1];
yield {
type: NoteSnippetTypes.TEXT,
value: lines.slice(startLine, endLine).join(EOL),
... | conditional_block |
facebook.ts | import cheerio from 'cheerio'
import { Service } from './service'
class Facebook extends Service {
static getProofUrl(proof: any) {
return this.normalizeUrl(proof)
}
static normalizeUrl(proof: any) {
let proofUrl = proof.proof_url.toLowerCase()
const urlRegex = /(?:http[s]*:\/\/){0,1}(?:[a-zA-Z0-9-]... | return proofUrl
}
static getProofStatement(searchText: string) {
const $ = cheerio.load(searchText)
const statement = $('meta[name="description"]').attr('content')
return (statement !== undefined) ? statement.trim() : ''
}
}
export { Facebook } | }
| random_line_split |
facebook.ts |
import cheerio from 'cheerio'
import { Service } from './service'
class Facebook extends Service {
static getProofUrl(proof: any) {
return this.normalizeUrl(proof)
}
static normalizeUrl(proof: any) | return proofUrl
}
static getProofStatement(searchText: string) {
const $ = cheerio.load(searchText)
const statement = $('meta[name="description"]').attr('content')
return (statement !== undefined) ? statement.trim() : ''
}
}
export { Facebook }
| {
let proofUrl = proof.proof_url.toLowerCase()
const urlRegex = /(?:http[s]*:\/\/){0,1}(?:[a-zA-Z0-9-]+\.)+facebook\.com/
proofUrl = super.prefixScheme(proofUrl)
if (proofUrl.startsWith('https://facebook.com')) {
let tokens = proofUrl.split('https://facebook.com')
proofUrl = `https://www.f... | identifier_body |
facebook.ts |
import cheerio from 'cheerio'
import { Service } from './service'
class Facebook extends Service {
static getProofUrl(proof: any) {
return this.normalizeUrl(proof)
}
static | (proof: any) {
let proofUrl = proof.proof_url.toLowerCase()
const urlRegex = /(?:http[s]*:\/\/){0,1}(?:[a-zA-Z0-9-]+\.)+facebook\.com/
proofUrl = super.prefixScheme(proofUrl)
if (proofUrl.startsWith('https://facebook.com')) {
let tokens = proofUrl.split('https://facebook.com')
proofUrl = `... | normalizeUrl | identifier_name |
index.js | var Chartist = require('chartist');
module.exports = makePluginInstance;
makePluginInstance.calculateScaleFactor = calculateScaleFactor;
makePluginInstance.scaleValue = scaleValue;
function makePluginInstance(userOptions) {
var defaultOptions = {
dot: {
min: 8,
max: 10,
unit: 'px'
},
... |
/**
* @param {Object} data - Object passed to 'draw' event listener
*/
function getActualSvgWidth(data) {
return data.element.root().width();
}
};
}
function calculateScaleFactor(min, max, value) {
if (max <= min) {
throw new Error('max must be > min');
}
var delta = max - min;... | {
var scaleFactor = calculateScaleFactor(thresholds.min, thresholds.max, getActualSvgWidth(data));
var strokeWidth = scaleValue(widthRange.min, widthRange.max, scaleFactor);
data.element.attr({
style: 'stroke-width: ' + strokeWidth + widthRange.unit
});
} | identifier_body |
index.js | var Chartist = require('chartist');
module.exports = makePluginInstance;
makePluginInstance.calculateScaleFactor = calculateScaleFactor;
makePluginInstance.scaleValue = scaleValue;
function makePluginInstance(userOptions) {
var defaultOptions = {
dot: {
min: 8,
max: 10,
unit: 'px'
},
... | * @param {Object} thresholds - Specifies chart width to base scaling on.
*/
function setStrokeWidth(data, widthRange, thresholds) {
var scaleFactor = calculateScaleFactor(thresholds.min, thresholds.max, getActualSvgWidth(data));
var strokeWidth = scaleValue(widthRange.min, widthRange.max, scaleF... | * Set stroke-width of the element of a 'data' object, based on chart width.
*
* @param {Object} data - Object passed to 'draw' event listener
* @param {Object} widthRange - Specifies min/max stroke-width and unit. | random_line_split |
index.js | var Chartist = require('chartist');
module.exports = makePluginInstance;
makePluginInstance.calculateScaleFactor = calculateScaleFactor;
makePluginInstance.scaleValue = scaleValue;
function makePluginInstance(userOptions) {
var defaultOptions = {
dot: {
min: 8,
max: 10,
unit: 'px'
},
... | (min, max, scaleFactor) {
if (scaleFactor > 1) throw new Error('scaleFactor cannot be > 1');
if (scaleFactor < 0) throw new Error('scaleFactor cannot be < 0');
if (max < min) throw new Error('max cannot be < min');
var delta = max - min;
return (delta * scaleFactor) + min;
}
| scaleValue | identifier_name |
main.rs | read_file(filename: &str, buffer: &mut String) -> Result<(), io::Error<>> {
let file = try!(File::open(filename));
let reader = BufReader::new(file);
for line in reader.lines() {
let line = try!(line);
buffer.push_str(&format!("{}\n", line));
}
Ok(())
}
fn | (filename: &str, buffer: &String) -> Result<(), io::Error<>> {
let mut file = try!(File::create(filename));
try!(file.write_all(&buffer.as_bytes()));
Ok(())
}
fn py_parse_args(range_str: &String) -> Vec<String> {
let mut ret = Vec::new();
let mut buf = String::new();
let mut level = 0;
for... | write_file | identifier_name |
main.rs | read_file(filename: &str, buffer: &mut String) -> Result<(), io::Error<>> {
let file = try!(File::open(filename));
let reader = BufReader::new(file);
for line in reader.lines() {
let line = try!(line);
buffer.push_str(&format!("{}\n", line));
}
Ok(())
}
fn write_file(filename: &str... | buf.push(c);
}
}
ret.push(buf.clone());
return ret;
}
fn py_range_to_string(range_str: &mut String) {
let range_args = py_parse_args(&range_str);
if !range_args.is_empty() {
let mut start = "0".to_string();
let mut end = "".to_string();
let mut step = "1... | if c == ' ' {
continue
}
if level == 0 { | random_line_split |
main.rs |
fn read_file(filename: &str, buffer: &mut String) -> Result<(), io::Error<>> {
let file = try!(File::open(filename));
let reader = BufReader::new(file);
for line in reader.lines() {
let line = try!(line);
buffer.push_str(&format!("{}\n", line));
}
Ok(())
}
fn write_file(filename:... | {
println!("Dogen - Documentation Generator for Lazy students");
println!("Copyright (c) 2016 Hannes Karppila Holder All Rights Reserved.");
println!("\n\tUsage: dogen infile\n");
} | identifier_body | |
main.rs | _file(filename: &str, buffer: &mut String) -> Result<(), io::Error<>> {
let file = try!(File::open(filename));
let reader = BufReader::new(file);
for line in reader.lines() {
let line = try!(line);
buffer.push_str(&format!("{}\n", line));
}
Ok(())
}
fn write_file(filename: &str, buf... |
let rr_decrease_one = get_group(&re_decrease_one, &inp);
if !rr_decrease_one.is_empty() {
result.push_str(&format!("# Decrease {} by one", rr_decrease_one));
return;
}
let rr_self_add = get_groups(&re_self_add, &inp);
if !rr_self_add.is_empty() {
result.push_str(&format!("#... | {
result.push_str(&format!("# Increase {} by one", rr_increase_one));
return;
} | conditional_block |
currency.ts | from './coin';
import { Token, TokenOpts, TokensListAPIUrl } from './token';
import { PersistenceProvider } from '../../providers/persistence/persistence';
export type CoinsMap<T> = { [key in string]: T };
@Injectable()
export class CurrencyProvider {
public coinOpts: CoinsMap<CoinOpts>;
public ratesApi = {} as ... | (img) {
img.onerror = null;
img.src = 'assets/img/default-erc20.svg';
}
isUtxoCoin(coin: string): boolean {
return !!this.coinOpts[coin].properties.isUtxo;
}
isSingleAddress(coin: string): boolean {
return !!this.coinOpts[coin].properties.singleAddress;
}
isSharedCoin(coin: string): boole... | defaultLogoURI | identifier_name |
currency.ts | from './coin';
import { Token, TokenOpts, TokensListAPIUrl } from './token';
import { PersistenceProvider } from '../../providers/persistence/persistence';
export type CoinsMap<T> = { [key in string]: T };
@Injectable()
export class CurrencyProvider {
public coinOpts: CoinsMap<CoinOpts>;
public ratesApi = {} as ... |
getBitpaySupportedTokens(): Token[] {
// Tokens previously supported by Bitpay that allow the payment of invoices
return this.bitpaySupportedTokens;
}
getAvailableCustomTokens(): Token[] {
// Custom tokens
return this.availableCustomTokens;
}
getMultiSigCoins(): string[] {
return this.... | {
// Tokens previously supported by Bitpay + custom tokens
return this.availableTokens;
} | identifier_body |
currency.ts | from './coin';
import { Token, TokenOpts, TokensListAPIUrl } from './token';
import { PersistenceProvider } from '../../providers/persistence/persistence';
export type CoinsMap<T> = { [key in string]: T };
@Injectable()
export class CurrencyProvider {
public coinOpts: CoinsMap<CoinOpts>;
public ratesApi = {} as ... |
isMultiSend(coin: string): boolean {
return !!this.coinOpts[coin].properties.hasMultiSend;
}
getAvailableCoins(): string[] {
return this.availableCoins;
}
getBitPayPaymentsAvailableCoins(): Token[] {
return Object.values(TokenOpts);
}
getAvailableChains(): string[] {
return _.uniq(
... | return walletId.replace(/-0x.*$/, '');
} | random_line_split |
__init__.py | # Copyright 2012 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | 'DeleteAction',
'FilterAction',
'FixedFilterAction',
'LinkAction',
'NameFilterAction',
'Column',
'DataTable',
'Row',
'WrappingColumn',
'DataTableView',
'MixedDataTableView',
'MultiTableMixin',
'MultiTableView',
'PagedTableMixin',
] | 'Action',
'BatchAction', | random_line_split |
setup.js | 'use strict';
var build = "build"; // ビルド結果が出力されるディレクトリ
var tmp = ".tmp"; // Sassコンパイルで作成されるcssのテンポラリーファイルの場所
var src = 'src'; // ソースコードの場所
module.exports = {
build: build,
tmp: tmp,
src: src,
sf: { | //Salesforceのビルド結果が出力されるディレクトリ
sfbuild: build + "/sf",
// デプロイする静的リソースの名前
resourceName: "vfResource",
// apex:pageタグの属性値
apexPageOption: {
// デフォルト値、すべてのページに適用されます
'default': {
"docType": "html-5.0",
"showHeader": false,
"standardStyleSheets": false
},
... | random_line_split | |
mdout.rs | use std::path::{Path, PathBuf};
use std::fs::{ File, rename };
use std::io::Write;
use std::io::{Result, Error, ErrorKind};
use std::cell::RefCell;
// #[derive(Debug)] // XXX: not for File
pub struct MarkdownOut {
/// Directory into which we write
outdir: PathBuf,
/// Serial number prefix for output files... | fn mkout(outdir: &PathBuf, filenum: u32, leafname: &str, is_tmp: bool) -> PathBuf {
let mut outpath = outdir.clone();
let sfx = if is_tmp {
"+" // XXX: insecure tmpfile. tmpnam is unstable & libc; rand is elsewhere
} else {
""
};
outpath.push(format!("{:02}_{}.md{}", filenum, leafna... | random_line_split | |
mdout.rs | use std::path::{Path, PathBuf};
use std::fs::{ File, rename };
use std::io::Write;
use std::io::{Result, Error, ErrorKind};
use std::cell::RefCell;
// #[derive(Debug)] // XXX: not for File
pub struct MarkdownOut {
/// Directory into which we write
outdir: PathBuf,
/// Serial number prefix for output files... | (&self) -> Result<()> {
let mut fhput = self.outfh.borrow_mut();
match *fhput {
Some(_) => {
*fhput = None;
rename(self.tmppath.as_path(), self.outpath.as_path())
},
None => self.gone(),
}
}
fn gone(&self) -> Result<()> ... | close | identifier_name |
setup.py | #!/usr/bin/env python3
# Copyright (C) 2013 LiuLang <gsushzhsosgsu@gmail.com>
# Use of this source code is governed by GPLv3 license that can be found
# in the LICENSE file.
from distutils.core import setup
from distutils.core import Command
from distutils.command.clean import clean as distutils_clean
from distutils... | ():
data_files = []
for dir, dirs, files in os.walk('share'):
#target = os.path.join('share', dir)
target = dir
if files:
files = [os.path.join(dir, f) for f in files]
data_files.append((target, files))
return data_files
# will be installed to /usr/local/bin
... | build_data_files | identifier_name |
setup.py | #!/usr/bin/env python3
# Copyright (C) 2013 LiuLang <gsushzhsosgsu@gmail.com>
# Use of this source code is governed by GPLv3 license that can be found
# in the LICENSE file.
from distutils.core import setup
from distutils.core import Command
from distutils.command.clean import clean as distutils_clean
from distutils... |
# will be installed to /usr/local/bin
scripts = ['qr-gui', ]
if __name__ == '__main__':
setup(
name = 'qr-gui',
description = Config.DESCRIPTION,
version = Config.VERSION,
license = 'GPLv3',
url = Config.HOMEPAGE,
author = 'LiuLang',
author_email = 'gsushz... | data_files = []
for dir, dirs, files in os.walk('share'):
#target = os.path.join('share', dir)
target = dir
if files:
files = [os.path.join(dir, f) for f in files]
data_files.append((target, files))
return data_files | identifier_body |
setup.py | #!/usr/bin/env python3
# Copyright (C) 2013 LiuLang <gsushzhsosgsu@gmail.com>
# Use of this source code is governed by GPLv3 license that can be found
# in the LICENSE file.
from distutils.core import setup
from distutils.core import Command
from distutils.command.clean import clean as distutils_clean
from distutils... | setup(
name = 'qr-gui',
description = Config.DESCRIPTION,
version = Config.VERSION,
license = 'GPLv3',
url = Config.HOMEPAGE,
author = 'LiuLang',
author_email = 'gsushzhsosgsu@gmail.com',
packages = ['qr_gui', ],
scripts = scripts,
data_f... | conditional_block | |
setup.py | #!/usr/bin/env python3
# Copyright (C) 2013 LiuLang <gsushzhsosgsu@gmail.com> | # in the LICENSE file.
from distutils.core import setup
from distutils.core import Command
from distutils.command.clean import clean as distutils_clean
from distutils.command.sdist import sdist as distutils_sdist
import glob
import os
import shutil
from qr_gui import Config
def build_data_files():
data_files = [... |
# Use of this source code is governed by GPLv3 license that can be found | random_line_split |
base.py | """
Django settings for CollegeSeatAllocation project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
from django.core.urlresolvers import reverse_lazy
from os.pat... |
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
# Raises ImproperlyConfigured exception if SECRET_KEY not in os.environ
SECRET_KEY = env('SECRET_KEY')
ALLOWED_HOS... | environ.Env.read_env(str(env_file)) | conditional_block |
base.py | """
Django settings for CollegeSeatAllocation project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
from django.core.urlresolvers import reverse_lazy
from os.pat... |
ROOT_URLCONF = 'CollegeSeatAllocation.urls'
WSGI_APPLICATION = 'CollegeSeatAllocation.wsgi.application'
# Database
# https://docs.djangoproject.com/en/dev/ref/settings/#databases
DATABASES = {
# Raises ImproperlyConfigured exception if DATABASE_URL not in
# os.environ
'default': env.db(),
}
# Internati... | ) | random_line_split |
14-builder-uglify-badmodule-cmd.js | var vows = require('vows'),
assert = require('assert'),
path = require('path'),
fs = require('fs'),
exec = require('child_process').exec,
base = path.join(__dirname, 'assets/badmodule/'),
buildBase = path.join(base, 'build'),
srcBase = path.join(base, 'src/foo'),
rimraf = require('rimraf... | stderr: stderr
});
});
},
'should fail with an error code 1': function (topic) {
assert.equal(topic.error.code, 1);
},
'should fail with an error message': function... | error: error, | random_line_split |
impl1.py | ## mostly copied from: http://norvig.com/spell-correct.html
import sys, random
import re, collections, time
TXT_FILE='';
BUF_DIR='';
NWORDS=None;
def words(text): |
def train(features):
model = collections.defaultdict(lambda: 1)
for f in features:
model[f] += 1
return model
alphabet = 'abcdefghijklmnopqrstuvwxyz'
def edits1(word):
splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]
deletes = [a + b[1:] for a, b in splits if b]
tra... | return re.findall('[a-z]+', text) | identifier_body |
impl1.py | ## mostly copied from: http://norvig.com/spell-correct.html
import sys, random
import re, collections, time
TXT_FILE='';
BUF_DIR='';
NWORDS=None;
def words(text): return re.findall('[a-z]+', text)
def train(features):
model = collections.defaultdict(lambda: 1)
for f in features:
model[f] += 1
r... | (word):
return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS)
def known(words): return set(w for w in words if w in NWORDS)
def correct(word):
candidates = known([word]) or known(edits1(word)) or known_edits2(word) or [word]
return max(candidates, key=NWORDS.get)
####################... | known_edits2 | identifier_name |
impl1.py | ## mostly copied from: http://norvig.com/spell-correct.html
import sys, random
import re, collections, time
TXT_FILE='';
BUF_DIR='';
NWORDS=None;
def words(text): return re.findall('[a-z]+', text)
def train(features):
model = collections.defaultdict(lambda: 1)
for f in features:
model[f] += 1
r... |
t0 = time.clock()
o_words = words(file(TXT_FILE).read())
NWORDS = train(o_words)
#print time.clock() - t0, " seconds build time"
#print "dictionary size: %d" %len(NWORDS)
et1 = time.clock() - t0
t_count = 10
rl = o_words[0:t_count] #random.sample(o_words, t_count)
orl = [''.join(random.sample(word, len(word)... |
#######################################################################################
if __name__ == '__main__':
TXT_FILE = sys.argv[1] | random_line_split |
impl1.py | ## mostly copied from: http://norvig.com/spell-correct.html
import sys, random
import re, collections, time
TXT_FILE='';
BUF_DIR='';
NWORDS=None;
def words(text): return re.findall('[a-z]+', text)
def train(features):
model = collections.defaultdict(lambda: 1)
for f in features:
model[f] += 1
r... |
#######################################################################################
print 'Done'
| TXT_FILE = sys.argv[1]
t0 = time.clock()
o_words = words(file(TXT_FILE).read())
NWORDS = train(o_words)
#print time.clock() - t0, " seconds build time"
#print "dictionary size: %d" %len(NWORDS)
et1 = time.clock() - t0
t_count = 10
rl = o_words[0:t_count] #random.sample(o_words, t_count)
orl = [''.join(random... | conditional_block |
gutters.py | #------------------------------------------------------------------------------
# Copyright (c) 2010, Enthought Inc
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD license.
#
# Author: Enthought Inc
# Description: <Enthought pyface code editor>
#------------------------... | (GutterWidget):
""" Draws status markers
"""
def __init__(self, *args, **kw):
super(StatusGutterWidget, self).__init__(*args, **kw)
self.error_lines = []
self.warn_lines = []
self.info_lines = []
def sizeHint(self):
return QtCore.QSize(10, 0)
def paintEven... | StatusGutterWidget | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.