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 |
|---|---|---|---|---|
useful.py | #
# This file is part of pyasn1 software.
#
# Copyright (c) 2005-2017, Ilya Etingof <etingof@gmail.com>
# License: http://pyasn1.sf.net/license.html
#
from pyasn1.type import univ, char, tag
__all__ = ['ObjectDescriptor', 'GeneralizedTime', 'UTCTime']
NoValue = univ.NoValue
noValue = univ.noValue
class ObjectDescri... |
class UTCTime(char.VisibleString):
__doc__ = char.GraphicString.__doc__
#: Default :py:class:`~pyasn1.type.tag.TagSet` object for |ASN.1| objects
tagSet = char.VisibleString.tagSet.tagImplicitly(
tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 23)
) |
#: Default :py:class:`~pyasn1.type.tag.TagSet` object for |ASN.1| objects
tagSet = char.VisibleString.tagSet.tagImplicitly(
tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 24)
) | random_line_split |
useful.py | #
# This file is part of pyasn1 software.
#
# Copyright (c) 2005-2017, Ilya Etingof <etingof@gmail.com>
# License: http://pyasn1.sf.net/license.html
#
from pyasn1.type import univ, char, tag
__all__ = ['ObjectDescriptor', 'GeneralizedTime', 'UTCTime']
NoValue = univ.NoValue
noValue = univ.noValue
class ObjectDescri... |
class GeneralizedTime(char.VisibleString):
__doc__ = char.GraphicString.__doc__
#: Default :py:class:`~pyasn1.type.tag.TagSet` object for |ASN.1| objects
tagSet = char.VisibleString.tagSet.tagImplicitly(
tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 24)
)
class UTCTime(char.VisibleSt... | __doc__ = char.GraphicString.__doc__
#: Default :py:class:`~pyasn1.type.tag.TagSet` object for |ASN.1| objects
tagSet = char.GraphicString.tagSet.tagImplicitly(
tag.Tag(tag.tagClassUniversal, tag.tagFormatSimple, 7)
) | identifier_body |
int_test.rs | // int_test.rs
//
// Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Jim Davies, Brian Gough
// Copyright (C) 2016 G.vd.Schoot
//
// This program 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 versi... | gsl::test_rel(mean, expected, rel, "mean(fractional)");
}
{
let mean = mean(slice_a);
let variance = variance_with_fixed_mean(slice_a, mean);
let expected = 13.7;
gsl::test_rel(variance, expected, rel, "variance_with_fixed_mean");
}
{
let mean = mean(sli... | {
// sample sets of integers
let slice_1 = &[1, 2, 3, 4, 5, 6];
let slice_a = &[17, 18, 16, 18, 12, 20, 18, 20, 20, 22, 20, 10, 8, 12, 16, 16, 18, 20, 18, 21];
let slice_b = &[19, 20, 22, 24, 10, 25, 20, 22, 21, 23, 20, 10, 12, 14, 12, 20, 22, 24, 23, 17];
let rel = 1.0e-10;
{
let m... | identifier_body |
int_test.rs | // int_test.rs
//
// Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Jim Davies, Brian Gough
// Copyright (C) 2016 G.vd.Schoot
//
// This program 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 versi... | () {
// sample sets of integers
let slice_1 = &[1, 2, 3, 4, 5, 6];
let slice_a = &[17, 18, 16, 18, 12, 20, 18, 20, 20, 22, 20, 10, 8, 12, 16, 16, 18, 20, 18, 21];
let slice_b = &[19, 20, 22, 24, 10, 25, 20, 22, 21, 23, 20, 10, 12, 14, 12, 20, 22, 24, 23, 17];
let rel = 1.0e-10;
{
le... | test_i32_slice | identifier_name |
int_test.rs | // int_test.rs
//
// Copyright (C) 1996, 1997, 1998, 1999, 2000, 2007 Jim Davies, Brian Gough
// Copyright (C) 2016 G.vd.Schoot
//
// This program 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 versi... | #[test]
fn test_i32_slice() {
// sample sets of integers
let slice_1 = &[1, 2, 3, 4, 5, 6];
let slice_a = &[17, 18, 16, 18, 12, 20, 18, 20, 20, 22, 20, 10, 8, 12, 16, 16, 18, 20, 18, 21];
let slice_b = &[19, 20, 22, 24, 10, 25, 20, 22, 21, 23, 20, 10, 12, 14, 12, 20, 22, 24, 23, 17];
let rel = 1... |
extern crate stat;
use stat::*;
| random_line_split |
api_client.py | import math
from service.fake_api_results import ALL_TITLES, OFFICIAL_COPY_RESULT, SELECTED_FULL_RESULTS
SEARCH_RESULTS_PER_PAGE = 20
def get_title(title_number):
return SELECTED_FULL_RESULTS.get(title_number)
def _get_titles(page_number):
nof_results = len(ALL_TITLES)
number_pages = math.ceil(nof_resu... |
def get_titles_by_address(address, page_number):
return _get_titles(page_number)
def get_official_copy_data(title_number):
return OFFICIAL_COPY_RESULT | random_line_split | |
api_client.py | import math
from service.fake_api_results import ALL_TITLES, OFFICIAL_COPY_RESULT, SELECTED_FULL_RESULTS
SEARCH_RESULTS_PER_PAGE = 20
def get_title(title_number):
return SELECTED_FULL_RESULTS.get(title_number)
def _get_titles(page_number):
nof_results = len(ALL_TITLES)
number_pages = math.ceil(nof_resu... | (address, page_number):
return _get_titles(page_number)
def get_official_copy_data(title_number):
return OFFICIAL_COPY_RESULT
| get_titles_by_address | identifier_name |
api_client.py | import math
from service.fake_api_results import ALL_TITLES, OFFICIAL_COPY_RESULT, SELECTED_FULL_RESULTS
SEARCH_RESULTS_PER_PAGE = 20
def get_title(title_number):
return SELECTED_FULL_RESULTS.get(title_number)
def _get_titles(page_number):
nof_results = len(ALL_TITLES)
number_pages = math.ceil(nof_resu... | return OFFICIAL_COPY_RESULT | identifier_body | |
test_api.py | # Copyright 2015 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.
from copy import deepcopy
from recipe_engine import recipe_test_api
class iOSTestApi(recipe_test_api.RecipeTestApi):
@recipe_test_api.mod_test_data
@sta... | }
}) | random_line_split | |
test_api.py | # Copyright 2015 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.
from copy import deepcopy
from recipe_engine import recipe_test_api
class iOSTestApi(recipe_test_api.RecipeTestApi):
@recipe_test_api.mod_test_data
@sta... |
def test_results(self):
return self.m.json.output({
'links': {
'fake URL text': 'fake URL',
},
'logs': {
'fake log': [
'fake log line 1',
'fake log line 2',
],
}
})
| return self.m.json.output({
'Mac OS X Version': '1.2.3',
'Xcode Version': '6.7.8',
'Xcode Build Version': '5D342509a',
'Xcode SDKs': [
'fake sdk 1.0',
'fake sdk 1.1',
'fake sdk 2.0',
],
}) | identifier_body |
test_api.py | # Copyright 2015 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.
from copy import deepcopy
from recipe_engine import recipe_test_api
class | (recipe_test_api.RecipeTestApi):
@recipe_test_api.mod_test_data
@staticmethod
def build_config(config):
return deepcopy(config)
def make_test_build_config(self, config):
return self.build_config(config)
@recipe_test_api.mod_test_data
@staticmethod
def parent_build_config(config):
return deep... | iOSTestApi | identifier_name |
test_compliancebuilding.py | import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.compliance_objects import ComplianceBuilding
log = logging.getLogger(__name__)
class | (unittest.TestCase):
def setUp(self):
self.fd, self.path = tempfile.mkstemp()
def tearDown(self):
os.remove(self.path)
def test_create_compliancebuilding(self):
pyidf.validation_level = ValidationLevel.error
obj = ComplianceBuilding()
# real
var_building_... | TestComplianceBuilding | identifier_name |
test_compliancebuilding.py | import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.compliance_objects import ComplianceBuilding
log = logging.getLogger(__name__)
class TestComplianceBuilding(unittest.TestCase):
def setUp(self):
self.fd, self.path ... |
idf2 = IDF(self.path)
self.assertAlmostEqual(idf2.compliancebuildings[0].building_rotation_for_appendix_g, var_building_rotation_for_appendix_g) | log.debug(line.strip()) | conditional_block |
test_compliancebuilding.py | import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.compliance_objects import ComplianceBuilding
log = logging.getLogger(__name__)
class TestComplianceBuilding(unittest.TestCase):
def setUp(self):
self.fd, self.path ... | for line in f:
log.debug(line.strip())
idf2 = IDF(self.path)
self.assertAlmostEqual(idf2.compliancebuildings[0].building_rotation_for_appendix_g, var_building_rotation_for_appendix_g) | random_line_split | |
test_compliancebuilding.py | import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.compliance_objects import ComplianceBuilding
log = logging.getLogger(__name__)
class TestComplianceBuilding(unittest.TestCase):
def setUp(self):
self.fd, self.path ... | pyidf.validation_level = ValidationLevel.error
obj = ComplianceBuilding()
# real
var_building_rotation_for_appendix_g = 1.1
obj.building_rotation_for_appendix_g = var_building_rotation_for_appendix_g
idf = IDF()
idf.add(obj)
idf.save(self.path, check=False)
... | identifier_body | |
categoryParser.js | function | (aCategory, aFunction)
{
if(document.location.host == '' || document.location.host == 'localhost' )
var url = 'test.html';
else
var url = categoryGetURLPrivate(aCategory);
$.ajax({
type: "GET",
url: url,
dataType:'html',
success: function(responseText)
{
var aData = {};
aData.categ... | parseCategory | identifier_name |
categoryParser.js | function parseCategory(aCategory, aFunction)
{
if(document.location.host == '' || document.location.host == 'localhost' )
var url = 'test.html';
else
var url = categoryGetURLPrivate(aCategory);
$.ajax({
type: "GET",
url: url,
dataType:'html',
success: function(responseText)
{
var aData ... | //alert(aData.sitesCooled.toString());
aData.sitesCooled.sort(ODPy.sortLocale);
//sites not cooled
$(responseText).find('.directory-url').find('li:not(.star)').each(function()
{
aData.sites[aData.sites.length] = $(this).html().replace(/href="/, ' target="_blank" hr... | {
aData.sitesCooled[aData.sitesCooled.length] = $(this).html().replace(/href="/, ' target="_blank" href="');
}); | random_line_split |
categoryParser.js | function parseCategory(aCategory, aFunction)
| aData.moz = '';
var tmp = 0;
//subcategories and links
$(responseText).find('.dir-1').each(function()
{
aData.categories[tmp] = [];
$(this).find('li').each(function()
{
aData.categories[tmp][aData.categories[tmp].... | {
if(document.location.host == '' || document.location.host == 'localhost' )
var url = 'test.html';
else
var url = categoryGetURLPrivate(aCategory);
$.ajax({
type: "GET",
url: url,
dataType:'html',
success: function(responseText)
{
var aData = {};
aData.categories = [];
aData.a... | identifier_body |
ImageSlider.js | // @flow
import React, { type Node, Component } from 'react';
import {
Image,
View,
ScrollView,
StyleSheet,
TouchableHighlight,
TouchableOpacity,
Dimensions,
} from 'react-native';
const reactNativePackage = require('react-native/package.json');
const splitVersion = reactNativePackage.version.split('.')... |
let newPosition = 0;
if (position !== -1 && position !== images.length) {
newPosition = Math.round(event.nativeEvent.contentOffset.x / width);
this.setState({ position: newPosition });
}
if (
onPositionChanged &&
!this.state.onPositionChangedCalled &&
newPosition < imag... | {
return this._move(images.length - 1, false);
} | conditional_block |
ImageSlider.js | // @flow
import React, { type Node, Component } from 'react';
import {
Image,
View,
ScrollView,
StyleSheet,
TouchableHighlight,
TouchableOpacity,
Dimensions,
} from 'react-native';
const reactNativePackage = require('react-native/package.json');
const splitVersion = reactNativePackage.version.split('.')... |
componentDidUpdate(prevProps: Object) {
const { position, autoPlayFlag } = this.props;
this.autoPlayFlag = autoPlayFlag;
if (position && prevProps.position !== position) {
this._move(position);
}
}
_clearInterval = () =>
this.state.interval && clearInterval(this.state.interval);
_se... | return this.props.position % this.props.images.length;
}
return this.state.position % this.props.images.length;
} | random_line_split |
auth.rs | // Copyright 2017 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By ... |
}
impl ReprC for AuthReq {
type C = *const ffi::AuthReq;
type Error = IpcError;
/// Constructs the object from the FFI counterpart.
///
/// After calling this function, the subobjects memory is owned by the
/// resulting object.
unsafe fn clone_from_repr_c(repr_c: *const ffi::AuthReq) -> ... | {
let AuthReq {
app,
app_container,
containers,
} = self;
let containers = containers_into_vec(containers).map_err(StringError::from)?;
let (containers_ptr, containers_len, containers_cap) = vec_into_raw_parts(containers);
Ok(ffi::AuthReq {
... | identifier_body |
auth.rs | // Copyright 2017 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By ... |
/// Represents an authorization request
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct AuthReq {
/// The application identifier for this request
pub app: AppExchangeInfo,
/// `true` if the app wants dedicated container for itself. `false`
/// otherwise.
pub app_container:... | use ffi::ipc::req as ffi;
use ffi_utils::{ReprC, StringError, vec_into_raw_parts};
use ipc::errors::IpcError;
use std::collections::HashMap; | random_line_split |
auth.rs | // Copyright 2017 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By ... | {
/// The application identifier for this request
pub app: AppExchangeInfo,
/// `true` if the app wants dedicated container for itself. `false`
/// otherwise.
pub app_container: bool,
/// The list of containers it wishes to access (and desired permissions).
pub containers: HashMap<String, C... | AuthReq | identifier_name |
urlfind.py | #!/usr/bin/env python3
import re
import os
import os.path
import sys
def main():
already_found = []
url_matcher = re.compile(r'(https?://(www.)?)?((youtu.be|youtube.(com|de|ch|at))/watch\?v=[-_0-9A-Za-z]{11}|youtu.be/[-_0-9A-Za-z]{11})')
backup_matcher = re.compile(r'youtu')
argc = len(sys.argv)
... |
else:
s = max(ms - 33, 0)
e = min(me + 33, whole_len)
num_backup_candidates += 1
print('found unmatched candidate: ' + whole_input[s:e])
print('found {0} unmatched candidates and created {1} URL files'.format(num_backup_candidates, num_found))
print('don... | if ms >= s and me <= e:
break | conditional_block |
urlfind.py | #!/usr/bin/env python3
import re
import os
import os.path
import sys
def | ():
already_found = []
url_matcher = re.compile(r'(https?://(www.)?)?((youtu.be|youtube.(com|de|ch|at))/watch\?v=[-_0-9A-Za-z]{11}|youtu.be/[-_0-9A-Za-z]{11})')
backup_matcher = re.compile(r'youtu')
argc = len(sys.argv)
if argc == 1:
whole_input = sys.stdin.read()
elif argc == 2:
... | main | identifier_name |
urlfind.py | #!/usr/bin/env python3
import re
import os
import os.path
import sys
def main():
already_found = []
url_matcher = re.compile(r'(https?://(www.)?)?((youtu.be|youtube.(com|de|ch|at))/watch\?v=[-_0-9A-Za-z]{11}|youtu.be/[-_0-9A-Za-z]{11})')
backup_matcher = re.compile(r'youtu')
argc = len(sys.argv)
... | ms = match.start()
me = match.end()
for (s, e) in already_found:
if ms >= s and me <= e:
break
else:
s = max(ms - 33, 0)
e = min(me + 33, whole_len)
num_backup_candidates += 1
print('found unmatched candidate: ' ... |
num_backup_candidates = 0
whole_len = len(whole_input)
for match in backup_matcher.finditer(whole_input): | random_line_split |
urlfind.py | #!/usr/bin/env python3
import re
import os
import os.path
import sys
def main():
| written = False
while (not written) and (filename_ctr < 31337):
try:
with open(os.path.join('./urls/', '{0}.txt'.format(filename_ctr)), mode='xt', encoding='utf8') as outf:
print(match.group(0), file=outf)
written = True
except ... | already_found = []
url_matcher = re.compile(r'(https?://(www.)?)?((youtu.be|youtube.(com|de|ch|at))/watch\?v=[-_0-9A-Za-z]{11}|youtu.be/[-_0-9A-Za-z]{11})')
backup_matcher = re.compile(r'youtu')
argc = len(sys.argv)
if argc == 1:
whole_input = sys.stdin.read()
elif argc == 2:
with o... | identifier_body |
setup.py | """
dwm package setup
"""
from __future__ import print_function
from setuptools import setup, find_packages
__version__ = '1.1.0'
def readme():
|
setup(
name='dwm',
version=__version__,
url='https://github.com/rh-marketingops/dwm',
license='GNU General Public License',
author='Jeremiah Coleman',
tests_require=['nose', 'mongomock>=3.5.0'],
install_requires=['pymongo>=3.2.2', 'tqdm>=4.8.4'],
author_email='colemanja91@gmail.com',
... | """ open readme for long_description """
try:
with open('README.md') as fle:
return fle.read()
except IOError:
return '' | identifier_body |
setup.py | """
dwm package setup
"""
from __future__ import print_function
from setuptools import setup, find_packages
__version__ = '1.1.0'
def readme():
""" open readme for long_description """
try:
with open('README.md') as fle:
return fle.read()
except IOError:
return ''
setup(... | description='Best practices for marketing data quality management',
long_description=readme(),
packages=find_packages(),
include_package_data=True,
platforms='any',
test_suite='nose.collector',
classifiers=[
'Programming Language :: Python',
'Development Status :: 4 - Beta',
... | install_requires=['pymongo>=3.2.2', 'tqdm>=4.8.4'],
author_email='colemanja91@gmail.com', | random_line_split |
setup.py | """
dwm package setup
"""
from __future__ import print_function
from setuptools import setup, find_packages
__version__ = '1.1.0'
def | ():
""" open readme for long_description """
try:
with open('README.md') as fle:
return fle.read()
except IOError:
return ''
setup(
name='dwm',
version=__version__,
url='https://github.com/rh-marketingops/dwm',
license='GNU General Public License',
author='J... | readme | identifier_name |
index.ts | /**
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to... |
import {Commit, GroupedCommits} from 'interfaces';
/**
* Groups commits by their commit status.
* @param commits Commits to be grouped
*/
export const groupByCommitStatus = (commits: Commit[]): GroupedCommits =>
commits.reduce((result, commit) => {
const currValue = result[commit.commitStatus] || [];
cur... | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ | random_line_split |
mod.rs | pub mod pic;
pub mod pit;
pub mod port_io;
use driver::vga;
use core::fmt::Write;
use driver::vga::Writer;
pub fn pic_init() {
unsafe {
//start the initialisation of the PICs
port_io::outb(pic::PIC_MASTER_COMMAND, pic::ICW1_INIT | pic::ICW1_ICW4);
port_io::wait();
port_io::outb(pic... | port_io::wait();
//provide additional environment information
port_io::outb(pic::PIC_MASTER_DATA, pic::ICW4_8086); //operate in 8086 mode
port_io::wait();
port_io::outb(pic::PIC_SLAVE_DATA, pic::ICW4_8086); //operate in 8086 mode
port_io::wait();
//mask all inte... | //provide slave/master relationship information
port_io::outb(pic::PIC_MASTER_DATA, 4); //inform MASTER there is a SLAVE at IRQ2
port_io::wait();
port_io::outb(pic::PIC_SLAVE_DATA, 2); //inform SLAVE it is a cascade identity | random_line_split |
mod.rs | pub mod pic;
pub mod pit;
pub mod port_io;
use driver::vga;
use core::fmt::Write;
use driver::vga::Writer;
pub fn | () {
unsafe {
//start the initialisation of the PICs
port_io::outb(pic::PIC_MASTER_COMMAND, pic::ICW1_INIT | pic::ICW1_ICW4);
port_io::wait();
port_io::outb(pic::PIC_SLAVE_COMMAND, pic::ICW1_INIT | pic::ICW1_ICW4);
port_io::wait();
//provide the PIC vector offsets
... | pic_init | identifier_name |
mod.rs | pub mod pic;
pub mod pit;
pub mod port_io;
use driver::vga;
use core::fmt::Write;
use driver::vga::Writer;
pub fn pic_init() {
unsafe {
//start the initialisation of the PICs
port_io::outb(pic::PIC_MASTER_COMMAND, pic::ICW1_INIT | pic::ICW1_ICW4);
port_io::wait();
port_io::outb(pic... | {
pit::set_phase(hz);
vga::okay();
write!(Writer::new(), "Initialised the PIT, at a phase of {:#} Hz\n", hz)
.expect("Unexpected failure in write!()");
} | identifier_body | |
server.rs | #![feature(core)]
#![feature(path_ext)]
extern crate eve;
extern crate getopts;
extern crate url;
extern crate core;
use std::thread;
use std::env;
use std::fs::PathExt;
use getopts::Options;
use std::net::SocketAddr;
use core::str::FromStr;
use eve::server;
use eve::static_server;
#[allow(dead_code)]
fn main() | return;
}
// parse static file server address
let default_addr = SocketAddr::from_str("0.0.0.0:8080").unwrap();
let addr = match matches.opt_str("f") {
Some(ip) => {
match SocketAddr::from_str(&*ip) {
Ok(addr) => addr,
Err(_) => {
println!("WARNING: Could not parse static file... | {
// handle command line arguments
let args: Vec<String> = env::args().collect();
// define the command line arguments
let mut opts = Options::new();
opts.optopt("f", "file-server-address", "specify a socket address for the static file server. Defaults to 0.0.0.0:8080","SOCKET ADDRESS");
opts.optopt("s", ... | identifier_body |
server.rs | #![feature(core)]
#![feature(path_ext)]
extern crate eve;
extern crate getopts;
extern crate url;
extern crate core;
use std::thread;
use std::env;
use std::fs::PathExt;
use getopts::Options;
use std::net::SocketAddr;
use core::str::FromStr;
use eve::server;
use eve::static_server;
#[allow(dead_code)]
fn | () {
// handle command line arguments
let args: Vec<String> = env::args().collect();
// define the command line arguments
let mut opts = Options::new();
opts.optopt("f", "file-server-address", "specify a socket address for the static file server. Defaults to 0.0.0.0:8080","SOCKET ADDRESS");
opts.optopt("s... | main | identifier_name |
server.rs | #![feature(core)]
#![feature(path_ext)]
extern crate eve;
extern crate getopts;
extern crate url;
extern crate core;
use std::thread;
use std::env;
use std::fs::PathExt;
use getopts::Options;
use std::net::SocketAddr;
use core::str::FromStr;
use eve::server;
use eve::static_server;
#[allow(dead_code)]
fn main() {
... | // parse static file server address
let default_addr = SocketAddr::from_str("0.0.0.0:8080").unwrap();
let addr = match matches.opt_str("f") {
Some(ip) => {
match SocketAddr::from_str(&*ip) {
Ok(addr) => addr,
Err(_) => {
println!("WARNING: Could not parse static file server address.\nDefau... | print!("{}", opts.usage(""));
return;
}
| random_line_split |
server.rs | #![feature(core)]
#![feature(path_ext)]
extern crate eve;
extern crate getopts;
extern crate url;
extern crate core;
use std::thread;
use std::env;
use std::fs::PathExt;
use getopts::Options;
use std::net::SocketAddr;
use core::str::FromStr;
use eve::server;
use eve::static_server;
#[allow(dead_code)]
fn main() {
... |
// parse static file server address
let default_addr = SocketAddr::from_str("0.0.0.0:8080").unwrap();
let addr = match matches.opt_str("f") {
Some(ip) => {
match SocketAddr::from_str(&*ip) {
Ok(addr) => addr,
Err(_) => {
println!("WARNING: Could not parse static file server address.\nDef... | {
print!("{}", opts.usage(""));
return;
} | conditional_block |
lib.rs | pub use self::client::{DummyPdClient, RpcClient};
pub use self::config::Config;
pub use self::errors::{Error, Result};
pub use self::feature_gate::{Feature, FeatureGate};
pub use self::util::PdConnector;
pub use self::util::REQUEST_RECONNECT_INTERVAL;
use std::ops::Deref;
use futures::future::BoxFuture;
use kvproto::... |
/// Gets Region by Region id.
fn get_region_by_id(&self, _region_id: u64) -> PdFuture<Option<metapb::Region>> {
unimplemented!();
}
/// Gets Region and its leader by Region id.
fn get_region_leader_by_id(
&self,
_region_id: u64,
) -> PdFuture<Option<(metapb::Region, me... | {
unimplemented!();
} | identifier_body |
lib.rs | UnixSecs;
use txn_types::TimeStamp;
pub type Key = Vec<u8>;
pub type PdFuture<T> = BoxFuture<'static, Result<T>>;
#[derive(Default, Clone)]
pub struct RegionStat {
pub down_peers: Vec<pdpb::PeerStats>,
pub pending_peers: Vec<metapb::Peer>,
pub written_bytes: u64,
pub written_keys: u64,
pub read_by... | {
store.take_peer_address()
} | conditional_block | |
lib.rs | pub use self::client::{DummyPdClient, RpcClient};
pub use self::config::Config;
pub use self::errors::{Error, Result};
pub use self::feature_gate::{Feature, FeatureGate};
pub use self::util::PdConnector;
pub use self::util::REQUEST_RECONNECT_INTERVAL;
use std::ops::Deref;
use futures::future::BoxFuture;
use kvproto::... |
/// Registers a handler to the client, which will be invoked after reconnecting to PD.
///
/// Please note that this method should only be called once.
fn handle_reconnect<F: Fn() + Sync + Send + 'static>(&self, _: F)
where
Self: Sized,
{
}
fn get_gc_safe_point(&self) -> PdFutu... | random_line_split | |
lib.rs | pub use self::client::{DummyPdClient, RpcClient};
pub use self::config::Config;
pub use self::errors::{Error, Result};
pub use self::feature_gate::{Feature, FeatureGate};
pub use self::util::PdConnector;
pub use self::util::REQUEST_RECONNECT_INTERVAL;
use std::ops::Deref;
use futures::future::BoxFuture;
use kvproto::... | (&self) -> Result<u64> {
unimplemented!();
}
/// Creates the cluster with cluster ID, node, stores and first Region.
/// If the cluster is already bootstrapped, return ClusterBootstrapped error.
/// When a node starts, if it finds nothing in the node and
/// cluster is not bootstrapped, it ... | get_cluster_id | identifier_name |
distinct_on.rs | use crate::expression::SelectableExpression;
use crate::pg::Pg;
use crate::query_builder::order_clause::{NoOrderClause, OrderClause};
use crate::query_builder::{AstPass, QueryFragment, QueryId, SelectQuery, SelectStatement};
use crate::query_dsl::methods::DistinctOnDsl;
use crate::query_dsl::order_dsl::ValidOrderingFor... | }
}
impl<ST, F, S, D, W, O, LOf, G, Selection> DistinctOnDsl<Selection>
for SelectStatement<F, S, D, W, O, LOf, G>
where
Selection: SelectableExpression<F>,
Selection::SqlType: SingleValue,
Self: SelectQuery<SqlType = ST>,
O: ValidOrderingForDistinct<DistinctOnClause<Selection>>,
SelectStat... | self.0.walk_ast(out.reborrow())?;
out.push_sql(")");
Ok(()) | random_line_split |
distinct_on.rs | use crate::expression::SelectableExpression;
use crate::pg::Pg;
use crate::query_builder::order_clause::{NoOrderClause, OrderClause};
use crate::query_builder::{AstPass, QueryFragment, QueryId, SelectQuery, SelectStatement};
use crate::query_dsl::methods::DistinctOnDsl;
use crate::query_dsl::order_dsl::ValidOrderingFor... | (self, selection: Selection) -> Self::Output {
SelectStatement::new(
self.select,
self.from,
DistinctOnClause(selection),
self.where_clause,
self.order,
self.limit_offset,
self.group_by,
self.locking,
)
}... | distinct_on | identifier_name |
nirvana.rpc.js | /**
*
* @authors fudapeng (icefirefd@163.com)
* @date 2016-01-12 16:04:06
* @version $Id$
* depend jquery.jsonrpcclient.js
*/
(function($) {
'use strict';
var Monitor = function(targetId){
this.show = false;
this.progress = {};
this.maskTarget = null;
var pushMessage = function... | pushMessage(key, message);
this.maskTarget.showLoading();
this.show = true;
}else{
pushMessage(key, message);
}
};
this.hideMonitor = function(key){
if(this.show && this.maskTarget != null){
this.maskTarget.hideLoading();
th... | }else{
$maskTarget = $(targetId);
this.maskTarget = $maskTarget;
}
} | random_line_split |
nirvana.rpc.js | /**
*
* @authors fudapeng (icefirefd@163.com)
* @date 2016-01-12 16:04:06
* @version $Id$
* depend jquery.jsonrpcclient.js
*/
(function($) {
'use strict';
var Monitor = function(targetId){
this.show = false;
this.progress = {};
this.maskTarget = null;
var pushMessage = function... |
};
this.showMonitor = function(key, message){
if(!this.show){
if(this.maskTarget == null){
var $maskTarget = null;
if(targetId === undefined || targetId == null){
$maskTarget = $('body');
this.maskTarget = $maskTarget;
}else{
$maskTarget = $... | {
progress.key = message;
} | conditional_block |
process.js | 'use strict';
var _ = require('lodash');
var chai = require('chai');
var rewire = require('rewire');
var DepGraph = require('dependency-graph').DepGraph;
var init = rewire('../../../core/lib/init');
var mockSrvs = require('../../mocks/services');
// Setup
chai.should();
var depGraph = new DepGraph();... | var processed = mockSrvs.map(init.process);
var dependants = depGraph.dependantsOf('service00');
dependants.should.include('service01', 'service03');
});
});
}; | it('Should include all dependants of a service in the dependency graph', function(){ | random_line_split |
lib.rs | extern crate regex;
extern crate fall_tree;
extern crate fall_parse;
mod fall;
mod ast_ext;
pub use self::fall::language as lang_fall;
pub use self::fall::{
ERROR,
WHITESPACE,
EOL_COMMENT,
NODE,
CLASS,
TOKENIZER,
RULE,
VERBATIM,
AST,
PUB,
TEST,
EQ,
PIPE,
STAR,
... | TRAIT,
AST_TRAIT_DEF,
};
pub use self::fall::{
FallFile,
TokenizerDef,
LexRule,
SynRule,
Parameters,
Parameter,
Attributes,
Attribute,
AttributeValue,
VerbatimDef,
AstDef,
AstNodeDef,
AstClassDef,
AstTraitDef,
MethodDef,
AstSelector,
TestDef,
... | AST_NODE_DEF,
AST_CLASS_DEF,
METHOD_DEF,
AST_SELECTOR, | random_line_split |
helper.py | import re
from django.template.defaultfilters import slugify
from django.conf import settings
def check_internal_spam_words(content):
return any(word.lower() in (content.lower()) for word in settings.SPAM_WORDS)
def get_client_ip(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
... | (instance, value, slug_field_name='slug', queryset=None,
slug_separator='-'):
"""
http://djangosnippets.org/snippets/690/
Calculates and stores a unique slug of ``value`` for an instance.
``slug_field_name`` should be a string matching the name of the field to
store the sl... | unique_slugify | identifier_name |
helper.py | import re
from django.template.defaultfilters import slugify
from django.conf import settings
def check_internal_spam_words(content):
return any(word.lower() in (content.lower()) for word in settings.SPAM_WORDS)
def get_client_ip(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
... |
setattr(instance, slug_field.attname, slug)
def _slug_strip(value, separator='-'):
"""
Cleans up a slug by removing slug separator characters that occur at the
beginning or end of a slug.
If an alternate separator is used, it will also replace any instances of
the default '-' sep... | slug = original_slug
end = '%s%s' % (slug_separator, next)
if slug_len and len(slug) + len(end) > slug_len:
slug = slug[:slug_len-len(end)]
slug = _slug_strip(slug, slug_separator)
slug = '%s%s' % (slug, end)
next += 1 | conditional_block |
helper.py | import re
from django.template.defaultfilters import slugify
from django.conf import settings
def check_internal_spam_words(content):
return any(word.lower() in (content.lower()) for word in settings.SPAM_WORDS)
def get_client_ip(request):
|
def unique_slugify(instance, value, slug_field_name='slug', queryset=None,
slug_separator='-'):
"""
http://djangosnippets.org/snippets/690/
Calculates and stores a unique slug of ``value`` for an instance.
``slug_field_name`` should be a string matching the name of the fiel... | x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
return ip | identifier_body |
helper.py | import re
from django.template.defaultfilters import slugify
from django.conf import settings
def check_internal_spam_words(content):
return any(word.lower() in (content.lower()) for word in settings.SPAM_WORDS)
def get_client_ip(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
... |
``slug_field_name`` should be a string matching the name of the field to
store the slug in (and the field to check against for uniqueness).
``queryset`` usually doesn't need to be explicitly provided - it'll default
to using the ``.all()`` queryset from the model's default manager.
"""
... | slug_separator='-'):
"""
http://djangosnippets.org/snippets/690/
Calculates and stores a unique slug of ``value`` for an instance.
| random_line_split |
toolbox.rs | // +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> |
// | |
// | This file is part of Tuna. |
... |
&Event::KeyDown(key, kmod) => {
if key == self.key && kmod == NONE {
*tool = self.tool;
return Action::redraw().and_stop();
}
}
_ => {}
}
Action::ignore()
}
}
//=============================... | {
*tool = self.tool;
return Action::redraw().and_stop();
} | conditional_block |
toolbox.rs | // +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> |
// | |
// | This file is part of Tuna. |
... | {
tool: Tool,
key: Keycode,
icon: ToolIcon,
}
impl ToolPicker {
fn new(tool: Tool, key: Keycode) -> ToolPicker {
let icon = match tool {
Tool::Checkerboard => ToolIcon::Checkerboard,
Tool::Eyedropper => ToolIcon::Eyedropper,
Tool::Lasso => ToolIcon::Lasso,
... | ToolPicker | identifier_name |
toolbox.rs | // +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> |
// | |
// | This file is part of Tuna. |
... | }
}
fn picker(
x: i32,
y: i32,
tool: Tool,
key: Keycode,
) -> Box<dyn GuiElement<Tool, ()>> {
Box::new(SubrectElement::new(
ToolPicker::new(tool, key),
Rect::new(x, y, 20, 20),
))
}
}
impl GuiElement<EditorState, ()> for ... | {
let elements: Vec<Box<dyn GuiElement<Tool, ()>>> = vec![
Toolbox::picker(2, 2, Tool::Pencil, Keycode::P),
Toolbox::picker(26, 2, Tool::PaintBucket, Keycode::K),
Toolbox::picker(50, 2, Tool::PaletteReplace, Keycode::V),
Toolbox::picker(2, 26, Tool::Watercolor, Ke... | identifier_body |
toolbox.rs | // +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> |
// | |
// | This file is part of Tuna. |
... | return Action::redraw().and_stop();
}
}
_ => {}
}
Action::ignore()
}
}
//===========================================================================// | return Action::redraw().and_stop();
}
&Event::KeyDown(key, kmod) => {
if key == self.key && kmod == NONE {
*tool = self.tool; | random_line_split |
Step2aCorr_Gilson_etal_2012.py | with inputs from Matthieu Gilson)
in Brian2rc3 for CAMP 2016.
'''
#import modules and functions to be used
from brian2 import * # importing brian also does:
# 'from pylab import *' which imports:
# matplot like commands into the namespace, further
... |
else:
#prefs.codegen.target = 'numpy'
prefs.codegen.target = 'weave'
#prefs.codegen.target = 'cython'
import random
import time
# http://stackoverflow.com/questions/31057197/should-i-use-random-seed-or-numpy-random-seed-to-control-random-number-gener
np.random.seed(0) # set seed for reproducibility ... | set_device('cpp_standalone', build_on_run=False) | conditional_block |
Step2aCorr_Gilson_etal_2012.py | with inputs from Matthieu Gilson)
in Brian2rc3 for CAMP 2016.
'''
#import modules and functions to be used
from brian2 import * # importing brian also does:
# 'from pylab import *' which imports:
# matplot like commands into the namespace, further
... | (PR,P,l,csqrt):
con = Synapses(PR,P,'',on_pre='spikerate+='+str(csqrt)+'/dt')
con.connect(True)
con.delay = 0.*ms
con1 = Synapses(PR,P,'',on_pre='spikerate='+str(baseline_input_rates[l*Ninp]/Hz)+'*Hz')
con1.connect(True)
con1.delay = simdt
inpconns.append((con,con1))
for k in range(3):
f... | correlate_spike_trains | identifier_name |
Step2aCorr_Gilson_etal_2012.py | (with inputs from Matthieu Gilson)
in Brian2rc3 for CAMP 2016.
'''
#import modules and functions to be used
from brian2 import * # importing brian also does:
# 'from pylab import *' which imports:
# matplot like commands into the namespace, further
... |
for k in range(3):
for l in range(Npools):
if Q[k,l]!=0.:
correlate_spike_trains(Pinps[k],Ppools[l],l,Q[k,l])
# ###########################################
# Connecting the network
# ###########################################
con = Synapses(Pinp1,P,stdp_eqns,\
on_pre='A+=w*0... | con = Synapses(PR,P,'',on_pre='spikerate+='+str(csqrt)+'/dt')
con.connect(True)
con.delay = 0.*ms
con1 = Synapses(PR,P,'',on_pre='spikerate='+str(baseline_input_rates[l*Ninp]/Hz)+'*Hz')
con1.connect(True)
con1.delay = simdt
inpconns.append((con,con1)) | identifier_body |
Step2aCorr_Gilson_etal_2012.py | with inputs from Matthieu Gilson)
in Brian2rc3 for CAMP 2016.
'''
#import modules and functions to be used
from brian2 import * # importing brian also does:
# 'from pylab import *' which imports:
# matplot like commands into the namespace, further
... |
# weights monitor
wm = StateMonitor(con,'w',record=range(Npools*Ninp), dt=1*second)
# ###########################################
# Simulate
# ###########################################
# a simple run would not include the monitors
net = Network(collect()) # collects Brian2 objects in current context
net... |
# voltage monitor
sm_rho = StateMonitor(P,'rho_out',record=[0]) | random_line_split |
auth.service.ts | import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';
//import 'rxjs/add/operator/map';
@Injectable()
export class AuthService {
userName: string;
loggedIn: boolean;
url = 'http://localhost/proyectosLaravel/c... | this.loggedIn = true;
} else {
this.loggedIn = false;
}
return this.loggedIn;
}
GetUser(){
let temp = localStorage.getItem('user');
temp = JSON.parse(temp);
return temp;
}
} | random_line_split | |
auth.service.ts | import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';
//import 'rxjs/add/operator/map';
@Injectable()
export class AuthService {
userName: string;
loggedIn: boolean;
url = 'http://localhost/proyectosLaravel/c... | (private http: Http) {
this.userName = '';
this.loggedIn = false;
}
login(userInfo) {
let url = `${this.url}/login`;
let iJon = JSON.stringify(userInfo);
let headers = new Headers();
//headers.append('Access-Control-Allow-Origin', '*');
headers.append('Content-Type', ... | constructor | identifier_name |
auth.service.ts | import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';
//import 'rxjs/add/operator/map';
@Injectable()
export class AuthService {
userName: string;
loggedIn: boolean;
url = 'http://localhost/proyectosLaravel/c... |
return this.loggedIn;
}
GetUser(){
let temp = localStorage.getItem('user');
temp = JSON.parse(temp);
return temp;
}
} | {
this.loggedIn = false;
} | conditional_block |
range-request-to-different-origins-worker.js | // This worker is meant to test range requests where the responses come from
// multiple origins. It forwards the first request to a cross-origin URL
// (generating an opaque response). The server is expected to return a 206
// Partial Content response. Then the worker lets subsequent range requests
// fall back to ne... |
self.addEventListener('fetch', e => {
const url = new URL(e.request.url);
if (url.search.indexOf('VIDEO') == -1) {
// Fall back for non-video.
return;
}
// Make the first request go cross-origin.
if (is_initial_request()) {
const cross_origin_url = get_host_info().HTTPS_REMOTE_O... | {
const old = initial;
initial = false;
return old;
} | identifier_body |
range-request-to-different-origins-worker.js | // This worker is meant to test range requests where the responses come from
// multiple origins. It forwards the first request to a cross-origin URL
// (generating an opaque response). The server is expected to return a 206
// Partial Content response. Then the worker lets subsequent range requests
// fall back to ne... | initial = false;
return old;
}
self.addEventListener('fetch', e => {
const url = new URL(e.request.url);
if (url.search.indexOf('VIDEO') == -1) {
// Fall back for non-video.
return;
}
// Make the first request go cross-origin.
if (is_initial_request()) {
const cross_origin_ur... |
let initial = true;
function is_initial_request() {
const old = initial; | random_line_split |
range-request-to-different-origins-worker.js | // This worker is meant to test range requests where the responses come from
// multiple origins. It forwards the first request to a cross-origin URL
// (generating an opaque response). The server is expected to return a 206
// Partial Content response. Then the worker lets subsequent range requests
// fall back to ne... | () {
const old = initial;
initial = false;
return old;
}
self.addEventListener('fetch', e => {
const url = new URL(e.request.url);
if (url.search.indexOf('VIDEO') == -1) {
// Fall back for non-video.
return;
}
// Make the first request go cross-origin.
if (is_initial_request()) {... | is_initial_request | identifier_name |
range-request-to-different-origins-worker.js | // This worker is meant to test range requests where the responses come from
// multiple origins. It forwards the first request to a cross-origin URL
// (generating an opaque response). The server is expected to return a 206
// Partial Content response. Then the worker lets subsequent range requests
// fall back to ne... |
// Make the first request go cross-origin.
if (is_initial_request()) {
const cross_origin_url = get_host_info().HTTPS_REMOTE_ORIGIN +
url.pathname + url.search;
const cross_origin_request = new Request(cross_origin_url,
{mode: 'no-cors', headers: e.request.headers});
e.re... | {
// Fall back for non-video.
return;
} | conditional_block |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![feature(alloc)]
#![feature(box_syntax)]
#![feature(core_intrinsics)]
#![feature(custom_derive)]
#![feature(fnbo... |
// Workaround for lack of `ptr_eq` on Arcs...
#[inline]
pub fn arc_ptr_eq<T: 'static + Send + Sync>(a: &Arc<T>, b: &Arc<T>) -> bool {
let a: &T = &**a;
let b: &T = &**b;
(a as *const T) == (b as *const T)
} |
pub fn breakpoint() {
unsafe { ::std::intrinsics::breakpoint() };
} | random_line_split |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![feature(alloc)]
#![feature(box_syntax)]
#![feature(core_intrinsics)]
#![feature(custom_derive)]
#![feature(fnbo... | () {
unsafe { ::std::intrinsics::breakpoint() };
}
// Workaround for lack of `ptr_eq` on Arcs...
#[inline]
pub fn arc_ptr_eq<T: 'static + Send + Sync>(a: &Arc<T>, b: &Arc<T>) -> bool {
let a: &T = &**a;
let b: &T = &**b;
(a as *const T) == (b as *const T)
}
| breakpoint | identifier_name |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![feature(alloc)]
#![feature(box_syntax)]
#![feature(core_intrinsics)]
#![feature(custom_derive)]
#![feature(fnbo... |
// Workaround for lack of `ptr_eq` on Arcs...
#[inline]
pub fn arc_ptr_eq<T: 'static + Send + Sync>(a: &Arc<T>, b: &Arc<T>) -> bool {
let a: &T = &**a;
let b: &T = &**b;
(a as *const T) == (b as *const T)
}
| {
unsafe { ::std::intrinsics::breakpoint() };
} | identifier_body |
rustkernel.rs | /*
* Copyright (C) 2018, Nils Asmussen <nils@os.inf.tu-dresden.de>
* Economic rights: Technische Universitaet Dresden (Germany)
*
* This file is part of M3 (Microkernel-based SysteM for Heterogeneous Manycores).
*
* M3 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Genera... | mod syscalls;
mod tests;
mod workloop; | mod cap;
mod com;
mod mem;
mod pes;
mod platform; | random_line_split |
widgets_radio.py | # Copyright (c) 2014-2015 Cedric Bellegarde <cedric.bellegarde@adishatz.org>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later vers... | self.set_property('halign', Gtk.Align.START)
def set_sensitive(self, b):
"""
Ignore set sensitive
"""
pass
def get_id(self):
"""
Return widget id (same value for all radio widgets)
"""
return Type.RADIOS
def do_get_preferred... | """
Init radio widget
@param name as string
@param radios_manager as RadiosManager
"""
AlbumWidget.__init__(self, None)
builder = Gtk.Builder()
builder.add_from_resource('/org/gnome/Lollypop/RadioWidget.ui')
builder.connect_signals(self)
... | identifier_body |
widgets_radio.py | # Copyright (c) 2014-2015 Cedric Bellegarde <cedric.bellegarde@adishatz.org>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later vers... |
def edit(self, widget):
"""
Edit radio
@param widget as Gtk.Widget
"""
self._popover = RadioPopover(self._name, self._radios_manager)
self._popover.set_relative_to(widget)
self._popover.show()
#######################
# PRIVATE #
########... | self._selected = Lp.player.current_track.id == Type.RADIOS\
and self._name == Lp.player.current_track.artist
surface = Lp.art.get_radio(
self._name,
ArtSize.BIG,
self._selected)
self._cover.set_from_surface(s... | conditional_block |
widgets_radio.py | # Copyright (c) 2014-2015 Cedric Bellegarde <cedric.bellegarde@adishatz.org>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later vers... | def __init__(self, name, radios_manager):
"""
Init radio widget
@param name as string
@param radios_manager as RadiosManager
"""
AlbumWidget.__init__(self, None)
builder = Gtk.Builder()
builder.add_from_resource('/org/gnome/Lollypop/RadioWi... | Widget with radio cover and title
"""
| random_line_split |
widgets_radio.py | # Copyright (c) 2014-2015 Cedric Bellegarde <cedric.bellegarde@adishatz.org>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later vers... | (self, widget, event):
"""
Edit radio on right click
@param widget as Gtk.Widget
@param event as Gdk.Event
"""
if event.button != 1:
self.edit(widget)
def _on_eventbox_realize1(self, eventbox):
"""
Change cursor over cover ... | _on_cover_press | identifier_name |
coroutine.py | import asyncio
from unittest.mock import MagicMock
def SimpleCoroutineMock(f=lambda *args, **kwargs: None):
builder = CoroutineMockBuilder()
return builder.addDelegate(f).build().mock()
class CoroutineMock(object):
# Handy for debugging failing tests in the debugger.
__blocking_dict = {}
def __... | (self):
return self.__mock
async def waitForSingleCall(self):
await self.start().wait()
self.unblock()
await self.end().wait()
class CoroutineMockBuilder(object):
def __init__(self):
self.__block = None
self.__returnSequence = []
def blocks(self):
... | mock | identifier_name |
coroutine.py | import asyncio
from unittest.mock import MagicMock
def SimpleCoroutineMock(f=lambda *args, **kwargs: None):
builder = CoroutineMockBuilder()
return builder.addDelegate(f).build().mock()
class CoroutineMock(object):
# Handy for debugging failing tests in the debugger.
| nonlocal returnIndex
try:
self.__endingEvent.clear()
self.__startingEvent.set()
if (self.__block is not None):
self.__blocking_dict[id(self)] = self
try:
await self.__block.wait()
... | __blocking_dict = {}
def __init__(self, returnSequence, block:asyncio.Event):
self.__startingEvent = asyncio.Event()
self.__endingEvent = asyncio.Event()
self.__returnSequence = tuple(returnSequence)
if (len(self.__returnSequence) < 1):
self.__returnSequence = (lambda *a... | identifier_body |
coroutine.py | import asyncio
from unittest.mock import MagicMock
def SimpleCoroutineMock(f=lambda *args, **kwargs: None):
builder = CoroutineMockBuilder()
return builder.addDelegate(f).build().mock()
class CoroutineMock(object):
# Handy for debugging failing tests in the debugger.
__blocking_dict = {}
def __... |
returnFunc = self.__returnSequence[returnIndex % self.__returnSequenceLen]
returnIndex += 1
return returnFunc(*args, **kwargs)
finally:
self.__startingEvent.clear()
self.__endingEvent.set()
return MagicMock(wraps=cr)
... | self.__blocking_dict[id(self)] = self
try:
await self.__block.wait()
finally:
del self.__blocking_dict[id(self)]
self.__block.clear() | conditional_block |
coroutine.py | import asyncio
from unittest.mock import MagicMock
def SimpleCoroutineMock(f=lambda *args, **kwargs: None):
builder = CoroutineMockBuilder()
return builder.addDelegate(f).build().mock()
class CoroutineMock(object):
# Handy for debugging failing tests in the debugger.
__blocking_dict = {}
def __... |
class CoroutineMockBuilder(object):
def __init__(self):
self.__block = None
self.__returnSequence = []
def blocks(self):
return self.blocksOn(asyncio.Event())
def blocksOn(self, event:asyncio.Event):
self.__block = event
return self
def exception(self, e, rep... | await self.start().wait()
self.unblock()
await self.end().wait() | random_line_split |
ZTAPExtractFields.py | from CommonServerPython import *
from typing import Dict, Any, List
import traceback
""" STANDALONE FUNCTION """
def extract_fields(value) -> List:
"""
Extracts ordered ZTAP fields for use in analytics
"""
output = []
for event in value:
fields = {}
for field in event["fields"]:... |
""" MAIN FUNCTION """
def main():
try:
return_results(extract_fields_command(demisto.args()))
except Exception as ex:
demisto.error(traceback.format_exc()) # print the traceback
return_error(f"Failed to execute BaseScript. Error: {str(ex)}")
""" ENTRY POINT """
if __name__ in (... | value = args.get("value", [])
if not value:
raise ValueError("value not specified")
# Call the standalone function and get the raw response
result = extract_fields(value)
return CommandResults(
outputs_prefix="ZTAPExtractFields",
outputs_key_field="",
outputs=result,
... | identifier_body |
ZTAPExtractFields.py | from CommonServerPython import *
from typing import Dict, Any, List
import traceback
""" STANDALONE FUNCTION """
def extract_fields(value) -> List:
"""
Extracts ordered ZTAP fields for use in analytics
"""
output = []
for event in value:
fields = {}
for field in event["fields"]:... |
# Call the standalone function and get the raw response
result = extract_fields(value)
return CommandResults(
outputs_prefix="ZTAPExtractFields",
outputs_key_field="",
outputs=result,
)
""" MAIN FUNCTION """
def main():
try:
return_results(extract_fields_comman... | raise ValueError("value not specified") | conditional_block |
ZTAPExtractFields.py | from CommonServerPython import *
from typing import Dict, Any, List
import traceback
""" STANDALONE FUNCTION """
def extract_fields(value) -> List:
"""
Extracts ordered ZTAP fields for use in analytics
"""
output = []
for event in value:
fields = {}
for field in event["fields"]:... | ():
try:
return_results(extract_fields_command(demisto.args()))
except Exception as ex:
demisto.error(traceback.format_exc()) # print the traceback
return_error(f"Failed to execute BaseScript. Error: {str(ex)}")
""" ENTRY POINT """
if __name__ in ("__main__", "__builtin__", "builtin... | main | identifier_name |
ZTAPExtractFields.py | from CommonServerPython import *
from typing import Dict, Any, List
import traceback
""" STANDALONE FUNCTION """
def extract_fields(value) -> List:
"""
Extracts ordered ZTAP fields for use in analytics
"""
output = []
for event in value:
fields = {} | for field in event["fields"]:
key = field["key"]
value = field["value"]
fields[key] = value
output.append(fields)
return output
""" COMMAND FUNCTION """
def extract_fields_command(args: Dict[str, Any]) -> CommandResults:
value = args.get("value", [])
... | random_line_split | |
grids.rs |
}
}
#[inline]
pub fn modify_bits_in_word(&mut self, row: usize, word_col: usize, mask: u64, op: BitOperation) {
match op {
BitOperation::Set => self[row][word_col] |= mask,
BitOperation::Clear => self[row][word_col] &= !mask,
BitOperation::Toggle =>... | }
let run_last_col = col + rle_len - 1;
if let Some(_last_col) = last_col {
if _last_col < run_last_col {
last_col = Some(run_last_col);
}
} else {
... | {
let (width, height) = (self.width(), self.height());
let mut first_row = None;
let mut last_row = None;
let mut first_col = None;
let mut last_col = None;
for row in 0..height {
let mut col = 0;
while col < width {
let (rle_len, c... | identifier_body |
grids.rs | else {
0
}
}
#[inline]
pub fn modify_bits_in_word(&mut self, row: usize, word_col: usize, mask: u64, op: BitOperation) {
match op {
BitOperation::Set => self[row][word_col] |= mask,
BitOperation::Clear => self[row][word_col] &= !mask,
Bi... | {
self.0[0].len()
} | conditional_block | |
grids.rs |
}
}
#[inline]
pub fn modify_bits_in_word(&mut self, row: usize, word_col: usize, mask: u64, op: BitOperation) {
match op {
BitOperation::Set => self[row][word_col] |= mask,
BitOperation::Clear => self[row][word_col] &= !mask,
BitOperation::Toggle =>... | (result: &mut String, output_col: &mut usize, rle_len: usize, ch: char) {
let what_to_add = if rle_len == 1 {
let mut s = String::with_capacity(1);
s.push(ch);
s
} else { format!("{}{}", rle_len, ch) };
if *output_col + what_to_add.len(... | push | identifier_name |
grids.rs | _col] &= !mask,
BitOperation::Toggle => self[row][word_col] ^= mask,
}
}
/// Sets, clears, or toggles a rectangle of bits.
///
/// # Panics
///
/// This function will panic if `region` is out of range.
pub fn modify_region(&mut self, region: Region, op: BitOperation) {
... | }
row += 1;
col = 0;
line_ends_buffered += 1; | random_line_split | |
int.rs | use arch::int;
pub fn mask_interrupt(i: u32, mask: bool) {
int::mask_interrupt(i, mask);
}
pub fn set_int(i: u32, idt_idx: u32) {
int::set_int(i, idt_idx);
}
pub fn fire_timer() {
int::fire_timer();
}
pub fn enable_interrupts() {
int::enable_interrupts();
}
pub fn disable_interrupts() {
int::di... | loop{};
},
_ => {
//println!("OTHER INTERRUPT {}", ctx.int_id);
//loop{};
}
}
} | disable_interrupts();
loop{}
}
14 => {
println!("PAGE FAULT 0x{:x}, addr: 0x{:x}", error_code, retaddr); | random_line_split |
int.rs | use arch::int;
pub fn mask_interrupt(i: u32, mask: bool) {
int::mask_interrupt(i, mask);
}
pub fn set_int(i: u32, idt_idx: u32) {
int::set_int(i, idt_idx);
}
pub fn fire_timer() |
pub fn enable_interrupts() {
int::enable_interrupts();
}
pub fn disable_interrupts() {
int::disable_interrupts();
}
pub fn interrupt_handler(int_id: u32, error_code: u32, retaddr: usize) {
match int_id {
80 => {
println!("[ TASK ] System call from user space");
}
81 ... | {
int::fire_timer();
} | identifier_body |
int.rs | use arch::int;
pub fn mask_interrupt(i: u32, mask: bool) {
int::mask_interrupt(i, mask);
}
pub fn set_int(i: u32, idt_idx: u32) {
int::set_int(i, idt_idx);
}
pub fn fire_timer() {
int::fire_timer();
}
pub fn enable_interrupts() {
int::enable_interrupts();
}
pub fn disable_interrupts() {
int::di... |
}
}
| {
//println!("OTHER INTERRUPT {}", ctx.int_id);
//loop{};
} | conditional_block |
int.rs | use arch::int;
pub fn mask_interrupt(i: u32, mask: bool) {
int::mask_interrupt(i, mask);
}
pub fn set_int(i: u32, idt_idx: u32) {
int::set_int(i, idt_idx);
}
pub fn fire_timer() {
int::fire_timer();
}
pub fn enable_interrupts() {
int::enable_interrupts();
}
pub fn | () {
int::disable_interrupts();
}
pub fn interrupt_handler(int_id: u32, error_code: u32, retaddr: usize) {
match int_id {
80 => {
println!("[ TASK ] System call from user space");
}
81 => {
println!("[ OK ] Interrupt test passes");
},
33 => prin... | disable_interrupts | identifier_name |
issue-41936-variance-coerce-unsized-cycle.rs | // Copyright 2016 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 ... | (){}
| main | identifier_name |
issue-41936-variance-coerce-unsized-cycle.rs | // Copyright 2016 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 ... |
// Change the array to a non-array, and error disappears
// Adding a new field to the end keeps the error
struct LogDataBuf([u8;8]);
struct Aref<T: ?Sized>
{
// Inner structure triggers the error, removing the inner removes the message.
ptr: Box<ArefInner<T>>,
}
impl<T: ?Sized + marker::Unsize<U>, U: ?Sized> ... | #![feature(unsize)]
#![feature(coerce_unsized)]
use std::{marker,ops}; | random_line_split |
renderer.ts | import { mat4 } from 'gl-matrix'
import { makeClear } from 'tvs-painter/dist/utils/context'
import { plane } from 'tvs-painter/dist/utils/geometry/plane'
import { events, Q, paint } from './context'
import base from './glsl/base.frag.glsl'
import planeFrag from './glsl/plane-material.frag.glsl'
import planeVert from '.... | // ===== scene =====
const planMat = mat4.fromTranslation(mat4.create(), [0, 0, -3])
const rotation = 0.001
const projection = mat4.perspective(mat4.create(), 45, 1, 0.01, 10)
const form = Q.getForm('plane').update(plane(2, 2))
const shade = Q.getShade('plane').update({
vert: planeVert,
frag: planeFrag,
})
export... | })
| random_line_split |
table-module.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 {NgModule} from '@angular/core';
import {MatTable} from './table';
import {CdkTableModule} from '@angular/cdk/... | MatFooterRow,
];
@NgModule({
imports: [CdkTableModule, CommonModule, MatCommonModule],
exports: EXPORTED_DECLARATIONS,
declarations: EXPORTED_DECLARATIONS,
})
export class MatTableModule {} | MatFooterCell,
// Row directions
MatHeaderRow,
MatRow, | random_line_split |
table-module.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 {NgModule} from '@angular/core';
import {MatTable} from './table';
import {CdkTableModule} from '@angular/cdk/... | {}
| MatTableModule | identifier_name |
lib.rs | //! Utitilty for writing nagios-style check scripts/plugins
//!
//! There are three things:
//!
//! * The `Status` enum for representing health status
//! * The `procfs` module, which contains rusty representations of some files
//! from /proc
//! * A few scripts in the bin directory, which contain actual
//! nagio... | /// Represent the nagios-ish error status of a script.
#[must_use]
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Deserialize)]
pub enum Status {
/// Unexpected result
Unknown,
/// Everything is fine
Ok,
/// Something is weird, but don't necessary call anybody
Warning,
/// OMG ... | }
/// All results are TabinResults
pub type TabinResult<T> = Result<T, TabinError>;
| random_line_split |
lib.rs | //! Utitilty for writing nagios-style check scripts/plugins
//!
//! There are three things:
//!
//! * The `Status` enum for representing health status
//! * The `procfs` module, which contains rusty representations of some files
//! from /proc
//! * A few scripts in the bin directory, which contain actual
//! nagio... | () {
use crate::Status::*;
assert!(Ok < Critical);
assert!(Ok < Warning);
assert_eq!(std::cmp::max(Warning, Critical), Critical)
}
| comparison_is_as_expected | identifier_name |
lib.rs | //! Utitilty for writing nagios-style check scripts/plugins
//!
//! There are three things:
//!
//! * The `Status` enum for representing health status
//! * The `procfs` module, which contains rusty representations of some files
//! from /proc
//! * A few scripts in the bin directory, which contain actual
//! nagio... |
}
impl FromStr for Status {
type Err = TabinError;
/// Primarily useful to construct from argv
fn from_str(s: &str) -> TabinResult<Status> {
use crate::Status::{Critical, Unknown, Warning};
match s {
"ok" => Ok(Status::Ok),
"warning" => Ok(Warning),
"cr... | {
["ok", "warning", "critical", "unknown"]
} | identifier_body |
settings.py | import os
# Django settings for Storefront project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NA... | SECRET_KEY = '5ff9b-_!8o66m+4dq!v!u3lq*5o)$oqgj1o#byi_j1l^koeko_'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDL... | # Make this unique, and don't share it with anybody. | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.