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
hash.rs
// Copyright 2015, 2016 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 la...
() { assert_eq!(hash::H256::from(0), H256(hash::H256::from(0)).into()); } }
hash_into
identifier_name
read_until.rs
use futures_core::future::Future; use futures_core::ready; use futures_core::task::{Context, Poll}; use futures_io::AsyncBufRead; use std::io; use std::mem; use std::pin::Pin; /// Future for the [`read_until`](super::AsyncBufReadExt::read_until) method. #[derive(Debug)] #[must_use = "futures do nothing unless you `.aw...
else { buf.extend_from_slice(available); (false, available.len()) } }; reader.as_mut().consume(used); *read += used; if done || used == 0 { return Poll::Ready(Ok(mem::replace(read, 0))); } } } impl<R: AsyncBufRead + ?S...
{ buf.extend_from_slice(&available[..=i]); (true, i + 1) }
conditional_block
read_until.rs
use futures_core::future::Future; use futures_core::ready; use futures_core::task::{Context, Poll}; use futures_io::AsyncBufRead; use std::io; use std::mem; use std::pin::Pin; /// Future for the [`read_until`](super::AsyncBufReadExt::read_until) method. #[derive(Debug)] #[must_use = "futures do nothing unless you `.aw...
read: usize, } impl<R: ?Sized + Unpin> Unpin for ReadUntil<'_, R> {} impl<'a, R: AsyncBufRead + ?Sized + Unpin> ReadUntil<'a, R> { pub(super) fn new(reader: &'a mut R, byte: u8, buf: &'a mut Vec<u8>) -> Self { Self { reader, byte, buf, read: 0 } } } pub(super) fn read_until_internal<R: AsyncBufRe...
pub struct ReadUntil<'a, R: ?Sized> { reader: &'a mut R, byte: u8, buf: &'a mut Vec<u8>,
random_line_split
read_until.rs
use futures_core::future::Future; use futures_core::ready; use futures_core::task::{Context, Poll}; use futures_io::AsyncBufRead; use std::io; use std::mem; use std::pin::Pin; /// Future for the [`read_until`](super::AsyncBufReadExt::read_until) method. #[derive(Debug)] #[must_use = "futures do nothing unless you `.aw...
impl<R: AsyncBufRead + ?Sized + Unpin> Future for ReadUntil<'_, R> { type Output = io::Result<usize>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let Self { reader, byte, buf, read } = &mut *self; read_until_internal(Pin::new(reader), cx, *byte, buf, read) ...
{ loop { let (done, used) = { let available = ready!(reader.as_mut().poll_fill_buf(cx))?; if let Some(i) = memchr::memchr(byte, available) { buf.extend_from_slice(&available[..=i]); (true, i + 1) } else { buf.extend_from_sli...
identifier_body
read_until.rs
use futures_core::future::Future; use futures_core::ready; use futures_core::task::{Context, Poll}; use futures_io::AsyncBufRead; use std::io; use std::mem; use std::pin::Pin; /// Future for the [`read_until`](super::AsyncBufReadExt::read_until) method. #[derive(Debug)] #[must_use = "futures do nothing unless you `.aw...
<R: AsyncBufRead + ?Sized>( mut reader: Pin<&mut R>, cx: &mut Context<'_>, byte: u8, buf: &mut Vec<u8>, read: &mut usize, ) -> Poll<io::Result<usize>> { loop { let (done, used) = { let available = ready!(reader.as_mut().poll_fill_buf(cx))?; if let Some(i) = memchr...
read_until_internal
identifier_name
1417_Weighing_Problem.py
# 1417. Weighing Problem # Gives nn coins, each weighing 10g, but the weight of one coin is 11g. There # is now a balance that can be accurately weighed. Ask at least a few times # to be sure to find the 11g gold coin. # # Example # Given n = 3, return 1. # # Explanation: # Select two gold coins on the two ends of the...
# coins and place them on the two ends of the balance for the second # weighing. The gold coin at the heavy end is 11g gold coins. # class Solution: # """ # @param n: The number of coins # @return: The Minimum weighing times int worst case # """ # def minimumtimes(self, n): # # Write your ...
# # Explanation: # Four gold coins can be divided into two groups and placed on both ends of # the scale. According to the weighing results, select the two heavy gold
random_line_split
activity.rs
use event::{Event, React}; use failure::Error; use framework::context::{RenderContextView, State, UpdateContextView}; use framework::FrameworkError; use render::MetaRenderer; pub enum Transition<T, R> where T: State, R: MetaRenderer, { None, Push(BoxActivity<T, R>), Pop, Abort, } impl<T, R> Tr...
pub fn render<C>(&mut self, context: &mut C) -> Result<(), Error> where C: RenderContextView<R, State = T>, { self.peek_mut().map_or(Ok(()), |activity| { activity.render(context).map_err(|error| error.into()) }) } fn peek_mut(&mut self) -> Option<&mut Activity<T,...
random_line_split
activity.rs
use event::{Event, React}; use failure::Error; use framework::context::{RenderContextView, State, UpdateContextView}; use framework::FrameworkError; use render::MetaRenderer; pub enum Transition<T, R> where T: State, R: MetaRenderer, { None, Push(BoxActivity<T, R>), Pop, Abort, } impl<T, R> Tr...
(&mut self) {} fn stop(&mut self) {} } pub struct ActivityStack<T, R> where T: State, R: MetaRenderer, { stack: Vec<BoxActivity<T, R>>, } impl<T, R> ActivityStack<T, R> where T: State, R: MetaRenderer, { pub fn new(activity: BoxActivity<T, R>) -> Self { ActivityStack { ...
resume
identifier_name
activity.rs
use event::{Event, React}; use failure::Error; use framework::context::{RenderContextView, State, UpdateContextView}; use framework::FrameworkError; use render::MetaRenderer; pub enum Transition<T, R> where T: State, R: MetaRenderer, { None, Push(BoxActivity<T, R>), Pop, Abort, } impl<T, R> Tr...
fn stop(&mut self) {} } pub struct ActivityStack<T, R> where T: State, R: MetaRenderer, { stack: Vec<BoxActivity<T, R>>, } impl<T, R> ActivityStack<T, R> where T: State, R: MetaRenderer, { pub fn new(activity: BoxActivity<T, R>) -> Self { ActivityStack { stack: vec![ac...
{}
identifier_body
activity.rs
use event::{Event, React}; use failure::Error; use framework::context::{RenderContextView, State, UpdateContextView}; use framework::FrameworkError; use render::MetaRenderer; pub enum Transition<T, R> where T: State, R: MetaRenderer, { None, Push(BoxActivity<T, R>), Pop, Abort, } impl<T, R> Tr...
else { None } } fn push(&mut self, activity: BoxActivity<T, R>) { if let Some(activity) = self.peek_mut() { activity.suspend(); } self.stack.push(activity); } fn pop(&mut self) -> bool { self.stack .pop() ...
{ // Cannot use `map`. Some(activity.as_mut()) }
conditional_block
notify.rs
use std::sync::{Arc, Mutex}; use std::thread; use std::time::Instant; use crossbeam_channel::Sender; use dbus::ffidisp::stdintf::org_freedesktop_dbus::{Properties, PropertiesPropertiesChanged}; use dbus::ffidisp::{BusType, Connection}; use dbus::message::SignalArgs; use serde_derive::Deserialize; use crate::blocks::{...
for msg in c.incoming(1000) { if let Some(signal) = PropertiesPropertiesChanged::from_message(&msg) { let value = signal.changed_properties.get("paused").unwrap(); let status = &value.0.as_i64().unwrap(); ...
random_line_split
notify.rs
use std::sync::{Arc, Mutex}; use std::thread; use std::time::Instant; use crossbeam_channel::Sender; use dbus::ffidisp::stdintf::org_freedesktop_dbus::{Properties, PropertiesPropertiesChanged}; use dbus::ffidisp::{BusType, Connection}; use dbus::message::SignalArgs; use serde_derive::Deserialize; use crate::blocks::{...
(&self) -> Vec<&dyn I3BarWidget> { vec![&self.output] } fn click(&mut self, e: &I3BarEvent) -> Result<()> { if let MouseButton::Left = e.button { let c = Connection::get_private(BusType::Session) .block_error("notify", "Failed to establish D-Bus connection")?; ...
view
identifier_name
notify.rs
use std::sync::{Arc, Mutex}; use std::thread; use std::time::Instant; use crossbeam_channel::Sender; use dbus::ffidisp::stdintf::org_freedesktop_dbus::{Properties, PropertiesPropertiesChanged}; use dbus::ffidisp::{BusType, Connection}; use dbus::message::SignalArgs; use serde_derive::Deserialize; use crate::blocks::{...
else { p.set("org.dunstproject.cmd0", "paused", true) .block_error("notify", "Failed to query D-Bus")?; } // block will auto-update due to monitoring the bus } Ok(()) } }
{ p.set("org.dunstproject.cmd0", "paused", false) .block_error("notify", "Failed to query D-Bus")?; }
conditional_block
task-comm-4.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 ...
println!("{}", r); assert_eq!(sum, 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8); }
println!("{}", r); r = rx.recv(); sum += r;
random_line_split
task-comm-4.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 ...
() { let mut r: int = 0; let mut sum: int = 0; let (tx, rx) = channel(); tx.send(1); tx.send(2); tx.send(3); tx.send(4); r = rx.recv(); sum += r; println!("{}", r); r = rx.recv(); sum += r; println!("{}", r); r = rx.recv(); sum += r; println!("{}", r); ...
test00
identifier_name
task-comm-4.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 ...
tx.send(5); tx.send(6); tx.send(7); tx.send(8); r = rx.recv(); sum += r; println!("{}", r); r = rx.recv(); sum += r; println!("{}", r); r = rx.recv(); sum += r; println!("{}", r); r = rx.recv(); sum += r; println!("{}", r); assert_eq!(sum, 1 + 2 + 3 + ...
{ let mut r: int = 0; let mut sum: int = 0; let (tx, rx) = channel(); tx.send(1); tx.send(2); tx.send(3); tx.send(4); r = rx.recv(); sum += r; println!("{}", r); r = rx.recv(); sum += r; println!("{}", r); r = rx.recv(); sum += r; println!("{}", r); r ...
identifier_body
treeNode.ts
// Copyright (c) 2017 Uber Technologies, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or a...
(fn) { const stack = []; stack.push({ node: this, childIndex: 0 }); const paths = []; while (stack.length) { const { node, childIndex } = stack[stack.length - 1]; if (node.children.length >= childIndex + 1) { stack[stack.length - 1].childIndex++; stack.push({ ...
paths
identifier_name
treeNode.ts
// Copyright (c) 2017 Uber Technologies, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or a...
get size() { let i = 0; this.walk(() => i++); return i; } addChild(child) { this.children.push(child instanceof TreeNode ? child : new TreeNode(child)); return this; } find(search) { const searchFn = TreeNode.iterFunction(TreeNode.searchFunction(search))...
{ return this.children.reduce((depth, child) => Math.max(child.depth + 1, depth), 1); }
identifier_body
treeNode.ts
// Copyright (c) 2017 Uber Technologies, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or a...
stack.pop(); } } return paths; } }
{ const path = stack.map(item => item.node.value); fn(path); }
conditional_block
treeNode.ts
// Copyright (c) 2017 Uber Technologies, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or a...
} return (value, node) => (search instanceof TreeNode ? node === search : value === search); } constructor(value, children = []) { this.value = value; this.children = children; } get depth() { return this.children.reduce((depth, child) => Math.max(child.depth + 1, ...
} static searchFunction(search) { if (typeof search === 'function') { return search;
random_line_split
0083_add_default_theme.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.10 on 2018-03-24 19:13 from __future__ import unicode_literals from django.db import migrations def add_theme(apps, schema_editor): SessionTheme = apps.get_model('exams', 'SessionTheme') SessionTheme.objects.get_or_create(name="Ocean", ...
(migrations.Migration): dependencies = [ ('exams', '0082_session_theme'), ] operations = [ migrations.RunPython(add_theme, reverse_code=delete_theme) ]
Migration
identifier_name
0083_add_default_theme.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.10 on 2018-03-24 19:13 from __future__ import unicode_literals from django.db import migrations def add_theme(apps, schema_editor): SessionTheme = apps.get_model('exams', 'SessionTheme') SessionTheme.objects.get_or_create(name="Ocean", ...
class Migration(migrations.Migration): dependencies = [ ('exams', '0082_session_theme'), ] operations = [ migrations.RunPython(add_theme, reverse_code=delete_theme) ]
SessionTheme = apps.get_model('exams', 'SessionTheme') SessionTheme.objects.filter(name="Ocean").delete()
identifier_body
0083_add_default_theme.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.10 on 2018-03-24 19:13
from django.db import migrations def add_theme(apps, schema_editor): SessionTheme = apps.get_model('exams', 'SessionTheme') SessionTheme.objects.get_or_create(name="Ocean", defaults={"primary_background_color": "#FFF", "sec...
from __future__ import unicode_literals
random_line_split
_common.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ let mut out = io::stdout(); let x: f64 = text.parse().unwrap(); let f64_bytes: u64 = unsafe { transmute(x) }; let x: f32 = text.parse().unwrap(); let f32_bytes: u32 = unsafe { transmute(x) }; writeln!(&mut out, "{:016x} {:08x} {}", f64_bytes, f32_bytes, text).unwrap(); }
identifier_body
_common.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(text: &str) { let mut out = io::stdout(); let x: f64 = text.parse().unwrap(); let f64_bytes: u64 = unsafe { transmute(x) }; let x: f32 = text.parse().unwrap(); let f32_bytes: u32 = unsafe { transmute(x) }; writeln!(&mut out, "{:016x} {:08x} {}", f64_bytes, f32_bytes, text).unwrap(); }
validate
identifier_name
_common.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
use std::io; use std::io::prelude::*; use std::mem::transmute; // Nothing up my sleeve: Just (PI - 3) in base 16. #[allow(dead_code)] pub const SEED: [u32; 3] = [0x243f_6a88, 0x85a3_08d3, 0x1319_8a2e]; pub fn validate(text: &str) { let mut out = io::stdout(); let x: f64 = text.parse().unwrap(); let f64_by...
// except according to those terms.
random_line_split
test_agraph.py
"""Unit tests for PyGraphviz interface.""" import os import tempfile import pytest import pytest pygraphviz = pytest.importorskip('pygraphviz') from networkx.testing import assert_edges_equal, assert_nodes_equal, \ assert_graphs_equal import networkx as nx class TestAGraph(object): def build_graph(sel...
G.add_edge(2, 3, weight=8) nx.nx_agraph.view_pygraphviz(G, edgelabel='weight') def test_graph_with_reserved_keywords(self): # test attribute/keyword clash case for #1582 # node: n # edges: u,v G = nx.Graph() G = self.build_graph(G) G.nodes['E']['n'] =...
G = nx.Graph() G.add_edge(1, 2, weight=7)
random_line_split
test_agraph.py
"""Unit tests for PyGraphviz interface.""" import os import tempfile import pytest import pytest pygraphviz = pytest.importorskip('pygraphviz') from networkx.testing import assert_edges_equal, assert_nodes_equal, \ assert_graphs_equal import networkx as nx class TestAGraph(object): def build_graph(sel...
def test_multi_directed(self): self.agraph_checks(nx.MultiDiGraph()) def test_view_pygraphviz(self): G = nx.Graph() # "An empty graph cannot be drawn." pytest.raises(nx.NetworkXException, nx.nx_agraph.view_pygraphviz, G) G = nx.barbell_graph(4, 6) nx.nx_agraph.view_py...
self.agraph_checks(nx.MultiGraph())
identifier_body
test_agraph.py
"""Unit tests for PyGraphviz interface.""" import os import tempfile import pytest import pytest pygraphviz = pytest.importorskip('pygraphviz') from networkx.testing import assert_edges_equal, assert_nodes_equal, \ assert_graphs_equal import networkx as nx class TestAGraph(object): def build_graph(sel...
(self): G = nx.Graph() G.add_edge(1, 2, weight=7) G.add_edge(2, 3, weight=8) nx.nx_agraph.view_pygraphviz(G, edgelabel='weight') def test_graph_with_reserved_keywords(self): # test attribute/keyword clash case for #1582 # node: n # edges: u,v G = nx.G...
test_view_pygraphviz_edgelable
identifier_name
hostname.rs
extern crate getopts; extern crate libc; use getopts::{optflag, getopts, usage, OptGroup}; use libc::{c_char, c_int, size_t}; use std::io::stdio; use std::os; static HOSTNAME_MAX_LENGTH: uint = 256; extern { fn gethostname(name: *mut c_char, namelen: size_t) -> c_int; } fn main() { let exit_status = run(os:...
() -> Result<String, String> { let mut name = String::with_capacity(HOSTNAME_MAX_LENGTH).to_c_str(); let result = unsafe { gethostname(name.as_mut_ptr(), HOSTNAME_MAX_LENGTH as size_t) }; if result == 0 { Ok(name.to_string()) } else { Err("Failed to get hostname".to_string()) } } f...
get_hostname
identifier_name
hostname.rs
extern crate getopts; extern crate libc; use getopts::{optflag, getopts, usage, OptGroup}; use libc::{c_char, c_int, size_t}; use std::io::stdio; use std::os; static HOSTNAME_MAX_LENGTH: uint = 256; extern { fn gethostname(name: *mut c_char, namelen: size_t) -> c_int; } fn main() { let exit_status = run(os:...
fn run(args: Vec<String>) -> int { let program = &args[0]; let parameters = [ optflag("V", "version", "Print the version number and exit"), optflag("h", "help", "Print this help message") ]; let options = match getopts(args.tail(), parameters) { Ok(options) => options, ...
{ let instructions = format!("Usage: {} [options] [HOSTNAME]", program); usage(instructions.as_slice(), options) }
identifier_body
hostname.rs
extern crate getopts; extern crate libc; use getopts::{optflag, getopts, usage, OptGroup}; use libc::{c_char, c_int, size_t}; use std::io::stdio; use std::os; static HOSTNAME_MAX_LENGTH: uint = 256; extern { fn gethostname(name: *mut c_char, namelen: size_t) -> c_int;
os::set_exit_status(exit_status); } fn usage_message(program: &String, options: &[OptGroup]) -> String { let instructions = format!("Usage: {} [options] [HOSTNAME]", program); usage(instructions.as_slice(), options) } fn run(args: Vec<String>) -> int { let program = &args[0]; let parameters = [ ...
} fn main() { let exit_status = run(os::args());
random_line_split
lib.rs
//! If you want to render templates, see the [`Render`](trait.Render.html) //! trait. //! //! To customise the templating behavior, see the //! [`TemplateSupport`](trait.TemplateSupport.html) trait. #![deny(missing_docs)] #[macro_use] extern crate nickel; extern crate mustache; extern crate rustc_serialize; use rust...
/// /// This can be useful if you want to keep a clean directory structure /// without having to spread that knowledge across your handlers. /// /// See `examples/adjusted_path.rs` for example usage. fn adjust_path<'a>(&self, path: &'a Path) -> Cow<'a, Path> { Cow::Borrowed(path) } ...
None } /// Adjust the path of a template lookup before it gets compiled.
random_line_split
lib.rs
//! If you want to render templates, see the [`Render`](trait.Render.html) //! trait. //! //! To customise the templating behavior, see the //! [`TemplateSupport`](trait.TemplateSupport.html) trait. #![deny(missing_docs)] #[macro_use] extern crate nickel; extern crate mustache; extern crate rustc_serialize; use rust...
<'a>(&self, path: &'a Path) -> Cow<'a, Path> { Cow::Borrowed(path) } /// The default layout to use when rendering. /// /// See `examples/default_layout.rs` for example usage. fn default_layout(&self) -> Option<Cow<Path>> { None } } /// Handle template caching through a borrowed...
adjust_layout_path
identifier_name
lib.rs
//! If you want to render templates, see the [`Render`](trait.Render.html) //! trait. //! //! To customise the templating behavior, see the //! [`TemplateSupport`](trait.TemplateSupport.html) trait. #![deny(missing_docs)] #[macro_use] extern crate nickel; extern crate mustache; extern crate rustc_serialize; use rust...
} /// Handle template caching through a borrowed reference. pub trait TemplateCache { /// Handles a cache lookup for a given template. /// /// # Expected behavior /// ```not_rust /// if let Some(template) = cache.get(path) { /// return handle(template) /// } else { /// let temp...
{ None }
identifier_body
urls.py
from django.conf.urls.defaults import patterns, url urlpatterns = patterns( 'show.views', url(r'^radioshow/entrylist/$', 'radioshow_entryitem_list', name='radioshow_entryitem_list'), url(r'^showcontributor/list/(?P<slug>[\w-]+)/$', 'showcontributor_content_list', name='showcontributor_content_list'),
url(r'^showcontributor/content/(?P<slug>[\w-]+)/$', 'showcontributor_content_detail', name='showcontributor_content_detail'), url(r'^showcontributor/contact/(?P<slug>[\w-]+)/$', 'showcontributor_contact', name='showcontributor_contact'), )
url(r'^showcontributor/appearance/(?P<slug>[\w-]+)/$', 'showcontributor_appearance_list', name='showcontributor_appearance_list'), url(r'^showcontributor/(?P<slug>[\w-]+)/$', 'showcontributor_detail', name='showcontributor_detail'),
random_line_split
firebase-withdrawals.service.ts
import {Inject, Injectable} from '@angular/core'; import {Observable, of, throwError} from 'rxjs'; import {NotificationService} from '../notification.service'; import {WithdrawalFactory} from '../../model/withdrawal.factory'; import {User} from '../../model/user'; import {Withdrawal} from '../../model/withdrawal'; impo...
} )); return of(withdrawal); } saveNotation(withdrawal: Withdrawal, notes: BottleNoting) { logInfo('[firebase] ===> sauvegarde d\'une notation'); this.withdrawRootRef.child(withdrawal.id).update( {notation: notes}, err => { if (err) { this.notificationService.error...
this.notificationService.debugAlert('Withdrawal created ' + withdrawal.id); }
conditional_block
firebase-withdrawals.service.ts
import {Inject, Injectable} from '@angular/core'; import {Observable, of, throwError} from 'rxjs'; import {NotificationService} from '../notification.service'; import {WithdrawalFactory} from '../../model/withdrawal.factory'; import {User} from '../../model/user'; import {Withdrawal} from '../../model/withdrawal'; impo...
initialize(user: User) { let userRoot = user.user; this.WITHDRAW_ROOT = schema.USERS_FOLDER + '/' + userRoot + '/' + schema.WITHDRAW_FOLDER; this.withdrawRootRef = this.angularFirebase.database.ref(this.WITHDRAW_ROOT); } cleanup() { this.USER_ROOT = undefined; this.WITHDRAW_ROOT = undefine...
{ store.select(SharedQuery.getLoginUser).pipe( filter(user => user != null), take(1) ).subscribe( (user: User) => this.initialize(user) ); }
identifier_body
firebase-withdrawals.service.ts
import {Inject, Injectable} from '@angular/core'; import {Observable, of, throwError} from 'rxjs'; import {NotificationService} from '../notification.service'; import {WithdrawalFactory} from '../../model/withdrawal.factory'; import {User} from '../../model/user'; import {Withdrawal} from '../../model/withdrawal'; impo...
// chargement fetchAllWithdrawals(nb: number = 10): Observable<Withdrawal[]> { return this.angularFirebase .list<Withdrawal>(this.WITHDRAW_ROOT).snapshotChanges().pipe( throttleTime(this.config.throttleTime), map((changes: SnapshotAction<Withdrawal>[]) => { let ret = changes....
this.WITHDRAW_ROOT = undefined; }
random_line_split
firebase-withdrawals.service.ts
import {Inject, Injectable} from '@angular/core'; import {Observable, of, throwError} from 'rxjs'; import {NotificationService} from '../notification.service'; import {WithdrawalFactory} from '../../model/withdrawal.factory'; import {User} from '../../model/user'; import {Withdrawal} from '../../model/withdrawal'; impo...
thdrawal: Withdrawal): Observable<Withdrawal> { logInfo('[firebase] ===> sauvegarde d\'un retrait'); this.withdrawRootRef.push(tools.sanitizeBeforeSave(withdrawal), ( err => { if (err !== null) { throwError(err); } else { this.notificationService.debugAlert('Withdrawal ...
eWithdrawal(wi
identifier_name
depth_test.py
#!/usr/bin/python3 import numpy as np import cv2 from collections import deque from obstacle_detector.distance_calculator import spline_dist from obstacle_detector.perspective import inv_persp_new from obstacle_detector.perspective import regress_perspecive from obstacle_detector.depth_mapper import calculate_depth...
cap.release() out.release() cv2.destroyAllWindows() video_test('../../video/6.mp4', '../results/depth_map_out.avi')
cv2.imwrite('screen.png', img)
conditional_block
depth_test.py
#!/usr/bin/python3 import numpy as np import cv2 from collections import deque from obstacle_detector.distance_calculator import spline_dist from obstacle_detector.perspective import inv_persp_new from obstacle_detector.perspective import regress_perspecive from obstacle_detector.depth_mapper import calculate_depth...
video_test('../../video/6.mp4', '../results/depth_map_out.avi')
cv2.destroyAllWindows()
random_line_split
depth_test.py
#!/usr/bin/python3 import numpy as np import cv2 from collections import deque from obstacle_detector.distance_calculator import spline_dist from obstacle_detector.perspective import inv_persp_new from obstacle_detector.perspective import regress_perspecive from obstacle_detector.depth_mapper import calculate_depth...
ret, frame = cap.read() height, width, _ = frame.shape out_height, out_width, _ = img.shape fourcc = cv2.VideoWriter_fourcc(*'XVID') out = cv2.VideoWriter( output_video_path \ if output_video_path is not None \ else 'output.avi', fourcc, 15.0, (out_width...
cx = 595 cy = 303 roi_width = 25 roi_length = 90 cap = cv2.VideoCapture( input_video_path \ if input_video_path is not None \ else input('enter video path: ')) old_images = deque() original_frames = deque() ret, frame = cap.read() for i in range(15): ...
identifier_body
depth_test.py
#!/usr/bin/python3 import numpy as np import cv2 from collections import deque from obstacle_detector.distance_calculator import spline_dist from obstacle_detector.perspective import inv_persp_new from obstacle_detector.perspective import regress_perspecive from obstacle_detector.depth_mapper import calculate_depth...
(input_video_path=None, output_video_path=None): cx = 595 cy = 303 roi_width = 25 roi_length = 90 cap = cv2.VideoCapture( input_video_path \ if input_video_path is not None \ else input('enter video path: ')) old_images = deque() original_frames = deque() ...
video_test
identifier_name
results.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Apr 3 10:31:30 2018 @author: BallBlueMeercat """ import pickle import os.path import time def save(save_path, output_name, output): # Saving results to run directory. filename = output_name+'.p' filename = os.path.join(save_path, filen...
def relocate(filename, speed, firstderivs_key): filename = filename # Create directory to move files to. directory = './results_Bfactor/'+str(int(time.time()))+'_'+str(speed)+'_model_'+firstderivs_key if not os.path.exists(directory): os.makedirs(directory) # Add filename t...
load_path = os.path.join(save_path, filename) content = [] try: with open(load_path,'rb') as rfp: content = pickle.load(rfp) except: print("didnt't open",load_path) return content
identifier_body
results.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Apr 3 10:31:30 2018 @author: BallBlueMeercat """ import pickle import os.path import time def save(save_path, output_name, output): # Saving results to run directory. filename = output_name+'.p' filename = os.path.join(save_path, filen...
# Add filename to the new directory new_filename = os.path.join(directory, filename) os.rename(filename, new_filename)
os.makedirs(directory)
conditional_block
results.py
#!/usr/bin/env python3
""" Created on Tue Apr 3 10:31:30 2018 @author: BallBlueMeercat """ import pickle import os.path import time def save(save_path, output_name, output): # Saving results to run directory. filename = output_name+'.p' filename = os.path.join(save_path, filename) pickle.dump(output, open(filename...
# -*- coding: utf-8 -*-
random_line_split
results.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Apr 3 10:31:30 2018 @author: BallBlueMeercat """ import pickle import os.path import time def save(save_path, output_name, output): # Saving results to run directory. filename = output_name+'.p' filename = os.path.join(save_path, filen...
(filename, speed, firstderivs_key): filename = filename # Create directory to move files to. directory = './results_Bfactor/'+str(int(time.time()))+'_'+str(speed)+'_model_'+firstderivs_key if not os.path.exists(directory): os.makedirs(directory) # Add filename to the new direc...
relocate
identifier_name
setup.py
######## # Copyright (c) 2013 GigaSpaces Technologies Ltd. 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 #
# distributed under the License is distributed on an "AS IS" BASIS, # * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # * See the License for the specific language governing permissions and # * limitations under the License. __author__ = 'Ganesh' from setuptools import setup versi...
# Unless required by applicable law or agreed to in writing, software
random_line_split
bit.rs
use std::fmt; #[derive(Clone, Copy, PartialEq)] pub(crate) struct Pack { mask: usize, shift: u32, } impl Pack { /// Value is packed in the `width` least-significant bits. pub(crate) const fn least_significant(width: u32) -> Pack
/// Value is packed in the `width` more-significant bits. pub(crate) const fn then(&self, width: u32) -> Pack { let shift = pointer_width() - self.mask.leading_zeros(); let mask = mask_for(width) << shift; Pack { mask, shift } } /// Width, in bits, dedicated to storing the va...
{ let mask = mask_for(width); Pack { mask, shift: 0 } }
identifier_body
bit.rs
use std::fmt; #[derive(Clone, Copy, PartialEq)] pub(crate) struct Pack { mask: usize, shift: u32, } impl Pack { /// Value is packed in the `width` least-significant bits. pub(crate) const fn least_significant(width: u32) -> Pack { let mask = mask_for(width); Pack { mask, shift: 0 } ...
/// Unpacks a value using a mask & shift. pub(crate) const fn unpack(src: usize, mask: usize, shift: u32) -> usize { (src & mask) >> shift }
pub(crate) const fn mask_for(n: u32) -> usize { let shift = 1usize.wrapping_shl(n - 1); shift | (shift - 1) }
random_line_split
bit.rs
use std::fmt; #[derive(Clone, Copy, PartialEq)] pub(crate) struct Pack { mask: usize, shift: u32, } impl Pack { /// Value is packed in the `width` least-significant bits. pub(crate) const fn least_significant(width: u32) -> Pack { let mask = mask_for(width); Pack { mask, shift: 0 } ...
(&self, value: usize, base: usize) -> usize { self.pack(value & self.max_value(), base) } pub(crate) fn unpack(&self, src: usize) -> usize { unpack(src, self.mask, self.shift) } } impl fmt::Debug for Pack { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { write!( ...
pack_lossy
identifier_name
PieChart.tsx
/* Copyright (C) 2017 Cloudbase Solutions SRL This program 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 version. This program is distribute...
else if (this.props.onMouseLeave) { this.props.onMouseLeave() } } @autobind handleMouseLeave() { if (this.props.onMouseLeave) { this.props.onMouseLeave() } } drawChart() { const canvas = this.canvas if (!canvas) { return } canvas.style.width = `${this.props.siz...
{ onMouseOver(item, mouseX, mouseY) }
conditional_block
PieChart.tsx
/* Copyright (C) 2017 Cloudbase Solutions SRL This program 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 version. This program is distribute...
}} > <Canvas width={this.props.size * 2} height={this.props.size * 2} ref={ref => { this.canvas = ref }} /> <OuterShadow size={this.props.size} /> {this.props.holeStyle ? <InnerShadow size={this.props.holeStyle.radius} /> : null} </Wrapper>...
<Wrapper ref={(ref: HTMLElement) => { if (this.props.customRef) this.props.customRef(ref)
random_line_split
PieChart.tsx
/* Copyright (C) 2017 Cloudbase Solutions SRL This program 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 version. This program is distribute...
() { const canvas = this.canvas if (!canvas) { return } canvas.removeEventListener('mousemove', this.handleMouseMove) canvas.removeEventListener('mouseleave', this.handleMouseLeave) } @autobind handleMouseMove(evt: MouseEvent) { const canvas = this.canvas const onMouseOver = thi...
componentWillUnmount
identifier_name
PieChart.tsx
/* Copyright (C) 2017 Cloudbase Solutions SRL This program 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 version. This program is distribute...
let beginAngle = Math.PI let endAngle = Math.PI for (let i = 0; i < this.angles.length; i += 1) { beginAngle = endAngle endAngle += this.angles[i] ctx.beginPath() ctx.moveTo(halfSize, halfSize) ctx.arc(halfSize, halfSize, halfSize, beginAngle, endAngle) if (ctx.isPointI...
{ const canvas = this.canvas if (!canvas) { return null } const halfSize = this.props.size / 2 const ctx = canvas.getContext('2d') if (!ctx) { return null } const holeStyle = this.props.holeStyle if (holeStyle) { ctx.beginPath() ctx.moveTo(halfSize, halfSize)...
identifier_body
StudyCreationBody.ts
/** * quantimodo * We make it easy to retrieve and analyze normalized user data from a wide array of devices and applications. Check out our [docs and sdk's](https://github.com/QuantiModo/docs) or [contact us](https://help.quantimo.do). * * OpenAPI spec version: 5.8.112511 * * * NOTE: This class is auto generat...
*/ "studyTitle"?: string; /** * Options: individual, group, global */ "type": string; }
*/ "effectVariableName": string; /** * Title of your study (optional)
random_line_split
run.py
""" Exim SES Transport Entry Points """ # Copyright 2013, Jayson Vantuyl <jvantuyl@gmail.com> # # This file is part of exim_ses_transport. # # exim_ses_transport is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Fou...
SesSender().run()
identifier_body
run.py
""" Exim SES Transport Entry Points """ # Copyright 2013, Jayson Vantuyl <jvantuyl@gmail.com> # # This file is part of exim_ses_transport. # # exim_ses_transport is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Fou...
def main(): SesSender().run()
random_line_split
run.py
""" Exim SES Transport Entry Points """ # Copyright 2013, Jayson Vantuyl <jvantuyl@gmail.com> # # This file is part of exim_ses_transport. # # exim_ses_transport is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Fou...
(): SesSender().run()
main
identifier_name
task.service.ts
import {Task} from './task.model' import {Injectable} from 'angular2/core' import {Http, Response, Headers, RequestOptions} from 'angular2/http'; import {Observable} from "rxjs/Observable"; @Injectable() export class TaskService { constructor( private http: Http ) { } private _tasksUrl = 'api/...
(task: Task): Observable<Response> { return this.http.delete(`api/tasks/${task.id}`, this.defaultRequestOptions) .map(res => res) .catch(this.handleError) } private extractTasks(res: Response) { if (res.status < 200 || res.status >= 300) { throw new Error('Ba...
deleteTask
identifier_name
task.service.ts
import {Task} from './task.model' import {Injectable} from 'angular2/core' import {Http, Response, Headers, RequestOptions} from 'angular2/http'; import {Observable} from "rxjs/Observable"; @Injectable() export class TaskService { constructor( private http: Http ) { } private _tasksUrl = 'api/...
private extractTask(res: Response) { if (res.status < 200 || res.status >= 300) { throw new Error('Bad response status: ' + res.status); } let body = res.json(); return body || {}; } private handleError(error: any) { let errMsg = error.message || 'S...
{ if (res.status < 200 || res.status >= 300) { throw new Error('Bad response status: ' + res.status); } let body = res.json(); return body.tasks || {}; }
identifier_body
task.service.ts
import {Task} from './task.model' import {Injectable} from 'angular2/core' import {Http, Response, Headers, RequestOptions} from 'angular2/http'; import {Observable} from "rxjs/Observable"; @Injectable() export class TaskService { constructor( private http: Http ) { } private _tasksUrl = 'api/...
let body = JSON.stringify({ task }); return this.http.patch(`api/tasks/${task.id}`, body, this.defaultRequestOptions) .map(this.extractTask) .catch(this.handleError) } deleteTask(task: Task): Observable<Response> { return this.http.delete(`api/tasks/${task.id}`, ...
.catch(this.handleError); } updateTask(task: Task): Observable<Task> {
random_line_split
task.service.ts
import {Task} from './task.model' import {Injectable} from 'angular2/core' import {Http, Response, Headers, RequestOptions} from 'angular2/http'; import {Observable} from "rxjs/Observable"; @Injectable() export class TaskService { constructor( private http: Http ) { } private _tasksUrl = 'api/...
let body = res.json(); return body || {}; } private handleError(error: any) { let errMsg = error.message || 'Server error'; console.error(errMsg); return Observable.throw(errMsg); } }
{ throw new Error('Bad response status: ' + res.status); }
conditional_block
fmt.rs
use crate::clippy_project_root; use shell_escape::escape; use std::ffi::OsStr; use std::path::Path; use std::process::{self, Command}; use std::{fs, io}; use walkdir::WalkDir; #[derive(Debug)] pub enum CliError { CommandFailed(String, String), IoError(io::Error), RustfmtNotInstalled, WalkDirError(walkd...
{ let mut args = vec!["+nightly".as_ref(), path.as_os_str()]; if context.check { args.push("--check".as_ref()); } let success = exec(context, "rustfmt", std::env::current_dir()?, &args)?; if !success { eprintln!("rustfmt failed on {}", path.display()); } Ok(success) }
identifier_body
fmt.rs
use crate::clippy_project_root; use shell_escape::escape; use std::ffi::OsStr; use std::path::Path; use std::process::{self, Command}; use std::{fs, io}; use walkdir::WalkDir; #[derive(Debug)] pub enum CliError { CommandFailed(String, String), IoError(io::Error), RustfmtNotInstalled, WalkDirError(walkd...
let context = FmtContext { check, verbose }; let result = try_run(&context); let code = match result { Ok(true) => 0, Ok(false) => { eprintln!(); eprintln!("Formatting check failed."); eprintln!("Run `cargo dev fmt` to update formatting."); 1 ...
}
random_line_split
fmt.rs
use crate::clippy_project_root; use shell_escape::escape; use std::ffi::OsStr; use std::path::Path; use std::process::{self, Command}; use std::{fs, io}; use walkdir::WalkDir; #[derive(Debug)] pub enum
{ CommandFailed(String, String), IoError(io::Error), RustfmtNotInstalled, WalkDirError(walkdir::Error), RaSetupActive, } impl From<io::Error> for CliError { fn from(error: io::Error) -> Self { Self::IoError(error) } } impl From<walkdir::Error> for CliError { fn from(error: wal...
CliError
identifier_name
fmt.rs
use crate::clippy_project_root; use shell_escape::escape; use std::ffi::OsStr; use std::path::Path; use std::process::{self, Command}; use std::{fs, io}; use walkdir::WalkDir; #[derive(Debug)] pub enum CliError { CommandFailed(String, String), IoError(io::Error), RustfmtNotInstalled, WalkDirError(walkd...
Ok(success) }
{ eprintln!("rustfmt failed on {}", path.display()); }
conditional_block
world-articles.component.ts
import { Component, OnInit } from '@angular/core'; import { ArticleService } from './article.service'; import { Observable } from 'rxjs/Observable'; @Component({ template: `<div class="row category-page"> <main class="col-md-8"> <h2><strong [innerHTML]="articles?.main.headLine"></strong></h2> ...
() { this._articleService.getArticleCategory(this.id) .subscribe(articles => this.articles = articles); } }
ngOnInit
identifier_name
world-articles.component.ts
import { Component, OnInit } from '@angular/core'; import { ArticleService } from './article.service'; import { Observable } from 'rxjs/Observable'; @Component({ template: `<div class="row category-page"> <main class="col-md-8"> <h2><strong [innerHTML]="articles?.main.headLine"></strong></h2> ...
ngOnInit() { this._articleService.getArticleCategory(this.id) .subscribe(articles => this.articles = articles); } }
{ return this.articles.aside.fullStory.replace('<br>', `<div class="photo">[ PHOTO ]</div>`); }
identifier_body
world-articles.component.ts
import { Component, OnInit } from '@angular/core'; import { ArticleService } from './article.service'; import { Observable } from 'rxjs/Observable'; @Component({ template: `<div class="row category-page"> <main class="col-md-8"> <h2><strong [innerHTML]="articles?.main.headLine"></strong></h2> ...
items: any[]; switch = false; content = '<div class="photo">[ PHOTO ]<div>'; constructor(private _articleService: ArticleService) {} createRange(number: number){ this.items = []; for(var i = 0; i < number; i++){ this.items.push(i); } return this.items; } i...
export class WorldArticlesComponent { id: number = 1; articles: any;
random_line_split
world-articles.component.ts
import { Component, OnInit } from '@angular/core'; import { ArticleService } from './article.service'; import { Observable } from 'rxjs/Observable'; @Component({ template: `<div class="row category-page"> <main class="col-md-8"> <h2><strong [innerHTML]="articles?.main.headLine"></strong></h2> ...
return this.items; } insert(){ return this.articles.aside.fullStory.replace('<br>', `<div class="photo">[ PHOTO ]</div>`); } ngOnInit() { this._articleService.getArticleCategory(this.id) .subscribe(articles => this.articles = articles); } }
{ this.items.push(i); }
conditional_block
scgi.rs
extern crate collections; use std::io::{BufferedReader, TcpListener, Listener, Acceptor}; use std::io::net::ip::{SocketAddr}; use std::from_str::{from_str}; use std::to_str::{ToStr}; use std::str::from_utf8; use collections::hashmap::HashMap; pub type Headers = HashMap<~str, ~str>; pub type SCGIMessage = (Headers, ~[...
reader.read_until(58).map(|b| from_str::<uint>(from_utf8(b.init()).expect("Unable to parse headers' length")).expect("Unable to parse headers' length")).unwrap(); let mut headers_read = 0; let mut headers = HashMap::new(); loop { i...
// XXX: ohgodwhat let headers_length =
random_line_split
scgi.rs
extern crate collections; use std::io::{BufferedReader, TcpListener, Listener, Acceptor}; use std::io::net::ip::{SocketAddr}; use std::from_str::{from_str}; use std::to_str::{ToStr}; use std::str::from_utf8; use collections::hashmap::HashMap; pub type Headers = HashMap<~str, ~str>; pub type SCGIMessage = (Headers, ~[...
(addr: SocketAddr, handler: Sender<(Headers, ~[u8], Sender<SCGIMessage>)>) -> SCGIServer { SCGIServer { listen_address: addr, handler: handler } } pub fn start(&self) { let mut listener = match TcpListener::bind(self.listen_address) { Ok(listener) =>...
new
identifier_name
views.py
import ujson as json import pytz from datetime import datetime import requests from django.http import HttpResponse, Http404 from django.shortcuts import render def index(request): return render(request, 'timetable/index.html', {}) def query(request, term): ret = [] if len(term) > 1: r = reques...
sections.append( { "from": section["departure"]["location"]["name"], "from_platform": section["departure"]["platform"], "from_time": section["departure"]["departureTimestamp"], ...
name = "{} nach {}".format(section["journey"]["name"], section["arrival"]["location"]["name"])
conditional_block
views.py
import ujson as json import pytz from datetime import datetime import requests from django.http import HttpResponse, Http404 from django.shortcuts import render def index(request): return render(request, 'timetable/index.html', {}) def query(request, term): ret = [] if len(term) > 1: r = reques...
for con in data["connections"]: sections = [] name = "" for section in con["sections"]: if not name and section["journey"]: name = "{} nach {}".format(section["journey"]["name"], section["arrival"]["location"]["name"...
start = start.replace("$.$", "/") to = to.replace("$.$", "/") if start and to: tz = pytz.timezone('Europe/Zurich') dt = datetime.fromtimestamp(int(selected_time), tz=tz) params = { "from": start, "to": to, "time": str(dt.time())[:5], "dat...
identifier_body
views.py
import ujson as json import pytz from datetime import datetime import requests from django.http import HttpResponse, Http404 from django.shortcuts import render def index(request): return render(request, 'timetable/index.html', {}) def query(request, term): ret = [] if len(term) > 1: r = reques...
dt = datetime.fromtimestamp(int(selected_time), tz=tz) params = { "from": start, "to": to, "time": str(dt.time())[:5], "date": str(dt.date()), "isArrivalTime": departure, } r = requests.get("https://transport.opendata.ch/v1/con...
start = start.replace("$.$", "/") to = to.replace("$.$", "/") if start and to: tz = pytz.timezone('Europe/Zurich')
random_line_split
views.py
import ujson as json import pytz from datetime import datetime import requests from django.http import HttpResponse, Http404 from django.shortcuts import render def
(request): return render(request, 'timetable/index.html', {}) def query(request, term): ret = [] if len(term) > 1: r = requests.get( "https://transport.opendata.ch/v1/locations?query=" + term) data = r.json() if 'stations' in data: for match in data['station...
index
identifier_name
concordance-options.ts
import turbocolor from "turbocolor"; const fakeAnsiStyles: { [key: string]: { open: string; close: string } } = {}; for (const key in turbocolor.Styles) { fakeAnsiStyles[key] = { open: "", close: "", }; } function
( withColor: boolean, ansi: { [key: string]: { open: string; close: string } } ) { const prev = turbocolor.enabled; turbocolor.enabled = withColor; const theme = { boolean: ansi.yellow, circular: turbocolor.gray("[Circular]"), date: { invalid: turbocolor.red("invalid"), value: ansi.bl...
createTheme
identifier_name
concordance-options.ts
import turbocolor from "turbocolor"; const fakeAnsiStyles: { [key: string]: { open: string; close: string } } = {}; for (const key in turbocolor.Styles) { fakeAnsiStyles[key] = { open: "", close: "", }; } function createTheme( withColor: boolean, ansi: { [key: string]: { open: string; close: string } ...
function: { name: ansi.blue, stringTag: ansi.magenta, }, global: ansi.magenta, item: { after: turbocolor.gray(",") }, list: { openBracket: turbocolor.gray("["), closeBracket: turbocolor.gray("]"), }, mapEntry: { after: turbocolor.gray(",") }, maxDepth: turbocolor....
{ const prev = turbocolor.enabled; turbocolor.enabled = withColor; const theme = { boolean: ansi.yellow, circular: turbocolor.gray("[Circular]"), date: { invalid: turbocolor.red("invalid"), value: ansi.blue, }, diffGutters: { actual: turbocolor.red("+") + " ", expected...
identifier_body
concordance-options.ts
import turbocolor from "turbocolor"; const fakeAnsiStyles: { [key: string]: { open: string; close: string } } = {}; for (const key in turbocolor.Styles) { fakeAnsiStyles[key] = { open: "", close: "", }; } function createTheme( withColor: boolean, ansi: { [key: string]: { open: string; close: string } ...
date: { invalid: turbocolor.red("invalid"), value: ansi.blue, }, diffGutters: { actual: turbocolor.red("+") + " ", expected: turbocolor.green("-") + " ", padding: " ", }, error: { ctor: { open: ansi.gray.open + "(", close: ")" + ansi.gray.close }, name: ans...
turbocolor.enabled = withColor; const theme = { boolean: ansi.yellow, circular: turbocolor.gray("[Circular]"),
random_line_split
KeySpatialNavigationHandler.ts
import * as THREE from "three"; import { Observable, Subscription, } from "rxjs"; import { withLatestFrom, switchMap, } from "rxjs/operators"; import { Image } from "../../graph/Image"; import { Container } from "../../viewer/Container"; import { Navigator } from "../../viewer/Navigator"; import { Co...
else { const shifts: { [dir: number]: number } = {}; shifts[NavigationDirection.StepBackward] = Math.PI; shifts[NavigationDirection.StepForward] = 0; shifts[NavigationDirection.StepLeft] = Math.PI / 2; shifts[Navigatio...
{ this._moveDir(direction, edgeStatus); }
conditional_block
KeySpatialNavigationHandler.ts
import * as THREE from "three"; import { Observable, Subscription, } from "rxjs"; import { withLatestFrom, switchMap, } from "rxjs/operators"; import { Image } from "../../graph/Image"; import { Container } from "../../viewer/Container"; import { Navigator } from "../../viewer/Navigator"; import { Co...
protected _enable(): void { const spatialEdges$: Observable<NavigationEdgeStatus> = this._navigator.stateService.currentImage$.pipe( switchMap( (image: Image): Observable<NavigationEdgeStatus> => { return image.spatialEdges$; })); th...
{ super(component, container, navigator); this._spatial = spatial; }
identifier_body
KeySpatialNavigationHandler.ts
import * as THREE from "three"; import { Observable, Subscription, } from "rxjs"; import { withLatestFrom, switchMap, } from "rxjs/operators";
import { Component } from "../Component"; import { KeyboardConfiguration } from "../interfaces/KeyboardConfiguration"; import { HandlerBase } from "../util/HandlerBase"; import { Spatial } from "../../geo/Spatial"; import { NavigationEdge } from "../../graph/edge/interfaces/NavigationEdge"; import { NavigationEdgeStatu...
import { Image } from "../../graph/Image"; import { Container } from "../../viewer/Container"; import { Navigator } from "../../viewer/Navigator";
random_line_split
KeySpatialNavigationHandler.ts
import * as THREE from "three"; import { Observable, Subscription, } from "rxjs"; import { withLatestFrom, switchMap, } from "rxjs/operators"; import { Image } from "../../graph/Image"; import { Container } from "../../viewer/Container"; import { Navigator } from "../../viewer/Navigator"; import { Co...
(enable: boolean): KeyboardConfiguration { return { keySpatialNavigation: enable }; } private _moveDir(direction: NavigationDirection, edgeStatus: NavigationEdgeStatus): void { for (const edge of edgeStatus.edges) { if (edge.data.direction === direction) { this._move...
_getConfiguration
identifier_name
format_number.ts
; integerLen++) { digits.unshift(0); } // pad zeros for small numbers for (; integerLen < 0; integerLen++) { digits.unshift(0); } // extract decimals digits if (integerLen > 0) { decimals = digits.splice(integerLen, digits.length); } else { decimals = digits; ...
format: string, minusSign = '-'): ParsedNumberFormat { const p = { minInt: 1, minFrac: 0, maxFrac: 0, posPre: '', posSuf: '', negPre: '', negSuf: '', gSize: 0, lgSize: 0 }; const patternParts = format.split(PATTERN_SEP); const positive = patternParts[0]; const negative = p...
arseNumberFormat(
identifier_name
format_number.ts
(format, getLocaleNumberSymbol(locale, NumberSymbol.MinusSign)); return formatNumberToLocaleString( value, pattern, locale, NumberSymbol.Group, NumberSymbol.Decimal, digitsInfo); } interface ParsedNumberFormat { minInt: number; // the minimum number of digits required in the fraction part of the number m...
// Do not keep meaningless fractional trailing zeros (e.g. 15.52000 --> 15.52) if (digits[i] === 0 && i >= minLen) { digits.pop(); } else { dropTrailingZeros = false; } }
conditional_block
format_number.ts
if (!isFinite(value)) { formattedText = getLocaleNumberSymbol(locale, NumberSymbol.Infinity); } else { let parsedNumber = parseNumber(value); if (isPercent) { parsedNumber = toPercent(parsedNumber); } let minInt = pattern.minInt; let minFraction = pattern.minFrac; let maxFraction...
let formattedText = ''; let isZero = false;
random_line_split
format_number.ts
percentage according to locale rules. * * @param value The number to format. * @param locale A locale code for the locale format rules to use. * @param digitInfo Decimal representation options, specified by a string in the following format: * `{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}`. See `Deci...
if (minFrac > maxFrac) { throw new Error(`The minimum number of digits after fraction (${ minFrac}) is higher than the maximum (${maxFrac}).`); } let digits = parsedNumber.digits; let fractionLen = digits.length - parsedNumber.integerLen; const fractionSize = Math.min(Math.max(minFrac, fractionL...
identifier_body
hash-filenames.js
/* eslint-disable no-console */ import fs from 'fs' import crypto from 'crypto' import { resolve } from 'path' import { Dir, DEV_PATH } from '../config' import transformFiles from './transform-files' const dirs = [ resolve(Dir.dist, 'js'), resolve(Dir.dist, 'css'), ] const mapData = {} function transformer(...
str.splice(filename.lastIndexOf('.'), 0, `.${hash}`) const filenameHashed = str.join('') const newFilePath = resolve(destinationPath, filenameHashed) fs.renameSync(oldFilePath, newFilePath) mapData[filename] = filenameHashed console.log(`${filename} was renamed to ${filenameHashed}`) } func...
{ const oldFilePath = resolve(sourcePath, filename) const fileContents = fs.readFileSync(oldFilePath, 'utf-8') const hash = crypto.createHash('md5').update(fileContents).digest('hex') if (filename.indexOf(hash) !== -1) { console.log(`${filename} is unchanged.`) const str = filename.s...
identifier_body
hash-filenames.js
/* eslint-disable no-console */ import fs from 'fs' import crypto from 'crypto' import { resolve } from 'path' import { Dir, DEV_PATH } from '../config' import transformFiles from './transform-files' const dirs = [ resolve(Dir.dist, 'js'), resolve(Dir.dist, 'css'), ] const mapData = {} function transformer(...
const fileContents = fs.readFileSync(oldFilePath, 'utf-8') const hash = crypto.createHash('md5').update(fileContents).digest('hex') if (filename.indexOf(hash) !== -1) { console.log(`${filename} is unchanged.`) const str = filename.split('.') str.splice(str.indexOf(hash), 1) ...
const oldFilePath = resolve(sourcePath, filename)
random_line_split
hash-filenames.js
/* eslint-disable no-console */ import fs from 'fs' import crypto from 'crypto' import { resolve } from 'path' import { Dir, DEV_PATH } from '../config' import transformFiles from './transform-files' const dirs = [ resolve(Dir.dist, 'js'), resolve(Dir.dist, 'css'), ] const mapData = {} function
({ filename, sourcePath, destinationPath }) { const oldFilePath = resolve(sourcePath, filename) const fileContents = fs.readFileSync(oldFilePath, 'utf-8') const hash = crypto.createHash('md5').update(fileContents).digest('hex') if (filename.indexOf(hash) !== -1) { console.log(`${filename} is ...
transformer
identifier_name
hash-filenames.js
/* eslint-disable no-console */ import fs from 'fs' import crypto from 'crypto' import { resolve } from 'path' import { Dir, DEV_PATH } from '../config' import transformFiles from './transform-files' const dirs = [ resolve(Dir.dist, 'js'), resolve(Dir.dist, 'css'), ] const mapData = {} function transformer(...
const str = filename.split('') str.splice(filename.lastIndexOf('.'), 0, `.${hash}`) const filenameHashed = str.join('') const newFilePath = resolve(destinationPath, filenameHashed) fs.renameSync(oldFilePath, newFilePath) mapData[filename] = filenameHashed console.log(`${filename} was re...
{ console.log(`${filename} is unchanged.`) const str = filename.split('.') str.splice(str.indexOf(hash), 1) const baseFilename = str.join('.') mapData[baseFilename] = filename return }
conditional_block
issue-573-layout-test-failures.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct Outer { pub i: u8, } #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct AutoIdVector { pub ar: Outer, } #[test] fn bindgen_test_layout_Auto...
stringify!(ar) ) ); } #[test] fn __bindgen_test_layout_Outer_open0_int_close0_instantiation() { assert_eq!( ::std::mem::size_of::<Outer>(), 1usize, concat!("Size of template specialization: ", stringify!(Outer)) ); assert_eq!( ::std::mem::align_of::<O...
{ assert_eq!( ::std::mem::size_of::<AutoIdVector>(), 1usize, concat!("Size of: ", stringify!(AutoIdVector)) ); assert_eq!( ::std::mem::align_of::<AutoIdVector>(), 1usize, concat!("Alignment of ", stringify!(AutoIdVector)) ); assert_eq!( unsafe ...
identifier_body
issue-573-layout-test-failures.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct Outer { pub i: u8, } #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct AutoIdVector { pub ar: Outer, } #[test] fn bindgen_test_layout_Auto...
assert_eq!( ::std::mem::align_of::<AutoIdVector>(), 1usize, concat!("Alignment of ", stringify!(AutoIdVector)) ); assert_eq!( unsafe { &(*(::std::ptr::null::<AutoIdVector>())).ar as *const _ as usize }, 0usize, concat!( "Offset ...
1usize, concat!("Size of: ", stringify!(AutoIdVector)) );
random_line_split
issue-573-layout-test-failures.rs
#![allow( dead_code, non_snake_case, non_camel_case_types, non_upper_case_globals )] #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct Outer { pub i: u8, } #[repr(C)] #[derive(Debug, Default, Copy, Clone)] pub struct
{ pub ar: Outer, } #[test] fn bindgen_test_layout_AutoIdVector() { assert_eq!( ::std::mem::size_of::<AutoIdVector>(), 1usize, concat!("Size of: ", stringify!(AutoIdVector)) ); assert_eq!( ::std::mem::align_of::<AutoIdVector>(), 1usize, concat!("Alignment ...
AutoIdVector
identifier_name
actionCreators.js
import { ActionCreators } from 'redux-undo'; import * as types from './actionTypes'; export function setInitialState(options) { return { type: types.SET_INITIAL_STATE, options }; } export function changeDimensions(gridProperty, increment) { return { type: types.CHANGE_DIMENSIONS, gridProperty, ...
(cell) { return { type: types.CHANGE_HOVERED_CELL, cell }; } export function undo() { return ActionCreators.undo(); } export function redo() { return ActionCreators.redo(); }
changeHoveredCell
identifier_name
actionCreators.js
import { ActionCreators } from 'redux-undo'; import * as types from './actionTypes'; export function setInitialState(options) { return { type: types.SET_INITIAL_STATE, options }; } export function changeDimensions(gridProperty, increment) { return { type: types.CHANGE_DIMENSIONS, gridProperty, ...
export function createNewFrame() { return { type: types.CREATE_NEW_FRAME }; } export function deleteFrame(frameId) { return { type: types.DELETE_FRAME, frameId }; } export function duplicateFrame(frameId) { return { type: types.DUPLICATE_FRAME, frameId }; } export function setDurati...
{ return { type: types.REORDER_FRAME, selectedIndex, destinationIndex }; }
identifier_body
actionCreators.js
import { ActionCreators } from 'redux-undo'; import * as types from './actionTypes'; export function setInitialState(options) { return { type: types.SET_INITIAL_STATE, options }; } export function changeDimensions(gridProperty, increment) { return { type: types.CHANGE_DIMENSIONS, gridProperty, ...
export function duplicateFrame(frameId) { return { type: types.DUPLICATE_FRAME, frameId }; } export function setDuration(duration) { return { type: types.SET_DURATION, duration }; } export function changeFrameInterval(frameIndex, interval) { return { type: types.CHANGE_FRAME_INTERVAL, ...
random_line_split
hash.rs
// Copyright 2017 Pants project contributors (see CONTRIBUTORS.md). // Licensed under the Apache License, Version 2.0 (see LICENSE). use digest::{Digest, FixedOutput}; use sha2::Sha256; use std::error::Error; use std::fmt; use std::io::{self, Write}; use hex; const FINGERPRINT_SIZE: usize = 32; #[derive(Clone, Cop...
0xab, 0xab, 0xab, 0xab, 0xab, 0xab, 0xab, ]), Fingerprint([0xab; 32]) ); } #[test] fn from_hex_string() { assert_eq!( Fingerprint::from_hex_string( "0123456789abcdefFEDCBA98765432100000000000000000ffFFfFfFFfFfFFff", )...
0xab,
random_line_split