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 |
|---|---|---|---|---|
particle.rs | struct Particle {
x: f32,
y: f32,
dx: f32,
dy: f32,
frames_left: i32
}
impl Particle {
fn animate(&mut self) {
if self.in_use() {
return; |
--frames_left;
x += dx;
y += dy;
}
fn in_use(&self) -> bool {
self.frames_left > 0
}
}
const POOL_SIZE: i32 = 1000;
struct ParticlePool {
particles: [Particle; POOL_SIZE]
}
impl ParticlePool {
fn create(&self, x: f32, y: f32, dx: f32, dy: f32, lifetime: i32) {
... | } | random_line_split |
particle.rs | struct Particle {
x: f32,
y: f32,
dx: f32,
dy: f32,
frames_left: i32
}
impl Particle {
fn animate(&mut self) {
if self.in_use() |
--frames_left;
x += dx;
y += dy;
}
fn in_use(&self) -> bool {
self.frames_left > 0
}
}
const POOL_SIZE: i32 = 1000;
struct ParticlePool {
particles: [Particle; POOL_SIZE]
}
impl ParticlePool {
fn create(&self, x: f32, y: f32, dx: f32, dy: f32, lifetime: i32) {
... | {
return;
} | conditional_block |
particle.rs | struct Particle {
x: f32,
y: f32,
dx: f32,
dy: f32,
frames_left: i32
}
impl Particle {
fn animate(&mut self) {
if self.in_use() {
return;
}
--frames_left;
x += dx;
y += dy;
}
fn | (&self) -> bool {
self.frames_left > 0
}
}
const POOL_SIZE: i32 = 1000;
struct ParticlePool {
particles: [Particle; POOL_SIZE]
}
impl ParticlePool {
fn create(&self, x: f32, y: f32, dx: f32, dy: f32, lifetime: i32) {
for i in 0..POOL_SIZE {
if !particles[i].in_use() {
... | in_use | identifier_name |
kqueue.rs | PollOpt, Token};
use event::{self, Event};
use sys::unix::cvt;
use sys::unix::io::set_cloexec;
/// Each Selector has a globally unique(ish) ID associated with it. This ID
/// gets tracked by `TcpStream`, `TcpListener`, etc... when they are first
/// registered with the `Selector`. If a type that is previously associa... | if e.flags & libc::EV_EOF != 0 {
event::kind_mut(&mut self.events[idx]).insert(Ready::hup());
// When the read end of the socket is closed, EV_EOF is set on
// flags, and fflags contains the error if there is one.
if e.fflags != 0 {
... | event::kind_mut(&mut self.events[idx]).insert(Ready::writable());
}
| conditional_block |
kqueue.rs | Opt, Token};
use event::{self, Event};
use sys::unix::cvt;
use sys::unix::io::set_cloexec;
/// Each Selector has a globally unique(ish) ID associated with it. This ID
/// gets tracked by `TcpStream`, `TcpListener`, etc... when they are first
/// registered with the `Selector`. If a type that is previously associated w... | ap: usize) -> Events {
Events {
sys_events: KeventList(Vec::with_capacity(cap)),
events: Vec::with_capacity(cap),
event_map: HashMap::with_capacity(cap)
}
}
#[inline]
pub fn len(&self) -> usize {
self.events.len()
}
#[inline]
pub fn c... | th_capacity(c | identifier_name |
kqueue.rs | PollOpt, Token};
use event::{self, Event};
use sys::unix::cvt;
use sys::unix::io::set_cloexec;
/// Each Selector has a globally unique(ish) ID associated with it. This ID
/// gets tracked by `TcpStream`, `TcpListener`, etc... when they are first
/// registered with the `Selector`. If a type that is previously associa... | ::std::ptr::null())));
for change in changes.iter() {
debug_assert_eq!(change.flags & libc::EV_ERROR, libc::EV_ERROR);
if change.data != 0 {
// there’s some error, but we want to ignore ENOENT error for EV_DELETE
... | kevent!(fd, libc::EVFILT_READ, flags | r, usize::from(token)),
kevent!(fd, libc::EVFILT_WRITE, flags | w, usize::from(token)),
];
try!(cvt(libc::kevent(self.kq, changes.as_ptr(), changes.len() as c_int,
changes.as_mut_ptr... | random_line_split |
feature-flag.directive.ts | import { Directive, TemplateRef, ViewContainerRef, Input } from '@angular/core';
import { FeatureFlagService } from '../services/feature-flag.service';
@Directive({
selector: '[ngFeatureFlag]'
})
export class FeatureFlagDirective {
@Input() ngFeatureFlagHidden = false;
@Input() ngFeatureFlagDefaultTo = false;
... | (featureFlag: string) {
if (featureFlag === undefined) {
console.error('Feature flag name required!');
return;
}
this.darkLumos.isEnabled(featureFlag)
.subscribe(status => {
if ((status && !this.ngFeatureFlagHidden) ||
(!status && this.ngFeatureFlagHidden)) {
t... | ngFeatureFlag | identifier_name |
feature-flag.directive.ts | import { Directive, TemplateRef, ViewContainerRef, Input } from '@angular/core';
import { FeatureFlagService } from '../services/feature-flag.service';
@Directive({
selector: '[ngFeatureFlag]'
})
export class FeatureFlagDirective {
@Input() ngFeatureFlagHidden = false;
@Input() ngFeatureFlagDefaultTo = false;
... |
this.darkLumos.isEnabled(featureFlag)
.subscribe(status => {
if ((status && !this.ngFeatureFlagHidden) ||
(!status && this.ngFeatureFlagHidden)) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
}
});
... | {
console.error('Feature flag name required!');
return;
} | conditional_block |
feature-flag.directive.ts | import { Directive, TemplateRef, ViewContainerRef, Input } from '@angular/core';
import { FeatureFlagService } from '../services/feature-flag.service';
@Directive({
selector: '[ngFeatureFlag]'
}) | @Input() set ngFeatureFlag(featureFlag: string) {
if (featureFlag === undefined) {
console.error('Feature flag name required!');
return;
}
this.darkLumos.isEnabled(featureFlag)
.subscribe(status => {
if ((status && !this.ngFeatureFlagHidden) ||
(!status && this.ngFeatu... | export class FeatureFlagDirective {
@Input() ngFeatureFlagHidden = false;
@Input() ngFeatureFlagDefaultTo = false;
| random_line_split |
feature-flag.directive.ts | import { Directive, TemplateRef, ViewContainerRef, Input } from '@angular/core';
import { FeatureFlagService } from '../services/feature-flag.service';
@Directive({
selector: '[ngFeatureFlag]'
})
export class FeatureFlagDirective {
@Input() ngFeatureFlagHidden = false;
@Input() ngFeatureFlagDefaultTo = false;
... |
}
| { } | identifier_body |
common.spec.ts | /*
* The MIT License
*
* Copyright 2019 Azarias Boutin.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, ... | it('Should be able to detect a valid 10fastfingers url', () => {
const validUrl = 'https://10fastfingers.com';
const valids = [ validUrl, validUrl + '/randomStuff', validUrl + '/' ];
const invalids = [ `a${validUrl}`, `${validUrl}c`, `http://google.fr`, 'http://10fastfingers.com' ];
valids.forEach((v) => ex... | });
| random_line_split |
sample.py | import json
from typing import NamedTuple
from collections import namedtuple
import kfp
import kfp.dsl as dsl
from kfp import components
from kfp.dsl.types import Integer
def get_current_namespace():
"""Returns current namespace if available, else kubeflow"""
try:
current_namespace = open(
... | master = {
"replicas": 1,
"restartPolicy": "OnFailure",
"template": {
"metadata": {
"annotations": {
# See https://github.com/kubeflow/website/issues/2011
"sidecar.istio.io/inject": "false"
}
},
... | ):
pytorchjob_launcher_op = components.load_component_from_file(
"./component.yaml"
)
| random_line_split |
sample.py | import json
from typing import NamedTuple
from collections import namedtuple
import kfp
import kfp.dsl as dsl
from kfp import components
from kfp.dsl.types import Integer
def get_current_namespace():
|
def create_worker_spec(
worker_num: int = 0
) -> NamedTuple(
"CreatWorkerSpec", [("worker_spec", dict)]
):
"""
Creates pytorch-job worker spec
"""
worker = {}
if worker_num > 0:
worker = {
"replicas": worker_num,
"restartPolicy": "OnFailure",
"t... | """Returns current namespace if available, else kubeflow"""
try:
current_namespace = open(
"/var/run/secrets/kubernetes.io/serviceaccount/namespace"
).read()
except:
current_namespace = "kubeflow"
return current_namespace | identifier_body |
sample.py | import json
from typing import NamedTuple
from collections import namedtuple
import kfp
import kfp.dsl as dsl
from kfp import components
from kfp.dsl.types import Integer
def | ():
"""Returns current namespace if available, else kubeflow"""
try:
current_namespace = open(
"/var/run/secrets/kubernetes.io/serviceaccount/namespace"
).read()
except:
current_namespace = "kubeflow"
return current_namespace
def create_worker_spec(
worker_num: ... | get_current_namespace | identifier_name |
sample.py | import json
from typing import NamedTuple
from collections import namedtuple
import kfp
import kfp.dsl as dsl
from kfp import components
from kfp.dsl.types import Integer
def get_current_namespace():
"""Returns current namespace if available, else kubeflow"""
try:
current_namespace = open(
... |
# # To run:
# client = kfp.Client()
# run = client.create_run_from_pipeline_package(
# pipeline_file,
# arguments={},
# run_name="test pytorchjob run"
# )
# print(f"Created run {run}")
| import kfp.compiler as compiler
pipeline_file = "test.tar.gz"
print(
f"Compiling pipeline as {pipeline_file}"
)
compiler.Compiler().compile(
mnist_train, pipeline_file
) | conditional_block |
urls.py | urlpatterns = patterns('',
url(r'^$', index),
url(r'^joblist$',
JobListView.as_view()),
url(r'^job/(?P<pk>\d+)/$',
DetailView.as_view(
model=Job,
# template_name='tacc_stats/detail.html',
)),
url(r'^job_memused_hist$', job_memused_hist ),
url(r'^job_tim... | from django.conf.urls.defaults import patterns, url
from django.views.generic import DetailView, ListView
from tacc_stats.models import Job
from tacc_stats.views import index, job_memused_hist, job_timespent_hist, create_heatmap, search, JobListView, render_json, get_job, data, list_hosts
| random_line_split | |
about_tuples.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutTuples(Koan):
def test_creating_a_tuple(self):
count_of_three = (1, 2, 5)
self.assertEqual(5, count_of_three[2])
def test_tuples_are_immutable_so_item_assignment_is_not_possible(self):
count_of_three =... | self.assertEqual(AttributeError, type(ex))
# Note, assertMatch() uses regular expression pattern matching,
# so you don't have to copy the whole message.
self.assertMatch("'tuple' object has no attribute 'append'", ex[0])
# Tuples are less flexible than lists, b... | except Exception as ex: | random_line_split |
about_tuples.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutTuples(Koan):
| self.assertMatch("'tuple' object has no attribute 'append'", ex[0])
# Tuples are less flexible than lists, but faster.
def test_tuples_can_only_be_changed_through_replacement(self):
count_of_three = (1, 2, 5)
list_count = list(count_of_three)
list_count.append("boom")
... | def test_creating_a_tuple(self):
count_of_three = (1, 2, 5)
self.assertEqual(5, count_of_three[2])
def test_tuples_are_immutable_so_item_assignment_is_not_possible(self):
count_of_three = (1, 2, 5)
try:
count_of_three[2] = "three"
except TypeError as ex:
... | identifier_body |
about_tuples.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutTuples(Koan):
def test_creating_a_tuple(self):
count_of_three = (1, 2, 5)
self.assertEqual(5, count_of_three[2])
def test_tuples_are_immutable_so_item_assignment_is_not_possible(self):
count_of_three =... | (self):
self.assertEqual((), ())
self.assertEqual((), tuple()) # Sometimes less confusing
def test_tuples_can_be_embedded(self):
lat = (37, 14, 6, 'N')
lon = (115, 48, 40, 'W')
place = ('Area 51', lat, lon)
self.assertEqual(('Area 51', (37, 14, 6, 'N'), (115, 48, 40... | test_creating_empty_tuples | identifier_name |
stats.test.js | const round = require('./round');
const { mean, median, stddev } = require('./stats');
const arr = [
40.73,
80.2,
59.54,
54.91,
93.57,
35.69,
99.44,
98.14,
89.3,
21.7,
54.26,
64.02,
18.05,
0.18,
14.79,
60.44,
47.63,
52.33,
75.62,
65.03,
];
describe('Stats', () => {
describe('... | it('should return median for an array', () => {
const expected = 57.225;
const actual = round(median(arr), 4);
expect(actual).toEqual(expected);
});
});
describe('stddev', () => {
it('should return 0 for an empty array', () => {
const expected = 0;
expect(stddev([])).toEqu... | random_line_split | |
prefixed_command_runner.py | from __future__ import unicode_literals
import os
import os.path
import subprocess
from pre_commit.util import cmd_output
class PrefixedCommandRunner(object):
"""A PrefixedCommandRunner allows you to run subprocess commands with
comand substitution.
For instance:
PrefixedCommandRunner('/tmp/foo... | def path(self, *parts):
path = os.path.join(self.prefix_dir, *parts)
return os.path.normpath(path)
def exists(self, *parts):
return os.path.exists(self.path(*parts))
@classmethod
def from_command_runner(cls, command_runner, path_end):
"""Constructs a new command runner ... | random_line_split | |
prefixed_command_runner.py | from __future__ import unicode_literals
import os
import os.path
import subprocess
from pre_commit.util import cmd_output
class | (object):
"""A PrefixedCommandRunner allows you to run subprocess commands with
comand substitution.
For instance:
PrefixedCommandRunner('/tmp/foo').run(['{prefix}foo.sh', 'bar', 'baz'])
will run ['/tmp/foo/foo.sh', 'bar', 'baz']
"""
def __init__(
self,
prefix_... | PrefixedCommandRunner | identifier_name |
prefixed_command_runner.py | from __future__ import unicode_literals
import os
import os.path
import subprocess
from pre_commit.util import cmd_output
class PrefixedCommandRunner(object):
"""A PrefixedCommandRunner allows you to run subprocess commands with
comand substitution.
For instance:
PrefixedCommandRunner('/tmp/foo... |
def run(self, cmd, **kwargs):
self._create_path_if_not_exists()
replaced_cmd = [
part.replace('{prefix}', self.prefix_dir) for part in cmd
]
return cmd_output(*replaced_cmd, __popen=self.__popen, **kwargs)
def path(self, *parts):
path = os.path.join(self.pr... | if not os.path.exists(self.prefix_dir):
self.__makedirs(self.prefix_dir) | identifier_body |
prefixed_command_runner.py | from __future__ import unicode_literals
import os
import os.path
import subprocess
from pre_commit.util import cmd_output
class PrefixedCommandRunner(object):
"""A PrefixedCommandRunner allows you to run subprocess commands with
comand substitution.
For instance:
PrefixedCommandRunner('/tmp/foo... |
def run(self, cmd, **kwargs):
self._create_path_if_not_exists()
replaced_cmd = [
part.replace('{prefix}', self.prefix_dir) for part in cmd
]
return cmd_output(*replaced_cmd, __popen=self.__popen, **kwargs)
def path(self, *parts):
path = os.path.join(self.pr... | self.__makedirs(self.prefix_dir) | conditional_block |
mod.rs | // +--------------------------------------------------------------------------+
// | Copyright 2016 Matthew D. Steele <mdsteele@alum.mit.edu> |
// | |
// | This file is part of System Syzygy. |
... | pub use self::window::Window;
pub use sdl2::rect::{Point, Rect};
pub const FRAME_DELAY_MILLIS: u32 = 40;
// ========================================================================= // | pub use self::event::{Event, KeyMod, Keycode};
pub use self::font::Font;
pub use self::resources::Resources;
pub use self::sound::Sound;
pub use self::sprite::Sprite; | random_line_split |
read_handlers.py | ## Copyright 2014 Cognitect. All Rights Reserved.
##
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
##
## http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable... |
if z == '-INF':
return float('-Inf')
raise ValueError("Don't know how to handle: " + str(z) + " as \"z\"")
| return float('Inf') | conditional_block |
read_handlers.py | ## Copyright 2014 Cognitect. All Rights Reserved.
##
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
##
## http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable... | @staticmethod
def from_rep(v):
return int(v)
class FloatHandler(object):
@staticmethod
def from_rep(v):
return float(v)
class UuidHandler(object):
@staticmethod
def from_rep(u):
"""Given a string, return a UUID object."""
if isinstance(u, pyversion.string_type... |
class IntHandler(object): | random_line_split |
read_handlers.py | ## Copyright 2014 Cognitect. All Rights Reserved.
##
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
##
## http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable... |
else:
class BigIntegerHandler(object):
@staticmethod
def from_rep(d):
return long(d)
class LinkHandler(object):
@staticmethod
def from_rep(l):
return transit_types.Link(**l)
class ListHandler(object):
@staticmethod
def from_rep(l):
return l
class Se... | @staticmethod
def from_rep(d):
return int(d) | identifier_body |
read_handlers.py | ## Copyright 2014 Cognitect. All Rights Reserved.
##
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
##
## http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable... | (u):
return transit_types.URI(u)
class DateHandler(object):
@staticmethod
def from_rep(d):
if isinstance(d, pyversion.int_types):
return DateHandler._convert_timestamp(d)
if "T" in d:
return dateutil.parser.parse(d)
return DateHandler._convert_timestamp(... | from_rep | identifier_name |
joiner.rs | use std::os;
use std::str;
use std::io::File;
fn main() {
let args: ~[~str] = os::args();
if args.len() != 3 {
println!("Usage: {:s} <msg.share1> <msg.share2>", args[0]);
} else {
let share1 = args[1].clone();
let share2 = args[2].clone(); |
match (msg1_file, msg2_file) {
(Some(mut msg1), Some(mut msg2)) => {
let msg1_bytes: ~[u8] = msg1.read_to_end();
let msg2_bytes: ~[u8] = msg2.read_to_end();
let result: ~[u8] = xor(msg1_bytes, msg2_bytes);
print!("{:?}", str::from_utf8... | let path1 = Path::new(share1.clone());
let path2 = Path::new(share2.clone());
let msg1_file = File::open(&path1);
let msg2_file = File::open(&path2); | random_line_split |
joiner.rs | use std::os;
use std::str;
use std::io::File;
fn main() {
let args: ~[~str] = os::args();
if args.len() != 3 {
println!("Usage: {:s} <msg.share1> <msg.share2>", args[0]);
} else |
}
fn xor(a: &[u8], b: &[u8]) -> ~[u8] {
let mut ret = ~[];
for i in range(0, a.len()) {
ret.push(a[i] ^ b[i]);
}
ret
}
| {
let share1 = args[1].clone();
let share2 = args[2].clone();
let path1 = Path::new(share1.clone());
let path2 = Path::new(share2.clone());
let msg1_file = File::open(&path1);
let msg2_file = File::open(&path2);
match (msg1_file, msg2_file) {
(Some(mu... | conditional_block |
joiner.rs | use std::os;
use std::str;
use std::io::File;
fn main() {
let args: ~[~str] = os::args();
if args.len() != 3 {
println!("Usage: {:s} <msg.share1> <msg.share2>", args[0]);
} else {
let share1 = args[1].clone();
let share2 = args[2].clone();
let path1 = Path::new(share1.clone... | (a: &[u8], b: &[u8]) -> ~[u8] {
let mut ret = ~[];
for i in range(0, a.len()) {
ret.push(a[i] ^ b[i]);
}
ret
}
| xor | identifier_name |
joiner.rs | use std::os;
use std::str;
use std::io::File;
fn main() {
let args: ~[~str] = os::args();
if args.len() != 3 {
println!("Usage: {:s} <msg.share1> <msg.share2>", args[0]);
} else {
let share1 = args[1].clone();
let share2 = args[2].clone();
let path1 = Path::new(share1.clone... | {
let mut ret = ~[];
for i in range(0, a.len()) {
ret.push(a[i] ^ b[i]);
}
ret
} | identifier_body | |
shelterpro_dbf.py | o.IsMember = asm.cint(row["MEMBER_IND"])
o.IsBanned = asm.cint(row["NOADOPT"] == "T" and "1" or "0")
if "FOSTERS" in row: o.IsFosterer = asm.cint(row["FOSTERS"])
# o.ExcludeFromBulkEmail = asm.cint(row["MAILINGSAM"]) # Not sure this is correct
# Animals
for row in canimal:
if not IMPORT_ANIMALS_WIT... | a.DeceasedDate = dispdate
a.PutToSleep = 1
a.PTSReasonID = 4 # Sick/Injured
a.Archived = 1
| random_line_split | |
shelterpro_dbf.py | [row["ANIMALKEY"]] = a
a.AnimalTypeID = gettype(row["ANIMLDES"])
a.SpeciesID = asm.species_id_for_name(row["ANIMLDES"].split(" ")[0])
a.AnimalName = asm.strip(row["PETNAME"]).title()
if a.AnimalName.strip() == "":
a.AnimalName = "(unknown)"
age = row["AGE"].split(" ")[0]
added = asm.now(... | if a is None: continue
m = asm.Movement()
m.AnimalID = a.ID
m.OwnerID = to.ID
m.MovementType = 3
m.MovementDate = dispdate
m.Comments = dispmeth
a.Archived = 1
a.ActiveMovementID = m.ID
a.ActiveMovementType = 3
... | conditional_block | |
shelterpro_dbf.py | (name):
return asm.read_dbf(name)
def gettype(animaldes):
spmap = {
"DOG": 2,
"CAT": 11
}
species = animaldes.split(" ")[0]
if species in spmap:
return spmap[species]
else:
return 2
def gettypeletter(aid):
tmap = {
2: "D",
10: "A",
11... | open_dbf | identifier_name | |
shelterpro_dbf.py |
def gettype(animaldes):
spmap = {
"DOG": 2,
"CAT": 11
}
species = animaldes.split(" ")[0]
if species in spmap:
return spmap[species]
else:
return 2
def gettypeletter(aid):
tmap = {
2: "D",
10: "A",
11: "U",
12: "S"
}
retu... | return asm.read_dbf(name) | identifier_body | |
cabi_mips.rs | // Copyright 2012-2013 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... | ty_align(elt)
}
_ => fail!("ty_size: unhandled type")
}
}
fn ty_size(ty: Type) -> uint {
match ty.kind() {
Integer => {
unsafe {
((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8
}
}
Pointer => 4,
Floa... | {
match ty.kind() {
Integer => {
unsafe {
((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8
}
}
Pointer => 4,
Float => 4,
Double => 8,
Struct => {
if ty.is_packed() {
1
} else {
... | identifier_body |
cabi_mips.rs | // Copyright 2012-2013 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 {
((llvm::LLVMGetIntTypeWidth(ty.to_ref()) as uint) + 7) / 8
}
}
Pointer => 4,
Float => 4,
Double => 8,
Struct => {
if ty.is_packed() {
1
} else {
let str_tys = ty.field_types();
... | }
fn ty_align(ty: Type) -> uint {
match ty.kind() {
Integer => { | random_line_split |
cabi_mips.rs | // Copyright 2012-2013 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... | (ccx: &CrateContext, ty: Type) -> Type {
let size = ty_size(ty) * 8;
Type::struct_(ccx, coerce_to_int(ccx, size).as_slice(), false)
}
pub fn compute_abi_info(ccx: &CrateContext,
atys: &[Type],
rty: Type,
ret_def: bool) -> FnType {
let ... | struct_ty | identifier_name |
evaluate-senna-hash-2-pos-chunk-128-64-rmsprop5.py | '''
evaluate result
'''
from keras.models import load_model
from keras.utils import np_utils
import numpy as np
import os
import sys
# add path
sys.path.append('../')
sys.path.append('../tools')
from tools import conf
from tools import load_data
from tools import prepare
# input sentence dimensions
step_length =... |
print('loading model...')
model = load_model(model_path)
print('loading model finished.')
for each in test_data:
embed_index, hash_index, pos, chunk, label, length, sentence = prepare.prepare_ner(batch=[each], gram='bi', form='BIOES')
pos = np.array([(np.concatenate([np_utils.to_categorical(p, pos_length), n... | for p, q in enumerate(chunktags):
if q.startswith("E-"):
chunktags[p] = "I-" + q[2:]
elif q.startswith("S-"):
if p==0:
chunktags[p] = "I-" + q[2:]
elif q[2:]==chunktags[p-1][2:]:
chunktags[p] = "B-" + q[2:]
elif q[2:]!=chunk... | identifier_body |
evaluate-senna-hash-2-pos-chunk-128-64-rmsprop5.py | '''
evaluate result
'''
from keras.models import load_model
from keras.utils import np_utils
import numpy as np
import os
import sys
# add path
sys.path.append('../')
sys.path.append('../tools')
from tools import conf
from tools import load_data
from tools import prepare
# input sentence dimensions
step_length =... | (chunktags):
# convert BIOES to BIO
for p, q in enumerate(chunktags):
if q.startswith("E-"):
chunktags[p] = "I-" + q[2:]
elif q.startswith("S-"):
if p==0:
chunktags[p] = "I-" + q[2:]
elif q[2:]==chunktags[p-1][2:]:
chunktags[p] ... | convert | identifier_name |
evaluate-senna-hash-2-pos-chunk-128-64-rmsprop5.py | '''
evaluate result
'''
from keras.models import load_model
from keras.utils import np_utils
import numpy as np
import os
import sys
# add path
sys.path.append('../')
sys.path.append('../tools')
from tools import conf
from tools import load_data
from tools import prepare
# input sentence dimensions
step_length =... | data = sys.argv[1]
best_epoch = sys.argv[2]
if data=="dev":
test_data = load_data.load_ner(dataset='eng.testa', form='BIOES')
elif data == "test":
test_data = load_data.load_ner(dataset='eng.testb', form='BIOES')
tokens = [len(x[0]) for x in test_data]
print(sum(tokens))
print('%s shape:'%data, len(test_data)... | chunk_length = conf.ner_chunk_length
# gazetteer_length = conf.gazetteer_length
IOB = conf.ner_BIOES_decode
| random_line_split |
evaluate-senna-hash-2-pos-chunk-128-64-rmsprop5.py | '''
evaluate result
'''
from keras.models import load_model
from keras.utils import np_utils
import numpy as np
import os
import sys
# add path
sys.path.append('../')
sys.path.append('../tools')
from tools import conf
from tools import load_data
from tools import prepare
# input sentence dimensions
step_length =... | # chunktags = convert(chunktags)
# chunktags = prepare.gazetteer_lookup(each[0], chunktags, data)
for ind, chunktag in enumerate(chunktags):
result.write(' '.join(word_pos_chunk[ind])+' '+chunktag+'\n')
result.write('\n')
result.close()
print('epoch %s predict over !'%best_epoch)
os.system... | embed_index, hash_index, pos, chunk, label, length, sentence = prepare.prepare_ner(batch=[each], gram='bi', form='BIOES')
pos = np.array([(np.concatenate([np_utils.to_categorical(p, pos_length), np.zeros((step_length-length[l], pos_length))])) for l,p in enumerate(pos)])
chunk = np.array([(np.concatenate([np_ut... | conditional_block |
part14.rs | // Rust-101, Part 14: Slices, Arrays, External Dependencies
// ========================================================
// ## Slices
pub fn sort<T: PartialOrd>(data: &mut [T]) {
if data.len() < 2 { return; }
// We decide that the element at 0 is our pivot, and then we move our cursors through the rest of th... | else {
OutputMode::Print
};
Options {
files: files.iter().map(|file| file.to_string()).collect(),
pattern: pattern.to_string(),
output_mode: mode,
}
}
// Finally, we can call the `run` function from the previous part on the options extrac... | {
OutputMode::SortAndPrint
} | conditional_block |
part14.rs | // Rust-101, Part 14: Slices, Arrays, External Dependencies
// ========================================================
// ## Slices
pub fn sort<T: PartialOrd>(data: &mut [T]) {
if data.len() < 2 { return; }
// We decide that the element at 0 is our pivot, and then we move our cursors through the rest of th... |
}
// **Exercise 14.3**: Wouldn't it be nice if rgrep supported regular expressions? There's already a crate that does all the parsing and matching on regular
// expression, it's called [regex](https://crates.io/crates/regex). Add this crate to the dependencies of your workspace, add an option ("-r") to switch
// the ... | {
unimplemented!()
} | identifier_body |
part14.rs | // Rust-101, Part 14: Slices, Arrays, External Dependencies
// ========================================================
// ## Slices
pub fn sort<T: PartialOrd>(data: &mut [T]) {
if data.len() < 2 { return; }
// We decide that the element at 0 is our pivot, and then we move our cursors through the rest of th... | let mode = if count {
OutputMode::Count
} else if sort {
OutputMode::SortAndPrint
} else {
OutputMode::Print
};
Options {
files: files.iter().map(|file| file.to_string()).collect(),
pattern: pattern.to_string(),
... | // We need to make the strings owned to construct the `Options` instance. | random_line_split |
part14.rs | // Rust-101, Part 14: Slices, Arrays, External Dependencies
// ========================================================
// ## Slices
pub fn sort<T: PartialOrd>(data: &mut [T]) {
if data.len() < 2 { return; }
// We decide that the element at 0 is our pivot, and then we move our cursors through the rest of th... | () {
let mut array_of_data: [f64; 5] = [1.0, 3.4, 12.7, -9.12, 0.1];
sort(&mut array_of_data);
}
// ## External Dependencies
// I disabled the following module (using a rather bad hack), because it only compiles if `docopt` is linked.
// Remove the attribute of the `rgrep` module to enable compilation.
#[cfg... | sort_array | identifier_name |
TwitterWebPart.ts | import { Version } from '@microsoft/sp-core-library';
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
PropertyPaneTextField
} from '@microsoft/sp-webpart-base';
import { escape } from '@microsoft/sp-lodash-subset';
import styles from './TwitterWebPart.module.scss';
import * as strings from 'TwitterWe... |
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.BasicGroupName,
groupFields: [
... | {
return Version.parse('1.0');
} | identifier_body |
TwitterWebPart.ts | import { Version } from '@microsoft/sp-core-library';
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
PropertyPaneTextField
} from '@microsoft/sp-webpart-base';
import { escape } from '@microsoft/sp-lodash-subset';
import styles from './TwitterWebPart.module.scss';
import * as strings from 'TwitterWe... | public render(): void {
this.domElement.innerHTML = `
<div class="${styles.twitter}">
<div class="${styles.container}">
<div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
<div class="ms-Grid-col ms-lg10 ms-xl8 ms-xlPush2 ms-lgPush1">
<a ... | random_line_split | |
TwitterWebPart.ts | import { Version } from '@microsoft/sp-core-library';
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
PropertyPaneTextField
} from '@microsoft/sp-webpart-base';
import { escape } from '@microsoft/sp-lodash-subset';
import styles from './TwitterWebPart.module.scss';
import * as strings from 'TwitterWe... | (): Version {
return Version.parse('1.0');
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.... | dataVersion | identifier_name |
php.js | define(["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.phpLang = phpLang;
function phpLang(hljs) {
var VARIABLE = {
begin: "\\$+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*"
};
var PREPROCESSOR = {
className: "... | illegal: null
})]
};
var NUMBER = {
variants: [hljs.BINARY_NUMBER_MODE, hljs.C_NUMBER_MODE]
};
return {
aliases: ["php", "php3", "php4", "php5", "php6", "php7"],
case_insensitive: true,
keywords: "and include_once list abstract global private echo interface as stati... | end: "'"
}, hljs.inherit(hljs.APOS_STRING_MODE, {
illegal: null
}), hljs.inherit(hljs.QUOTE_STRING_MODE, { | random_line_split |
php.js | define(["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.phpLang = phpLang;
function | (hljs) {
var VARIABLE = {
begin: "\\$+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*"
};
var PREPROCESSOR = {
className: "meta",
begin: /<\?(php)?|\?>/
};
var STRING = {
className: "string",
contains: [hljs.BACKSLASH_ESCAPE, PREPROCESSOR],
variants: [{
begin: 'b... | phpLang | identifier_name |
php.js | define(["exports"], function (_exports) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.phpLang = phpLang;
function phpLang(hljs) | illegal: null
})]
};
var NUMBER = {
variants: [hljs.BINARY_NUMBER_MODE, hljs.C_NUMBER_MODE]
};
return {
aliases: ["php", "php3", "php4", "php5", "php6", "php7"],
case_insensitive: true,
keywords: "and include_once list abstract global private echo interface as stati... | {
var VARIABLE = {
begin: "\\$+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*"
};
var PREPROCESSOR = {
className: "meta",
begin: /<\?(php)?|\?>/
};
var STRING = {
className: "string",
contains: [hljs.BACKSLASH_ESCAPE, PREPROCESSOR],
variants: [{
begin: 'b"',
... | identifier_body |
tests.js | /* global describe, beforeEach, it */
import { expect } from "chai";
import { shouldOpenInNewTab } from "./utils";
describe("app/lib/utils:shouldOpenInNewTab", () => {
let mockClickEvent;
beforeEach(() => {
mockClickEvent = { | });
it("should default to false", () => {
expect(shouldOpenInNewTab(mockClickEvent)).to.be.false;
});
it("should return true when ctrl-clicked", () => {
mockClickEvent.ctrlKey = true;
expect(shouldOpenInNewTab(mockClickEvent)).to.be.true;
});
it("should return true when cmd-clicked", () => {
... | ctrlKey: false,
metaKey: false,
type: "click",
button: 0
}; | random_line_split |
edl-split.js | function convertEdl() {
var join = document.getElementById("join").checked;
var stills = document.getElementById("stills").checked;
var crop = document.getElementById("crop").checked;
var input = document.getElementById("input").value;
var frames = [];
var pat = /C +(\d+)/g;
var match = pat... | output += "c" + i;
} else {
output += "+c" + i;
}
}
}
document.getElementById("output").value = output;
} | output += "\n\\";
}
if (i === 0) { | random_line_split |
edl-split.js | function convertEdl() | output += "#~ ";
}
output += "Trim(" + frames[i] + ", ";
if (stills) {
output += "-1)";
} else if (i < (frames.length - 1)) {
output += frames[i + 1] + "-1)";
} else {
output += "0)";
}
if (crop) {
outp... | {
var join = document.getElementById("join").checked;
var stills = document.getElementById("stills").checked;
var crop = document.getElementById("crop").checked;
var input = document.getElementById("input").value;
var frames = [];
var pat = /C +(\d+)/g;
var match = pat.exec(input);
whil... | identifier_body |
edl-split.js | function convertEdl() {
var join = document.getElementById("join").checked;
var stills = document.getElementById("stills").checked;
var crop = document.getElementById("crop").checked;
var input = document.getElementById("input").value;
var frames = [];
var pat = /C +(\d+)/g;
var match = pat... |
}
}
document.getElementById("output").value = output;
}
| {
output += "+c" + i;
} | conditional_block |
edl-split.js | function | () {
var join = document.getElementById("join").checked;
var stills = document.getElementById("stills").checked;
var crop = document.getElementById("crop").checked;
var input = document.getElementById("input").value;
var frames = [];
var pat = /C +(\d+)/g;
var match = pat.exec(input);
w... | convertEdl | identifier_name |
head-let-destructuring.js | // Copyright (C) 2016 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
esid: sec-iteration-statements
es6id: 13.7
description: >
The token sequence `let [`is interpreted as the beginning of a destructuring
binding pattern
info: |
Syntax
I... |
for ( let[x] in obj ) {
value = x;
}
assert.sameValue(typeof x, 'undefined', 'binding is block-scoped');
assert.sameValue(value, 'k'); | var value;
obj.key = 1; | random_line_split |
index.d.ts | // Type definitions for non-npm package DiskQuotaTypeLibrary 1.0
// Project: https://msdn.microsoft.com/en-us/library/windows/desktop/bb773938(v=vs.85).aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
| dqAcctDeleted = 2,
dqAcctInvalid = 3,
dqAcctResolved = 0,
dqAcctUnavailable = 1,
dqAcctUnknown = 4,
dqAcctUnresolved = 5,
}
// tslint:disable-next-line no-const-enum
const enum QuotaStateConstants {
dqStateDisable = 0,
dqStateEnforce = 2,
... | /// <reference types="activex-interop" />
declare namespace DiskQuotaTypeLibrary {
// tslint:disable-next-line no-const-enum
const enum AccountStatusConstants { | random_line_split |
index.d.ts | // Type definitions for non-npm package DiskQuotaTypeLibrary 1.0
// Project: https://msdn.microsoft.com/en-us/library/windows/desktop/bb773938(v=vs.85).aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
/// <refere... | {
private 'DiskQuotaTypeLibrary.DiskQuotaControl_typekey': DiskQuotaControl;
private constructor();
/** Add a user quota entry by Name */
AddUser(LogonName: string): DIDiskQuotaUser;
/** Default quota limit applied to new volume users (byte value) */
DefaultQuotaLimit:... | DiskQuotaControl | identifier_name |
run_combined.py | import os
import csv
import pickle
from indra.literature import id_lookup
from indra.sources import trips, reach, index_cards
from assembly_eval import have_file, run_assembly
if __name__ == '__main__':
pmc_ids = [s.strip() for s in open('pmcids.txt', 'rt').readlines()]
# Load the REACH reading output
wit... |
# Combine all statements
all_statements = tp.statements + reach_stmts_for_pmcid + nactem_stmts
# Run assembly
run_assembly(all_statements, 'combined', pmcid)
| icp = index_cards.process_json_file(fname, 'nactem')
nactem_stmts = icp.statements | conditional_block |
run_combined.py | import os
import csv
import pickle
from indra.literature import id_lookup
from indra.sources import trips, reach, index_cards
from assembly_eval import have_file, run_assembly
if __name__ == '__main__':
pmc_ids = [s.strip() for s in open('pmcids.txt', 'rt').readlines()]
# Load the REACH reading output |
# Load the PMID to PMCID map
pmcid_to_pmid = {}
with open('pmc_batch_4_id_map.txt') as f:
csvreader = csv.reader(f, delimiter='\t')
for row in csvreader:
pmcid_to_pmid[row[0]] = row[1]
for pmcid in pmc_ids:
print 'Processing %s...' % pmcid
# Process TRIPS
... | with open('reach/reach_stmts_batch_4_eval.pkl') as f:
reach_stmts = pickle.load(f) | random_line_split |
MemberBio.tsx | import React from 'react'
import { Link } from 'gatsby'
import styled from 'styled-components'
import { IMember } from '../../types'
import { TEAM_MEMBER_ROUTE } from '../../constants/routes'
import { Card, Flex, H4, LinkChevronRightIcon, Fade } from '../../shared'
import {
BORDER_RADIUS_LG,
minWidth,
PHONE,
... | const CenteredFlex = styled(Flex)`
align-items: center;
`
interface IMemberBioProps {
author: IMember
}
const Bio = styled.div`
font-size: 80%;
line-height: 1.375;
p {
margin-bottom: ${M2};
}
`
const StyledCenteredFlex = styled(CenteredFlex)`
${maxWidth(PHONE)} {
align-items: start;
}
`
con... | }
`
| random_line_split |
regions-trait-1.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 ... | <'a> { c: &'a ctxt }
impl<'a> get_ctxt for has_ctxt<'a> {
// Here an error occurs because we used `&self` but
// the definition used `&`:
fn get_ctxt(&self) -> &'a ctxt { //~ ERROR method `get_ctxt` has an incompatible type
self.c
}
}
fn get_v(gc: Box<get_ctxt>) -> uint {
gc.get_ctxt().v... | has_ctxt | identifier_name |
regions-trait-1.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 ... |
}
fn get_v(gc: Box<get_ctxt>) -> uint {
gc.get_ctxt().v
}
fn main() {
let ctxt = ctxt { v: 22u };
let hc = has_ctxt { c: &ctxt };
assert_eq!(get_v(box hc as Box<get_ctxt>), 22u);
} | fn get_ctxt(&self) -> &'a ctxt { //~ ERROR method `get_ctxt` has an incompatible type
self.c
} | random_line_split |
filesearch.rs | option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_camel_case_types)]
pub use self::FileMatch::*;
use std::collections::HashSet;
use std::io::fs::PathExtensions;
use std::io::fs;
use std::os;
use util::fs as myfs;
use session::search_paths::{SearchPaths, ... | FileDoesntMatch => {
debug!("rejected {}", path.display());
}
}
}
rslt
}
Err(..) => FileDoesntMatch,
}
});
}
... | rslt = FileMatches;
} | random_line_split |
filesearch.rs | option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_camel_case_types)]
pub use self::FileMatch::*;
use std::collections::HashSet;
use std::io::fs::PathExtensions;
use std::io::fs;
use std::os;
use util::fs as myfs;
use session::search_paths::{SearchPaths, ... | }
visited_dirs.insert(tlib_path.as_vec().to_vec());
// Try RUST_PATH
if !found {
let rustpath = rust_path();
for path in rustpath.iter() {
let tlib_path = make_rustpkg_lib_path(
self.sysroot, path, self.triple);
... | {
let mut visited_dirs = HashSet::new();
let mut found = false;
for path in self.search_paths.iter(self.kind) {
match f(path) {
FileMatches => found = true,
FileDoesntMatch => ()
}
visited_dirs.insert(path.as_vec().to_vec());
... | identifier_body |
filesearch.rs | option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_camel_case_types)]
pub use self::FileMatch::*;
use std::collections::HashSet;
use std::io::fs::PathExtensions;
use std::io::fs;
use std::os;
use util::fs as myfs;
use session::search_paths::{SearchPaths, ... | <F>(&self, mut pick: F) where F: FnMut(&Path) -> FileMatch {
self.for_each_lib_search_path(|lib_search_path| {
debug!("searching {}", lib_search_path.display());
match fs::readdir(lib_search_path) {
Ok(files) => {
let mut rslt = FileDoesntMatch;
... | search | identifier_name |
mod.rs | // Copyright 2020 The Tink-Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or ag... | pub use reader::*;
mod validation;
pub use validation::*;
mod writer;
pub use writer::*;
#[cfg(feature = "insecure")]
#[cfg_attr(docsrs, doc(cfg(feature = "insecure")))]
pub mod insecure; | mod manager;
pub use manager::*;
mod mem_io;
pub use mem_io::*;
mod reader; | random_line_split |
test_product_tmpl_image.py | # Copyright 2019 Rafis Bikbov <https://it-projects.info/team/RafiZz>
# Copyright 2019 Alexandr Kolushov <https://it-projects.info/team/KolushovAlexandr>
# Copyright 2019 Eugene Molotov <https://it-projects.info/team/em230418>
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html).
import logging
from odo... | (self, px=1024):
return "https://upload.wikimedia.org/wikipedia/commons/thumb/1/1e/Gullfoss%2C_an_iconic_waterfall_of_Iceland.jpg/{}px-Gullfoss%2C_an_iconic_waterfall_of_Iceland.jpg".format(
px
)
def _get_odoo_image_url(self, model, record_id, field):
return "/web/image?model={}... | _get_original_image_url | identifier_name |
test_product_tmpl_image.py | # Copyright 2019 Rafis Bikbov <https://it-projects.info/team/RafiZz>
# Copyright 2019 Alexandr Kolushov <https://it-projects.info/team/KolushovAlexandr>
# Copyright 2019 Eugene Molotov <https://it-projects.info/team/em230418>
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html).
import logging
from odo... | }
)
odoo_image_url = self._get_odoo_image_url(
"product.product", product_product.id, "image"
)
odoo_image_medium_url = self._get_odoo_image_url(
"product.product", product_product.id, "image_medium"
)
odoo_image_small_url = self._get_... | random_line_split | |
test_product_tmpl_image.py | # Copyright 2019 Rafis Bikbov <https://it-projects.info/team/RafiZz>
# Copyright 2019 Alexandr Kolushov <https://it-projects.info/team/KolushovAlexandr>
# Copyright 2019 Eugene Molotov <https://it-projects.info/team/em230418>
# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html).
import logging
from odo... | "image": self._get_original_image_url(1024),
"image_medium": self._get_original_image_url(128),
"image_small": self._get_original_image_url(64),
}
)
product_product = env["product.product"].create(
{
"name": "Test p... | def _get_original_image_url(self, px=1024):
return "https://upload.wikimedia.org/wikipedia/commons/thumb/1/1e/Gullfoss%2C_an_iconic_waterfall_of_Iceland.jpg/{}px-Gullfoss%2C_an_iconic_waterfall_of_Iceland.jpg".format(
px
)
def _get_odoo_image_url(self, model, record_id, field):
... | identifier_body |
ecosystem.config.js | module.exports = {
apps: [{
name: 'URL-ShortenerAPI',
script: './source/server.js',
env: {
watch: 'source',
ignore_watch : 'source/gui',
NODE_ENV: 'development',
MONGO_PORT: 28017,
API_PORT: 8000
},
env_production: {
watch: false,
NODE_ENV: 'production',
... | 'ref': 'origin/master',
'repo': 'git@github.com:taxnuke/url-shortener.git',
'path': '/var/www/short.taxnuke.ru',
'post-deploy':
'npm i && npm run build && pm2 startOrReload ecosystem.config.js \
--update-env --env production'
}
}
} | production: {
'user': 'adminus',
'host': '138.68.183.160', | random_line_split |
tweets.py | # -*- coding: utf-8 -*-
'''
script.matchcenter - Football information for Kodi
A program addon that can be mapped to a key on your remote to display football information.
Livescores, Event details, Line-ups, League tables, next and previous matches by team. Follow what
others are saying about the match ... | the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU ... | 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 | random_line_split |
tweets.py | # -*- coding: utf-8 -*-
'''
script.matchcenter - Football information for Kodi
A program addon that can be mapped to a key on your remote to display football information.
Livescores, Event details, Line-ups, League tables, next and previous matches by team. Follow what
others are saying about the match ... | (twitterhash=None, standalone=False):
if not twitterhash:
userInput = True
if os.path.exists(tweet_file):
twitter_data = json.loads(FileIO.fileread(tweet_file))
twitterhash = twitter_data["hash"]
twitter_mediafile = twitter_data["file"]
if twitter_mediafile == xbmc.getInfoLabel('Player.Filenameandpath'... | start | identifier_name |
tweets.py | # -*- coding: utf-8 -*-
'''
script.matchcenter - Football information for Kodi
A program addon that can be mapped to a key on your remote to display football information.
Livescores, Event details, Line-ups, League tables, next and previous matches by team. Follow what
others are saying about the match ... | def getTweets(self):
self.getControl(32500).setLabel("#"+self.hash)
self.getControl(32503).setImage(os.path.join(addon_path,"resources","img","twitter_sm.png"))
tweetitems = []
tweets = tweet.get_hashtag_tweets(self.hash)
if tweets:
for _tweet in tweets:
td = ssutils.get_timedelta_string(datetime.date... | def __init__( self, *args, **kwargs ):
self.isRunning = True
self.hash = kwargs["hash"]
self.standalone = kwargs["standalone"]
self.teamObjs = {}
def onInit(self):
xbmc.log(msg="[Match Center] Twitter cycle started", level=xbmc.LOGDEBUG)
self.getControl(32540).setImage(os.path.join(addon_path,"resources",... | identifier_body |
tweets.py | # -*- coding: utf-8 -*-
'''
script.matchcenter - Football information for Kodi
A program addon that can be mapped to a key on your remote to display football information.
Livescores, Event details, Line-ups, League tables, next and previous matches by team. Follow what
others are saying about the match ... |
if twitterhash:
#Save twitter hashtag
if twitter_history_enabled == 'true':
tweet.add_hashtag_to_twitter_history(twitterhash)
if xbmc.getCondVisibility("Player.HasMedia") and save_hashes_during_playback == 'true':
tweet.savecurrenthash(twitterhash)
main = TwitterDialog('script-matchcenter-Twitter.xm... | dialog = xbmcgui.Dialog()
twitterhash = dialog.input(translate(32046), type=xbmcgui.INPUT_ALPHANUM)
if len(twitterhash) != 0:
twitterhash = twitterhash.replace("#","")
else:
xbmcgui.Dialog().ok(translate(32000), translate(32047))
mainmenu.start() | conditional_block |
os.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 ... |
use libc;
use libc::{c_int, c_char, c_void};
use prelude::*;
use io::{IoResult, IoError};
use sys::fs::FileDesc;
use ptr;
use os::TMPBUF_SZ;
pub fn errno() -> uint {
use libc::types::os::arch::extra::DWORD;
#[link_name = "kernel32"]
extern "system" {
fn GetLastError() -> DWORD;
}
unsafe... | random_line_split | |
os.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 ... | {
// Windows pipes work subtly differently than unix pipes, and their
// inheritance has to be handled in a different way that I do not
// fully understand. Here we explicitly make the pipe non-inheritable,
// which means to pass it to a subprocess they need to be duplicated
// first, as in std::run... | identifier_body | |
os.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 ... |
let msg = String::from_utf16(::str::truncate_utf16_at_nul(buf));
match msg {
Some(msg) => format!("OS Error {}: {}", errnum, msg),
None => format!("OS Error {} (FormatMessageW() returned invalid UTF-16)", errnum),
}
}
}
pub unsafe fn pipe() -> IoResult<(FileDesc, F... | {
// Sometimes FormatMessageW can fail e.g. system doesn't like langId,
let fm_err = errno();
return format!("OS Error {} (FormatMessageW() returned error {})", errnum, fm_err);
} | conditional_block |
os.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 ... | () -> uint {
use libc::types::os::arch::extra::DWORD;
#[link_name = "kernel32"]
extern "system" {
fn GetLastError() -> DWORD;
}
unsafe {
GetLastError() as uint
}
}
/// Get a detailed string description for the given error number
pub fn error_string(errnum: i32) -> String {
... | errno | identifier_name |
cisco_constants.py | # Copyright 2011 Cisco Systems, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requir... | # Attachment attributes
INSTANCE_ID = 'instance_id'
TENANT_ID = 'tenant_id'
TENANT_NAME = 'tenant_name'
HOST_NAME = 'host_name'
# Network attributes
NET_ID = 'id'
NET_NAME = 'name'
NET_VLAN_ID = 'vlan_id'
NET_VLAN_NAME = 'vlan_name'
NET_PORTS = 'ports'
CREDENTIAL_ID = 'credential_id'
CREDENTIAL_NAME = 'credential_nam... | # under the License.
#
# @author: Sumit Naiksatam, Cisco Systems, Inc.
| random_line_split |
Npc.js | import Objects from './'
import Character from './Character'
import Actions from '../actions'
import Attacks from '../actions/Attacks'
import Dash from '../actions/Dash'
const addMoveAnimations = function () {
Object.keys(this.directions).map(
(direction) => this.atlasAnimations.add({
action: Actions.move,... | () {
super.update()
}
}
| update | identifier_name |
Npc.js | import Objects from './'
import Character from './Character'
import Actions from '../actions'
import Attacks from '../actions/Attacks'
import Dash from '../actions/Dash'
const addMoveAnimations = function () {
Object.keys(this.directions).map(
(direction) => this.atlasAnimations.add({
action: Actions.move,... | }) {
super({
game,
x,
y,
name,
type: Objects.npc,
firstSprite: `${name}-move-down-1`
})
this.setActions([
new Attacks({
character: this,
attacks: [{id: 0, type: 'normal', time: 24, speed: 13, cooldown: 15}]
}),
new Dash({
chara... | }
export default class extends Character {
constructor ({
game, x, y, name | random_line_split |
Npc.js | import Objects from './'
import Character from './Character'
import Actions from '../actions'
import Attacks from '../actions/Attacks'
import Dash from '../actions/Dash'
const addMoveAnimations = function () {
Object.keys(this.directions).map(
(direction) => this.atlasAnimations.add({
action: Actions.move,... |
this.speed = 140
addMoveAnimations.call(this)
addAtkAnimations.call(this)
}
update () {
super.update()
}
}
| {
super({
game,
x,
y,
name,
type: Objects.npc,
firstSprite: `${name}-move-down-1`
})
this.setActions([
new Attacks({
character: this,
attacks: [{id: 0, type: 'normal', time: 24, speed: 13, cooldown: 15}]
}),
new Dash({
character:... | identifier_body |
formatagesource0.rs | use std::fmt::{self, Formatter, Display};
struct City {
name: &'static str,
// Latitude
lat: f32,
// Longitude
lon: f32,
}
impl Display for City {
// `f` est un tampon, cette méthode écrit la chaîne de caractères
// formattée à l'intérieur de ce dernier.
fn fmt(&se | f: &mut Formatter) -> fmt::Result {
let lat_c = if self.lat >= 0.0 { 'N' } else { 'S' };
let lon_c = if self.lon >= 0.0 { 'E' } else { 'W' };
// `write!` est équivalente à `format!`, à l'exception qu'elle écrira
// la chaîne de caractères formatée dans un tampon (le premier argument).
... | lf, | identifier_name |
formatagesource0.rs | use std::fmt::{self, Formatter, Display};
struct City {
name: &'static str,
// Latitude
lat: f32,
// Longitude
lon: f32,
}
impl Display for City {
// `f` est un tampon, cette méthode écrit la chaîne de caractères
// formattée à l'intérieur de ce dernier.
fn fmt(&self, f: &mut Formatter... | // le trait fmt::Display.
println!("{:?}", *color)
}
} | Color { red: 0, green: 3, blue: 254 },
Color { red: 0, green: 0, blue: 0 },
].iter() {
// Utilisez le marqueur `{}` une fois que vous aurez implémenté | random_line_split |
formatagesource0.rs | use std::fmt::{self, Formatter, Display};
struct City {
name: &'static str,
// Latitude
lat: f32,
// Longitude
lon: f32,
}
impl Display for City {
// `f` est un tampon, cette méthode écrit la chaîne de caractères
// formattée à l'intérieur de ce dernier.
fn fmt(&self, f: &mut Formatter... | let lon_c = if self.lon >= 0.0 { 'E' } else { 'W' };
// `write!` est équivalente à `format!`, à l'exception qu'elle écrira
// la chaîne de caractères formatée dans un tampon (le premier argument).
write!(f, "{}: {:.3}°{} {:.3}°{}",
self.name, self.lat.abs(), lat_c, self.lon.ab... | ;
| conditional_block |
models.py | from django.db import models
# Create your models here.
MEASUREMENT = (
('c', 'cups'),
('tsp', 'teaspoons'),
('tbsp', 'tablespoons'),
('item', 'item'),
)
class Step(models.Model):
"""A step in a recipe"""
order = models.IntegerField()
directions = models.TextField()
recipe = models.F... | class Recipe(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name | random_line_split | |
models.py | from django.db import models
# Create your models here.
MEASUREMENT = (
('c', 'cups'),
('tsp', 'teaspoons'),
('tbsp', 'tablespoons'),
('item', 'item'),
)
class Step(models.Model):
"""A step in a recipe"""
order = models.IntegerField()
directions = models.TextField()
recipe = models.F... | name = models.CharField(max_length=100)
def __str__(self):
return self.name | identifier_body | |
models.py | from django.db import models
# Create your models here.
MEASUREMENT = (
('c', 'cups'),
('tsp', 'teaspoons'),
('tbsp', 'tablespoons'),
('item', 'item'),
)
class Step(models.Model):
"""A step in a recipe"""
order = models.IntegerField()
directions = models.TextField()
recipe = models.F... | (self):
return self.name
class RecipeIngredient(models.Model):
ingredient = models.ForeignKey('Ingredient')
recipe = models.ForeignKey('Recipe')
quantity = models.FloatField()
unit = models.CharField(choices=MEASUREMENT, max_length=10)
description = models.CharField(max_length=100)
not... | __str__ | identifier_name |
zeroconf.py | """
This module exposes Home Assistant via Zeroconf.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/zeroconf/
"""
import logging
import socket
import voluptuous as vol
from homeassistant import util | DOMAIN = 'zeroconf'
REQUIREMENTS = ['zeroconf==0.19.1']
ZEROCONF_TYPE = '_home-assistant._tcp.local.'
CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({}),
}, extra=vol.ALLOW_EXTRA)
def setup(hass, config):
"""Set up Zeroconf and make Home Assistant discoverable."""
from zeroconf import Zeroconf, Servic... | from homeassistant.const import (EVENT_HOMEASSISTANT_STOP, __version__)
_LOGGER = logging.getLogger(__name__)
DEPENDENCIES = ['api'] | random_line_split |
zeroconf.py | """
This module exposes Home Assistant via Zeroconf.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/zeroconf/
"""
import logging
import socket
import voluptuous as vol
from homeassistant import util
from homeassistant.const import (EVENT_HOMEASSISTANT... | (event):
"""Stop Zeroconf."""
zeroconf.unregister_service(info)
zeroconf.close()
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_zeroconf)
return True
| stop_zeroconf | identifier_name |
zeroconf.py | """
This module exposes Home Assistant via Zeroconf.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/zeroconf/
"""
import logging
import socket
import voluptuous as vol
from homeassistant import util
from homeassistant.const import (EVENT_HOMEASSISTANT... |
info = ServiceInfo(ZEROCONF_TYPE, zeroconf_name, host_ip_pton,
hass.http.server_port, 0, 0, params)
zeroconf.register_service(info)
def stop_zeroconf(event):
"""Stop Zeroconf."""
zeroconf.unregister_service(info)
zeroconf.close()
hass.bus.listen_once(EV... | """Set up Zeroconf and make Home Assistant discoverable."""
from zeroconf import Zeroconf, ServiceInfo
zeroconf = Zeroconf()
zeroconf_name = '{}.{}'.format(hass.config.location_name, ZEROCONF_TYPE)
requires_api_password = hass.config.api.api_password is not None
params = {
'version': __ve... | identifier_body |
reverse_lookup.js | describe("domain landing page", () => {
beforeEach(() => {
cy.elektraLogin(
Cypress.env("TEST_DOMAIN"),
Cypress.env("TEST_USER"),
Cypress.env("TEST_PASSWORD")
)
})
| cy.visit(`/${Cypress.env("TEST_DOMAIN")}/lookup/reverselookup`)
cy.contains('[data-test=page-title]','Find Project')
cy.get('#reverseLookupValue').type('elektra-test-vm (do not delete){enter}')
cy.contains('Could not load object (Request failed with status code 404)')
cy.get('#reverseLookupValue').t... | it("open reverse lookup page and search for elektra test vm", () => { | random_line_split |
data.py | import itertools
import os
import zipfile
import numpy as np
import requests
import scipy.sparse as sp
def _get_movielens_path():
"""
Get path to the movielens dataset file.
"""
return os.path.join(os.path.dirname(os.path.abspath(__file__)),
'movielens.zip')
def _download... | (rows, cols, data):
"""
Build the training matrix (no_users, no_items),
with ratings >= 4.0 being marked as positive and
the rest as negative.
"""
mat = sp.lil_matrix((rows, cols), dtype=np.int32)
for uid, iid, rating, timestamp in data:
if rating >= 4.0:
mat[uid, iid] ... | _build_interaction_matrix | identifier_name |
data.py | import itertools
import os
import zipfile
import numpy as np
import requests
import scipy.sparse as sp
def _get_movielens_path():
"""
Get path to the movielens dataset file.
"""
return os.path.join(os.path.dirname(os.path.abspath(__file__)),
'movielens.zip')
def _download... |
return mat.tocoo()
def _get_movie_raw_metadata():
"""
Get raw lines of the genre file.
"""
path = _get_movielens_path()
if not os.path.isfile(path):
_download_movielens(path)
with zipfile.ZipFile(path) as datafile:
return datafile.read('ml-100k/u.item').decode(errors='... | if rating >= 4.0:
mat[uid, iid] = 1.0
else:
mat[uid, iid] = -1.0 | conditional_block |
data.py | import itertools
import os | import zipfile
import numpy as np
import requests
import scipy.sparse as sp
def _get_movielens_path():
"""
Get path to the movielens dataset file.
"""
return os.path.join(os.path.dirname(os.path.abspath(__file__)),
'movielens.zip')
def _download_movielens(dest_path):
... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.