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 |
|---|---|---|---|---|
permissions.py | #encoding=utf8
from rest_framework import permissions
from django.contrib import messages
from copy import deepcopy
from rest_framework.permissions import *
def own_object_permission(field_name):
class P(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
print h... |
return P | random_line_split | |
permissions.py | #encoding=utf8
from rest_framework import permissions
from django.contrib import messages
from copy import deepcopy
from rest_framework.permissions import *
def own_object_permission(field_name):
class P(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
print h... | (self, request, view):
result = request.user.is_authenticated() and request.user.has_perm(perm)
if not result:
messages.warning(request._request, u'啊哦,亲~这里不允许访问啵~你要有更厉害的权限才行哟')
return result
return P | has_permission | identifier_name |
permissions.py | #encoding=utf8
from rest_framework import permissions
from django.contrib import messages
from copy import deepcopy
from rest_framework.permissions import *
def own_object_permission(field_name):
class P(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
print h... |
else:
return False
return P
def own_object_or_superuser_permission(field_name):
class P(permissions.BasePermission):
def has_object_permission(self, request, view, obj):
if request.user.is_superuser or hasattr(obj, field_name) and getattr(obj, field_name) ==... | return True | conditional_block |
shared_spec.ts | /**
* @license
* Copyright Google LLC 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 {createLView, createTNode, createTView} from '@angular/core/src/render3/instructions/shared';
import {TNodeTyp... |
function emptyTemplate() {}
| {
setBindingIndex(getBindingRoot());
} | identifier_body |
shared_spec.ts | /**
* @license
* Copyright Google LLC 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 {createLView, createTNode, createTView} from '@angular/core/src/render3/instructions/shared';
import {TNodeType} from '@angular/core/src/render3/interfaces/node';
import {domRendererFactory3} from '@angular/core/src/render3/interfaces/renderer';
import {HEADER_OFFSET, LViewFlags, TVIEW, TViewType} from '@angular... | */
| random_line_split |
shared_spec.ts | /**
* @license
* Copyright Google LLC 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 {createLView, createTNode, createTView} from '@angular/core/src/render3/instructions/shared';
import {TNodeTyp... | () {}
| emptyTemplate | identifier_name |
template-param-usage-9.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct DoesNotUse {
pub _address: u8,
}
pub type DoesNotUse_Aliased<T> = T;
pub type DoesNotUse_Typedefed<U> = U;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub s... | let mut s = ::std::mem::MaybeUninit::<Self>::uninit();
unsafe {
::std::ptr::write_bytes(s.as_mut_ptr(), 0, 1);
s.assume_init()
}
}
} | fn default() -> Self { | random_line_split |
template-param-usage-9.rs | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct DoesNotUse {
pub _address: u8,
}
pub type DoesNotUse_Aliased<T> = T;
pub type DoesNotUse_Typedefed<U> = U;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub s... | <T, U> {
pub member: DoesNotUse_Aliased<T>,
pub another: DoesNotUse_Typedefed<U>,
pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell<T>>,
pub _phantom_1: ::std::marker::PhantomData<::std::cell::UnsafeCell<U>>,
}
impl<T, U> Default for DoesNotUse_IndirectUsage<T, U> {
fn default() -> ... | DoesNotUse_IndirectUsage | identifier_name |
replace.ts | /* eslint-disable unicorn/consistent-function-scoping */
import { ensure, isDefined, isString } from 'tiny-types';
import { AnswersQuestions } from '../../../actor';
import { Answerable } from '../../../Answerable';
import { AnswerMappingFunction } from '../AnswerMappingFunction';
/**
* @desc
* Returns a new strin... |
return Promise.all([
actor.answer(pattern),
actor.answer(replacement),
]).then(([p, r]) =>
value.replace(p, r as any),
);
}
} | (value: string) => {
ensure('The value to be mapped', value, isDefined(), isString()) | random_line_split |
replace.ts | /* eslint-disable unicorn/consistent-function-scoping */
import { ensure, isDefined, isString } from 'tiny-types';
import { AnswersQuestions } from '../../../actor';
import { Answerable } from '../../../Answerable';
import { AnswerMappingFunction } from '../AnswerMappingFunction';
/**
* @desc
* Returns a new strin... | {
return (actor: AnswersQuestions) =>
(value: string) => {
ensure('The value to be mapped', value, isDefined(), isString())
return Promise.all([
actor.answer(pattern),
actor.answer(replacement),
]).then(([p, r]) =>
value.re... | identifier_body | |
replace.ts | /* eslint-disable unicorn/consistent-function-scoping */
import { ensure, isDefined, isString } from 'tiny-types';
import { AnswersQuestions } from '../../../actor';
import { Answerable } from '../../../Answerable';
import { AnswerMappingFunction } from '../AnswerMappingFunction';
/**
* @desc
* Returns a new strin... | (pattern: Answerable<RegExp | string>, replacement: Answerable<string | ((substring: string, ...args: any[]) => string)>): AnswerMappingFunction<string, string> {
return (actor: AnswersQuestions) =>
(value: string) => {
ensure('The value to be mapped', value, isDefined(), isString())
... | replace | identifier_name |
custom.rs | //! Custom RLE compressed recording format
//!
//! This works by pushing all bits read by the CPU onto bit vectors, and comparing the data read in
//! each frame with the data from the last frame.
//!
//! Each entry we write to the recording is prefixed by the number of frames after the previous
//! entry the new entry... | (reader: Box<BufRead>, _snes: &Snes) -> io::Result<Self> {
Ok(Replayer {
reader: reader,
})
}
fn replay_frame(&mut self, ports: &mut Ports) -> io::Result<()> {
unimplemented!()
}
}
| new | identifier_name |
custom.rs | //! Custom RLE compressed recording format
//!
//! This works by pushing all bits read by the CPU onto bit vectors, and comparing the data read in
//! each frame with the data from the last frame.
//!
//! Each entry we write to the recording is prefixed by the number of frames after the previous
//! entry the new entry... | reader: reader,
})
}
fn replay_frame(&mut self, ports: &mut Ports) -> io::Result<()> {
unimplemented!()
}
} |
impl super::Replayer for Replayer {
fn new(reader: Box<BufRead>, _snes: &Snes) -> io::Result<Self> {
Ok(Replayer { | random_line_split |
unilateral.rs | use crate::{
algo::TarjanScc,
core::{
property::{
proxy_remove_edge_where_weight, proxy_remove_vertex, HasVertexGraph, RemoveEdge,
RemoveVertex, Subgraph, Weak,
},
Directed, Ensure, Graph, GraphDerefMut,
},
};
use std::borrow::Borrow;
/// A marker trait for graphs that are unilaterally connected.
///
//... | (c: Self::Ensured, _: ()) -> Self
{
Self(c)
}
fn validate(c: &Self::Ensured, _: &()) -> bool
{
if let Ok(graph) = HasVertexGraph::ensure(c.graph(), ())
{
// Algorithm: First use Tarjan's Strongly Connected Component (SCC) algorithm to
// find SCCs and then check whether every component has an edge to t... | ensure_unvalidated | identifier_name |
unilateral.rs | use crate::{
algo::TarjanScc,
core::{
property::{
proxy_remove_edge_where_weight, proxy_remove_vertex, HasVertexGraph, RemoveEdge,
RemoveVertex, Subgraph, Weak,
},
Directed, Ensure, Graph, GraphDerefMut,
},
};
use std::borrow::Borrow;
/// A marker trait for graphs that are unilaterally connected.
///
//... | where
C::Graph: Graph<Directedness = Directed>;
impl<C: Ensure> Ensure for UnilateralGraph<C>
where
C::Graph: Graph<Directedness = Directed>,
{
fn ensure_unvalidated(c: Self::Ensured, _: ()) -> Self
{
Self(c)
}
fn validate(c: &Self::Ensured, _: &()) -> bool
{
if let Ok(graph) = HasVertexGraph::ensure(c.gra... | pub struct UnilateralGraph<C: Ensure>(C) | random_line_split |
unilateral.rs | use crate::{
algo::TarjanScc,
core::{
property::{
proxy_remove_edge_where_weight, proxy_remove_vertex, HasVertexGraph, RemoveEdge,
RemoveVertex, Subgraph, Weak,
},
Directed, Ensure, Graph, GraphDerefMut,
},
};
use std::borrow::Borrow;
/// A marker trait for graphs that are unilaterally connected.
///
//... | }
scc_current = scc_next;
}
}
true
}
}
impl<C: Ensure + GraphDerefMut> RemoveVertex for UnilateralGraph<C>
where
C::Graph: RemoveVertex<Directedness = Directed>,
{
fn remove_vertex(&mut self, v: impl Borrow<Self::Vertex>) -> Result<Self::VertexWeight, ()>
{
proxy_remove_vertex::<UnilateralGraph<_... | {
// Algorithm: First use Tarjan's Strongly Connected Component (SCC) algorithm to
// find SCCs and then check whether every component has an edge to the next one
// in the list. Note: Tarjan's algorithm produces SCCs in reverse topological
// order, so we don't need to sort, just check the first has an ed... | conditional_block |
unilateral.rs | use crate::{
algo::TarjanScc,
core::{
property::{
proxy_remove_edge_where_weight, proxy_remove_vertex, HasVertexGraph, RemoveEdge,
RemoveVertex, Subgraph, Weak,
},
Directed, Ensure, Graph, GraphDerefMut,
},
};
use std::borrow::Borrow;
/// A marker trait for graphs that are unilaterally connected.
///
//... |
fn validate(c: &Self::Ensured, _: &()) -> bool
{
if let Ok(graph) = HasVertexGraph::ensure(c.graph(), ())
{
// Algorithm: First use Tarjan's Strongly Connected Component (SCC) algorithm to
// find SCCs and then check whether every component has an edge to the next one
// in the list. Note: Tarjan's al... | {
Self(c)
} | identifier_body |
test_liveness.py | import graph
import dot
from core import *
import dataflow
def make_inst(g, addr, dest, op, *args):
def make_arg(a):
if a is None:
return None
if isinstance(a, int):
return VALUE(a)
if isinstance(a, str):
return REG(a)
return a
b = BBlock(add... | for i, info in g.iter_sorted_nodes():
assert info["live_gen"] == GEN_LV[i]
assert info["live_kill"] == KILL_LV[i]
assert info["live_in"] == LV_entry[i], (info["live_in"], LV_entry[i])
assert info["live_out"] == LV_exit[i] | 7: {REG("x")},
}
| random_line_split |
test_liveness.py | import graph
import dot
from core import *
import dataflow
def make_inst(g, addr, dest, op, *args):
def make_arg(a):
if a is None:
return None
if isinstance(a, int):
return VALUE(a)
if isinstance(a, str):
return REG(a)
return a
b = BBlock(add... | ():
g = graph.Graph()
make_inst(g, 1, "x", "=", 2)
make_inst(g, 2, "y", "=", 4)
make_inst(g, 3, "x", "=", 1)
make_inst(g, 4, None, "if", COND(EXPR(">", REG("x"), REG("y"))))
make_inst(g, 5, "z", "=", REG("y"))
make_inst(g, 6, "z", "*", REG("y"), REG("y"))
make_inst(g, 7, "x", "=", REG("z... | test_nielson_2_1_4 | identifier_name |
test_liveness.py | import graph
import dot
from core import *
import dataflow
def make_inst(g, addr, dest, op, *args):
|
def test_nielson_2_1_4():
g = graph.Graph()
make_inst(g, 1, "x", "=", 2)
make_inst(g, 2, "y", "=", 4)
make_inst(g, 3, "x", "=", 1)
make_inst(g, 4, None, "if", COND(EXPR(">", REG("x"), REG("y"))))
make_inst(g, 5, "z", "=", REG("y"))
make_inst(g, 6, "z", "*", REG("y"), REG("y"))
make_ins... | def make_arg(a):
if a is None:
return None
if isinstance(a, int):
return VALUE(a)
if isinstance(a, str):
return REG(a)
return a
b = BBlock(addr)
args = [make_arg(a) for a in args]
b.add(Inst(make_arg(dest), op, args, addr))
g.add_node(a... | identifier_body |
test_liveness.py | import graph
import dot
from core import *
import dataflow
def make_inst(g, addr, dest, op, *args):
def make_arg(a):
if a is None:
|
if isinstance(a, int):
return VALUE(a)
if isinstance(a, str):
return REG(a)
return a
b = BBlock(addr)
args = [make_arg(a) for a in args]
b.add(Inst(make_arg(dest), op, args, addr))
g.add_node(addr, val=b)
def test_nielson_2_1_4():
g = graph.Graph()
... | return None | conditional_block |
patient-relationship-type-resource.service.spec.ts | import { TestBed } from '@angular/core/testing';
import { LocalStorageService } from '../utils/local-storage.service';
import { AppSettingsService } from '../app-settings/app-settings.service';
import { PatientRelationshipTypeResourceService } from './patient-relationship-type-resource.service';
import {
HttpClientTe... |
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
PatientRelationshipTypeResourceService,
AppSettingsService,
LocalStorageService
],
imports: [HttpClientTestingModule]
});
service = TestBed.get(PatientRelationshipTypeResourceService);
httpMock... |
describe('Service: Pratient Relationship ResourceService', () => {
let service: PatientRelationshipTypeResourceService;
let httpMock: HttpTestingController; | random_line_split |
tls.py | _size:
return client_hello[:client_hello_size]
return None
def parse_client_hello(data: bytes) -> Optional[net_tls.ClientHello]:
"""
Check if the supplied bytes contain a full ClientHello message,
and if so, parse it.
Returns:
- A ClientHello object on success
- No... |
def start_tls(self) -> layer.CommandGenerator[None]:
assert not self.tls
tls_start = TlsStartData(self.conn, self.context)
if tls_start.conn == tls_start.context.client:
yield TlsStartClientHook(tls_start)
else:
yield TlsStartServerHook(tls_start)
i... | return super().__repr__().replace(")", f" {self.conn.sni} {self.conn.alpn})") | identifier_body |
tls.py | _size:
return client_hello[:client_hello_size]
return None
def parse_client_hello(data: bytes) -> Optional[net_tls.ClientHello]:
"""
Check if the supplied bytes contain a full ClientHello message,
and if so, parse it.
Returns:
- A ClientHello object on success
- No... |
return None
HTTP1_ALPNS = (b"http/1.1", b"http/1.0", b"http/0.9")
HTTP_ALPNS = (b"h2",) + HTTP1_ALPNS
# We need these classes as hooks can only have one argument at the moment.
@dataclass
class ClientHelloData:
context: context.Context
"""The context object for this connection."""
client_hello: ne... | try:
return net_tls.ClientHello(client_hello[4:])
except EOFError as e:
raise ValueError("Invalid ClientHello") from e | conditional_block |
tls.py | server
# side, the peer's certificate must be obtained separately using SSL_get_peer_certificate(3).
all_certs = self.tls.get_peer_cert_chain() or []
if self.conn == self.context.client:
cert = self.tls.get_peer_certificate()
if cert:
... | yer(_TL | identifier_name | |
tls.py | _size:
return client_hello[:client_hello_size]
return None
def parse_client_hello(data: bytes) -> Optional[net_tls.ClientHello]:
"""
Check if the supplied bytes contain a full ClientHello message,
and if so, parse it.
Returns:
- A ClientHello object on success
- No... | class _TLSLayer(tunnel.TunnelLayer):
tls: SSL.Connection = None # type: ignore
"""The OpenSSL connection object"""
def __init__(self, context: context.Context, conn: connection.Connection):
super().__init__(
context,
tunnel_connection=conn,
conn=conn,
)
... | random_line_split | |
dev-runner.js | 'use strict'
const chalk = require('chalk')
const electron = require('electron')
const path = require('path')
const { say } = require('cfonts')
const { spawn } = require('child_process')
const webpack = require('webpack')
const WebpackDevServer = require('webpack-dev-server')
const webpackHotMiddleware = require('webp... |
const compiler = webpack(mainConfig)
compiler.plugin('watch-run', (compilation, done) => {
logStats('Main', chalk.white.bold('compiling...'))
hotMiddleware.publish({ action: 'compiling' })
done()
})
compiler.watch({}, (err, stats) => {
if (err) {
console.log(err)
... | }else{
mainConfig.entry.main = [path.join(__dirname, '../src/main/index.proxy.js')].concat(mainConfig.entry.main)
}
| random_line_split |
dev-runner.js | 'use strict'
const chalk = require('chalk')
const electron = require('electron')
const path = require('path')
const { say } = require('cfonts')
const { spawn } = require('child_process')
const webpack = require('webpack')
const WebpackDevServer = require('webpack-dev-server')
const webpackHotMiddleware = require('webp... | }
)
server.listen(9080)
})
}
function startMain() {
return new Promise((resolve, reject) => {
if (process.argv.slice(2).indexOf('--proxy') < 0) {
mainConfig.entry.main = [path.join(__dirname, '../src/main/index.dev.js')].concat(mainConfig.entry.main)
}else{
mainConfig.entry.main = [... | app.use(hotMiddleware)
ctx.middleware.waitUntilValid(() => {
resolve()
})
}
| identifier_body |
dev-runner.js | 'use strict'
const chalk = require('chalk')
const electron = require('electron')
const path = require('path')
const { say } = require('cfonts')
const { spawn } = require('child_process')
const webpack = require('webpack')
const WebpackDevServer = require('webpack-dev-server')
const webpackHotMiddleware = require('webp... |
electronProcess = spawn(electron, ['--inspect=5858', path.join(__dirname, '../dist/electron/main.js')])
electronProcess.stdout.on('data', data => {
electronLog(data, 'blue')
})
electronProcess.stderr.on('data', data => {
electronLog(data, 'red')
})
electronProcess.on('close', () => {
if (!man... | tElectron() { | identifier_name |
queue.py | ][0]
def get_unsubscribe_message(unsubscribe_message, expose_recipients):
if not unsubscribe_message:
unsubscribe_message = _("Unsubscribe from this list")
html = """<div style="margin: 15px auto; padding: 0px 7px; text-align: center; color: #8d99a6;">
<!--cc message-->
<p style="margin: 15px auto;">
<a... | message = email.message
if email.add_unsubscribe_link and email.reference_doctype: # is missing the check for unsubscribe message but will not add as there will be no unsubscribe url
unsubscribe_url = get_unsubcribed_url(email.reference_doctype, email.reference_name, recipient,
email.unsubscribe_method, email.unsu... | identifier_body | |
queue.py | :
email_queue = get_email_queue(recipients, sender, subject, **kwargs)
if kwargs.get('now'):
send_one(email_queue.name, now=True)
def get_email_queue(recipients, sender, subject, **kwargs):
'''Make Email Queue object'''
e = frappe.new_doc('Email Queue')
e.priority = kwargs.get('send_priority')
try:
mail ... | frappe.db.sql("""update `tabEmail Queue` set status='Error', error=%s
where name=%s""", ("No recipients to send to", email.name), auto_commit=auto_commit) | conditional_block | |
queue.py | margin: 15px auto; padding: 0px 7px; text-align: center; color: #8d99a6;">
<!--cc message-->
<p style="margin: 15px auto;">
<a href="<!--unsubscribe url-->" style="color: #8d99a6; text-decoration: underline;
target="_blank">{unsubscribe_message}
</a>
</p>
</div>""".format(unsubscribe_message=uns... | clear_outbox | identifier_name | |
queue.py | add_days(nowdate(), send_after)
email_account = get_outgoing_email_account(True, append_to=reference_doctype)
if not sender or sender == "Administrator":
sender = email_account.default_sender
check_email_limit(recipients)
formatted = get_formatted_html(subject, message, email_account=email_account)
try:
t... | else:
unsubscribed = []
recipients = [r for r in list(set(recipients)) if r and r not in unsubscribed]
email_content = formatted
email_text_context = text_content
if add_unsubscribe_link and reference_doctype and (unsubscribe_message or reference_doctype=="Newsletter") and add_unsubscribe_link==1:
unsubscri... | unsubscribed += [d.email for d in frappe.db.get_all("Email Unsubscribe", "email",
{"global_unsubscribe": 1})] | random_line_split |
BindableTestCaseTplScript.js | /*
* Copyright 2013 Amadeus s.a.s.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to i... |
this.data.keystrokes.push(value);
},
somethingOnBlur : function () {
this.data.wasBlurred = true;
}
}
});
| {
this.data.keystrokes = [];
} | conditional_block |
BindableTestCaseTplScript.js | /*
* Copyright 2013 Amadeus s.a.s.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to i... | }
}); | random_line_split | |
expression-014.js | /**
File Name: expression-014.js
Corresponds To: ecma/Expressions/11.2.2-9-n.js
ECMA Section: 11.2.2. The new operator
Description:
Author: christine@netscape.com
Date: 12 november 1997
*/
var SECTION = "expression-014.js";
var VERSION = "ECM... |
test(); | " (threw " + exception +")",
expect,
result ); | random_line_split |
inline.rs | def::DefTy(did, true) => {
record_extern_fqn(cx, did, clean::TypeEnum);
ret.extend(build_impls(cx, tcx, did));
build_type(cx, tcx, did)
}
// Assume that the enum type is reexported next to the variant, and
// variants don't show up in documentation spe... | (cx: &DocContext, tcx: &ty::ctxt, did: ast::DefId) -> clean::ItemEnum {
let t = tcx.lookup_item_type(did);
let predicates = tcx.lookup_predicates(did);
match t.ty.sty {
ty::TyEnum(edef, _) if !csearch::is_typedef(&tcx.sess.cstore, did) => {
return clean::EnumItem(clean::Enum {
... | build_type | identifier_name |
inline.rs | s.borrow_mut().insert(did.krate) {
csearch::each_top_level_item_of_crate(&tcx.sess.cstore,
did.krate,
|def, _, _| {
populate_impls(cx, tcx, def, &mut impls)
});
fn populate_impls(cx: &DocCont... | {clean::Immutable} | conditional_block | |
inline.rs | let did = def.def_id();
let inner = match def {
def::DefTrait(did) => {
record_extern_fqn(cx, did, clean::TypeTrait);
clean::TraitItem(build_external_trait(cx, tcx, did))
}
def::DefFn(did, false) => {
// If this function is a tuple struct constructor, ... | let mut ret = Vec::new(); | random_line_split | |
inline.rs | Item {
inner: clean::DefaultImplItem(clean::DefaultImpl {
// FIXME: this should be decoded
unsafety: ast::Unsafety::Normal,
trait_: match associated_trait.as_ref().unwrap().clean(cx) {
clean::TraitBound(polyt, _) => polyt.trait_,
... | {
let mut ty_bounds = Vec::new();
g.where_predicates.retain(|pred| {
match *pred {
clean::WherePredicate::BoundPredicate {
ty: clean::Generic(ref s),
ref bounds
} if *s == "Self" => {
ty_bounds.extend(bounds.iter().cloned());
... | identifier_body | |
robotServer.js | var fs = require('fs')
net = require('net')
child = require('child_process')
spawn = child.spawn
exec = child.exec
var robot_ip = '20.10.10.115',
robot_name = 'raspberry pi',
robot_port = 5002
var server_ip = '192.168.2.2',
server_name = 'drewpi',
server_port =... | }) | console.log('Server open at: %j\n', address)
| random_line_split |
robotServer.js |
var fs = require('fs')
net = require('net')
child = require('child_process')
spawn = child.spawn
exec = child.exec
var robot_ip = '20.10.10.115',
robot_name = 'raspberry pi',
robot_port = 5002
var server_ip = '192.168.2.2',
server_name = 'drewpi',
server_port ... |
})
})
socket.on('end', function()
{
console.log('disconnected')
})
});
server.listen(robot_port, robot_ip, function(){
address = server.address()
console.log('Server open at: %j\n', address)
})
| {
console.log(err)
} | conditional_block |
SignUpForm.tsx | import {
createStyles,
FormControl,
Input,
InputAdornment,
InputLabel,
Theme,
WithStyles,
} from '@material-ui/core';
import Button from '@material-ui/core/Button';
import Divider from '@material-ui/core/Divider';
import IconButton from '@material-ui/core/IconButton';
import Paper from '@material-ui/core/Paper';... | />
<TextField
id="confirmEmail"
name="confirmEmail"
label="Confirmar email"
margin="normal"
fullWidth
onChange={handleChange('confirmEmail')}
/>
<FormControl fullWidth margin="normal">
<InputLabel htmlFor="password">Senha</InputLabel>
<Input
id="password"
... | fullWidth
onChange={handleChange('email')} | random_line_split |
individual.py | import logging
from ..report.individual import IndividualReport
class | (object):
logger = logging.getLogger("ddvt.rep_gen.ind")
def __init__(self, test):
self.test = test
async def generate(self, parent):
test_group = None
try:
test_group = self.test(parent.filename)
except OSError as e:
parent.report.valid = False
parent.report.reports.append(Ind... | IndividualGenerator | identifier_name |
individual.py | import logging
from ..report.individual import IndividualReport
class IndividualGenerator(object):
| except Exception as e:
self.logger.warning("failed test")
parent.report.valid = False
parent.report.reports.append(IndividualReport(test, 0,
{'error': str(e)}))
| logger = logging.getLogger("ddvt.rep_gen.ind")
def __init__(self, test):
self.test = test
async def generate(self, parent):
test_group = None
try:
test_group = self.test(parent.filename)
except OSError as e:
parent.report.valid = False
parent.report.reports.append(IndividualRepor... | identifier_body |
individual.py | import logging
from ..report.individual import IndividualReport
class IndividualGenerator(object):
logger = logging.getLogger("ddvt.rep_gen.ind")
def __init__(self, test):
self.test = test
async def generate(self, parent):
test_group = None
try:
test_group = self.test(parent.filename)
ex... | self.logger.info("Starting Test: {}".format(test))
try:
result, status = getattr(test_group, test)()
parent.report.reports.append(IndividualReport(test, status, result))
# TODO: Figure out what to do next
except Exception as e:
self.logger.warning("failed test")
paren... | conditional_block | |
individual.py | import logging
from ..report.individual import IndividualReport |
def __init__(self, test):
self.test = test
async def generate(self, parent):
test_group = None
try:
test_group = self.test(parent.filename)
except OSError as e:
parent.report.valid = False
parent.report.reports.append(IndividualReport("FileValid", 0,
... |
class IndividualGenerator(object):
logger = logging.getLogger("ddvt.rep_gen.ind") | random_line_split |
missing_symbols.py | """
Copyright (c) 2016 Genome Research Ltd.
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, distr... | time.sleep(rate_limit - diff)
PREV_TIME = time.time()
def get_gene_id(chrom, start_pos, end_pos, build="grch37", verbose=False, attempts=0):
"""find the hgnc symbol overlapping a variant position
Args:
variant: data frame or list for a variant, containing columns named
... |
global PREV_TIME
diff = time.time() - PREV_TIME
if diff < rate_limit: | random_line_split |
missing_symbols.py | """
Copyright (c) 2016 Genome Research Ltd.
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, distr... | symbols[de_novos["symbol"] == ""] = missing
# 360 out of 17000 de novos still lack HGNC symbols. Their consequences are:
#
# consequence count
# ======================== =====
# downstream_gene_variant 17
# intergenic_variant 259
# regulatory... | """ adds gene symbols to variants lacking them.
Args:
de_novos: dataframe of de novo variants
build: whether to use the 'grch37' or 'grch38' build (default=GRCh37)
Returns:
pandas Series of HGNC symbols, with additional annotations for many
variants previously lacking a... | identifier_body |
missing_symbols.py | """
Copyright (c) 2016 Genome Research Ltd.
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, distr... | (url, headers):
""" open url with python libraries
Args:
url:
headers:
Returns:
tuple of http response, http response code, and http headers
"""
req = request.Request(url, headers=headers)
try:
handler = request.urlopen(req)
except HTTPErro... | open_url | identifier_name |
missing_symbols.py | """
Copyright (c) 2016 Genome Research Ltd.
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, distr... |
rate_limit_requests()
# define parts of the URL
ext = "overlap/region/human/{0}:{1}-{2}?feature=gene".format(chrom, start_pos, end_pos)
server_dict = {"grch37": "grch37.", "grch38": ""}
base_url = "http://{}rest.ensembl.org".format(server_dict[build])
url = "{0}/{1}".format(base_url, ... | raise ValueError("too many attempts, figure out why its failing") | conditional_block |
api.js | import { stringify } from 'qs'
import _request from '@/utils/request'
import mini from '@/utils/mini'
import env from '@/config/env'
// import { modelApis, commonParams } from './model'
// import { version } from '../package.json'
let apiBaseUrl
apiBaseUrl = `${env.apiBaseUrl}`
const regHttp = /^https?/i
const isMoc... |
/**
* API 命名规则
* - 使用 camelCase 命名格式(小驼峰命名)
* - 命名尽量对应 RESTful 风格,`${动作}${资源}`
* - 假数据增加 fake 前缀
* - 便捷易用大于规则,程序是给人看的
*/
// api 列表
const modelApis = {
// 初始化配置
test: 'https://easy-mock.com/mock/5aa79bf26701e17a67bde1d7/',
getConfig: '/common/initconfig',
getWxSign: '/common/getwxsign',
// 积分兑换
getP... | {
const originUrl = regHttp.test(url) ? url : `${apiBaseUrl}${url}`
return _request(originUrl, compact(options), success, fail)
} | identifier_body |
api.js | import { stringify } from 'qs'
import _request from '@/utils/request'
import mini from '@/utils/mini'
import env from '@/config/env'
// import { modelApis, commonParams } from './model'
// import { version } from '../package.json'
let apiBaseUrl
apiBaseUrl = `${env.apiBaseUrl}`
const regHttp = /^https?/i
const isMoc... | identifier_name | ||
api.js | import { stringify } from 'qs'
import _request from '@/utils/request'
import mini from '@/utils/mini'
import env from '@/config/env'
// import { modelApis, commonParams } from './model'
// import { version } from '../package.json'
let apiBaseUrl
apiBaseUrl = `${env.apiBaseUrl}`
const regHttp = /^https?/i
const isMoc... | logout: 'POST /user/logout',
// 地址管理
addressList: '/user/addresslist',
addAddress: 'POST /user/addaddress',
updateAddress: 'POST /user/updateaddress',
setDefaultAddress: 'POST /user/setdefaultaddress',
deleteAddress: 'POST /user/deleteaddress',
provinceList: '/nation/provincelist',
cityList: '/nation/... | refundInit: '/refund/init',
refundDetail: '/refund/detail',
refundApply: 'POST /refund/apply',
// 登录注销
login: 'POST /user/login', | random_line_split |
dialogue.pane.component.spec.ts | import { ComponentFixture, TestBed } from '@angular/core/testing';
import { AmexiodialogueKeyPaneComponent } from './dialogue.pane.component';
import { LifeCycleBaseComponent } from '../../base/lifecycle.base.component';
import { AmexioFooterComponent } from '../action/pane.action.footer';
import {CommonIconComponent} ... |
}); | }); | random_line_split |
setup.py | from setuptools import setup, find_packages
from helga_spook import __version__ as version
setup(name='helga-spook',
version=version,
description=('prints nsa buzzwords'),
classifiers=['Development Status :: 4 - Beta',
'License :: OSI Approved :: GNU General Public License v3 (GPL... | ],
),
) | entry_points = dict(
helga_plugins=[
'spook = helga_spook.plugin:spook', | random_line_split |
page.py | 000000
vmemmap: gdb.Value
directmap_base = 0xffff880000000000
pageflags: Dict[str, int] = dict()
PG_tail = -1
PG_slab = -1
PG_lru = -1
setup_page_type_done = False
setup_pageflags_done = False
setup_pageflags_finish_done = False
ZONES_WIDTH = -1
NODES_WIDTH = -1
# TODO... |
cls.PAGE_SIZE = 1 << cls.PAGE_SHIFT
cls.slab_cache_name = find_member_variant(gdbtype, ['slab_cache', 'lru'])
cls.slab_page_name = find_member_variant(gdbtype, ['slab_page', 'lru'])
cls.compound_head_name = find_member_variant(gdbtype, ['compound_head', 'first_page'])
if not h... | cls.PAGE_SHIFT = 16
# also a config
cls.directmap_base = 0xc000000000000000
cls.sparsemem = True
cls.SECTION_SIZE_BITS = 24 | conditional_block |
page.py | 0000000
vmemmap: gdb.Value
directmap_base = 0xffff880000000000
pageflags: Dict[str, int] = dict()
PG_tail = -1
PG_slab = -1
PG_lru = -1
setup_page_type_done = False
setup_pageflags_done = False | NODES_WIDTH = -1
# TODO have arch provide this?
BITS_PER_LONG = -1
PAGE_SIZE = 4096
PAGE_SHIFT = 12
sparsemem = False
SECTION_SIZE_BITS = -1 # Depends on sparsemem=True
SECTIONS_PER_ROOT = -1 # Depends on SPARSEMEM_EXTREME
_is_tail: Callable[['Page'], bool]
_compound_head: Cal... | setup_pageflags_finish_done = False
ZONES_WIDTH = -1 | random_line_split |
page.py | 000000
vmemmap: gdb.Value
directmap_base = 0xffff880000000000
pageflags: Dict[str, int] = dict()
PG_tail = -1
PG_slab = -1
PG_lru = -1
setup_page_type_done = False
setup_pageflags_done = False
setup_pageflags_finish_done = False
ZONES_WIDTH = -1
NODES_WIDTH = -1
# TODO... | (self) -> bool:
return bool(self.flags & self.PG_tail)
def __is_tail_compound_head_bit(self) -> bool:
return bool(self.gdb_obj['compound_head'] & 1)
def is_tail(self) -> bool:
return self._is_tail()
def is_slab(self) -> bool:
return bool(self.flags & self.PG_slab)
def... | __is_tail_flag | identifier_name |
page.py | slab_cache', 'lru'])
cls.slab_page_name = find_member_variant(gdbtype, ['slab_page', 'lru'])
cls.compound_head_name = find_member_variant(gdbtype, ['compound_head', 'first_page'])
if not hasattr(cls, 'vmemmap'):
cls.vmemmap = gdb.Value(cls.vmemmap_base).cast(gdbtype.pointer())
... | max_pfn = int(symvals.max_pfn)
for pfn in range(max_pfn):
try:
yield (Page.pfn_to_page(pfn), pfn)
except gdb.error:
# TODO: distinguish pfn_valid() and report failures for those?
pass | identifier_body | |
assignmentCompatWithCallSignatures5.ts | // checking assignment compat for function types. No errors in this file
class Base { foo: string; }
class | extends Base { bar: string; }
class Derived2 extends Derived { baz: string; }
class OtherDerived extends Base { bing: string; }
var a: <T>(x: T) => T[];
var a2: <T>(x: T) => string[];
var a3: <T>(x: T) => void;
var a4: <T,U>(x: T, y: U) => string;
var a5: <T,U>(x: (arg: T) => U) => T;
var a6: <T extends Base... | Derived | identifier_name |
assignmentCompatWithCallSignatures5.ts | // checking assignment compat for function types. No errors in this file
class Base { foo: string; }
class Derived extends Base { bar: string; }
class Derived2 extends Derived { baz: string; }
class OtherDerived extends Base { bing: string; }
var a: <T>(x: T) => T[];
var a2: <T>(x: T) => string[];
var a3: <T... | <T extends Derived>(x: (a: T) => T): T[];
<T extends Base>(x: (a: T) => T): T[];
};
var a18: {
(x: {
<T extends Derived>(a: T): T;
<T extends Base>(a: T): T;
}): any[];
(x: {
<T extends Derived2>(a: T): T;
<T extends Base>(a: T): T;
}): any[];
... | random_line_split | |
ga.rs | extern crate rand;
extern crate evo;
extern crate petgraph;
extern crate graph_annealing;
use rand::{Rng, SeedableRng};
use rand::isaac::Isaac64Rng;
use evo::{Evaluator, Individual, MinFitness, OpCrossover1, OpMutate, OpSelect,
OpSelectRandomIndividual, OpVariation, Probability, ProbabilityValue, RatedPopul... | VariationMethod::Reproduction
}
}
}
// XXX: No need for Fitness
impl<I: Individual, F: PartialOrd> OpSelectRandomIndividual<I, F> for Toolbox {
fn select_random_individual(&mut self, population: &RatedPopulation<I, F>) -> usize {
// let (idx, _) = tournament_selection(&mut self.rng,... | random_line_split | |
ga.rs | extern crate rand;
extern crate evo;
extern crate petgraph;
extern crate graph_annealing;
use rand::{Rng, SeedableRng};
use rand::isaac::Isaac64Rng;
use evo::{Evaluator, Individual, MinFitness, OpCrossover1, OpMutate, OpSelect,
OpSelectRandomIndividual, OpVariation, Probability, ProbabilityValue, RatedPopul... |
let filename = format!("line_{:04}.svg", gen);
let ind = pop.get_individual(pop.fittest());
draw_graph(&ind.to_graph(), &filename);
}
let _optimum = evo::ea_mu_plus_lambda(&mut toolbox,
&evaluator,
rat... | {
return;
} | conditional_block |
ga.rs | extern crate rand;
extern crate evo;
extern crate petgraph;
extern crate graph_annealing;
use rand::{Rng, SeedableRng};
use rand::isaac::Isaac64Rng;
use evo::{Evaluator, Individual, MinFitness, OpCrossover1, OpMutate, OpSelect,
OpSelectRandomIndividual, OpVariation, Probability, ProbabilityValue, RatedPopul... | (&mut self, population: &RatedPopulation<I, F>, mu: usize) -> RatedPopulation<I, F> {
let mut pop: RatedPopulation<I, F> = RatedPopulation::with_capacity(mu);
for _ in 0..mu {
let choice = tournament_selection_fast(&mut self.rng,
|i1, i2| po... | select | identifier_name |
ga.rs | extern crate rand;
extern crate evo;
extern crate petgraph;
extern crate graph_annealing;
use rand::{Rng, SeedableRng};
use rand::isaac::Isaac64Rng;
use evo::{Evaluator, Individual, MinFitness, OpCrossover1, OpMutate, OpSelect,
OpSelectRandomIndividual, OpVariation, Probability, ProbabilityValue, RatedPopul... | rng: Box::new(rng),
prob_crossover: Probability::new(0.3), // 0.7, 0.3 -> 20.
prob_mutation: Probability::new(0.5),
prob_bitflip: Probability::new(2.0 / BITS as f32),
tournament_size: 3,
};
fn stat(gen: usize, nevals: usize, pop: &RatedPopulation<AdjGenome, MinFitness<f6... | {
const MATRIX_N: usize = 40;
const BITS: usize = MATRIX_N * MATRIX_N;
const MU: usize = 6000;
const LAMBDA: usize = 60 * MATRIX_N;
const NGEN: usize = 2000;
let evaluator = MyEval { goal: Goal::new(line_graph(MATRIX_N as u32)) };
let seed: &[_] = &[45234341, 12343423, 123239];
let mut... | identifier_body |
platformstyle.js | // Copyright (C) 2015 Sam Parkinson
// This program is free software; you can redistribute it and/or
// modify it under the terms of the 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 version.
//
// You should hav... | (x, y, r, event, scale, stage) {
if (platform.FFOS) return {};
return showMaterialHighlight(x, y, r, event, scale, stage);
}
| showButtonHighlight | identifier_name |
platformstyle.js | // Copyright (C) 2015 Sam Parkinson
// This program is free software; you can redistribute it and/or
// modify it under the terms of the 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 version.
//
// You should hav... | {
if (platform.FFOS) return {};
return showMaterialHighlight(x, y, r, event, scale, stage);
} | identifier_body | |
platformstyle.js | // Copyright (C) 2015 Sam Parkinson
// This program is free software; you can redistribute it and/or
// modify it under the terms of the 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 version.
//
// You should hav... | FF: /Firefox/i.test(navigator.userAgent),
mobile: /Mobi/i .test(navigator.userAgent),
tablet: /Tablet/i .test(navigator.userAgent)
}
platform.androidWebkit = platform.android && !platform.FF;
platform.FFOS = platform.FF
&& (platform.mobile || platform.tablet)
&& !platform.a... | android: /Android/i.test(navigator.userAgent), | random_line_split |
main.py | # -*- coding: utf-8 -*-
import datetime
from openerp import http
from openerp.http import request
from openerp.addons.website_portal.controllers.main import website_account
class website_account(website_account):
@http.route(['/my/home'], type='http', auth="user", website=True)
def account(self, **kw):
... | (self, order=None):
partner = request.env['res.users'].browse(request.uid).partner_id
domain = [
('partner_id.id', '=', partner.id),
('state', 'not in', ['draft', 'cancel']),
('id', '=', order)
]
order = request.env['sale.order'].search(domain)
... | orders_followup | identifier_name |
main.py | # -*- coding: utf-8 -*-
import datetime
from openerp import http
from openerp.http import request
from openerp.addons.website_portal.controllers.main import website_account
class website_account(website_account):
@http.route(['/my/home'], type='http', auth="user", website=True)
def account(self, **kw):
... | response.qcontext.update({
'date': datetime.date.today().strftime('%Y-%m-%d'),
'quotations': quotations,
'orders': orders,
'invoices': invoices,
})
return response
@http.route(['/my/orders/<int:order>'], type='http', auth="user", website=True)... | random_line_split | |
main.py | # -*- coding: utf-8 -*-
import datetime
from openerp import http
from openerp.http import request
from openerp.addons.website_portal.controllers.main import website_account
class website_account(website_account):
@http.route(['/my/home'], type='http', auth="user", website=True)
def account(self, **kw):
... | 'invoices': invoices,
})
return response
@http.route(['/my/orders/<int:order>'], type='http', auth="user", website=True)
def orders_followup(self, order=None):
partner = request.env['res.users'].browse(request.uid).partner_id
domain = [
('partner_id.id',... | """ Add sales documents to main account page """
response = super(website_account, self).account()
partner = request.env.user.partner_id
res_sale_order = request.env['sale.order']
res_invoices = request.env['account.invoice']
quotations = res_sale_order.search([
('st... | identifier_body |
Assessment.ts | /*
Copyright (C) 2017 Cloudbase Solutions SRL
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 option) any later version.
This program is distribute... | fieldValues: { [fieldValue: string]: any },
networks: NetworkMap[],
vmSizes: { [vmSize: string]: VmSize },
} | source: Endpoint | null,
target: Endpoint,
selectedInstances: Instance[], | random_line_split |
poll.rs | ::connect("216.58.193.100:80".parse()?)?;
///
/// thread::sleep(Duration::from_secs(1));
///
/// let mut poll = Poll::new()?;
/// let registry = poll.registry().clone();
///
/// // The connect is not guaranteed to have started until it is registered at
/// // this point
/// registry.register(&sock, Token(0), Interests:... | /// A basic example -- establishing a `TcpStream` connection.
///
/// ```
/// # use std::error::Error;
/// # fn try_main() -> Result<(), Box<dyn Error>> {
/// use mio::{Events, Poll, Interests, Token};
/// use mio::net::TcpStream;
///
/// use std::net::{TcpListener, SocketAddr};
... | /// | random_line_split |
poll.rs | poll_interruptible(
&mut self,
events: &mut Events,
timeout: Option<Duration>,
) -> io::Result<usize> {
self.poll2(events, timeout, true)
}
fn poll2(
&mut self,
events: &mut Events,
mut timeout: Option<Duration>,
interruptible: bool,
) ->... | reregister | identifier_name | |
poll.rs | IOCP] uses a completion model
/// instead of a readiness model. In this case, `Poll` must adapt the completion
/// model Mio's API. While non-trivial, the bridge layer is still quite
/// efficient. The most expensive part being calls to `read` and `write` require
/// data to be copied into an intermediate buffer before... | {
timeout = Some(to - elapsed);
} | conditional_block | |
poll.rs | both from the system selector and the internal readiness queue.
///
/// [epoll]: http://man7.org/linux/man-pages/man7/epoll.7.html
/// [kqueue]: https://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2
/// [IOCP]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365198(v=vs.85).aspx
/// [`signalfd`]: http:... | {
fmt.debug_struct("Poll").finish()
} | identifier_body | |
header.ts | /**
* Onshape REST API
* The Onshape REST API consumed by all clients.
*
* OpenAPI spec version: 1.93
* Contact: api-support@onshape.zendesk.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
... | () {
return Header.attributeTypeMap;
}
}
export namespace Header {
export enum StyleEnum {
Simple = <any> 'simple'
}
}
| getAttributeTypeMap | identifier_name |
header.ts | /**
* Onshape REST API
* The Onshape REST API consumed by all clients.
*
* OpenAPI spec version: 1.93
* Contact: api-support@onshape.zendesk.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
... | "baseName": "deprecated",
"type": "boolean"
},
{
"name": "style",
"baseName": "style",
"type": "Header.StyleEnum"
},
{
"name": "explode",
"baseName": "explode",
"type": "boolean"
},
... | "type": "boolean"
},
{
"name": "deprecated", | random_line_split |
event.py | # Copyright (C) 2017,2019, Yu Sheng Lin, johnjohnlys@media.ee.ntu.edu.tw
# This file is part of Nicotb.
# Nicotb 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... |
if COSIM and hier:
BindEvent(n, (TOP_PREFIX+hier).encode())
return n
def CreateEvents(descs: list):
return [CreateEvent(event) for event in descs]
def GetEvent(ev):
return ev if isinstance(ev, int) else CreateEvent(ev)
def SignalEvent(ev, all_ev=True):
event_queue.append((ev, all_ev))
def DestroyEvent(ev: i... | n = len(waiting_coro)
waiting_coro.append(list()) | conditional_block |
event.py | # Copyright (C) 2017,2019, Yu Sheng Lin, johnjohnlys@media.ee.ntu.edu.tw
# This file is part of Nicotb.
# Nicotb 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... | SignalEvent(INIT_EVENT) | random_line_split | |
event.py | # Copyright (C) 2017,2019, Yu Sheng Lin, johnjohnlys@media.ee.ntu.edu.tw
# This file is part of Nicotb.
# Nicotb 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... | (ev, all_ev=True):
event_queue.append((ev, all_ev))
def DestroyEvent(ev: int):
# Do not destroy events created with hier name
waiting_coro[ev] = list()
event_released.add(ev)
# Initialize a default event, so coroutines can implement SystemC-like dont_initialize
INIT_EVENT = CreateEvent()
SignalEvent(INIT_EVENT)
| SignalEvent | identifier_name |
event.py | # Copyright (C) 2017,2019, Yu Sheng Lin, johnjohnlys@media.ee.ntu.edu.tw
# This file is part of Nicotb.
# Nicotb 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... |
def CreateEvents(descs: list):
return [CreateEvent(event) for event in descs]
def GetEvent(ev):
return ev if isinstance(ev, int) else CreateEvent(ev)
def SignalEvent(ev, all_ev=True):
event_queue.append((ev, all_ev))
def DestroyEvent(ev: int):
# Do not destroy events created with hier name
waiting_coro[ev] = ... | if event_released:
n = event_released.pop()
else:
n = len(waiting_coro)
waiting_coro.append(list())
if COSIM and hier:
BindEvent(n, (TOP_PREFIX+hier).encode())
return n | identifier_body |
sidebar-menu.component.js | var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(d... | SidebarMenuComponent = __decorate([
Component({
selector: 'app-sidebar-menu',
templateUrl: './sidebar-menu.component.html',
styleUrls: ['./sidebar-menu.component.css']
}),
__metadata('design:paramtypes', [])
], SidebarMenuComponent);
return Sideba... | }
}; | random_line_split |
sidebar-menu.component.js | var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(d... | () {
}
SidebarMenuComponent.prototype.ngOnInit = function () {
};
SidebarMenuComponent.prototype.ngAfterViewInit = function () {
this.sidebarMenu = $('#sidebar-menu');
};
SidebarMenuComponent.prototype.anchorClicked = function (event) {
this.li = $(event.toElement).parent();
... | SidebarMenuComponent | identifier_name |
sidebar-menu.component.js | var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(d... |
this.li.addClass('active');
$('ul:first', this.li).slideDown();
}
else {
this.li.removeClass('active active-sm');
$('ul:first', this.li).slideUp();
}
};
SidebarMenuComponent = __decorate([
Component({
selector: 'app-sid... | {
this.sidebarMenu.find('li').removeClass('active active-sm');
this.sidebarMenu.find('li ul').slideUp();
} | conditional_block |
sidebar-menu.component.js | var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(d... |
SidebarMenuComponent.prototype.ngOnInit = function () {
};
SidebarMenuComponent.prototype.ngAfterViewInit = function () {
this.sidebarMenu = $('#sidebar-menu');
};
SidebarMenuComponent.prototype.anchorClicked = function (event) {
this.li = $(event.toElement).parent();
if (!t... | {
} | identifier_body |
test_event.py | from vadvisor.store.event import InMemoryStore
import pytest
from freezegun import freeze_time
from datetime import datetime, timedelta
@pytest.fixture
@freeze_time("2012-01-14 03:00:00")
def expired_store():
store = InMemoryStore(60)
# Insert old data
store.put('old')
store.put('old')
store.put('... |
@pytest.fixture
@freeze_time("2012-01-14 03:01:50")
def newest_store(new_store):
# Insert newer data
new_store.put('newest')
new_store.put('newest')
new_store.put('newest')
return new_store
def test_empty_store():
store = InMemoryStore()
assert store.get() == []
@freeze_time("2012-01-... | expired_store.put('new')
expired_store.put('new')
expired_store.put('new')
return expired_store | identifier_body |
test_event.py | from vadvisor.store.event import InMemoryStore
import pytest
from freezegun import freeze_time
from datetime import datetime, timedelta
@pytest.fixture
@freeze_time("2012-01-14 03:00:00")
def expired_store():
store = InMemoryStore(60)
# Insert old data
store.put('old') |
@pytest.fixture
@freeze_time("2012-01-14 03:01:30")
def new_store(expired_store):
# Insert newer data
expired_store.put('new')
expired_store.put('new')
expired_store.put('new')
return expired_store
@pytest.fixture
@freeze_time("2012-01-14 03:01:50")
def newest_store(new_store):
# Insert newer... | store.put('old')
store.put('old')
return store
| random_line_split |
test_event.py | from vadvisor.store.event import InMemoryStore
import pytest
from freezegun import freeze_time
from datetime import datetime, timedelta
@pytest.fixture
@freeze_time("2012-01-14 03:00:00")
def expired_store():
store = InMemoryStore(60)
# Insert old data
store.put('old')
store.put('old')
store.put('... | (new_store):
assert new_store.get(elements=2) == ['new', 'new']
@freeze_time("2012-01-14 03:02:00")
def test_get_not_older_than(newest_store):
events = newest_store.get(
elements=2,
start_time=datetime.utcnow() - timedelta(seconds=20)
)
assert events == ['newest', 'newest']
@freeze_t... | test_get_two_new | identifier_name |
writer.py | # Copyright 2022 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
import logging
import traceback
from sis_provisioner.dao.uw_account import get_all_uw_accounts
from sis_provisioner.csv import get_filepath
from sis_provisioner.csv.user_writer import make_import_user_csv_files
from sis_provisioner.... |
def load_files(self):
try:
number_users_wrote = make_import_user_csv_files(
self.fetch_users(), self.filepath)
logger.info("Total {0:d} users wrote into {1}\n".format(
number_users_wrote, self.filepath))
return number_users_wrote
e... | random_line_split | |
writer.py | # Copyright 2022 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
import logging
import traceback
from sis_provisioner.dao.uw_account import get_all_uw_accounts
from sis_provisioner.csv import get_filepath
from sis_provisioner.csv.user_writer import make_import_user_csv_files
from sis_provisioner.... | (self):
return get_all_uw_accounts()
def load_files(self):
try:
number_users_wrote = make_import_user_csv_files(
self.fetch_users(), self.filepath)
logger.info("Total {0:d} users wrote into {1}\n".format(
number_users_wrote, self.filepath))
... | fetch_users | identifier_name |
writer.py | # Copyright 2022 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
import logging
import traceback
from sis_provisioner.dao.uw_account import get_all_uw_accounts
from sis_provisioner.csv import get_filepath
from sis_provisioner.csv.user_writer import make_import_user_csv_files
from sis_provisioner.... | except Exception:
log_exception(
logger,
"Failed to make user csv file in {0}".format(self.filepath),
traceback.format_exc())
| """
For the given loader, create the corresponsing csv files.
"""
def __init__(self,):
"""
@param: loader an account_managers.loader subclass object
"""
self.file_wrote = False
self.filepath = get_filepath(path_prefix=get_csv_file_path_prefix())
def fetch_users(s... | identifier_body |
CRC_sdx_ENS.js | removal of the onmouseover call in a cross-browser way
var sDD = ' onmouseover="' + options.dragdrop + '(\''+ targetDiv.id +'\',\'' + id + '\')" ';
} else {
var sDD = '';
}
if (Object.isUndefined(options.cssClass)) { options.cssClass = 'sdxDefaultPRS';}
// user can override
bCanExp = true;
if (O... | {
cl_onCompleteCB(retMsg);
} | conditional_block | |
CRC_sdx_ENS.js | // create an instance and populate with info
var t = new i2b2_SDX_Encapsulation_EXTENDED();
t.origData = Object.clone(sdxData.origData);
t.sdxInfo = Object.clone(sdxData.sdxInfo);
t.parent = sdxParentNode;
t.children = new Hash();
t.children.loaded = false;
// add to hash
sdxParentNode.children.set(qm_... | function i2b2_SDX_Encapsulation_EXTENDED() {}
| random_line_split | |
CRC_sdx_ENS.js | () {}
// create an instance and populate with info
var t = new i2b2_SDX_Encapsulation_EXTENDED();
t.origData = Object.clone(sdxData.origData);
t.sdxInfo = Object.clone(sdxData.sdxInfo);
t.parent = sdxParentNode;
t.children = new Hash();
t.children.loaded = false;
// add to hash
sdxParentNode.children.... | i2b2_SDX_Encapsulation_EXTENDED | identifier_name | |
CRC_sdx_ENS.js |
// create an instance and populate with info
var t = new i2b2_SDX_Encapsulation_EXTENDED();
t.origData = Object.clone(sdxData.origData);
t.sdxInfo = Object.clone(sdxData.sdxInfo);
t.parent = sdxParentNode;
t.children = new Hash();
t.children.loaded = false;
// add to hash
sdxParentNode.children.set(q... | {} | identifier_body | |
entry_with_else.rs | // run-rustfix
#![allow(unused, clippy::needless_pass_by_value, clippy::collapsible_if)]
#![warn(clippy::map_entry)]
use std::collections::{BTreeMap, HashMap};
use std::hash::Hash;
macro_rules! m {
($e:expr) => {{ $e }};
}
fn foo() {}
fn insert_if_absent0<K: Eq + Hash + Copy, V: Copy>(m: &mut HashMap<K, V>, k:... | foo();
} else {
m.insert(k, v);
}
if !m.contains_key(&k) {
m.insert(k, v);
} else {
m.insert(k, v2);
}
if m.contains_key(&k) {
if true { m.insert(k, v) } else { m.insert(k, v2) }
} else {
m.insert(k, v)
};
if m.contains_key(&k) {
... | {
if !m.contains_key(&k) {
m.insert(k, v);
} else {
m.insert(k, v2);
}
if m.contains_key(&k) {
m.insert(k, v);
} else {
m.insert(k, v2);
}
if !m.contains_key(&k) {
m.insert(k, v);
} else {
foo();
}
if !m.contains_key(&k) { | identifier_body |
entry_with_else.rs | // run-rustfix
#![allow(unused, clippy::needless_pass_by_value, clippy::collapsible_if)]
#![warn(clippy::map_entry)]
use std::collections::{BTreeMap, HashMap};
use std::hash::Hash;
macro_rules! m {
($e:expr) => {{ $e }};
}
fn foo() {}
fn insert_if_absent0<K: Eq + Hash + Copy, V: Copy>(m: &mut HashMap<K, V>, k:... | () {}
| main | identifier_name |
entry_with_else.rs | // run-rustfix
#![allow(unused, clippy::needless_pass_by_value, clippy::collapsible_if)]
#![warn(clippy::map_entry)]
use std::collections::{BTreeMap, HashMap};
use std::hash::Hash;
macro_rules! m {
($e:expr) => {{ $e }};
}
fn foo() {}
fn insert_if_absent0<K: Eq + Hash + Copy, V: Copy>(m: &mut HashMap<K, V>, k:... |
fn main() {} | None
};
} | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.