file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
service.py | # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... |
def start(self):
"""
Starts the ChromeDriver Service.
:Exceptions:
- WebDriverException : Raised either when it cannot find the
executable, when it does not have permissions for the
executable, or when it cannot connect to the service.
- Possibly ot... | """
Creates a new instance of the Service
:Args:
- executable_path : Path to the ChromeDriver
- port : Port the service is running on
- service_args : List of args to pass to the chromedriver service
- log_path : Path for the chromedriver service to log to"""
... | identifier_body |
service.py | # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... | (self):
"""
Tells the ChromeDriver to stop and cleans up the process
"""
#If its dead dont worry
if self.process is None:
return
#Tell the Server to die!
try:
from urllib import request as url_request
except ImportError:
... | stop | identifier_name |
runtimeversionmanager-tests.js | /**
* Copyright 2011 Microsoft Corporation
*
* 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 agreed to i... | var runtimeKernel = {
getGoalStateClient: function () { return {}; },
getCurrentStateClient: function () { return {}; }
};
var runtimeVersionManager = new RuntimeVersionManager(runtimeVersionProtocolClient, runtimeKernel);
runtimeVersionManager.getRuntimeClient(versionsEndpointPath, functio... | "</RuntimeServerDiscovery>"
);
var runtimeVersionProtocolClient = new RuntimeVersionProtocolClient(inputChannel); | random_line_split |
job.py | from disco.core import Disco, result_iterator
from disco.settings import DiscoSettings
from disco.func import chain_reader
from discodex.objects import DataSet
from freequery.document import docparse
from freequery.document.docset import Docset
from freequery.index.tf_idf import TfIdf
class IndexJob(object):
def... |
def start(self):
results = self.__run_job(self.__index_job())
self.__run_discodex_index(results)
def __run_job(self, job):
results = job.wait()
if self.profile:
self.__profile_job(job)
return results
def __index_job(self):
return self.d... | self.spec = spec
self.discodex = discodex
self.docset = Docset(spec.docset_name)
self.disco = Disco(DiscoSettings()['DISCO_MASTER'])
self.nr_partitions = 8
self.profile = profile | identifier_body |
job.py | from disco.core import Disco, result_iterator
from disco.settings import DiscoSettings
from disco.func import chain_reader
from discodex.objects import DataSet
from freequery.document import docparse
from freequery.document.docset import Docset
from freequery.index.tf_idf import TfIdf
class | (object):
def __init__(self, spec, discodex,
disco_addr="disco://localhost", profile=False):
# TODO(sqs): refactoring potential with PagerankJob
self.spec = spec
self.discodex = discodex
self.docset = Docset(spec.docset_name)
self.disco = Disco(DiscoSettings... | IndexJob | identifier_name |
job.py | from disco.core import Disco, result_iterator
from disco.settings import DiscoSettings
from disco.func import chain_reader
from discodex.objects import DataSet
from freequery.document import docparse
from freequery.document.docset import Docset
from freequery.index.tf_idf import TfIdf
class IndexJob(object):
def... |
return results
def __index_job(self):
return self.disco.new_job(
name="index_tfidf",
input=['tag://' + self.docset.ddfs_tag],
map_reader=docparse,
map=TfIdf.map,
reduce=TfIdf.reduce,
sort=True,
partitions=s... | self.__profile_job(job) | conditional_block |
job.py | from disco.core import Disco, result_iterator
from disco.settings import DiscoSettings
from disco.func import chain_reader
from discodex.objects import DataSet
from freequery.document import docparse
from freequery.document.docset import Docset
from freequery.index.tf_idf import TfIdf
class IndexJob(object):
def... | ds = DataSet(input=results, options=opts)
origname = self.discodex.index(ds)
self.disco.wait(origname) # origname is also the disco job name
self.discodex.clone(origname, self.spec.invindex_name) | } | random_line_split |
module_unittest.py | #!/usr/bin/env python
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Tests for the module module, which contains Module and related classes."""
import os
import unittest
from tvcm import fake_fs
from... | (unittest.TestCase):
def test_module(self):
fs = fake_fs.FakeFS()
fs.AddFile('/src/x.html', """
<!DOCTYPE html>
<link rel="import" href="/y.html">
<link rel="import" href="/z.html">
<script>
'use strict';
</script>
""")
fs.AddFile('/src/y.html', """
<!DOCTYPE html>
<link rel="import" href="/z.html">
""")... | ModuleIntegrationTests | identifier_name |
module_unittest.py | #!/usr/bin/env python
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Tests for the module module, which contains Module and related classes."""
import os
import unittest
from tvcm import fake_fs
from... | """)
fs.AddFile('/x/y/z/foo.jpeg', '')
fs.AddFile('/x/y/z/foo2.html', """
<!DOCTYPE html>
""")
fs.AddFile('/x/raw/bar.js', 'hello')
project = project_module.Project([
os.path.normpath('/x/y'), os.path.normpath('/x/raw/')])
loader = resource_loader.ResourceLoader(project)
with fs:
m... | .x .y {
background-image: url(foo.jpeg);
} | random_line_split |
module_unittest.py | #!/usr/bin/env python
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Tests for the module module, which contains Module and related classes."""
import os
import unittest
from tvcm import fake_fs
from... | fs = fake_fs.FakeFS()
fs.AddFile('/x/y/z/foo.html', """
<!DOCTYPE html>
<link rel="import" href="/z/foo2.html">
<link rel="stylesheet" href="/z/foo.css">
<script src="/bar.js"></script>
""")
fs.AddFile('/x/y/z/foo.css', """
.x .y {
background-image: url(foo.jpeg);
}
""")
fs.AddFile('/x/y/z/foo.jpeg', ''... | identifier_body | |
trait-bounds-in-arc.rs | // ignore-pretty
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT lice... | for pet in arc.iter() {
pet.name(|name| {
assert!(name[0] == 'a' as u8 && name[1] == 'l' as u8);
})
}
}
fn check_pedigree(arc: Arc<Vec<~Pet:Share+Send>>) {
for pet in arc.iter() {
assert!(pet.of_good_pedigree());
}
} | }
fn check_names(arc: Arc<Vec<~Pet:Share+Send>>) { | random_line_split |
trait-bounds-in-arc.rs | // ignore-pretty
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT lice... | (&self, blk: |&str|) { blk(self.name) }
fn num_legs(&self) -> uint { 4 }
fn of_good_pedigree(&self) -> bool { self.num_whiskers >= 4 }
}
impl Pet for Dogge {
fn name(&self, blk: |&str|) { blk(self.name) }
fn num_legs(&self) -> uint { 4 }
fn of_good_pedigree(&self) -> bool {
self.bark_decibel... | name | identifier_name |
trait-bounds-in-arc.rs | // ignore-pretty
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT lice... | {
for pet in arc.iter() {
assert!(pet.of_good_pedigree());
}
} | identifier_body | |
sketch2.ts | //#!tsc && NODE_PATH=dist/src node dist/sketch2.js
| Rect,
TextHjustify,
TextVjustify,
Transform,
DECIDEG2RAD,
TextAngle,
} from "./src/kicad_common";
import { StrokeFont } from "./src/kicad_strokefont";
import { Plotter, CanvasPlotter } from "./src/kicad_plotter";
import * as fs from "fs";
{
const font = StrokeFont.instance;
const width = 2000, height = 2000;
... | import {
Point, | random_line_split |
central-panel.component.ts | import { Component, OnInit, Inject, EventEmitter } from '@angular/core';
import { EditorService, LeftSelection } from '../editor.service';
import { AxScriptFlow } from 'src/app/ax-model/model';
import { MapRowVM, SelectorDatastoreService, MapsVM } from 'src/app/ax-selector/selector-datastore.service';
import { EditorGl... | this.selectTab(s)
} else {
this.tabs = [s].concat(this.baseTabs);
this.selected = s;
if(this.selected.map) {
this.mapSelected = this.mapName(this.selected.map());
}
if(this.selected.steps) {
this.steps = Array.from(this.selected... | if(s.name === CentralPanelComponent.consoleTab.name) { | random_line_split |
central-panel.component.ts | import { Component, OnInit, Inject, EventEmitter } from '@angular/core';
import { EditorService, LeftSelection } from '../editor.service';
import { AxScriptFlow } from 'src/app/ax-model/model';
import { MapRowVM, SelectorDatastoreService, MapsVM } from 'src/app/ax-selector/selector-datastore.service';
import { EditorGl... |
mapChanged(map:MapRowVM[]) {
this.selected.onChangeMap(map);
}
mapName(map:MapRowVM[]):MapWithName {
return {
rows: map,
name: this.selected.name
}
}
}
| {
if (this.selected.onChangeSteps) {
this.selected.onChangeSteps(flow);
}
} | identifier_body |
central-panel.component.ts | import { Component, OnInit, Inject, EventEmitter } from '@angular/core';
import { EditorService, LeftSelection } from '../editor.service';
import { AxScriptFlow } from 'src/app/ax-model/model';
import { MapRowVM, SelectorDatastoreService, MapsVM } from 'src/app/ax-selector/selector-datastore.service';
import { EditorGl... | (flow:AxScriptFlow[]) {
if (this.selected.onChangeSteps) {
this.selected.onChangeSteps(flow);
}
}
mapChanged(map:MapRowVM[]) {
this.selected.onChangeMap(map);
}
mapName(map:MapRowVM[]):MapWithName {
return {
rows: map,
name: this.selected.name
}
}
}
| scriptChanged | identifier_name |
central-panel.component.ts | import { Component, OnInit, Inject, EventEmitter } from '@angular/core';
import { EditorService, LeftSelection } from '../editor.service';
import { AxScriptFlow } from 'src/app/ax-model/model';
import { MapRowVM, SelectorDatastoreService, MapsVM } from 'src/app/ax-selector/selector-datastore.service';
import { EditorGl... | else {
this.oldCurrentResolution = '';
}
let isCurrentResolution = s && s.length > 0 && s.every(x => x.selectedResolution === this.global.res_string)
if(isCurrentResolution) {
this.baseTabs = [this.monitorTab,CentralPanelComponent.consoleTab];
if(!this.tabs.includ... | {
this.oldCurrentResolution = s[0].selectedResolution
} | conditional_block |
qa_test.py | """
Copyright 2013 OpERA
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 agreed to in writing, softwar... | (self):
"""
Test the feedback algorithm
"""
obj = KunstTimeFeedback()
# Estado inicial
# Initial state.
self.assertEqual(False, obj.feedback())
obj.wait() # wait = 1
# 2 ^ 0 == 1
# wait = 0
self.assertEqual(True, obj.fee... | test_feedback_002 | identifier_name |
qa_test.py | """
Copyright 2013 OpERA
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 agreed to in writing, softwar... | """
obj = KunstTimeFeedback()
# Estado inicial
# Initial state.
self.assertEqual(False, obj.feedback())
obj.wait() # wait = 1
# 2 ^ 0 == 1
# wait = 0
self.assertEqual(True, obj.feedback())
# Aumentamos o tempo de sensoriamento ... | Test the feedback algorithm | random_line_split |
qa_test.py | """
Copyright 2013 OpERA
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 agreed to in writing, softwar... |
if __name__ == '__main__':
unittest.main()
| """
Test the feedback algorithm
"""
obj = KunstTimeFeedback()
# Estado inicial
# Initial state.
self.assertEqual(False, obj.feedback())
obj.wait() # wait = 1
# 2 ^ 0 == 1
# wait = 0
self.assertEqual(True, obj.feedback())
... | identifier_body |
qa_test.py | """
Copyright 2013 OpERA
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 agreed to in writing, softwar... | unittest.main() | conditional_block | |
ConstValues.ts | //////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2014-2015, Egret Technology Inc.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
... | 换为弧度
*/
public static ANGLE_TO_RADIAN:number = Math.PI / 180;
/**
* 弧度转换为角度
*/
public static RADIAN_TO_ANGLE:number = 180 / Math.PI;
/**
*龙骨
*/
public static DRAGON_BONES:string = "dragonBones";
/**
* 骨架
*/
public static ARMATURE:string = "armature";
/**
*皮肤
*/
public static... | **
* 角度转 | identifier_name |
ConstValues.ts | //////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2014-2015, Egret Technology Inc.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
... | /**
* 偏移
*/
public static A_OFFSET:string = "offset";
/**
* 循环
*/
public static A_LOOP:string = "loop";
/**
* 事件
*/
public static A_EVENT:string = "event";
/**
* 事件参数
*/
public static A_EVENT_PARAMETERS:string = "eventParameters";
/**
* 声音
*/
public static A_SOUND:strin... | * 缩放
*/
public static A_SCALE:string = "scale"; | random_line_split |
xmodule_django.py | """
Exposes Django utilities for consumption in the xmodule library
NOTE: This file should only be imported into 'django-safe' code, i.e. known that this code runs int the Django
runtime environment with the djangoapps in common configured to load
"""
import webpack_loader
# NOTE: we are importing this method so that... | fragment.add_css_url(chunk['url']) | conditional_block | |
xmodule_django.py | """
Exposes Django utilities for consumption in the xmodule library
NOTE: This file should only be imported into 'django-safe' code, i.e. known that this code runs int the Django
runtime environment with the djangoapps in common configured to load
"""
import webpack_loader
# NOTE: we are importing this method so that... | ():
"""
This method will return the hostname that was used in the current Django request
"""
hostname = None
request = get_current_request()
if request:
hostname = request.META.get('HTTP_HOST')
return hostname
def add_webpack_to_fragment(fragment, bundle_name, extension=None, conf... | get_current_request_hostname | identifier_name |
xmodule_django.py | """
Exposes Django utilities for consumption in the xmodule library
NOTE: This file should only be imported into 'django-safe' code, i.e. known that this code runs int the Django
runtime environment with the djangoapps in common configured to load
"""
import webpack_loader
# NOTE: we are importing this method so that... | fragment.add_css_url(chunk['url']) | random_line_split | |
xmodule_django.py | """
Exposes Django utilities for consumption in the xmodule library
NOTE: This file should only be imported into 'django-safe' code, i.e. known that this code runs int the Django
runtime environment with the djangoapps in common configured to load
"""
import webpack_loader
# NOTE: we are importing this method so that... |
def add_webpack_to_fragment(fragment, bundle_name, extension=None, config='DEFAULT'):
"""
Add all webpack chunks to the supplied fragment as the appropriate resource type.
"""
for chunk in webpack_loader.utils.get_files(bundle_name, extension, config):
if chunk['name'].endswith(('.js', '.js.g... | """
This method will return the hostname that was used in the current Django request
"""
hostname = None
request = get_current_request()
if request:
hostname = request.META.get('HTTP_HOST')
return hostname | identifier_body |
test_inline_arbitrary_chapel.py | from pych.extern import Chapel
import os.path
currentloc = os.path.dirname(os.path.realpath(__file__))
# Don't have a way to specify where the Chapel module arbitraryfile would live
# The intention seems to be the addition of an argument lib to @Chapel
@Chapel(module_dirs=[os.path.join(currentloc + '/sfiles/chapel/')... |
import testcase
# contains the general testing method, which allows us to gather output
def test_using_other_chapel_code():
"""
ensures that an inline definition of a Chapel function with a use statement
will work when the module being used lives in a directory specified with
the decorator argument "... | useArbitrary() | conditional_block |
test_inline_arbitrary_chapel.py | from pych.extern import Chapel
import os.path
currentloc = os.path.dirname(os.path.realpath(__file__))
# Don't have a way to specify where the Chapel module arbitraryfile would live
# The intention seems to be the addition of an argument lib to @Chapel
@Chapel(module_dirs=[os.path.join(currentloc + '/sfiles/chapel/')... | """
ensures that an inline definition of a Chapel function with a use statement
will work when the module being used lives in a directory specified with
the decorator argument "module_dirs"
"""
out = testcase.runpy(os.path.realpath(__file__))
assert out.endswith('6\n14 14 3 14 14\n14 14 3 14 14\... | identifier_body | |
test_inline_arbitrary_chapel.py | from pych.extern import Chapel
import os.path
currentloc = os.path.dirname(os.path.realpath(__file__))
# Don't have a way to specify where the Chapel module arbitraryfile would live
# The intention seems to be the addition of an argument lib to @Chapel
@Chapel(module_dirs=[os.path.join(currentloc + '/sfiles/chapel/')... | ():
"""
use arbitraryfile;
writeln(foo(1, 2));
// Should be 6
writeln(bar());
// Should be: 14 14 3 14 14
// 14 14 3 14 14
writeln(baz());
// Should be: (contents = 3.0)
// (contents = 3.0)
"""
return None
if __name__ == "__main__":
useArbitrary()
import testcase
#... | useArbitrary | identifier_name |
test_inline_arbitrary_chapel.py | from pych.extern import Chapel
import os.path
currentloc = os.path.dirname(os.path.realpath(__file__))
# Don't have a way to specify where the Chapel module arbitraryfile would live
# The intention seems to be the addition of an argument lib to @Chapel
@Chapel(module_dirs=[os.path.join(currentloc + '/sfiles/chapel/')... | the decorator argument "module_dirs"
"""
out = testcase.runpy(os.path.realpath(__file__))
assert out.endswith('6\n14 14 3 14 14\n14 14 3 14 14\n(contents = 3.0)\n(contents = 3.0)\n') | ensures that an inline definition of a Chapel function with a use statement
will work when the module being used lives in a directory specified with | random_line_split |
mod.rs | use super::Numeric;
use std::ops::{Add, Sub, Mul, Div, Rem};
use std::ops;
use std::convert;
use std::mem::transmute;
#[cfg(test)] mod test;
#[macro_use] mod macros;
pub trait Matrix<N>: Sized {
fn nrows(&self) -> usize;
fn ncols(&self) -> usize;
}
//#[cfg(not(simd))] | //pub struct Matrix2<N>
//where N: Numeric { pub x1y1: N, pub x2y1: N
// , pub x1y2: N, pub x2y2: N
// }
//
// #[cfg(not(simd))]
// #[repr(C)]
// #[derive(Clone, Copy, Eq, PartialEq, PartialOrd, Debug, Hash)]
//pub struct Matrix3<N>
//where N: Numeric { pub x1y1: N, pub x2y1: N, pub x3y1... | //#[repr(C)]
//#[derive(Clone, Copy, Eq, PartialEq, PartialOrd, Debug, Hash)] | random_line_split |
urls.py | #-*- coding: utf-8 -*-
| app_name = "perso"
urlpatterns = [
url(r'^$', views.main, name='main'),
url(r'^(?P<pageId>[0-9]+)/?$', views.main, name='main'),
url(r'^about/?$', views.about, name='ab... | from django.conf.urls import url
from . import views
| random_line_split |
textSearch.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | import {FileWalker} from 'vs/workbench/services/search/node/fileSearch';
import {UTF16le, UTF16be, UTF8, detectEncodingByBOMFromBuffer} from 'vs/base/node/encoding';
import {ISerializedFileMatch, IRawSearch, ISearchEngine} from 'vs/workbench/services/search/node/rawSearchService';
export class Engine implements ISearc... | import iconv = require('iconv-lite');
import baseMime = require('vs/base/common/mime');
import {ILineMatch, IProgress} from 'vs/platform/search/common/search';
import {detectMimesFromFile, IMimeAndEncoding} from 'vs/base/node/mime'; | random_line_split |
textSearch.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | implements ISerializedFileMatch {
public path: string;
public lineMatches: LineMatch[];
constructor(path: string) {
this.path = path;
this.lineMatches = [];
}
public addMatch(lineMatch: LineMatch): void {
assert.ok(lineMatch, 'Missing parameter (lineMatch = ' + lineMatch + ')');
this.lineMatches.push(l... | FileMatch | identifier_name |
Logger.js | "use strict";
/*
* Copyright (C) 2014 Riccardo Re <kingrichard1980.gmail.com>
* This file is part of "Ancilla Libary".
*
* "Ancilla Libary" 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 vers... | ( oOptions ){
return Chalk.styles[ oOptions.sHeaderStyleBackground ].open + Chalk.styles[ oOptions.sHeaderStyleColor ].open + oOptions.sHeader + Chalk.styles[ oOptions.sHeaderStyleColor ].close + Chalk.styles[ oOptions.sHeaderStyleBackground ].close;
}
}
module.exports = Logger;
| __getTag | identifier_name |
Logger.js | "use strict";
/*
* Copyright (C) 2014 Riccardo Re <kingrichard1980.gmail.com>
* This file is part of "Ancilla Libary".
*
* "Ancilla Libary" 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 vers... | }
__getRandomItemFromArray( aArray, aFilterArray ){
if( !aFilterArray ){
aFilterArray = [];
}
let _aFilteredArray = aArray.filter(function( sElement ){
for( let _sElement in aFilterArray ){
if( aFilterArray.hasOwnProperty( _sElement ) ){
if( _sElement === sElement ){
return false;
... | random_line_split | |
Logger.js | "use strict";
/*
* Copyright (C) 2014 Riccardo Re <kingrichard1980.gmail.com>
* This file is part of "Ancilla Libary".
*
* "Ancilla Libary" 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 vers... |
}
return Bluebird.all( _aPromises );
} else {
Bluebird.reject( Constant._ERROR_GENERIC_UNKNOWN );
}
}
disableRemoteTransport(){
let _aPromises = [ Bluebird.resolve() ];
let _oLoggers = winston.loggers.loggers;
for( let _sLoggerID in _oLoggers ){
if( _oLoggers.hasOwnProp... | {
let _bFound = false;
let _oTransports = _oLoggers[ _sLoggerID ].transports;
for( let _sTransportID in _oTransports ){
if( _oTransports.hasOwnProperty( _sTransportID ) && _sTransportID.match('(wstransport|mqtttransport)') ){
_bFound = true;
}
... | conditional_block |
Logger.js | "use strict";
/*
* Copyright (C) 2014 Riccardo Re <kingrichard1980.gmail.com>
* This file is part of "Ancilla Libary".
*
* "Ancilla Libary" 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 vers... |
__getRandomItemFromArray( aArray, aFilterArray ){
if( !aFilterArray ){
aFilterArray = [];
}
let _aFilteredArray = aArray.filter(function( sElement ){
for( let _sElement in aFilterArray ){
if( aFilterArray.hasOwnProperty( _sElement ) ){
if( _sElement === sElement ){
return false;
... | {
return _.extend( this.__oOptions, oOptions );
} | identifier_body |
user_update_eligibility.py | from datetime import timedelta
import logging
from django.utils.timezone import now
from django.core.management.base import BaseCommand
from TWLight.users.models import Editor
from TWLight.users.helpers.editor_data import (
editor_global_userinfo,
editor_valid,
editor_enough_edits,
editor_not_blocked,
... |
# These are used to limit the set of editors updated by the command.
# Nothing is passed to the model method.
if options["timedelta_days"]:
timedelta_days = int(options["timedelta_days"])
# Get editors that haven't been updated in the specified time range, with an option t... | datetime_override = now_or_datetime.fromisoformat(options["datetime"])
now_or_datetime = datetime_override | conditional_block |
user_update_eligibility.py | from datetime import timedelta
import logging
from django.utils.timezone import now
from django.core.management.base import BaseCommand
from TWLight.users.models import Editor
from TWLight.users.helpers.editor_data import (
editor_global_userinfo,
editor_valid,
editor_enough_edits,
editor_not_blocked,
... |
def handle(self, *args, **options):
"""
Updates editor info and Bundle eligibility for currently-eligible Editors.
Parameters
----------
args
options
Returns
-------
None
"""
# Default behavior is to use current datetime for... | """
Adds command arguments.
"""
parser.add_argument(
"--datetime",
action="store",
help="ISO datetime used for calculating eligibility. Defaults to now. Currently only used for backdating command runs in tests.",
)
parser.add_argument(
... | identifier_body |
user_update_eligibility.py | from datetime import timedelta
import logging
from django.utils.timezone import now
from django.core.management.base import BaseCommand
from TWLight.users.models import Editor
from TWLight.users.helpers.editor_data import (
editor_global_userinfo,
editor_valid,
editor_enough_edits,
editor_not_blocked,
... | (self, parser):
"""
Adds command arguments.
"""
parser.add_argument(
"--datetime",
action="store",
help="ISO datetime used for calculating eligibility. Defaults to now. Currently only used for backdating command runs in tests.",
)
parse... | add_arguments | identifier_name |
user_update_eligibility.py | from datetime import timedelta
import logging
from django.utils.timezone import now
from django.core.management.base import BaseCommand
from TWLight.users.models import Editor
from TWLight.users.helpers.editor_data import (
editor_global_userinfo,
editor_valid,
editor_enough_edits,
editor_not_blocked,
... | )
parser.add_argument(
"--timedelta_days",
action="store",
help="Number of days used to define 'recent' edits. Defaults to 30. Currently only used for faking command runs in tests.",
)
parser.add_argument(
"--wp_username",
actio... | help="Specify Wikipedia global_userinfo data. Defaults to fetching live data. Currently only used for faking command runs in tests.", | random_line_split |
network_process.py | #!/usr/bin/python
# -*- coding: UTF-8 -*-
'''
Created on Jan 17, 2017
@author: hegxiten
'''
import sys
import geo.haversine as haversine
from imposm.parser import OSMParser
import geo.haversine as haversine
import numpy
import time
from scipy import spatial
import csv
import codecs
import math
default_encoding='u... | def process_network(FOLDER,FILE,CONCURRENCYVAL,GLOBALROUNDINGDIGITS):
stations={}
'''stations[station_node_osmid]=[name, lat, lon]'''
refnodes_index_dict={}
'''refnodes_index_dict[nodeid]=listindex_of_nodeid'''
refnodes=[]
'''refnodes=[nodeid1,nodeid2,nodeid3...]'''
ref... | PI=3.14159265358
| random_line_split |
network_process.py | #!/usr/bin/python
# -*- coding: UTF-8 -*-
'''
Created on Jan 17, 2017
@author: hegxiten
'''
import sys
import geo.haversine as haversine
from imposm.parser import OSMParser
import geo.haversine as haversine
import numpy
import time
from scipy import spatial
import csv
import codecs
import math
default_encoding='u... | ():
'''Load coordinates of reference-nodes from csv format output'''
startt=time.time()
with codecs.open(FOLDER+FILE+'_waysegment_nodecoords.csv', 'rb',encoding='utf-8') as csvfile:
'''Example row: >>123(osmid),40.11545(latitude),-88.24111(longitude)<<'''
spamreader = csv... | loadcoordinates | identifier_name |
network_process.py | #!/usr/bin/python
# -*- coding: UTF-8 -*-
'''
Created on Jan 17, 2017
@author: hegxiten
'''
import sys
import geo.haversine as haversine
from imposm.parser import OSMParser
import geo.haversine as haversine
import numpy
import time
from scipy import spatial
import csv
import codecs
import math
default_encoding='u... |
stopt=time.time()
print("Loading way segments ("+str(stopt-startt)+")")
def output_nodes_csv():
target = codecs.open(FOLDER+FILE+"_nodes.csv", 'w',encoding='utf-8')
for x in node_fromto_dict:
if x in stations:
if len(node_fromto_dict[x])!=0... | if s not in node_fromto_dict:
disconnected_stations.append(s)
stations[s].append('disconnected')
else:
connected_stations.append(s)
stations[s].append('connected') | conditional_block |
network_process.py | #!/usr/bin/python
# -*- coding: UTF-8 -*-
'''
Created on Jan 17, 2017
@author: hegxiten
'''
import sys
import geo.haversine as haversine
from imposm.parser import OSMParser
import geo.haversine as haversine
import numpy
import time
from scipy import spatial
import csv
import codecs
import math
default_encoding='u... |
def output_links_csv():
target = codecs.open(FOLDER+FILE+"_links.csv", 'w',encoding='utf-8')
headerkeys=attribute_mapper.values()[0].keys()
header='vertex_1,vertex_2'
for k in headerkeys:
header=header+','+k
target.write(header+'\n')
for x in node_fromto... | target = codecs.open(FOLDER+FILE+"_nodes.csv", 'w',encoding='utf-8')
for x in node_fromto_dict:
if x in stations:
if len(node_fromto_dict[x])!=0:
target.write(str(x)+",$"+stations[x][0].decode('utf-8')+"$,"+str(stations[x][1])+","+str(stations[x][2])+"\n") ... | identifier_body |
__init__.py | """Main module."""
import os
import pygame
import signal
import logging
import argparse
from threading import Event
from multiprocessing import Value
from injector import Injector, singleton
from ballercfg import ConfigurationManager
from .locals import * # noqa
from .events import EventManager, TickEvent
from .mo... | while not self.shutdown.is_set():
# Pump/handle events (both pygame and akurra)
self.events.poll()
# Calculate time (in seconds) that has passed since last tick
delta_time = self.clock.tick(self.max_fps) / 1000
# Dispatch tick
self.events... | game.play()
except AttributeError:
raise ValueError('No game module named "%s" exists!' % self.game)
| random_line_split |
__init__.py | """Main module."""
import os
import pygame
import signal
import logging
import argparse
from threading import Event
from multiprocessing import Value
from injector import Injector, singleton
from ballercfg import ConfigurationManager
from .locals import * # noqa
from .events import EventManager, TickEvent
from .mo... |
def main():
"""Main entry point."""
# Parse command-line arguments and set required variables
parser = argparse.ArgumentParser(description='Run the Akurra game engine.')
parser.add_argument('--log-level', type=str, default='INFO', help='set the log level',
choices=['CRITICAL',... | """Base game class."""
def __init__(self, game, log_level='INFO', debug=False):
"""Constructor."""
# Set up container
global container
self.container = container = Injector(build_container)
self.game = game
self.log_level = log_level
self.debug = debug
... | identifier_body |
__init__.py | """Main module."""
import os
import pygame
import signal
import logging
import argparse
from threading import Event
from multiprocessing import Value
from injector import Injector, singleton
from ballercfg import ConfigurationManager
from .locals import * # noqa
from .events import EventManager, TickEvent
from .mo... | main() | conditional_block | |
__init__.py | """Main module."""
import os
import pygame
import signal
import logging
import argparse
from threading import Event
from multiprocessing import Value
from injector import Injector, singleton
from ballercfg import ConfigurationManager
from .locals import * # noqa
from .events import EventManager, TickEvent
from .mo... | :
"""Base game class."""
def __init__(self, game, log_level='INFO', debug=False):
"""Constructor."""
# Set up container
global container
self.container = container = Injector(build_container)
self.game = game
self.log_level = log_level
self.debug = debu... | Akurra | identifier_name |
textfiles.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (snapshot: ITextSnapshot): string {
const chunks: string[] = [];
let chunk: string | null;
while (typeof (chunk = snapshot.read()) === 'string') {
chunks.push(chunk);
}
return chunks.join('');
}
export function stringToSnapshot(value: string): ITextSnapshot {
let done = false;
return {
read(): string | n... | snapshotToString | identifier_name |
textfiles.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
read(): VSBuffer | null {
let value = this.snapshot.read();
// Handle preamble if provided
if (!this.preambleHandled) {
this.preambleHandled = true;
if (typeof this.preamble === 'string') {
if (typeof value === 'string') {
value = this.preamble + value;
} else {
value = this.preamble;... | { } | identifier_body |
textfiles.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
return chunks.join('');
}
export function stringToSnapshot(value: string): ITextSnapshot {
let done = false;
return {
read(): string | null {
if (!done) {
done = true;
return value;
}
return null;
}
};
}
export class TextSnapshotReadable implements VSBufferReadable {
private preambleHan... | {
chunks.push(chunk);
} | conditional_block |
textfiles.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | export interface ITextFileService extends IDisposable {
_serviceBrand: ServiceIdentifier<any>;
readonly onWillMove: Event<IWillMoveEvent>;
readonly onAutoSaveConfigurationChange: Event<IAutoSaveConfiguration>;
readonly onFilesAssociationChange: Event<void>;
readonly isHotExitEnabled: boolean;
/**
* Access... | import { VSBuffer, VSBufferReadable } from 'vs/base/common/buffer';
import { isUndefinedOrNull } from 'vs/base/common/types';
export const ITextFileService = createDecorator<ITextFileService>('textFileService');
| random_line_split |
chris_app.js | 'use strict';
var key_arr = document.getElementsByClassName('key');
var border = document.getElementById('key-container');
var keycode_letters = {
key_nums: [82, 84, 89, 85, 73, 79, 80, 65, 83, 68, 70, 71, 72, 74, 75, 76],//key codes
key_letters: ['A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ';'],//array of keys
... |
//toggle method, class list
| {
if(keycode_letters.key_nums.includes(event.keyCode)){
border.style.boxShadow = 'none';
for (var i = 0; i < keycode_letters.key_nums.length; i++) {
key_arr[i].classList.toggle('keytwo');
if (event.keyCode === keycode_letters.key_nums[i]) {
key_arr[i].classList.toggle('keythree');
}
... | identifier_body |
chris_app.js | 'use strict';
var key_arr = document.getElementsByClassName('key');
var border = document.getElementById('key-container');
var keycode_letters = {
key_nums: [82, 84, 89, 85, 73, 79, 80, 65, 83, 68, 70, 71, 72, 74, 75, 76],//key codes
key_letters: ['A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ';'],//array of keys
... | (event) {
if(keycode_letters.key_nums.includes(event.keyCode)){
for (var i = 0; i < keycode_letters.key_nums.length; i++) {
key_arr[i].classList.toggle('keytwo');
if (event.keyCode === keycode_letters.key_nums[i]) {
var audio = document.getElementById(event.keyCode.toString());
var fi... | keyHandler | identifier_name |
chris_app.js | 'use strict';
var key_arr = document.getElementsByClassName('key');
var border = document.getElementById('key-container');
var keycode_letters = {
key_nums: [82, 84, 89, 85, 73, 79, 80, 65, 83, 68, 70, 71, 72, 74, 75, 76],//key codes
key_letters: ['A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ';'],//array of keys
... | for (var i = 0; i < keycode_letters.key_nums.length; i++) {
key_arr[i].classList.toggle('keytwo');
if (event.keyCode === keycode_letters.key_nums[i]) {
key_arr[i].classList.toggle('keythree');
}
}
}
}
//toggle method, class list | function upHandler (event) {
if(keycode_letters.key_nums.includes(event.keyCode)){
border.style.boxShadow = 'none'; | random_line_split |
chris_app.js | 'use strict';
var key_arr = document.getElementsByClassName('key');
var border = document.getElementById('key-container');
var keycode_letters = {
key_nums: [82, 84, 89, 85, 73, 79, 80, 65, 83, 68, 70, 71, 72, 74, 75, 76],//key codes
key_letters: ['A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ';'],//array of keys
... |
}
}
};
function upHandler (event) {
if(keycode_letters.key_nums.includes(event.keyCode)){
border.style.boxShadow = 'none';
for (var i = 0; i < keycode_letters.key_nums.length; i++) {
key_arr[i].classList.toggle('keytwo');
if (event.keyCode === keycode_letters.key_nums[i]) {
key_arr... | {
var audio = document.getElementById(event.keyCode.toString());
var filepath = keycode_letters.key_sounds[i];
audio.src = filepath;
audio.play();
key_arr[i].classList.toggle('keythree');
border.style.boxShadow = '2px 2px 5px 5px white';
} | conditional_block |
release.py | #!/usr/bin/env python
from __future__ import print_function
import re
import ast
import subprocess
import sys
from optparse import OptionParser
DEBUG = False
CONFIRM_STEPS = False
DRY_RUN = False
def skip_step():
"""
Asks for user's response whether to run a step. Default is yes.
:return: boolean
"""... |
def version(version_file):
_version_re = re.compile(r'__version__\s+=\s+(.*)')
with open(version_file, 'rb') as f:
ver = str(ast.literal_eval(_version_re.search(
f.read().decode('utf-8')).group(1)))
return ver
def commit_for_release(version_file, ver):
run_step('git', 'reset')... | subprocess.check_output(cmd) | conditional_block |
release.py | #!/usr/bin/env python
from __future__ import print_function
import re
import ast
import subprocess
import sys
from optparse import OptionParser
DEBUG = False
CONFIRM_STEPS = False
DRY_RUN = False
def | ():
"""
Asks for user's response whether to run a step. Default is yes.
:return: boolean
"""
global CONFIRM_STEPS
if CONFIRM_STEPS:
choice = raw_input("--- Confirm step? (y/N) [y] ")
if choice.lower() == 'n':
return True
return False
def run_step(*args):
""... | skip_step | identifier_name |
release.py | #!/usr/bin/env python
from __future__ import print_function
import re
import ast
import subprocess
import sys
from optparse import OptionParser
DEBUG = False
CONFIRM_STEPS = False
DRY_RUN = False
def skip_step():
"""
Asks for user's response whether to run a step. Default is yes.
:return: boolean
"""... | return True
return False
def run_step(*args):
"""
Prints out the command and asks if it should be run.
If yes (default), runs it.
:param args: list of strings (command and args)
"""
global DRY_RUN
cmd = args
print(' '.join(cmd))
if skip_step():
print('--- S... | choice = raw_input("--- Confirm step? (y/N) [y] ")
if choice.lower() == 'n': | random_line_split |
release.py | #!/usr/bin/env python
from __future__ import print_function
import re
import ast
import subprocess
import sys
from optparse import OptionParser
DEBUG = False
CONFIRM_STEPS = False
DRY_RUN = False
def skip_step():
"""
Asks for user's response whether to run a step. Default is yes.
:return: boolean
"""... |
def create_git_tag(tag_name):
run_step('git', 'tag', '-s', '-m', tag_name, tag_name)
def create_source_tarball():
run_step('python', 'setup.py', 'sdist')
def upload_source_tarball():
run_step('python', 'setup.py', 'sdist', 'upload')
def push_to_github():
run_step('git', 'push', 'origin', 'maste... | run_step('git', 'reset')
run_step('git', 'add', version_file)
run_step('git', 'commit', '--message', 'Releasing version %s' % ver) | identifier_body |
log.js | /**
* Logger configuration
*
* Configure the log level for your app, as well as the transport
* (Underneath the covers, Sails uses Winston for logging, which
* allows for some pretty neat custom transports/adapters for log messages)
*
* For more information on the Sails logger, check out:
* http://sailsjs.org/#... | */
module.exports = {
// Valid `level` configs:
// i.e. the minimum log level to capture with sails.log.*()
//
// 'error' : Display calls to `.error()`
// 'warn' : Display calls from `.error()` to `.warn()`
// 'debug' : Display calls from `.error()`, `.warn()` to `.debug()`
// 'info' : Di... | random_line_split | |
ThemeSwitcher.tsx | import React, { useContext, useState } from 'react';
import { useTranslation } from 'react-i18next';
import Toggle from '../../Toggle';
import ThemeContext from '../ThemeContext';
import { dark, light } from '../../../themes';
const ThemeSwitcher = () => {
const { switchTheme, theme } = useContext(ThemeContext);
c... | setDarkMode(theme === dark);
}, [theme]);
const toggle = () => {
if (switchTheme) {
switchTheme(hasDarkMode ? light : dark);
}
};
return (
<Toggle icon={hasDarkMode ? 'talend-eye-slash' : 'talend-eye'} onChange={toggle}>
{t('THEME_TOGGLE_DARK_MODE', 'Toggle dark mode')}
</Toggle>
);
};
export de... | React.useEffect(() => { | random_line_split |
ThemeSwitcher.tsx | import React, { useContext, useState } from 'react';
import { useTranslation } from 'react-i18next';
import Toggle from '../../Toggle';
import ThemeContext from '../ThemeContext';
import { dark, light } from '../../../themes';
const ThemeSwitcher = () => {
const { switchTheme, theme } = useContext(ThemeContext);
c... |
};
return (
<Toggle icon={hasDarkMode ? 'talend-eye-slash' : 'talend-eye'} onChange={toggle}>
{t('THEME_TOGGLE_DARK_MODE', 'Toggle dark mode')}
</Toggle>
);
};
export default ThemeSwitcher;
| {
switchTheme(hasDarkMode ? light : dark);
} | conditional_block |
convex_try_new3d.rs | extern crate nalgebra as na;
use na::Point3;
use ncollide3d::shape::ConvexHull;
fn main() | {
let points = vec![
Point3::new(0.0f32, 0.0, 1.0),
Point3::new(0.0, 0.0, -1.0),
Point3::new(0.0, 1.0, 0.0),
Point3::new(0.0, -1.0, 0.0),
Point3::new(1.0, 0.0, 0.0),
Point3::new(-1.0, 0.0, 0.0),
];
let indices = vec![
0, 4, 2, 0, 3, 4, 5, 0, 2, 5, 3, ... | identifier_body | |
convex_try_new3d.rs | extern crate nalgebra as na;
use na::Point3;
use ncollide3d::shape::ConvexHull;
fn | () {
let points = vec![
Point3::new(0.0f32, 0.0, 1.0),
Point3::new(0.0, 0.0, -1.0),
Point3::new(0.0, 1.0, 0.0),
Point3::new(0.0, -1.0, 0.0),
Point3::new(1.0, 0.0, 0.0),
Point3::new(-1.0, 0.0, 0.0),
];
let indices = vec![
0, 4, 2, 0, 3, 4, 5, 0, 2, 5, ... | main | identifier_name |
convex_try_new3d.rs | extern crate nalgebra as na;
use na::Point3;
use ncollide3d::shape::ConvexHull;
fn main() {
let points = vec![
Point3::new(0.0f32, 0.0, 1.0),
Point3::new(0.0, 0.0, -1.0),
Point3::new(0.0, 1.0, 0.0),
Point3::new(0.0, -1.0, 0.0),
Point3::new(1.0, 0.0, 0.0),
Point3::ne... | } | ];
let convex = ConvexHull::try_new(points, &indices).expect("Invalid convex shape.");
convex.check_geometry(); | random_line_split |
product.py | # -*- coding: utf-8 -*-
# Copyright 2014-2016 Akretion (http://www.akretion.com)
# @author Alexis de Lattre <alexis.delattre@akretion.com>
# Copyright 2016 Sodexis (http://sodexis.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from openerp import models, fields, api, _
from openerp.exceptions imp... | (self):
if self.rented_product_id and self.type != 'service':
raise ValidationError(_(
"The rental product '%s' must be of type 'Service'.")
% self.name)
if self.rented_product_id and not self.must_have_dates:
raise ValidationError(_(
... | _check_rental | identifier_name |
product.py | # -*- coding: utf-8 -*-
# Copyright 2014-2016 Akretion (http://www.akretion.com)
# @author Alexis de Lattre <alexis.delattre@akretion.com>
# Copyright 2016 Sodexis (http://sodexis.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from openerp import models, fields, api, _
from openerp.exceptions imp... | res = super(ProductProduct, self)._need_procurement()
if not res:
for product in self:
if product.type == 'service' and product.rented_product_id:
return True
# TODO find a replacement for soline.rental_type == 'new_rental')
return res | identifier_body | |
product.py | # -*- coding: utf-8 -*-
# Copyright 2014-2016 Akretion (http://www.akretion.com)
# @author Alexis de Lattre <alexis.delattre@akretion.com>
# Copyright 2016 Sodexis (http://sodexis.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from openerp import models, fields, api, _
from openerp.exceptions imp... | rented_product_id = fields.Many2one(
'product.product', string='Related Rented Product',
domain=[('type', 'in', ('product', 'consu'))])
# Link rented HW product -> rental service
rental_service_ids = fields.One2many(
'product.product', 'rented_product_id',
string='Related Ren... | random_line_split | |
product.py | # -*- coding: utf-8 -*-
# Copyright 2014-2016 Akretion (http://www.akretion.com)
# @author Alexis de Lattre <alexis.delattre@akretion.com>
# Copyright 2016 Sodexis (http://sodexis.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from openerp import models, fields, api, _
from openerp.exceptions imp... |
# TODO find a replacement for soline.rental_type == 'new_rental')
return res
| for product in self:
if product.type == 'service' and product.rented_product_id:
return True | conditional_block |
status.js |
'use strict';
var utils = this.utils || {};
utils.status = (function() {
// This constant is essential to resolve what is the path of the CSS file
// that defines the animations
//var FILE_NAME = 'status';
// How many milliseconds is displayed the status component by default
var DISPLAYED_TIME = 2000;
... | () {
if (timeoutID === null) {
return;
}
window.clearTimeout(timeoutID);
timeoutID = null;
}
/*
* Shows the status component
*
* @param{Object} Message. It could be a string or a DOMFragment that
* represents the normal and strong strings
*
* @param{int} It d... | clearHideTimeout | identifier_name |
status.js |
'use strict';
var utils = this.utils || {};
utils.status = (function() {
// This constant is essential to resolve what is the path of the CSS file
// that defines the animations
//var FILE_NAME = 'status';
// How many milliseconds is displayed the status component by default
var DISPLAYED_TIME = 2000;
... |
/*
* This function is invoked when some animation is ended
*/
function animationEnd(evt) {
var eventName = 'status-showed';
if (evt.animationName === 'hide') {
clearHideTimeout();
section.classList.add('hidden');
eventName = 'status-hidden';
}
window.dispatchEvent(new Cus... | {
clearHideTimeout();
content.innerHTML = '';
if (typeof message === 'string') {
content.textContent = message;
} else {
try {
// Here we should have a DOMFragment
content.appendChild(message);
} catch(ex) {
console.error('DOMException: ' + ex.message);
}... | identifier_body |
status.js |
'use strict';
var utils = this.utils || {};
utils.status = (function() {
// This constant is essential to resolve what is the path of the CSS file
// that defines the animations
//var FILE_NAME = 'status';
// How many milliseconds is displayed the status component by default
var DISPLAYED_TIME = 2000;
... |
build();
}
// Initializing the library
if (document.readyState === 'complete') {
initialize();
} else {
document.addEventListener('DOMContentLoaded', function loaded() {
document.removeEventListener('DOMContentLoaded', loaded);
initialize();
});
}
return {
/*
* The l... | {
return;
} | conditional_block |
status.js | 'use strict';
var utils = this.utils || {};
utils.status = (function() {
// This constant is essential to resolve what is the path of the CSS file
// that defines the animations
//var FILE_NAME = 'status';
// How many milliseconds is displayed the status component by default
var DISPLAYED_TIME = 2000;
... | */
setDuration: function setDuration(time) {
DISPLAYED_TIME = time || DISPLAYED_TIME;
}
};
})(); | * | random_line_split |
release_entry.rs | use hex::*;
use regex::Regex;
use semver::Version;
use std::iter::*;
use std::error::{Error};
use url::{Url};
use url::percent_encoding::{percent_decode};
/* Example lines:
# SHA256 of the file Name Version Size [delta/full] release%
e4548fba3f902e63e3fff36db7cbbd183... | ,
_ => Err(From::from("Invalid Release Entry string"))
}
}
pub fn parse_entries(content: &str) -> Result<Vec<ReleaseEntry>, Box<Error>> {
let mut was_error: Option<Box<Error>> = None;
let r: Vec<ReleaseEntry> = content.split("\n").filter_map(|x| {
let r = COMMENT.replace_all(x, "");
... | {
let (sha256, name, version, size, delta_or_full, percent) = (e[0], e[1], e[2], e[3], e[4], e[5]);
let mut ret = ReleaseEntry {
sha256: [0; 32],
is_delta: try!(ReleaseEntry::parse_delta_full(delta_or_full)),
filename_or_url: try!(ReleaseEntry::parse_name(name)).to_owned(),... | conditional_block |
release_entry.rs | use hex::*;
use regex::Regex;
use semver::Version;
use std::iter::*;
use std::error::{Error};
use url::{Url};
use url::percent_encoding::{percent_decode};
/* Example lines:
# SHA256 of the file Name Version Size [delta/full] release%
e4548fba3f902e63e3fff36db7cbbd183... |
#[test]
fn parse_should_fail_negative_percentages() {
let input = "e4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 delta -145%";
ReleaseEntry::parse(input).unwrap_err();
}
#[test]
fn url_encoded_filenames_should_end_up_decoded() {
let input = "e4548fba3... | {
let input = "e4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 delta 145%";
ReleaseEntry::parse(input).unwrap_err();
} | identifier_body |
release_entry.rs | use hex::*;
use regex::Regex;
use semver::Version;
use std::iter::*;
use std::error::{Error};
use url::{Url};
use url::percent_encoding::{percent_decode};
/* Example lines:
# SHA256 of the file Name Version Size [delta/full] release%
e4548fba3f902e63e3fff36db7cbbd183... | () {
let input = "e4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35 myproject.7z 1.2.3 12345 delta -145%";
ReleaseEntry::parse(input).unwrap_err();
}
#[test]
fn url_encoded_filenames_should_end_up_decoded() {
let input = "e4548fba3f902e63e3fff36db7cbbd1837493e21c51f0751e51ee1483ddd0f35... | parse_should_fail_negative_percentages | identifier_name |
release_entry.rs | use hex::*;
use regex::Regex;
use semver::Version;
use std::iter::*;
use std::error::{Error};
use url::{Url};
use url::percent_encoding::{percent_decode};
/* Example lines:
# SHA256 of the file Name Version Size [delta/full] release%
e4548fba3f902e63e3fff36db7cbbd183... | pub sha256: [u8; 32],
pub filename_or_url: String,
pub version: Version,
pub length: i64,
pub is_delta: bool,
pub percentage: i32,
}
impl Default for ReleaseEntry {
fn default() -> ReleaseEntry {
ReleaseEntry {
filename_or_url: "Foobdar".to_owned(),
version: Version::parse("1.0.0").unwrap... | pub struct ReleaseEntry { | random_line_split |
htmltrackelement.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/. */
use dom::bindings::codegen::Bindings::HTMLTrackElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLTrack... |
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLTrackElement> {
let element = HTMLTrackElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLTrackElementBinding::Wr... | {
HTMLTrackElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLTrackElement, localName, prefix, document)
}
} | identifier_body |
htmltrackelement.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/. */
use dom::bindings::codegen::Bindings::HTMLTrackElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLTrack... | htmlelement: HTMLElement,
}
impl HTMLTrackElementDerived for EventTarget {
fn is_htmltrackelement(&self) -> bool {
*self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTrackElement)))
}
}
impl HTMLTrackElement {
fn new_inherited(local... | pub struct HTMLTrackElement { | random_line_split |
htmltrackelement.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/. */
use dom::bindings::codegen::Bindings::HTMLTrackElementBinding;
use dom::bindings::codegen::InheritTypes::HTMLTrack... | (&self) -> bool {
*self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTrackElement)))
}
}
impl HTMLTrackElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLTrackElement {
HTMLT... | is_htmltrackelement | identifier_name |
generic.py | # -*- coding: utf-8 -*-
"""Operating system independent (generic) preprocessor plugins."""
from dfvfs.helpers import file_system_searcher
from plaso.lib import definitions
from plaso.preprocessors import interface
from plaso.preprocessors import manager
class DetermineOperatingSystemPlugin(
interface.FileSystem... |
elif '/system/library' in locations:
operating_system = definitions.OPERATING_SYSTEM_FAMILY_MACOS
elif '/etc' in locations:
operating_system = definitions.OPERATING_SYSTEM_FAMILY_LINUX
if operating_system != definitions.OPERATING_SYSTEM_FAMILY_UNKNOWN:
mediator.SetValue('operating_syst... | operating_system = definitions.OPERATING_SYSTEM_FAMILY_WINDOWS_NT | conditional_block |
generic.py | # -*- coding: utf-8 -*-
"""Operating system independent (generic) preprocessor plugins."""
from dfvfs.helpers import file_system_searcher
from plaso.lib import definitions
from plaso.preprocessors import interface
from plaso.preprocessors import manager
class | (
interface.FileSystemArtifactPreprocessorPlugin):
"""Plugin to determine the operating system."""
# pylint: disable=abstract-method
# This plugin does not use an artifact definition and therefore does not
# use _ParsePathSpecification.
# We need to check for both forward and backward slashes since the ... | DetermineOperatingSystemPlugin | identifier_name |
generic.py | # -*- coding: utf-8 -*-
"""Operating system independent (generic) preprocessor plugins."""
from dfvfs.helpers import file_system_searcher
from plaso.lib import definitions
from plaso.preprocessors import interface
from plaso.preprocessors import manager
class DetermineOperatingSystemPlugin(
interface.FileSystem... |
# pylint: disable=unused-argument
def Collect(self, mediator, artifact_definition, searcher, file_system):
"""Collects values using a file artifact definition.
Args:
mediator (PreprocessMediator): mediates interactions between preprocess
plugins and other components, such as storage and k... | """Initializes a plugin to determine the operating system."""
super(DetermineOperatingSystemPlugin, self).__init__()
self._find_specs = [
file_system_searcher.FindSpec(
case_sensitive=False, location='/etc',
location_separator='/'),
file_system_searcher.FindSpec(
... | identifier_body |
generic.py | # -*- coding: utf-8 -*-
"""Operating system independent (generic) preprocessor plugins."""
from dfvfs.helpers import file_system_searcher
from plaso.lib import definitions
from plaso.preprocessors import interface
from plaso.preprocessors import manager
| """Plugin to determine the operating system."""
# pylint: disable=abstract-method
# This plugin does not use an artifact definition and therefore does not
# use _ParsePathSpecification.
# We need to check for both forward and backward slashes since the path
# specification will be dfVFS back-end dependent... |
class DetermineOperatingSystemPlugin(
interface.FileSystemArtifactPreprocessorPlugin): | random_line_split |
cryptauth.py | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import httplib
import json
import logging
import pprint
import time
logger = logging.getLogger('proximity_auth.%s' % __name__)
_GOOGLE_APIS_URL = 'www.goog... | response.
"""
conn = httplib.HTTPSConnection(self._google_apis_url)
path = _REQUEST_PATH % function_path
headers = {
'authorization': 'Bearer ' + self._access_token,
'Content-Type': 'application/json'
}
body = json.dumps(request_data)
logger.info('Making request to %s wi... | time.sleep(timeout_secs)
return self.FindEligibleUnlockDevices(time_delta_millis=timeout_secs)
def _SendRequest(self, function_path, request_data):
""" Sends an HTTP request to CryptAuth and returns the deserialized | random_line_split |
cryptauth.py | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import httplib
import json
import logging
import pprint
import time
logger = logging.getLogger('proximity_auth.%s' % __name__)
_GOOGLE_APIS_URL = 'www.goog... | (self, time_delta_millis=None):
""" Finds devices eligible to be an unlock key.
Args:
time_delta_millis: If specified, then only return eligible devices that
have contacted CryptAuth in the last time delta.
Returns:
A tuple containing two lists, one of eligible devices and the other of... | FindEligibleUnlockDevices | identifier_name |
cryptauth.py | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import httplib
import json
import logging
import pprint
import time
logger = logging.getLogger('proximity_auth.%s' % __name__)
_GOOGLE_APIS_URL = 'www.goog... |
# We wait for phones to update their status with CryptAuth.
logger.info('Waiting for %s seconds for phone status...' % timeout_secs)
time.sleep(timeout_secs)
return self.FindEligibleUnlockDevices(time_delta_millis=timeout_secs)
def _SendRequest(self, function_path, request_data):
""" Sends an HT... | return None | conditional_block |
cryptauth.py | # Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import httplib
import json
import logging
import pprint
import time
logger = logging.getLogger('proximity_auth.%s' % __name__)
_GOOGLE_APIS_URL = 'www.goog... |
def GetMyDevices(self):
""" Invokes the GetMyDevices API.
Returns:
A list of devices or None if the API call fails.
Each device is a dictionary of the deserialized JSON returned by
CryptAuth.
"""
request_data = {
'approvedForUnlockRequired': False,
'allowStaleRead': Fa... | self._access_token = access_token
self._google_apis_url = google_apis_url | identifier_body |
Gruntfile.js | module.exports = function (grunt) {
"use strict";
grunt.initConfig({
dirs: {
css: 'app/css',
js: 'app/js',
sass: 'app/sass',
},
compass: {
dist: {
options: {
config: 'config.rb',
}
}
},
concat: {
options: {
seperator: ';',
... | }
},
uglify: {
options: {
// mangle: false,
debug: true,
},
target: {
files: {
'<%= dirs.js %>/app.min.js': ['<%= dirs.js %>/app.js']
}
}
},
watch: {
css: {
files: [
'<%= dirs.sass %>/*.scss',
'<%= ... | random_line_split | |
OutputBindingCard.tsx | import i18next from 'i18next';
import { Link } from 'office-ui-fabric-react';
import React, { useContext } from 'react'; | import { ReactComponent as OutputSvg } from '../../../../../../images/Common/output.svg';
import { ArmObj } from '../../../../../../models/arm-obj';
import { Binding, BindingDirection } from '../../../../../../models/functions/binding';
import { BindingInfo } from '../../../../../../models/functions/function-binding';
... | import { useTranslation } from 'react-i18next'; | random_line_split |
table_colgroup.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/. */
//! CSS table formatting contexts.
#![deny(unsafe_code)]
use app_units::Au;
use context::LayoutContext;
use disp... |
fn iterate_through_fragment_border_boxes(&self,
_: &mut FragmentBorderBoxIterator,
_: i32,
_: &Point2D<Au>) {}
fn mutate_fragments(&mut self, _: &mut FnMut(&mut Fragment)) {}... | {
panic!("Table column groups can't be containing blocks!")
} | identifier_body |
table_colgroup.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/. */
//! CSS table formatting contexts.
#![deny(unsafe_code)]
use app_units::Au;
use context::LayoutContext;
use disp... |
fn collect_stacking_contexts(&mut self, state: &mut StackingContextCollectionState) {
self.base.stacking_context_id = state.current_stacking_context_id;
self.base.clipping_and_scrolling = Some(state.current_clipping_and_scrolling);
}
fn repair_style(&mut self, _: &::ServoArc<ComputedValues... | random_line_split | |
table_colgroup.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/. */
//! CSS table formatting contexts.
#![deny(unsafe_code)]
use app_units::Au;
use context::LayoutContext;
use disp... | (&mut self, _: &::ServoArc<ComputedValues>) {}
fn compute_overflow(&self) -> Overflow {
Overflow::new()
}
fn generated_containing_block_size(&self, _: OpaqueFlow) -> LogicalSize<Au> {
panic!("Table column groups can't be containing blocks!")
}
fn iterate_through_fragment_border_bo... | repair_style | identifier_name |
detect_outlier.py | import numpy as np
import sys
sys.path.append("../Pipeline/Audio/Pipeline/")
from AudioPipe.features import mfcc # Feature Extraction Module, part of the shared preprocessing
import AudioPipe.speaker.recognition as SR # Speaker Recognition Module
import scipy.io.wavfile as wav
import commands, os
import json
import ar... |
def from_jsonfile(filename):
with open(filename) as fh:
return json.load(fh)
def get_sec(time_str):
h, m, s = time_str.split(':')
return int(h) * 3600 + int(m) * 60 + float(s)
def to_json(result, **kwargs):
'''Return a JSON representation of the aligned transcript'''
options = {
... | temp_fl = os.path.join(spk_dir,"temp.txt")
count = 0
with open(temp_fl, "w") as fh:
for clip in clip_ls:
if count>100:
break
fh.write("file "+clip["name"]+"\n")
count+=1
# Merge all the data into one audio
audio_merge = os.path.join(spk_dir,"me... | identifier_body |
detect_outlier.py | import numpy as np
import sys
sys.path.append("../Pipeline/Audio/Pipeline/")
from AudioPipe.features import mfcc # Feature Extraction Module, part of the shared preprocessing
import AudioPipe.speaker.recognition as SR # Speaker Recognition Module
import scipy.io.wavfile as wav
import commands, os
import json
import ar... | if os.path.exists(stat_fn) and os.path.getsize(stat_fn) > 0:
stat_dict = from_jsonfile(stat_fn)
else:
stat_dict = {}
if spk_name not in stat_dict:
stat_dict[spk_name]={}
for clip in clip_ls:
audio_test = os.path.join(spk_dir,clip["name"])
#commands.getstatusoutput... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.