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
__init__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # Copyright Kitware Inc. # # Licensed under the Apache License, Version 2.0 ( the "License" ); # you may not use this file except in compliance with the License. # You may obtain a copy of ...
(event): # This will only trigger if no exceptions (for access, invalid id, etc.) are thrown extraParams = event.info['params'] if 'terms' in extraParams: collectionResponse = event.info['returnVal'] collectionId = collectionResponse['_id'] terms = extraParams['terms'] Model...
afterPostPutCollection
identifier_name
id3v1.rs
else { Some(Year {value: year}) } } } impl Bounded for Year { #![allow(deprecated)] fn min_value() -> Year { Year {value: 0} } fn max_value() -> Year { Year {value: 9999} } } /// ID3v1 extended time tags--encoded in the format "mmm:ss", a valid value can be...
{ None }
conditional_block
id3v1.rs
-> Year { Year {value: 0} } fn max_value() -> Year { Year {value: 9999} } } /// ID3v1 extended time tags--encoded in the format "mmm:ss", a valid value can be a maximum of 999m99s = 999*60+99 = 60039 seconds. #[derive(Copy, Clone, Debug)] pub struct Time { value: u16, } impl Time { ...
<W: Write>(&self, writer: &mut W, write_track_number: bool) -> Result<(), io::Error> { use self::Fields::*; try!(writer.write(TAG)); try!(write_zero_padded(writer, &*self.title, 0, Title.length())); try!(write_zero_padded(writer, &*self.artist, 0, Artist.length())); try!(write_ze...
write
identifier_name
id3v1.rs
() -> Year { Year {value: 0} } fn max_value() -> Year { Year {value: 9999} } } /// ID3v1 extended time tags--encoded in the format "mmm:ss", a valid value can be a maximum of 999m99s = 999*60+99 = 60039 seconds. #[derive(Copy, Clone, Debug)] pub struct Time { value: u16, } impl Time { ...
} impl Bounded for Time { #![allow(deprecated)] fn min_value() -> Time { Time {value: 0} } fn max_value() -> Time { Time {value: 60039} } } impl fmt::Display for Time { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:03}:{:02}", self.seconds()/60, se...
} else { Some(Time {value: seconds}) } }
random_line_split
id3v1.rs
-> Year { Year {value: 0} } fn max_value() -> Year { Year {value: 9999} } } /// ID3v1 extended time tags--encoded in the format "mmm:ss", a valid value can be a maximum of 999m99s = 999*60+99 = 60039 seconds. #[derive(Copy, Clone, Debug)] pub struct Time { value: u16, } impl Time { ...
impl Tag { /// Create a new ID3v1 tag with no information. pub fn new() -> Tag { Tag { title: vec![], artist: vec![], album: vec![], year: Year::new(0).unwrap(), comment: vec![], track: 0, genre: 0, speed: 0, genre_str: vec![], start_time: Time::new(0).unwrap(), end_time: Time:...
{ let start = ::std::cmp::min(offset, data.len()); let actual_len = ::std::cmp::min(offset+len, data.len()); try!(writer.write(&data[start..actual_len])); for _ in 0..(len-(actual_len-start)) { try!(writer.write(&[0])); } Ok(()) }
identifier_body
atomic.rs
use byteorder::{ReadBytesExt, LittleEndian}; use super::{Section, Struct, Result, Error, ReadExt, Stream}; use super::{FrameList, Frame, FrameObjectValue, FrameObject}; use super::{GeometryList, Geometry, Extension}; use std::cell::RefCell; use std::rc::{Rc, Weak}; bitflags! { /// Specifies the options available ...
} impl FrameObject for Rc<Atomic> { fn to_frame_object(&self) -> FrameObjectValue { FrameObjectValue::Atomic(self.clone()) } fn frame_refcell(&self) -> &RefCell<Option<Weak<Frame>>> { &self.parent } } impl Atomic { /// Constructs an atomic containing the specified geometry. p...
{ 0x0014 }
identifier_body
atomic.rs
use byteorder::{ReadBytesExt, LittleEndian}; use super::{Section, Struct, Result, Error, ReadExt, Stream}; use super::{FrameList, Frame, FrameObjectValue, FrameObject}; use super::{GeometryList, Geometry, Extension}; use std::cell::RefCell; use std::rc::{Rc, Weak}; bitflags! { /// Specifies the options available ...
(frame: Option<Rc<Frame>>, flags: AtomicFlags, geometry: Rc<Geometry>) -> Rc<Atomic> { let atomic = Rc::new(Atomic::new(flags, geometry)); atomic.set_frame(frame); atomic } /// Gets the frame attached to this Atomic. pub fn frame(&self) ->...
with_frame
identifier_name
atomic.rs
use byteorder::{ReadBytesExt, LittleEndian}; use super::{Section, Struct, Result, Error, ReadExt, Stream}; use super::{FrameList, Frame, FrameObjectValue, FrameObject}; use super::{GeometryList, Geometry, Extension}; use std::cell::RefCell; use std::rc::{Rc, Weak}; bitflags! { /// Specifies the options available ...
let (frame_index, geo_index, flags, _) = try!(Struct::read_up(rws, |rws| { Ok((try!(rws.read_u32::<LittleEndian>()), try!(rws.read_u32::<LittleEndian>()), try!(rws.read_u32::<LittleEndian>()), try!(rws.read_u32::<LittleEndian>()))) // unused ...
/// The previosly read geometry and frames from the same clump object in the stream must /// be passed to this read procedure. pub fn read<R: ReadExt>(rws: &mut Stream<R>, framelist: &FrameList, geolist: &GeometryList) -> Result<Rc<A...
random_line_split
StackedUtils.ts
import { flatten, keyBy, sortNumeric, uniq } from "../../clientUtils/Util" import { StackedPointPositionType, StackedSeries } from "./StackedConstants" // This method shift up the Y Values of a Series with Points in place.
// Todo: use a lib? export const stackSeries = <PositionType extends StackedPointPositionType>( seriesArr: readonly StackedSeries<PositionType>[] ): readonly StackedSeries<PositionType>[] => { seriesArr.forEach((series, seriesIndex) => { if (!seriesIndex) return // The first series does not need to be s...
random_line_split
bin.rs
use super::{RmpWrite}; use crate::encode::{write_marker, ValueWriteError}; use crate::Marker; /// Encodes and attempts to write the most efficient binary array length implementation to the given /// write, returning the marker used. /// /// This function is useful when you want to get full control for writing the data...
{ write_bin_len(wr, data.len() as u32)?; wr.write_bytes(data) .map_err(ValueWriteError::InvalidDataWrite) }
identifier_body
bin.rs
use super::{RmpWrite}; use crate::encode::{write_marker, ValueWriteError}; use crate::Marker; /// Encodes and attempts to write the most efficient binary array length implementation to the given /// write, returning the marker used. /// /// This function is useful when you want to get full control for writing the data...
<W: RmpWrite>(wr: &mut W, len: u32) -> Result<Marker, ValueWriteError<W::Error>> { if len < 256 { write_marker(&mut *wr, Marker::Bin8)?; wr.write_data_u8(len as u8)?; Ok(Marker::Bin8) } else if len <= u16::MAX as u32 { write_marker(&mut *wr, Marker::Bin16)?; wr.write_data...
write_bin_len
identifier_name
bin.rs
use super::{RmpWrite}; use crate::encode::{write_marker, ValueWriteError}; use crate::Marker; /// Encodes and attempts to write the most efficient binary array length implementation to the given /// write, returning the marker used. /// /// This function is useful when you want to get full control for writing the data...
.map_err(ValueWriteError::InvalidDataWrite) }
wr.write_bytes(data)
random_line_split
qa_config.py
# # # Copyright (C) 2007, 2011 Google Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distri...
# Get node with least number of uses def compare(a, b): result = cmp(a.get('_count', 0), b.get('_count', 0)) if result == 0: result = cmp(a['primary'], b['primary']) return result nodes.sort(cmp=compare) node = nodes[0] node['_count'] = node.get('_count', 0) + 1 return node def Relea...
raise qa_error.OutOfNodesError("No nodes left")
conditional_block
qa_config.py
# # # Copyright (C) 2007, 2011 Google Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or
# WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, In...
# (at your option) any later version. # # This program is distributed in the hope that it will be useful, but
random_line_split
qa_config.py
# # # Copyright (C) 2007, 2011 Google Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distri...
def Validate(): if len(cfg['nodes']) < 1: raise qa_error.Error("Need at least one node") if len(cfg['instances']) < 1: raise qa_error.Error("Need at least one instance") if len(cfg["disk"]) != len(cfg["disk-growth"]): raise qa_error.Error("Config options 'disk' and 'disk-growth' must have" ...
"""Loads the passed configuration file. """ global cfg # pylint: disable-msg=W0603 cfg = serializer.LoadJson(utils.ReadFile(path)) Validate()
identifier_body
qa_config.py
# # # Copyright (C) 2007, 2011 Google Inc. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distri...
(path): """Loads the passed configuration file. """ global cfg # pylint: disable-msg=W0603 cfg = serializer.LoadJson(utils.ReadFile(path)) Validate() def Validate(): if len(cfg['nodes']) < 1: raise qa_error.Error("Need at least one node") if len(cfg['instances']) < 1: raise qa_error.Error("Ne...
Load
identifier_name
DataStoreService.ts
/** * Copyright © 2021 Rémi Pace. * This file is part of Abc-Map. * * Abc-Map is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later vers...
ath: string): string { const hasher = crypto.createHash('sha512'); return hasher.update(path).digest('hex'); } const datastorePath = this.config.datastore.path; function relativePath(manifestPath: string, filePath: string): string { const absolute = path.resolve(path.dirname(manifestPath)...
sh(p
identifier_name
DataStoreService.ts
/** * Copyright © 2021 Rémi Pace. * This file is part of Abc-Map. * * Abc-Map is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later vers...
const docs = artefacts.map(ArtefactMapper.dtoToDoc); return this.dao.saveAll(docs); } public async findById(id: string): Promise<AbcArtefact | undefined> { return this.dao.findById(id).then((res) => (res ? ArtefactMapper.docToDto(res) : undefined)); } public async list(limit: number, offset = 0): ...
return Promise.resolve(); }
conditional_block
DataStoreService.ts
/** * Copyright © 2021 Rémi Pace. * This file is part of Abc-Map. * * Abc-Map is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later vers...
const license = relativePath(manifest.path, manifest.artefact.license); const doc: ArtefactDocument = { _id: hash(artefactPath), name: artefact.name, description: artefact.description, keywords: artefact.keywords || [], link: artefact.link, license, p...
const artefact = manifest.artefact; const artefactPath = path.relative(datastorePath, manifest.path); const files = manifest.artefact.files.map((file) => relativePath(manifest.path, file));
random_line_split
DataStoreService.ts
/** * Copyright © 2021 Rémi Pace. * This file is part of Abc-Map. * * Abc-Map is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later vers...
public getRoot(): string { let result = this.config.datastore.path; if (!path.isAbsolute(result)) { result = path.resolve(result); } return result.replace(/\/$/, ''); } public async index(): Promise<void> { const root = this.getRoot(); logger.info(`Indexing datastore path: ${root}`)...
return this.dao.count(); }
identifier_body
setup.py
""" Setup for the API """ import api log = api.logger.use(__name__) def index_mongo(): """
Ensure the mongo collections are indexed. """ db = api.common.get_conn() log.debug("Ensuring mongo is indexed.") db.users.ensure_index("uid", unique=True, name="unique uid") db.users.ensure_index("username", unique=True, name="unique username") db.groups.ensure_index("gid", unique=True, ...
random_line_split
setup.py
""" Setup for the API """ import api log = api.logger.use(__name__) def index_mongo():
db.cache.ensure_index("args", name="args")
""" Ensure the mongo collections are indexed. """ db = api.common.get_conn() log.debug("Ensuring mongo is indexed.") db.users.ensure_index("uid", unique=True, name="unique uid") db.users.ensure_index("username", unique=True, name="unique username") db.groups.ensure_index("gid", unique=Tr...
identifier_body
setup.py
""" Setup for the API """ import api log = api.logger.use(__name__) def
(): """ Ensure the mongo collections are indexed. """ db = api.common.get_conn() log.debug("Ensuring mongo is indexed.") db.users.ensure_index("uid", unique=True, name="unique uid") db.users.ensure_index("username", unique=True, name="unique username") db.groups.ensure_index("gid", u...
index_mongo
identifier_name
enumvalues_8.js
[ ['local_680',['Local',['../namespacektt.html#a27feefe5217ccf7232f658cd88143f0fa509820290d57f333403f490dde7316f4',1,'ktt::Local()'],['../namespacektt.html#ac17be234b9c499fc808a40ba1fb17af5a509820290d57f333403f490dde7316f4',1,'ktt::Local()'],['../namespacektt.html#ac5bc0a65f097bc3326d6497c0f3877b0a509820290d57f333403...
var searchData=
random_line_split
GymEvent.py
# Standard Library Imports # 3rd Party Imports # Local Imports from PokeAlarm.Utils import get_gmaps_link, get_applemaps_link, \ get_waze_link, get_dist_as_str, get_team_emoji, get_ex_eligible_emoji from . import BaseEvent from PokeAlarm import Unknown class GymEvent(BaseEvent): """ Event representing the cha...
# Team Info 'old_team': locale.get_team_name(self.old_team_id), 'old_team_id': self.old_team_id, 'old_team_emoji': get_team_emoji(self.old_team_id), 'old_team_color': locale.get_team_color(self.old_team_id), 'old_team_leader': locale.get_leader_na...
""" Return a dict with all the DTS for this event. """ dts = self.custom_dts.copy() dts.update({ # Identification 'gym_id': self.gym_id, # Location 'lat': self.lat, 'lng': self.lng, 'lat_5': "{:.5f}".format(self.lat), '...
identifier_body
GymEvent.py
# Standard Library Imports # 3rd Party Imports # Local Imports from PokeAlarm.Utils import get_gmaps_link, get_applemaps_link, \ get_waze_link, get_dist_as_str, get_team_emoji, get_ex_eligible_emoji from . import BaseEvent from PokeAlarm import Unknown class GymEvent(BaseEvent): """ Event representing the cha...
return dts
# Guards 'slots_available': self.slots_available, 'guard_count': self.guard_count, })
random_line_split
GymEvent.py
# Standard Library Imports # 3rd Party Imports # Local Imports from PokeAlarm.Utils import get_gmaps_link, get_applemaps_link, \ get_waze_link, get_dist_as_str, get_team_emoji, get_ex_eligible_emoji from . import BaseEvent from PokeAlarm import Unknown class GymEvent(BaseEvent): """ Event representing the cha...
(self, data): """ Creates a new Gym Event based on the given dict. """ super(GymEvent, self).__init__('gym') check_for_none = BaseEvent.check_for_none # Identification self.gym_id = data.get('gym_id', data.get('id')) # Location self.lat = float(data['latitude'])...
__init__
identifier_name
ArtworkFilterMobileActionSheet.jest.tsx
import { mount } from "enzyme" import React from "react" import { ArtworkFilterContextProvider, initialArtworkFilterState, useArtworkFilterContext, } from "../ArtworkFilterContext" import { ArtworkFilterMobileActionSheet } from "../ArtworkFilterMobileActionSheet" import { ArtworkFilters } from "../ArtworkFilters"...
filters: { ...initialArtworkFilterState, page: 20, }, }) wrapper .find("Button") .findWhere(c => c.text() === "Clear all") .first() .simulate("click") expect(context.stagedFilters).toEqual({ ...initialArtworkFilterState, reset: true, }) ...
it("resets staged filters to defaults on `Reset` button click", () => { const wrapper = getWrapper({
random_line_split
FilteredLookupInDetailDialog.ts
namespace sharp.Serene.BasicSamples { /** * Basic order dialog with a category selection */ @Serenity.Decorators.registerClass() export class FilteredLookupInDetailDialog extends Serenity.EntityDialog<Northwind.OrderRow, any> { protected getFormKey() { return FilteredLookupInDetailForm....
{ return Northwind.OrderRow.nameProperty; } protected getService() { return Northwind.OrderService.baseUrl; } private form: FilteredLookupInDetailForm; constructor() { super(); this.form = new FilteredLookupInDetailForm(this.idPrefix); this.form.CategoryID...
tNameProperty()
identifier_name
FilteredLookupInDetailDialog.ts
namespace sharp.Serene.BasicSamples { /**
@Serenity.Decorators.registerClass() export class FilteredLookupInDetailDialog extends Serenity.EntityDialog<Northwind.OrderRow, any> { protected getFormKey() { return FilteredLookupInDetailForm.formKey; } protected getIdProperty() { return Northwind.OrderRow.idProperty; } protected get...
* Basic order dialog with a category selection */
random_line_split
FilteredLookupInDetailDialog.ts
namespace sharp.Serene.BasicSamples { /** * Basic order dialog with a category selection */ @Serenity.Decorators.registerClass() export class FilteredLookupInDetailDialog extends Serenity.EntityDialog<Northwind.OrderRow, any> { protected getFormKey() { return FilteredLookupInDetailForm....
protected getService() { return Northwind.OrderService.baseUrl; } private form: FilteredLookupInDetailForm; constructor() { super(); this.form = new FilteredLookupInDetailForm(this.idPrefix); this.form.CategoryID.change(e => { this.form.Detai...
return Northwind.OrderRow.nameProperty; }
identifier_body
setup.py
__author__ = 'jdaniel' import argparse from distutils.core import setup, Command import shutil from setuptools import find_packages import os import sys __version__ = "1.0.0" GAIA_DIR = os.getenv("HOME") + "/Gaia_v" + __version__ #GAIA_DIR = "/my/custom/install/location" + "/Gaia_" + __version__ class Color(object)...
alg_path = cur_dir + "/Algorithms/" alg_files = [f for f in os.listdir(alg_path) if os.path.isfile(alg_path + f)] for alg_file in alg_files: shutil.copyfile(cur_dir + "/Algorithms/" + alg_file, GAIA_DIR + "/Algorithms/" + alg_file) wrapped_alg_path = cur_dir + "/GaiaSolve/Algorithms/" wrapped_alg_files = [f for...
print Color.HEADER + "Creating directory " + GAIA_DIR + "/Algorithms" + Color.ENDC os.makedirs(GAIA_DIR + "/Algorithms")
conditional_block
setup.py
__author__ = 'jdaniel' import argparse from distutils.core import setup, Command import shutil from setuptools import find_packages import os import sys __version__ = "1.0.0" GAIA_DIR = os.getenv("HOME") + "/Gaia_v" + __version__ #GAIA_DIR = "/my/custom/install/location" + "/Gaia_" + __version__ class Color(object)...
shutil.copyfile(cur_dir + "/Algorithms/" + alg_file, GAIA_DIR + "/Algorithms/" + alg_file) wrapped_alg_path = cur_dir + "/GaiaSolve/Algorithms/" wrapped_alg_files = [f for f in os.listdir(wrapped_alg_path) if os.path.isfile(wrapped_alg_path + f)] for wrapped_alg_file in wrapped_alg_files: shutil.copyfile(wrap...
for alg_file in alg_files:
random_line_split
setup.py
__author__ = 'jdaniel' import argparse from distutils.core import setup, Command import shutil from setuptools import find_packages import os import sys __version__ = "1.0.0" GAIA_DIR = os.getenv("HOME") + "/Gaia_v" + __version__ #GAIA_DIR = "/my/custom/install/location" + "/Gaia_" + __version__ class
(object): """ Escape sequences for adding Color to console output. Note, that these do not write to file. """ HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' print Color.HEADER + "*****************************...
Color
identifier_name
setup.py
__author__ = 'jdaniel' import argparse from distutils.core import setup, Command import shutil from setuptools import find_packages import os import sys __version__ = "1.0.0" GAIA_DIR = os.getenv("HOME") + "/Gaia_v" + __version__ #GAIA_DIR = "/my/custom/install/location" + "/Gaia_" + __version__ class Color(object)...
print Color.HEADER + "************************************************" + Color.ENDC print Color.HEADER + " INSTALLING GAIA " + Color.ENDC print Color.HEADER + "************************************************" + Color.ENDC setup( name="Gaia", description="Parallel Multi-Obje...
""" Escape sequences for adding Color to console output. Note, that these do not write to file. """ HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m'
identifier_body
_authorized_relationship_for_all_trees.py
# ############################################################################ # OSIS stands for Open Student Information System. It's an application # designed to manage the core business of higher education institutions, # such as universities, faculties, institutes and professional schools. # The core business i...
ode_to_paste_to = self.tree.get_node(self.path) trees = self.tree_repository.search_from_children([node_to_paste_to.entity_id]) trees.append(self.tree) for tree in trees: for parent_node in tree.get_parents_node_with_respect_to_reference(node_to_paste_to): PasteAuthor...
identifier_body
_authorized_relationship_for_all_trees.py
# ############################################################################ # OSIS stands for Open Student Information System. It's an application # designed to manage the core business of higher education institutions, # such as universities, faculties, institutes and professional schools. # The core business i...
asteAuthorizedRelationshipValidator( tree, self.node_to_paste, parent_node, link_type=self.link_type ).validate()
conditional_block
_authorized_relationship_for_all_trees.py
# ############################################################################ # OSIS stands for Open Student Information System. It's an application # designed to manage the core business of higher education institutions, # such as universities, faculties, institutes and professional schools. # The core business i...
from base.ddd.utils.business_validator import BusinessValidator from base.models.enums.link_type import LinkTypes from program_management.ddd.business_types import * from program_management.ddd.validators._authorized_relationship import PasteAuthorizedRelationshipValidator class ValidateAuthorizedRelationshipForAllT...
# at the root of the source code of this program. If not, # see http://www.gnu.org/licenses/. # ############################################################################ from typing import Optional
random_line_split
_authorized_relationship_for_all_trees.py
# ############################################################################ # OSIS stands for Open Student Information System. It's an application # designed to manage the core business of higher education institutions, # such as universities, faculties, institutes and professional schools. # The core business i...
self, tree: 'ProgramTree', node_to_paste: 'Node', path: 'Path', tree_repository: 'ProgramTreeRepository', link_type: Optional[LinkTypes] ) -> None: super().__init__() self.tree = tree self.node_to_paste = node_to_paste ...
_init__(
identifier_name
pwm.rs
value: u32) { // note that for whatever reason, the match registers are fragmented // across two registers. They aren't even located next to each other // in memory match *self { Channel0PeriodReserved =>
, Channel1 => { reg::PWM1().mr[1].set_value(value); }, Channel2 => { reg::PWM1().mr[2].set_value(value); }, Channel3 => { reg::PWM1().mr[3].set_value(value); }, Channel4 => { reg::PWM1().mr2[0].set_value(value); }, Channel5 => { reg::PWM1().mr2[1].set_value(value); }, Channel6 => { r...
{ reg::PWM1().mr[0].set_value(value); }
conditional_block
pwm.rs
value: u32) { // note that for whatever reason, the match registers are fragmented // across two registers. They aren't even located next to each other // in memory match *self { Channel0PeriodReserved => { reg::PWM1().mr[0].set_value(value); }, Channel1 => { reg::PWM1().mr[1].set_value(va...
channel: channel, period_us: period_us, // 20ms is pretty common pulsewidth_us: 0, }; pwm.update_period(); pwm.update_pulsewidth(); pwm } /// Update the PWM Signal based on the current state fn update_period(&self) { // Put the counter into reset and disable the counter ...
{ PWM1Clock.enable(); PWM1Clock.set_divisor(PWM_CLOCK_DIVISOR); reg::PWM1().pr.set_value(0); // no prescaler // single PWM mode (reset TC on match 0 for Ch0) reg::PWM1().mcr.set_pwmmr0r(true); // enable PWM output on this channel match channel { Channel0PeriodReserved => { unsafe { ...
identifier_body
pwm.rs
value: u32) { // note that for whatever reason, the match registers are fragmented // across two registers. They aren't even located next to each other // in memory match *self { Channel0PeriodReserved => { reg::PWM1().mr[0].set_value(value); }, Channel1 => { reg::PWM1().mr[1].set_value(va...
(&self) -> u32 { self.pulsewidth_us } } /// LPC17xx PWM Register Definitions (User Manual: 24.6) mod reg { use volatile_cell::VolatileCell; use core::ops::Drop; ioregs!(PWM1@0x40018000 = { /// Interrupt Register. The IR can be written to clear /// interrupts. The IR can be read to identify which ...
get_pulsewidth_us
identifier_name
pwm.rs
, value: u32) { // note that for whatever reason, the match registers are fragmented // across two registers. They aren't even located next to each other // in memory match *self { Channel0PeriodReserved => { reg::PWM1().mr[0].set_value(value); }, Channel1 => { reg::PWM1().mr[1].set_value(v...
self.pulsewidth_us = pulsewidth_us; self.update_pulsewidth(); } fn get_pulsewidth_us(&self) -> u32 { self.pulsewidth_us } } /// LPC17xx PWM Register Definitions (User Manual: 24.6) mod reg { use volatile_cell::VolatileCell; use core::ops::Drop; ioregs!(PWM1@0x40018000 = { /// Interrupt R...
} fn set_pulsewidth_us(&mut self, pulsewidth_us: u32) {
random_line_split
cache.ts
/** * Copyright 2017-present Palantir Technologies, Inc. All rights reserved. * Licensed under the MIT License (the "License"); you may obtain a copy of the * license at https://github.com/palantir/typesettable/blob/develop/LICENSE */ export class Cache<T> { private cache: {[key: string]: T} = {}; private comp...
/** * Attempt to look up k in the cache, computing the result if it isn't * found. * * @param {string} k The key to look up in the cache. * @return {T} The value associated with k; the result of compute(k). */ public get(k: string): T { if (!this.cache.hasOwnProperty(k)) { this.cache[k] ...
random_line_split
cache.ts
/** * Copyright 2017-present Palantir Technologies, Inc. All rights reserved. * Licensed under the MIT License (the "License"); you may obtain a copy of the * license at https://github.com/palantir/typesettable/blob/develop/LICENSE */ export class Cache<T> { private cache: {[key: string]: T} = {}; private comp...
return this.cache[k]; } /** * Reset the cache empty. * * @return {Cache<T>} The calling Cache. */ public clear(): Cache<T> { this.cache = {}; return this; } }
{ this.cache[k] = this.compute(k); }
conditional_block
cache.ts
/** * Copyright 2017-present Palantir Technologies, Inc. All rights reserved. * Licensed under the MIT License (the "License"); you may obtain a copy of the * license at https://github.com/palantir/typesettable/blob/develop/LICENSE */ export class
<T> { private cache: {[key: string]: T} = {}; private compute: (k: string) => T; /** * @constructor * * @param {string} compute The function whose results will be cached. */ constructor(compute: (k: string) => T) { this.compute = compute; } /** * Attempt to look up k in the cache, compu...
Cache
identifier_name
cache.ts
/** * Copyright 2017-present Palantir Technologies, Inc. All rights reserved. * Licensed under the MIT License (the "License"); you may obtain a copy of the * license at https://github.com/palantir/typesettable/blob/develop/LICENSE */ export class Cache<T> { private cache: {[key: string]: T} = {}; private comp...
/** * Attempt to look up k in the cache, computing the result if it isn't * found. * * @param {string} k The key to look up in the cache. * @return {T} The value associated with k; the result of compute(k). */ public get(k: string): T { if (!this.cache.hasOwnProperty(k)) { this.cache[k...
{ this.compute = compute; }
identifier_body
models.py
import datetime import os from sqlalchemy import create_engine from sqlalchemy import MetaData, Table, Column, DateTime, Float, Integer, ForeignKey from sqlalchemy import between, func from sqlalchemy.sql import select from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy import Column, String, DateTime, Fl...
def is_authenticated(self): """Return True if the user is authenticated.""" return True def is_anonymous(self): """False, as anonymous users aren't supported.""" return False
"""Return the email address to satisfy Flask-Login's requirements.""" return self.user_id
identifier_body
models.py
import datetime import os from sqlalchemy import create_engine from sqlalchemy import MetaData, Table, Column, DateTime, Float, Integer, ForeignKey from sqlalchemy import between, func from sqlalchemy.sql import select from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy import Column, String, DateTime, Fl...
def get_public_meters(): """ Return a list of publicly viewable meters """ meters = Meter.query.filter(Meter.sharing == "public") for meter in meters: user_name = User.query.filter_by(user_id=meter.user_id).first().username yield (meter.meter_id, meter.meter_name, user_name) def visible...
user_name = User.query.filter_by(user_id=meter.user_id).first().username yield (meter.meter_id, meter.meter_name, user_name)
conditional_block
models.py
import datetime import os from sqlalchemy import create_engine from sqlalchemy import MetaData, Table, Column, DateTime, Float, Integer, ForeignKey from sqlalchemy import between, func from sqlalchemy.sql import select from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy import Column, String, DateTime, Fl...
(self): """True, as all users are active.""" return True def get_id(self): """Return the email address to satisfy Flask-Login's requirements.""" return self.user_id def is_authenticated(self): """Return True if the user is authenticated.""" return True def ...
is_active
identifier_name
models.py
import datetime import os from sqlalchemy import create_engine
from sqlalchemy import between, func from sqlalchemy.sql import select from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy import Column, String, DateTime, Float, Integer from werkzeug.security import generate_password_hash, check_password_hash from . import db, app class Meter(db.Model): """ A li...
from sqlalchemy import MetaData, Table, Column, DateTime, Float, Integer, ForeignKey
random_line_split
designs.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); /** * @author Alvaro Martinez de Miguel (Demi) [demipel8@gmail.com] */ var endpoint = 'designs'; exports.default = function (Request) { var options = { uri: '' + endpoint, method: 'POST' }; design.get = get; return { design:...
(id) { if (typeof id !== 'string') throw new Error('Id parameters missing or not a string'); var options = { uri: endpoint + '/' + id, method: 'GET' }; return Request(options); } };
get
identifier_name
designs.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); /**
*/ var endpoint = 'designs'; exports.default = function (Request) { var options = { uri: '' + endpoint, method: 'POST' }; design.get = get; return { design: design }; function design(colors, font) { if (!colors || typeof font !== 'string') throw new Error('Required parameters missing'); var bod...
* @author Alvaro Martinez de Miguel (Demi) [demipel8@gmail.com]
random_line_split
designs.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); /** * @author Alvaro Martinez de Miguel (Demi) [demipel8@gmail.com] */ var endpoint = 'designs'; exports.default = function (Request) { var options = { uri: '' + endpoint, method: 'POST' }; design.get = get; return { design:...
};
{ if (typeof id !== 'string') throw new Error('Id parameters missing or not a string'); var options = { uri: endpoint + '/' + id, method: 'GET' }; return Request(options); }
identifier_body
mod.rs
use std::thread::JoinHandle; use std::sync::mpsc::SyncSender; use search; use timer::Timer; use types::options; pub use self::mode::Mode; mod mode; pub struct State { pub search_state: Option<search::State>, pub search_guard: Option<JoinHandle<search::BestMove>>, pub search_tx: Option<SyncSender<search:...
(&mut self) { *self = State { mode: Mode::NewGame, ucinewgame_support: true, options: self.options.clone(), ..State::new() } } }
reset_new_game
identifier_name
mod.rs
use std::thread::JoinHandle; use std::sync::mpsc::SyncSender;
use types::options; pub use self::mode::Mode; mod mode; pub struct State { pub search_state: Option<search::State>, pub search_guard: Option<JoinHandle<search::BestMove>>, pub search_tx: Option<SyncSender<search::Cmd>>, pub mode: Mode, pub start_search_time: Option<u64>, pub start_move_time: ...
use search; use timer::Timer;
random_line_split
train.py
#! /usr/bin/python # -*- coding: utf-8 -*- import ast import pickle import numpy as np import os import socket import sys import importlib from datetime import datetime import theano as th import theanet.neuralnet as nn ################################ HELPER FUNCTIONS ############################ def share(data, d...
def write(self, data): self.stream.write(data) def forceflush(self): if self.use_file: self.stream.close() self.stream = open(self.name, 'a', 1) def __getattr__(self, attr): return getattr(self.stream, attr) ################################### MAIN CODE ###...
else: self.stream = sys.stdout
random_line_split
train.py
#! /usr/bin/python # -*- coding: utf-8 -*- import ast import pickle import numpy as np import os import socket import sys import importlib from datetime import datetime import theano as th import theanet.neuralnet as nn ################################ HELPER FUNCTIONS ############################ def share(data, d...
else: aux_err_name = 'P(MLE)' def get_test_indices(tot_samps, bth_samps=tr_prms['TEST_SAMP_SZ']): n_bths_each = int(bth_samps / batch_sz) n_bths_all = int(tot_samps / batch_sz) cur = 0 while True: yield [i % n_bths_all for i in range(cur, cur + n_bths_each)] cur = (cur + n_bths_ea...
aux_err_name = 'BitErr'
conditional_block
train.py
#! /usr/bin/python # -*- coding: utf-8 -*- import ast import pickle import numpy as np import os import socket import sys import importlib from datetime import datetime import theano as th import theanet.neuralnet as nn ################################ HELPER FUNCTIONS ############################ def share(data, d...
test_indices = get_test_indices(te_corpus_sz) trin_indices = get_test_indices(tr_corpus_sz) pickle_file_name = out_file_head + '_{:02.0f}.pkl' saved_file_name = None def do_test(): global saved_file_name test_err, aux_test_err = test_wrapper(test_fn_te(i) for i in ...
n_bths_each = int(bth_samps / batch_sz) n_bths_all = int(tot_samps / batch_sz) cur = 0 while True: yield [i % n_bths_all for i in range(cur, cur + n_bths_each)] cur = (cur + n_bths_each) % n_bths_all
identifier_body
train.py
#! /usr/bin/python # -*- coding: utf-8 -*- import ast import pickle import numpy as np import os import socket import sys import importlib from datetime import datetime import theano as th import theanet.neuralnet as nn ################################ HELPER FUNCTIONS ############################ def share(data, d...
(self): if self.use_file: self.stream.close() self.stream = open(self.name, 'a', 1) def __getattr__(self, attr): return getattr(self.stream, attr) ################################### MAIN CODE ################################ if len(sys.argv) < 3: print('Usage:', sys.a...
forceflush
identifier_name
main.js
var app = require('app'); // Module to control application life. var BrowserWindow = require('browser-window'); // Module to create native browser window. // Report crashes to our server. // require('crash-reporter').start(); // Keep a global reference of the window object, if you don't, the window will // be close...
}); // Specify flash path. // On Windows, it might be /path/to/pepflashplayer.dll // On Mac, /path/to/PepperFlashPlayer.plugin // On Linux, /path/to/libpepflashplayer.so // app.commandLine.appendSwitch('ppapi-flash-path', '/path/to/libpepflashplayer.so'); app.commandLine.appendSwitch('ppapi-flash-path', '/Application...
{ app.quit(); }
conditional_block
main.js
var app = require('app'); // Module to control application life. var BrowserWindow = require('browser-window'); // Module to create native browser window. // Report crashes to our server. // require('crash-reporter').start(); // Keep a global reference of the window object, if you don't, the window will // be close...
'web-preferences': { 'plugins': true } }); // and load the index.html of the app. mainWindow.loadUrl('file://' + __dirname + '/index.html'); // Emitted when the window is closed. mainWindow.on('closed', function() { // Dereference the window object mainWindow = null; }); // Displa...
'title': 'StreamShell', 'width': 800,
random_line_split
__init__.py
import os FILEPATH = os.path.join( os.path.abspath(os.path.dirname(os.path.dirname(__file__))), 'blns.txt') """Path to the file""" def naughty_strings(filepath=FILEPATH): """Get the list of naughty_strings. By default this will get the strings from the blns.txt file Code is a simple port of what i...
# above line leaves trailing newline characters; strip them out strings = [x.strip(u'\n') for x in strings] # remove empty-lines and comments strings = [x for x in strings if x and not x.startswith(u'#')] # insert empty string since all are being removed ...
random_line_split
__init__.py
import os FILEPATH = os.path.join( os.path.abspath(os.path.dirname(os.path.dirname(__file__))), 'blns.txt') """Path to the file""" def
(filepath=FILEPATH): """Get the list of naughty_strings. By default this will get the strings from the blns.txt file Code is a simple port of what is already in the /scripts directory :param filepath: Optional filepath the the blns.txt file :returns: The list of naughty strings """ strin...
naughty_strings
identifier_name
__init__.py
import os FILEPATH = os.path.join( os.path.abspath(os.path.dirname(os.path.dirname(__file__))), 'blns.txt') """Path to the file""" def naughty_strings(filepath=FILEPATH):
strings = [x for x in strings if x and not x.startswith(u'#')] # insert empty string since all are being removed strings.insert(0, u"") return strings
"""Get the list of naughty_strings. By default this will get the strings from the blns.txt file Code is a simple port of what is already in the /scripts directory :param filepath: Optional filepath the the blns.txt file :returns: The list of naughty strings """ strings = [] with open(fil...
identifier_body
Settings.py
import collections import json import os class Settings(collections.MutableMapping): def __init__(self, filename): self.filename = filename self.store = {} self.read() def read(self): if os.path.exists(self.filename): with open(self.filename, 'r') as f: ...
def write(self): with open(self.filename, 'w') as f: json.dump(self.store, f, sort_keys=True, indent=2, separators=(',', ': ')) def __setitem__(self, key, value): self.store[key] = value self.write() def __delitem__(self, key): del self.store[key] self...
self.write()
conditional_block
Settings.py
import collections import json import os class Settings(collections.MutableMapping): def __init__(self, filename): self.filename = filename self.store = {} self.read() def read(self): if os.path.exists(self.filename): with open(self.filename, 'r') as f: ...
def __len__(self): return len(self.store)
return iter(self.store)
identifier_body
Settings.py
import collections import json import os class Settings(collections.MutableMapping): def __init__(self, filename):
def read(self): if os.path.exists(self.filename): with open(self.filename, 'r') as f: self.store = json.load(f) else: self.write() def write(self): with open(self.filename, 'w') as f: json.dump(self.store, f, sort_keys=True, indent=2, ...
self.filename = filename self.store = {} self.read()
random_line_split
Settings.py
import collections import json import os class Settings(collections.MutableMapping): def __init__(self, filename): self.filename = filename self.store = {} self.read() def
(self): if os.path.exists(self.filename): with open(self.filename, 'r') as f: self.store = json.load(f) else: self.write() def write(self): with open(self.filename, 'w') as f: json.dump(self.store, f, sort_keys=True, indent=2, separators=(...
read
identifier_name
admin.py
from django.contrib import admin from django_revision.modeladmin_mixin import ModelAdminRevisionMixin from edc_base.modeladmin_mixins import ( ModelAdminNextUrlRedirectMixin, ModelAdminFormInstructionsMixin, ModelAdminFormAutoNumberMixin, ModelAdminReadOnlyMixin, ModelAdminAuditFieldsMixin) from .admin_si...
@admin.register(InnerContainer, site=edc_map_admin) class InnerContainerAdmin(ModelAdminMixin): form = InnerContainerForm list_per_page = 10 list_display = ('map_area', 'device_id', 'name', 'created', 'modified') list_filter = ( 'created', 'modified', 'map_area', 'c...
form = ContainerForm list_per_page = 10 list_display = ('name', 'map_area', 'created', 'modified') list_filter = ( 'created', 'modified', 'map_area', 'map_area', 'hostname_modified') search_fields = ('map_area', 'id')
identifier_body
admin.py
from django.contrib import admin from django_revision.modeladmin_mixin import ModelAdminRevisionMixin from edc_base.modeladmin_mixins import ( ModelAdminNextUrlRedirectMixin, ModelAdminFormInstructionsMixin, ModelAdminFormAutoNumberMixin, ModelAdminReadOnlyMixin, ModelAdminAuditFieldsMixin) from .admin_si...
(ModelAdminMixin): form = InnerContainerForm list_per_page = 10 list_display = ('map_area', 'device_id', 'name', 'created', 'modified') list_filter = ( 'created', 'modified', 'map_area', 'container__name', 'name', 'hostname_modified') search_fields...
InnerContainerAdmin
identifier_name
admin.py
from django.contrib import admin from django_revision.modeladmin_mixin import ModelAdminRevisionMixin from edc_base.modeladmin_mixins import ( ModelAdminNextUrlRedirectMixin, ModelAdminFormInstructionsMixin, ModelAdminFormAutoNumberMixin, ModelAdminReadOnlyMixin, ModelAdminAuditFieldsMixin) from .admin_si...
list_filter = ( 'created', 'modified', 'map_area', 'map_area', 'hostname_modified') search_fields = ('map_area', 'id') @admin.register(InnerContainer, site=edc_map_admin) class InnerContainerAdmin(ModelAdminMixin): form = InnerContainerForm list_per_page = 10...
list_display = ('name', 'map_area', 'created', 'modified')
random_line_split
settings.py
# Django settings for testautoslug project. import os PROJECT_ROOT = os.path.dirname(__file__) DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@domain.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', ...
# On Unix systems, a value of None will cause Django to use the same # timezone as the operating system. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18ngu...
# although not all choices may be available on all operating systems.
random_line_split
expandable.pipe.ts
* Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later versi...
/* * Lumeer: Modern Data Definition and Processing Platform *
random_line_split
expandable.pipe.ts
/* * Lumeer: Modern Data Definition and Processing Platform * * Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either ...
implements PipeTransform { public transform(row: TableConfigRow): boolean { return row && !row.expanded && row.linkedRows && row.linkedRows.length > 1; } }
ExpandablePipe
identifier_name
app.e2e-spec.ts
import { browser, element, by } from 'protractor'; import { resolve } from 'path'; const page = { configClearButton: element.all(by.css('app-config > div button')).get(2), configErrorButton: element.all(by.css('app-config > div button')).get(3), configErrorMessage: element(by.css('app-config p')), configGetBut...
expect(await page.logList.getText()).toContain(message); }; describe('Http Tests', () => { // It seems that currently Chrome/ChromeDriver fail to click a button that is just outside the // viewport (or maybe only partially inside the viewport) - at least in headless mode. // Possible solutions: // 1. Click t...
random_line_split
app.e2e-spec.ts
import { browser, element, by } from 'protractor'; import { resolve } from 'path'; const page = { configClearButton: element.all(by.css('app-config > div button')).get(2), configErrorButton: element.all(by.css('app-config > div button')).get(3), configErrorMessage: element(by.css('app-config p')), configGetBut...
}); beforeEach(() => browser.get('')); describe('Heroes', () => { it('retrieves the list of heroes at startup', async () => { expect(await page.heroesListItems.count()).toBe(4); expect(await page.heroesListItems.get(0).getText()).toContain('Dr Nice'); await checkLogForMessage('GET "api/he...
{ browser.driver.manage().window().setSize(1920, 1080); }
conditional_block
test_forms_field.py
#:coding=utf-8: from django.test import TestCase as DjangoTestCase from django.forms import Form from beproud.django.commons.forms import EmailField __all__ = ( 'EmailFieldTest', 'JSONFormFieldTest', 'JSONWidgetTest', ) class EmailTestForm(Form): email = EmailField(label="email") class EmailFiel...
def test_multi_email(self): form = EmailTestForm({"email": "aaa spam+extra@eggs.com email@email.com"}) self.assertFalse(form.is_valid()) def test_longtld(self): form = EmailTestForm({"email": "spam@eggs.engineer"}) self.assertTrue(form.is_valid()) def test_punycode(self):...
form = EmailTestForm({"email": "spam+extra@eggs.com"}) self.assertTrue(form.is_valid())
identifier_body
test_forms_field.py
#:coding=utf-8: from django.test import TestCase as DjangoTestCase from django.forms import Form from beproud.django.commons.forms import EmailField __all__ = ( 'EmailFieldTest', 'JSONFormFieldTest', 'JSONWidgetTest', ) class EmailTestForm(Form): email = EmailField(label="email")
form = EmailTestForm({"email": "spam@eggs.com"}) self.assertTrue(form.is_valid()) def test_keitai_email(self): form = EmailTestForm({"email": "-spam..eggs-@softbank.ne.jp"}) self.assertTrue(form.is_valid()) form = EmailTestForm({"email": ".*&$.-spam..!!eggs!!-.*.@ezweb.ne.j...
class EmailFieldTest(DjangoTestCase): def test_basic_email(self):
random_line_split
test_forms_field.py
#:coding=utf-8: from django.test import TestCase as DjangoTestCase from django.forms import Form from beproud.django.commons.forms import EmailField __all__ = ( 'EmailFieldTest', 'JSONFormFieldTest', 'JSONWidgetTest', ) class EmailTestForm(Form): email = EmailField(label="email") class EmailFiel...
(self): form = EmailTestForm({"email": "aaa spam+extra@eggs.com email@email.com"}) self.assertFalse(form.is_valid()) def test_longtld(self): form = EmailTestForm({"email": "spam@eggs.engineer"}) self.assertTrue(form.is_valid()) def test_punycode(self): form = EmailTestF...
test_multi_email
identifier_name
test_retry_and_refresh.py
from __future__ import unicode_literals from mock import ANY, call from boxsdk.config import API def test_automatic_refresh( box_client, mock_box_network, generic_successful_response, successful_token_response, unauthorized_response, ): mock_box_network.session.request.side...
# coding: utf-8
random_line_split
test_retry_and_refresh.py
# coding: utf-8 from __future__ import unicode_literals from mock import ANY, call from boxsdk.config import API def test_automatic_refresh( box_client, mock_box_network, generic_successful_response, successful_token_response, unauthorized_response, ):
'GET', '{0}/folders/0'.format(API.BASE_API_URL), headers=ANY, params=None, ), ]
mock_box_network.session.request.side_effect = [ unauthorized_response, successful_token_response, generic_successful_response, ] box_client.folder(0).get() assert mock_box_network.session.request.mock_calls == [ call( 'GET', '{0}/folders/0'.format(API...
identifier_body
test_retry_and_refresh.py
# coding: utf-8 from __future__ import unicode_literals from mock import ANY, call from boxsdk.config import API def
( box_client, mock_box_network, generic_successful_response, successful_token_response, unauthorized_response, ): mock_box_network.session.request.side_effect = [ unauthorized_response, successful_token_response, generic_successful_response, ] ...
test_automatic_refresh
identifier_name
ICommentListComponentProps.ts
import { Comment } from 'core/domain/comments' import {Map} from 'immutable' export interface ICommentListComponentProps { /** * Ad dictionary of comment * * @type {{[commentId: string]: Comment}} * @memberof ICommentListComponentProps */ comments: Map<string, Comment> /** * Comments editor s...
* * @type {boolean} * @memberof ICommentListComponentProps */ isPostOwner: boolean /** * The post identifier comments belong to */ postId: string /** * Comment on the post is disabled {false} or not {true} * * @type {boolean} * @memberof ICommentListComponentProps */ disable...
*/ commentsEditorStatus?: {[commentId: string]: boolean} /** * Current user is post the post owner {true} or not false
random_line_split
index.d.ts
import * as React from 'react' import { Box, Theme, Dimensions, MotionProps, ColorProps, SvgDefsAndFill } from '@nivo/core' import { InheritedColorConfig } from '@nivo/colors'
id: string | number value: number label: string | number } export type WaffleTooltipData = WaffleDatum & { color: string position: number row: number column: number groupIndex: number startAt: number endAt: number } export...
declare module '@nivo/waffle' { export type WaffleFillDirection = 'top' | 'right' | 'bottom' | 'left' export interface WaffleDatum {
random_line_split
index.d.ts
import * as React from 'react' import { Box, Theme, Dimensions, MotionProps, ColorProps, SvgDefsAndFill } from '@nivo/core' import { InheritedColorConfig } from '@nivo/colors' declare module '@nivo/waffle' { export type WaffleFillDirection = 'top' | 'right' | 'bottom' | 'left' export interface WaffleDatum { ...
extends React.Component<WaffleSvgProps & Dimensions> {} export class ResponsiveWaffle extends React.Component<WaffleSvgProps> {} export type WaffleHtmlProps = WaffleBaseProps & WaffleCommonProps & MotionProps export class WaffleHtml extends React.Component<WaffleHtmlProps & Dimensions> {} export clas...
Waffle
identifier_name
unpack.py
# jhbuild - a build script for GNOME 1.x and 2.x # Copyright (C) 2007 Alberto Ruiz <aruiz@gnome.org> # # unpack.py: helper functions for unpacking compressed packages # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the ...
ext = os.path.splitext(localfile)[-1] if ext == '.lzma' and has_command('lzcat') and has_command('tar'): buildscript.execute('lzcat -d "%s" | tar xf -' % localfile, cwd=target_directory) elif ext == '.xz' and has_command('xzcat') and has_command('tar'): buildscript.execute(...
final_target_directory = target_directory target_directory = tempfile.mkdtemp(dir=final_target_directory)
conditional_block
unpack.py
# jhbuild - a build script for GNOME 1.x and 2.x # Copyright (C) 2007 Alberto Ruiz <aruiz@gnome.org> # # unpack.py: helper functions for unpacking compressed packages # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the ...
def attr_to_file_perm(host, attr): if host == 0: if attr & 1: perm = 0444 else: perm = 0666 else: perm = attr perm &= 0x08FF0000 perm >>= 16 perm |= 0x00000100 return perm def attr_...
if host == 0: return False return attr == 0xA1ED0000
identifier_body
unpack.py
# jhbuild - a build script for GNOME 1.x and 2.x # Copyright (C) 2007 Alberto Ruiz <aruiz@gnome.org> # # unpack.py: helper functions for unpacking compressed packages # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the ...
(host, attr): if host == 0: return False return attr == 0xA1ED0000 def attr_to_file_perm(host, attr): if host == 0: if attr & 1: perm = 0444 else: perm = 0666 else: perm = attr perm &= 0x08FF...
attr_check_symlink
identifier_name
unpack.py
# jhbuild - a build script for GNOME 1.x and 2.x # Copyright (C) 2007 Alberto Ruiz <aruiz@gnome.org> # # unpack.py: helper functions for unpacking compressed packages # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the ...
pkg = tarfile.open(localfile, 'r|*') pkg.extractall(target_directory) pkg.close() def unpack_zip_file(localfile, target_directory): # Attributes are stored in ZIP files in a host-dependent way. # The zipinfo.create_system value describes the host OS. # Known values: # * 3 (UNIX) # ...
from jhbuild.utils.cmds import has_command from jhbuild.errors import CommandError def unpack_tar_file(localfile, target_directory):
random_line_split
hg.js
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow */ i...
isHGRepository, };
random_line_split
hg.js
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow */ i...
else { resolve( stdout .split('\n') .map(changedPath => path.resolve(cwd, changedPath)), ); } } else { reject(code + ': ' + stderr); } }); }); } function isHGRepository(cwd: string): Promise<?string> { return new Promise(r...
{ resolve([]); }
conditional_block
maps-vector.component.ts
import { Component, ElementRef, Input, OnChanges, OnDestroy, AfterViewInit } from '@angular/core'; import 'jqvmap'; @Component({ selector: 'lk-maps-vector', templateUrl: './maps-vector.component.html', styleUrls: [ './maps-vector.component.scss' ] }) export class MapsVectorComponent implements OnChanges, O...
() { this.buildMap(); } ngOnDestroy() { this.map = null; this.nativeElement.remove(); } private buildMap() { this.jqueryElement.find('.maps-vector-container').css({ height: this.height + 'px', width: '100%' }); this.jqueryElement.find('.maps-vector-container').vectorMap(thi...
ngAfterViewInit
identifier_name
maps-vector.component.ts
import { Component, ElementRef, Input, OnChanges, OnDestroy, AfterViewInit } from '@angular/core'; import 'jqvmap'; @Component({ selector: 'lk-maps-vector', templateUrl: './maps-vector.component.html', styleUrls: [ './maps-vector.component.scss' ] }) export class MapsVectorComponent implements OnChanges, O...
private buildMap() { this.jqueryElement.find('.maps-vector-container').css({ height: this.height + 'px', width: '100%' }); this.jqueryElement.find('.maps-vector-container').vectorMap(this.options); } }
{ this.map = null; this.nativeElement.remove(); }
identifier_body
maps-vector.component.ts
import { Component, ElementRef, Input, OnChanges, OnDestroy, AfterViewInit } from '@angular/core'; import 'jqvmap'; @Component({ selector: 'lk-maps-vector', templateUrl: './maps-vector.component.html', styleUrls: [ './maps-vector.component.scss' ]
private nativeElement: any; private jqueryElement: JQuery; private map: any; constructor(public elementRef: ElementRef) { this.nativeElement = elementRef.nativeElement; this.jqueryElement = $(this.nativeElement); } ngOnChanges() { this.buildMap(); } ngAfterViewInit() { this.buildMap(...
}) export class MapsVectorComponent implements OnChanges, OnDestroy, AfterViewInit { @Input() options: any; @Input() height: number;
random_line_split
epoch_fetch.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
(&self, hash: H256, engine: Arc<EthEngine>, checker: Arc<StateDependentProof<EthereumMachine>>) -> Self::Transition { self.request(request::Signal { hash: hash, engine: engine, proof_check: checker, }) } }
epoch_transition
identifier_name
epoch_fetch.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
// GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use std::sync::{Arc, Weak}; use ethcore::encoded; use ethcore::engines::{EthEngine, StateDependentProof}; use ethcore::header::Header...
// but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
random_line_split
epoch_fetch.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
} impl ChainDataFetcher for EpochFetch { type Error = &'static str; type Body = BoxFuture<encoded::Block, &'static str>; type Receipts = BoxFuture<Vec<Receipt>, &'static str>; type Transition = BoxFuture<Vec<u8>, &'static str>; fn block_body(&self, header: &Header) -> Self::Body { self.request(request::Body(...
{ Box::new(match self.sync.read().upgrade() { Some(sync) => { let on_demand = &self.on_demand; let maybe_future = sync.with_context(move |ctx| { on_demand.request(ctx, req).expect(ALL_VALID_BACKREFS) }); match maybe_future { Some(x) => Either::A(x.map_err(|_| "Request canceled")), N...
identifier_body
test.py
#!/usr/bin/env python ## path configuration caffe_root = './caffe' script_path = '.' caffe_model = script_path + '/soccer.prototxt' caffe_weight = script_path + '/snapshot/superlatefusion_iter_15000.caffemodel' caffe_inference_weight = script_path + '/superlatefusion_inference.caffemodel' ### start generate caffemode...
print net.params.keys() res = forward_once(net) layers = ['data', 'data2', 'seg-label', 'input', 'conv1', 'conv2', 'conv3', 'seg-score'] import os # debug output for name in layers: if not os.path.exists('debug/%s' % name): os.mkdir('debug/%s' % name) blob = net.blobs[name] for b in range(0,...
start_ind = 0 end_ind = len(net.layers) - 1 net._forward(start_ind, end_ind) return {out: net.blobs[out].data for out in net.outputs}
identifier_body
test.py
#!/usr/bin/env python ## path configuration caffe_root = './caffe' script_path = '.' caffe_model = script_path + '/soccer.prototxt' caffe_weight = script_path + '/snapshot/superlatefusion_iter_15000.caffemodel' caffe_inference_weight = script_path + '/superlatefusion_inference.caffemodel' ### start generate caffemode...
(net): start_ind = 0 end_ind = len(net.layers) - 1 net._forward(start_ind, end_ind) return {out: net.blobs[out].data for out in net.outputs} print net.params.keys() res = forward_once(net) layers = ['data', 'data2', 'seg-label', 'input', 'conv1', 'conv2', 'conv3', 'seg-score'] import os # debug o...
forward_once
identifier_name