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 |
|---|---|---|---|---|
view.py | # -*- coding: utf-8 -*-
__author__ = 'itconsense@gmail.com'
from collections import OrderedDict
from math import pi
from Products.Five import BrowserView
from plone import api
import base64
import logging
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import six
LOG = logging.getLogger('eva... |
class Result(object):
def __init__(self):
self.good = ''
self.details = {}
class EvaluateTestView(BrowserView):
no_text = 'Kein Textbaustein'
factors = {
'Meistens': 5,
'Manchmal': 3,
'Selten': 1,
'Nie': 0
}
pie_factors = {
'Meistens': 3... | def __call__(self):
portal_setup = api.portal.get_tool(name='portal_setup')
portal_setup.runImportStepFromProfile(
'profile-plonetheme.sunburst:default', 'cssregistry', run_dependencies=False)
portal_skins = api.portal.get_tool(name='portal_skins')
custom = portal_skins['cust... | identifier_body |
view.py | # -*- coding: utf-8 -*-
__author__ = 'itconsense@gmail.com'
from collections import OrderedDict
from math import pi
from Products.Five import BrowserView
from plone import api
import base64
import logging
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import six
LOG = logging.getLogger('eva... |
summary_elements = self.get_summary_elements()
if summary < 75:
result['summary'] = summary_elements['bad']
elif 75 >= summary < 130:
result['summary'] = summary_elements['med']
else:
result['summary'] = summary_elements['good']
self.chart_img... | LOG.warn('Details of group {0} are empty!'.format(group)) | conditional_block |
generic-struct.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | <TKey, TValue> {
key: TKey,
value: TValue
}
fn main() {
let int_int = AGenericStruct { key: 0, value: 1 };
let int_float = AGenericStruct { key: 2, value: 3.5f64 };
let float_int = AGenericStruct { key: 4.5f64, value: 5 };
let float_int_float = AGenericStruct {
key: 6.5f64,
val... | AGenericStruct | identifier_name |
generic-struct.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license | // option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-tidy-linelength
// Some versions of the non-rust-enabled LLDB print the wrong generic
// parameter type names in this test.
// rust-lldb
// compile-flags:-g
// === GDB TESTS ===============================... | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your | random_line_split |
test_GffGeneParser.py | #!/usr/bin/env python
import unittest
from SDDetector.Entities.Gene import Gene
from SDDetector.Entities.Transcript import Transcript
from SDDetector.Entities.CDS import CDS
from SDDetector.Parser.Gff.GffGeneParser import GffGeneParser
class TestGffGeneParser(unittest.TestCase):
def setUp(self):
pass
... | if __name__ == "__main__":
suite = unittest.TestLoader().loadTestsFromTestCase(TestGffGeneParser)
unittest.TextTestRunner(verbosity=2).run(suite) |
# self.assertEqual(iGffGeneParser.getAllGenes()[0],lGenes[0])
| random_line_split |
test_GffGeneParser.py | #!/usr/bin/env python
import unittest
from SDDetector.Entities.Gene import Gene
from SDDetector.Entities.Transcript import Transcript
from SDDetector.Entities.CDS import CDS
from SDDetector.Parser.Gff.GffGeneParser import GffGeneParser
class TestGffGeneParser(unittest.TestCase):
def setUp(self):
pass
... | suite = unittest.TestLoader().loadTestsFromTestCase(TestGffGeneParser)
unittest.TextTestRunner(verbosity=2).run(suite) | conditional_block | |
test_GffGeneParser.py | #!/usr/bin/env python
import unittest
from SDDetector.Entities.Gene import Gene
from SDDetector.Entities.Transcript import Transcript
from SDDetector.Entities.CDS import CDS
from SDDetector.Parser.Gff.GffGeneParser import GffGeneParser
class TestGffGeneParser(unittest.TestCase):
def | (self):
pass
def tearDown(self):
pass
def test_getAllGenes(self):
"""Test getAllGenes method"""
iGffGeneParser = GffGeneParser("test-data/gene.gff3")
lGenes = [Gene('G00001','Chr1',23988,24919,-1,[Transcript('G00001.1','Chr1',23988,24919,-1,'G00001',[CDS('G00001.1_cds_1... | setUp | identifier_name |
test_GffGeneParser.py | #!/usr/bin/env python
import unittest
from SDDetector.Entities.Gene import Gene
from SDDetector.Entities.Transcript import Transcript
from SDDetector.Entities.CDS import CDS
from SDDetector.Parser.Gff.GffGeneParser import GffGeneParser
class TestGffGeneParser(unittest.TestCase):
def setUp(self):
pass
... |
# lGenes = [Gene('G00001','Chr1',23988,24919,-1,[Transcript('G00001.1','Chr1',23988,24919,-1,'G00001',[CDS('G00001.1_cds_1','Chr1',23988,24083, -1, 'G00001.1'),CDS('G00001.1_cds_1','Chr1',24274,24427,-1,'G00001.1'),CDS('G00001.1_cds_1','Chr1',24489,24919,-1,'G00001.1')])])]
# self.assertEqual(iGffGenePa... | """Test getAllGenes method"""
# iGffGeneParser = GffGeneParser("/home/nlapalu/Workspace/Github/SDDetector/data/arabidopsis/TAIR10.new.gff3")
pass | identifier_body |
protobuf-bin-gen-rust.rs | #![crate_type = "bin"]
#![feature(globs)]
extern crate protobuf;
extern crate getopts;
use std::io::fs::*;
use std::io::Reader;
use std::io::Writer;
use std::path::Path;
use std::os;
use protobuf::parse_from_reader;
use protobuf::descriptor::*;
use protobuf::codegen::*;
fn write_file(bin: &str, gen_options: &GenOp... | () {
let args = os::args();
let opts = vec!();
let matches = getopts::getopts(args.tail(), opts.as_slice()).unwrap();
let pb_bin = match matches.free.as_slice() {
[ref pb_bin] => pb_bin.to_string(),
_ => panic!("must have exactly one argument")
};
let gen_options = GenOptions {
... | main | identifier_name |
protobuf-bin-gen-rust.rs | #![crate_type = "bin"]
#![feature(globs)]
extern crate protobuf;
extern crate getopts;
use std::io::fs::*;
use std::io::Reader;
use std::io::Writer;
use std::path::Path;
use std::os;
use protobuf::parse_from_reader;
use protobuf::descriptor::*;
use protobuf::codegen::*;
fn write_file(bin: &str, gen_options: &GenOp... | }
}
fn main() {
let args = os::args();
let opts = vec!();
let matches = getopts::getopts(args.tail(), opts.as_slice()).unwrap();
let pb_bin = match matches.free.as_slice() {
[ref pb_bin] => pb_bin.to_string(),
_ => panic!("must have exactly one argument")
};
let gen_options ... | for r in results.iter() {
let mut file_writer = File::create(&Path::new(r.name.as_slice())).unwrap();
file_writer.write(r.content.as_slice()).unwrap(); | random_line_split |
protobuf-bin-gen-rust.rs | #![crate_type = "bin"]
#![feature(globs)]
extern crate protobuf;
extern crate getopts;
use std::io::fs::*;
use std::io::Reader;
use std::io::Writer;
use std::path::Path;
use std::os;
use protobuf::parse_from_reader;
use protobuf::descriptor::*;
use protobuf::codegen::*;
fn write_file(bin: &str, gen_options: &GenOp... |
fn main() {
let args = os::args();
let opts = vec!();
let matches = getopts::getopts(args.tail(), opts.as_slice()).unwrap();
let pb_bin = match matches.free.as_slice() {
[ref pb_bin] => pb_bin.to_string(),
_ => panic!("must have exactly one argument")
};
let gen_options = GenOp... | {
let mut is = File::open(&Path::new(bin)).unwrap();
let fds = parse_from_reader::<FileDescriptorSet>(&mut is as &mut Reader).unwrap();
let file_names: Vec<String> = fds.get_file().iter()
.map(|f| f.get_name().to_string())
.collect();
let results = gen(fds.get_file(), file_names.as_slic... | identifier_body |
borrowck-let-suggestion-suffixes.rs | fn id<T>(x: T) -> T { x }
fn f() {
let old = ['o']; // statement 0
let mut v1 = Vec::new(); // statement 1
|
v2.push(&young[0]); // statement 4
//~^ ERROR `young[_]` does not live long enough
//~| NOTE borrowed value does not live long enough
} //~ NOTE `young[_]` dropped here while still borrowed
let mut v3 = Vec::new(); // statement 5
v3.push(&id('x')); // statement 6
... | let mut v2 = Vec::new(); // statement 2
{
let young = ['y']; // statement 3 | random_line_split |
borrowck-let-suggestion-suffixes.rs | fn id<T>(x: T) -> T { x }
fn f() {
let old = ['o']; // statement 0
let mut v1 = Vec::new(); // statement 1
let mut v2 = Vec::new(); // statement 2
{
let young = ['y']; // statement 3
v2.push(&young[0]); // statement 4
//~^ ERROR `young[_]` does not live lon... | (&self) { } }
impl<T> Fake for T { }
| use_ref | identifier_name |
borrowck-let-suggestion-suffixes.rs | fn id<T>(x: T) -> T |
fn f() {
let old = ['o']; // statement 0
let mut v1 = Vec::new(); // statement 1
let mut v2 = Vec::new(); // statement 2
{
let young = ['y']; // statement 3
v2.push(&young[0]); // statement 4
//~^ ERROR `young[_]` does not live long enough
//~| NOT... | { x } | identifier_body |
run_tests.py | #!/usr/bin/env python3
import random
import numpy as np
import gym
from gym_minigrid.register import env_list
from gym_minigrid.minigrid import Grid, OBJECT_TO_IDX
# Test specifically importing a specific environment
from gym_minigrid.envs import DoorKeyEnv
# Test importing wrappers
from gym_minigrid.wrappers import... | env.reset()
env.step(0)
env.close()
env = gym.make(env_name)
env = ImgObsWrapper(env)
env.reset()
env.step(0)
env.close()
# Test the fully observable wrapper
env = gym.make(env_name)
env = FullyObsWrapper(env)
env.reset()
obs, _, _, _ = env.step(0)
a... | env = gym.make(env_name)
env = ReseedWrapper(env)
for _ in range(10): | random_line_split |
run_tests.py | #!/usr/bin/env python3
import random
import numpy as np
import gym
from gym_minigrid.register import env_list
from gym_minigrid.minigrid import Grid, OBJECT_TO_IDX
# Test specifically importing a specific environment
from gym_minigrid.envs import DoorKeyEnv
# Test importing wrappers
from gym_minigrid.wrappers import... |
env.reset()
# Run for a few episodes
num_episodes = 0
while num_episodes < 5:
# Pick a random action
action = random.randint(0, env.action_space.n - 1)
obs, reward, done, info = env.step(action)
# Validate the agent position
assert env.agent_pos[0] < env.widt... | seed = 1337 + i
env.seed(seed)
grid1 = env.grid
env.seed(seed)
grid2 = env.grid
assert grid1 == grid2 | conditional_block |
models.py | .utils.models import TimestampModel
from open_connect.groups.tasks import remove_user_from_group
autocomplete_light.register(Tag)
GROUP_STATUSES = (
('active', 'Active'),
('deleted', 'Deleted')
)
class Category(TimestampModel):
"""Group Category"""
slug = models.SlugField(unique=True)
name = mo... | (self, location, queryset=None):
"""Groups search by location."""
coords = get_coordinates(location)
# If no coordinates are provided, return an empty queryset
if not coords:
return Group.objects.none()
if queryset is None:
queryset = Group.objects.publi... | location_search | identifier_name |
models.py | .utils.models import TimestampModel
from open_connect.groups.tasks import remove_user_from_group
autocomplete_light.register(Tag)
GROUP_STATUSES = (
('active', 'Active'),
('deleted', 'Deleted')
)
class Category(TimestampModel):
"""Group Category"""
slug = models.SlugField(unique=True)
name = mo... |
if location:
groups = self.location_search(location, queryset=groups)
return groups
def location_search(self, location, queryset=None):
"""Groups search by location."""
coords = get_coordinates(location)
# If no coordinates are provided, return an empty querys... | | Q(description__icontains=search)
| Q(tags__slug__icontains=search)
).distinct() | random_line_split |
models.py | .utils.models import TimestampModel
from open_connect.groups.tasks import remove_user_from_group
autocomplete_light.register(Tag)
GROUP_STATUSES = (
('active', 'Active'),
('deleted', 'Deleted')
)
class Category(TimestampModel):
"""Group Category"""
slug = models.SlugField(unique=True)
name = mo... |
def published(self, **kwargs):
"""Get published groups."""
return self.get_queryset().filter(published=True, **kwargs)
def search(self, search=None, location=None):
"""Groups search"""
groups = Group.objects.published().select_related('image', 'group')
if search:
... | """Create a new group."""
name = kwargs.pop('name', None)
if 'group' not in kwargs and name:
kwargs['group'] = AuthGroup.objects.create(name=name)
return super(GroupManager, self).create(**kwargs) | identifier_body |
models.py | .utils.models import TimestampModel
from open_connect.groups.tasks import remove_user_from_group
autocomplete_light.register(Tag)
GROUP_STATUSES = (
('active', 'Active'),
('deleted', 'Deleted')
)
class Category(TimestampModel):
"""Group Category"""
slug = models.SlugField(unique=True)
name = mo... |
return super(Group, self).save(
force_insert, force_update, using, update_fields)
def delete(self, using=None):
"""Don't actually delete."""
self.status = 'deleted'
self.save()
for user in self.group.user_set.all().iterator():
remove_user_from_group... | self.is_national = False | conditional_block |
async_route_handler.ts | import {Promise, PromiseWrapper} from 'angular2/src/facade/async';
import {isPresent, Type} from 'angular2/src/facade/lang';
import {RouteHandler} from './route_handler';
import {RouteData, BLANK_ROUTE_DATA} from './instruction';
export class AsyncRouteHandler implements RouteHandler {
/** @internal */
_resolved... | }
resolveComponentType(): Promise<any> {
if (isPresent(this._resolvedComponent)) {
return this._resolvedComponent;
}
return this._resolvedComponent = this._loader().then((componentType) => {
this.componentType = componentType;
return componentType;
});
}
} |
constructor(private _loader: Function, data: {[key: string]: any} = null) {
this.data = isPresent(data) ? new RouteData(data) : BLANK_ROUTE_DATA; | random_line_split |
async_route_handler.ts | import {Promise, PromiseWrapper} from 'angular2/src/facade/async';
import {isPresent, Type} from 'angular2/src/facade/lang';
import {RouteHandler} from './route_handler';
import {RouteData, BLANK_ROUTE_DATA} from './instruction';
export class AsyncRouteHandler implements RouteHandler {
/** @internal */
_resolved... | (): Promise<any> {
if (isPresent(this._resolvedComponent)) {
return this._resolvedComponent;
}
return this._resolvedComponent = this._loader().then((componentType) => {
this.componentType = componentType;
return componentType;
});
}
}
| resolveComponentType | identifier_name |
async_route_handler.ts | import {Promise, PromiseWrapper} from 'angular2/src/facade/async';
import {isPresent, Type} from 'angular2/src/facade/lang';
import {RouteHandler} from './route_handler';
import {RouteData, BLANK_ROUTE_DATA} from './instruction';
export class AsyncRouteHandler implements RouteHandler {
/** @internal */
_resolved... |
return this._resolvedComponent = this._loader().then((componentType) => {
this.componentType = componentType;
return componentType;
});
}
}
| {
return this._resolvedComponent;
} | conditional_block |
response.js | const HTTP_CODE = {
OK: 200,
BAD_REQUEST: 400
};
class ResponseHelper {
/**
* @description
* Sends success response to the user
*
* @param {Object} res response object
* @param {Object} [data] content to return
*/
static success(res, data) |
/**
* @description
* Sends error response to the user
*
* @param {Object} res response object
* @param {Object} [data] content to return
* @param {Number} [code=400] error code
*/
static fail(res, data, code) {
const result = data || {};
result.status = 'error';
result.code = code || HTTP_CODE.B... | {
const result = data || {};
result.status = 'ok';
res.send(HTTP_CODE.OK, result);
} | identifier_body |
response.js | const HTTP_CODE = {
OK: 200,
BAD_REQUEST: 400
};
class ResponseHelper {
/**
* @description
* Sends success response to the user
*
* @param {Object} res response object
* @param {Object} [data] content to return
*/
static success(res, data) {
const result = data || {};
result.status = 'ok';
res.se... | typeof object[propertyName] === 'object' &&
!Array.isArray(object)
) {
object[propertyName] = ResponseHelper.maskFields(
object[propertyName],
fields
);
}
});
return object;
}
}
module.exports = ResponseHelper; | random_line_split | |
response.js | const HTTP_CODE = {
OK: 200,
BAD_REQUEST: 400
};
class ResponseHelper {
/**
* @description
* Sends success response to the user
*
* @param {Object} res response object
* @param {Object} [data] content to return
*/
static success(res, data) {
const result = data || {};
result.status = 'ok';
res.se... |
});
return object;
}
}
module.exports = ResponseHelper;
| {
object[propertyName] = ResponseHelper.maskFields(
object[propertyName],
fields
);
} | conditional_block |
response.js | const HTTP_CODE = {
OK: 200,
BAD_REQUEST: 400
};
class | {
/**
* @description
* Sends success response to the user
*
* @param {Object} res response object
* @param {Object} [data] content to return
*/
static success(res, data) {
const result = data || {};
result.status = 'ok';
res.send(HTTP_CODE.OK, result);
}
/**
* @description
* Sends error resp... | ResponseHelper | identifier_name |
Application.TrackerMap.js | /**
* TrackerMap
*
* @author Alexey Grebenshchikov
* @copyright (c) 2008, by Alexey Grebenshchikov
* @date 14 october 2010
* @version 0.1
*
* @license login.js is licensed under the terms of the Open Source
* LGPL 3.0 license. Commercial use is permitted to the extent that the
* code/component(s) do... |
},
/*
* get all devices markers
*/
getDevicesMarkers: function() {
return this.devicesMarkers;
}
}); // eo TrackerMap | {
var lonlat = new OpenLayers.LonLat(lon, lat).transform(this.viewProjection, this.map.projection);
marker = this.devicesMarkers[imei];
marker.move(lonlat);
this.setCenter(lon, lat, zoom);
} | conditional_block |
Application.TrackerMap.js | /**
* TrackerMap
*
* @author Alexey Grebenshchikov
* @copyright (c) 2008, by Alexey Grebenshchikov
* @date 14 october 2010
* @version 0.1
*
* @license login.js is licensed under the terms of the Open Source
* LGPL 3.0 license. Commercial use is permitted to the extent that the
* code/component(s) do... | });
this.devicesLayer = new OpenLayers.Layer.Vector('Devices', {
projection: new OpenLayers.Projection("EPSG:4326"),
visibility: true,
displayInLayerSwitcher: false,
styleMap: planeStyleMap
});
this.map.addLayers([this.baseLayer, this.devic... | random_line_split | |
validations.rs | byte combination out of: [[[x y] z] w]
// NOTE: Performance is sensitive to the exact formulation here
let init = utf8_first_byte(x, 2);
let y = unwrap_or_0(bytes.next());
let mut ch = utf8_acc_cont_byte(init, y);
if x >= 0xE0 {
// [[x y z] w] case
// 5th bit in 0xE0 .. 0xEF is alwa... | }
// https://tools.ietf.org/html/rfc3629
static UTF8_CHAR_WIDTH: [u8; 256] = [
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, // 0x1F
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, |
Ok(()) | random_line_split |
validations.rs | <'a, I: Iterator<Item = &'a u8>>(bytes: &mut I) -> Option<u32> {
// Decode UTF-8
let x = *bytes.next()?;
if x < 128 {
return Some(x as u32);
}
// Multibyte case follows
// Decode from a byte combination out of: [[[x y] z] w]
// NOTE: Performance is sensitive to the exact formulation... | next_code_point | identifier_name | |
validations.rs |
/// Reads the next code point out of a byte iterator (assuming a
/// UTF-8-like encoding).
#[unstable(feature = "str_internals", issue = "none")]
#[inline]
pub fn next_code_point<'a, I: Iterator<Item = &'a u8>>(bytes: &mut I) -> Option<u32> {
// Decode UTF-8
let x = *bytes.next()?;
if x < 128 {
re... | {
match opt {
Some(&byte) => byte,
None => 0,
}
} | identifier_body | |
app.js | var app = app || {};
$(function(){
"use-strict";
var ShiftGridApplication = Backbone.Marionette.Application.extend({
initialize: function(options) {
this.shiftData = new app.GridRows(options.rows);
this.shiftLayout = this.initializeLayout(options.el);
// Shift Grid
... | this.shiftLayout.pagination.show(paginationView);
gridView.listenTo(paginationView.model, "change:selectedDate", gridView.changeDate);
},
initializeModal: function(cellView) {
/*
* The cell click event is bubbled all the way up to here, where
... | random_line_split | |
index.tsx | import React from 'react';
import Table from '@material-ui/core/Table';
import TableHead from '@material-ui/core/TableHead';
import TableBody from '@material-ui/core/TableBody';
import {Box, makeStyles} from '@material-ui/core';
import TableHeading from './TableHeading';
import TableItem from './TableItem';
impo... |
export default TransactionTable; | random_line_split | |
expand.rs | use std::str;
use memchr::memchr;
use bytes::Captures;
pub fn expand(caps: &Captures, mut replacement: &[u8], dst: &mut Vec<u8>) {
while !replacement.is_empty() {
match memchr(b'$', replacement) {
None => break,
Some(i) => {
dst.extend(&replacement[..i]);
... | (b: &u8) -> bool {
match *b {
b'0' ... b'9' | b'a' ... b'z' | b'A' ... b'Z' | b'_' => true,
_ => false,
}
}
| is_valid_cap_letter | identifier_name |
expand.rs | use std::str;
use memchr::memchr;
use bytes::Captures;
pub fn expand(caps: &Captures, mut replacement: &[u8], dst: &mut Vec<u8>) {
while !replacement.is_empty() {
match memchr(b'$', replacement) {
None => break,
Some(i) => {
dst.extend(&replacement[..i]);
... | if !replacement.get(cap_end).map_or(false, |&b| b == b'}') {
return None;
}
cap_end += 1;
}
Some(CaptureRef {
rest: &replacement[cap_end..],
cap: match cap.parse::<u32>() {
Ok(i) => Ref::Number(i as usize),
Err(_) => Ref::Named(cap),
... | random_line_split | |
borrowck-borrow-overloaded-deref-mut.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (x: Own<int>) {
let _i = &mut *x; //~ ERROR cannot borrow
}
fn deref_mut2(mut x: Own<int>) {
let _i = &mut *x;
}
fn deref_extend<'a>(x: &'a Own<int>) -> &'a int {
&**x
}
fn deref_extend_mut1<'a>(x: &'a Own<int>) -> &'a mut int {
&mut **x //~ ERROR cannot borrow
}
fn deref_extend_mut2<'a>(x: &'a mut ... | deref_mut1 | identifier_name |
borrowck-borrow-overloaded-deref-mut.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | value: *mut T
}
impl<T> Deref for Own<T> {
type Target = T;
fn deref<'a>(&'a self) -> &'a T {
unsafe { &*self.value }
}
}
impl<T> DerefMut for Own<T> {
fn deref_mut<'a>(&'a mut self) -> &'a mut T {
unsafe { &mut *self.value }
}
}
fn deref_imm(x: Own<int>) {
let _i = &*x;
... |
struct Own<T> { | random_line_split |
borrowck-borrow-overloaded-deref-mut.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn assign1<'a>(x: Own<int>) {
*x = 3; //~ ERROR cannot borrow
}
fn assign2<'a>(x: &'a Own<int>) {
**x = 3; //~ ERROR cannot borrow
}
fn assign3<'a>(x: &'a mut Own<int>) {
**x = 3;
}
pub fn main() {}
| {
&mut **x
} | identifier_body |
timer.rs | // Copyright 2020 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use crate::{
AsRawDescriptor, FakeClock, FromRawDescriptor, IntoRawDescriptor, RawDescriptor, Result,
};
use std::os::unix::io::{AsRawFd, FromRawF... | (pub TimerFd);
impl Timer {
pub fn new() -> Result<Timer> {
TimerFd::new().map(Timer)
}
}
/// See [FakeTimerFd](sys_util::FakeTimerFd) for struct- and method-level
/// documentation.
pub struct FakeTimer(FakeTimerFd);
impl FakeTimer {
pub fn new(clock: Arc<Mutex<FakeClock>>) -> Self {
FakeT... | Timer | identifier_name |
timer.rs | // Copyright 2020 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use crate::{
AsRawDescriptor, FakeClock, FromRawDescriptor, IntoRawDescriptor, RawDescriptor, Result,
};
use std::os::unix::io::{AsRawFd, FromRawF... | pub fn wait(&mut self) -> Result<()> {
self.0.wait().map(|_| ())
}
pub fn is_armed(&self) -> Result<bool> {
self.0.is_armed()
}
pub fn clear(&mut self) -> Result<()> {
self.0.clear()
}
... | self.0.reset(dur, interval)
}
| random_line_split |
jog.component.ts | import {Component, OnInit} from '@angular/core';
import {MachineService} from '../../services/machine.service'
import {SettingsService} from '../../services/settings.service'
import {Settings} from '../../model/settings'
import {
faChevronCircleUp,
faChevronCircleDown,
faChevronCircleLeft,
faChevronCirc... | selector: 'app-jog',
templateUrl: './jog.component.html',
styleUrls: ['./jog.component.scss']
})
export class JogComponent implements OnInit {
public faChevronCircleUp = faChevronCircleUp;
public faChevronCircleDown = faChevronCircleDown;
public faChevronCircleLeft = faChevronCircleLeft;
pub... | random_line_split | |
jog.component.ts | import {Component, OnInit} from '@angular/core';
import {MachineService} from '../../services/machine.service'
import {SettingsService} from '../../services/settings.service'
import {Settings} from '../../model/settings'
import {
faChevronCircleUp,
faChevronCircleDown,
faChevronCircleLeft,
faChevronCirc... | (stepSize: string) {
stepSize = stepSize.replace(',', '.');
if (!stepSize.endsWith('.') && !stepSize.endsWith('.0') && !stepSize.endsWith('.00') && this._settings.jogStepSizeXY !== parseFloat(stepSize)) {
this._settings.jogStepSizeXY = parseFloat(stepSize);
this.settingsService.s... | onStepSizeXYChange | identifier_name |
jog.component.ts | import {Component, OnInit} from '@angular/core';
import {MachineService} from '../../services/machine.service'
import {SettingsService} from '../../services/settings.service'
import {Settings} from '../../model/settings'
import {
faChevronCircleUp,
faChevronCircleDown,
faChevronCircleLeft,
faChevronCirc... |
ngOnInit() {
this.settingsService.getSettings()
.subscribe((settings) => {
this._settings = settings;
})
}
jog(x: number, y: number, z: number) {
this.machineService.jog(x, y, z)
.subscribe(() => {
console.log("Joggin... | {
return this._settings;
} | identifier_body |
jog.component.ts | import {Component, OnInit} from '@angular/core';
import {MachineService} from '../../services/machine.service'
import {SettingsService} from '../../services/settings.service'
import {Settings} from '../../model/settings'
import {
faChevronCircleUp,
faChevronCircleDown,
faChevronCircleLeft,
faChevronCirc... |
}
onStepSizeXYChange(stepSize: string) {
stepSize = stepSize.replace(',', '.');
if (!stepSize.endsWith('.') && !stepSize.endsWith('.0') && !stepSize.endsWith('.00') && this._settings.jogStepSizeXY !== parseFloat(stepSize)) {
this._settings.jogStepSizeXY = parseFloat(stepSize);
... | {
this._settings.jogFeedRate = parseFloat(feedRate);
this.settingsService.setSettings(this._settings).subscribe();
} | conditional_block |
test_rotation.rs | extern crate mp4parse_capi;
use std::io::Read;
use mp4parse_capi::*;
extern fn buf_read(buf: *mut u8, size: usize, userdata: *mut std::os::raw::c_void) -> isize {
let input: &mut std::fs::File = unsafe { &mut *(userdata as *mut _) };
let mut buf = unsafe { std::slice::from_raw_parts_mut(buf, size) };
match... |
let mut counts: u32 = 0;
rv = mp4parse_get_track_count(parser, &mut counts);
assert_eq!(rv, Mp4parseStatus::Ok);
assert_eq!(counts, 1);
let mut video = Mp4parseTrackVideoInfo::default();
let rv = mp4parse_get_track_video_info(parser, 0, &mut video);
assert_eq!(... | assert_eq!(rv, Mp4parseStatus::Ok); | random_line_split |
test_rotation.rs | extern crate mp4parse_capi;
use std::io::Read;
use mp4parse_capi::*;
extern fn buf_read(buf: *mut u8, size: usize, userdata: *mut std::os::raw::c_void) -> isize |
#[test]
fn parse_rotation() {
let mut file = std::fs::File::open("tests/video_rotation_90.mp4").expect("Unknown file");
let io = Mp4parseIo {
read: Some(buf_read),
userdata: &mut file as *mut _ as *mut std::os::raw::c_void
};
unsafe {
let parser = mp4parse_new(&io);
l... | {
let input: &mut std::fs::File = unsafe { &mut *(userdata as *mut _) };
let mut buf = unsafe { std::slice::from_raw_parts_mut(buf, size) };
match input.read(&mut buf) {
Ok(n) => n as isize,
Err(_) => -1,
}
} | identifier_body |
test_rotation.rs | extern crate mp4parse_capi;
use std::io::Read;
use mp4parse_capi::*;
extern fn buf_read(buf: *mut u8, size: usize, userdata: *mut std::os::raw::c_void) -> isize {
let input: &mut std::fs::File = unsafe { &mut *(userdata as *mut _) };
let mut buf = unsafe { std::slice::from_raw_parts_mut(buf, size) };
match... | () {
let mut file = std::fs::File::open("tests/video_rotation_90.mp4").expect("Unknown file");
let io = Mp4parseIo {
read: Some(buf_read),
userdata: &mut file as *mut _ as *mut std::os::raw::c_void
};
unsafe {
let parser = mp4parse_new(&io);
let mut rv = mp4parse_read(p... | parse_rotation | identifier_name |
typeid-intrinsic.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | () {
unsafe {
assert_eq!(TypeId::of::<other1::A>(), other1::id_A());
assert_eq!(TypeId::of::<other1::B>(), other1::id_B());
assert_eq!(TypeId::of::<other1::C>(), other1::id_C());
assert_eq!(TypeId::of::<other1::D>(), other1::id_D());
assert_eq!(TypeId::of::<other1::E>(), othe... | main | identifier_name |
typeid-intrinsic.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | hash::hash::<TypeId, SipHasher>(&b));
} | random_line_split | |
typeid-intrinsic.rs | // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | assert_eq!(other1::id_F(), other2::id_F());
assert_eq!(other1::id_G(), other2::id_G());
assert_eq!(other1::id_H(), other2::id_H());
assert_eq!(TypeId::of::<int>(), other2::foo::<int>());
assert_eq!(TypeId::of::<int>(), other1::foo::<int>());
assert_eq!(other2::foo::<int>... | {
unsafe {
assert_eq!(TypeId::of::<other1::A>(), other1::id_A());
assert_eq!(TypeId::of::<other1::B>(), other1::id_B());
assert_eq!(TypeId::of::<other1::C>(), other1::id_C());
assert_eq!(TypeId::of::<other1::D>(), other1::id_D());
assert_eq!(TypeId::of::<other1::E>(), other1:... | identifier_body |
demo.py | from pathlib import Path
import cv2
import dlib
import numpy as np
import argparse
from contextlib import contextmanager
from omegaconf import OmegaConf
from tensorflow.keras.utils import get_file
from src.factory import get_model
pretrained_model = "https://github.com/yu4u/age-gender-estimation/releases/download/v0.... |
for img in image_generator:
input_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img_h, img_w, _ = np.shape(input_img)
# detect faces using dlib detector
detected = detector(input_img, 1)
faces = np.empty((len(detected), img_size, img_size, 3))
if len(detected) > 0:
... | args = get_args()
weight_file = args.weight_file
margin = args.margin
image_dir = args.image_dir
if not weight_file:
weight_file = get_file("weights.28-3.73.hdf5", pretrained_model, cache_subdir="pretrained_models",
file_hash=modhash, cache_dir=str(Path(__file__).... | identifier_body |
demo.py | from pathlib import Path
import cv2
import dlib
import numpy as np
import argparse
from contextlib import contextmanager
from omegaconf import OmegaConf
from tensorflow.keras.utils import get_file
from src.factory import get_model
pretrained_model = "https://github.com/yu4u/age-gender-estimation/releases/download/v0.... | main() | conditional_block | |
demo.py | from pathlib import Path
import cv2
import dlib
import numpy as np
import argparse
from contextlib import contextmanager
from omegaconf import OmegaConf
from tensorflow.keras.utils import get_file
from src.factory import get_model
pretrained_model = "https://github.com/yu4u/age-gender-estimation/releases/download/v0.... |
def draw_label(image, point, label, font=cv2.FONT_HERSHEY_SIMPLEX,
font_scale=0.8, thickness=1):
size = cv2.getTextSize(label, font, font_scale, thickness)[0]
x, y = point
cv2.rectangle(image, (x, y - size[1]), (x + size[0], y), (255, 0, 0), cv2.FILLED)
cv2.putText(image, label, point, f... | return args
| random_line_split |
demo.py | from pathlib import Path
import cv2
import dlib
import numpy as np
import argparse
from contextlib import contextmanager
from omegaconf import OmegaConf
from tensorflow.keras.utils import get_file
from src.factory import get_model
pretrained_model = "https://github.com/yu4u/age-gender-estimation/releases/download/v0.... | ():
parser = argparse.ArgumentParser(description="This script detects faces from web cam input, "
"and estimates age and gender for the detected faces.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argum... | get_args | identifier_name |
Task Form - Information.ts | var EntityLogicalName = "task";
var Form_b62ce022_cc0f_4c8c_bb29_21948f70dc74_Properties = {
actualdurationminutes: "actualdurationminutes"
,category: "category"
,description: "description"
,ownerid: "ownerid"
,prioritycode: "prioritycode"
,regardingobjectid: "regardingobjectid"
,scheduledend: "scheduledend"
,subcatego... | ,subcategory: "subcategory"
,subject: "subject"
}; | random_line_split | |
configSectionFooter.component.ts | import type { IComponentOptions, IController } from 'angular';
import { copy, module, toJson } from 'angular';
import { cloneDeep } from 'lodash';
import type { Application } from '../../application.model';
import { ApplicationWriter } from '../../service/ApplicationWriter';
export interface IConfigSectionFooterViewS... | (): void {
copy(this.viewState.originalConfig, this.config);
this.viewState.isDirty = false;
}
private saveSuccess(): void {
this.viewState.originalConfig = cloneDeep(this.config);
this.viewState.originalStringVal = toJson(this.config);
this.viewState.isDirty = false;
this.viewState.saving ... | revert | identifier_name |
configSectionFooter.component.ts | import type { IComponentOptions, IController } from 'angular';
import { copy, module, toJson } from 'angular';
import { cloneDeep } from 'lodash';
import type { Application } from '../../application.model';
import { ApplicationWriter } from '../../service/ApplicationWriter';
export interface IConfigSectionFooterViewS... |
public save(): void {
this.viewState.saving = true;
this.viewState.saveError = false;
const updateCommand: any = {
name: this.application.name,
accounts: this.application.attributes.accounts,
};
updateCommand[this.configField] = this.config;
ApplicationWriter.updateApplication(u... | this.viewState.saveError = true;
} | random_line_split |
configSectionFooter.component.ts | import type { IComponentOptions, IController } from 'angular';
import { copy, module, toJson } from 'angular';
import { cloneDeep } from 'lodash';
import type { Application } from '../../application.model';
import { ApplicationWriter } from '../../service/ApplicationWriter';
export interface IConfigSectionFooterViewS... |
public save(): void {
this.viewState.saving = true;
this.viewState.saveError = false;
const updateCommand: any = {
name: this.application.name,
accounts: this.application.attributes.accounts,
};
updateCommand[this.configField] = this.config;
ApplicationWriter.updateApplication(... | {
this.viewState.saving = false;
this.viewState.saveError = true;
} | identifier_body |
abi.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
pub static slice_elt_base: uint = 0u;
pub static slice_elt_len: uint = 1u; | random_line_split | |
with_nom_result.rs | use m3u8_rs::Playlist;
use std::io::Read; | fn main() {
let mut file = std::fs::File::open("playlist.m3u8").unwrap();
let mut bytes: Vec<u8> = Vec::new();
file.read_to_end(&mut bytes).unwrap();
let parsed = m3u8_rs::parse_playlist(&bytes);
let playlist = match parsed {
Result::Ok((_i, playlist)) => playlist,
Result::Err(e) =... | random_line_split | |
with_nom_result.rs | use m3u8_rs::Playlist;
use std::io::Read;
fn | () {
let mut file = std::fs::File::open("playlist.m3u8").unwrap();
let mut bytes: Vec<u8> = Vec::new();
file.read_to_end(&mut bytes).unwrap();
let parsed = m3u8_rs::parse_playlist(&bytes);
let playlist = match parsed {
Result::Ok((_i, playlist)) => playlist,
Result::Err(e) => panic... | main | identifier_name |
with_nom_result.rs | use m3u8_rs::Playlist;
use std::io::Read;
fn main() {
let mut file = std::fs::File::open("playlist.m3u8").unwrap();
let mut bytes: Vec<u8> = Vec::new();
file.read_to_end(&mut bytes).unwrap();
let parsed = m3u8_rs::parse_playlist(&bytes);
let playlist = match parsed {
Result::Ok((_i, playl... | {
let mut file = std::fs::File::open("playlist.m3u8").unwrap();
let mut bytes: Vec<u8> = Vec::new();
file.read_to_end(&mut bytes).unwrap();
let parsed = m3u8_rs::parse_playlist(&bytes);
match parsed {
Result::Ok((_i, Playlist::MasterPlaylist(pl))) => println!("Master playlist:\n{:?}", pl),... | identifier_body | |
detect-dsize_8h.js | var detect_dsize_8h =
[
[ "DetectDsizeData_", "structDetectDsizeData__.html", "structDetectDsizeData__" ],
[ "DETECTDSIZE_EQ", "detect-dsize_8h.html#a88bc36da4cea5874206a080baaaab4fe", null ],
[ "DETECTDSIZE_GT", "detect-dsize_8h.html#a1f4c47480e6b0d7c602f12aede2eb2ad", null ],
[ "DETECTDSIZE_LT", "dete... | ]; | random_line_split | |
main.rs | extern crate http;
extern crate iron;
extern crate staticfile;
extern crate time;
use time::now;
use std::io::net::ip::Ipv4Addr;
use iron::{Iron, Chain, Alloy, Request, Response, Server, Status, Continue, FromFn,};
use iron::mixin::Serve;
use staticfile::Static;
fn come_again(_req: &mut Request, res: &mut Response... |
else
{
server.chain.link(FromFn::new(come_again));
}
server.listen(Ipv4Addr(0, 0, 0, 0), 3000);
}
}
| {
if time::now().tm_min <= 1
{
server.chain.link(Static::new(Path::new("./")));
}
} | conditional_block |
main.rs | extern crate http;
extern crate iron;
extern crate staticfile;
extern crate time;
use time::now;
use std::io::net::ip::Ipv4Addr;
use iron::{Iron, Chain, Alloy, Request, Response, Server, Status, Continue, FromFn,};
use iron::mixin::Serve;
use staticfile::Static;
fn come_again(_req: &mut Request, res: &mut Response... | {
loop
{
let mut server: Server = Iron::new();
if time::now().tm_hour == 17
{
if time::now().tm_min <= 1
{
server.chain.link(Static::new(Path::new("./")));
}
}
else
{
server.chain.link(FromFn::new(come_again));
}
server.listen(Ipv4Ad... | identifier_body | |
main.rs | extern crate http;
extern crate iron;
extern crate staticfile;
extern crate time;
use time::now;
use std::io::net::ip::Ipv4Addr;
use iron::{Iron, Chain, Alloy, Request, Response, Server, Status, Continue, FromFn,};
use iron::mixin::Serve;
use staticfile::Static;
fn | (_req: &mut Request, res: &mut Response, _alloy: &mut Alloy) -> Status
{
let _ = res.serve(::http::status::Ok, "Wrong time, come back later.");
Continue
}
fn main()
{
loop
{
let mut server: Server = Iron::new();
if time::now().tm_hour == 17
{
if time::now().tm_min <= 1
{... | come_again | identifier_name |
main.rs | extern crate http;
extern crate iron;
extern crate staticfile;
extern crate time;
use time::now;
use std::io::net::ip::Ipv4Addr;
use iron::{Iron, Chain, Alloy, Request, Response, Server, Status, Continue, FromFn,};
use iron::mixin::Serve;
use staticfile::Static;
fn come_again(_req: &mut Request, res: &mut Response... | {
server.chain.link(FromFn::new(come_again));
}
server.listen(Ipv4Addr(0, 0, 0, 0), 3000);
}
} | else | random_line_split |
i18next-browser-languagedetector-tests.ts | import * as i18next from "i18next";
import * as LngDetector from "i18next-browser-languagedetector";
const options: LngDetector.DetectorOptions = {
// order and from where user language should be detected
order: ["querystring", "cookie", "localStorage", "navigator", "htmlTag"],
// keys or params to lookup... | ,
cacheUserLanguage(lng: string, options: LngDetector.DetectorOptions) {
// options -> are passed in options
// lng -> current language, will be called after init and on changeLanguage
// store it
}
};
const customDetector2: LngDetector.CustomDetector = {
name: "myDetectorsName",
... | {
// options -> are passed in options
return "en";
} | identifier_body |
i18next-browser-languagedetector-tests.ts | import * as i18next from "i18next";
import * as LngDetector from "i18next-browser-languagedetector";
const options: LngDetector.DetectorOptions = {
// order and from where user language should be detected
order: ["querystring", "cookie", "localStorage", "navigator", "htmlTag"],
// keys or params to lookup... |
const lngDetector = new LngDetector(null, options);
lngDetector.init(options);
lngDetector.addDetector(customDetector);
i18next
.use(lngDetector)
.init({
detection: options
}); | return undefined;
}
}; | random_line_split |
i18next-browser-languagedetector-tests.ts | import * as i18next from "i18next";
import * as LngDetector from "i18next-browser-languagedetector";
const options: LngDetector.DetectorOptions = {
// order and from where user language should be detected
order: ["querystring", "cookie", "localStorage", "navigator", "htmlTag"],
// keys or params to lookup... | (lng: string, options: LngDetector.DetectorOptions) {
// options -> are passed in options
// lng -> current language, will be called after init and on changeLanguage
// store it
}
};
const customDetector2: LngDetector.CustomDetector = {
name: "myDetectorsName",
lookup(options: LngD... | cacheUserLanguage | identifier_name |
frame_reader.rs | //! This reader composes frames of bytes started with a 4 byte frame header indicating the size of
//! the buffer. An exact size buffer will be allocated once the 4 byte frame header is received.
use std::io::{self, Read, Error, ErrorKind};
use std::collections::VecDeque;
use std::mem;
#[derive(Debug)]
pub struct Fra... |
fn read_value<T: Read>(&mut self, reader: &mut T) -> io::Result<usize> {
let bytes_read = try!(reader.read(&mut self.current[self.bytes_read..]));
self.bytes_read += bytes_read;
if self.bytes_read == self.current.len() {
self.completed_frames.push_back(mem::replace(&mut self.cur... | {
let bytes_read = try!(reader.read(&mut self.header[self.bytes_read..]));
self.bytes_read += bytes_read;
if self.bytes_read == 4 {
let len = unsafe { u32::from_be(mem::transmute(self.header)) };
self.bytes_read = 0;
self.reading_header = false;
self.c... | identifier_body |
frame_reader.rs | //! This reader composes frames of bytes started with a 4 byte frame header indicating the size of
//! the buffer. An exact size buffer will be allocated once the 4 byte frame header is received.
use std::io::{self, Read, Error, ErrorKind};
use std::collections::VecDeque;
use std::mem;
#[derive(Debug)]
pub struct Fra... |
// Write a partial value
let mut data = Cursor::new(&buf1[0..5]);
let bytes_read = reader.read(&mut data).unwrap();
assert_eq!(5, bytes_read);
assert_eq!(None, reader.iter_mut().next());
// Complete writing the first value
let mut data = Cursor::new(&buf1[5..]);... | assert_eq!(None, reader.iter_mut().next()); | random_line_split |
frame_reader.rs | //! This reader composes frames of bytes started with a 4 byte frame header indicating the size of
//! the buffer. An exact size buffer will be allocated once the 4 byte frame header is received.
use std::io::{self, Read, Error, ErrorKind};
use std::collections::VecDeque;
use std::mem;
#[derive(Debug)]
pub struct Fra... | <T: Read>(&mut self, reader: &mut T) -> io::Result<usize> {
if self.reading_header {
self.read_header(reader)
} else {
self.read_value(reader)
}
}
// TODO: Return an error if size is greater than max_frame_size
fn read_header<T: Read>(&mut self, reader: &mut ... | do_read | identifier_name |
partner_communication_config.py | ##############################################################################
#
# Copyright (C) 2021 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py
#
#####################... |
def _get_test_objects(self, partner):
if self.model == "res.partner":
object_ids = partner.ids
elif self.model == "recurring.contract":
object_ids = partner.sponsorship_ids.ids
elif self.model == "correspondence":
object_ids = partner.mapped("sponsorship... | return {
"name": "Test communication cases",
"type": "ir.actions.act_window",
"view_type": "form",
"view_mode": "form",
"context": self.env.context,
"res_model": "partner.communication.test.cases.wizard",
'target': 'current',
} | identifier_body |
partner_communication_config.py | ##############################################################################
#
# Copyright (C) 2021 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py
#
#####################... | :return: True
"""
self.ensure_one()
comm_obj = self.env["partner.communication.job"].with_context(
must_skip_send_to_printer=True)
res = []
for number_sponsorship in [1, 3, 4]:
partner = self._find_partner(number_sponsorship, lang, family_case)
... | Generates example communications for our multiple cases in CH
depending on the language and the family case
Outputs the texts in a file
:param lang: | random_line_split |
partner_communication_config.py | ##############################################################################
#
# Copyright (C) 2021 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py
#
#####################... | (self, lang="de_DE", family_case="single", send_mode="digital"):
"""
Generates example communications for our multiple cases in CH
depending on the language and the family case
Outputs the texts in a file
:param lang:
:return: True
"""
self.ensure_one()
... | generate_test_cases_by_language_family_case | identifier_name |
partner_communication_config.py | ##############################################################################
#
# Copyright (C) 2021 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Emanuel Cino <ecino@compassion.ch>
#
# The licence is in the file __manifest__.py
#
#####################... |
elif self.model == "account.invoice.line":
object_ids = self.env["account.invoice.line"].search([
("partner_id", "=", partner.id),
("invoice_id.invoice_category", "=", "fund")
], limit=4).ids
elif self.model == "account.invoice":
objec... | object_ids = partner.sponsored_child_ids.ids | conditional_block |
evenoddsort.ts | /**
* Copyright 2018 Jim Armstrong (www.algorithmist.net)
*
* 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 applic... | (input: Array<number>): Array<number>
{
if (!input) {
return [];
}
let result: Array<number> = new Array<number>();
const n: number = input.length;
// edge cases
if (n == 0) {
return result;
}
if (n == 1)
{
result.push(input[0]);
return result;
}
// copy the input arr... | evenoddsort | identifier_name |
evenoddsort.ts | /**
* Copyright 2018 Jim Armstrong (www.algorithmist.net)
*
* 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 applic... | const sorted: Array<number> = input.slice();
sorted.sort( (a: number, b: number): number => {return b-a} );
// highest even/odd positions and number of even/odd positions
const mod: number = (n-1) % 2;
const m: number = Math.ceil(n/2);
const k: number = n - m;
const startEven: numbe... | {
if (!input) {
return [];
}
let result: Array<number> = new Array<number>();
const n: number = input.length;
// edge cases
if (n == 0) {
return result;
}
if (n == 1)
{
result.push(input[0]);
return result;
}
// copy the input array and sort | identifier_body |
evenoddsort.ts | /**
* Copyright 2018 Jim Armstrong (www.algorithmist.net)
*
* 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 applic... |
// copy the input array and sort
const sorted: Array<number> = input.slice();
sorted.sort( (a: number, b: number): number => {return b-a} );
// highest even/odd positions and number of even/odd positions
const mod: number = (n-1) % 2;
const m: number = Math.ceil(n/2);
const k: number ... | {
result.push(input[0]);
return result;
} | conditional_block |
evenoddsort.ts | /**
* Copyright 2018 Jim Armstrong (www.algorithmist.net)
*
* 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 applic... | // copy the input array and sort
const sorted: Array<number> = input.slice();
sorted.sort( (a: number, b: number): number => {return b-a} );
// highest even/odd positions and number of even/odd positions
const mod: number = (n-1) % 2;
const m: number = Math.ceil(n/2);
const k: number ... | random_line_split | |
wbi-auth-reducer.tsx | import { createAction, Action } from 'redux-actions';
import * as Immutable from 'seamless-immutable';
import {IWbiAuthResponse} from '../services/wbi/wbi-auth'
// Action Types - LOAD, CREATE, UPDATE, REMOVE
const UPDATE_USERNAME = 'wbiAuth/UPDATE_USERNAME';
const UPDATE_PASSWORD = 'wbiAuth/UPDATE_PASSWORD';
const LO... | username: string;
password: string;
isLoading: boolean;
errorMessage : string | null;
token: IWbiAuthResponse | null;
}
export const initialState: IWbiAuthReducer = {
username: '',
password: '',
isLoading: false,
errorMessage: null,
token: null
};
export default function reducer(state = Immutable.f... | random_line_split | |
wbi-auth-reducer.tsx | import { createAction, Action } from 'redux-actions';
import * as Immutable from 'seamless-immutable';
import {IWbiAuthResponse} from '../services/wbi/wbi-auth'
// Action Types - LOAD, CREATE, UPDATE, REMOVE
const UPDATE_USERNAME = 'wbiAuth/UPDATE_USERNAME';
const UPDATE_PASSWORD = 'wbiAuth/UPDATE_PASSWORD';
const LO... | (state = Immutable.from(initialState), action: Action<any>) {
switch (action.type) {
case UPDATE_USERNAME:
return state.merge({
username: action.payload,
});
case UPDATE_PASSWORD:
return state.merge({
password: action.payload,
});
case LOGIN:
return state.... | reducer | identifier_name |
wbi-auth-reducer.tsx | import { createAction, Action } from 'redux-actions';
import * as Immutable from 'seamless-immutable';
import {IWbiAuthResponse} from '../services/wbi/wbi-auth'
// Action Types - LOAD, CREATE, UPDATE, REMOVE
const UPDATE_USERNAME = 'wbiAuth/UPDATE_USERNAME';
const UPDATE_PASSWORD = 'wbiAuth/UPDATE_PASSWORD';
const LO... | token: null
});
case LOGIN_SUCCESS:
return state.merge({
isLoading: false,
errorMessage: null,
token : action.payload
});
case LOGIN_ERROR:
return state.merge({
isLoading: false,
errorMessage: action.payload,
token : null
});
... | {
switch (action.type) {
case UPDATE_USERNAME:
return state.merge({
username: action.payload,
});
case UPDATE_PASSWORD:
return state.merge({
password: action.payload,
});
case LOGIN:
return state.merge({
isLoading: true,
errorMessage: null
... | identifier_body |
MenuBlock-test.tsx | /*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, o... |
it('should render a closed menu block', () => {
expect(shallowRender()).toMatchSnapshot();
});
it('should render an opened menu block', () => {
expect(shallowRender({ openByDefault: true })).toMatchSnapshot();
});
it('should not render a high depth differently than a depth of 3', () => {
expect(
shallowRen... | import { click } from '../../../../helpers/testUtils';
import MenuBlock from '../MenuBlock'; | random_line_split |
SearchIndexBuilder.js | import path from 'path';
import DocBuilder from './DocBuilder.js';
/**
* Search index of identifier builder class.
*/
export default class SearchIndexBuilder extends DocBuilder {
/**
* execute building output.
* @param {function(javascript: string, filePath: string)} callback - is called with output.
*/
... | else if (doc.kind === 'testDescribe' || doc.kind === 'testIt') {
displayText = doc.testFullDescription;
indexText = [...(doc.testTargets || []), ...(doc._custom_test_targets || [])].join(' ').toLowerCase();
let filePath = doc.longname.split('~')[0];
let fileDoc = this._find({kind: 'test... | {
displayText = `<span>${doc.name}</span> <span class="search-result-import-path">${doc.importPath}</span>`;
indexText = `${doc.importPath}~${doc.name}`.toLowerCase();
url = this._getURL(doc);
} | conditional_block |
SearchIndexBuilder.js | import path from 'path';
import DocBuilder from './DocBuilder.js';
/**
* Search index of identifier builder class.
*/
export default class | extends DocBuilder {
/**
* execute building output.
* @param {function(javascript: string, filePath: string)} callback - is called with output.
*/
exec(callback) {
let searchIndex = [];
let docs = this._find({});
for (let doc of docs) {
let indexText, url, displayText;
if (doc.im... | SearchIndexBuilder | identifier_name |
SearchIndexBuilder.js | import path from 'path';
import DocBuilder from './DocBuilder.js';
/**
* Search index of identifier builder class.
*/
export default class SearchIndexBuilder extends DocBuilder {
/**
* execute building output.
* @param {function(javascript: string, filePath: string)} callback - is called with output.
*/
... | }
searchIndex.sort((a, b)=>{
if (a[2] === b[2]) {
return 0;
} else if (a[2] < b[2]) {
return -1;
} else {
return 1;
}
});
let javascript = 'window.esdocSearchIndex = ' + JSON.stringify(searchIndex, null, 2);
callback(javascript, 'script/search_index... | random_line_split | |
SearchIndexBuilder.js | import path from 'path';
import DocBuilder from './DocBuilder.js';
/**
* Search index of identifier builder class.
*/
export default class SearchIndexBuilder extends DocBuilder {
/**
* execute building output.
* @param {function(javascript: string, filePath: string)} callback - is called with output.
*/
... | url = this._getURL(doc);
}
let kind = doc.kind;
switch (kind) {
case 'constructor':
kind = 'method';
break;
case 'get':
case 'set':
kind = 'member';
break;
case 'testDescribe':
case 'testIt':
kind = 'tes... | {
let searchIndex = [];
let docs = this._find({});
for (let doc of docs) {
let indexText, url, displayText;
if (doc.importPath) {
displayText = `<span>${doc.name}</span> <span class="search-result-import-path">${doc.importPath}</span>`;
indexText = `${doc.importPath}~${doc.name... | identifier_body |
fullscreen.rs | #[cfg(target_os = "android")]
#[macro_use]
extern crate android_glue;
extern crate glutin;
use std::io;
mod support;
#[cfg(target_os = "android")]
android_start!(main);
#[cfg(not(feature = "window"))]
fn main() { println!("This example requires glutin to be compiled with the `window` feature"); }
#[cfg(feature = ... | () {
// enumerating monitors
let monitor = {
for (num, monitor) in glutin::get_available_monitors().enumerate() {
println!("Monitor #{}: {:?}", num, monitor.get_name());
}
print!("Please write the number of the monitor to use: ");
let mut num = String::new();
... | main | identifier_name |
fullscreen.rs | #[cfg(target_os = "android")]
#[macro_use]
extern crate android_glue;
extern crate glutin;
use std::io;
mod support;
#[cfg(target_os = "android")]
android_start!(main);
#[cfg(not(feature = "window"))]
fn main() { println!("This example requires glutin to be compiled with the `window` feature"); }
#[cfg(feature = ... | .with_title("Hello world!".to_string())
.with_fullscreen(monitor)
.build()
.unwrap();
unsafe { window.make_current() };
let context = support::load(&window);
while !window.is_closed() {
context.draw_frame((0.0, 1.0, 0.0, 1.0));
window.swap_buffers();
... | {
// enumerating monitors
let monitor = {
for (num, monitor) in glutin::get_available_monitors().enumerate() {
println!("Monitor #{}: {:?}", num, monitor.get_name());
}
print!("Please write the number of the monitor to use: ");
let mut num = String::new();
i... | identifier_body |
fullscreen.rs | #[cfg(target_os = "android")]
#[macro_use]
extern crate android_glue;
extern crate glutin;
use std::io;
mod support;
#[cfg(target_os = "android")]
android_start!(main);
#[cfg(not(feature = "window"))]
fn main() { println!("This example requires glutin to be compiled with the `window` feature"); }
#[cfg(feature = ... |
unsafe { window.make_current() };
let context = support::load(&window);
while !window.is_closed() {
context.draw_frame((0.0, 1.0, 0.0, 1.0));
window.swap_buffers();
println!("{:?}", window.wait_events().next());
}
} | .with_fullscreen(monitor)
.build()
.unwrap(); | random_line_split |
router-stubs.ts | /* tslint:disable */
// export for convenience.
export { ActivatedRoute, Router, RouterLink, RouterOutlet } from '@angular/router';
import { Component, Directive, Injectable, Input } from '@angular/core';
import { NavigationExtras } from '@angular/router';
// #docregion router-link
@Directive({
selector: '[router... | (commands: any[], extras?: NavigationExtras) { }
}
// Only implements params and part of snapshot.paramMap
// #docregion activated-route-stub
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { convertToParamMap, ParamMap } from '@angular/router';
@Injectable()
export class ActivatedRouteStub {
// A... | navigate | identifier_name |
router-stubs.ts | /* tslint:disable */
// export for convenience.
export { ActivatedRoute, Router, RouterLink, RouterOutlet } from '@angular/router';
import { Component, Directive, Injectable, Input } from '@angular/core';
import { NavigationExtras } from '@angular/router';
| // #docregion router-link
@Directive({
selector: '[routerLink]',
host: {
'(click)': 'onClick()'
}
})
export class RouterLinkStubDirective {
@Input('routerLink') linkParams: any;
@Input('queryParams') queryParams: any;
navigatedTo: any = null;
onClick() {
this.navigatedTo = t... | random_line_split | |
entry.rs | use std::fmt;
use std::fs;
use std::path::Path;
use std::slice::Iter;
use modes::DisplayableEntry;
use utils;
use utils::SizeDisplay;
#[derive(Debug)]
pub struct Entry {
name: String,
self_size: u64,
children: Vec<Entry>,
is_file: bool,
}
impl Entry {
pub fn for_path(path: &Path) -> Result<Entry,... | else if metadata.is_file() {
vec![]
} else {
return Err("not a file or directory".to_string());
};
children.sort_by(
// Note: We change the ordering to get in descending order
|a, b| b.size().cmp(&a.size())
);
Ok(Entry {
... | {
Entry::in_directory(path)
} | conditional_block |
entry.rs | use std::fmt;
use std::fs;
use std::path::Path;
use std::slice::Iter;
use modes::DisplayableEntry;
use utils;
use utils::SizeDisplay;
#[derive(Debug)]
pub struct Entry {
name: String,
self_size: u64,
children: Vec<Entry>,
is_file: bool,
}
impl Entry {
pub fn for_path(path: &Path) -> Result<Entry,... | (&self) -> bool {
self.is_file
}
}
impl fmt::Display for Entry {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} {}", self.name(), self.size().as_size_display())
}
}
#[cfg(test)]
mod test {
use super::*;
use modes::DisplayableEntry;
use std::path::Path;
... | is_file | identifier_name |
entry.rs | use std::fmt;
use std::fs;
use std::path::Path;
use std::slice::Iter;
use modes::DisplayableEntry;
use utils;
use utils::SizeDisplay;
#[derive(Debug)]
pub struct Entry {
name: String,
self_size: u64,
children: Vec<Entry>,
is_file: bool,
}
impl Entry {
pub fn for_path(path: &Path) -> Result<Entry,... |
#[test]
fn it_can_be_displayed() {
use utils::SizeDisplay;
let file = Entry::for_path(Path::new("./LICENSE")).unwrap();
assert_eq!(format!("{}", file), format!("LICENSE {}", file.size().as_size_display()));
}
#[test]
fn it_calculates_size_from_children() {
let ent... | {
let file = Entry::for_path(Path::new("./LICENSE")).unwrap();
assert_eq!(file.children_iter().count(), 0);
} | identifier_body |
entry.rs | use std::fmt;
use std::fs;
use std::path::Path;
use std::slice::Iter;
use modes::DisplayableEntry;
use utils;
use utils::SizeDisplay;
#[derive(Debug)]
pub struct Entry {
name: String,
self_size: u64,
children: Vec<Entry>,
is_file: bool,
}
impl Entry {
pub fn for_path(path: &Path) -> Result<Entry,... | let mut children = if metadata.is_dir() {
Entry::in_directory(path)
} else if metadata.is_file() {
vec![]
} else {
return Err("not a file or directory".to_string());
};
children.sort_by(
// Note: We change the ordering to get in de... | random_line_split | |
ogone.py | 'AAVZIP',
'ACCEPTANCE',
'ALIAS',
'AMOUNT',
'BIC',
'BIN',
'BRAND',
'CARDNO',
'CCCTY',
'CN',
'COMPLUS',
... | 'EXCEPTIONURL': '%s' % urlparse.urljoin(base_url, OgoneController._exception_url),
'CANCELURL': '%s' % urlparse.urljoin(base_url, OgoneController._cancel_url),
}
if ogone_tx_values.get('return_url'):
temp_ogone_tx_values['PARAMPLUS'] = 'return_url=%s' % ogone_tx_value... | 'OWNERCTY': partner_values['country'] and partner_values['country'].name or '',
'OWNERTELNO': partner_values['phone'],
'ACCEPTURL': '%s' % urlparse.urljoin(base_url, OgoneController._accept_url),
'DECLINEURL': '%s' % urlparse.urljoin(base_url, OgoneController._decline_ur... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.