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 |
|---|---|---|---|---|
conf.py | # -*- coding: utf-8 -*-
#
# python-keystoneclient documentation build configuration file, created by
# sphinx-quickstart on Sun Dec 6 14:19:25 2009.
#
# This file is execfile()d with the current directory set to its containing
# dir.
#
# Note that not all possible configuration values are present in this
# autogenerat... | # List of tuples 'sourcefile', 'target', 'title', 'Authors name', 'manual'
man_pages = [
('man/keystone', 'keystone', 'Client for OpenStack Identity API',
['OpenStack Contributors'], 1),
]
# -- Options for HTML output --------------------------------------------------
# The theme to use for HTML and HTML He... | #modindex_common_prefix = []
# Grouping the document tree for man pages. | random_line_split |
lib.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/. */ | #![feature(io)]
#![feature(rustc_private)]
#![feature(std_misc)]
#![allow(missing_copy_implementations)]
#[macro_use]
extern crate log;
extern crate azure;
extern crate devtools_traits;
extern crate geom;
extern crate gfx;
extern crate layers;
extern crate layout_traits;
extern crate png;
extern crate script_traits;... |
#![feature(box_syntax)]
#![feature(core)]
#![feature(int_uint)] | random_line_split |
request.rs | use error;
use hyper;
use hyper_rustls;
use response;
use std;
use types;
use url;
#[derive(Debug, Clone)]
pub struct Request<'a> {
client: std::sync::Arc<hyper::Client>,
method: types::Method,
url: url::Url<'a>,
headers: hyper::header::Headers,
body: String,
}
impl<'a> Request<'a> {
pub fn new() -> Req... |
pub fn add_header<H>(&mut self, header: H) -> &mut Request<'a>
where H: hyper::header::Header + hyper::header::HeaderFormat
{
self.headers.set(header);
self
}
pub fn add_path<S>(&mut self, path: S) -> &mut Request<'a>
where S: Into<String>
{
self.url.add_path(path.into());
self
... | {
self.body = body.into();
self
} | identifier_body |
request.rs | use error;
use hyper;
use hyper_rustls;
use response;
use std;
use types;
use url;
#[derive(Debug, Clone)]
pub struct Request<'a> {
client: std::sync::Arc<hyper::Client>,
method: types::Method,
url: url::Url<'a>,
headers: hyper::header::Headers,
body: String,
}
impl<'a> Request<'a> {
pub fn new() -> Req... | <K, S>(&mut self, key: K, val: S) -> &mut Request<'a>
where K: Into<String>,
S: Into<std::borrow::Cow<'a, str>>
{
self.url.add_query_param(key, val);
self
}
pub fn basic_auth<U, P>(&mut self, u: U, p: Option<P>) -> &mut Request<'a>
where U: Into<String>,
P: Into<String>
{
... | add_query_param | identifier_name |
request.rs | use error;
use hyper;
use hyper_rustls;
use response;
use std;
use types;
use url;
#[derive(Debug, Clone)]
pub struct Request<'a> {
client: std::sync::Arc<hyper::Client>,
method: types::Method,
url: url::Url<'a>,
headers: hyper::header::Headers,
body: String,
}
impl<'a> Request<'a> {
pub fn new() -> Req... |
pub fn set_body<S>(&mut self, body: S) -> &mut Request<'a>
where S: Into<String>
{
self.body = body.into();
self
}
pub fn add_header<H>(&mut self, header: H) -> &mut Request<'a>
where H: hyper::header::Header + hyper::header::HeaderFormat
{
self.headers.set(header);
self
}
p... | self.headers = headers;
self
} | random_line_split |
create_project.py | from __future__ import absolute_import
from django import forms
from django.contrib import messages
from django.core.urlresolvers import reverse
from sentry.models import Project, Team
from sentry.web.forms.add_project import AddProjectForm
from sentry.web.frontend.base import OrganizationView
from sentry.utils.http ... | del self.fields['team']
else:
self.fields['team'].choices = (
(t.slug, t.name)
for t in team_list
)
self.fields['team'].widget.choices = self.fields['team'].choices
def clean_team(self):
value = self.cleaned_data['team'... | super(AddProjectWithTeamForm, self).__init__(*args, **kwargs)
self.team_list = team_list
if len(self.team_list) == 1: | random_line_split |
create_project.py | from __future__ import absolute_import
from django import forms
from django.contrib import messages
from django.core.urlresolvers import reverse
from sentry.models import Project, Team
from sentry.web.forms.add_project import AddProjectForm
from sentry.web.frontend.base import OrganizationView
from sentry.utils.http ... |
return None
def save(self, actor, ip_address):
team = self.cleaned_data.get('team', self.team_list[0])
return super(AddProjectWithTeamForm, self).save(actor, team, ip_address)
class CreateProjectView(OrganizationView):
# TODO(dcramer): I'm 95% certain the access is incorrect here as ... | return team | conditional_block |
create_project.py | from __future__ import absolute_import
from django import forms
from django.contrib import messages
from django.core.urlresolvers import reverse
from sentry.models import Project, Team
from sentry.web.forms.add_project import AddProjectForm
from sentry.web.frontend.base import OrganizationView
from sentry.utils.http ... | (AddProjectForm):
team = forms.ChoiceField(
choices=(), required=True,
help_text='The team controls who has access to this project.',
)
class Meta:
fields = ('name', 'team')
model = Project
def __init__(self, user, team_list, *args, **kwargs):
super(AddProjectWi... | AddProjectWithTeamForm | identifier_name |
create_project.py | from __future__ import absolute_import
from django import forms
from django.contrib import messages
from django.core.urlresolvers import reverse
from sentry.models import Project, Team
from sentry.web.forms.add_project import AddProjectForm
from sentry.web.frontend.base import OrganizationView
from sentry.utils.http ... | )
self.fields['team'].widget.choices = self.fields['team'].choices
def clean_team(self):
value = self.cleaned_data['team']
for team in self.team_list:
if value == team.slug:
return team
return None
def save(self, actor, ip_address):
... | team = forms.ChoiceField(
choices=(), required=True,
help_text='The team controls who has access to this project.',
)
class Meta:
fields = ('name', 'team')
model = Project
def __init__(self, user, team_list, *args, **kwargs):
super(AddProjectWithTeamForm, self).__in... | identifier_body |
sql-view.tsx | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ... |
renderResultTable() {
const { result, loading, error } = this.state;
return <ReactTable
data={result ? result.rows : []}
loading={loading}
noDataText={!loading && result && !result.rows.length ? 'No results' : (error || '')}
sortable={false}
columns={
(result ? result.... | {
const {explainDialogOpen, explainResult, loadingExplain, explainError} = this.state;
if (!loadingExplain && explainDialogOpen) {
return <QueryPlanDialog
explainResult={explainResult}
explainError={explainError}
onClose={() => this.setState({explainDialogOpen: false})}
/>;
... | identifier_body |
sql-view.tsx | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ... | else {
const actualQuery = wrapQuery ?
`SELECT * FROM (${queryString.trim().replace(/;+$/, '')}) LIMIT 5000` :
queryString;
const queryPayload: Record<string, any> = {
query: actualQuery,
resultFormat: 'array',
header: true
};
... | {
// Secret way to issue a native JSON "rune" query
const runeQuery = Hjson.parse(queryString);
if (bypassCache) {
runeQuery.context = runeQuery.context || {};
runeQuery.context.useCache = false;
runeQuery.context.populateCache = false;
}
... | conditional_block |
sql-view.tsx | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ... | (): void {
this.sqlQueryManager = new QueryManager({
processQuery: async (queryWithFlags: QueryWithFlags) => {
const { queryString, bypassCache, wrapQuery } = queryWithFlags;
const startTime = new Date();
if (queryString.trim().startsWith('{')) {
// Secret way to issue a nat... | componentDidMount | identifier_name |
sql-view.tsx | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ... | import { QueryPlanDialog } from '../dialogs/query-plan-dialog';
import {
BasicQueryExplanation,
decodeRune,
HeaderRows,
localStorageGet, LocalStorageKeys,
localStorageSet, parseQueryPlan,
queryDruidRune,
queryDruidSql, QueryManager,
SemiJoinQueryExplanation
} from '../utils';
import './sql-view.scss';
... |
import { NullTableCell } from '../components/null-table-cell';
import { SqlControl } from '../components/sql-control'; | random_line_split |
crf.py | .num_classes_padded], values=b_scores
)
e_scores = self.model.param_init_net.GivenTensorFill(
[], "e_scores", shape=[1, self.num_classes_padded], values=e_scores
)
zero_index = self.model.net.ConstantFill(
[], shape=[1, ], value=0
)
length = self.... | new_predictions[i] = predictions[i]
old_best = np.argmax(w_predictions)
old_bests.append(old_best)
# Swap the scores of the current best tag and the tag on the
# Viterbi path
w_predictions[viterbi[i]], w_predictions[old_best] = \
... | conditional_block | |
crf.py | [],
[core.ScopedBlobReference('crf_transitions')],
shape=[self.num_classes_padded, self.num_classes_padded],
min=-1.0,
max=1.0
)
self.transitions = transitions_blob
self.model.params.append(self.transitions)
def crf_loss(s... | return "{}/{}".format(str(scope), str(name))
step_model = model_helper.ModelHelper(name='crf_step',
param_model=self.model)
input_t, cell_t_prev, _ = (
step_model.net.AddExternalInputs(
core.Sc... |
def s(name):
''
# We have to manually scope due to our internal/external blob
# relationships. | random_line_split |
crf.py | self.transitions, core.ScopedBlobReference('transitions_snapshot')
)
# Compute best path unary score from the logits
path_unary_score = self._gather_entries_sum(
predictions, labels, self.num_classes
)
# Append BOS and EOS entries to the predictions and la... | def __init__(self, model, num_classes, transitions_blob=None):
self.model = model
self.num_classes = num_classes
self.num_classes_padded = num_classes + 2 # After adding BOS and EOS
if not transitions_blob:
transitions_blob = self.model.param_init_net.UniformFill(
... | identifier_body | |
crf.py | [],
[core.ScopedBlobReference('crf_transitions')],
shape=[self.num_classes_padded, self.num_classes_padded],
min=-1.0,
max=1.0
)
self.transitions = transitions_blob
self.model.params.append(self.transitions)
def crf_loss(s... | (self, labels):
bos_i = self.num_classes
eos_i = self.num_classes + 1
bos_i_b = self.model.param_init_net.ConstantFill(
[], shape=[1], value=bos_i
)
eos_i_b = self.model.param_init_net.ConstantFill(
[], shape=[1], value=eos_i
)
labels = sel... | _pad_labels | identifier_name |
urls.py | # Copyright 2010 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
from django.conf.urls import patterns, url
from piston.authentication import HttpBasicAuthentication
from piston.resource import Resource
from identityprovider.auth import (
... | )
v10accounts = Resource(
handler=v10.AccountsHandler,
authentication=SSOOAuthAuthentication()
)
v11root = Resource(handler=v11.RootHandler)
v11auth = Resource(
handler=v11.AuthenticationHandler,
authentication=HttpBasicAuthentication(auth_func=basic_authenticate)
)
v2accounts = Resource(
handle... | handler=v10.AuthenticationHandler,
authentication=HttpBasicAuthentication(auth_func=basic_authenticate) | random_line_split |
mod.rs | //! Public-key authenticated encryption
//!
//! # Security model
//! The `seal()` function is designed to meet the standard notions of privacy and | //! encryption in the public-key setting: security notions and analyses,"
//! http://eprint.iacr.org/2001/079.
//!
//! Distinct messages between the same {sender, receiver} set are required
//! to have distinct nonces. For example, the lexicographically smaller
//! public key can use nonce 1 for its first message to th... | //! third-party unforgeability for a public-key authenticated-encryption scheme
//! using nonces. For formal definitions see, e.g., Jee Hea An, "Authenticated | random_line_split |
yanntricksKScolorD.py | from yanntricks import *
def | ():
pspict,fig = SinglePicture("KScolorD")
pspict.dilatation(1)
x=var('x')
C=Circle(Point(0,0),1)
N1=C.graph(90,180)
N2=C.graph(270,360)
C.parameters.color="blue"
N1.parameters.color="black"
N2.parameters.color=N1.parameters.color
N1.wave(0.1,0.2)
#N2.wave(0.1,0.2)
N=Po... | KScolorD | identifier_name |
yanntricksKScolorD.py | from yanntricks import *
def KScolorD():
| fig.write_the_file()
| pspict,fig = SinglePicture("KScolorD")
pspict.dilatation(1)
x=var('x')
C=Circle(Point(0,0),1)
N1=C.graph(90,180)
N2=C.graph(270,360)
C.parameters.color="blue"
N1.parameters.color="black"
N2.parameters.color=N1.parameters.color
N1.wave(0.1,0.2)
#N2.wave(0.1,0.2)
N=Point(0,1)... | identifier_body |
yanntricksKScolorD.py | from yanntricks import *
def KScolorD(): | C=Circle(Point(0,0),1)
N1=C.graph(90,180)
N2=C.graph(270,360)
C.parameters.color="blue"
N1.parameters.color="black"
N2.parameters.color=N1.parameters.color
N1.wave(0.1,0.2)
#N2.wave(0.1,0.2)
N=Point(0,1)
S=Point(0,-1)
pspict.axes.no_graduation()
pspict.DrawGraphs(C,N1,N... | pspict,fig = SinglePicture("KScolorD")
pspict.dilatation(1)
x=var('x') | random_line_split |
ProjectPermissionscheme.ts | import {baseResource} from './baseResource';
/**
* ProjectPermissionscheme Resource for associating permission schemes and projects.
*
* @constructor ProjectPermissionscheme
* @property {IConnector} connector the jira connector instance
*/
export class ProjectPermissionscheme extends baseResource {
construc... | * @param {Object} options An object containing options to pass to the Jira API.
* @param {string} options.projectKeyOrId projectKeyOrId
* @param {string} options.expand expand
* @param {string} options.token token The token to use for authentication. This token is supplied on a sucessful login. If... | * @memberOf ProjectPermissionscheme# | random_line_split |
ProjectPermissionscheme.ts | import {baseResource} from './baseResource';
/**
* ProjectPermissionscheme Resource for associating permission schemes and projects.
*
* @constructor ProjectPermissionscheme
* @property {IConnector} connector the jira connector instance
*/
export class ProjectPermissionscheme extends baseResource {
construc... |
let callback = ((typeof args[args.length - 1]) === 'function') ? args.pop() : null;
let options = ((typeof args[0]) === 'object') ? args[0] : {}
return this.makeRequest('getAssignedPermissionScheme','GET','rest/api/2/project/:projectKeyOrId/permissionscheme',options,callback)
};
}
| {
throw new Error("options must be passed");
} | conditional_block |
ProjectPermissionscheme.ts | import {baseResource} from './baseResource';
/**
* ProjectPermissionscheme Resource for associating permission schemes and projects.
*
* @constructor ProjectPermissionscheme
* @property {IConnector} connector the jira connector instance
*/
export class | extends baseResource {
constructor (connector:IConnector,Model:any,settings:any) {
super(connector,Model,settings);
this.methods = [];
this.register();
}
/**
* Assigns a permission scheme with a project.
*
* @method assignPermissionScheme
* @memberOf Proje... | ProjectPermissionscheme | identifier_name |
test_wind_dir.py | # Simple example of reading the MCP3008 analog input channels and printing
import time
import sys
import numpy as np
# Import SPI library (for hardware SPI) and MCP3008 library.
import Adafruit_GPIO.SPI as SPI
import Adafruit_MCP3008
import RPi.GPIO as GPIO
import spidev
# Software SPI configuration:
#CLK = 18
#MIS... | ledPin = 18
GPIO.setmode(GPIO.BCM)
GPIO.setup(ledPin,GPIO.OUT)
samplingTime = 280.0
deltaTime = 40.0
sleepTime = 9680.0
directions = {'N':3.84,'NNE':1.98,'NE':2.25,'ENE':0.41,'E':0.45,'ESE':0.32,'SE':0.90,'SSE':0.62,'S':1.40,'SSW':1.19,'SW':3.08,'WSW':2.93,'W':4.62,'WNW':4.04,'NW':4.78,'NNW':3.43}
directions = dict... |
# choose GPIO pin | random_line_split |
test_wind_dir.py | # Simple example of reading the MCP3008 analog input channels and printing
import time
import sys
import numpy as np
# Import SPI library (for hardware SPI) and MCP3008 library.
import Adafruit_GPIO.SPI as SPI
import Adafruit_MCP3008
import RPi.GPIO as GPIO
import spidev
# Software SPI configuration:
#CLK = 18
#MIS... |
elif c > b and c < en:
direction = sortd[i]
break
#dustDensity = 0.17*calcVoltage-0.1
#if dustDensity < 0:
# dustDensity = 0.00
# Print the ADC values.
print "Raw signal value (0 - 1023): ", voMeasured
... | direction = 4.78
break | conditional_block |
build_binaries.py | (object):
def __init__(self, tags):
self.tags = tags
self.dirty = False
self.board_list = board_list.BoardList()
def progress(self, string):
'''pretty-print progress'''
print("BB: %s" % string)
def run_git(self, args):
'''run git with args git_args; returns ... | build_binaries | identifier_name | |
build_binaries.py | based on ctag - for examplle, if the board is avr and ctag
is bob we will attempt to checkout bob-AVR'''
if self.dirty:
self.progress("Skipping checkout for dirty build")
return True
self.progress("Trying checkout %s %s %s %s" %
(vehicle, ctag, cboard, cfr... | with open(filepath, "a"):
pass | conditional_block | |
build_binaries.py |
class build_binaries(object):
def __init__(self, tags):
self.tags = tags
self.dirty = False
self.board_list = board_list.BoardList()
def progress(self, string):
'''pretty-print progress'''
print("BB: %s" % string)
def run_git(self, args):
'''run git with ... | '''return required compiler for a build tag.
return format is the version string that waf configure will detect.
You should setup a link from this name in $HOME/arm-gcc directory pointing at the
appropriate compiler
'''
if not is_chibios_build(board):
# only override compiler for Ch... | identifier_body | |
build_binaries.py | tdir)
def touch_filepath(self, filepath):
'''creates a file at filepath, or updates the timestamp on filepath'''
if os.path.exists(filepath):
os.utime(filepath, None)
else:
with open(filepath, "a"):
pass
def build_vehicle(self, tag, vehicle, boa... | shutil.move(new_json_filepath_gz, json_filepath_gz)
self.progress("Manifest generation successful")
self.progress("Generating stable releases")
gen_stable.make_all_stable(self.binaries) | random_line_split | |
main.rs | //parser created by Ivan Temchenko <ivan.temchenko@yandex.ua>, 2015
extern crate csv;
use std::collections::HashSet;
use std::fs::{File, OpenOptions};
use std::io::{BufWriter, Write};
use std::path::Path;
struct All {
y0: Vec<Vec<String>>,
y1: Vec<Vec<String>>,
y2: Vec<Vec<String>>,
y3: Vec<Vec<String>>,
y4: Ve... | uniq.p0 = find_uniq(all.y0);
println!("15% done..");
uniq.p1 = find_uniq(all.y1);
println!("30% done..");
uniq.p2 = find_uniq(all.y2);
println!("45% done..");
uniq.p3 = find_uniq(all.y3);
println!("60% done..");
uniq.p4 = find_uniq(all.y4);
println!("75% done..");
uniq.p5 = find_uniq(all.y5);
println!("90% ... | {
let mut all = All {y0: vec![], y1: vec![], y2: vec![], y3: vec![], y4: vec![], y5: vec![], y6: vec![], els: vec![]};
let mut uniq = Uniq {p0: vec![], p1: vec![], p2: vec![], p3: vec![], p4: vec![], p5: vec![], p6: vec![]};
let mut train = csv::Reader::from_file("./data/train.csv").unwrap();
for train_record in t... | identifier_body |
main.rs | //parser created by Ivan Temchenko <ivan.temchenko@yandex.ua>, 2015
extern crate csv;
use std::collections::HashSet;
use std::fs::{File, OpenOptions};
use std::io::{BufWriter, Write};
use std::path::Path;
struct All {
y0: Vec<Vec<String>>,
y1: Vec<Vec<String>>,
y2: Vec<Vec<String>>,
y3: Vec<Vec<String>>,
y4: Ve... | (v: Vec<Vec<String>>) -> Vec<String> {
v.into_iter().flat_map(|v| v).collect::<HashSet<String>>().into_iter().collect()
}
fn write_to_file(s: String) {
let path = Path::new("./data/sol.csv");
let mut options = OpenOptions::new();
options.write(true).append(true);
let file = match options.open(&path) {
Ok(fil... | find_uniq | identifier_name |
main.rs | //parser created by Ivan Temchenko <ivan.temchenko@yandex.ua>, 2015
extern crate csv;
use std::collections::HashSet;
use std::fs::{File, OpenOptions};
use std::io::{BufWriter, Write};
use std::path::Path;
struct All {
y0: Vec<Vec<String>>,
y1: Vec<Vec<String>>,
y2: Vec<Vec<String>>,
y3: Vec<Vec<String>>,
y4: Ve... | p5: Vec<String>,
p6: Vec<String>,
}
struct RCounter {
c0: i32,
c1: i32,
c2: i32,
c3: i32,
c4: i32,
c5: i32,
c6: i32,
}
fn main() {
let mut all = All {y0: vec![], y1: vec![], y2: vec![], y3: vec![], y4: vec![], y5: vec![], y6: vec![], els: vec![]};
let mut uniq = Uniq {p0: vec![], p1: vec![], p2: vec![], p3... | p2: Vec<String>,
p3: Vec<String>,
p4: Vec<String>, | random_line_split |
main.rs | //parser created by Ivan Temchenko <ivan.temchenko@yandex.ua>, 2015
extern crate csv;
use std::collections::HashSet;
use std::fs::{File, OpenOptions};
use std::io::{BufWriter, Write};
use std::path::Path;
struct All {
y0: Vec<Vec<String>>,
y1: Vec<Vec<String>>,
y2: Vec<Vec<String>>,
y3: Vec<Vec<String>>,
y4: Ve... |
}
for u in &uniq.p4 {
if test_string == &u.to_string() {
rate.c4 += 1;
}
}
for u in &uniq.p5 {
if test_string == &u.to_string() {
rate.c5 += 1;
}
}
for u in &uniq.p6 {
if test_string == &u.to_string() {
rate.c6 += 1;
}
}
}
let mut decisi... | {
rate.c3 += 1;
} | conditional_block |
vEQ_benchmark.py |
vlc_verbosity = -1
default_youtube_quality= 'bestvideo'
benchmark_duration = 20#or -1 for length of video
meter = None
default_folder= makeDefaultDBFolder()
default_database = os.path.join( default_folder, "vEQ_db.sqlite")
logging.getLogger().setLevel(logging.DEBUG)
def main(argv=None):
parser = argparse.Argum... | home = expanduser("~")
print home
video_download_folder = os.path.join(home, "vEQ-benchmark")
if not os.path.exists(video_download_folder):
os.makedirs(video_download_folder)
return video_download_folder | identifier_body | |
vEQ_benchmark.py | (argv=None):
parser = argparse.ArgumentParser(description="vEQ-benchmark: A Benchmarking and Measurement Tool for Video")
parser.add_argument("video" , metavar="VIDEO", help="A local file or URL(Youtube, Vimeo etc.) for the video to be benchmarked")
parser.add_argument("-y", "--youtube-format", metavar="for... | main | identifier_name | |
vEQ_benchmark.py | the plot of this should be displayed on the screen after a session is completed")
parser.add_argument("-p", "--player", metavar="player", dest="system_player", default="libvlc", help="The Player to use to playback video - default is VLC MediaPlayer")
parser.add_argument("--hwdecode", dest="hw_decode", action='... | video_title = s = re.sub(r"[^\w\s]", '', video_title)
except: | random_line_split | |
vEQ_benchmark.py | ("video" , metavar="VIDEO", help="A local file or URL(Youtube, Vimeo etc.) for the video to be benchmarked")
parser.add_argument("-y", "--youtube-format", metavar="format", dest="youtube_quality", default=default_youtube_quality, help="For Youtube videos, a value that corressponds to the quality level see youtube-d... |
vEQPlayback = VLCPlayback(video,vEQdb,vlc_args,meter)
logging.debug("Starting Playback with VLC")
vEQPlayback.startPlayback(benchmark_duration)
else:
# use subprocess to start video player and montioring!
# GenericPlaybackObject.startPlayback(benchmarkduration... | vlc_args = vlc_args + "--avcodec-hw=any" | conditional_block |
simple_form_control_spec.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {verifyNoBrowserErrors} from '../../../../_common/e2e_util';
describe('simpleFormControl example', () => {
... | input.click();
input.sendKeys('s!');
expect(valueP.getText()).toEqual('Value: values!');
});
it('should show the correct validity state', () => {
expect(statusP.getText()).toEqual('Validation status: VALID');
input.click();
input.clear();
input.sendKeys('a');
e... | });
it('should update the value as user types', () => { | random_line_split |
blog.tsx | // import { GetServerSideProps } from 'next'
import { Provider } from 'mobx-react'
import { METRIC, THREAD } from '@/constant'
import {
articlePublishSEO,
ssrFetchPrepare,
ssrBaseStates,
refreshIfneed,
ssrError,
} from '@/utils'
import { useStore } from '@/stores/init'
import GlobalLayout from '@/containers... | >
<BlogEditor />
</GlobalLayout>
</Provider>
)
}
export default CreateBlogPage | noSidebar | random_line_split |
utils.ts | import { PASSIVE_EVENTS } from "../dom/feature_detection";
/* istanbul ignore next */
/**
* getEventTarget retrieves target element from an event.
*
* There are still some differences in modern browsers, so we need to use this function to retrieve event targets.
*
* #quirks
*
* @param ev Event.
* @returns Targ... | (ev: Event): EventTarget {
let target = ev.target || window;
/**
* Some browsers are implementing it according to SVG 1.1 specs:
*
* https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/7998724/
*
* "If event attributes are assigned to referenced elements, then the actual target for ... | getEventTarget | identifier_name |
utils.ts | import { PASSIVE_EVENTS } from "../dom/feature_detection";
/* istanbul ignore next */
/**
* getEventTarget retrieves target element from an event.
*
* There are still some differences in modern browsers, so we need to use this function to retrieve event targets.
*
* #quirks
*
* @param ev Event.
* @returns Targ... | */
if ((target as any).correspondingUseElement !== void 0) {
target = (target as any).correspondingUseElement;
}
return target;
}
/*
istanbul ignore next */
/**
* `{ capture: true, passive: true }` object that should be used as a 3rd parameter for `addEventListener` method.
*/
export const EVENT_CAPTU... | {
let target = ev.target || window;
/**
* Some browsers are implementing it according to SVG 1.1 specs:
*
* https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/7998724/
*
* "If event attributes are assigned to referenced elements, then the actual target for the event will be the
... | identifier_body |
utils.ts | import { PASSIVE_EVENTS } from "../dom/feature_detection";
/* istanbul ignore next */
/**
* getEventTarget retrieves target element from an event.
*
* There are still some differences in modern browsers, so we need to use this function to retrieve event targets.
*
* #quirks
*
* @param ev Event.
* @returns Targ... | *
* https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/7998724/
*
* "If event attributes are assigned to referenced elements, then the actual target for the event will be the
* SVGElementInstance object within the 'instance tree' corresponding to the given referenced element."
*
*... | random_line_split | |
utils.ts | import { PASSIVE_EVENTS } from "../dom/feature_detection";
/* istanbul ignore next */
/**
* getEventTarget retrieves target element from an event.
*
* There are still some differences in modern browsers, so we need to use this function to retrieve event targets.
*
* #quirks
*
* @param ev Event.
* @returns Targ... | return target;
}
/* istanbul ignore next */
/**
* `{ capture: true, passive: true }` object that should be used as a 3rd parameter for `addEventListener` method.
*/
export const EVENT_CAPTURE_PASSIVE_OPTIONS = PASSIVE_EVENTS ? { "capture": true, "passive": true } : true;
/* istanbul ignore next */
/**
* `{ capture... | target = (target as any).correspondingUseElement;
}
| conditional_block |
rwlock.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self) -> bool {
ffi::pthread_rwlock_trywrlock(self.inner.get()) == 0
}
#[inline]
pub unsafe fn read_unlock(&self) {
let r = ffi::pthread_rwlock_unlock(self.inner.get());
debug_assert_eq!(r, 0);
}
#[inline]
pub unsafe fn write_unlock(&self) { self.read_unlock() }
#[i... | try_write | identifier_name |
rwlock.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
#[inline]
pub unsafe fn destroy(&self) {
let r = ffi::pthread_rwlock_destroy(self.inner.get());
debug_assert_eq!(r, 0);
}
}
| { self.read_unlock() } | identifier_body |
rwlock.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | pub unsafe fn read(&self) {
let r = ffi::pthread_rwlock_rdlock(self.inner.get());
debug_assert_eq!(r, 0);
}
#[inline]
pub unsafe fn try_read(&self) -> bool {
ffi::pthread_rwlock_tryrdlock(self.inner.get()) == 0
}
#[inline]
pub unsafe fn write(&self) {
let r = ... | // Might be moved and address is changing it is better to avoid
// initialization of potentially opaque OS data before it landed
RWLOCK_INIT
}
#[inline] | random_line_split |
fields.py | import json
from django.db import models
from django.conf import settings
from django.utils.six import with_metaclass, text_type
from django.utils.translation import ugettext_lazy as _
from . import SirTrevorContent
from .forms import SirTrevorFormField
class SirTrevorField(with_metaclass(models.SubfieldBase, models.... |
if 'south' in settings.INSTALLED_APPS:
from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^sirtrevor\.fields\.SirTrevorField"])
| return text_type(value) | identifier_body |
fields.py | import json
from django.db import models
from django.conf import settings
from django.utils.six import with_metaclass, text_type
from django.utils.translation import ugettext_lazy as _
from . import SirTrevorContent
from .forms import SirTrevorFormField
class SirTrevorField(with_metaclass(models.SubfieldBase, models.... | (self):
return 'TextField'
def formfield(self, **kwargs):
defaults = {
'form_class': SirTrevorFormField
}
defaults.update(kwargs)
return super(SirTrevorField, self).formfield(**defaults)
def to_python(self, value):
return SirTrevorContent(value)
... | get_internal_type | identifier_name |
fields.py | import json
from django.db import models
from django.conf import settings
from django.utils.six import with_metaclass, text_type
from django.utils.translation import ugettext_lazy as _
from . import SirTrevorContent
from .forms import SirTrevorFormField
class SirTrevorField(with_metaclass(models.SubfieldBase, models.... | return super(SirTrevorField, self).formfield(**defaults)
def to_python(self, value):
return SirTrevorContent(value)
def get_db_prep_value(self, value, connection, prepared=False):
return text_type(value)
if 'south' in settings.INSTALLED_APPS:
from south.modelsinspector import add_... | 'form_class': SirTrevorFormField
}
defaults.update(kwargs) | random_line_split |
fields.py | import json
from django.db import models
from django.conf import settings
from django.utils.six import with_metaclass, text_type
from django.utils.translation import ugettext_lazy as _
from . import SirTrevorContent
from .forms import SirTrevorFormField
class SirTrevorField(with_metaclass(models.SubfieldBase, models.... | from south.modelsinspector import add_introspection_rules
add_introspection_rules([], ["^sirtrevor\.fields\.SirTrevorField"]) | conditional_block | |
view.py | # Webhooks for external integrations.
from typing import Any, Dict, List, Mapping
from django.http import HttpRequest, HttpResponse
from zerver.decorator import webhook_view
from zerver.lib.request import REQ, has_request_variables
from zerver.lib.response import json_success
from zerver.lib.webhooks.common import c... |
else:
quality_gate_status = "error"
conditions = payload["qualityGate"]["conditions"]
conditions = parse_conditions(conditions)
if not conditions:
return MESSAGE_WITHOUT_BRANCH_AND_CONDITIONS.format(
project_name, project_url, quality_gate_status
)
msg = MESSAGE... | quality_gate_status = "success" | conditional_block |
view.py | # Webhooks for external integrations.
from typing import Any, Dict, List, Mapping
from django.http import HttpRequest, HttpResponse
from zerver.decorator import webhook_view
from zerver.lib.request import REQ, has_request_variables
from zerver.lib.response import json_success
from zerver.lib.webhooks.common import c... | if branch:
topic = TOPIC_WITH_BRANCH.format(project, branch)
message = render_body_with_branch(payload)
else:
topic = project
message = render_body_without_branch(payload)
check_send_webhook_message(request, user_profile, topic, message)
return json_success() | if "branch" in payload.keys():
branch = payload["branch"].get("name", None) | random_line_split |
view.py | # Webhooks for external integrations.
from typing import Any, Dict, List, Mapping
from django.http import HttpRequest, HttpResponse
from zerver.decorator import webhook_view
from zerver.lib.request import REQ, has_request_variables
from zerver.lib.response import json_success
from zerver.lib.webhooks.common import c... | (conditions: List[Mapping[str, Any]]) -> str:
return "\n".join(
[
parse_condition(condition)
for condition in conditions
if condition["status"].lower() != "ok" and condition["status"].lower() != "no_value"
]
)
def render_body_with_branch(payload: Mapping[str... | parse_conditions | identifier_name |
view.py | # Webhooks for external integrations.
from typing import Any, Dict, List, Mapping
from django.http import HttpRequest, HttpResponse
from zerver.decorator import webhook_view
from zerver.lib.request import REQ, has_request_variables
from zerver.lib.response import json_success
from zerver.lib.webhooks.common import c... |
@webhook_view("Sonarqube")
@has_request_variables
def api_sonarqube_webhook(
request: HttpRequest,
user_profile: UserProfile,
payload: Dict[str, Any] = REQ(argument_type="body"),
) -> HttpResponse:
project = payload["project"]["name"]
branch = None
if "branch" in payload.keys():
branc... | project_name = payload["project"]["name"]
project_url = payload["project"]["url"]
quality_gate_status = payload["qualityGate"]["status"].lower()
if quality_gate_status == "ok":
quality_gate_status = "success"
else:
quality_gate_status = "error"
conditions = payload["qualityGate"]["co... | identifier_body |
viewport.rs | // This file is part of rgtk.
//
// rgtk 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 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... | self) -> gtk::ShadowType {
unsafe {
ffi::gtk_viewport_get_shadow_type(GTK_VIEWPORT(self.pointer))
}
}
pub fn set_shadow_type(&mut self, ty: gtk::ShadowType) {
unsafe {
ffi::gtk_viewport_set_shadow_type(GTK_VIEWPORT(self.pointer), ty)
}
}
}
impl_drop!... | t_shadow_type(& | identifier_name |
viewport.rs | // This file is part of rgtk.
//
// rgtk 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 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser Gener... | random_line_split | |
viewport.rs | // This file is part of rgtk.
//
// rgtk 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 3 of the License, or
// (at your option) any later version.
//
// rgtk is distributed in the hop... |
impl_drop!(Viewport);
impl_TraitWidget!(Viewport);
impl gtk::ContainerTrait for Viewport {}
impl gtk::BinTrait for Viewport {}
impl gtk::ScrollableTrait for Viewport {}
impl_widget_events!(Viewport);
| unsafe {
ffi::gtk_viewport_set_shadow_type(GTK_VIEWPORT(self.pointer), ty)
}
}
} | identifier_body |
corpus.py | # -*- coding: utf-8 -*-
# Copyright (C) 2010 Samalyse SARL
# Copyright (C) 2010-2014 Parisson SARL
# This file is part of Telemeta.
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, eithe... |
return False
def computed_duration(self):
duration = Duration()
for child in self.children.all():
duration += child.computed_duration()
return duration
computed_duration.verbose_name = _('total available duration')
class Meta(MetaCore):
db_table = 'medi... | if child.has_mediafile:
return True | conditional_block |
corpus.py | # -*- coding: utf-8 -*-
# Copyright (C) 2010 Samalyse SARL
# Copyright (C) 2010-2014 Parisson SARL
# This file is part of Telemeta.
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, eithe... | from __future__ import division
from django.utils.translation import ugettext_lazy as _
from telemeta.models.core import *
from telemeta.models.resource import *
from telemeta.models.collection import *
class MediaCorpus(MediaBaseResource):
"Describe a corpus"
element_type = 'corpus'
children_type = 'col... | random_line_split | |
corpus.py | # -*- coding: utf-8 -*-
# Copyright (C) 2010 Samalyse SARL
# Copyright (C) 2010-2014 Parisson SARL
# This file is part of Telemeta.
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, eithe... | (MetaCore):
db_table = 'media_corpus_related'
verbose_name = _('corpus related media')
verbose_name_plural = _('corpus related media')
| Meta | identifier_name |
corpus.py | # -*- coding: utf-8 -*-
# Copyright (C) 2010 Samalyse SARL
# Copyright (C) 2010-2014 Parisson SARL
# This file is part of Telemeta.
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, eithe... | def has_mediafile(self):
for child in self.children.all():
if child.has_mediafile:
return True
return False
def computed_duration(self):
duration = Duration()
for child in self.children.all():
duration += child.computed_duration()
... | "Describe a corpus"
element_type = 'corpus'
children_type = 'collections'
children = models.ManyToManyField(MediaCollection, related_name="corpus",
verbose_name=_('collections'), blank=True)
recorded_from_year = IntegerFi... | identifier_body |
singleton.py | # Taken from here: https://stackoverflow.com/questions/50566934/why-is-this-singleton-implementation-not-thread-safe
import functools
import threading
lock = threading.Lock()
def synchronized(lock):
""" Synchronization decorator """
def wrapper(f):
@functools.wraps(f)
def inner_wrapper(*args... | cls._instances[cls] = super(SingletonOptimized, cls).__call__(*args, **kwargs) | conditional_block | |
singleton.py | # Taken from here: https://stackoverflow.com/questions/50566934/why-is-this-singleton-implementation-not-thread-safe
import functools
import threading
lock = threading.Lock()
def synchronized(lock):
""" Synchronization decorator """
def wrapper(f):
@functools.wraps(f)
def inner_wrapper(*args... |
@synchronized(lock)
def _locked_call(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(SingletonOptimized, cls).__call__(*args, **kwargs) | random_line_split | |
singleton.py | # Taken from here: https://stackoverflow.com/questions/50566934/why-is-this-singleton-implementation-not-thread-safe
import functools
import threading
lock = threading.Lock()
def synchronized(lock):
""" Synchronization decorator """
def wrapper(f):
|
return wrapper
class SingletonOptimized(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._locked_call(*args, **kwargs)
return cls._instances[cls]
@synchronized(lock)
def _locked_call(cls, *args, **kwargs):
if cls not... | @functools.wraps(f)
def inner_wrapper(*args, **kw):
with lock:
return f(*args, **kw)
return inner_wrapper | identifier_body |
singleton.py | # Taken from here: https://stackoverflow.com/questions/50566934/why-is-this-singleton-implementation-not-thread-safe
import functools
import threading
lock = threading.Lock()
def | (lock):
""" Synchronization decorator """
def wrapper(f):
@functools.wraps(f)
def inner_wrapper(*args, **kw):
with lock:
return f(*args, **kw)
return inner_wrapper
return wrapper
class SingletonOptimized(type):
_instances = {}
def __call__(cls, *... | synchronized | identifier_name |
svgsvgelement.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::attr::Attr;
use dom::bindings::codegen::Bindings::SVGSVGElementBinding;
use dom::bindings::inheritance::C... | svggraphicselement:
SVGGraphicsElement::new_inherited(local_name, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(local_name: LocalName,
prefix: Option<DOMString>,
document: &Document) -> Root<SVGSVGElement> {
Node::ref... | prefix: Option<DOMString>,
document: &Document) -> SVGSVGElement {
SVGSVGElement { | random_line_split |
svgsvgelement.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::attr::Attr;
use dom::bindings::codegen::Bindings::SVGSVGElementBinding;
use dom::bindings::inheritance::C... | (local_name: LocalName,
prefix: Option<DOMString>,
document: &Document) -> SVGSVGElement {
SVGSVGElement {
svggraphicselement:
SVGGraphicsElement::new_inherited(local_name, prefix, document)
}
}
#[allow(unrooted_must_root)]
... | new_inherited | identifier_name |
svgsvgelement.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::attr::Attr;
use dom::bindings::codegen::Bindings::SVGSVGElementBinding;
use dom::bindings::inheritance::C... |
fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue {
match name {
&local_name!("width") => AttrValue::from_u32(value.into(), DEFAULT_WIDTH),
&local_name!("height") => AttrValue::from_u32(value.into(), DEFAULT_HEIGHT),
_ => self.super_type()... | {
self.super_type().unwrap().attribute_mutated(attr, mutation);
} | identifier_body |
trait-bounds-impl-comparison-1.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn test_error7_fn<T: A + Eq>(&self) {}
//~^ ERROR the requirement `T : core::cmp::Eq` appears on the impl
fn test_error8_fn<T: C>(&self) {}
//~^ ERROR the requirement `T : C` appears on the impl
}
trait Getter<T> { }
trait Trait {
fn method<G:Getter<isize>>();
}
impl Trait for usize {
fn ... | {} | identifier_body |
trait-bounds-impl-comparison-1.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
impl Foo for isize {
// invalid bound for T, was defined as Eq in trait
fn test_error1_fn<T: Ord>(&self) {}
//~^ ERROR the requirement `T : core::cmp::Ord` appears on the impl
// invalid bound for T, was defined as Eq + Ord in trait
fn test_error2_fn<T: Eq + B>(&self) {}
//~^ ERROR the require... | fn test_error8_fn<T: B>(&self);
} | random_line_split |
trait-bounds-impl-comparison-1.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <T: Ord + Eq>(&self) {}
// multiple bounds, different order as in trait
fn test4_fn<T: Eq + Ord>(&self) {}
// parameters in impls must be equal or more general than in the defining trait
fn test_error5_fn<T: B>(&self) {}
//~^ ERROR the requirement `T : B` appears on the impl
// bound `std::cm... | test3_fn | identifier_name |
admin_script_builder.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use anyhow::Result;
use diem_framework::compile_script;
use diem_types::{
account_address::AccountAddress,
account_config::diem_root_address,
transaction::{Script, WriteSetPayload},
};
use handlebars::Handlebars;
use serde::... | (validators: Vec<AccountAddress>) -> WriteSetPayload {
assert!(!validators.is_empty(), "Unexpected validator set length");
let mut script = template_path();
script.push("remove_validators.move");
let script = {
let mut hb = Handlebars::new();
hb.set_strict_mode(true);
hb.registe... | encode_remove_validators_payload | identifier_name |
admin_script_builder.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use anyhow::Result;
use diem_framework::compile_script;
use diem_types::{
account_address::AccountAddress,
account_config::diem_root_address,
transaction::{Script, WriteSetPayload},
};
use handlebars::Handlebars;
use serde::... |
pub fn template_path() -> PathBuf {
let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
path.push(SCRIPTS_DIR_PATH.to_string());
path
}
pub fn encode_remove_validators_payload(validators: Vec<AccountAddress>) -> WriteSetPayload {
assert!(!validators.is_empty(), "Unexpected validator set length"... | {
let mut temp_file = NamedTempFile::new()?;
temp_file.write_all(input.as_bytes())?;
let cur_path = temp_file.path().to_str().unwrap().to_owned();
Ok(Script::new(compile_script(cur_path), vec![], vec![]))
} | identifier_body |
admin_script_builder.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use anyhow::Result;
use diem_framework::compile_script;
use diem_types::{
account_address::AccountAddress,
account_config::diem_root_address,
transaction::{Script, WriteSetPayload},
};
use handlebars::Handlebars;
use serde::... | ) -> WriteSetPayload {
let mut script = template_path();
script.push(script_name_in_templates);
let script = {
let mut hb = Handlebars::new();
hb.register_template_file("script", script).unwrap();
hb.set_strict_mode(true);
let output = hb.render("script", args).unwrap();
... | execute_as: Option<AccountAddress>, | random_line_split |
res_company.py | # -*- coding: utf-8 -*-
from odoo import api, fields, models, tools
from odoo.exceptions import UserError
import os
from odoo.tools import misc
import re
# 成本计算方法,已实现 先入先出
CORE_COST_METHOD = [('average', u'全月一次加权平均法'),
('std',u'定额成本'),
('fifo', u'先进先出法'),
]
... | res = re.match('^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$', self.email)
if not res:
raise UserError(u'请检查邮箱格式是否正确: %s' % self.email)
start_date = fields.Date(u'启用日期',
required=True,
default=lambda self: field... | random_line_split | |
res_company.py | # -*- coding: utf-8 -*-
from odoo import api, fields, models, tools
from odoo.exceptions import UserError
import os
from odoo.tools import misc
import re
# 成本计算方法,已实现 先入先出
CORE_COST_METHOD = [('average', u'全月一次加权平均法'),
('std',u'定额成本'),
('fifo', u'先进先出法'),
]
... | default=lambda self: fields.Date.context_today(self))
cost_method = fields.Selection(CORE_COST_METHOD, u'存货计价方法',
help=u'''GoodERP仓库模块使用先进先出规则匹配
每次出库对应的入库成本和数量,但不实时记账。
财务月结时使用此方法相应调整发出成本''', def... | .match('^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$', self.email)
if not res:
raise UserError(u'请检查邮箱格式是否正确: %s' % self.email)
start_date = fields.Date(u'启用日期',
required=True,
| identifier_body |
res_company.py | # -*- coding: utf-8 -*-
from odoo import api, fields, models, tools
from odoo.exceptions import UserError
import os
from odoo.tools import misc
import re
# 成本计算方法,已实现 先入先出
CORE_COST_METHOD = [('average', u'全月一次加权平均法'),
('std',u'定额成本'),
('fifo', u'先进先出法'),
]
... | default=_get_logo, attachment=True)
company_id = fields.Many2one(
'res.company',
string=u'公司',
change_default=True,
default=lambda self: self.env['res.company']._company_default_get())
| identifier_name | |
res_company.py | # -*- coding: utf-8 -*-
from odoo import api, fields, models, tools
from odoo.exceptions import UserError
import os
from odoo.tools import misc
import re
# 成本计算方法,已实现 先入先出
CORE_COST_METHOD = [('average', u'全月一次加权平均法'),
('std',u'定额成本'),
('fifo', u'先进先出法'),
]
... | default=lambda self: fields.Date.context_today(self))
cost_method = fields.Selection(CORE_COST_METHOD, u'存货计价方法',
help=u'''GoodERP仓库模块使用先进先出规则匹配
每次出库对应的入库成本和数量,但不实时记账。
财务月结时使用此方法相应调整发出成本''', def... | email)
if not res:
raise UserError(u'请检查邮箱格式是否正确: %s' % self.email)
start_date = fields.Date(u'启用日期',
required=True,
| conditional_block |
cursos.client.controller.test.js | 'use strict'; | // Cursos Controller Spec
describe('Cursos Controller Tests', function() {
// Initialize global variables
var CursosController,
scope,
$httpBackend,
$stateParams,
$location;
// The $resource service augments the response object with methods for updating and deleting the resource.
// If we were to use... |
(function() { | random_line_split |
test_semantic_faster.py | #!/usr/bin/env python
"""Test faster version of sematic similarity"""
from __future__ import print_function
# Computing basic semantic similarities between GO terms
# Adapted from book chapter written by _Alex Warwick Vesztrocy and Christophe Dessimoz_
# How to compute semantic similarity between GO terms.
# First... |
# Compare old and new count
tic = timeit.default_timer()
gocnts_old = _old_init_count_terms(godag_r0, assoc.values())
assert gocnts_old
prt_hms(tic, 'OLD EXPECTED {N:,} TermCounts initialized'.format(N=len(gocnts_old)))
for goid, cnt_old in gocnts_old.items():
assert cnt_old == tcntobj... | for goid, cnt in ns2tcnt[nspc].gocnts.items():
assert tcntobj.gocnts[goid] == cnt | conditional_block |
test_semantic_faster.py | #!/usr/bin/env python
"""Test faster version of sematic similarity"""
from __future__ import print_function
# Computing basic semantic similarities between GO terms
# Adapted from book chapter written by _Alex Warwick Vesztrocy and Christophe Dessimoz_
# How to compute semantic similarity between GO terms.
# First... | ():
"""Test faster version of sematic similarity"""
godag_r0 = get_godag('go-basic.obo')
## godag_r1 = get_godag('go-basic.obo', optional_attrs=['relationship'])
annoobj = GpadReader(get_anno_fullname('goa_human.gpad'), godag=godag_r0)
ns2assoc = annoobj.get_ns2assc()
assoc = annoobj.get_id2gos(... | test_semantic_similarity | identifier_name |
test_semantic_faster.py | #!/usr/bin/env python
"""Test faster version of sematic similarity"""
from __future__ import print_function
# Computing basic semantic similarities between GO terms
# Adapted from book chapter written by _Alex Warwick Vesztrocy and Christophe Dessimoz_
# How to compute semantic similarity between GO terms.
# First... | assert gocnts_old
prt_hms(tic, 'OLD EXPECTED {N:,} TermCounts initialized'.format(N=len(gocnts_old)))
for goid, cnt_old in gocnts_old.items():
assert cnt_old == tcntobj.gocnts[goid]
def _old_init_count_terms(go2obj, annots_values):
'''
Fills in the counts and overall aspect counts.
... | """Test faster version of sematic similarity"""
godag_r0 = get_godag('go-basic.obo')
## godag_r1 = get_godag('go-basic.obo', optional_attrs=['relationship'])
annoobj = GpadReader(get_anno_fullname('goa_human.gpad'), godag=godag_r0)
ns2assoc = annoobj.get_ns2assc()
assoc = annoobj.get_id2gos('all')
... | identifier_body |
test_semantic_faster.py | #!/usr/bin/env python
"""Test faster version of sematic similarity"""
from __future__ import print_function
# Computing basic semantic similarities between GO terms
# Adapted from book chapter written by _Alex Warwick Vesztrocy and Christophe Dessimoz_
# How to compute semantic similarity between GO terms.
# First... | ## godag_r1 = get_godag('go-basic.obo', optional_attrs=['relationship'])
annoobj = GpadReader(get_anno_fullname('goa_human.gpad'), godag=godag_r0)
ns2assoc = annoobj.get_ns2assc()
assoc = annoobj.get_id2gos('all')
# Get TermCounts for each namespace and for all namespaces
ns2tcnt = {ns:TermCoun... | godag_r0 = get_godag('go-basic.obo') | random_line_split |
ring_slices.rs | use core::ptr::{self};
/// Returns the two slices that cover the `VecDeque`'s valid range
pub trait RingSlices: Sized {
fn slice(self, from: usize, to: usize) -> Self;
fn split_at(self, i: usize) -> (Self, Self);
fn ring_slices(buf: Self, head: usize, tail: usize) -> (Self, Self) {
let contiguous ... |
}
}
impl<T> RingSlices for &[T] {
fn slice(self, from: usize, to: usize) -> Self {
&self[from..to]
}
fn split_at(self, i: usize) -> (Self, Self) {
(*self).split_at(i)
}
}
impl<T> RingSlices for &mut [T] {
fn slice(self, from: usize, to: usize) -> Self {
&mut self[from.... | {
let (mid, right) = buf.split_at(tail);
let (left, _) = mid.split_at(head);
(right, left)
} | conditional_block |
ring_slices.rs | use core::ptr::{self};
/// Returns the two slices that cover the `VecDeque`'s valid range
pub trait RingSlices: Sized {
fn slice(self, from: usize, to: usize) -> Self;
fn split_at(self, i: usize) -> (Self, Self);
fn ring_slices(buf: Self, head: usize, tail: usize) -> (Self, Self) {
let contiguous ... | (self, mid: usize) -> (Self, Self) {
let len = self.len();
let ptr = self.as_mut_ptr();
assert!(mid <= len);
(
ptr::slice_from_raw_parts_mut(ptr, mid),
ptr::slice_from_raw_parts_mut(ptr.wrapping_add(mid), len - mid),
)
}
}
| split_at | identifier_name |
ring_slices.rs | use core::ptr::{self};
/// Returns the two slices that cover the `VecDeque`'s valid range
pub trait RingSlices: Sized {
fn slice(self, from: usize, to: usize) -> Self;
fn split_at(self, i: usize) -> (Self, Self);
fn ring_slices(buf: Self, head: usize, tail: usize) -> (Self, Self) {
let contiguous ... | }
impl<T> RingSlices for *mut [T] {
fn slice(self, from: usize, to: usize) -> Self {
assert!(from <= to && to < self.len());
// Not using `get_unchecked_mut` to keep this a safe operation.
let len = to - from;
ptr::slice_from_raw_parts_mut(self.as_mut_ptr().wrapping_add(from), len)
... | random_line_split | |
ring_slices.rs | use core::ptr::{self};
/// Returns the two slices that cover the `VecDeque`'s valid range
pub trait RingSlices: Sized {
fn slice(self, from: usize, to: usize) -> Self;
fn split_at(self, i: usize) -> (Self, Self);
fn ring_slices(buf: Self, head: usize, tail: usize) -> (Self, Self) {
let contiguous ... |
fn split_at(self, mid: usize) -> (Self, Self) {
let len = self.len();
let ptr = self.as_mut_ptr();
assert!(mid <= len);
(
ptr::slice_from_raw_parts_mut(ptr, mid),
ptr::slice_from_raw_parts_mut(ptr.wrapping_add(mid), len - mid),
)
}
}
| {
assert!(from <= to && to < self.len());
// Not using `get_unchecked_mut` to keep this a safe operation.
let len = to - from;
ptr::slice_from_raw_parts_mut(self.as_mut_ptr().wrapping_add(from), len)
} | identifier_body |
write_ogr.rs | extern crate gdal;
use std::path::Path;
use std::fs;
use gdal::errors::Error;
use gdal::vector::{Defn, Driver, Feature, FieldDefn, FieldValue, Geometry, OGRFieldType};
/// Example 1, the detailed way:
fn example_1() -> Result<(), Error> {
let _ = fs::remove_file("/tmp/output1.geojson");
let drv = Driver::get(... | () -> Result<(), Error> {
let _ = fs::remove_file("/tmp/output2.geojson");
let driver = Driver::get("GeoJSON")?;
let mut ds = driver.create(Path::new("/tmp/output2.geojson"))?;
let layer = ds.create_layer()?;
layer.create_defn_fields(&[
("Name", OGRFieldType::OFTString),
("Value", O... | example_2 | identifier_name |
write_ogr.rs | extern crate gdal;
use std::path::Path;
use std::fs;
use gdal::errors::Error;
use gdal::vector::{Defn, Driver, Feature, FieldDefn, FieldValue, Geometry, OGRFieldType};
/// Example 1, the detailed way:
fn example_1() -> Result<(), Error> {
let _ = fs::remove_file("/tmp/output1.geojson");
let drv = Driver::get(... | {
example_1().unwrap();
example_2().unwrap();
} | identifier_body | |
write_ogr.rs | extern crate gdal;
use std::path::Path;
use std::fs;
use gdal::errors::Error;
use gdal::vector::{Defn, Driver, Feature, FieldDefn, FieldValue, Geometry, OGRFieldType};
/// Example 1, the detailed way:
fn example_1() -> Result<(), Error> {
let _ = fs::remove_file("/tmp/output1.geojson");
let drv = Driver::get(... | let mut ft = Feature::new(&defn)?;
ft.set_geometry(Geometry::from_wkt("POINT (46.50 22.50)")?)?;
ft.set_field_string("Name", "Feature 2")?;
match ft.set_field_double("Values", 0.789) {
Ok(v) => v,
Err(err) => println!("{}", err),
};
ft.create(lyr)?;
Ok(())
}
/// Example 2, ... | random_line_split | |
lib.rs | // Copyright © 2018 Cormac O'Brien
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without | // restriction, including without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission noti... | random_line_split | |
searching.js | const array = [1, 42, 7, 9, 13, 10, 20, 35, 45, -7, -3, 0, 4, -1, 15];
Array.prototype.find = function(isOk) {
const len = this.length;
for(let i = 0; i < len; i += 1) {
if(isOk(this[i], i, this)) {
return this[i];
}
}
}
Array.prototype.findIndex = function(isOk) {
const len = this.l... |
}
return -1;
}
console.log(array.find(x => x % 2 === 0));
console.log(array.find(x => x % 2 === 1));
console.log(array.find(x => x > 10 && x < 20));
console.log(array.find(x => x === 45));
console.log(array.find(x => x === 46));
console.log(array.findIndex(x => x % 2 === 0));
console.log(array.find... | {
return i;
} | conditional_block |
searching.js | const array = [1, 42, 7, 9, 13, 10, 20, 35, 45, -7, -3, 0, 4, -1, 15];
Array.prototype.find = function(isOk) {
const len = this.length;
for(let i = 0; i < len; i += 1) {
if(isOk(this[i], i, this)) {
return this[i];
}
}
}
Array.prototype.findIndex = function(isOk) {
const len = this.l... | console.log(array.findIndex(x => x === 46)); | console.log(array.findIndex(x => x % 2 === 0));
console.log(array.findIndex(x => x % 2 === 1));
console.log(array.findIndex(x => x > 10 && x < 20));
console.log(array.findIndex(x => x === 45));
| random_line_split |
comments.rs |
pub fn doc_comment_style(comment: &str) -> ast::AttrStyle {
assert!(is_doc_comment(comment));
if comment.starts_with("//!") || comment.starts_with("/*!") {
ast::AttrInner
} else {
ast::AttrOuter
}
}
pub fn strip_doc_comment_decoration(comment: &str) -> ~str {
/// remove whitespac... | {
(s.starts_with("///") && !is_line_non_doc_comment(s)) ||
s.starts_with("//!") ||
(s.starts_with("/**") && !is_block_non_doc_comment(s)) ||
s.starts_with("/*!")
} | identifier_body | |
comments.rs | }
}
pub fn strip_doc_comment_decoration(comment: &str) -> ~str {
/// remove whitespace-only lines from the start/end of lines
fn vertical_trim(lines: ~[~str]) -> ~[~str] {
let mut i = 0u;
let mut j = lines.len();
// first line of all-stars should be omitted
if lines.len() > 0 ... | ,
lines: ~[read_one_line_comment(rdr)],
pos: p
});
}
fn read_line_comments(rdr: @mut StringReader, code_to_the_left: bool,
comments: &mut ~[cmnt]) {
debug2!(">>> line comments");
let p = rdr.last_pos;
let mut lines: ~[~str] = ~[];
while rdr.... | { isolated } | conditional_block |
comments.rs | (comment: &str) -> ast::AttrStyle {
assert!(is_doc_comment(comment));
if comment.starts_with("//!") || comment.starts_with("/*!") {
ast::AttrInner
} else {
ast::AttrOuter
}
}
pub fn strip_doc_comment_decoration(comment: &str) -> ~str {
/// remove whitespace-only lines from the star... | doc_comment_style | identifier_name | |
comments.rs | '/' as u8) ||
(val[0] == '#' as u8 && val[1] == '!' as u8));
return val;
}
fn consume_non_eol_whitespace(rdr: @mut StringReader) {
while is_whitespace(rdr.curr) && rdr.curr != '\n' && !is_eof(rdr) {
bump(rdr);
}
}
fn push_blank_line_comment(rdr: @mut StringReader, comments: &mut ... |
#[test] fn test_block_doc_comment_2() { | random_line_split | |
lib.rs | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any lat... | pub mod evm;
pub mod interpreter;
#[macro_use]
pub mod factory;
mod vmtype;
mod instructions;
#[cfg(feature = "jit" )]
mod jit;
#[cfg(test)]
mod tests;
#[cfg(all(feature="benches", test))]
mod benches;
pub use vm::{
Schedule, CleanDustMode, EnvInfo, CallType, ActionParams, Ext,
ContractCreateResult, Message... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.