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 |
|---|---|---|---|---|
user-tags-resolver.service.spec.ts | import { TestBed, inject } from '@angular/core/testing';
import { LoggedUserTagsResolver } from './user-tags-resolver.service';
import { ModelService } from '../model.service';
import { AuthService } from '../auth.service';
import { UserTag } from '../shared/types';
class ModelStubService {
async readUserTags(_user... | const userTags = await service.resolve();
expect(userTags.length).toEqual(5);
}));
}); | expect(service).toBeTruthy();
}));
it('should resolve with tags of the logged user', inject([LoggedUserTagsResolver], async (service: LoggedUserTagsResolver) => {
| random_line_split |
user-tags-resolver.service.spec.ts | import { TestBed, inject } from '@angular/core/testing';
import { LoggedUserTagsResolver } from './user-tags-resolver.service';
import { ModelService } from '../model.service';
import { AuthService } from '../auth.service';
import { UserTag } from '../shared/types';
class ModelStubService {
async readUserTags(_user... | {
username = 'test-user';
}
describe('LoggedUserTagsResolver', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
LoggedUserTagsResolver,
{ provide: ModelService, useClass: ModelStubService },
{ provide: AuthService, useClass: AuthStubService }
]
}... | AuthStubService | identifier_name |
_load_balancer_network_interfaces_operations.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | cls = kwargs.pop('cls', None) # type: ClsType["_models.NetworkInterfaceListResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2018-12-01"
a... | :raises: ~azure.core.exceptions.HttpResponseError
""" | random_line_split |
_load_balancer_network_interfaces_operations.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | request = self._client.get(url, query_parameters, header_parameters)
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize('NetworkInterfaceListResult', pipeline_response)
list_of_elem = deserialized.value
if ... | header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list.metadata['url'] # type: ignore
path_format_arguments = {
... | identifier_body |
_load_balancer_network_interfaces_operations.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | :
"""LoadBalancerNetworkInterfacesOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models:... | LoadBalancerNetworkInterfacesOperations | identifier_name |
_load_balancer_network_interfaces_operations.py | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
async def extract_data(pipeline_response):
deserialized = self._deserializ... | url = self.list.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'loadBalancerName': self._serialize.url("load_balancer_name", load_balancer_name, 'str'),
... | conditional_block |
normailzed-horizontal-bar-chart.ts | import { GraphData, ColorScheme } from './graph-data';
export class NormailzedHorizontalBarChart {
| (
public results: GraphData[],
// the chart data
public scheme: ColorScheme,
// the color scheme of the chart
public schemeType: string = 'ordinal',
// the color scale type. Can be either 'ordinal' or 'linear'
public animations: boolean = true,
//... | constructor | identifier_name |
normailzed-horizontal-bar-chart.ts | import { GraphData, ColorScheme } from './graph-data';
export class NormailzedHorizontalBarChart {
constructor (
public results: GraphData[],
// the chart data
public scheme: ColorScheme,
// the color scheme of the chart
public schemeType: string = 'ordinal',
... |
}
/**
* Outputs:
* select click event
* activate element activation event (mouse enter)
* deactivate element deactivation event (mouse leave)
*/
/**
* <ngx-charts-bar-horizontal-normalized
[results]=""
[scheme]=""
[schemeType]=""
[animations]=""
[legend]=""
[legendTi... | {} | identifier_body |
normailzed-horizontal-bar-chart.ts | import { GraphData, ColorScheme } from './graph-data';
export class NormailzedHorizontalBarChart {
constructor (
public results: GraphData[],
// the chart data
public scheme: ColorScheme,
// the color scheme of the chart
public schemeType: string = 'ordinal',
... | }
/**
* Outputs:
* select click event
* activate element activation event (mouse enter)
* deactivate element deactivation event (mouse leave)
*/
/**
* <ngx-charts-bar-horizontal-normalized
[results]=""
[scheme]=""
[schemeType]=""
[animations]=""
[legend]=""
[legendTitl... | // function the y axis tick formatting
) {}
| random_line_split |
simpleweapon.py | # -*- coding: utf-8 -*-
# Copyright Tom SF Haines
#
# 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 ag... | self.firing = s
if self.firing:
self.triggerTime = 0.0 | identifier_body | |
simpleweapon.py | # -*- coding: utf-8 -*-
# Copyright Tom SF Haines
#
# 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 ag... | (self):
for i in self.postReload():
yield i
def postReload(self):
# Load the actor...
self.mesh = Actor(self.meshPath)
yield
# Shader generator makes it shiny, plus we need it in the right places in the render graph...
self.mesh.setShaderAuto()
self.mesh.reparentTo(self.gunView)
... | postInit | identifier_name |
simpleweapon.py | # -*- coding: utf-8 -*-
# Copyright Tom SF Haines
#
# 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 ag... |
self.reload(manager,xml)
def destroy(self):
self.gunView.removeNode()
if self.ray!=None:
self.ray.destroy()
def reload(self,manager,xml):
# Get the path to load weapons from...
basePath = manager.get('paths').getConfig().find('weapons').get('path')
# Variables to manage the firi... | self.gunView = render.attachNewNode('gun-view')
self.ray = None | random_line_split |
simpleweapon.py | # -*- coding: utf-8 -*-
# Copyright Tom SF Haines
#
# 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 ag... | sparkQuat = Quat()
sparkQuat.setFromAxisAngleRad(ang,axis)
# Set it going...
self.sparksManager.doEffect(self.sparksEffect, render, False, pos, sparkQuat)
# Make a bullet hole
if hit.hasBody() and isinstance(hit.getBody().getData(), NodePath):
se... | self.triggerTime -= self.bulletRate
hit,pos,norm = ray_cast.nearestHit(self.space,self.ray)
# Create a muzzle flash effect...
self.flashManager.doEffect(self.flashEffect, self.flashBone, True, self.flashPos)
if hit:
# Create an impact sparks effect...
# Calculate th... | conditional_block |
knmi_getdata.py | #!/usr/bin/env python2
'''
Description:
Author: Ronald van Haren, NLeSC (r.vanharen@esciencecenter.nl)
Created: -
Last Modified: -
License: Apache 2.0
Notes: -
'''
from lxml.html import parse
import csv
import urllib2
from lxml import html
import numbers
import json
import os
import ut... | (self):
'''
check if outputdir exists and create if not
'''
if not os.path.exists(self.outputdir):
os.makedirs(self.outputdir)
if __name__ == "__main__":
# define argument menu
description = 'Get data KNMI reference stations'
parser = argparse.ArgumentParser(desc... | check_output_dir | identifier_name |
knmi_getdata.py | #!/usr/bin/env python2
'''
Description:
Author: Ronald van Haren, NLeSC (r.vanharen@esciencecenter.nl)
Created: -
Last Modified: -
License: Apache 2.0
Notes: -
'''
from lxml.html import parse
import csv
import urllib2
from lxml import html
import numbers
import json
import os
import ut... | lon = float(lond[0]) + float(lond[1])/60
return lat,lon
def check_output_dir(self):
'''
check if outputdir exists and create if not
'''
if not os.path.exists(self.outputdir):
os.makedirs(self.outputdir)
if __name__ == "__main__":
# define argument me... | random_line_split | |
knmi_getdata.py | #!/usr/bin/env python2
'''
Description:
Author: Ronald van Haren, NLeSC (r.vanharen@esciencecenter.nl)
Created: -
Last Modified: -
License: Apache 2.0
Notes: -
'''
from lxml.html import parse
import csv
import urllib2
from lxml import html
import numbers
import json
import os
import ut... |
if __name__ == "__main__":
# define argument menu
description = 'Get data KNMI reference stations'
parser = argparse.ArgumentParser(description=description)
# fill argument groups
parser.add_argument('-o', '--outputdir', help='Data output directory',
default=os.path.join(os... | os.makedirs(self.outputdir) | conditional_block |
knmi_getdata.py | #!/usr/bin/env python2
'''
Description:
Author: Ronald van Haren, NLeSC (r.vanharen@esciencecenter.nl)
Created: -
Last Modified: -
License: Apache 2.0
Notes: -
'''
from lxml.html import parse
import csv
import urllib2
from lxml import html
import numbers
import json
import os
import ut... |
def get_station_ids(self):
'''
get all stationids from the KNMI website
'''
self.url = 'http://www.knmi.nl/klimatologie/uurgegevens/'
page = parse(self.url)
# get list of ids
rows = page.xpath(".//tbody/@id")
#self.stationids = [int(stationid[3:]) fo... | self.csvfile = opts.csvfile
self.outputdir = opts.outputdir
self.keep = opts.keep
self.check_output_dir()
if len(opts.stationid)==0:
self.get_station_ids()
else:
self.stationdids = [opts.stationid]
self.download_station_data()
self.get_stat... | identifier_body |
macro.py | """Seqan Doc Links for Trac.
Version 0.1.
Copyright (C) 2010 Manuel Holtgrewe
Install by copying this file into the plugins directory of your trac
work directory. In your trac.ini, you can use something like this
(the following also shows the defaults).
[seqan_doc_links]
prefix = seqan
base_url = http://www.... | *
* {{{dox:ContainerConcept#length}}}
"""
import urllib
import sys
from trac.core import *
import trac.wiki
import genshi.builder as gb
import genshi
from trac.web.chrome import ITemplateProvider, add_stylesheet
def getFilename(cat, item):
"""Get the filename that dddoc would create.
Args:
cat St... | * {{{seqan:"Concept.Simple Type"}}} seqan:"Concept.Simple Type"
* {{{seqan:"Spec.Chunk Pool Allocator}}} seqan:"Spec.Chunk Pool Allocator" | random_line_split |
macro.py | """Seqan Doc Links for Trac.
Version 0.1.
Copyright (C) 2010 Manuel Holtgrewe
Install by copying this file into the plugins directory of your trac
work directory. In your trac.ini, you can use something like this
(the following also shows the defaults).
[seqan_doc_links]
prefix = seqan
base_url = http://www.... | (self):
from pkg_resources import resource_filename
return [('doc_links', resource_filename(__name__, 'htdocs'))]
| get_htdocs_dirs | identifier_name |
macro.py | """Seqan Doc Links for Trac.
Version 0.1.
Copyright (C) 2010 Manuel Holtgrewe
Install by copying this file into the plugins directory of your trac
work directory. In your trac.ini, you can use something like this
(the following also shows the defaults).
[seqan_doc_links]
prefix = seqan
base_url = http://www.... |
### ITemplateProvider methods
def get_templates_dirs(self):
return []
def get_htdocs_dirs(self):
from pkg_resources import resource_filename
return [('doc_links', resource_filename(__name__, 'htdocs'))]
| """Function to perform formatting for dox:XYZ links.
This roughly follows [1].
[1] http://trac.edgewall.org/wiki/TracDev/IWikiSyntaxProviderExample
"""
# Stylesheet already done for doc_links.
add_stylesheet(formatter.req, 'doc_links/css/doc_links.css')
# The following ... | identifier_body |
macro.py | """Seqan Doc Links for Trac.
Version 0.1.
Copyright (C) 2010 Manuel Holtgrewe
Install by copying this file into the plugins directory of your trac
work directory. In your trac.ini, you can use something like this
(the following also shows the defaults).
[seqan_doc_links]
prefix = seqan
base_url = http://www.... |
else:
label = target
# Ignore if the target does not contain a dot.
if not '.' in target:
return target
# Now, use dddoc's logic to generate the appropriate file name for
file_name = getFilename(*target.split('.', 1))
span = [gb.tag.span(genshi.HT... | category, item = tuple(target.split('.', 1))
label = item
# Strip everything before and including the first hash.
if '#' in label:
label = label.split('#', 1)[1] | conditional_block |
fem.py | #!/usr/bin/env python
"""FEM library
Demonstrates some simple finite element definitions, and computes a mass
matrix
$ python fem.py
[ 1/60, 0, -1/360, 0, -1/90, -1/360]
[ 0, 4/45, 0, 2/45, 2/45, -1/90]
[-1/360, 0, 1/60, -1/90, 0, -1/360]
[ 0, 2/45, -1/90, 4/45, 2/45, 0]
... | (self, nsd):
self.nsd = nsd
coords = []
if nsd <= 3:
coords = symbols('x,y,z')[:nsd]
else:
coords = []
for d in range(0,nsd):
coords.append(Symbol("x_%d" % d))
self.coords = coords
def integrate(self,f):
coords = self.coords
... | __init__ | identifier_name |
fem.py | #!/usr/bin/env python
"""FEM library
Demonstrates some simple finite element definitions, and computes a mass
matrix
$ python fem.py
[ 1/60, 0, -1/360, 0, -1/90, -1/360]
[ 0, 4/45, 0, 2/45, 2/45, -1/90]
[-1/360, 0, 1/60, -1/90, 0, -1/360]
[ 0, 2/45, -1/90, 4/45, 2/45, 0]
... | us = []
for i in range(0, fe.nbf()):
ui = Symbol("u_%d" % i)
us.append(ui)
u += ui*fe.N[i]
J = zeros(fe.nbf())
for i in range(0, fe.nbf()):
Fi = u*fe.N[i]
print Fi
for j in range(0, fe.nbf()):
uj = us[j]
integrands = diff(Fi, uj)
print integra... | fe = Lagrange(2,2)
u = 0
#compute u = sum_i u_i N_i | random_line_split |
fem.py | #!/usr/bin/env python
"""FEM library
Demonstrates some simple finite element definitions, and computes a mass
matrix
$ python fem.py
[ 1/60, 0, -1/360, 0, -1/90, -1/360]
[ 0, 4/45, 0, 2/45, 2/45, -1/90]
[-1/360, 0, 1/60, -1/90, 0, -1/360]
[ 0, 2/45, -1/90, 4/45, 2/45, 0]
... |
def bernstein_space(order, nsd):
if nsd > 3:
raise RuntimeError("Bernstein only implemented in 1D, 2D, and 3D")
sum = 0
basis = []
coeff = []
if nsd == 1:
b1, b2 = x, 1-x
for o1 in range(0,order+1):
for o2 in range(0,order+1):
if o1 + o2 == order:
... | coords = self.coords
nsd = self.nsd
limit = 1
for p in coords:
limit -= p
intf = f
for d in range(0,nsd):
p = coords[d]
limit += p
intf = integrate(intf, (p, 0, limit))
return intf | identifier_body |
fem.py | #!/usr/bin/env python
"""FEM library
Demonstrates some simple finite element definitions, and computes a mass
matrix
$ python fem.py
[ 1/60, 0, -1/360, 0, -1/90, -1/360]
[ 0, 4/45, 0, 2/45, 2/45, -1/90]
[-1/360, 0, 1/60, -1/90, 0, -1/360]
[ 0, 2/45, -1/90, 4/45, 2/45, 0]
... |
pprint(J)
if __name__ == "__main__":
main()
| Fi = u*fe.N[i]
print Fi
for j in range(0, fe.nbf()):
uj = us[j]
integrands = diff(Fi, uj)
print integrands
J[j,i] = t.integrate(integrands) | conditional_block |
main.py | import sys
import argparse
import time
sys.path.append('./bin/moabc')
import optimizer
#引数の処理
#parserの初期化
parser = argparse.ArgumentParser(description='This script optimizes bayesian network graph structure by MOABC')
#強化成功率表
parser.add_argument("infile_pt", type=str)
#一回の強化費用
parser.add_argument("-pg","--pricegri... | group_sp.add_argument('-n-sp', '--no-saveprogress', action='store_false')
parser.set_defaults(saveprogress=False)
#並列化のプロセス数
parser.add_argument("-np","--num_proc", type=int, default=1)
#画像出力の有無
# sshログインとかだと無理なので、Falseを入れる
group_wi = parser.add_mutually_exclusive_group()
group_wi.add_argument('-wi', '--withimage'... | #学習中の結果の保存
group_sp = parser.add_mutually_exclusive_group()
group_sp.add_argument('-sp', '--saveprogress', action='store_true') | random_line_split |
main.py | import sys
import argparse
import time
sys.path.append('./bin/moabc')
import optimizer
#引数の処理
#parserの初期化
parser = argparse.ArgumentParser(description='This script optimizes bayesian network graph structure by MOABC')
#強化成功率表
parser.add_argument("infile_pt", type=str)
#一回の強化費用
parser.add_argument("-pg","--pricegri... | conditional_block | ||
camerarotation.py | # Inviwo Python script
import inviwo
import math
import time
start = time.clock()
scale = 1;
| d = 15
steps = 120
for i in range(0, steps):
r = (2 * 3.14 * i) / steps
x = d*math.sin(r)
z = -d*math.cos(r)
inviwo.setPropertyValue("EntryExitPoints.camera",((x*scale,3*scale,z*scale),(0,0,0),(0,1,0)))
for i in range(0, steps):
r = (2 * 3.14 * i) / (steps)
x = 1.0*math.sin(r)
z = 1.0... | random_line_split | |
camerarotation.py | # Inviwo Python script
import inviwo
import math
import time
start = time.clock()
scale = 1;
d = 15
steps = 120
for i in range(0, steps):
r = (2 * 3.14 * i) / steps
x = d*math.sin(r)
z = -d*math.cos(r)
inviwo.setPropertyValue("EntryExitPoints.camera",((x*scale,3*scale,z*scale),(0,0,0),(0,... |
end = time.clock()
fps = 2*steps / (end - start)
fps = round(fps,3)
print("Frames per second: " + str(fps))
print("Time per frame: " + str(round(1000/fps,1)) + " ms") | r = (2 * 3.14 * i) / (steps)
x = 1.0*math.sin(r)
z = 1.0*math.cos(r)
inviwo.setCameraUp("EntryExitPoints.camera",(x*scale,z*scale,0)) | conditional_block |
slim.py | # Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at | # distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ========================================================================... | #
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software | random_line_split |
french_texts_dl.py | # Retrieves all text files from CNAM ABU (see license here : http://abu.cnam.fr/cgi-bin/donner_licence) for further treatment
import urllib.request
import os
from bs4 import BeautifulSoup, SoupStrainer
# Proxy handling
proxies = {'http':''}
opnr = urllib.request.build_opener(urllib.request.ProxyHandler(proxies))
u... | os.mkdir(dir)
read=False
cnt=0
buffstring=''
# Reads text file from "DEBUT DU FICHIER" to "FIN DU FICHIER", regroups lines in packets of ~15000 chars and stores in text file
for i in range(len(lines))... | random_line_split | |
french_texts_dl.py | # Retrieves all text files from CNAM ABU (see license here : http://abu.cnam.fr/cgi-bin/donner_licence) for further treatment
import urllib.request
import os
from bs4 import BeautifulSoup, SoupStrainer
# Proxy handling
proxies = {'http':''}
opnr = urllib.request.build_opener(urllib.request.ProxyHandler(proxies))
u... |
f=open(dir+'/'+str(cnt)+'.txt','w',encoding='utf8')
f.write(buffstring)
f.close()
buffstring=''
cnt =cnt+1
... | name = link['href'].split('?')[1]
print(name)
# Download text file
with urllib.request.urlopen('http://abu.cnam.fr/cgi-bin/donner_unformated?'+name) as response:
# Conversion to ISO-Latin 1
text = response.read().decode('ISO-8859-1'... | conditional_block |
coord.rs | use std::ops::*;
use std::fmt;
#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct Coord<T>(pub T, pub T);
impl<T> Coord<T> {
pub const fn squared(value: T) -> Self where T: Copy {
Coord(value, value)
}
pub fn sum(self) -> T where T: Add<Output=T> {
let Coord(x, y) = self;
... |
}
| {
let coord = Coord(5,6);
assert_eq!(5, coord.0);
assert_eq!(6, coord.1);
} | identifier_body |
coord.rs | use std::ops::*;
use std::fmt;
#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct Coord<T>(pub T, pub T);
impl<T> Coord<T> {
pub const fn squared(value: T) -> Self where T: Copy {
Coord(value, value)
}
pub fn sum(self) -> T where T: Add<Output=T> {
let Coord(x, y) = self;
... | <U>(self, mut func: impl FnMut(T) -> U) -> Coord<U> {
let Coord(x, y) = self;
Coord(func(x), func(y))
}
}
impl<T: fmt::Debug> fmt::Debug for Coord<T> {
fn fmt (&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({:?}, {:?})", self.0, self.1)
}
}
impl<T: fmt::Display> fmt::D... | map | identifier_name |
coord.rs | use std::ops::*;
use std::fmt;
#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct Coord<T>(pub T, pub T);
impl<T> Coord<T> {
pub const fn squared(value: T) -> Self where T: Copy {
Coord(value, value)
}
pub fn sum(self) -> T where T: Add<Output=T> {
let Coord(x, y) = self;
... | use super::*;
#[test]
fn sanity() {
let coord = Coord(5,6);
assert_eq!(5, coord.0);
assert_eq!(6, coord.1);
}
} |
#[cfg(test)]
mod tests { | random_line_split |
forms.py | from app import app
from fields import PreValidatedFormField
from flask_wtf import Form
from wtforms import (TextField, TextAreaField, FormField, FieldList,
HiddenField, SubmitField)
from wtforms.validators import (DataRequired, Optional, StopValidation)
EMPTY_VALUES = ['', None]
def DynamicList... |
class AnnotatedTextForm(AnnotatedForm):
refdata = TextField('reference data', validators=[Optional()])
class AnnotatedTextAreaForm(AnnotatedForm):
refdata = TextAreaField('reference data', validators=[Optional()])
class AnnotatedIntForm(AnnotatedForm):
int_data = TextField('Some text', validators=[in... | return super(AnnotatedForm, self).validate() | identifier_body |
forms.py | from app import app
from fields import PreValidatedFormField
from flask_wtf import Form
from wtforms import (TextField, TextAreaField, FormField, FieldList,
HiddenField, SubmitField)
from wtforms.validators import (DataRequired, Optional, StopValidation)
EMPTY_VALUES = ['', None]
def DynamicList... | entry points, each with their own sub forms. Contains general data entry
metadata that should be shared among all fields, some of which is specified
again per field (classification)
'''
#metadata = FormField(ReportMetadataForm)
#operators = DynamicListForm(FormField(OperatorForm), min_entries=1)... |
class ReportEntryForm(AnnotatedForm):
'''
Class to encompass general data entry from a report, from a variety of | random_line_split |
forms.py | from app import app
from fields import PreValidatedFormField
from flask_wtf import Form
from wtforms import (TextField, TextAreaField, FormField, FieldList,
HiddenField, SubmitField)
from wtforms.validators import (DataRequired, Optional, StopValidation)
EMPTY_VALUES = ['', None]
def DynamicList... |
class ReportMetadataForm(Form):
uncertainty_measure = TextField('Uncertainty', validators=[DataRequired()])
classification = TextField('Classification', validators=[DataRequired()])
provenance = TextField('Provenance', validators=[DataRequired()])
created_at = TextField('Created at', validators=[Data... | raise StopValidation() | conditional_block |
forms.py | from app import app
from fields import PreValidatedFormField
from flask_wtf import Form
from wtforms import (TextField, TextAreaField, FormField, FieldList,
HiddenField, SubmitField)
from wtforms.validators import (DataRequired, Optional, StopValidation)
EMPTY_VALUES = ['', None]
def DynamicList... | (self):
return super(AnnotatedForm, self).validate()
class AnnotatedTextForm(AnnotatedForm):
refdata = TextField('reference data', validators=[Optional()])
class AnnotatedTextAreaForm(AnnotatedForm):
refdata = TextAreaField('reference data', validators=[Optional()])
class AnnotatedIntForm(Annotate... | validate | identifier_name |
enum.rs | // Task : To explain enum in rust
// Author : Vigneshwer
// Version : 1.0
// Date : 3 Dec 2016
fn main() {
let hulk = Hero::Strong(100);
let fasty = Hero::Fast;
//converting from
let spiderman = Hero::Info {
name: "spiderman".to_owned(),
secret: "peter parker".to_owned(),
};
g... | (h: Hero) {
match h {
Hero::Fast => println!("Fast"),
Hero::Strong(i) => println!("Lifts {} tons", i),
Hero::Info { name, secret } => {
println!(" name is : {0} secret is : {1}", name, secret);
}
}
}
| get_info | identifier_name |
enum.rs |
fn main() {
let hulk = Hero::Strong(100);
let fasty = Hero::Fast;
//converting from
let spiderman = Hero::Info {
name: "spiderman".to_owned(),
secret: "peter parker".to_owned(),
};
get_info(spiderman);
get_info(hulk);
get_info(fasty);
}
// declaring the enum
enum Hero... | // Task : To explain enum in rust
// Author : Vigneshwer
// Version : 1.0
// Date : 3 Dec 2016 | random_line_split | |
enum.rs | // Task : To explain enum in rust
// Author : Vigneshwer
// Version : 1.0
// Date : 3 Dec 2016
fn main() |
// declaring the enum
enum Hero {
Fast,
Strong(i32),
Info { name: String, secret: String },
}
// function to perform for each types
fn get_info(h: Hero) {
match h {
Hero::Fast => println!("Fast"),
Hero::Strong(i) => println!("Lifts {} tons", i),
Hero::Info { name, secret } => ... | {
let hulk = Hero::Strong(100);
let fasty = Hero::Fast;
//converting from
let spiderman = Hero::Info {
name: "spiderman".to_owned(),
secret: "peter parker".to_owned(),
};
get_info(spiderman);
get_info(hulk);
get_info(fasty);
} | identifier_body |
val.py | # val for type checking (literal or ENUM style)
from pyrser import fmt
from pyrser.type_system.signature import *
from pyrser.type_system.type_name import *
class Val(Signature):
"""
Describe a value signature for the language
"""
nvalues = 0
valuniq = dict()
def __init__(self, value, tret: s... |
else:
idx = Val.valuniq[k]
super().__init__('$' + str(idx))
def internal_name(self):
"""
Return the unique internal name
"""
unq = super().internal_name()
if self.tret is not None:
unq += "_" + self.tret
return unq
| Val.nvalues += 1
Val.valuniq[k] = Val.nvalues
idx = Val.nvalues | conditional_block |
val.py | # val for type checking (literal or ENUM style)
from pyrser import fmt
from pyrser.type_system.signature import *
from pyrser.type_system.type_name import *
class | (Signature):
"""
Describe a value signature for the language
"""
nvalues = 0
valuniq = dict()
def __init__(self, value, tret: str):
if not isinstance(value, str):
value = str(value)
self.value = value
if not isinstance(tret, TypeName):
tret = Type... | Val | identifier_name |
val.py | # val for type checking (literal or ENUM style)
from pyrser import fmt
from pyrser.type_system.signature import *
from pyrser.type_system.type_name import *
class Val(Signature):
"""
Describe a value signature for the language
"""
nvalues = 0
valuniq = dict()
def __init__(self, value, tret: s... | """
Return the unique internal name
"""
unq = super().internal_name()
if self.tret is not None:
unq += "_" + self.tret
return unq | identifier_body | |
val.py | # val for type checking (literal or ENUM style)
from pyrser import fmt
from pyrser.type_system.signature import *
from pyrser.type_system.type_name import *
class Val(Signature):
"""
Describe a value signature for the language
"""
nvalues = 0
valuniq = dict() | if not isinstance(value, str):
value = str(value)
self.value = value
if not isinstance(tret, TypeName):
tret = TypeName(tret)
self.tret = tret
k = self.value + "$" + tret
idx = 0
if k not in Val.valuniq:
Val.nvalues += 1
... |
def __init__(self, value, tret: str): | random_line_split |
lib.rs | //! This library provides wrappers for LLVM that are memory-safe and follow
//! Rust idioms. | //!
//! The original LLVM reference is available [here](http://llvm.org/doxygen/)
//! but take note that this isn't as thorough as this documentation.
extern crate llvm_sys as ffi;
extern crate libc;
extern crate cbox;
#[macro_use]
mod macros;
mod buffer;
mod block;
mod builder;
mod compile;
mod context;
mod engine;
... | random_line_split | |
Cap02_pagina_25_comp_interactiva.py | '''
@author: Sergio Rojas
@contact: rr.sergio@gmail.com
--------------------------
Contenido bajo
Atribución-NoComercial-CompartirIgual 3.0 Venezuela (CC BY-NC-SA 3.0 VE)
http://creativecommons.org/licenses/by-nc-sa/3.0/ve/
Creado en abril 19, 2016
'''
print(3+5)
print(2-6)
print(2*7)
print(6/2)
print(1/3)
print(1.... | print(2.5**(3.2 + 2.1))
print(6.78**30)
print(8.647504884825773*1e+24 - 8.647504884825773*10**24)
print(1e+2)
print(1e2)
print(1e-2)
print(2e4)
print(4**(1./2.))
print(4**0.5)
print(8**(1./3.))
print(8**0.3333) | print(2.5**3) | random_line_split |
index.d.ts | // Type definitions for Alt 0.16.10
// Project: https://github.com/goatslacker/alt
// Definitions by: Michael Shearer <https://github.com/Shearerbeard>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
///<reference types="react"/>
declare namespace AltJS {
interface Sto... | {
constructor(config?:AltConfig);
actions:Actions;
bootstrap(jsonData:string):void;
takeSnapshot( ...storeNames:Array<string>):string;
flush():Object;
recycle( ...stores:Array<AltJS.AltStore<any>>):void;
rollback():void;
dispatch(action?:AltJS.Action<any>|string, data?:Object, details?:... | Alt | identifier_name |
index.d.ts | // Type definitions for Alt 0.16.10
// Project: https://github.com/goatslacker/alt
// Definitions by: Michael Shearer <https://github.com/Shearerbeard>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
///<reference types="react"/>
declare namespace AltJS {
interface Sto... | error
}
export type Actions = {[action:string]:Action<any>};
export interface Action<T> {
( args:T):void;
defer(data:any):void;
}
export interface ActionsClass {
generateActions?( ...action:Array<string>):void;
dispatch( ...payload:Array<any>):void;
actions?:Actions;
}
type Sta... | init,
rollback, | random_line_split |
example.rs | #[derive(Debug, PartialEq, Eq)]
pub struct Palindrome {
pub factors: Vec<(u64, u64)>,
}
impl Palindrome {
/// Create a palindrome with the given factors
pub fn new(mut a: u64, mut b: u64) -> Palindrome {
if a > b {
std::mem::swap(&mut a, &mut b);
}
Palindrome {
... | Some((mut minp, mut maxp)) => {
match (a * b).cmp(&minp.value()) {
std::cmp::Ordering::Greater => {}
std::cmp::Ordering::Less => minp = Palindrome::new(a, b),
std::cmp::Ordering::Equal => minp... | result = match result {
None => Some((Palindrome::new(a, b), Palindrome::new(a, b))), | random_line_split |
example.rs | #[derive(Debug, PartialEq, Eq)]
pub struct | {
pub factors: Vec<(u64, u64)>,
}
impl Palindrome {
/// Create a palindrome with the given factors
pub fn new(mut a: u64, mut b: u64) -> Palindrome {
if a > b {
std::mem::swap(&mut a, &mut b);
}
Palindrome {
factors: vec![(a, b)],
}
}
/// Re... | Palindrome | identifier_name |
example.rs | #[derive(Debug, PartialEq, Eq)]
pub struct Palindrome {
pub factors: Vec<(u64, u64)>,
}
impl Palindrome {
/// Create a palindrome with the given factors
pub fn new(mut a: u64, mut b: u64) -> Palindrome {
if a > b {
std::mem::swap(&mut a, &mut b);
}
Palindrome {
... |
/// Insert a new set of factors into an existing palindrome
pub fn insert(&mut self, mut a: u64, mut b: u64) {
if a > b {
std::mem::swap(&mut a, &mut b);
}
self.factors.push((a, b));
self.factors.sort_unstable();
self.factors.dedup();
}
}
/// return the... | {
// this could in theory panic with a bounds error, but the length of
// self.factors is known to start at 1 and is only ever increased
self.factors[0].0 * self.factors[0].1
} | identifier_body |
363. Max Sum of Rectangle No Larger Than K.py | """
Given a non-empty 2D matrix matrix and an integer k, find the max sum of a rectangle in the matrix such that its sum is no larger than k.
Example:
Given matrix = [
[1, 0, 1],
[0, -2, 3]
]
k = 2
The answer is 2. Because the sum of rectangle [[0, 1], [-2, 3]] is 2 and 2 is the max number no larger than k (k = 2... | import bisect
class Solution(object):
def maxSumSubmatrix(self, matrix, k):
"""
:type matrix: List[List[int]]
:type k: int
:rtype: int
"""
m, n, result = len(matrix), len(matrix[0]), float('-inf')
# m should > n
if m < n:
matrix = zip(*ma... | random_line_split | |
363. Max Sum of Rectangle No Larger Than K.py | """
Given a non-empty 2D matrix matrix and an integer k, find the max sum of a rectangle in the matrix such that its sum is no larger than k.
Example:
Given matrix = [
[1, 0, 1],
[0, -2, 3]
]
k = 2
The answer is 2. Because the sum of rectangle [[0, 1], [-2, 3]] is 2 and 2 is the max number no larger than k (k = 2... | result = max(result, block_sum - block_sums[pos])
bisect.insort(block_sums, block_sum)
return result
| def maxSumSubmatrix(self, matrix, k):
"""
:type matrix: List[List[int]]
:type k: int
:rtype: int
"""
m, n, result = len(matrix), len(matrix[0]), float('-inf')
# m should > n
if m < n:
matrix = zip(*matrix)
m, n = n, m
for l ... | identifier_body |
363. Max Sum of Rectangle No Larger Than K.py | """
Given a non-empty 2D matrix matrix and an integer k, find the max sum of a rectangle in the matrix such that its sum is no larger than k.
Example:
Given matrix = [
[1, 0, 1],
[0, -2, 3]
]
k = 2
The answer is 2. Because the sum of rectangle [[0, 1], [-2, 3]] is 2 and 2 is the max number no larger than k (k = 2... | (object):
def maxSumSubmatrix(self, matrix, k):
"""
:type matrix: List[List[int]]
:type k: int
:rtype: int
"""
m, n, result = len(matrix), len(matrix[0]), float('-inf')
# m should > n
if m < n:
matrix = zip(*matrix)
m, n = n, m
... | Solution | identifier_name |
363. Max Sum of Rectangle No Larger Than K.py | """
Given a non-empty 2D matrix matrix and an integer k, find the max sum of a rectangle in the matrix such that its sum is no larger than k.
Example:
Given matrix = [
[1, 0, 1],
[0, -2, 3]
]
k = 2
The answer is 2. Because the sum of rectangle [[0, 1], [-2, 3]] is 2 and 2 is the max number no larger than k (k = 2... |
bisect.insort(block_sums, block_sum)
return result
| result = max(result, block_sum - block_sums[pos]) | conditional_block |
aakuan_guardian.py | import sys
from services.spawn import MobileTemplate
from services.spawn import WeaponTemplate
from resources.datatables import WeaponType
from resources.datatables import Difficulty
from resources.datatables import Options
from java.util import Vector
def addTemplate(core):
| weaponTemplates = Vector()
weapontemplate = WeaponTemplate('object/weapon/melee/polearm/shared_polearm_vibro_axe.iff', WeaponType.CARBINE, 1.0, 15, 'energy')
weaponTemplates.add(weapontemplate)
mobileTemplate.setWeaponTemplateVector(weaponTemplates)
attacks = Vector()
mobileTemplate.setDefaultAttack('melee... | mobileTemplate = MobileTemplate()
mobileTemplate.setCreatureName('aakuan_guardian')
mobileTemplate.setLevel(48)
mobileTemplate.setDifficulty(Difficulty.NORMAL)
mobileTemplate.setMinSpawnDistance(4)
mobileTemplate.setMaxSpawnDistance(8)
mobileTemplate.setDeathblow(True)
mobileTemplate.setScale(1)
mob... | identifier_body |
aakuan_guardian.py | import sys
from services.spawn import MobileTemplate
from services.spawn import WeaponTemplate
from resources.datatables import WeaponType
from resources.datatables import Difficulty
from resources.datatables import Options
from java.util import Vector
def addTemplate(core):
mobileTemplate = MobileTemplate... | mobileTemplate.setScale(1)
mobileTemplate.setSocialGroup("aakuans")
mobileTemplate.setAssistRange(0)
mobileTemplate.setStalker(True)
mobileTemplate.setOptionsBitmask(Options.AGGRESSIVE | Options.ATTACKABLE)
templates = Vector()
templates.add('object/mobile/shared_dressed_aakuan_guardian_trandoshan_male_0... | mobileTemplate.setMinSpawnDistance(4)
mobileTemplate.setMaxSpawnDistance(8)
mobileTemplate.setDeathblow(True)
| random_line_split |
aakuan_guardian.py | import sys
from services.spawn import MobileTemplate
from services.spawn import WeaponTemplate
from resources.datatables import WeaponType
from resources.datatables import Difficulty
from resources.datatables import Options
from java.util import Vector
def | (core):
mobileTemplate = MobileTemplate()
mobileTemplate.setCreatureName('aakuan_guardian')
mobileTemplate.setLevel(48)
mobileTemplate.setDifficulty(Difficulty.NORMAL)
mobileTemplate.setMinSpawnDistance(4)
mobileTemplate.setMaxSpawnDistance(8)
mobileTemplate.setDeathblow(True)
mobileTemplate.setScal... | addTemplate | identifier_name |
privacy1.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
trait B {
fn foo() -> Self;
}
impl B for int { fn foo() -> int { 3 } }
pub enum Enum {
Pub
}
mod baz {
pub struct A;
impl A {
pub fn foo() {}
fn bar() {}
pub fn foo2(&self) {}
fn bar2(&self) {}
}
... | {} | identifier_body |
privacy1.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {}
fn bar() {}
pub fn foo2(&self) {}
fn bar2(&self) {}
}
// both of these are re-exported by `bar`, but only one should be
// validly re-exported
pub fn foo() {}
fn bar() {}
}
extern {
fn epriv();
pub fn epub();
... | foo | identifier_name |
privacy1.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | ::bar::baz::A.foo2(); //~ ERROR: struct `A` is inaccessible
//~^ NOTE: module `baz` is private
::bar::baz::A.bar2(); //~ ERROR: struct `A` is inaccessible
//~^ ERROR: method `bar2` is private
//~^^ NOTE: ... | ::bar::A.bar2(); //~ ERROR: method `bar2` is private
::bar::baz::A::foo(); //~ ERROR: method `foo` is inaccessible
//~^ NOTE: module `baz` is private
::bar::baz::A::bar(); //~ ERROR: method `bar` is private | random_line_split |
GameState.ts | /**
* @author Digitsensitive <digit.sensitivee@gmail.com>
* @copyright 2017 Digitsensitive
* @license Digitsensitive
*/
import * as NE from '../node_modules/neuroevolution-typescript/main';
import { Player } from './Player'
import { Ball } from './Ball'
const neuvol: NE.Neuroevolution = new NE.Neuroev... |
}
this.aiPaddle.render();
this.ball.render();
}
private aiMovePaddle(): void {
if (this.aiPaddle.getTypePlayer() == 3) {
if (this.aiPaddle.getPos().y > this.ball.getPos().y+this.p2) {
this.aiPaddle.setMoveUp(true);
}
else if (this.aiPaddle.getPos().y < this.ball.getPos().y-this... | {
this.paddlesLeft[i].render();
} | conditional_block |
GameState.ts | /**
* @author Digitsensitive <digit.sensitivee@gmail.com>
* @copyright 2017 Digitsensitive
* @license Digitsensitive
*/
import * as NE from '../node_modules/neuroevolution-typescript/main';
import { Player } from './Player'
import { Ball } from './Ball'
const neuvol: NE.Neuroevolution = new NE.Neuroev... |
update(): void {
/* neuroevolution integration paddles left */
for (let i = 0; i < this.paddlesLeft.length; i++) {
if (this.paddlesLeft[i].alive) {
var inputs = [
this.paddlesLeft[i].getPos().y / this.game.world.height,
this.ball.getPos().y / this.game.world.height,
... | {
/* create texts */
generation++;
this.scoreTexts[2].text = "Generation: "+generation;
this.scoreTexts[3].text = "Generation: "+generation;
/* create the game objects */
this.gen = neuvol.nextGeneration();
for (let i in this.gen) {
let p = new Player(this.game, 160, this.game.world.c... | identifier_body |
GameState.ts | /**
* @author Digitsensitive <digit.sensitivee@gmail.com>
* @copyright 2017 Digitsensitive
* @license Digitsensitive
*/
import * as NE from '../node_modules/neuroevolution-typescript/main';
import { Player } from './Player'
import { Ball } from './Ball'
const neuvol: NE.Neuroevolution = new NE.Neuroev... | if (res > 0.5) {
this.paddlesLeft[i].goUp();
}
else {
this.paddlesLeft[i].goDown();
}
this.aiMovePaddle();
/* collision check */
this.game.physics.arcade.collide(this.paddlesLeft[i], this.ball, this.collisionPaddleBall, null, this);
... | this.ball.getPos().y - this.paddlesLeft[i].getPos().y];
var res = this.gen[i].compute(inputs);
| random_line_split |
GameState.ts | /**
* @author Digitsensitive <digit.sensitivee@gmail.com>
* @copyright 2017 Digitsensitive
* @license Digitsensitive
*/
import * as NE from '../node_modules/neuroevolution-typescript/main';
import { Player } from './Player'
import { Ball } from './Ball'
const neuvol: NE.Neuroevolution = new NE.Neuroev... | (): boolean {
for (let i in this.paddlesLeft) {
if(this.paddlesLeft[i].alive){
return false;
}
}
return true;
}
private restartGame(): void {
this.game.state.restart();
}
}
| isItEnd | identifier_name |
time-to-leave.js | 'use strict';
var React = require('react');
var PureRenderMixin = require('react-addons-pure-render-mixin');
var SvgIcon = require('../../svg-icon');
var NotificationTimeToLeave = React.createClass({
displayName: 'NotificationTimeToLeave',
mixins: [PureRenderMixin],
| render: function render() {
return React.createElement(
SvgIcon,
this.props,
React.createElement('path', { d: 'M18.92 5.01C18.72 4.42 18.16 4 17.5 4h-11c-.66 0-1.21.42-1.42 1.01L3 11v8c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-1h12v1c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-8l-2.08-5.99zM6.5 15c-.83 0-1.5-.67-... | random_line_split | |
extract.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use cpython::Python;
/// Trait for extracting a Rust object from a Python wrapper class.
///
/// A common pattern when writing bindings for ... | (&self, py: Python) -> Self::Inner {
self.extract_inner_ref(py).clone()
}
}
| extract_inner | identifier_name |
extract.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the | */
use cpython::Python;
/// Trait for extracting a Rust object from a Python wrapper class.
///
/// A common pattern when writing bindings for Rust objects is to define
/// a Python wrapper class using the `py_class!` macro, with the underlying
/// Rust object stored as a data field within the Python object.
///
///... | * GNU General Public License version 2. | random_line_split |
extract.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use cpython::Python;
/// Trait for extracting a Rust object from a Python wrapper class.
///
/// A common pattern when writing bindings for ... |
}
| {
self.extract_inner_ref(py).clone()
} | identifier_body |
__init__.py | # Orca
#
# Copyright 2005-2009 Sun Microsystems Inc.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This... | # You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., Franklin Street, Fifth Floor,
# Boston MA 02110-1301 USA.
"""Custom script for Packagemanager."""
from script import Script | random_line_split | |
Remove _Resources.py | import os, shutil, xbmc, xbmcgui
pDialog = xbmcgui.DialogProgress()
dialog = xbmcgui.Dialog()
Game_Directories = [ "E:\\Games\\", "F:\\Games\\", "G:\\Games\\", "E:\\Applications\\", "F:\\Applications\\", "G:\\Applications\\", "E:\\Homebrew\\", "F:\\Homebrew\\", "G:\\Homebrew\\", "E:\\Apps\\", "F:\\Apps\\", "G:\\Apps... |
if os.path.isfile(DefaultTBN):
os.remove(DefaultTBN)
else:
print "Cannot find: " + DefaultTBN
if os.path.isfile(FanartJPG):
os.remove(FanartJPG)
else:
print "Cannot find: " + FanartJPG
pDialog.close()
dialog.ok("COMPLETE","Done, _Resources Folders Removed.") | print "Cannot find: " + _Resources | conditional_block |
Remove _Resources.py | import os, shutil, xbmc, xbmcgui
pDialog = xbmcgui.DialogProgress()
dialog = xbmcgui.Dialog()
Game_Directories = [ "E:\\Games\\", "F:\\Games\\", "G:\\Games\\", "E:\\Applications\\", "F:\\Applications\\", "G:\\Applications\\", "E:\\Homebrew\\", "F:\\Homebrew\\", "G:\\Homebrew\\", "E:\\Apps\\", "F:\\Apps\\", "G:\\Apps... | if os.path.isdir( Game_Directories ):
pDialog.create( "PARSING XBOX GAMES","Initializing" )
pDialog.update(0,"Removing _Resources Folders","","This can take some time, please be patient.")
for Items in sorted( os.listdir( Game_Directories ) ):
if os.path.isdir(os.path.join( Game_Directories, Items)):
... | for Game_Directories in Game_Directories:
| random_line_split |
gulpfile.js | // Init
var gulp = require('gulp');
var jshint = require('gulp-jshint');
var stylish = require('jshint-stylish');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var less = require('gulp-less');
var paths = {
js: [
'./bower_components/jquery/dist/jquery.js',
'./bower_c... | './bower_components/bootstrap/js/scrollspy.js',
'./bower_components/bootstrap/js/tab.js',
'./bower_components/bootstrap/js/tooltip.js',
'./src/js/*.js'
],
jsWatch: './src/js/*.js',
less: './src/less/master.less',
lessWatch: './src/less/**/*.less',
build: 'template/assets/'
};
// JS
gulp.task('... | './bower_components/bootstrap/js/popover.js', | random_line_split |
gulpfile.js | // Init
var gulp = require('gulp');
var jshint = require('gulp-jshint');
var stylish = require('jshint-stylish');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var less = require('gulp-less');
var paths = {
js: [
'./bower_components/jquery/dist/jquery.js',
'./bower_c... | (err) {
console.log(err.toString());
this.emit('end');
} | handleError | identifier_name |
gulpfile.js | // Init
var gulp = require('gulp');
var jshint = require('gulp-jshint');
var stylish = require('jshint-stylish');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var less = require('gulp-less');
var paths = {
js: [
'./bower_components/jquery/dist/jquery.js',
'./bower_c... | {
console.log(err.toString());
this.emit('end');
} | identifier_body | |
cell.rs | // Lumol, an extensible molecular simulation engine
// Copyright (C) Lumol's contributors — BSD license
use std::fs::File;
use std::io::{self, BufWriter};
use std::io::prelude::*;
use std::path::{Path, PathBuf};
use log::error;
use super::Output;
use lumol_core::System;
/// The `CellOutput` writes all the component... | mpl Output for CellOutput {
#[allow(clippy::non_ascii_literal)]
fn setup(&mut self, _: &System) {
writeln_or_log!(self, "# Unit cell of the simulation");
writeln_or_log!(self, "# Step A/Å B/Å C/Å α/deg β/deg γ/deg");
}
fn write(&mut self, system: &System) {
writeln_or_log!(self,... | Ok(CellOutput {
file: BufWriter::new(File::create(filename.as_ref())?),
path: filename.as_ref().to_owned(),
})
}
}
i | identifier_body |
cell.rs | // Lumol, an extensible molecular simulation engine
// Copyright (C) Lumol's contributors — BSD license
use std::fs::File;
use std::io::{self, BufWriter};
use std::io::prelude::*;
use std::path::{Path, PathBuf};
use log::error;
use super::Output;
use lumol_core::System;
/// The `CellOutput` writes all the component... | fn cell() {
test_output(
|path| Box::new(CellOutput::new(path).unwrap()),
"# Unit cell of the simulation
# Step A/Å B/Å C/Å α/deg β/deg γ/deg
42 10 10 10 90 90 90
",
);
}
} | use super::*;
use super::super::tests::test_output;
#[test] | random_line_split |
cell.rs | // Lumol, an extensible molecular simulation engine
// Copyright (C) Lumol's contributors — BSD license
use std::fs::File;
use std::io::{self, BufWriter};
use std::io::prelude::*;
use std::path::{Path, PathBuf};
use log::error;
use super::Output;
use lumol_core::System;
/// The `CellOutput` writes all the component... | self, _: &System) {
writeln_or_log!(self, "# Unit cell of the simulation");
writeln_or_log!(self, "# Step A/Å B/Å C/Å α/deg β/deg γ/deg");
}
fn write(&mut self, system: &System) {
writeln_or_log!(self, "{} {} {} {} {} {} {}",
system.step,
system.cell.a(),
... | (&mut | identifier_name |
issue-34053.rs | // run-pass
use std::sync::atomic::{AtomicUsize, Ordering};
static DROP_COUNTER: AtomicUsize = AtomicUsize::new(0);
struct A(i32);
impl Drop for A {
fn drop(&mut self) |
}
static FOO: A = A(123);
const BAR: A = A(456);
impl A {
const BAZ: A = A(789);
}
fn main() {
assert_eq!(DROP_COUNTER.load(Ordering::SeqCst), 0);
assert_eq!(&FOO.0, &123);
assert_eq!(DROP_COUNTER.load(Ordering::SeqCst), 0);
assert_eq!(BAR.0, 456);
assert_eq!(DROP_COUNTER.load(Ordering::SeqC... | {
// update global drop count
DROP_COUNTER.fetch_add(1, Ordering::SeqCst);
} | identifier_body |
issue-34053.rs | // run-pass
use std::sync::atomic::{AtomicUsize, Ordering};
static DROP_COUNTER: AtomicUsize = AtomicUsize::new(0);
struct A(i32);
impl Drop for A {
fn | (&mut self) {
// update global drop count
DROP_COUNTER.fetch_add(1, Ordering::SeqCst);
}
}
static FOO: A = A(123);
const BAR: A = A(456);
impl A {
const BAZ: A = A(789);
}
fn main() {
assert_eq!(DROP_COUNTER.load(Ordering::SeqCst), 0);
assert_eq!(&FOO.0, &123);
assert_eq!(DROP_COU... | drop | identifier_name |
issue-34053.rs | // run-pass
use std::sync::atomic::{AtomicUsize, Ordering};
| fn drop(&mut self) {
// update global drop count
DROP_COUNTER.fetch_add(1, Ordering::SeqCst);
}
}
static FOO: A = A(123);
const BAR: A = A(456);
impl A {
const BAZ: A = A(789);
}
fn main() {
assert_eq!(DROP_COUNTER.load(Ordering::SeqCst), 0);
assert_eq!(&FOO.0, &123);
assert_e... | static DROP_COUNTER: AtomicUsize = AtomicUsize::new(0);
struct A(i32);
impl Drop for A { | random_line_split |
solution.rs | use std::env;
use std::io::prelude::*;
use std::io::BufReader;
use std::fs::File;
fn is_triangle(mut triangle: Vec<i32>) -> bool
{
triangle.sort();
return triangle[0] + triangle[1] > triangle[2];
}
fn main() {
let args: Vec<String> = env::args().collect();
let f = File::open(&args[1]).expect("Could n... | .filter(|s| !s.is_empty())
.map(|s| s.parse().unwrap())
.collect();
for num in &numbers {
all_nums.push(*num);
}
if is_triangle(numbers) {
horizontal += 1;
}
}
let mut vertical = 0;
for i in 0..(all_nums.len() /... | for line in reader.lines() {
let numbers: Vec<i32> = line.unwrap()
.split(' ')
.map(|s| s.trim()) | random_line_split |
solution.rs | use std::env;
use std::io::prelude::*;
use std::io::BufReader;
use std::fs::File;
fn is_triangle(mut triangle: Vec<i32>) -> bool
{
triangle.sort();
return triangle[0] + triangle[1] > triangle[2];
}
fn | () {
let args: Vec<String> = env::args().collect();
let f = File::open(&args[1]).expect("Could not open file");
let reader = BufReader::new(f);
let mut horizontal = 0;
let mut all_nums: Vec<i32> = Vec::new();
for line in reader.lines() {
let numbers: Vec<i32> = line.unwrap()
... | main | identifier_name |
solution.rs | use std::env;
use std::io::prelude::*;
use std::io::BufReader;
use std::fs::File;
fn is_triangle(mut triangle: Vec<i32>) -> bool
{
triangle.sort();
return triangle[0] + triangle[1] > triangle[2];
}
fn main() {
let args: Vec<String> = env::args().collect();
let f = File::open(&args[1]).expect("Could n... |
}
}
println!("{} triangles possible horizontally", horizontal);
println!("{} triangles possible vertically", vertical);
}
| {
vertical += 1;
} | conditional_block |
solution.rs | use std::env;
use std::io::prelude::*;
use std::io::BufReader;
use std::fs::File;
fn is_triangle(mut triangle: Vec<i32>) -> bool
|
fn main() {
let args: Vec<String> = env::args().collect();
let f = File::open(&args[1]).expect("Could not open file");
let reader = BufReader::new(f);
let mut horizontal = 0;
let mut all_nums: Vec<i32> = Vec::new();
for line in reader.lines() {
let numbers: Vec<i32> = line.unwrap()
... | {
triangle.sort();
return triangle[0] + triangle[1] > triangle[2];
} | identifier_body |
functions.py | capture import *
def default(val, d):
if val is not None:
return val
else:
return d
def current_word(document):
piter = document.get_iter_at_mark(document.get_insert())
start = piter.copy()
if not piter.starts_word() and (piter.inside_word() or piter.ends_word()):
start.ba... | anel.write(line)
| identifier_body | |
functions.py | GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or F... | try:
start, end = document.get_selection_bounds()
except ValueError:
if input_type == 'selection-document':
start, end = document.get_bounds()
if output_type == 'replace-selection':
document.select_r... | elif input_type == 'selection' or input_type == 'selection-document': | random_line_split |
functions.py | General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNE... | action, window, panel, node):
if node.save_files == 'document' and window.get_active_document():
MultipleDocumentsSaver(window, panel, [window.get_active_document()], node)
return
elif node.save_files == 'all':
MultipleDocumentsSaver(window, panel, window.get_documents(), node)
r... | apture_menu_action( | identifier_name |
functions.py | General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNE... | capture.connect('stdout-line', capture_stdout_line_document, document, pos)
elif output_type != 'nothing':
capture.connect('stdout-line', capture_stdout_line_panel, panel)
document.begin_user_action()
capture.connect('stderr-line', capture_stderr_line_panel, panel)
capture.connect('... | os = document.get_end_iter()
| conditional_block |
main.rs | mod common;
mod color;
mod math;
mod ppm;
mod renderer;
mod shade_record;
mod shape;
mod tracer;
mod view_plane;
mod world;
use std::cell::RefCell;
use std::rc::Rc;
use color::RGBColor;
use renderer::Renderer;
use tracer::{Tracer, MultipleObjects};
use view_plane::ViewPlane;
use world::World;
fn | () {
let mut view_plane = ViewPlane::new(300, 300, 1.0, 1.0, RGBColor::new(0.5 , 0.5, 0.5));
let world = Rc::new(RefCell::new(World::new()));
let tracer = Box::new(MultipleObjects::new(world.clone())) as Box<Tracer>;
let renderer = Renderer::new(tracer);
world.borrow().build();
renderer.render_... | main | identifier_name |
main.rs | mod common;
mod color;
mod math;
mod ppm;
mod renderer;
mod shade_record;
mod shape;
mod tracer;
mod view_plane;
mod world;
use std::cell::RefCell;
use std::rc::Rc;
use color::RGBColor;
use renderer::Renderer;
use tracer::{Tracer, MultipleObjects};
use view_plane::ViewPlane;
use world::World;
fn main() | {
let mut view_plane = ViewPlane::new(300, 300, 1.0, 1.0, RGBColor::new(0.5 , 0.5, 0.5));
let world = Rc::new(RefCell::new(World::new()));
let tracer = Box::new(MultipleObjects::new(world.clone())) as Box<Tracer>;
let renderer = Renderer::new(tracer);
world.borrow().build();
renderer.render_wor... | identifier_body | |
main.rs | mod common;
mod color;
mod math;
mod ppm;
mod renderer;
mod shade_record;
mod shape;
mod tracer; | use std::rc::Rc;
use color::RGBColor;
use renderer::Renderer;
use tracer::{Tracer, MultipleObjects};
use view_plane::ViewPlane;
use world::World;
fn main() {
let mut view_plane = ViewPlane::new(300, 300, 1.0, 1.0, RGBColor::new(0.5 , 0.5, 0.5));
let world = Rc::new(RefCell::new(World::new()));
let tracer =... | mod view_plane;
mod world;
use std::cell::RefCell; | random_line_split |
test.py | import time
import os
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
testdir = os.path.dirname(os.path.abspath(__file__))
chrome_options.add_argument('nwapp=' + testdir)
driver = webdriver.Chrome(executable_path=os.environ['CHROMEDRIVER'], chrome_optio... | raise Exception('Timeout when waiting for element' + elem_id)
assert('onRequest' in ret2)
assert('onRequest' in ret1)
finally:
driver.quit() | random_line_split | |
test.py | import time
import os
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
testdir = os.path.dirname(os.path.abspath(__file__))
chrome_options.add_argument('nwapp=' + testdir)
driver = webdriver.Chrome(executable_path=os.environ['CHROMEDRIVER'], chrome_optio... |
assert('onRequest' in ret2)
assert('onRequest' in ret1)
finally:
driver.quit()
| try:
ret2 = driver.find_element_by_id('request2').get_attribute('innerHTML')
ret1 = driver.find_element_by_id('request1').get_attribute('innerHTML')
if (ret2 != ''):
print 'show webview delayed value'
print ret2
print 'show request norm... | conditional_block |
daq_device_info.py | from __future__ import absolute_import, division, print_function
from builtins import * # @UnusedWildImport
from mcculw import ul
from mcculw.ul import ULError
from mcculw.enums import (BoardInfo, InfoType, ErrorCode, EventType,
ExpansionInfo)
from .ai_info import AiInfo
from .ao_info import... | return self._ctr_info.is_supported
def get_ctr_info(self): # -> CtrInfo
return self._ctr_info
@property
def supports_daq_input(self): # -> boolean
return self._daqi_info.is_supported
def get_daqi_info(self): # -> DaqiInfo
return self._daqi_info
@property
de... | return self._ao_info
@property
def supports_counters(self): # -> boolean | random_line_split |
daq_device_info.py | from __future__ import absolute_import, division, print_function
from builtins import * # @UnusedWildImport
from mcculw import ul
from mcculw.ul import ULError
from mcculw.enums import (BoardInfo, InfoType, ErrorCode, EventType,
ExpansionInfo)
from .ai_info import AiInfo
from .ao_info import... |
self._ai_info = AiInfo(self._board_num)
self._ao_info = AoInfo(self._board_num)
self._ctr_info = CtrInfo(self._board_num)
self._daqi_info = DaqiInfo(self._board_num)
self._daqo_info = DaqoInfo(self._board_num)
self._dio_info = DioInfo(self._board_num)
@property
... | raise ULError(ErrorCode.BADBOARD) | conditional_block |
daq_device_info.py | from __future__ import absolute_import, division, print_function
from builtins import * # @UnusedWildImport
from mcculw import ul
from mcculw.ul import ULError
from mcculw.enums import (BoardInfo, InfoType, ErrorCode, EventType,
ExpansionInfo)
from .ai_info import AiInfo
from .ao_info import... | (self): # -> int
return ul.get_config(InfoType.BOARDINFO, self.board_num, 0,
BoardInfo.NUMEXPS)
@property
def exp_info(self): # -> list[ExpInfo]
exp_info = []
for expansion_num in range(self.num_expansions):
exp_info.append(ExpInfo(self._board_... | num_expansions | identifier_name |
daq_device_info.py | from __future__ import absolute_import, division, print_function
from builtins import * # @UnusedWildImport
from mcculw import ul
from mcculw.ul import ULError
from mcculw.enums import (BoardInfo, InfoType, ErrorCode, EventType,
ExpansionInfo)
from .ai_info import AiInfo
from .ao_info import... |
def get_daqi_info(self): # -> DaqiInfo
return self._daqi_info
@property
def supports_daq_output(self): # -> boolean
return self._daqo_info.is_supported
def get_daqo_info(self): # -> DaqoInfo
return self._daqo_info
@property
def supports_digital_io(self): # -> boo... | return self._daqi_info.is_supported | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.