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 |
|---|---|---|---|---|
lib.rs | #![warn(missing_docs)]
// #![feature(external_doc)]
// #![doc(include = "../README.md")]
//! For an introduction and context view, read...
//!
//! [README.md pending](https://github.com/jleahred/...)
//!
//! A very basic example...
//! ```rust
//!```
//!
//!
//!
//! Please, read [README.md pending](https://github.com/... |
#[cfg(test)]
mod test;
use result::*;
use rules::*;
use status::Status;
fn from_status_error_2_result_error(e: status::Error) -> Error {
Error {
pos: e.status.pos.clone(),
expected: e.expected,
line: e
.status
.text2parse
.lines()
.into_iter... | pub mod result;
#[macro_use]
pub mod rules;
pub(crate) mod status; | random_line_split |
lib.rs | #![warn(missing_docs)]
// #![feature(external_doc)]
// #![doc(include = "../README.md")]
//! For an introduction and context view, read...
//!
//! [README.md pending](https://github.com/jleahred/...)
//!
//! A very basic example...
//! ```rust
//!```
//!
//!
//!
//! Please, read [README.md pending](https://github.com/... | <'a, CustI>(text: &'a str, rules: &SetOfRules<CustI>) -> Result<'a> {
let status = Status::init(text);
expr::non_term::parse_ref_rule(rules, status, &RuleName("main".to_string()))
.map_err(from_status_error_2_result_error)?
.check_finalization()
}
// --------------------------------------------... | parse | identifier_name |
lib.rs | #![warn(missing_docs)]
// #![feature(external_doc)]
// #![doc(include = "../README.md")]
//! For an introduction and context view, read...
//!
//! [README.md pending](https://github.com/jleahred/...)
//!
//! A very basic example...
//! ```rust
//!```
//!
//!
//!
//! Please, read [README.md pending](https://github.com/... |
// --------------------------------------------------------------------------------
// todo:
impl<'a> Status<'a> {
fn check_finalization(&self) -> Result<'a> {
if self.pos.n == self.text2parse.len() {
Ok(())
} else {
match &self.deeper_error {
None => Err(E... | {
let status = Status::init(text);
expr::non_term::parse_ref_rule(rules, status, &RuleName("main".to_string()))
.map_err(from_status_error_2_result_error)?
.check_finalization()
} | identifier_body |
lib.rs | #![warn(missing_docs)]
// #![feature(external_doc)]
// #![doc(include = "../README.md")]
//! For an introduction and context view, read...
//!
//! [README.md pending](https://github.com/jleahred/...)
//!
//! A very basic example...
//! ```rust
//!```
//!
//!
//!
//! Please, read [README.md pending](https://github.com/... | else {
match &self.deeper_error {
None => Err(Error {
pos: self.pos.clone(),
expected: im::vector!["not consumed full input...".to_owned()],
line: self
.text2parse
.lines()
... | {
Ok(())
} | conditional_block |
wordcount_debugging.py | #
# 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 may not us... | logging.getLogger().setLevel(logging.INFO)
run() | conditional_block | |
wordcount_debugging.py | #
# 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 may not us... | (beam.DoFn):
"""A DoFn that filters for a specific key based on a regular expression."""
def __init__(self, pattern):
super(FilterTextFn, self).__init__()
self.pattern = pattern
# A custom metric can track values in your pipeline as it runs. Those
# values will be available in the monitoring system ... | FilterTextFn | identifier_name |
wordcount_debugging.py | #
# 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 may not us... |
return (pcoll
| 'split' >> (beam.FlatMap(lambda x: re.findall(r'[A-Za-z\']+', x))
.with_output_types(unicode))
| 'pair_with_one' >> beam.Map(lambda x: (x, 1))
| 'group' >> beam.GroupByKey()
| 'count' >> beam.Map(count_ones))
def run(argv=... | (word, ones) = word_ones
return (word, sum(ones)) | identifier_body |
wordcount_debugging.py | #
# 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 may not us... | logging.getLogger().setLevel(logging.INFO)
run() | #
# You can set the default logging level to a different level when running
# locally. | random_line_split |
todoFooter.js | import React from 'react';
import PropTypes from 'prop-types';
import {observer} from 'mobx-react';
import {action} from 'mobx';
import {pluralize} from '../utils';
import { ALL_TODOS, ACTIVE_TODOS, COMPLETED_TODOS } from '../constants';
@observer
export default class TodoFooter extends React.Component {
| () {
const todoStore = this.props.todoStore;
if (!todoStore.activeTodoCount && !todoStore.completedCount)
return null;
const activeTodoWord = pluralize(todoStore.activeTodoCount, 'item');
return (
<footer className="footer">
<span className="todo-count">
<strong>{todoStore.activeTodoCount}</str... | render | identifier_name |
todoFooter.js | import React from 'react';
import PropTypes from 'prop-types';
import {observer} from 'mobx-react';
import {action} from 'mobx';
import {pluralize} from '../utils';
import { ALL_TODOS, ACTIVE_TODOS, COMPLETED_TODOS } from '../constants';
@observer
export default class TodoFooter extends React.Component {
render() {
... | renderFilterLink(filterName, url, caption) {
return (<li>
<a href={"#/" + url}
className={filterName === this.props.viewStore.todoFilter ? "selected" : ""}>
{caption}
</a>
{' '}
</li>)
}
@action
clearCompleted = () => {
this.props.todoStore.clearCompleted();
};
}
TodoFooter.propTypes = {
... | </footer>
);
}
| random_line_split |
commentsView.js | define(['jquery', 'backbone', 'views/commentView'],
function($, Backbone, CommentView){
return Backbone.View.extend({
initialize: function() {
this.subViews = [];
},
attachToView: function() {
var self = this;
thi... | return this;
},
render: function() {
this.collection.forEach(function(model) {
this.addOneToList(model);
}, this);
return this;
},
addOneToList: function (model) {
var comm... | el: photoEl
});
self.subViews.push(messageView);
}); | random_line_split |
fragments.rs | non_member(mpi, &moved[..]) &&
non_member(mpi, &assigned[..])
});
debug!("fragments 5 unmoved: {:?}", frag_lps(&unmoved[..]));
// Swap contents back in.
fragments.unmoved_fragments = unmoved;
fragments.parents_of_fragments = parents;
fragments.moved_leaf_paths = moved;
... | {
let opt_variant_did = match parent.kind {
LpDowncast(_, variant_did) => Some(variant_did),
LpVar(..) | LpUpvar(..) | LpExtend(..) => enum_variant_did,
};
let loan_path_elem = LpInterior(InteriorField(new_field_name));
let new_lp_type = match new_field_name {
mc::NamedField(ast... | identifier_body | |
fragments.rs | iblings(this, tcx, &mut unmoved, lp, None);
}
unmoved.sort();
unmoved.dedup();
debug!("fragments 4 unmoved: {:?}", frag_lps(&unmoved[..]));
// Fifth, filter the leftover fragments down to its core.
unmoved.retain(|f| match *f {
AllButOneFrom(_) => true,
Just(mpi) => non_member(... | mc::NamedField(ast_name) =>
ty::named_element_ty(tcx, parent.to_type(), ast_name, opt_variant_did),
mc::PositionalField(idx) =>
ty::positional_element_ty(tcx, parent.to_type(), idx, opt_variant_did), | random_line_split | |
fragments.rs | .j` if we
/// never move out any child like `a.j.x`); any parent paths
/// (e.g. `a` for the `a.j` example) are moved over to
/// `parents_of_fragments`.
moved_leaf_paths: Vec<MovePathIndex>,
/// `assigned_leaf_paths` tracks paths that have been used
/// directly by being overwritten, but is ot... | <'tcx>(this: &MoveData<'tcx>,
tcx: &ty::ctxt<'tcx>,
gathered_fragments: &mut Vec<Fragment>,
lp: Rc<LoanPath<'tcx>>,
origin_id: Option<ast::NodeId>) {
match lp.kind {
LpVar(_) | LpUpvar... | add_fragment_siblings | identifier_name |
rtnl.rs | #[cfg(target_env="gnu")]
Mcautojoin => libc::IFA_F_MCAUTOJOIN,
#[cfg(target_env="gnu")]
StablePrivacy => libc::IFA_F_STABLE_PRIVACY
);
impl_var!(
/// `rtm_type`
/// The results of a lookup from a route table
Rtn, libc::c_uchar,
Unspec => libc::RTN_UNSPEC,
Unicast => libc::RTN_UNICAST,
... | Priority => libc::IFLA_PRIORITY,
Master => libc::IFLA_MASTER,
Wireless => libc::IFLA_WIRELESS,
Protinfo => libc::IFLA_PROTINFO,
Txqlen => libc::IFLA_TXQLEN,
Map => libc::IFLA_MAP,
Weight => libc::IFLA_WEIGHT,
Operstate => libc::IFLA_OPERSTATE,
Linkmode => libc::IFLA_LINKMODE,
Lin... | Link => libc::IFLA_LINK,
Qdisc => libc::IFLA_QDISC,
Stats => libc::IFLA_STATS,
Cost => libc::IFLA_COST, | random_line_split |
json_pipe_example.ts | import {Component, provide} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
// #docregion JsonPipe
@Component({
selector: 'json-example',
template: `<div>
<p>Without JSON pipe:</p>
<pre>{{object}}</pre>
<p>With JSON pipe:</p>
<pre>{{object | json}}</pre>
</div>`
})
expo... | () {
bootstrap(AppCmp);
}
| main | identifier_name |
json_pipe_example.ts | import {Component, provide} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
// #docregion JsonPipe
@Component({
selector: 'json-example',
template: `<div>
<p>Without JSON pipe:</p>
<pre>{{object}}</pre>
<p>With JSON pipe:</p>
<pre>{{object | json}}</pre>
</div>`
})
expo... | {
bootstrap(AppCmp);
} | identifier_body | |
json_pipe_example.ts | import {Component, provide} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';
// #docregion JsonPipe | <p>Without JSON pipe:</p>
<pre>{{object}}</pre>
<p>With JSON pipe:</p>
<pre>{{object | json}}</pre>
</div>`
})
export class JsonPipeExample {
object: Object = {foo: 'bar', baz: 'qux', nested: {xyz: 3, numbers: [1, 2, 3, 4, 5]}}
}
// #enddocregion
@Component({
selector: 'example-app',
directives... | @Component({
selector: 'json-example',
template: `<div> | random_line_split |
upload-page.ts | import { Component } from '@angular/core';
import { ActionSheetController, Modal, ModalController, NavController, ToastController, ViewController } from 'ionic-angular';
import { Camera, CameraOptions } from 'ionic-native';
import { FirebaseProvider } from '../../providers/firebase-provider/firebase-provider';
@Compon... | {
photo: string;
loginModal: Modal;
public get isAuthenticated(): boolean {
return this.fbProv.isAuthenticated;
}
constructor(
public navCtrl: NavController,
public modalCtrl: ModalController,
public actionSheetCtrl: ActionSheetController,
public toastCtrl... | UploadPage | identifier_name |
upload-page.ts | import { Component } from '@angular/core';
import { ActionSheetController, Modal, ModalController, NavController, ToastController, ViewController } from 'ionic-angular';
import { Camera, CameraOptions } from 'ionic-native';
import { FirebaseProvider } from '../../providers/firebase-provider/firebase-provider';
@Compon... |
}
openOptions(): void {
let actionSheet = this.actionSheetCtrl.create({
title: 'Select One',
buttons: [
{
text: 'Take Photo',
handler: () => {
this.takePic();
}
}... | {
// todo 2: create and present modal
} | conditional_block |
upload-page.ts | import { Component } from '@angular/core';
import { ActionSheetController, Modal, ModalController, NavController, ToastController, ViewController } from 'ionic-angular';
import { Camera, CameraOptions } from 'ionic-native';
import { FirebaseProvider } from '../../providers/firebase-provider/firebase-provider';
@Compon... |
showLogin(): void {
if (!this.loginModal || !this.loginModal.isLoaded() || !this.loginModal.isLast()) {
// todo 2: create and present modal
}
}
openOptions(): void {
let actionSheet = this.actionSheetCtrl.create({
title: 'Select One',
buttons: [... | {
if (firebase.auth().currentUser) {
console.log(firebase.auth().currentUser.email);
this.toastCtrl.create({
duration: 3000,
message: `${firebase.auth().currentUser.email} is logged in.`,
position: 'middle'
}).present();
... | identifier_body |
upload-page.ts | import { Component } from '@angular/core';
import { ActionSheetController, Modal, ModalController, NavController, ToastController, ViewController } from 'ionic-angular';
import { Camera, CameraOptions } from 'ionic-native';
import { FirebaseProvider } from '../../providers/firebase-provider/firebase-provider';
@Compon... | encodingType: Camera.EncodingType.JPEG,
mediaType: Camera.MediaType.PICTURE,
saveToPhotoAlbum: false,
allowEdit: false,
correctOrientation: true // Corrects Android orientation quirks
};
this.getPicture(opts);
}
uploadPic(): void {
... | random_line_split | |
PcapTimeline.py | from scapy.all import *
import plotly
from datetime import datetime
import pandas as pd
#Read the packets from file
packets=rdpcap('mypcap.pcap')
#lists to hold packetinfo
pktBytes=[]
pktTimes=[]
#Read each packet and append to the lists
for pkt in packets:
if IP in pkt:
try:
pktBytes.app... | # convert list to series
bytes=pd.Series(pktBytes).astype(int)
times=pd.to_datetime(pd.Series(pktTimes).astype(str), errors='coerce')
#Create the dateframe
df=pd.DataFrame({"Bytes": bytes, "Times":times})
#Set the date to a timestamp
df=df.set_index('Times')
df2=df.resample('2S').sum()
print(df2)
#Crea... | except:
pass
| random_line_split |
PcapTimeline.py | from scapy.all import *
import plotly
from datetime import datetime
import pandas as pd
#Read the packets from file
packets=rdpcap('mypcap.pcap')
#lists to hold packetinfo
pktBytes=[]
pktTimes=[]
#Read each packet and append to the lists
for pkt in packets:
|
# convert list to series
bytes=pd.Series(pktBytes).astype(int)
times=pd.to_datetime(pd.Series(pktTimes).astype(str), errors='coerce')
#Create the dateframe
df=pd.DataFrame({"Bytes": bytes, "Times":times})
#Set the date to a timestamp
df=df.set_index('Times')
df2=df.resample('2S').sum()
print(df2)
#... | if IP in pkt:
try:
pktBytes.append(pkt[IP].len)
pktTime=datetime.fromtimestamp(pkt.time)
pktTimes.append(pktTime.strftime("%Y-%m-%d %H:%M:%S.%f"))
except:
pass | conditional_block |
error.py | #
# Copyright (C) 2009, 2010 JAGSAT Development Team (see below)
#
# This file is part of JAGSAT.
#
# JAGSAT 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 ... | (LoggableError):
pass
| CoreError | identifier_name |
error.py | #
# Copyright (C) 2009, 2010 JAGSAT Development Team (see below)
#
# This file is part of JAGSAT.
#
# JAGSAT 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 ... | pass | identifier_body | |
error.py | #
# Copyright (C) 2009, 2010 JAGSAT Development Team (see below)
#
# This file is part of JAGSAT.
#
# JAGSAT 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 ... | # - Thomas Forss
#
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
from base.error import *
class CoreError (LoggableError):
pass | # - Juan Pedro Bolivar Puente
# - Alberto Villegas Erce
# - Guillem Medina
# - Sarah Lindstrom
# - Aksel Junkkila | random_line_split |
cppreference.py |
full = (head + tail).replace('"', '\\(dq')
""" remove [static] tag as in string::npos[static] """
full = full.replace("[static]", "");
return '\n.IP "%s"\n%s\n' % (full, g.group(2))
NAV_BAR_END = '<div class="t-navbar-sep">.?</div></div>'
# Format replacement RE list
# The '.SE' pseudo macro is desc... | head = head.strip() + ' (3)' | conditional_block | |
cppreference.py |
NAV_BAR_END = '<div class="t-navbar-sep">.?</div></div>'
# Format replacement RE list
# The '.SE' pseudo macro is described in the function: html2groff
rps = [
# Workaround: remove <p> in t-dcl
(r'<tr class="t-dcl">(.*?)</tr>',
lambda g: re.sub('<p/?>', '', g.group(1)), re.S),
# Header, Name
(r... | if g.group(1).find("<a href=") == -1:
return ""
head = re.sub(r'<.*?>', '', g.group(1)).strip()
tail = ''
cppvertag = re.search(
'^(.*?)(\[(?:(?:since|until) )?C\+\+\d+\]\s*(,\s*)?)+$', head)
if cppvertag:
head = cppvertag.group(1).strip()
tail = ' ' + cppvertag.group(2)
... | identifier_body | |
cppreference.py | tag
(r'<ul>', r'\n.RS 2\n', 0),
(r'</ul>', r'\n.RE\n.sp\n', 0),
# 'li' tag
(r'<li>\s*(.+?)</li>', r'\n.IP \[bu] 3\n\1\n', re.S),
# 'pre' tag
(r'<pre[^>]*>(.+?)</pre\s*>', r'\n.in +2n\n.nf\n\1\n.fi\n.in\n', re.S),
# Footer
(r'<div class="printfooter">',
r'\n.SE\n.IEND\n.SH "REFERENC... | func_test | identifier_name | |
cppreference.py | # This program 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along ... | # (at your option) any later version.
# | random_line_split | |
b100.py | """
Synthesise a QA module into the B100 FPGA.
"""
import os
import shutil
import subprocess
| from fpga_sdrlib.config import uhddir, miscdir, fpgaimage_fn
b100dir = os.path.join(uhddir, 'fpga', 'usrp2', 'top', 'B100')
custom_src_dir = os.path.join(config.verilogdir, 'uhd')
def set_image(fn):
shutil.copyfile(fn, fpgaimage_fn)
def make_defines_file(builddir, defines):
fn = os.path.join(builddir, 'globa... |
from jinja2 import Environment, FileSystemLoader
from fpga_sdrlib import config | random_line_split |
b100.py | """
Synthesise a QA module into the B100 FPGA.
"""
import os
import shutil
import subprocess
from jinja2 import Environment, FileSystemLoader
from fpga_sdrlib import config
from fpga_sdrlib.config import uhddir, miscdir, fpgaimage_fn
b100dir = os.path.join(uhddir, 'fpga', 'usrp2', 'top', 'B100')
custom_src_dir = o... | (builddir, defines):
fn = os.path.join(builddir, 'global_defines.vh')
f = open(fn, 'w')
f.write(make_defines_prefix(defines))
f.close
return fn
def make_defines_prefix(defines):
lines = []
for k, v in defines.items():
if v is False:
pass
elif v is True:
... | make_defines_file | identifier_name |
b100.py | """
Synthesise a QA module into the B100 FPGA.
"""
import os
import shutil
import subprocess
from jinja2 import Environment, FileSystemLoader
from fpga_sdrlib import config
from fpga_sdrlib.config import uhddir, miscdir, fpgaimage_fn
b100dir = os.path.join(uhddir, 'fpga', 'usrp2', 'top', 'B100')
custom_src_dir = o... |
f.close()
os.chdir(currentdir)
return os.path.join(output_dir, 'B100.bin')
| raise StandardError("Synthesis failed: see {0}".format(logfile_fn)) | conditional_block |
b100.py | """
Synthesise a QA module into the B100 FPGA.
"""
import os
import shutil
import subprocess
from jinja2 import Environment, FileSystemLoader
from fpga_sdrlib import config
from fpga_sdrlib.config import uhddir, miscdir, fpgaimage_fn
b100dir = os.path.join(uhddir, 'fpga', 'usrp2', 'top', 'B100')
custom_src_dir = o... |
def make_defines_file(builddir, defines):
fn = os.path.join(builddir, 'global_defines.vh')
f = open(fn, 'w')
f.write(make_defines_prefix(defines))
f.close
return fn
def make_defines_prefix(defines):
lines = []
for k, v in defines.items():
if v is False:
pass
el... | shutil.copyfile(fn, fpgaimage_fn) | identifier_body |
globe.js | // This is an example Chiasm plugin based on this D3 Canvas example:
// http://bl.ocks.org/mbostock/ba63c55dd2dbc3ab0127
function Globe (){
var my = ChiasmComponent({
backgroundColor: "black",
foregroundColor: "white",
center: [0, 0], | });
var canvas = document.createElement("canvas");
var context = canvas.getContext("2d");
var projection = d3.geo.orthographic()
.clipAngle(90);
var path = d3.geo.path()
.projection(projection)
.context(context);
// Interaction that lets the user rotate the globe.
// Draws from http://bl.o... | bounds: null,
zoom: 1,
sens: 0.25 | random_line_split |
globe.js | // This is an example Chiasm plugin based on this D3 Canvas example:
// http://bl.ocks.org/mbostock/ba63c55dd2dbc3ab0127
function Globe () |
// Interaction that lets the user rotate the globe.
// Draws from http://bl.ocks.org/KoGor/5994804
d3.select(canvas)
.call(d3.behavior.drag()
.origin(function() {
var r = projection.rotate();
return {
x: r[0] / my.sens,
y: -r[1] / my.sens
};
})
.o... | {
var my = ChiasmComponent({
backgroundColor: "black",
foregroundColor: "white",
center: [0, 0],
bounds: null,
zoom: 1,
sens: 0.25
});
var canvas = document.createElement("canvas");
var context = canvas.getContext("2d");
var projection = d3.geo.orthographic()
.clipAngle(90);
... | identifier_body |
globe.js | // This is an example Chiasm plugin based on this D3 Canvas example:
// http://bl.ocks.org/mbostock/ba63c55dd2dbc3ab0127
function | (){
var my = ChiasmComponent({
backgroundColor: "black",
foregroundColor: "white",
center: [0, 0],
bounds: null,
zoom: 1,
sens: 0.25
});
var canvas = document.createElement("canvas");
var context = canvas.getContext("2d");
var projection = d3.geo.orthographic()
.clipAngle(90);
... | Globe | identifier_name |
process_builder.rs | use std::fmt::{mod, Show, Formatter};
use std::os;
use std::c_str::CString;
use std::io::process::{Command, ProcessOutput, InheritFd};
use std::collections::HashMap;
use util::{ProcessError, process_error};
#[deriving(Clone,PartialEq)]
pub struct ProcessBuilder {
program: CString,
args: Vec<CString>,
env:... |
// TODO: should InheritFd be hardcoded?
pub fn exec(&self) -> Result<(), ProcessError> {
let mut command = self.build_command();
command.stdout(InheritFd(1))
.stderr(InheritFd(2))
.stdin(InheritFd(0));
let exit = try!(command.status().map_err(|e| {
... | {
self.env.insert(key.to_string(), val.map(|t| t.to_c_str()));
self
} | identifier_body |
process_builder.rs | use std::fmt::{mod, Show, Formatter};
use std::os;
use std::c_str::CString;
use std::io::process::{Command, ProcessOutput, InheritFd};
use std::collections::HashMap;
use util::{ProcessError, process_error};
#[deriving(Clone,PartialEq)]
pub struct ProcessBuilder {
program: CString,
args: Vec<CString>,
env:... | fn debug_string(&self) -> String {
let program = String::from_utf8_lossy(self.program.as_bytes_no_nul());
let mut program = program.into_string();
for arg in self.args.iter() {
program.push_char(' ');
let s = String::from_utf8_lossy(arg.as_bytes_no_nul());
... | random_line_split | |
process_builder.rs | use std::fmt::{mod, Show, Formatter};
use std::os;
use std::c_str::CString;
use std::io::process::{Command, ProcessOutput, InheritFd};
use std::collections::HashMap;
use util::{ProcessError, process_error};
#[deriving(Clone,PartialEq)]
pub struct ProcessBuilder {
program: CString,
args: Vec<CString>,
env:... | (&self) -> Result<(), ProcessError> {
let mut command = self.build_command();
command.stdout(InheritFd(1))
.stderr(InheritFd(2))
.stdin(InheritFd(0));
let exit = try!(command.status().map_err(|e| {
process_error(format!("Could not execute process `{}`",... | exec | identifier_name |
process_builder.rs | use std::fmt::{mod, Show, Formatter};
use std::os;
use std::c_str::CString;
use std::io::process::{Command, ProcessOutput, InheritFd};
use std::collections::HashMap;
use util::{ProcessError, process_error};
#[deriving(Clone,PartialEq)]
pub struct ProcessBuilder {
program: CString,
args: Vec<CString>,
env:... |
}
pub fn build_command(&self) -> Command {
let mut command = Command::new(self.program.as_bytes_no_nul());
command.cwd(&self.cwd);
for arg in self.args.iter() {
command.arg(arg.as_bytes_no_nul());
}
for (k, v) in self.env.iter() {
let k = k.as_sl... | {
Err(process_error(format!("Process didn't exit successfully: `{}`",
self.debug_string()),
None, Some(&output.status), Some(&output)))
} | conditional_block |
access.js | // Tradity.de Server
// Copyright (C) 2016 Tradity.de Tech Team <tech@tradity.de>
// 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, either version 3 of the License, or
// (at your optio... | (area) {
return this.hasAnyAccess || (this.areas.indexOf(area) !== -1);
}
/**
* Grants all access levels held by another access object.
*
* @param {module:access~Access} otherAccess Another access object.
*
* @function module:access~Access#update
*/
update(otherAccess) {
if (otherAcc... | has | identifier_name |
access.js | // Tradity.de Server
// Copyright (C) 2016 Tradity.de Tech Team <tech@tradity.de>
// 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, either version 3 of the License, or
// (at your optio... | * @return {boolean} Indicates whether access is present.
*
* @function module:access~Access#has
*/
has(area) {
return this.hasAnyAccess || (this.areas.indexOf(area) !== -1);
}
/**
* Grants all access levels held by another access object.
*
* @param {module:access~Access} otherAccess ... | * @param {string} area The access level identifier.
* | random_line_split |
access.js | // Tradity.de Server
// Copyright (C) 2016 Tradity.de Tech Team <tech@tradity.de>
// 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, either version 3 of the License, or
// (at your optio... |
return this.areas;
}
/**
* Checks for privileges to a certain access level.
*
* @param {string} area The access level identifier.
*
* @return {boolean} Indicates whether access is present.
*
* @function module:access~Access#has
*/
has(area) {
return this.hasAnyAccess ||... | {
return ['*'];
} | conditional_block |
access.js | // Tradity.de Server
// Copyright (C) 2016 Tradity.de Tech Team <tech@tradity.de>
// 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, either version 3 of the License, or
// (at your optio... |
/**
* Serializes the access levels associated with this access object
* into a JSON string that can be passed to {@link module:access~Access.fromJSON}.
*
* @return {string} A short machine-readable description of the access
* levels associated with this access object.
*
* @... | { return this.toJSON(); } | identifier_body |
variance-trait-matching.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 main() {} | random_line_split | |
variance-trait-matching.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 main() {}
| {
let mut x = 1;
let y: &'static mut isize = Make::make(&mut x); //~ ERROR `x` does not live long enough
y
} | identifier_body |
variance-trait-matching.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 ... | () -> &'static mut isize {
let mut x = 1;
let y: &'static mut isize = Make::make(&mut x); //~ ERROR `x` does not live long enough
y
}
fn main() {}
| f | identifier_name |
draw_model_test_setup.py | # ==============================================================================
# Copyright 2019 - Philip Paquette
#
# NOTICE: 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 rest... | ():
""" Creates a testable setup to test a model and a constructor """
def __init__(self, policy_model_ctor, value_model_ctor, draw_model_ctor, dataset_builder, adapter_ctor,
load_policy_args, load_value_args, load_draw_args):
""" Constructor
:param policy_model_ctor: The p... | DrawModelTestSetup | identifier_name |
draw_model_test_setup.py | # ==============================================================================
# Copyright 2019 - Philip Paquette
#
# NOTICE: 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 rest... | arg_type, arg_name, arg_value, _ = arg
flags[arg_name] = define[arg_type](arg_value)
if arg_type == '---' and arg_name in flags:
del flags[arg_name]
return flags
def run_tests(self):
""" Run all tests """
IOLoop.current().run_sync(self.run... | for arg in args: | random_line_split |
draw_model_test_setup.py | # ==============================================================================
# Copyright 2019 - Philip Paquette
#
# NOTICE: 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 rest... | # Parsing new flags
args = load_policy_args()
if load_value_args is not None:
args += load_value_args()
args += load_draw_args()
self.hparams = self.parse_flags(args)
# Other attributes
self.graph = None
self.sess = None
self.adapter =... | """ Creates a testable setup to test a model and a constructor """
def __init__(self, policy_model_ctor, value_model_ctor, draw_model_ctor, dataset_builder, adapter_ctor,
load_policy_args, load_value_args, load_draw_args):
""" Constructor
:param policy_model_ctor: The policy mo... | identifier_body |
draw_model_test_setup.py | # ==============================================================================
# Copyright 2019 - Philip Paquette
#
# NOTICE: 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 rest... |
return flags
def run_tests(self):
""" Run all tests """
IOLoop.current().run_sync(self.run_tests_async)
@gen.coroutine
def run_tests_async(self):
""" Run tests in an asynchronous IO Loop """
self.build_model()
self.adapter = self.adapter_ctor(self.queue_dat... | arg_type, arg_name, arg_value, _ = arg
flags[arg_name] = define[arg_type](arg_value)
if arg_type == '---' and arg_name in flags:
del flags[arg_name] | conditional_block |
mod.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::SourceLocationKey;
use fixture_tests::Fixture;
use graphql_ir::build;
use graphql_syntax::parse_executable;
use graph... | {
let source_location = SourceLocationKey::standalone(fixture.file_name);
let ast = parse_executable(fixture.content, source_location).unwrap();
build(&TEST_SCHEMA, &ast.definitions)
.map(|definitions| print_ir(&TEST_SCHEMA, &definitions).join("\n\n"))
.map_err(|errors| {
errors
... | identifier_body | |
mod.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::SourceLocationKey;
use fixture_tests::Fixture;
use graphql_ir::build;
use graphql_syntax::parse_executable;
use graph... | } | }) | random_line_split |
mod.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::SourceLocationKey;
use fixture_tests::Fixture;
use graphql_ir::build;
use graphql_syntax::parse_executable;
use graph... | (fixture: &Fixture<'_>) -> Result<String, String> {
let source_location = SourceLocationKey::standalone(fixture.file_name);
let ast = parse_executable(fixture.content, source_location).unwrap();
build(&TEST_SCHEMA, &ast.definitions)
.map(|definitions| print_ir(&TEST_SCHEMA, &definitions).join("\n\n"... | transform_fixture | identifier_name |
hammer_gestures.d.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 { OpaqueToken } from '@angular/core';
import { EventManagerPlugin } from './event_manager';
/**
* A DI token ... | extends EventManagerPlugin {
private _config;
constructor(_config: HammerGestureConfig);
supports(eventName: string): boolean;
addEventListener(element: HTMLElement, eventName: string, handler: Function): Function;
isCustomEvent(eventName: string): boolean;
}
| HammerGesturesPlugin | identifier_name |
hammer_gestures.d.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 { OpaqueToken } from '@angular/core';
import { EventManagerPlugin } from './event_manager';
/**
* A DI token ... | } | supports(eventName: string): boolean;
addEventListener(element: HTMLElement, eventName: string, handler: Function): Function;
isCustomEvent(eventName: string): boolean; | random_line_split |
__init__.py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (c) 2009 Zikzakmedia S.L. (http://zikzakmedia.com) All Rights Reserved.
# Jordi Esteve <jesteve@zikzakmedia.com>
# $Id$
#
# Th... | import wizard_run | """ | random_line_split |
EmailService.ts | /**
* Copyright © 2021 Rémi Pace.
* This file is part of Abc-Map.
*
* Abc-Map 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, either version 3 of
* the License, or (at your option) any later vers... | o: string, token: string): Promise<void> {
const subject = 'Activation de votre compte Abc-Map';
const href = `${this.config.externalUrl}/confirm-account/${token}`;
const content = `
<p>Bonjour !</p>
<p>Pour activer votre compte Abc-Map, veuillez <a href="${href}" data-cy="enable-account-lin... | nfirmRegistration(t | identifier_name |
EmailService.ts | /**
* Copyright © 2021 Rémi Pace.
* This file is part of Abc-Map.
*
* Abc-Map 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, either version 3 of
* the License, or (at your option) any later vers... | public confirmRegistration(to: string, token: string): Promise<void> {
const subject = 'Activation de votre compte Abc-Map';
const href = `${this.config.externalUrl}/confirm-account/${token}`;
const content = `
<p>Bonjour !</p>
<p>Pour activer votre compte Abc-Map, veuillez <a href="${href... | }
| random_line_split |
bunch.rs |
#![feature(test)]
extern crate misc;
extern crate lsm;
extern crate test;
fn tid() -> String {
// TODO use the rand crate
fn bytes() -> std::io::Result<[u8;16]> {
use std::fs::OpenOptions;
let mut f = try!(OpenOptions::new()
.read(true)
.open("/dev/urandom"));
... | (b: &mut test::Bencher) {
fn f() -> lsm::Result<bool> {
//println!("running");
let db = try!(lsm::db::new(tempfile("bunch"), lsm::DEFAULT_SETTINGS));
const NUM : usize = 10000;
let mut a = Vec::new();
for i in 0 .. 10 {
let g = try!(db.WriteSegmentFromSortedSequ... | bunch | identifier_name |
bunch.rs | #![feature(test)]
extern crate misc;
extern crate lsm;
extern crate test;
fn tid() -> String {
// TODO use the rand crate
fn bytes() -> std::io::Result<[u8;16]> {
use std::fs::OpenOptions;
let mut f = try!(OpenOptions::new()
.read(true)
.open("/dev/urandom"));
... | {
let lck = try!(db.GetWriteLock());
try!(lck.commitSegments(a.clone()));
}
let g3 = try!(db.merge(0, 2, None));
assert!(g3.is_some());
let g3 = g3.unwrap();
{
let lck = try!(db.GetWriteLock());
try!(lck.commitMerge(g3));
... | } | random_line_split |
bunch.rs |
#![feature(test)]
extern crate misc;
extern crate lsm;
extern crate test;
fn tid() -> String {
// TODO use the rand crate
fn bytes() -> std::io::Result<[u8;16]> {
use std::fs::OpenOptions;
let mut f = try!(OpenOptions::new()
.read(true)
.open("/dev/urandom"));
... |
let ba = bytes().unwrap();
to_hex_string(&ba)
}
fn tempfile(base: &str) -> String {
std::fs::create_dir("tmp");
let file = "tmp/".to_string() + base + "_" + &tid();
file
}
#[bench]
fn bunch(b: &mut test::Bencher) {
fn f() -> lsm::Result<bool> {
//println!("running");
let db =... | {
let strs: Vec<String> = ba.iter()
.map(|b| format!("{:02X}", b))
.collect();
strs.connect("")
} | identifier_body |
retry.ts | import { Operator } from '../Operator';
import { Subscriber } from '../Subscriber';
import { Observable } from '../Observable';
import { TeardownLogic } from '../Subscription';
/**
* Returns an Observable that mirrors the source Observable, resubscribing to it if it calls `error` and the
* predicate returns true for... | } | random_line_split | |
retry.ts | import { Operator } from '../Operator';
import { Subscriber } from '../Subscriber';
import { Observable } from '../Observable';
import { TeardownLogic } from '../Subscription';
/**
* Returns an Observable that mirrors the source Observable, resubscribing to it if it calls `error` and the
* predicate returns true for... | <T> implements Operator<T, T> {
constructor(private count: number,
private source: Observable<T>) {
}
call(subscriber: Subscriber<T>, source: any): TeardownLogic {
return source._subscribe(new RetrySubscriber(subscriber, this.count, this.source));
}
}
/**
* We need this JSDoc comment for af... | RetryOperator | identifier_name |
noMisusedNewRule.ts | /**
* @license
* Copyright 2017 Palantir Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by... | (ctx: Lint.WalkContext<void>) {
return ts.forEachChild(ctx.sourceFile, function cb(node: ts.Node): void {
if (isMethodSignature(node)) {
if (getPropertyName(node.name) === "constructor") {
ctx.addFailureAtNode(node, Rule.FAILURE_STRING_INTERFACE);
}
} else if ... | walk | identifier_name |
noMisusedNewRule.ts | /**
* @license
* Copyright 2017 Palantir Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by... |
}
function walk(ctx: Lint.WalkContext<void>) {
return ts.forEachChild(ctx.sourceFile, function cb(node: ts.Node): void {
if (isMethodSignature(node)) {
if (getPropertyName(node.name) === "constructor") {
ctx.addFailureAtNode(node, Rule.FAILURE_STRING_INTERFACE);
}
... | {
return this.applyWithFunction(sourceFile, walk);
} | identifier_body |
noMisusedNewRule.ts | /**
* @license
* Copyright 2017 Palantir Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by... | public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
return this.applyWithFunction(sourceFile, walk);
}
}
function walk(ctx: Lint.WalkContext<void>) {
return ts.forEachChild(ctx.sourceFile, function cb(node: ts.Node): void {
if (isMethodSignature(node)) {
if (getPropert... | public static FAILURE_STRING_CLASS = '`new` in a class is a method named "new". Did you mean `constructor`?';
| random_line_split |
noMisusedNewRule.ts | /**
* @license
* Copyright 2017 Palantir Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by... |
return ts.forEachChild(node, cb);
});
}
function returnTypeMatchesParent(parent: { name?: ts.Identifier }, decl: ts.SignatureDeclaration): boolean {
if (parent.name === undefined || decl.type === undefined || !isTypeReferenceNode(decl.type)) {
return false;
}
return decl.type.typeName.... | {
if (returnTypeMatchesParent(node.parent as ts.InterfaceDeclaration, node)) {
ctx.addFailureAtNode(node, Rule.FAILURE_STRING_INTERFACE);
}
} | conditional_block |
mod.rs | #[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::OR {
#[doc = r" Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'... | #[inline(always)]
pub fn reset_value() -> W {
W { bits: 0 }
}
#[doc = r" Writes raw bits to the register"]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bits 0:1 - Timer input 1 remap"]
#[inline(alw... | impl W {
#[doc = r" Reset value of the register"] | random_line_split |
mod.rs | #[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::OR {
#[doc = r" Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'... | {
bits: u8,
}
impl RMPR {
#[doc = r" Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r" Proxy"]
pub struct _RMPW<'a> {
w: &'a mut W,
}
impl<'a> _RMPW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline(always)]
pub uns... | RMPR | identifier_name |
mod.rs | #[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::OR {
#[doc = r" Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'... |
#[doc = r" Writes the reset value to the register"]
#[inline(always)]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = r" Value of the field"]
pub struct RMPR {
bits: u8,
}
impl RMPR {
#[doc = r" Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
... | {
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
} | identifier_body |
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/. */
#![deny(unsafe_code)]
extern crate gfx;
extern crate ipc_channel;
extern crate metrics;
extern crate msg;
extern ... | // This module contains traits in layout used generically
// in the rest of Servo.
// The traits are here instead of in layout so
// that these modules won't have to depend on layout.
use gfx::font_cache_thread::FontCacheThread;
use ipc_channel::ipc::{IpcReceiver, IpcSender};
use metrics::PaintTimeMetrics;
use msg... | random_line_split | |
inputmask.date.extensions.js | {
var formatCode = {
d: [ "[1-9]|[12][0-9]|3[01]", Date.prototype.setDate, "day", Date.prototype.getDate ],
dd: [ "0[1-9]|[12][0-9]|3[01]", Date.prototype.setDate, "day", function() {
return pad(Date.prototype.getDate.call(this), 2);
} ],
ddd: [ "" ],
dddd: [ "" ... |
if ("string" == typeof mask) {
for (;match = getTokenizer(opts).exec(format); ) {
var value = mask.slice(0, match[0].length);
formatCode.hasOwnProperty(match[0]) && (targetValidator = formatCode[match[0]][0],
targetProp = formatCode[match[0]][2], dat... | {
dateObj[targetProp] = extendProperty(value), dateObj["raw" + targetProp] = value,
void 0 !== dateOperation && dateOperation.call(dateObj.date, "month" == targetProp ? parseInt(dateObj[targetProp]) - 1 : dateObj[targetProp]);
} | identifier_body |
inputmask.date.extensions.js | {
var formatCode = {
d: [ "[1-9]|[12][0-9]|3[01]", Date.prototype.setDate, "day", Date.prototype.getDate ],
dd: [ "0[1-9]|[12][0-9]|3[01]", Date.prototype.setDate, "day", function() {
return pad(Date.prototype.getDate.call(this), 2);
} ],
ddd: [ "" ],
dddd: [ "" ... | (maskString, format, opts) {
var targetProp, match, dateOperation, targetValidator, dateObj = {
date: new Date(1, 0, 1)
}, mask = maskString;
function extendProperty(value) {
var correctedValue;
if (opts.min && opts.min[targetProp] || opts.max && opts.max[targ... | analyseMask | identifier_name |
inputmask.date.extensions.js | {
var formatCode = {
d: [ "[1-9]|[12][0-9]|3[01]", Date.prototype.setDate, "day", Date.prototype.getDate ],
dd: [ "0[1-9]|[12][0-9]|3[01]", Date.prototype.setDate, "day", function() {
return pad(Date.prototype.getDate.call(this), 2);
} ],
ddd: [ "" ],
dddd: [ "" ... | targetProp = formatCode[match[0]][2], dateOperation = formatCode[match[0]][1], setValue(dateObj, value)),
mask = mask.slice(value.length);
}
return dateObj;
}
}
return Inputmask.extendAliases({
datetime: {
mask: function(opts) ... | var value = mask.slice(0, match[0].length);
formatCode.hasOwnProperty(match[0]) && (targetValidator = formatCode[match[0]][0], | random_line_split |
ui_codificadores_POT.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/Users/chernomirdinmacuvele/Documents/workspace/PscArt2.0.X/UserInt/ui_codificadores_POT.ui'
#
# Created by: PyQt5 UI code generator 5.8.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
... | _translate = QtCore.QCoreApplication.translate
Form.setWindowTitle(_translate("Form", "Codificador"))
self.label.setText(_translate("Form", "Codigo:"))
self.LECodigo.setPlaceholderText(_translate("Form", "Ex:AAA"))
self.label_3.setText(_translate("Form", "Nome:"))
self.LE... | QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form): | random_line_split |
ui_codificadores_POT.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/Users/chernomirdinmacuvele/Documents/workspace/PscArt2.0.X/UserInt/ui_codificadores_POT.ui'
#
# Created by: PyQt5 UI code generator 5.8.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
... | (self, Form):
Form.setObjectName("Form")
Form.resize(306, 332)
self.gridLayout = QtWidgets.QGridLayout(Form)
self.gridLayout.setObjectName("gridLayout")
self.label = QtWidgets.QLabel(Form)
self.label.setObjectName("label")
self.gridLayout.addWidget(self.label, 0, ... | setupUi | identifier_name |
ui_codificadores_POT.py | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/Users/chernomirdinmacuvele/Documents/workspace/PscArt2.0.X/UserInt/ui_codificadores_POT.ui'
#
# Created by: PyQt5 UI code generator 5.8.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
... | self.label_4.setObjectName("label_4")
self.gridLayout.addWidget(self.label_4, 2, 0, 1, 1)
self.PTEDescricao = QtWidgets.QPlainTextEdit(Form)
self.PTEDescricao.setObjectName("PTEDescricao")
self.gridLayout.addWidget(self.PTEDescricao, 2, 1, 1, 1)
self.label_5 = QtWidgets.Q... | def setupUi(self, Form):
Form.setObjectName("Form")
Form.resize(306, 332)
self.gridLayout = QtWidgets.QGridLayout(Form)
self.gridLayout.setObjectName("gridLayout")
self.label = QtWidgets.QLabel(Form)
self.label.setObjectName("label")
self.gridLayout.addWidget(self... | identifier_body |
css_section.rs | // This file was generated by gir (5c017c9) from gir-files (71d73f0)
// DO NOT EDIT
use CssSectionType;
use ffi;
use glib::translate::*;
glib_wrapper! {
pub struct CssSection(Shared<ffi::GtkCssSection>);
match fn {
ref => |ptr| ffi::gtk_css_section_ref(ptr),
unref => |ptr| ffi::gtk_css_sectio... | (&self) -> CssSectionType {
unsafe {
from_glib(ffi::gtk_css_section_get_section_type(self.to_glib_none().0))
}
}
pub fn get_start_line(&self) -> u32 {
unsafe {
ffi::gtk_css_section_get_start_line(self.to_glib_none().0)
}
}
pub fn get_start_positi... | get_section_type | identifier_name |
css_section.rs | // This file was generated by gir (5c017c9) from gir-files (71d73f0)
// DO NOT EDIT
use CssSectionType;
use ffi;
use glib::translate::*;
glib_wrapper! {
pub struct CssSection(Shared<ffi::GtkCssSection>);
match fn {
ref => |ptr| ffi::gtk_css_section_ref(ptr),
unref => |ptr| ffi::gtk_css_sectio... | }
} |
pub fn get_start_position(&self) -> u32 {
unsafe {
ffi::gtk_css_section_get_start_position(self.to_glib_none().0)
} | random_line_split |
css_section.rs | // This file was generated by gir (5c017c9) from gir-files (71d73f0)
// DO NOT EDIT
use CssSectionType;
use ffi;
use glib::translate::*;
glib_wrapper! {
pub struct CssSection(Shared<ffi::GtkCssSection>);
match fn {
ref => |ptr| ffi::gtk_css_section_ref(ptr),
unref => |ptr| ffi::gtk_css_sectio... |
pub fn get_end_position(&self) -> u32 {
unsafe {
ffi::gtk_css_section_get_end_position(self.to_glib_none().0)
}
}
//pub fn get_file(&self) -> /*Ignored*/Option<gio::File> {
// unsafe { TODO: call ffi::gtk_css_section_get_file() }
//}
pub fn get_parent(&self) ->... | {
unsafe {
ffi::gtk_css_section_get_end_line(self.to_glib_none().0)
}
} | identifier_body |
validators.rs | // src/common/validation/validators.rs
/// Validators
// Import Modules
// External
use ::regex::Regex;
/// Check that a field is not supplied, or None
///
/// # Arguments
/// `val` - Option<T> the Option field
///
/// # Returns
/// `bool` - True if valid, false otherwise (None)
pub fn empty<T>(val: &Option<T>) -> b... |
/// Check that two values are identical
///
/// # Arguments
/// `val1` - Generic type T
/// `val2` - Generic type T
///
/// # Returns
/// `bool` - True if valid, false otherwise (None)
pub fn equals<T: PartialEq>(val1: T, val2: T) -> bool{
val1 == val2
}
/// Check if a string matches a regular expression
///
///... | {
match val{
Some(v) => !v.is_empty(),
None => false
}
} | identifier_body |
validators.rs | // src/common/validation/validators.rs
/// Validators
// Import Modules
// External
use ::regex::Regex;
/// Check that a field is not supplied, or None
///
/// # Arguments
/// `val` - Option<T> the Option field
///
/// # Returns
/// `bool` - True if valid, false otherwise (None)
pub fn empty<T>(val: &Option<T>) -> b... | (value: &str, regex: &str) -> bool{
let re = Regex::new(regex).unwrap();
re.is_match(value)
}
| matches | identifier_name |
validators.rs | // src/common/validation/validators.rs
/// Validators
// Import Modules
// External
use ::regex::Regex;
/// Check that a field is not supplied, or None
///
/// # Arguments
/// `val` - Option<T> the Option field
///
/// # Returns
/// `bool` - True if valid, false otherwise (None)
pub fn empty<T>(val: &Option<T>) -> b... | /// Check that a field is not empty
///
/// # Arguments
/// `val` - Option<T> the Option field
///
/// # Returns
/// `bool` - True if valid, false otherwise (None)
pub fn not_empty<T>(val: Option<T>) -> bool{
match val{
Some(_) => true,
None => false
}
}
/// Check that a String field is not emp... | }
}
| random_line_split |
custom-typings.d.ts | /*
* Custom Type Definitions
* When including 3rd party modules you also need to include the type definition for the module
* if they don't provide one within the module. You can try to install it with typings
typings install node --save
* If you can't find the type definition in the registry we can make an ambie... | }
interface NodeModule extends WebpackModule {
} | random_line_split | |
executor.py | """Executor util helpers."""
from __future__ import annotations
from concurrent.futures import ThreadPoolExecutor
import contextlib
import logging
import queue
import sys
from threading import Thread
import time
import traceback
from .thread import async_raise
_LOGGER = logging.getLogger(__name__)
MAX_LOG_ATTEMPTS ... |
attempt += 1
remaining_threads -= join_or_interrupt_threads(
remaining_threads,
timeout_remaining / _JOIN_ATTEMPTS,
attempt <= MAX_LOG_ATTEMPTS,
)
timeout_remaining = EXECUTOR_SHUTDOWN_TIMEOUT - (
time.mo... | return | conditional_block |
executor.py | """Executor util helpers."""
from __future__ import annotations | import contextlib
import logging
import queue
import sys
from threading import Thread
import time
import traceback
from .thread import async_raise
_LOGGER = logging.getLogger(__name__)
MAX_LOG_ATTEMPTS = 2
_JOIN_ATTEMPTS = 10
EXECUTOR_SHUTDOWN_TIMEOUT = 10
def _log_thread_running_at_shutdown(name: str, ident: in... |
from concurrent.futures import ThreadPoolExecutor | random_line_split |
executor.py | """Executor util helpers."""
from __future__ import annotations
from concurrent.futures import ThreadPoolExecutor
import contextlib
import logging
import queue
import sys
from threading import Thread
import time
import traceback
from .thread import async_raise
_LOGGER = logging.getLogger(__name__)
MAX_LOG_ATTEMPTS ... | (self, *args, **kwargs) -> None: # type: ignore
"""Shutdown backport from cpython 3.9 with interrupt support added."""
with self._shutdown_lock: # type: ignore[attr-defined]
self._shutdown = True
# Drain all work items from the queue, and then cancel their
# associa... | shutdown | identifier_name |
executor.py | """Executor util helpers."""
from __future__ import annotations
from concurrent.futures import ThreadPoolExecutor
import contextlib
import logging
import queue
import sys
from threading import Thread
import time
import traceback
from .thread import async_raise
_LOGGER = logging.getLogger(__name__)
MAX_LOG_ATTEMPTS ... | return joined
class InterruptibleThreadPoolExecutor(ThreadPoolExecutor):
"""A ThreadPoolExecutor instance that will not deadlock on shutdown."""
def shutdown(self, *args, **kwargs) -> None: # type: ignore
"""Shutdown backport from cpython 3.9 with interrupt support added."""
with self._... | """Attempt to join or interrupt a set of threads."""
joined = set()
timeout_per_thread = timeout / len(threads)
for thread in threads:
thread.join(timeout=timeout_per_thread)
if not thread.is_alive() or thread.ident is None:
joined.add(thread)
continue
if l... | identifier_body |
pauli_vector.py | import abc
import pytools
from quantumsim.algebra.algebra import dm_to_pv, pv_to_dm
class PauliVectorBase(metaclass=abc.ABCMeta):
| _size_max = 2**22
# noinspection PyUnusedLocal
@abc.abstractmethod
def __init__(self, bases, pv=None, *, force=False):
self.bases = list(bases)
if self.size > self._size_max and not force:
raise ValueError(
'Density matrix of the system is going to have {} it... | """A metaclass, that defines standard interface for Quantumsim density
matrix backend.
Every instance, that implements the interface of this class, should call
`super().__init__` in the beginning of its execution, because a lot of
sanity checks are done here.
Parameters
----------
bases : ... | identifier_body |
pauli_vector.py | import abc
import pytools
from quantumsim.algebra.algebra import dm_to_pv, pv_to_dm
class | (metaclass=abc.ABCMeta):
"""A metaclass, that defines standard interface for Quantumsim density
matrix backend.
Every instance, that implements the interface of this class, should call
`super().__init__` in the beginning of its execution, because a lot of
sanity checks are done here.
Parameter... | PauliVectorBase | identifier_name |
pauli_vector.py | import abc
import pytools
from quantumsim.algebra.algebra import dm_to_pv, pv_to_dm
class PauliVectorBase(metaclass=abc.ABCMeta):
"""A metaclass, that defines standard interface for Quantumsim density
matrix backend.
Every instance, that implements the interface of this class, should call
`super().__... |
# noinspection PyMethodMayBeStatic
def _validate_ptm_shape(self, ptm, target_shape, name):
if ptm.shape != target_shape:
raise ValueError(
"`{name}` shape must be {target_shape}, got {real_shape}"
.format(name=name,
target_shape=targe... | raise ValueError(
"`{name}` number {n} does not exist in the system, "
"it contains {n_qubits} qubits in total."
.format(name=name, n=number, n_qubits=self.n_qubits)) | conditional_block |
pauli_vector.py | import abc
import pytools
from quantumsim.algebra.algebra import dm_to_pv, pv_to_dm
class PauliVectorBase(metaclass=abc.ABCMeta):
"""A metaclass, that defines standard interface for Quantumsim density
matrix backend.
Every instance, that implements the interface of this class, should call
`super().__... | Pauli vector, that represents the density matrix in the selected
bases. If `None`, density matrix is initialized in
:math:`\\left| 0 \\cdots 0 \\right\\rangle` state.
force : bool
By default creation of too large density matrix (more than
:math:`2^22` elements currently) is n... | Parameters
----------
bases : list of quantumsim.bases.PauliBasis
A descrption of the basis for the subsystems.
pv : array or None | random_line_split |
todo.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: MIT. See LICENSE
import frappe
import json
from frappe.model.document import Document
from frappe.utils import get_fullname, parse_addr
exclude_from_linked_with = True
class ToDo(Document):
DocType = 'ToDo'
def validate(self):
self... |
def update_in_reference(self):
if not (self.reference_type and self.reference_name):
return
try:
assignments = frappe.get_all("ToDo", filters={
"reference_type": self.reference_type,
"reference_name": self.reference_name,
"status": ("!=", "Cancelled")
}, pluck="allocated_to")
assignments... | return frappe.db.delete("Communication Link", {
"link_doctype": self.doctype,
"link_name": self.name
}) | identifier_body |
todo.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: MIT. See LICENSE
import frappe
import json
from frappe.model.document import Document
from frappe.utils import get_fullname, parse_addr
exclude_from_linked_with = True
class ToDo(Document):
DocType = 'ToDo'
def validate(self):
self... |
self._assignment = {
"text": removal_message,
"comment_type": "Assignment Completed"
}
def on_update(self):
if self._assignment:
self.add_assign_comment(**self._assignment)
self.update_in_reference()
def on_trash(self):
self.delete_communication_links()
self.update_in_reference()
d... | removal_message = frappe._("Assignment of {0} removed by {1}").format(
get_fullname(self.allocated_to), get_fullname(frappe.session.user)) | conditional_block |
todo.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: MIT. See LICENSE
import frappe
import json
from frappe.model.document import Document
from frappe.utils import get_fullname, parse_addr
exclude_from_linked_with = True
class ToDo(Document):
DocType = 'ToDo'
def validate(self):
self... | @classmethod
def get_owners(cls, filters=None):
"""Returns list of owners after applying filters on todo's.
"""
rows = frappe.get_all(cls.DocType, filters=filters or {}, fields=['allocated_to'])
return [parse_addr(row.allocated_to)[1] for row in rows if row.allocated_to]
# NOTE: todo is viewable if a user is... | else:
raise
| random_line_split |
todo.py | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: MIT. See LICENSE
import frappe
import json
from frappe.model.document import Document
from frappe.utils import get_fullname, parse_addr
exclude_from_linked_with = True
class ToDo(Document):
DocType = 'ToDo'
def validate(self):
self... | (user):
if not user: user = frappe.session.user
todo_roles = frappe.permissions.get_doctype_roles('ToDo')
if 'All' in todo_roles:
todo_roles.remove('All')
if any(check in todo_roles for check in frappe.get_roles(user)):
return None
else:
return """(`tabToDo`.allocated_to = {user} or `tabToDo`.assigned_by =... | get_permission_query_conditions | identifier_name |
voxel_tree.rs | {
mask = mask >> voxel.lg_size;
} else {
// TODO: Check for overflow.
mask = mask << -voxel.lg_size;
}
mask
}
fn find_mut<'a, Step, E>(
&'a mut self,
voxel: &voxel::Bounds,
mut step: Step,
) -> Result<&'a mut TreeBody, E> where
Step: FnMut(&'a mut TreeBody) -> Resu... | grow_is_transparent | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.