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 |
|---|---|---|---|---|
page-base.component.ts | /**
* @license
* Copyright 2017 JBoss 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 applicable law o... |
});
this.updatePageTitle();
}
/**
* Called to update the page title.
*/
protected updatePageTitle(): void {
this.titleService.setTitle(this.pageTitle());
}
/**
* Returns the appropriate page title for this page.
*
*/
protected abstract pageTit... | {
this.loadAsyncPageData(this._params, this._queryParams);
} | conditional_block |
install.py | # -*- coding: UTF-8 -*-
# Copyright 2019-2021 Rumma & Ko Ltd
# License: GNU Affero General Public License v3 (see file COPYING for details)
import subprocess
from rstgen.utils import confirm
from django.core.management.base import BaseCommand
from django.conf import settings
def runcmd(cmd, **kw): # same code as in... | """Run the cmd similar as os.system(), but stop when Ctrl-C."""
# kw.update(stdout=subprocess.PIPE)
# kw.update(stderr=subprocess.STDOUT)
kw.update(shell=True)
kw.update(universal_newlines=True)
kw.update(check=True)
# subprocess.check_output(cmd, **kw)
subprocess.run(cmd, **kw)
# os... | random_line_split | |
install.py | # -*- coding: UTF-8 -*-
# Copyright 2019-2021 Rumma & Ko Ltd
# License: GNU Affero General Public License v3 (see file COPYING for details)
import subprocess
from rstgen.utils import confirm
from django.core.management.base import BaseCommand
from django.conf import settings
def | (cmd, **kw): # same code as in getlino.py
"""Run the cmd similar as os.system(), but stop when Ctrl-C."""
# kw.update(stdout=subprocess.PIPE)
# kw.update(stderr=subprocess.STDOUT)
kw.update(shell=True)
kw.update(universal_newlines=True)
kw.update(check=True)
# subprocess.check_output(cmd, *... | runcmd | identifier_name |
install.py | # -*- coding: UTF-8 -*-
# Copyright 2019-2021 Rumma & Ko Ltd
# License: GNU Affero General Public License v3 (see file COPYING for details)
import subprocess
from rstgen.utils import confirm
from django.core.management.base import BaseCommand
from django.conf import settings
def runcmd(cmd, **kw): # same code as in... | reqs = set(settings.SITE.get_requirements())
if len(reqs) == 0:
print("No requirements")
else:
reqs = sorted(reqs)
if options['list']:
print('\n'.join(reqs))
return
runcmd('pip install --upgrade pip')
# cmd = "pi... | identifier_body | |
install.py | # -*- coding: UTF-8 -*-
# Copyright 2019-2021 Rumma & Ko Ltd
# License: GNU Affero General Public License v3 (see file COPYING for details)
import subprocess
from rstgen.utils import confirm
from django.core.management.base import BaseCommand
from django.conf import settings
def runcmd(cmd, **kw): # same code as in... |
runcmd('pip install --upgrade pip')
# cmd = "pip install --upgrade --trusted-host svn.forge.pallavi.be {}".format(' '.join(reqs))
cmd = "pip install --upgrade {}".format(' '.join(reqs))
if not options['interactive'] or confirm("{} (y/n) ?".format(cmd)):
r... | print('\n'.join(reqs))
return | conditional_block |
example_analyzeplist.py | #!/usr/bin/env python
"""
This is an example MIDAS module
"""
from os.path import isfile
from os import chmod
from time import time, gmtime, strftime
import logging
from sys import argv
from lib.ty_orm import TyORM
from lib.plist import read_plist, get_plist_key
from lib.config import Config
from lib.data_science imp... | (self, key):
"""
Log the values of the launch agent/daemon keys in self.check_keys_hash
"""
key = key.lower()
key_hash = "%s_hash" % (key.lower(), )
value = get_plist_key(self.plist_file, key)
if value:
try:
if isinstance(value, basest... | check_key_executable | identifier_name |
example_analyzeplist.py | #!/usr/bin/env python
"""
This is an example MIDAS module
"""
from os.path import isfile
from os import chmod
from time import time, gmtime, strftime
import logging
from sys import argv
from lib.ty_orm import TyORM
from lib.plist import read_plist, get_plist_key
from lib.config import Config
from lib.data_science imp... | plist_post_changed_files = a.post_changed_files
plist_pre_new_files = a.pre_new_files
plist_post_new_files = a.post_new_files
data_science = DataScience(
ORM,
plist_post_changed_files,
"plist",
"name",
... | start = time()
# the "exec_date" is used as the "date" field in the datastore
exec_date = strftime("%a, %d %b %Y %H:%M:%S", gmtime())
# the table definitions are stored in a library file. this is instantiating
# the ORM object and initializing the tables
ORM = TyORM(Config.get("database"))
if ... | conditional_block |
example_analyzeplist.py | #!/usr/bin/env python
"""
This is an example MIDAS module
"""
from os.path import isfile
from os import chmod
from time import time, gmtime, strftime
import logging
from sys import argv
from lib.ty_orm import TyORM
from lib.plist import read_plist, get_plist_key
from lib.config import Config
from lib.data_science imp... | self.plist_file = None
if self.changed_files:
self.analyze_changed_files()
if self.new_files:
self.analyze_new_files()
def gather_hashes(self):
"""
return a dictionary of plist names and their corresponding hashes
"""
hash_data = ORM... | """AnalyzePlist analyzes property list files installed on the system"""
def __init__(self):
self.data = {}
self.pre_changed_files = []
self.post_changed_files = []
self.pre_new_files = []
self.post_new_files = []
self.check_keys = Config.get("plist_check_keys")
... | identifier_body |
example_analyzeplist.py | #!/usr/bin/env python
"""
This is an example MIDAS module
"""
from os.path import isfile
from os import chmod
from time import time, gmtime, strftime |
from lib.ty_orm import TyORM
from lib.plist import read_plist, get_plist_key
from lib.config import Config
from lib.data_science import DataScience
from lib.helpers.filesystem import hash_file, list_launch_agents, \
list_launch_daemons, list_app_info_plist, list_plugin_info_plist, \
list_current_host_pref_file... | import logging
from sys import argv | random_line_split |
get_device_configuration.py | #!/usr/bin/env python
#
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Gets and writes the configurations of the attached devices.
This configuration is used by later build steps to determine which de... | (argv):
parser = optparse.OptionParser()
parser.add_option('--stamp', action='store')
parser.add_option('--output', action='store')
options, _ = parser.parse_args(argv)
devices = build_device.GetAttachedDevices()
device_configurations = []
for d in devices:
configuration, is_online, has_root = (
... | main | identifier_name |
get_device_configuration.py | #!/usr/bin/env python
#
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Gets and writes the configurations of the attached devices.
This configuration is used by later build steps to determine which de... |
elif len(devices) > 1:
# Note that this checks len(devices) and not len(device_configurations).
# This way, any time there are multiple devices attached it is
# explicitly stated which device we will install things to even if all but
# one device were rejected for other reasons (e.g. two devices atta... | build_utils.PrintBigWarning(
'No valid devices attached. Skipping managed install steps.') | conditional_block |
get_device_configuration.py | #!/usr/bin/env python
#
# Copyright 2013 The Chromium Authors. All rights reserved. | # found in the LICENSE file.
"""Gets and writes the configurations of the attached devices.
This configuration is used by later build steps to determine which devices to
install to and what needs to be installed to those devices.
"""
import optparse
import sys
from util import build_utils
from util import build_dev... | # Use of this source code is governed by a BSD-style license that can be | random_line_split |
get_device_configuration.py | #!/usr/bin/env python
#
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Gets and writes the configurations of the attached devices.
This configuration is used by later build steps to determine which de... | '"adb root" failed on device: %s\n'
'Skipping managed install for this device.'
% configuration['description'])
continue
device_configurations.append(configuration)
if len(device_configurations) == 0:
build_utils.PrintBigWarning(
'No valid devices attached. Skippi... | parser = optparse.OptionParser()
parser.add_option('--stamp', action='store')
parser.add_option('--output', action='store')
options, _ = parser.parse_args(argv)
devices = build_device.GetAttachedDevices()
device_configurations = []
for d in devices:
configuration, is_online, has_root = (
build... | identifier_body |
fedjax_test.py | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | unittest.main() | conditional_block | |
fedjax_test.py | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | (unittest.TestCase):
"""Test fedjax can be imported correctly."""
def test_import(self):
self.assertTrue(hasattr(fedjax, 'FederatedAlgorithm'))
self.assertTrue(hasattr(fedjax.aggregators, 'Aggregator'))
self.assertTrue(hasattr(fedjax.algorithms, 'fed_avg'))
self.assertTrue(hasattr(fedjax.datasets, ... | FedjaxTest | identifier_name |
fedjax_test.py | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | self.assertTrue(hasattr(fedjax.algorithms, 'fed_avg'))
self.assertTrue(hasattr(fedjax.datasets, 'emnist'))
self.assertTrue(hasattr(fedjax.models, 'emnist'))
self.assertTrue(hasattr(fedjax.training, 'save_checkpoint'))
def test_no_core(self):
self.assertFalse(hasattr(fedjax, 'core'))
if __name__... | def test_import(self):
self.assertTrue(hasattr(fedjax, 'FederatedAlgorithm'))
self.assertTrue(hasattr(fedjax.aggregators, 'Aggregator')) | random_line_split |
fedjax_test.py | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
if __name__ == '__main__':
unittest.main()
| """Test fedjax can be imported correctly."""
def test_import(self):
self.assertTrue(hasattr(fedjax, 'FederatedAlgorithm'))
self.assertTrue(hasattr(fedjax.aggregators, 'Aggregator'))
self.assertTrue(hasattr(fedjax.algorithms, 'fed_avg'))
self.assertTrue(hasattr(fedjax.datasets, 'emnist'))
self.ass... | identifier_body |
App.js | import React from 'react';
import styles from './App.less';
import withContext from '../../decorators/withContext';
import withStyles from '../../decorators/withStyles';
import Rankinglist from '../Rankinglist/Rankinglist';
@withContext
@withStyles(styles)
class | {
render() {
return (
<div id="app">
<div className="panel panel-primary">
<div className="panel-heading">
<h3 className="panel-title">Norges Tour</h3>
</div>
<div id="main-wrapper">
<nav className="sidebar-left" id="left-menu">
... | App | identifier_name |
App.js | import React from 'react';
import styles from './App.less';
import withContext from '../../decorators/withContext';
import withStyles from '../../decorators/withStyles';
import Rankinglist from '../Rankinglist/Rankinglist';
@withContext
@withStyles(styles)
class App {
render() {
return (
<div id="app"> | <nav className="sidebar-left" id="left-menu">
<ul className="nav nav-pills nav-stacked">
<li role="presentation" className="active"><a href="#">
<span className="glyphicon glyphicon-stats" aria-hidden="true"></span> Rankinglister</a>
</li>
... | <div className="panel panel-primary">
<div className="panel-heading">
<h3 className="panel-title">Norges Tour</h3>
</div>
<div id="main-wrapper"> | random_line_split |
termination.py | # Copyright 2015-2017 Cisco Systems, Inc.
# All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless req... | while data:
info_type, info_len = struct.unpack('!HH', data[0:4])
info_value = data[4: 4 + info_len]
if info_type == 0:
infor_tlv['string'] = info_value.decode('ascii')
elif info_type == 1:
infor_tlv['reason'] = cls.reason_codict[st... | @classmethod
def unpack(cls, data):
infor_tlv = dict() | random_line_split |
termination.py | # Copyright 2015-2017 Cisco Systems, Inc.
# All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless req... |
return cls(value=infor_tlv)
| info_type, info_len = struct.unpack('!HH', data[0:4])
info_value = data[4: 4 + info_len]
if info_type == 0:
infor_tlv['string'] = info_value.decode('ascii')
elif info_type == 1:
infor_tlv['reason'] = cls.reason_codict[struct.unpack('!H', info_value)[0]... | conditional_block |
termination.py | # Copyright 2015-2017 Cisco Systems, Inc.
# All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless req... | (cls, data):
infor_tlv = dict()
while data:
info_type, info_len = struct.unpack('!HH', data[0:4])
info_value = data[4: 4 + info_len]
if info_type == 0:
infor_tlv['string'] = info_value.decode('ascii')
elif info_type == 1:
i... | unpack | identifier_name |
termination.py | # Copyright 2015-2017 Cisco Systems, Inc.
# All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless req... | infor_tlv = dict()
while data:
info_type, info_len = struct.unpack('!HH', data[0:4])
info_value = data[4: 4 + info_len]
if info_type == 0:
infor_tlv['string'] = info_value.decode('ascii')
elif info_type == 1:
infor_tlv['reason'] = c... | identifier_body | |
pad.rs | use ffi::*;
use caps::Caps;
use reference::Reference;
use object::Object;
use std::ptr;
use std::mem;
use std::ops::{Deref, DerefMut};
pub struct Pad{
pad: Object
}
#[derive(Debug)]
#[repr(isize)]
pub enum LinkReturn{
WrongHierarchy = GST_PAD_LINK_WRONG_HIERARCHY as isize,
WasLinked = GST_PAD_LINK_WAS_LI... | }
impl ::Transfer<GstPad> for Pad{
unsafe fn transfer(self) -> *mut GstPad{
self.pad.transfer() as *mut GstPad
}
}
impl Reference for Pad{
fn reference(&self) -> Pad{
Pad{ pad: self.pad.reference() }
}
}
impl AsRef<Object> for Pad{
fn as_ref(&self) -> &Object{
&self.pad
... | }
pub unsafe fn gst_pad_mut(&mut self) -> *mut GstPad{
self.pad.gst_object_mut() as *mut GstPad
} | random_line_split |
pad.rs | use ffi::*;
use caps::Caps;
use reference::Reference;
use object::Object;
use std::ptr;
use std::mem;
use std::ops::{Deref, DerefMut};
pub struct Pad{
pad: Object
}
#[derive(Debug)]
#[repr(isize)]
pub enum LinkReturn{
WrongHierarchy = GST_PAD_LINK_WRONG_HIERARCHY as isize,
WasLinked = GST_PAD_LINK_WAS_LI... |
}
}
pub fn is_linked(&self) -> bool{
unsafe{
let pad: &mut GstPad = mem::transmute(self.gst_pad());
pad.peer != ptr::null_mut()
}
}
pub fn query_caps(&self, filter: Option<Caps>) -> Option<Caps>{
unsafe{
let caps = gst_pad_query_caps... | {
Err(mem::transmute(ret as isize))
} | conditional_block |
pad.rs | use ffi::*;
use caps::Caps;
use reference::Reference;
use object::Object;
use std::ptr;
use std::mem;
use std::ops::{Deref, DerefMut};
pub struct Pad{
pad: Object
}
#[derive(Debug)]
#[repr(isize)]
pub enum LinkReturn{
WrongHierarchy = GST_PAD_LINK_WRONG_HIERARCHY as isize,
WasLinked = GST_PAD_LINK_WAS_LI... | (&self) -> bool{
unsafe{
let pad: &mut GstPad = mem::transmute(self.gst_pad());
pad.peer != ptr::null_mut()
}
}
pub fn query_caps(&self, filter: Option<Caps>) -> Option<Caps>{
unsafe{
let caps = gst_pad_query_caps(self.gst_pad() as *mut GstPad, filter... | is_linked | identifier_name |
pad.rs | use ffi::*;
use caps::Caps;
use reference::Reference;
use object::Object;
use std::ptr;
use std::mem;
use std::ops::{Deref, DerefMut};
pub struct Pad{
pad: Object
}
#[derive(Debug)]
#[repr(isize)]
pub enum LinkReturn{
WrongHierarchy = GST_PAD_LINK_WRONG_HIERARCHY as isize,
WasLinked = GST_PAD_LINK_WAS_LI... |
}
impl AsRef<Object> for Pad{
fn as_ref(&self) -> &Object{
&self.pad
}
}
impl AsMut<Object> for Pad{
fn as_mut(&mut self) -> &mut Object{
&mut self.pad
}
}
impl From<Pad> for Object{
fn from(b: Pad) -> Object{
b.pad
}
}
impl Deref for Pad{
type Target = Object;
... | {
Pad{ pad: self.pad.reference() }
} | identifier_body |
visitor.rs | all kythe entries except files
pub struct KytheVisitor<'a, 'tcx: 'a> {
pub writer: &'a Box<EntryWriter>,
pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
pub codemap: &'a CodeMap,
pub corpus: &'a Corpus,
/// The vname of the parent item. The value changes as we recurse through the HIR, and is used
/// for chil... | fn anchor_from_sub_span(&self, span: Span, sub: &str) -> Result<VName, String> {
let start = self.codemap.lookup_byte_offset(span.lo);
let snippet = match self.codemap.span_to_snippet(span) {
Ok(s) => s,
Err(e) => return Err(format!("{:?}", e)),
};
let sub_sta... | self.anchor(&start.fm.name, start_byte, end_byte)
}
/// Emits the appropriate node and facts for an anchor defined as a substring within a span
/// and returns the node's VName | random_line_split |
visitor.rs | self.anchor(&start.fm.name, start_byte, end_byte)
}
/// Emits the appropriate node and facts for an anchor defined as a substring within a span
/// and returns the node's VName
fn anchor_from_sub_span(&self, span: Span, sub: &str) -> Result<VName, String> {
let start = self.codemap.look... | visit_impl_item | identifier_name | |
visitor.rs | kythe entries except files
pub struct KytheVisitor<'a, 'tcx: 'a> {
pub writer: &'a Box<EntryWriter>,
pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
pub codemap: &'a CodeMap,
pub corpus: &'a Corpus,
/// The vname of the parent item. The value changes as we recurse through the HIR, and is used
/// for childof ... | }
}
}
}
walk_block(self, block);
}
/// Captures refs and ref/calls
fn visit_expr(&mut self, expr: &'v Expr) {
if is_from_macro(&expr.span) {
return walk_expr(self, expr);
}
match expr.node {
//... | {
if let ExprCall(_, ref args) = base.node {
if let ExprLoop(ref block, _) = outer_arms[0].body.node {
if let Some(ref expr) = block.expr {
if let ExprMatch(_, ref arms, _) = expr.node {
... | conditional_block |
visitor.rs | (&file_name);
self.writer.node(&vname, Fact::NodeKind, &NodeKind::Anchor);
self.writer.node(&vname, Fact::LocStart, &start_str);
self.writer.node(&vname, Fact::LocEnd, &end_str);
self.writer.edge(&vname, EdgeKind::ChildOf, &file_vname);
vname
}
/// Produces a vname uniq... | {
let old_parent = self.parent_vname.clone();
let def_id = self.tcx.map.local_def_id(item.id);
let def_name = item.name.to_string();
let def_vname = self.vname_from_defid(def_id);
use rustc::hir::Item_::*;
match item.node {
ItemStatic(..) | ItemConst(..) => ... | identifier_body | |
xqueue.py | """
Fixture to configure XQueue response.
"""
import requests
import json
from common.test.acceptance.fixtures import XQUEUE_STUB_URL
class XQueueResponseFixtureError(Exception):
"""
Error occurred while configuring the stub XQueue.
"""
pass
class XQueueResponseFixture(object):
"""
Configu... | """
Configure the stub via HTTP.
"""
url = XQUEUE_STUB_URL + "/set_config"
# Configure the stub to respond to submissions to our queue
payload = {self._pattern: json.dumps(self._response_dict)}
response = requests.put(url, data=payload)
if not response.ok:
... | identifier_body | |
xqueue.py | """
Fixture to configure XQueue response.
"""
import requests
import json
from common.test.acceptance.fixtures import XQUEUE_STUB_URL
class XQueueResponseFixtureError(Exception):
"""
Error occurred while configuring the stub XQueue.
"""
pass
class XQueueResponseFixture(object):
"""
Configu... | (self, pattern, response_dict):
"""
Configure XQueue stub to POST `response_dict` (a dictionary)
back to the LMS when it receives a submission that contains the string
`pattern`.
Remember that there is one XQueue stub shared by all the tests;
if possible, you should have... | __init__ | identifier_name |
xqueue.py | """
Fixture to configure XQueue response.
"""
import requests
import json |
class XQueueResponseFixtureError(Exception):
"""
Error occurred while configuring the stub XQueue.
"""
pass
class XQueueResponseFixture(object):
"""
Configure the XQueue stub's response to submissions.
"""
def __init__(self, pattern, response_dict):
"""
Configure XQue... |
from common.test.acceptance.fixtures import XQUEUE_STUB_URL
| random_line_split |
xqueue.py | """
Fixture to configure XQueue response.
"""
import requests
import json
from common.test.acceptance.fixtures import XQUEUE_STUB_URL
class XQueueResponseFixtureError(Exception):
"""
Error occurred while configuring the stub XQueue.
"""
pass
class XQueueResponseFixture(object):
"""
Configu... | raise XQueueResponseFixtureError(
"Could not configure XQueue stub for queue '{1}'. Status code: {2}".format(
self._pattern, self._response_dict)) | conditional_block | |
encoder.js | var ebml = require('../lib/ebml/index.js'),
assert = require('assert');
describe('embl', function() {
describe('Encoder', function() {
function createEncoder(expected, done) |
it('should write a single tag', function(done) {
var encoder = createEncoder([0x42, 0x86, 0x81, 0x01], done);
encoder.writeTag('EBMLVersion', new Buffer([0x01]));
});
it('should write a tag with a single child', function(done) {
var encoder = createEncoder([0... | {
var encoder = new ebml.Encoder();
encoder.on('data', function(chunk) {
assert.equal(chunk.toString('hex'), new Buffer(expected).toString('hex'));
done();
});
return encoder;
} | identifier_body |
encoder.js | var ebml = require('../lib/ebml/index.js'),
assert = require('assert');
describe('embl', function() {
describe('Encoder', function() {
function | (expected, done) {
var encoder = new ebml.Encoder();
encoder.on('data', function(chunk) {
assert.equal(chunk.toString('hex'), new Buffer(expected).toString('hex'));
done();
});
return encoder;
}
it('should write a single tag... | createEncoder | identifier_name |
encoder.js | assert = require('assert');
describe('embl', function() {
describe('Encoder', function() {
function createEncoder(expected, done) {
var encoder = new ebml.Encoder();
encoder.on('data', function(chunk) {
assert.equal(chunk.toString('hex'), new Buffer(expected).toS... | var ebml = require('../lib/ebml/index.js'), | random_line_split | |
transfer.py | import sys
from sim import Sim
from node import Node
from link import Link
from transport import Transport
from tcp import TCP
from network import Network
import optparse
import os
import subprocess
class AppHandler(object):
def __init__(self,filename, directory):
self.filename = filename
self.di... |
def run(self):
# parameters
Sim.scheduler.reset()
Sim.set_debug('AppHandler')
Sim.set_debug('TCP')
# setup network
net = Network('../networks/setup.txt')
net.loss(self.loss)
# setup routes
n1 = net.get_node('n1')
n2 = net.get_node('... | args = ['diff','-u',self.in_directory + '/' + self.filename,self.out_directory+'/'+self.filename]
result = subprocess.Popen(args,stdout = subprocess.PIPE).communicate()[0]
print
if not result:
print "File transfer correct!"
else:
print "File transfer failed. Here ... | identifier_body |
transfer.py | import sys
from sim import Sim
from node import Node
from link import Link
from transport import Transport
from tcp import TCP
from network import Network
import optparse
import os
import subprocess
class AppHandler(object):
def __init__(self,filename, directory):
self.filename = filename
self.di... | c2 = TCP(t2,n2.get_address('n1'),1,n1.get_address('n2'),1,a,window=self.window)
# send a file
with open(self.in_directory + '/' + self.filename,'r') as f:
while True:
data = f.read(10000)
if not data:
break
Sim.sche... | random_line_split | |
transfer.py | import sys
from sim import Sim
from node import Node
from link import Link
from transport import Transport
from tcp import TCP
from network import Network
import optparse
import os
import subprocess
class AppHandler(object):
def __init__(self,filename, directory):
self.filename = filename
self.di... |
Sim.scheduler.add(delay=0, event=data, handler=c1.send)
# run the simulation
Sim.scheduler.run()
# print str(self.window) + " & " + \
# str(Sim.scheduler.current_time()) + " & " + \
# str(4116160.0 / float(Sim.scheduler.current_time())) + " & " +... | break | conditional_block |
transfer.py | import sys
from sim import Sim
from node import Node
from link import Link
from transport import Transport
from tcp import TCP
from network import Network
import optparse
import os
import subprocess
class AppHandler(object):
def __init__(self,filename, directory):
self.filename = filename
self.di... | (self,data):
Sim.trace('AppHandler',"application got %d bytes" % (len(data)))
self.f.write(data)
self.f.flush()
class Main(object):
def __init__(self):
self.iterations = 1 #set from flags
self.out_directory = '../output/received'
self.in_directory = '../data'
... | receive_data | identifier_name |
Gruntfile.js | ]
}
},
// Empties folders to start fresh
clean: {
dist: {
files: [{
dot: true,
src: [
'.tmp',
'<%= yeoman.dist %>/{,*/}*',
'!<%= yeoman.dist %>/.git*'
]
}]
},
server: '.tmp'
},
// Add vendor ... | {
return grunt.task.run(['build', 'connect:dist:keepalive']);
} | conditional_block | |
Gruntfile.js | ']
},
compass: {
files: ['<%= yeoman.app %>/styles/{,*/}*.{scss,sass}'],
tasks: ['compass:server', 'autoprefixer']
},
gruntfile: {
files: ['Gruntfile.js']
},
livereload: {
options: {
livereload: '<%= connect.options.livereload %>'
},
... | }
}
},
// Renames files for browser caching purposes
filerev: {
dist: {
src: [
'<%= yeoman.dist %>/scripts/{,*/}*.js',
'<%= yeoman.dist %>/styles/{,*/}*.css',
'<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
'<%= yeoman.dist... | },
server: {
options: {
debugInfo: true | random_line_split |
album-handler.ts | // (C) Copyright 2015 Martin Dougiamas
//
// 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 agre... | implements CoreFileUploaderHandler {
name = 'CoreFileUploaderAlbum';
priority = 2000;
constructor(private appProvider: CoreAppProvider, private utils: CoreUtilsProvider,
private uploaderHelper: CoreFileUploaderHelperProvider) { }
/**
* Whether or not the handler is enabled on a site ... | CoreFileUploaderAlbumHandler | identifier_name |
album-handler.ts | // (C) Copyright 2015 Martin Dougiamas
//
// 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 agre... | } | }
};
} | random_line_split |
pcspeaker_pl.ts | <?xml version="1.0" ?><!DOCTYPE TS><TS language="pl" version="2.1">
<context>
<name>@default</name>
<message>
<source>PC Speaker</source>
<translation>PC Speaker</translation>
</message>
</context>
<context>
<name>PCSpeakerConfigurationWidget</name>
<message>
<source>Put the ... | <translation>Wpisz dźwięki oddzielone spacją, dla pauzy użyj znaku _ (twarda spacja), np. D2/2 C1#/1 _/4 H0#/8. Po ukośniku wstawiasz odwrotność długości dźwięku (1, 2, 4, 8, dla 16-F)</translation>
</message>
</context>
</TS> | random_line_split | |
closure.rs | <'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
arg_scope_id: ScopeId,
freevars: &[ty::Freevar])
-> Block<'blk, 'tcx>
{
let _icx = push_ctxt("closure::load_closure_environment");
// Special case for sma... | load_closure_environment | identifier_name | |
closure.rs | cx(), substs, &function_type);
// Normalize type so differences in regions and typedefs don't cause
// duplicate declarations
let function_type = erase_regions(ccx.tcx(), &function_type);
let params = match function_type.sty {
ty::TyClosure(_, substs) => &substs.types,
_ => unreachable!... | let tcx = ccx.tcx();
let typer = NormalizingClosureTyper::new(tcx);
// Find a version of the closure type. Substitute static for the | random_line_split | |
closure.rs | _ptr");
Store(bcx, llenv, alloc);
Some(alloc)
} else {
None
};
for (i, freevar) in freevars.iter().enumerate() {
let upvar_id = ty::UpvarId { var_id: freevar.def.local_node_id(),
closure_expr_id: closure_id.node };
let upvar_captu... | fn trans_closure_adapter_shim<'a, 'tcx>(
ccx: &'a CrateContext<'a, 'tcx>,
closure_def_id: ast::DefId,
substs: Substs<'tcx>,
llfn_closure_kind: ty::ClosureKind | // The substitutions should have no type parameters remaining
// after passing through fulfill_obligation
let llfn = callee::trans_fn_ref_with_substs(ccx,
closure_def_id,
node,
... | identifier_body |
MD2.py | # ===================================================================
#
# Copyright (c) 2014, Legrandin <helderijs@gmail.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributio... |
# The size of the resulting hash in bytes.
digest_size = MD2Hash.digest_size
# The internal block size of the hash algorithm in bytes.
block_size = MD2Hash.block_size
| """Create a new hash object.
:parameter data:
Optional. The very first chunk of the message to hash.
It is equivalent to an early call to :meth:`MD2Hash.update`.
:type data: byte string/byte array/memoryview
:Return: A :class:`MD2Hash` hash object
"""
return MD2Hash().new(data) | identifier_body |
MD2.py | # ===================================================================
#
# Copyright (c) 2014, Legrandin <helderijs@gmail.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributio... |
def digest(self):
"""Return the **binary** (non-printable) digest of the message that has been hashed so far.
:return: The hash digest, computed over the data processed so far.
Binary form.
:rtype: byte string
"""
bfr = create_string_buffer(self.digest_si... | raise ValueError("Error %d while instantiating MD2"
% result) | conditional_block |
MD2.py | # ===================================================================
#
# Copyright (c) 2014, Legrandin <helderijs@gmail.com>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributio... | (self):
"""Return the **binary** (non-printable) digest of the message that has been hashed so far.
:return: The hash digest, computed over the data processed so far.
Binary form.
:rtype: byte string
"""
bfr = create_string_buffer(self.digest_size)
resu... | digest | identifier_name |
MD2.py | # ===================================================================
#
# Copyright (c) 2014, Legrandin <helderijs@gmail.com>
# All rights reserved. | #
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary f... | random_line_split | |
GuiEvents.ts | import { FieldSchema, Processor, ValueSchema } from '@ephox/boulder';
import { Arr, Cell, Optional } from '@ephox/katamari';
import { PlatformDetection } from '@ephox/sand';
import { DomEvent, EventArgs, EventUnbinder, SelectorExists, SugarElement, SugarNode } from '@ephox/sugar';
import * as Keys from '../alien/Keys'... |
// INVESTIGATE: Come up with a better way of doing this. Related target can be used, but not on FF.
// It allows the active element to change before firing the blur that we will listen to
// for things like closing popups
focusoutTimeout.set(Optional.some(setTimeout(() => {
settings.triggerEvent... | {
event.kill();
} | conditional_block |
GuiEvents.ts | import { FieldSchema, Processor, ValueSchema } from '@ephox/boulder';
import { Arr, Cell, Optional } from '@ephox/katamari';
import { PlatformDetection } from '@ephox/sand';
import { DomEvent, EventArgs, EventUnbinder, SelectorExists, SugarElement, SugarNode } from '@ephox/sugar';
import * as Keys from '../alien/Keys'... | pointerEvents.concat([
'selectstart',
'input',
'contextmenu',
'change',
'transitionend',
// Test the drag events
'drag',
'dragstart',
'dragend',
'dragenter',
'dragleave',
'dragover',
'drop',
'keyup'
]),
(type) => DomEvent.bi... | // These events are just passed through ... no additional processing
const simpleEvents = Arr.map( | random_line_split |
callsigs.py | # Copyright 2016 Autodesk 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 applicable law or agreed to in writing, software
# distributed under th... | # | random_line_split |
callsigs.py | # Copyright 2016 Autodesk 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 applicable law or agreed to in writing... | (f):
"""Modify f's call signature (using the `__signature__` attribute)"""
if wraps:
fname = original_function.__name__
f = functools.wraps(original_function)(f)
f.__name__ = fname # revert name change
else:
fname = f.__name__
f.__signatur... | decorator | identifier_name |
callsigs.py | # Copyright 2016 Autodesk 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 applicable law or agreed to in writing... |
def get_with_inst(self, obj, cls):
overridden = getattr(super(cls, obj), self.name, None)
@wraps(self.mthd, assigned=('__name__','__module__'))
def f(*args, **kwargs):
return self.mthd(obj, *args, **kwargs)
return self.use_parent_doc(f, overridden)
def get_no_in... | if obj:
return self.get_with_inst(obj, cls)
else:
return self.get_no_inst(cls) | identifier_body |
callsigs.py | # Copyright 2016 Autodesk 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 applicable law or agreed to in writing... |
else:
f.__doc__ = sigstring
return f
return decorator
def kwargs_from(reference_function, mod_docs=True):
""" Replaces ``**kwargs`` in a call signature with keyword arguments from another function.
Args:
reference_function (function): function to get kwargs f... | f.__doc__ = sigstring + f.__doc__ | conditional_block |
models.py | from datetime import date
from django.db import models
from smart_selects.db_fields import ChainedForeignKey
from urlparse import urlparse
class Organization(models.Model):
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class Season(models.Model):
name = models.... | # TODO: refactor into base class
def get_webcal_url(self, request):
if request:
domain = request.build_absolute_uri()
self.domain = domain
http_url = urlparse(domain)
webcal_url = http_url.geturl().replace(http_url.scheme, 'webcal', 1)
return '%s%s.ics' %... | return u"[%s] %s" % (self.number, self.name)
| random_line_split |
models.py | from datetime import date
from django.db import models
from smart_selects.db_fields import ChainedForeignKey
from urlparse import urlparse
class Organization(models.Model):
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class Season(models.Model):
name = models.... | (self, request):
if request:
domain = request.build_absolute_uri()
self.domain = domain
http_url = urlparse(domain)
webcal_url = http_url.geturl().replace(http_url.scheme, 'webcal', 1)
return '%s%s.ics' % (webcal_url, self.name.replace(' ', '_'))
class Team(mo... | get_webcal_url | identifier_name |
models.py | from datetime import date
from django.db import models
from smart_selects.db_fields import ChainedForeignKey
from urlparse import urlparse
class Organization(models.Model):
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class Season(models.Model):
name = models.... |
class Team(models.Model):
number = models.IntegerField()
name = models.CharField(max_length=100)
slug = models.SlugField()
color = models.CharField(max_length=100)
league = models.ForeignKey('League', related_name='teams')
class Meta:
ordering = ['number']
def __unicode__(self):... | name = models.CharField(max_length=100)
slug = models.SlugField()
season = models.ForeignKey('Season', related_name='leagues', null=True, blank=True)
org = models.ForeignKey('Organization', related_name='org', null=True, blank=True)
key = models.CharField(max_length=100)
is_active = models.BooleanFi... | identifier_body |
models.py | from datetime import date
from django.db import models
from smart_selects.db_fields import ChainedForeignKey
from urlparse import urlparse
class Organization(models.Model):
name = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class Season(models.Model):
name = models.... |
@property
def color_conflict(self):
if self.home_team.color.upper() == self.away_team.color.upper():
return True
else:
return False
class Meta:
ordering = ['time']
def __unicode__(self):
return u"%s vs. %s @ %s" % (self.home_team.name, self.awa... | return False | conditional_block |
state_codes.py | # Tiger/Line country shapefiles' "statefp" field is the FIPS code.
# The following is http://www.epa.gov/enviro/html/codes/state.html
data = """
State Abbreviation FIPS Code State Name
AK 02 ALASKA
AL 01 ALABAMA
AR 05 ARKANSAS
AS 60 AMERICAN SAMOA
AZ 04 ARIZONA
CA 06 CALIFORNIA
CO 08 COLORADO
CT 09 CONNECTICUT
DC 11 ... |
#print data
#print fips2postal
| fips2postal[fips] = postal | conditional_block |
state_codes.py | # Tiger/Line country shapefiles' "statefp" field is the FIPS code.
# The following is http://www.epa.gov/enviro/html/codes/state.html
data = """
State Abbreviation FIPS Code State Name
AK 02 ALASKA
AL 01 ALABAMA
AR 05 ARKANSAS
AS 60 AMERICAN SAMOA
AZ 04 ARIZONA
CA 06 CALIFORNIA
CO 08 COLORADO
CT 09 CONNECTICUT
DC 11 ... | IL 17 ILLINOIS
IN 18 INDIANA
KS 20 KANSAS
KY 21 KENTUCKY
LA 22 LOUISIANA
MA 25 MASSACHUSETTS
MD 24 MARYLAND
ME 23 MAINE
MI 26 MICHIGAN
MN 27 MINNESOTA
MO 29 MISSOURI
MS 28 MISSISSIPPI
MT 30 MONTANA
NC 37 NORTH CAROLINA
ND 38 NORTH DAKOTA
NE 31 NEBRASKA
NH 33 NEW HAMPSHIRE
NJ 34 NEW JERSEY
NM 35 NEW MEXICO
NV 32 NEVADA
... | GU 66 GUAM
HI 15 HAWAII
IA 19 IOWA
ID 16 IDAHO | random_line_split |
picdisplay.js | $(window).ready(function () {
$('.picunit a').each(function (i, el) {
var imgurl = $('.picdetailurl span:eq(' + i + ')').text();
console.log(imgurl);
$(el).click(function (event) {
document.documentElement.style.overflow = 'hidden';
imgtag = format('<img src="{0}" alt... | (event) {
$('.picdetail').hide(500);
document.documentElement.style.overflow = 'auto';
event.preventDefault();
$('.picscroll').empty();
} | disableDetail | identifier_name |
picdisplay.js | $(window).ready(function () {
$('.picunit a').each(function (i, el) {
var imgurl = $('.picdetailurl span:eq(' + i + ')').text();
console.log(imgurl);
$(el).click(function (event) {
document.documentElement.style.overflow = 'hidden';
imgtag = format('<img src="{0}" alt... | {
$('.picdetail').hide(500);
document.documentElement.style.overflow = 'auto';
event.preventDefault();
$('.picscroll').empty();
} | identifier_body | |
picdisplay.js | $(window).ready(function () {
$('.picunit a').each(function (i, el) {
var imgurl = $('.picdetailurl span:eq(' + i + ')').text();
console.log(imgurl);
$(el).click(function (event) {
document.documentElement.style.overflow = 'hidden';
imgtag = format('<img src="{0}" alt... | $('.picarticle').click(function (event) {
event.stopPropagation();
});
$('.close').click(function (event) {
disableDetail(event);
});
});
function disableDetail(event) {
$('.picdetail').hide(500);
document.documentElement.style.overflow = 'auto';
event.preventDefault();
... | $('.picdetail').click(function (event) {
disableDetail(event);
}); | random_line_split |
aarch64.rs | //! Aarch64 run-time features.
/// Checks if `aarch64` feature is enabled.
#[macro_export]
#[unstable(feature = "stdsimd", issue = "27731")]
#[allow_internal_unstable(stdsimd_internal, stdsimd)]
macro_rules! is_aarch64_feature_detected {
("neon") => {
// FIXME: this should be removed once we rename Aarch64... | {
/// ARM Advanced SIMD (ASIMD)
asimd,
/// Polynomial Multiply
pmull,
/// Floating point support
fp,
/// Half-float support.
fp16,
/// Scalable Vector Extension (SVE)
sve,
/// CRC32 (Cyclic Redundancy Check)
crc,
/// Crypto: AES + PMULL + SHA1 + SHA2
crypto,
... | Feature | identifier_name |
aarch64.rs | //! Aarch64 run-time features.
/// Checks if `aarch64` feature is enabled.
#[macro_export]
#[unstable(feature = "stdsimd", issue = "27731")]
#[allow_internal_unstable(stdsimd_internal, stdsimd)]
macro_rules! is_aarch64_feature_detected {
("neon") => {
// FIXME: this should be removed once we rename Aarch64... | };
}
/// ARM Aarch64 CPU Feature enum. Each variant denotes a position in a bitset
/// for a particular feature.
///
/// PLEASE: do not use this, it is an implementation detail subject to change.
#[doc(hidden)]
#[allow(non_camel_case_types)]
#[repr(u8)]
#[unstable(feature = "stdsimd_internal", issue = "0")]
pub en... | is_aarch64_feature_detected!($t);
};
($t:tt) => {
compile_error!(concat!("unknown aarch64 target feature: ", $t)) | random_line_split |
difference.py | """
Boolean geometry difference of solids.
"""
from __future__ import absolute_import
#Init has to be imported first because it has code to workaround the python bug where relative imports don't work if the module is imported as a main module.
import __init__
from fabmetheus_utilities.geometry.geometry_utilities im... | (elementNode):
'Get new derivation.'
return evaluate.EmptyObject(elementNode)
def processElementNode(elementNode):
"Process the xml element."
evaluate.processArchivable(Difference, elementNode)
class Difference( boolean_solid.BooleanSolid ):
"A difference object."
def getLoopsFromObjectLoopsList(self, importRa... | getNewDerivation | identifier_name |
difference.py | """
Boolean geometry difference of solids.
"""
from __future__ import absolute_import
#Init has to be imported first because it has code to workaround the python bug where relative imports don't work if the module is imported as a main module.
import __init__
from fabmetheus_utilities.geometry.geometry_utilities im... | "A difference object."
def getLoopsFromObjectLoopsList(self, importRadius, visibleObjectLoopsList):
"Get loops from visible object loops list."
return self.getDifference(importRadius, visibleObjectLoopsList)
def getXMLLocalName(self):
"Get xml class name."
return self.__class__.__name__.lower() | identifier_body | |
difference.py | """
Boolean geometry difference of solids.
"""
from __future__ import absolute_import
#Init has to be imported first because it has code to workaround the python bug where relative imports don't work if the module is imported as a main module.
import __init__
from fabmetheus_utilities.geometry.geometry_utilities im... |
def convertElementNode(elementNode, geometryOutput):
"Convert the xml element to a difference xml element."
group.convertContainerElementNode(elementNode, geometryOutput, Difference())
def getNewDerivation(elementNode):
'Get new derivation.'
return evaluate.EmptyObject(elementNode)
def processElementNode(element... | __author__ = 'Enrique Perez (perez_enrique@yahoo.com)'
__credits__ = 'Nophead <http://hydraraptor.blogspot.com/>\nArt of Illusion <http://www.artofillusion.org/>'
__date__ = '$Date: 2008/21/04 $'
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
| random_line_split |
reject-specialized-drops-8142.rs | // Copyright 2015 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 ... |
#[unsafe_destructor]
impl<One> Drop for V<One,One> { fn drop(&mut self) { } } // REJECT
//~^ERROR Implementations of Drop cannot be specialized
#[unsafe_destructor]
impl<'lw> Drop for W<'lw,'lw> { fn drop(&mut self) { } } // REJECT
//~^ERROR Implementations of Drop cannot be specialized
pub f... |
#[unsafe_destructor]
impl<'t,Bt:'t> Drop for T<'t,Bt> { fn drop(&mut self) { } } // ACCEPT
impl Drop for U { fn drop(&mut self) { } } // ACCEPT | random_line_split |
reject-specialized-drops-8142.rs | // Copyright 2015 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 ... | (&mut self) { } } // REJECT
//~^ ERROR Implementations of Drop cannot be specialized
#[unsafe_destructor]
impl<Adds_bnd:Bound> Drop for Q<Adds_bnd> { fn drop(&mut self) { } } // REJECT
//~^ ERROR The requirement `Adds_bnd : Bound` is added only by the Drop impl.
#[unsafe_destructor]
impl<'rbnd,Adds_rbnd:'rbnd> Drop f... | drop | identifier_name |
pyIMUCalibrationServer.py | from socket import *
from pytroykaimu import TroykaIMU
import time
import datetime
# Адрес
HOST = ''
PORT = 21567
BUFSIZ = 128
ADDR = (HOST, PORT)
imu = TroykaIMU()
tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)
# Запрет на ожидание
# tcpSerSock.setblocking(False)
def print_log... | dataencode = data.encode('utf-8').ljust(128, b' ')
if dataencode:
try:
# отправляем данные
tcpCliSock.send(dataencode)
time.sleep(0.05)
except:
# разрываем соединение, проблема с клие... | g('waiting for connection...')
# Ждем соединения клиента
tcpCliSock, addr = tcpSerSock.accept()
# Время ожидания данных от клиента
tcpCliSock.settimeout(0.02)
print_log('connection from: ' + str(addr))
# Соединились, передаем данные
while True:
m_x, ... | conditional_block |
pyIMUCalibrationServer.py | from socket import *
from pytroykaimu import TroykaIMU
import time
import datetime
# Адрес
HOST = ''
PORT = 21567
BUFSIZ = 128
ADDR = (HOST, PORT)
imu = TroykaIMU()
tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)
# Запрет на ожидание
# tcpSerSock.setblocking(False)
def print_log... | {}'.format(datetime.datetime.now(), text))
while True:
try:
print_log('waiting for connection...')
# Ждем соединения клиента
tcpCliSock, addr = tcpSerSock.accept()
# Время ожидания данных от клиента
tcpCliSock.settimeout(0.02)
print_log('connection from: ' + str(... | print('{} | identifier_name |
pyIMUCalibrationServer.py | from socket import *
from pytroykaimu import TroykaIMU
import time
import datetime
# Адрес
HOST = ''
PORT = 21567
BUFSIZ = 128
ADDR = (HOST, PORT)
imu = TroykaIMU()
tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)
# Запрет на ожидание
# tcpSerSock.setblocking(False)
def print_log... | # разрываем соединение, проблема с клиентом
print_log('Client terminated the connection')
tcpCliSock.close()
break
# Ждем соединение
except KeyboardInterrupt:
# Закрываем сервер
print_log('Server was... | tcpCliSock.send(dataencode)
time.sleep(0.05)
except: | random_line_split |
pyIMUCalibrationServer.py | from socket import *
from pytroykaimu import TroykaIMU
import time
import datetime
# Адрес
HOST = ''
PORT = 21567
BUFSIZ = 128
ADDR = (HOST, PORT)
imu = TroykaIMU()
tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)
# Запрет на ожидание
# tcpSerSock.setblocking(False)
def print_log... | :
print_log('waiting for connection...')
# Ждем соединения клиента
tcpCliSock, addr = tcpSerSock.accept()
# Время ожидания данных от клиента
tcpCliSock.settimeout(0.02)
print_log('connection from: ' + str(addr))
# Соединились, передаем данные
while True:
... | at(datetime.datetime.now(), text))
while True:
try | identifier_body |
security.ts | import * as crypto from 'crypto';
import { Maybe } from './maybe';
import { AuthToken, PermissionLevel } from './requestUtils';
import { getAllRegexMatches } from './functionalUtils';
const algorithm = 'aes-256-ctr';
const hash = 'sha512';
const encoding: crypto.Utf8AsciiBinaryEncoding = 'utf8';
const formatBinary: cr... |
export async function validateCookie(cookie: string): Promise<boolean> {
const tokenResult: Maybe<AuthToken> = parseCookie(cookie);
return tokenResult.caseOf({
just: (token: AuthToken) => {
return validateAuthToken(token);
},
nothing: () => false
});
}
export function ... | return fail;
} | random_line_split |
security.ts | import * as crypto from 'crypto';
import { Maybe } from './maybe';
import { AuthToken, PermissionLevel } from './requestUtils';
import { getAllRegexMatches } from './functionalUtils';
const algorithm = 'aes-256-ctr';
const hash = 'sha512';
const encoding: crypto.Utf8AsciiBinaryEncoding = 'utf8';
const formatBinary: cr... | (salt: string, password: string): string {
try {
const hashMethod = crypto.createHmac(hash, salt);
hashMethod.update(password);
return hashMethod.digest(formatLatin);
} catch (e) {
console.log('could not hash password', password, 'with salt', salt, 'internal message:', e.message)... | hashPassword | identifier_name |
security.ts | import * as crypto from 'crypto';
import { Maybe } from './maybe';
import { AuthToken, PermissionLevel } from './requestUtils';
import { getAllRegexMatches } from './functionalUtils';
const algorithm = 'aes-256-ctr';
const hash = 'sha512';
const encoding: crypto.Utf8AsciiBinaryEncoding = 'utf8';
const formatBinary: cr... |
const cookiePrelude: string = 'IgetbackAuth=';
const allMatches: string[] = getAllRegexMatches(cookie, `${cookiePrelude}([a-f0-9]+)`);
// attempt to get the latest cookie added to the session- not great
const token = allMatches[allMatches.length - 1];
if (!token) {
return fail;
}
... | {
return fail;
} | conditional_block |
security.ts | import * as crypto from 'crypto';
import { Maybe } from './maybe';
import { AuthToken, PermissionLevel } from './requestUtils';
import { getAllRegexMatches } from './functionalUtils';
const algorithm = 'aes-256-ctr';
const hash = 'sha512';
const encoding: crypto.Utf8AsciiBinaryEncoding = 'utf8';
const formatBinary: cr... | }
const result: AuthToken = {
email: deserializedResult.email,
authorizedAt: new Date(deserializedResult.authorizedAt),
permissionLevel: deserializedResult.permissionLevel
};
return Maybe.just(result);
} catch (e) {
console.log('JSON excep... | {
const fail: Maybe<AuthToken> = Maybe.nothing<AuthToken>();
if (!cookie) {
return fail;
}
const cookiePrelude: string = 'IgetbackAuth=';
const allMatches: string[] = getAllRegexMatches(cookie, `${cookiePrelude}([a-f0-9]+)`);
// attempt to get the latest cookie added to the session- n... | identifier_body |
updateImageOnWindowsAgent.ts | import ma = require('azure-pipelines-task-lib/mock-answer');
import tmrm = require('azure-pipelines-task-lib/mock-run');
import path = require('path');
let taskPath = path.join(__dirname, '..', 'main.js');
let tr: tmrm.TaskMockRunner = new tmrm.TaskMockRunner(taskPath);
tr.setInput("action", "Update image");
tr.setIn... |
process.env["AZURE_HTTP_USER_AGENT"] = "L0test";
process.env["ENDPOINT_AUTH_AzureRM"] = "{\"parameters\":{\"serviceprincipalid\":\"id\",\"serviceprincipalkey\":\"key\",\"tenantid\":\"tenant\"},\"scheme\":\"ServicePrincipal\"}";
process.env["ENDPOINT_AUTH_PARAMETER_AzureRM_SERVICEPRINCIPALID"] = "id";
process.env["END... | {
tr.setInput("customScriptsDirectory", "C:\\some\\dir with'quote");
tr.setInput("customScript", process.env["_vmssOsType_"] === "Linux" ? "set V'a`r$.sh" : "de$p`l o'y.ps1");
tr.setInput("customScriptArguments", "\"first 'arg'\" seco`nd$arg");
tr.setInput("customScriptsStorageAccount", "teststorage1");... | conditional_block |
updateImageOnWindowsAgent.ts | import ma = require('azure-pipelines-task-lib/mock-answer');
import tmrm = require('azure-pipelines-task-lib/mock-run');
import path = require('path');
let taskPath = path.join(__dirname, '..', 'main.js');
let tr: tmrm.TaskMockRunner = new tmrm.TaskMockRunner(taskPath);
tr.setInput("action", "Update image");
tr.setIn... |
Date.now = function (): number {
return 12345;
}
tr.registerMock('azure-pipelines-task-lib/toolrunner', require('azure-pipelines-task-lib/mock-toolrunner'));
tr.registerMock('azure-arm-rest-v2/azure-arm-compute', require('./mock_node_modules/azure-arm-compute'));
tr.registerMock('azure-arm-rest-v2/azure-arm-stora... | } | random_line_split |
run_if_widget.tsx | /*
* Copyright 2021 ThoughtWorks, 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 applicable law or agr... | }
} | random_line_split | |
run_if_widget.tsx | /*
* Copyright 2021 ThoughtWorks, 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 applicable law or agr... | vnode.state.onchange();
}}
property={vnode.state.any}/>
</div>
</div>
);
}
}
| {
return (
<div data-test-id="run-if-condition">
<h4>Run If Conditions:</h4>
<div data-test-id="run-if-condition-help-text" class={styles.runIfConditionHelpText}>
Decide whether task should run, based on the status of the job. <Link href={docsUrl("advanced_usage/dev_conditional_task_... | identifier_body |
run_if_widget.tsx | /*
* Copyright 2021 ThoughtWorks, 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 applicable law or agr... | (vnode: m.Vnode<Attrs, State>) {
return (
<div data-test-id="run-if-condition">
<h4>Run If Conditions:</h4>
<div data-test-id="run-if-condition-help-text" class={styles.runIfConditionHelpText}>
Decide whether task should run, based on the status of the job. <Link href={docsUrl("advan... | view | identifier_name |
run_if_widget.tsx | /*
* Copyright 2021 ThoughtWorks, 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 applicable law or agr... |
vnode.state.passed = Stream(vnode.attrs.runIf().indexOf("passed") !== -1);
vnode.state.failed = Stream(vnode.attrs.runIf().indexOf("failed") !== -1);
vnode.state.any = Stream(vnode.attrs.runIf().indexOf("any") !== -1);
vnode.state.clearPassedAndFailed = () => {
vnode.state.passed(false);
... | {
vnode.attrs.runIf(["passed"]);
} | conditional_block |
cell.rs |
///
/// See the [module-level documentation](index.html) for more.
#[stable(feature = "rust1", since = "1.0.0")]
pub struct RefCell<T: ?Sized> {
borrow: Cell<BorrowFlag>,
value: UnsafeCell<T>,
}
/// An enumeration of values returned from the `state` method on a `RefCell<T>`.
#[derive(Copy, Clone, PartialEq, D... | deref | identifier_name | |
cell.rs | //! ```
//!
#![stable(feature = "rust1", since = "1.0.0")]
use clone::Clone;
use cmp::PartialEq;
use default::Default;
use marker::{Copy, Send, Sync, Sized};
use ops::{Deref, DerefMut, Drop};
use option::Option;
use option::Option::{None, Some};
/// A mutable memory location that admits only `Copy` data.
///
/// See... | match BorrowRefMut::new(&self.borrow) { | random_line_split | |
urls.py | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.administrator_page), | url(r'^jd/(?P<jd_id>\d+)/create/$', views.create_jd),
url(r'^new_ssh_key/$', views.new_ssh_key_page),
url(r'^ssh_key/(?P<ssh_key_id>\d+)/delete/', views.delete_ssh_key),
url(r'^ssh_key/(?P<ssh_key_id>\d+)/create/$', views.create_ssh_key),
url(r'^new_parameter/$', views.new_parameter_page),
url(r... | url(r'^new_jd/$', views.new_jd_page),
url(r'^test_data/refresh/$', views.test_data_refresh),
url(r'^jd/(?P<jd_id>\d+)/delete/', views.delete_jd), | random_line_split |
num.rs | 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 http://opensource.org/licenses/MIT>, at your
// option... | ; // No more digits left to accumulate.
}
} else {
// Do the same as above, but accounting for two's complement.
for byte in buf.iter_mut().rev() {
let n = zero - (x % base); // Get the current place value.
x = ... | { break } | conditional_block |
num.rs | 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 http://opensource.org/licenses/MIT>, at your
// op... | /// A binary (base 2) radix
#[derive(Clone, PartialEq)]
struct Binary;
/// An octal (base 8) radix
#[derive(Clone, PartialEq)]
struct Octal;
/// A decimal (base 10) radix
#[derive(Clone, PartialEq)]
struct Decimal;
/// A hexadecimal (base 16) radix, formatted with lower-case characters
#[derive(Clone, PartialEq)]
st... | random_line_split | |
num.rs | 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 http://opensource.org/licenses/MIT>, at your
// op... | ;
/// A hexadecimal (base 16) radix, formatted with upper-case characters
#[derive(Clone, PartialEq)]
pub struct UpperHex;
macro_rules! radix {
($T:ident, $base:expr, $prefix:expr, $($x:pat => $conv:expr),+) => {
impl GenericRadix for $T {
fn base(&self) -> u8 { $base }
fn prefix(&... | LowerHex | identifier_name |
dokuwiki.py | point to a directory" % rootpath)
# check a 'data' directory exists, establish pathes for each subdirectory
self.data = os.path.join(rootpath, "data")
if not os.path.isdir(self.data):
raise RuntimeError("Dokuwiki root path '%s' does not contain a data directory" % rootpath)
... | """
Convert a Mediawiki internal anchor heading link to the Dokuwiki anchor heading link id
Equivalent function in dokuwiki is _headerToLink in inc/parser/xhtml.php
which calls sectionID in inc/pageutils.php
"""
result = names.clean_id(mw_heading_name, True)
result = re.sub(r'[:.]', '', result)... | identifier_body | |
dokuwiki.py | , shutil, re, requests, calendar, codecs, sys
from requests.auth import HTTPBasicAuth
import wikicontent
import simplemediawiki
import names
class Exporter(object):
def __init__(self, rootpath):
# verify the dokuwiki rootpath exists
self.root = rootpath
if not os.path.isdir(rootpath):
... | (self):
""" Fix permissions under the data directory
This means applying the data directory's permissions and ownership to all underlying parts.
If this fails due to insufficient privileges then it just prints a warning and continues on.
"""
stat = os.stat(self.data)
tr... | fixup_permissions | identifier_name |
dokuwiki.py | gzip, shutil, re, requests, calendar, codecs, sys
from requests.auth import HTTPBasicAuth
import wikicontent
import simplemediawiki
import names
class Exporter(object):
def __init__(self, rootpath):
# verify the dokuwiki rootpath exists
self.root = rootpath
if not os.path.isdir(rootpath):... | for image in images:
# download the image from the Mediawiki server
print("Downloading %s..." % image['name'])
r = requests.get(image['url'], auth=auth)
# write the actual image out to the data/file directory
name = make_dokuwiki_pagename(image['name']... | filemeta = os.path.join(self.data, "media_meta", file_namespace)
ensure_directory_exists(filemeta) | random_line_split |
dokuwiki.py | if not os.path.isdir(rootpath):
raise RuntimeError("Dokuwiki root path '%s' does not point to a directory" % rootpath)
# check a 'data' directory exists, establish pathes for each subdirectory
self.data = os.path.join(rootpath, "data")
if not os.path.isdir(self.data):
r... | return nums_stripped | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.