file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
lib.rs | //! A Rust library for allocation-limited computation of the Discrete Cosine Transform.
//!
//! 1D DCTs are allocation-free but 2D requires allocation.
//!
//! Features:
//!
//! * `simd`: use SIMD types to speed computation (2D DCT only)
//! * `cos-approx`: use a Taylor series approximation of cosine instead of the std... |
}
}
fn dct_1dx2(vec: Vec<f64x2>) -> Vec<f64x2> {
let mut out = Vec::with_capacity(vec.len());
for u in 0 .. vec.len() {
let mut z = valx2!(0.0);
for x in 0 .. vec.len() {
z += vec[x] * cos_approx(
PI * valx2!(
... | .map(f64x2)
.collect();
dct_1dx2(vals); | random_line_split |
lib.rs | //! A Rust library for allocation-limited computation of the Discrete Cosine Transform.
//!
//! 1D DCTs are allocation-free but 2D requires allocation.
//!
//! Features:
//!
//! * `simd`: use SIMD types to speed computation (2D DCT only)
//! * `cos-approx`: use a Taylor series approximation of cosine instead of the std... |
let test_values = [PI, PI / 2.0, PI / 4.0, 1.0, -1.0, 2.0 * PI, 3.0 * PI, 4.0 / 3.0 * PI];
for &x in &test_values {
test_cos_approx(x);
test_cos_approx(-x);
}
}
/*
#[cfg(feature = "simd")]
mod dct_simd {
use simdty::f64x2;
use std::f64::consts::{PI, SQRT_2};
macro_rules... | {
let approx = cos(x);
let cos = x.cos();
assert!(
approx.abs_sub(x.cos()) <= ERROR,
"Approximation cos({x}) = {approx} was outside a tolerance of {error}; control value: {cos}",
x = x, approx = approx, error = ERROR, cos = cos,
);
} | identifier_body |
lib.rs | //! A Rust library for allocation-limited computation of the Discrete Cosine Transform.
//!
//! 1D DCTs are allocation-free but 2D requires allocation.
//!
//! Features:
//!
//! * `simd`: use SIMD types to speed computation (2D DCT only)
//! * `cos-approx`: use a Taylor series approximation of cosine instead of the std... | else {
x.cos()
}
}
/// Perform a 2D DCT on a 1D-packed vector with a given rowstride.
///
/// E.g. a vector of length 9 with a rowstride of 3 will be processed as a 3x3 matrix.
///
/// Returns a vector of the same size packed in the same way.
pub fn dct_2d(packed_2d: &[f64], rowstride: usize) -> Vec<f64> ... | {
// Normalize to [0, pi] or else the Taylor series spits out very wrong results.
let x = (x.abs() + PI) % (2.0 * PI) - PI;
// Approximate the cosine of `val` using a 4-term Taylor series.
// Can be expanded for higher precision.
let x2 = x.powi(2);
let x4 = x.powi(4);
... | conditional_block |
lib.rs | //! A Rust library for allocation-limited computation of the Discrete Cosine Transform.
//!
//! 1D DCTs are allocation-free but 2D requires allocation.
//!
//! Features:
//!
//! * `simd`: use SIMD types to speed computation (2D DCT only)
//! * `cos-approx`: use a Taylor series approximation of cosine instead of the std... | (packed_2d: &[f64], rowstride: usize) -> Vec<f64> {
assert_eq!(packed_2d.len() % rowstride, 0);
let mut row_dct: Vec<f64> = packed_2d
.chunks(rowstride)
.flat_map(DCT1D::new)
.collect();
swap_rows_columns(&mut row_dct, rowstride);
let mut column_dct: Vec<f64> = packed_2d
... | dct_2d | identifier_name |
constants.rs | // The MIT License (MIT)
// Copyright © 2014-2018 Miguel Peláez <kernelfreeze@outlook.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction, including without limitation... | pub const VERSION_TEXT: &str = "Litecraft A1\nMinecraft 1.13.1"; | /// Debug version string | random_line_split |
stash.py | # coding: utf-8
import time
import sublime
from sublime_plugin import WindowCommand
from .util import noop
from .cmd import GitCmd
from .helpers import GitStashHelper, GitStatusHelper, GitErrorHelper
class GitStashWindowCmd(GitCmd, GitStashHelper, GitErrorHelper):
def pop_or_apply_from_panel(self, action):
... | if not stashes:
return sublime.error_message('No stashes. Use the Git: Stash command to stash changes')
callback = self.pop_or_apply_callback(repo, action, stashes)
panel = []
for name, title in stashes:
panel.append([title, "stash@{%s}" % name])
self.wi... | random_line_split | |
stash.py | # coding: utf-8
import time
import sublime
from sublime_plugin import WindowCommand
from .util import noop
from .cmd import GitCmd
from .helpers import GitStashHelper, GitStatusHelper, GitErrorHelper
class GitStashWindowCmd(GitCmd, GitStashHelper, GitErrorHelper):
def pop_or_apply_from_panel(self, action):
... |
snapshot = time.strftime("Snapshot at %Y-%m-%d %H:%M:%S")
self.git(['stash', 'save', '--', snapshot], cwd=repo)
self.git(['stash', 'apply', '-q', 'stash@{0}'], cwd=repo)
self.window.run_command('git_status', {'refresh_only': True})
class GitStashPopCommand(WindowCommand, GitStashWind... | return | conditional_block |
stash.py | # coding: utf-8
import time
import sublime
from sublime_plugin import WindowCommand
from .util import noop
from .cmd import GitCmd
from .helpers import GitStashHelper, GitStatusHelper, GitErrorHelper
class GitStashWindowCmd(GitCmd, GitStashHelper, GitErrorHelper):
def pop_or_apply_from_panel(self, action):
... |
class GitStashCommand(WindowCommand, GitCmd, GitStatusHelper):
"""
Documentation coming soon.
"""
def run(self, untracked=False):
repo = self.get_repo()
if not repo:
return
def on_done(title):
title = title.strip()
self.git(['stash', 'save... | def inner(choice):
if choice != -1:
name, _ = stashes[choice]
exit_code, stdout, stderr = self.git(['stash', action, '-q', 'stash@{%s}' % name], cwd=repo)
if exit_code != 0:
sublime.error_message(self.format_error_message(stderr))
... | identifier_body |
stash.py | # coding: utf-8
import time
import sublime
from sublime_plugin import WindowCommand
from .util import noop
from .cmd import GitCmd
from .helpers import GitStashHelper, GitStatusHelper, GitErrorHelper
class GitStashWindowCmd(GitCmd, GitStashHelper, GitErrorHelper):
def pop_or_apply_from_panel(self, action):
... | (self):
self.pop_or_apply_from_panel('apply')
| run | identifier_name |
MarchingCubes.d.ts | import {
BufferGeometry,
Material,
ImmediateRenderObject
} from '../../../src/Three';
export class | extends ImmediateRenderObject {
constructor( resolution: number, material: Material, enableUvs?: boolean, enableColors?: boolean );
enableUvs: boolean;
enableColors: boolean;
resolution: number;
// parameters
isolation: number;
// size of field, 32 is pushing it in Javascript :)
size: number;
size2: nu... | MarchingCubes | identifier_name |
MarchingCubes.d.ts | import {
BufferGeometry,
Material,
ImmediateRenderObject
} from '../../../src/Three';
export class MarchingCubes extends ImmediateRenderObject {
constructor( resolution: number, material: Material, enableUvs?: boolean, enableColors?: boolean );
enableUvs: boolean;
enableColors: boolean;
resolution: number;
... | export const triTable: Int32Array[]; | generateBufferGeometry(): BufferGeometry;
}
export const edgeTable: Int32Array[]; | random_line_split |
real_ints.rs | //! Defines basic operations defined under Real_Ints theory in SMTLIB2.
use std::fmt;
#[macro_use]
use crate::backends::backend::SMTNode;
#[derive(Clone, Debug)]
pub enum OpCodes {
Neg,
Sub,
Add,
Mul,
Div,
Lte,
Lt,
Gte,
Gt,
ToReal,
ToInt,
IsInt,
ConstInt(u64),
... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
let s = match *self {
OpCodes::Neg => "-".to_owned(),
OpCodes::Sub => "-".to_owned(),
OpCodes::Add => "+".to_owned(),
OpCodes::Mul => "*".to_owned(),
OpCodes::Div => "/".to_owned(),
OpCodes::... | fmt | identifier_name |
real_ints.rs | //! Defines basic operations defined under Real_Ints theory in SMTLIB2.
use std::fmt;
#[macro_use]
use crate::backends::backend::SMTNode;
#[derive(Clone, Debug)]
pub enum OpCodes { | Neg,
Sub,
Add,
Mul,
Div,
Lte,
Lt,
Gte,
Gt,
ToReal,
ToInt,
IsInt,
ConstInt(u64),
ConstReal(f64),
FreeVar(String),
}
impl fmt::Display for OpCodes {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let s = match *self {
OpCodes::Ne... | random_line_split | |
columns.py | #!/usr/bin/env python
"""
This module contains the :class:`Column` class, which defines a "vertical"
array of tabular data. Whereas :class:`.Row` instances are independent of their
parent :class:`.Table`, columns depend on knowledge of both their position in
the parent (column name, data type) as well as the rows that... | self._name = data['_name']
self._data_type = data['_data_type']
self._rows = data['_rows']
self._keys = data['_keys']
@property
def index(self):
"""
This column's index.
"""
return self._index
@property
def name(self):
"""
... | Restore pickled state.
This is necessary on Python2.7 when using :code:`__slots__`.
"""
self._index = data['_index'] | random_line_split |
columns.py | #!/usr/bin/env python
"""
This module contains the :class:`Column` class, which defines a "vertical"
array of tabular data. Whereas :class:`.Row` instances are independent of their
parent :class:`.Table`, columns depend on knowledge of both their position in
the parent (column name, data type) as well as the rows that... | (self):
"""
Get the values in this column with any null values removed and sorted.
"""
return sorted(self.values_without_nulls(), key=null_handler)
| values_without_nulls_sorted | identifier_name |
columns.py | #!/usr/bin/env python
"""
This module contains the :class:`Column` class, which defines a "vertical"
array of tabular data. Whereas :class:`.Row` instances are independent of their
parent :class:`.Table`, columns depend on knowledge of both their position in
the parent (column name, data type) as well as the rows that... |
def null_handler(k):
"""
Key method for sorting nulls correctly.
"""
if k is None:
return NullOrder()
return k
class Column(MappedSequence):
"""
Proxy access to column data. Instances of :class:`Column` should
not be constructed directly. They are created by :class:`.Table`... | xrange = range | conditional_block |
columns.py | #!/usr/bin/env python
"""
This module contains the :class:`Column` class, which defines a "vertical"
array of tabular data. Whereas :class:`.Row` instances are independent of their
parent :class:`.Table`, columns depend on knowledge of both their position in
the parent (column name, data type) as well as the rows that... |
@memoize
def values(self):
"""
Get the values in this column, as a tuple.
"""
return tuple(row[self._index] for row in self._rows)
@memoize
def values_distinct(self):
"""
Get the distinct values in this column, as a tuple.
"""
return tup... | """
This column's data type.
"""
return self._data_type | identifier_body |
http.rs | use crate::real_std::{
fmt, fs,
path::PathBuf,
pin::Pin,
sync::{Arc, Mutex},
};
use {
collect_mac::collect,
futures::{
future::{self, BoxFuture},
prelude::*,
ready,
task::{self, Poll},
},
http::{
header::{HeaderMap, HeaderName, HeaderValue},
... | (vm: &Thread) -> ArcType {
let r = generic::R::make_type(vm);
Type::app(
vm.find_type_info("std.http.types.HttpEffect")
.map(|alias| alias.into_type())
.unwrap_or_else(|_| Type::hole()),
collect![r],
)
}
}
pub type EffectHandler<T> = E... | make_type | identifier_name |
http.rs | use crate::real_std::{
fmt, fs,
path::PathBuf,
pin::Pin,
sync::{Arc, Mutex},
};
use {
collect_mac::collect,
futures::{
future::{self, BoxFuture},
prelude::*,
ready,
task::{self, Poll},
},
http::{
header::{HeaderMap, HeaderName, HeaderValue},
... | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "hyper::Body")
}
}
// Since `Body` implements `Userdata` gluon will automatically marshal the gluon representation
// into `&Body` argument
fn read_chunk(body: &Body) -> impl Future<Output = IO<Option<PushAsRef<Bytes, [u8]>>>> {
use f... | impl fmt::Debug for Body { | random_line_split |
http.rs | use crate::real_std::{
fmt, fs,
path::PathBuf,
pin::Pin,
sync::{Arc, Mutex},
};
use {
collect_mac::collect,
futures::{
future::{self, BoxFuture},
prelude::*,
ready,
task::{self, Poll},
},
http::{
header::{HeaderMap, HeaderName, HeaderValue},
... |
pub fn handle<E>(
&mut self,
method: http::Method,
uri: http::Uri,
body: impl Stream<Item = Result<Bytes, E>> + Send + 'static,
) -> BoxFuture<'static, crate::Result<hyper::Response<hyper::Body>>>
where
E: fmt::Display + Send + 'static,
{
let child_thread... |
// Retrieve the `handle` function from the http module which we use to evaluate values of type
// `EffectHandler Response`
let handle: Function<RootedThread, ListenFn> = thread
.get_global("std.http.handle")
.unwrap_or_else(|err| panic!("{}", err));
Self { handle... | identifier_body |
arc-rw-read-mode-shouldnt-escape.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 x = ~arc::RWArc::new(1);
let mut y = None;
do x.write_downgrade |write_mode| {
y = Some(x.downgrade(write_mode));
//~^ ERROR cannot infer an appropriate lifetime
}
y.unwrap();
// Adding this line causes a method unification failure instead
// do (&option::unwrap(y)).rea... | identifier_body | |
arc-rw-read-mode-shouldnt-escape.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
extern mod extra;
use extra::arc;
fn main() {
let x = ~arc::RWArc::new(1);
let mut y = None;
do x.write_downgrade |write_mode| {
y = S... | // 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 | random_line_split |
arc-rw-read-mode-shouldnt-escape.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 x = ~arc::RWArc::new(1);
let mut y = None;
do x.write_downgrade |write_mode| {
y = Some(x.downgrade(write_mode));
//~^ ERROR cannot infer an appropriate lifetime
}
y.unwrap();
// Adding this line causes a method unification failure instead
// do (&option::unwrap(y)).... | main | identifier_name |
uz-UZ.js | export default {
el: {
colorpicker: {
confirm: 'Qabul qilish',
clear: 'Tozalash'
},
datepicker: {
now: 'Hozir',
today: 'Bugun',
cancel: 'Bekor qilish',
clear: 'Tozalash',
confirm: 'Qabul qilish',
selectDate: 'Kunni tanlash',
selectTime: 'Soatni tanlash... | sat: 'Shan'
},
months: {
jan: 'Yan',
feb: 'Fev',
mar: 'Mar',
apr: 'Apr',
may: 'May',
jun: 'Iyun',
jul: 'Iyul',
aug: 'Avg',
sep: 'Sen',
oct: 'Okt',
nov: 'Noy',
dec: 'Dek'
}
},
select: {
... | fri: 'Jum', | random_line_split |
__init__.py | # coding=utf-8
"""
Profiler utility for python | from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
import os
import cProfile
from pstats import Stats
from cProfile import Profile
def start_profile... | Erik de Jonge
erik@a8.nl
license: gpl2
""" | random_line_split |
__init__.py | # coding=utf-8
"""
Profiler utility for python
Erik de Jonge
erik@a8.nl
license: gpl2
"""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
import os... | (pr, items=20, printstats=False, returnvalue=False):
"""
@type pr: str, unicode
@type items: int
@type printstats: bool
@type returnvalue: bool
@return: None
"""
p = Stats(pr)
if returnvalue is True:
return p.get_print_list([items])
p.strip_dirs()
console("total time... | end_profile | identifier_name |
__init__.py | # coding=utf-8
"""
Profiler utility for python
Erik de Jonge
erik@a8.nl
license: gpl2
"""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
import os... |
else:
if not os.path.exists("./" + sourcefile.replace(".py", ".png")):
print("\033[31mcannot find", sourcefile.replace(".py", ".png"), "\033[0m")
else:
os.system("open " + sourcefile.replace(".py", ".png"))
if os.remove("output.pstats"):
os.remov... | print("\033[31mgprof2dot error:\033[0m")
print("\033[33m", "pip install graphviz", "\033[0m")
print("\033[33m", "pip install gprof2dot", "\033[0m")
print("\033[33m", "gprof2dot is in path? (/usr/local/bin/gprof2dot)", "\033[0m") | conditional_block |
__init__.py | # coding=utf-8
"""
Profiler utility for python
Erik de Jonge
erik@a8.nl
license: gpl2
"""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
import os... | """
@type sourcefile: str, unicode
@return: None
"""
if 0 != os.system("python -m cProfile -o output.pstats ./" + sourcefile):
print("\033[31mprofile error:\033[0m")
print("\033[33m", "pip install graphviz", "\033[0m")
print("\033[33m", "pip install gprof2dot", "\033[0m")
el... | identifier_body | |
lib.rs | #![feature(if_let)]
use std::os;
use std::io::Command;
use std::io::process::InheritFd;
use std::default::Default;
/// Extra configuration to pass to gcc.
pub struct Config {
/// Directories where gcc will look for header files.
pub include_directories: Vec<Path>,
/// Additional definitions (`-DKEY` or `-... | os::getenv("AR").unwrap_or(if is_android {
format!("{}-ar", target)
} else {
"ar".to_string()
})
}
fn cflags() -> Vec<String> {
os::getenv("CFLAGS").unwrap_or(String::new())
.as_slice().words().map(|s| s.to_string())
.collect()
}
fn ios_flags(target: &str) -> Vec<String> ... |
fn ar(target: &str) -> String {
let is_android = target.find_str("android").is_some();
| random_line_split |
lib.rs | #![feature(if_let)]
use std::os;
use std::io::Command;
use std::io::process::InheritFd;
use std::default::Default;
/// Extra configuration to pass to gcc.
pub struct Config {
/// Directories where gcc will look for header files.
pub include_directories: Vec<Path>,
/// Additional definitions (`-DKEY` or `-... | else if is_android {
format!("{}-gcc", target)
} else {
"cc".to_string()
})
}
fn ar(target: &str) -> String {
let is_android = target.find_str("android").is_some();
os::getenv("AR").unwrap_or(if is_android {
format!("{}-ar", target)
} else {
"ar".to_string()
})... | {
"gcc".to_string()
} | conditional_block |
lib.rs | #![feature(if_let)]
use std::os;
use std::io::Command;
use std::io::process::InheritFd;
use std::default::Default;
/// Extra configuration to pass to gcc.
pub struct Config {
/// Directories where gcc will look for header files.
pub include_directories: Vec<Path>,
/// Additional definitions (`-DKEY` or `-... |
fn cflags() -> Vec<String> {
os::getenv("CFLAGS").unwrap_or(String::new())
.as_slice().words().map(|s| s.to_string())
.collect()
}
fn ios_flags(target: &str) -> Vec<String> {
let mut is_device_arch = false;
let mut res = Vec::new();
if target.starts_with("arm-") {
res.push("-ar... | {
let is_android = target.find_str("android").is_some();
os::getenv("AR").unwrap_or(if is_android {
format!("{}-ar", target)
} else {
"ar".to_string()
})
} | identifier_body |
lib.rs | #![feature(if_let)]
use std::os;
use std::io::Command;
use std::io::process::InheritFd;
use std::default::Default;
/// Extra configuration to pass to gcc.
pub struct | {
/// Directories where gcc will look for header files.
pub include_directories: Vec<Path>,
/// Additional definitions (`-DKEY` or `-DKEY=VALUE`).
pub definitions: Vec<(String, Option<String>)>,
/// Additional object files to link into the final archive
pub objects: Vec<Path>,
}
impl Default f... | Config | identifier_name |
converge.c.ts | import * as dts from 'dts-element';
import { max_curry_level } from './$curriedFunctions';
const min_input_count = 1;
const max_input_count = 3;
const min_function_count = 1;
const max_function_count = max_curry_level;
const generic_return = 'R';
const after_generics = [...new Array(max_function_count)].map(
(_, in... | (input_generic, index) => `
${parameters[index]}: ${input_generic}
`,
)
.join(',')}) => ${after_generic}
`,
)
.join(',')}]
): ${curried_function_name}<${[
...current_input_generics,
generic_return,
].join(',')}... | after_generic => `
(${current_input_generics
.map( | random_line_split |
converge.c.ts | import * as dts from 'dts-element';
import { max_curry_level } from './$curriedFunctions';
const min_input_count = 1;
const max_input_count = 3;
const min_function_count = 1;
const max_function_count = max_curry_level;
const generic_return = 'R';
const after_generics = [...new Array(max_function_count)].map(
(_, in... |
export default dts.parse(`
import {${import_curried_functions.join(',')}} from './$curriedFunctions';
import {List, Variadic} from './$types';
${declarations.join('\n')}
function $variadic<${generic_return}>(after: Variadic<${generic_return}>, fns: List<Variadic<any>>): Variadic<${generic_return}>;
`).members... | {
const curried_function_name = `CurriedFunction${input_count}`;
for (
let function_count = min_function_count;
function_count <= max_function_count;
function_count++
) {
const current_input_generics = input_generics.slice(0, input_count);
const current_after_generics = after_generics.slice(0,... | conditional_block |
resizeDialog.js | import React from 'react'
import { Map } from 'immutable'
import Path from 'path'
const ResizeDialogModal = ({ resizePath, resizeSize, initialSize, actions }) => {
const handleSettingInput = (e) => actions.updateModal('resizeSize', e.target.value)
const hideResizeDialog = (newSize) => actions.hideResizeDialog(Map({ ... |
}
const handleSettingKeyDown = (e) => {
if (e.keyCode === 13) {
handleSubmit()
e.preventDefault()
}
}
return (
<div className={'hosting-options-modal modal' + (resizePath ? '': ' hidden')}>
<form className="hosting-options modal-message" onSubmit="">
<div className="close-button" onClick={clos... | {
hideResizeDialog(resizeSize)
} | conditional_block |
resizeDialog.js | import React from 'react'
import { Map } from 'immutable'
import Path from 'path'
const ResizeDialogModal = ({ resizePath, resizeSize, initialSize, actions }) => {
const handleSettingInput = (e) => actions.updateModal('resizeSize', e.target.value)
const hideResizeDialog = (newSize) => actions.hideResizeDialog(Map({ ... | export default ResizeDialogModal | }
| random_line_split |
Ball.ts | /*
* This file is part of 6502.ts, an emulator for 6502 based systems built
* in Typescript
*
* Copyright (c) 2014 -- 2020 Christian Speckner and contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Sof... |
getPixel(colorIn: number): number {
return this.collision ? colorIn : this.color;
}
shuffleStatus(): void {
const oldEnabledOld = this._enabledOld;
this._enabledOld = this._enabledNew;
if (this._delaying && this._enabledOld !== oldEnabledOld) {
this._flushLin... | {
this.collision = this._rendering && this._renderCounter >= 0 && this._enabled ? 0 : this._collisionMask;
const starfieldEffect = this._moving && isReceivingHclock;
if (this._counter === 156) {
const starfieldDelta = (this._counter - this._lastMovementTick + 160) % 4;
... | identifier_body |
Ball.ts | /*
* This file is part of 6502.ts, an emulator for 6502 based systems built
* in Typescript
*
* Copyright (c) 2014 -- 2020 Christian Speckner and contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Sof... | (private _collisionMask: number, private _flushLineCache: () => void) {
this.reset();
}
reset(): void {
this.color = 0xffffffff;
this.collision = 0;
this._width = 1;
this._enabledOld = false;
this._enabledNew = false;
this._enabled = false;
this._... | constructor | identifier_name |
Ball.ts | /*
* This file is part of 6502.ts, an emulator for 6502 based systems built
* in Typescript
*
* Copyright (c) 2014 -- 2020 Christian Speckner and contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Sof... | }
vdelbl(value: number): void {
const oldDelaying = this._delaying;
this._delaying = (value & 0x01) > 0;
if (oldDelaying !== this._delaying) {
this._flushLineCache();
this._updateEnabled();
}
}
startMovement(): void {
this._moving = tru... | random_line_split | |
vperm2i128.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn vperm2i128_1() {
run_test(&Instruction { mnemonic: Mnemonic::VPERM2I128, operand1: Some(Direct(YMM0)), operand2: Some(D... | } | random_line_split | |
vperm2i128.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn | () {
run_test(&Instruction { mnemonic: Mnemonic::VPERM2I128, operand1: Some(Direct(YMM0)), operand2: Some(Direct(YMM5)), operand3: Some(Direct(YMM1)), operand4: Some(Literal8(22)), lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 85, 70, 193, 22], OperandSiz... | vperm2i128_1 | identifier_name |
vperm2i128.rs | use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode};
use ::RegType::*;
use ::instruction_def::*;
use ::Operand::*;
use ::Reg::*;
use ::RegScale::*;
fn vperm2i128_1() {
run_test(&Instruction { mnemonic: Mnemonic::VPERM2I128, operand1: Some(Direct(YMM0)), operand2: Some(D... |
fn vperm2i128_4() {
run_test(&Instruction { mnemonic: Mnemonic::VPERM2I128, operand1: Some(Direct(YMM5)), operand2: Some(Direct(YMM4)), operand3: Some(IndirectScaledDisplaced(RCX, Eight, 707114910, Some(OperandSize::Ymmword), None)), operand4: Some(Literal8(11)), lock: false, rounding_mode: None, merge_mode: None... | {
run_test(&Instruction { mnemonic: Mnemonic::VPERM2I128, operand1: Some(Direct(YMM4)), operand2: Some(Direct(YMM1)), operand3: Some(Direct(YMM5)), operand4: Some(Literal8(103)), lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[196, 227, 117, 70, 229, 103], OperandSiz... | identifier_body |
hdpmodel.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2012 Jonathan Esterhazy <jonathan.esterhazy at gmail.com>
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
#
# HDP inference code is adapted from the onlinehdp.py script by
# Chong Wang (chongw at cs.princeton.edu).
# http://www.c... |
def __getitem__(self, bow, eps=0.01):
is_corpus, corpus = utils.is_corpus(bow)
if is_corpus:
return self._apply(corpus)
gamma = self.inference([bow])[0]
topic_dist = gamma / sum(gamma) if sum(gamma) != 0 else []
return [(topicid, topicvalue) for topicid, topicval... | if self.lda_alpha is None or self.lda_beta is None:
raise RuntimeError("model must be trained to perform inference")
chunk = list(chunk)
if len(chunk) > 1:
logger.debug("performing inference on a chunk of %i documents" % len(chunk))
gamma = np.zeros((len(chunk), self.lda... | identifier_body |
hdpmodel.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2012 Jonathan Esterhazy <jonathan.esterhazy at gmail.com>
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
#
# HDP inference code is adapted from the onlinehdp.py script by
# Chong Wang (chongw at cs.princeton.edu).
# http://www.c... |
def update_finished(self, start_time, chunks_processed, docs_processed):
return (
# chunk limit reached
(self.max_chunks and chunks_processed == self.max_chunks) or
# time limit reached
(self.max_time and time.clock() - start_time > self.max_time) or
... | logger.info('PROGRESS: finished document %i of %i' %
(self.m_num_docs_processed, self.m_D)) | random_line_split |
hdpmodel.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2012 Jonathan Esterhazy <jonathan.esterhazy at gmail.com>
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
#
# HDP inference code is adapted from the onlinehdp.py script by
# Chong Wang (chongw at cs.princeton.edu).
# http://www.c... |
else:
topic = (k, topic_terms)
shown.append(topic)
return shown
def show_topic_terms(self, topic_data, topn):
return [(self.dictionary[wid], weight) for (weight, wid) in topic_data[:topn]]
def format_topic(self, topic_id, topic_terms):
if self.... | topic = self.format_topic(k, topic_terms)
# assuming we only output formatted topics
if log:
logger.info(topic) | conditional_block |
hdpmodel.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2012 Jonathan Esterhazy <jonathan.esterhazy at gmail.com>
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
#
# HDP inference code is adapted from the onlinehdp.py script by
# Chong Wang (chongw at cs.princeton.edu).
# http://www.c... | (self, chunk):
if self.lda_alpha is None or self.lda_beta is None:
raise RuntimeError("model must be trained to perform inference")
chunk = list(chunk)
if len(chunk) > 1:
logger.debug("performing inference on a chunk of %i documents" % len(chunk))
gamma = np.zero... | inference | identifier_name |
mod.rs | #![macro_escape]
use serialize::json::{Json, ParserError};
use url::Url;
use std::collections::HashMap;
use std::io::IoError;
use std::local_data::Ref;
#[cfg(not(teepee))]
pub use self::http::Client;
#[cfg(teepee)]
pub use self::teepee::Client;
mod http;
mod teepee;
macro_rules! params {
{$($key:expr: $val:ex... |
pub fn has_modhash() -> bool {
_modhash.get().is_some()
}
/// Map a std::io::IoError to a serialize::json::IoError (ParserError variant)
pub fn err_io_to_json_io(err: IoError) -> ParserError {
super::serialize::json::IoError(err.kind, err.desc)
}
#[test]
fn test_params() {
let params = params!{
... | {
_modhash.get()
} | identifier_body |
mod.rs | #![macro_escape]
use serialize::json::{Json, ParserError};
use url::Url;
use std::collections::HashMap;
use std::io::IoError;
use std::local_data::Ref;
#[cfg(not(teepee))]
pub use self::http::Client;
#[cfg(teepee)]
pub use self::teepee::Client;
mod http;
mod teepee;
macro_rules! params {
{$($key:expr: $val:ex... |
#[test]
fn test_params() {
let params = params!{
"hello": "goodbye",
"yes": "no",
};
drop(params);
} | random_line_split | |
mod.rs | #![macro_escape]
use serialize::json::{Json, ParserError};
use url::Url;
use std::collections::HashMap;
use std::io::IoError;
use std::local_data::Ref;
#[cfg(not(teepee))]
pub use self::http::Client;
#[cfg(teepee)]
pub use self::teepee::Client;
mod http;
mod teepee;
macro_rules! params {
{$($key:expr: $val:ex... | (modhash: &str) {
_modhash.replace(Some(modhash.into_string()));
}
pub fn get_modhash() -> Option<Ref<String>> {
_modhash.get()
}
pub fn has_modhash() -> bool {
_modhash.get().is_some()
}
/// Map a std::io::IoError to a serialize::json::IoError (ParserError variant)
pub fn err_io_to_json_io(err: IoError)... | set_modhash | identifier_name |
ListAssetTransactions.ts | import { ListAssetTransactions } from '../../src/Commands'
import { TestCommand } from '../test-helpers'
describe('/ListAssetTransactions', function() {
it(
'ListAssetTransactions() should return a properly configured JSON-RPC request',
function() {
const asset = 'asset'
const verbose = true
... | [asset, verbose, count, start, localOrdering],
)
},
)
}) | ListAssetTransactions, | random_line_split |
single_thread_calculator.rs | use crate::{MonteCarloPiCalculator, gen_random};
use std::sync::Arc;
pub struct SingleThreadCalculator {}
impl SingleThreadCalculator {
#[inline]
fn gen_randoms_static(n: usize) -> (Vec<f64>, Vec<f64>) {
let mut xs = vec![0.0; n];
let mut ys = vec![0.0; n];
for i in 0..n {
... |
}
return cnt;
}
}
impl MonteCarloPiCalculator for SingleThreadCalculator {
#[inline]
fn new(_n: usize) -> SingleThreadCalculator {
return SingleThreadCalculator {};
}
#[inline]
fn gen_randoms(&self, n: usize) -> (Vec<f64>, Vec<f64>) {
return SingleThreadCalcul... | {
cnt += 1;
} | conditional_block |
single_thread_calculator.rs | use crate::{MonteCarloPiCalculator, gen_random};
use std::sync::Arc;
pub struct SingleThreadCalculator {}
impl SingleThreadCalculator {
#[inline]
fn gen_randoms_static(n: usize) -> (Vec<f64>, Vec<f64>) {
let mut xs = vec![0.0; n];
let mut ys = vec![0.0; n];
for i in 0..n {
... | (xs: &Arc<Vec<f64>>, ys: &Arc<Vec<f64>>, n: usize) -> u64 {
let mut cnt = 0;
for i in 0..n {
if (xs[i] * xs[i] + ys[i] * ys[i] < 1.0) {
cnt += 1;
}
}
return cnt;
}
}
impl MonteCarloPiCalculator for SingleThreadCalculator {
#[inline]
f... | cal_static | identifier_name |
single_thread_calculator.rs | use crate::{MonteCarloPiCalculator, gen_random};
use std::sync::Arc;
pub struct SingleThreadCalculator {}
impl SingleThreadCalculator {
#[inline]
fn gen_randoms_static(n: usize) -> (Vec<f64>, Vec<f64>) {
let mut xs = vec![0.0; n];
let mut ys = vec![0.0; n];
for i in 0..n {
... |
}
impl MonteCarloPiCalculator for SingleThreadCalculator {
#[inline]
fn new(_n: usize) -> SingleThreadCalculator {
return SingleThreadCalculator {};
}
#[inline]
fn gen_randoms(&self, n: usize) -> (Vec<f64>, Vec<f64>) {
return SingleThreadCalculator::gen_randoms_static(n);
}
... | {
let mut cnt = 0;
for i in 0..n {
if (xs[i] * xs[i] + ys[i] * ys[i] < 1.0) {
cnt += 1;
}
}
return cnt;
} | identifier_body |
single_thread_calculator.rs | use crate::{MonteCarloPiCalculator, gen_random};
use std::sync::Arc;
pub struct SingleThreadCalculator {}
impl SingleThreadCalculator {
#[inline]
fn gen_randoms_static(n: usize) -> (Vec<f64>, Vec<f64>) {
let mut xs = vec![0.0; n];
let mut ys = vec![0.0; n];
for i in 0..n {
... | fn cal_static(xs: &Arc<Vec<f64>>, ys: &Arc<Vec<f64>>, n: usize) -> u64 {
let mut cnt = 0;
for i in 0..n {
if (xs[i] * xs[i] + ys[i] * ys[i] < 1.0) {
cnt += 1;
}
}
return cnt;
}
}
impl MonteCarloPiCalculator for SingleThreadCalculator {
... |
#[inline]
#[allow(unused_parens)] | random_line_split |
http_stream.py | #!/usr/bin/env python
#
# Update a redis server cache when an evenement is trigger
# in MySQL replication log
#
from pymysqlreplication import BinLogStreamReader
from pymysqlreplication.row_event import *
mysql_settings = {'host': '127.0.0.1', 'port': 3306, 'user': 'root', 'passwd': ''}
import json
import cherrypy
c... |
def index(self):
cherrypy.response.headers['Content-Type'] = 'text/plain'
def content():
for binlogevent in self.stream:
for row in binlogevent.rows:
if isinstance(binlogevent, DeleteRowsEvent):
yield json.dumps({
... | self.stream = BinLogStreamReader(connection_settings = mysql_settings,
only_events = [DeleteRowsEvent, WriteRowsEvent, UpdateRowsEvent], blocking = True, resume_stream = True) | identifier_body |
http_stream.py | #!/usr/bin/env python
#
# Update a redis server cache when an evenement is trigger
# in MySQL replication log
#
from pymysqlreplication import BinLogStreamReader
from pymysqlreplication.row_event import *
mysql_settings = {'host': '127.0.0.1', 'port': 3306, 'user': 'root', 'passwd': ''}
import json
import cherrypy
c... |
return content()
index.exposed = True
index._cp_config = {"response.stream": True}
cherrypy.quickstart(Streamer())
| yield json.dumps({
"action": "insert",
"id": row["values"]["id"],
"doc": row["values"]}) + "\n" | conditional_block |
http_stream.py | #!/usr/bin/env python
#
# Update a redis server cache when an evenement is trigger
# in MySQL replication log
#
from pymysqlreplication import BinLogStreamReader
from pymysqlreplication.row_event import *
mysql_settings = {'host': '127.0.0.1', 'port': 3306, 'user': 'root', 'passwd': ''}
import json
import cherrypy
c... | ():
for binlogevent in self.stream:
for row in binlogevent.rows:
if isinstance(binlogevent, DeleteRowsEvent):
yield json.dumps({
"action": "delete",
"id": row["values"]["id"]}) + "\n"
... | content | identifier_name |
http_stream.py | #!/usr/bin/env python
#
# Update a redis server cache when an evenement is trigger
# in MySQL replication log
#
from pymysqlreplication import BinLogStreamReader
from pymysqlreplication.row_event import *
mysql_settings = {'host': '127.0.0.1', 'port': 3306, 'user': 'root', 'passwd': ''}
import json
import cherrypy
c... |
cherrypy.quickstart(Streamer()) | index._cp_config = {"response.stream": True} | random_line_split |
old_clustering_example.py | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 03 10:16:52 2015
@author: Keine
"""
import sqlite3
cx = sqlite3.connect("../text2DB/get_data.db")
distxy = [([0.0] * 49) for i in range(49)]
cu = cx.cursor()
for i in range(49):
|
cx.close();
#print distxy[49-1][48-1]
#from scipy.cluster.hierarchy import linkage, dendrogram
#R = dendrogram(linkage(distxy, method='complete'))
#suptitle('Cluster Dendrogram', fontweight='bold', fontsize=14);
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial.distance import pdist, squareform
... | for j in range(49):
if i == j:
distxy[i-1][j-1] = 0.0
else:
print i
print j
sql = cu.execute("""select similarity from old_similarity where id1 = ? and id2 = ?""", (i,j))
if sql.fetchall() == []:
sim = 0
else:
... | conditional_block |
old_clustering_example.py | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 03 10:16:52 2015
@author: Keine
"""
import sqlite3
cx = sqlite3.connect("../text2DB/get_data.db")
distxy = [([0.0] * 49) for i in range(49)]
cu = cx.cursor()
for i in range(49):
for j in range(49):
if i == j:
distxy[i-1][j-1] = 0.0
else:
... |
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial.distance import pdist, squareform
from scipy.cluster.hierarchy import linkage, dendrogram
data_dist = pdist(distxy) # computing the distance
data_link = linkage(data_dist) # computing the linkage
dendrogram(data_link)
plt.xlabel('User_ID')
plt.ylabe... |
#suptitle('Cluster Dendrogram', fontweight='bold', fontsize=14); | random_line_split |
merge-collection.js | /*
* Copyright 2016-2017 Hewlett Packard Enterprise Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
define([
'backbone',
'find/app/util/merge-collection'
], function(Backbone, MergeCollection) {
'use strict';... | expect(this.mergeCollection.at(0)).toBe(this.dogCollection.at(0));
expect(this.mergeCollection.at(1)).toBe(this.catCollection.at(0));
});
it('preserves the collection reference on the models', function() {
expect(this.mergeCollection.findWhere({animal: Animal.CAT}).c... | expect(this.mergeCollection.length).toBe(2); | random_line_split |
sk.js | /*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2007 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* ... | DlgLnkURL : "URL",
DlgLnkAnchorSel : "Vybrať kotvu",
DlgLnkAnchorByName : "Podľa mena kotvy",
DlgLnkAnchorById : "Podľa Id objektu",
DlgLnkNoAnchors : "(V stránke nie je definovaná žiadna kotva)",
DlgLnkEMail : "E-Mailová adresa",
DlgLnkEMailSubject : "Predmet správy",
DlgLnkEMailBody : "Telo správy",
Dl... | DlgLnkTypeURL : "URL",
DlgLnkTypeAnchor : "Kotva v tejto stránke",
DlgLnkTypeEMail : "E-Mail",
DlgLnkProto : "Protokol",
DlgLnkProtoOther : "<iný>",
| random_line_split |
monitor_correction_test.py | # Copyright 2014 Diamond Light Source Ltd.
#
# 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 agreed t... | (self):
data_file = tu.get_test_data_path('mm.nxs')
process_file = tu.get_test_process_path('monitor_correction_test.nxs')
run_protected_plugin_runner(tu.set_options(data_file,
process_file=process_file))
if __name__ == "__main__":
unittest... | test_monitor_correction | identifier_name |
monitor_correction_test.py | # Copyright 2014 Diamond Light Source Ltd.
#
# 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 agreed t... |
if __name__ == "__main__":
unittest.main()
| def test_monitor_correction(self):
data_file = tu.get_test_data_path('mm.nxs')
process_file = tu.get_test_process_path('monitor_correction_test.nxs')
run_protected_plugin_runner(tu.set_options(data_file,
process_file=process_file)) | identifier_body |
monitor_correction_test.py | # Copyright 2014 Diamond Light Source Ltd.
#
# 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 agreed t... | from savu.test.travis.framework_tests.plugin_runner_test import \
run_protected_plugin_runner
class MonitorCorrectionTest(unittest.TestCase):
def test_monitor_correction(self):
data_file = tu.get_test_data_path('mm.nxs')
process_file = tu.get_test_process_path('monitor_correction_test.nxs')
... | random_line_split | |
monitor_correction_test.py | # Copyright 2014 Diamond Light Source Ltd.
#
# 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 agreed t... | unittest.main() | conditional_block | |
__init__.py | # -*- coding: utf-8 -*-
import re
import datetime
import logging
from urlparse import parse_qsl
from mamchecker.model import depth_1st, problemCtxObjs, keysOmit, table_entry, ctxkey
from mamchecker.hlp import datefmt, last
from mamchecker.util import PageBase |
def prepare(
qs # url query_string (after ?)
, skey # start key, filter is filled up with it.
# student key normally, but can be other, e.g. school, too.
# if a parent belongs to user then all children can be queried
, userkey
):
'''prepares the perameters for depth_1st
>... | from google.appengine.ext import ndb
| random_line_split |
__init__.py | # -*- coding: utf-8 -*-
import re
import datetime
import logging
from urlparse import parse_qsl
from mamchecker.model import depth_1st, problemCtxObjs, keysOmit, table_entry, ctxkey
from mamchecker.hlp import datefmt, last
from mamchecker.util import PageBase
from google.appengine.ext import ndb
def prepare(
... | (x):
'''convert to GAE filters from
lst is ["<field><operator><value>",...]
~ -> =
q = query_string
age fields: H = hours, S = seconds, M = minutes, d = days
'''
AGES = {'d': 'days', 'H': 'hours', 'M': 'minutes', 'S': 'seconds'}
ABBR = {'q': 'query_string... | filters | identifier_name |
__init__.py | # -*- coding: utf-8 -*-
import re
import datetime
import logging
from urlparse import parse_qsl
from mamchecker.model import depth_1st, problemCtxObjs, keysOmit, table_entry, ctxkey
from mamchecker.hlp import datefmt, last
from mamchecker.util import PageBase
from google.appengine.ext import ndb
def prepare(
... |
else:
return qqf, [], O, False, userkey
class Page(PageBase):
def __init__(self, _request):
super(self.__class__, self).__init__(_request)
self.table = lambda: depth_1st(
*
prepare(
self.request.query_string,
self.request.studen... | return qqf, keys, O, True | conditional_block |
__init__.py | # -*- coding: utf-8 -*-
import re
import datetime
import logging
from urlparse import parse_qsl
from mamchecker.model import depth_1st, problemCtxObjs, keysOmit, table_entry, ctxkey
from mamchecker.hlp import datefmt, last
from mamchecker.util import PageBase
from google.appengine.ext import ndb
def prepare(
... |
#qs = ''
O = problemCtxObjs
# q=query, qq=*->[], qqf=filter->gae filter (name,op,value)
q = filter(None, [k.strip() for k, v in parse_qsl(qs, True)])
qq = [[] if x == '*' else x for x in q]
qqf = [filters() if filters(x) else x for x in qq]
# fill up to len(O)
delta = len(O) - len(qqf)
... | '''convert to GAE filters from
lst is ["<field><operator><value>",...]
~ -> =
q = query_string
age fields: H = hours, S = seconds, M = minutes, d = days
'''
AGES = {'d': 'days', 'H': 'hours', 'M': 'minutes', 'S': 'seconds'}
ABBR = {'q': 'query_string'}
fi... | identifier_body |
smooth-scroll.js | /*!
* smooth-scroll v9.4.1: Animate scrolling to anchor links
* (c) 2016 Chris Ferdinandi
* MIT License
* http://github.com/cferdinandi/smooth-scroll
*/
(function (root, factory) {
if ( typeof define === 'function' && define.amd ) {
define([], factory(root));
} else if ( typeof exports === 'object' ) {
modu... | n = Math.max(location - headerHeight - offset, 0);
return Math.min(location, getDocumentHeight() - getViewportHeight());
};
/**
* Determine the viewport's height
* @private
* @returns {Number}
*/
var getViewportHeight = function() {
return Math.max(document.documentElement.clientHeight, window.in... | location += anchor.offsetTop;
anchor = anchor.offsetParent;
} while (anchor);
}
locatio | conditional_block |
smooth-scroll.js | /*!
* smooth-scroll v9.4.1: Animate scrolling to anchor links
* (c) 2016 Chris Ferdinandi
* MIT License
* http://github.com/cferdinandi/smooth-scroll
*/
(function (root, factory) {
if ( typeof define === 'function' && define.amd ) {
define([], factory(root));
} else if ( typeof exports === 'object' ) {
modu... |
};
/**
* Escape special characters for use with querySelector
* @public
* @param {String} id The anchor ID to escape
* @author Mathias Bynens
* @link https://github.com/mathiasbynens/CSS.escape
*/
smoothScroll.escapeCharacters = function ( id ) {
// Remove leading hash
if ( id.charAt(0) === '#' ) ... |
}
return null; | random_line_split |
playmp3.py | #! /usr/bin/env python2
# -*- coding: utf-8 -*-
#======================================================================
#
# playsnd.py - play sound with ctypes + mci
#
# Created by skywind on 2013/12/01
# Last change: 2014/01/26 23:40:20
#
#======================================================================... |
def mciGetErrorString (self, error):
buffer = self.__buffer
with self.__lock:
hr = self.__mciGetErrorStringW(error, buffer, 2048)
if hr == 0:
hr = None
else:
hr = buffer.value
return hr
def open (self, filename, media_type = ''):
if not os.path.exists(filename):
return Non... | if encoding is None:
encoding = sys.getfilesystemencoding()
if isinstance(command, bytes):
command = command.decode(encoding)
with self.__lock:
hr = self.__mciSendString(command, self.__buffer, 2048, 0)
hr = (hr != 0) and long(hr) or self.__buffer.value
return hr | identifier_body |
playmp3.py | #! /usr/bin/env python2
# -*- coding: utf-8 -*-
#======================================================================
#
# playsnd.py - play sound with ctypes + mci
#
# Created by skywind on 2013/12/01
# Last change: 2014/01/26 23:40:20
#
#======================================================================... | #----------------------------------------------------------------------
class WinMM (object):
def __init__ (self, prefix = ''):
import ctypes.wintypes
self.__winmm = ctypes.windll.winmm
self.__mciSendString = self.__winmm.mciSendStringW
self.__prefix = prefix
LPCWSTR = ctypes.wintypes.LPCWSTR
UIN... | #----------------------------------------------------------------------
# WinMM - Windows player
| random_line_split |
playmp3.py | #! /usr/bin/env python2
# -*- coding: utf-8 -*-
#======================================================================
#
# playsnd.py - play sound with ctypes + mci
#
# Created by skywind on 2013/12/01
# Last change: 2014/01/26 23:40:20
#
#======================================================================... | ():
winmm = WinMM()
name = winmm.open('d:/music/sample.mp3')
print(name)
print(winmm.get_length(name))
print(winmm.get_volume(name))
print(winmm.set_volume(name, 1000))
ts = time.time()
print(winmm.play(name))
ts = time.time() - ts
print("ts", ts)
input()
print('is_playing', winmm.is... | test1 | identifier_name |
playmp3.py | #! /usr/bin/env python2
# -*- coding: utf-8 -*-
#======================================================================
#
# playsnd.py - play sound with ctypes + mci
#
# Created by skywind on 2013/12/01
# Last change: 2014/01/26 23:40:20
#
#======================================================================... |
elif position < 0:
position = 'end'
else:
position = str(position)
return self.__mci_no_return(u'seek %s to %s'%name)
def pause (self, name):
return self.__mci_no_return(u'pause %s'%name)
def resume (self, name):
return self.__mci_no_return(u'resume %s'%name)
def get_volume (self, na... | position = '0' | conditional_block |
pool.js | var assert = require('assert');
var adapter = require('../index.js');
var config = require('./support/config.js');
var makeSlowQuery = require('./support/makeSlowQuery.js');
var ConnectionPool = false;
try {
ConnectionPool = require('any-db-pool');
}
catch (e) {
ConnectionPool = false;
}
var delaySeconds = 2;
var ... |
};
var onDone = function(){
var keys = Object.keys(ids);
assert.strictEqual(ids.length, todo, 'There should be '+todo+' connections acquired');
assert.strictEqual(ids.length, keys.length - 1, 'There should be '+todo+' connections acquired');
done();
};
pool.acquire(function(err, connection){
... | {
onDone();
} | conditional_block |
pool.js | var assert = require('assert');
var adapter = require('../index.js');
var config = require('./support/config.js');
var makeSlowQuery = require('./support/makeSlowQuery.js');
var ConnectionPool = false;
try {
ConnectionPool = require('any-db-pool');
}
catch (e) {
ConnectionPool = false;
}
var delaySeconds = 2;
var ... |
it('should exist', function(){
assert.ok(pool);
});
['query', 'acquire', 'release', 'close'].forEach(function(name){
it('should provide `'+name+'()` method', function(){
assert.ok(pool.query, 'There should be a `'+name+'` provided by the ConnectionPool object');
assert.ok(pool.query instanceof Function, ... | after(function(done){
pool.close(done);
}); | random_line_split |
config.py | # -*- coding: utf-8 -*-
#
# This file is part of Zenodo.
# Copyright (C) 2015 CERN.
#
# Zenodo is free software; you can redistribute it | #
# Zenodo is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with... | # 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. | random_line_split |
package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Gengeo(AutotoolsPackage):
"""GenGeo is a library of tools for creating complex particle
... | 'CCFLAGS=-fpermissive',
'CXXFLAGS=-fpermissive',
]
return args | '--verbose',
'--with-boost=' + self.spec['boost'].prefix, | random_line_split |
package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Gengeo(AutotoolsPackage):
| """GenGeo is a library of tools for creating complex particle
geometries for use in ESyS-Particle simulations. GenGeo is a standalone
application with a Python API that creates geometry files suitable for
importing into ESyS-Particle simulations. The functionality of GenGeo far
exceeds the in-simulation... | identifier_body | |
package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Gengeo(AutotoolsPackage):
"""GenGeo is a library of tools for creating complex particle
... | (self, spec, prefix):
autogen = Executable('./autogen.sh')
autogen()
def configure_args(self):
args = [
'--verbose',
'--with-boost=' + self.spec['boost'].prefix,
'CCFLAGS=-fpermissive',
'CXXFLAGS=-fpermissive',
]
return args
| autoreconf | identifier_name |
buffer.ts | import c = require('../context');
/** A memory block of values */
export class Mem {
/** The GL buffer target, or any other native binding */
public buffer:any = null;
/** A data block of memeory */
public data:ArrayBuffer;
/** Open gl context */
private _glc:c.Context;
/** Size of this memory block ... |
this.data.set(data);
return this;
}
}
/** Convenience function for a simple data element */
export function factory(length:number):Buffer<Float32Array> {
var size = Float32Array['BYTES_PER_ELEMENT'] * length;
var mem = new Mem(size);
return new Buffer<Float32Array>(Float32Array, mem, length, 0);... | {
throw Error('Invalid set length ' + data.length + ' != buffer size ' + this.length);
} | conditional_block |
buffer.ts | import c = require('../context');
/** A memory block of values */
export class Mem {
/** The GL buffer target, or any other native binding */
public buffer:any = null;
/** A data block of memeory */
public data:ArrayBuffer;
/** Open gl context */
private _glc:c.Context;
/** Size of this memory block ... |
/*
* Replace a section of the data in this data block
* @param offset The offset into this VP to set data from.
* @param src The source to read new data from
* @param srcOffset The offset into the source for elements
* @param items The number of items to copy over
*/
public memset(offset:number,... | {
var max = this.mem.size / this.block;
if (length > max) {
throw Error('Invalid length ' + length + ' when memory block is only ' + max + ' long');
}
switch (type) {
case Float32Array:
var rtn:any = new Float32Array(this.mem.data, this.block * offset, length);
return <T> rtn... | identifier_body |
buffer.ts | import c = require('../context');
/** A memory block of values */
export class Mem {
/** The GL buffer target, or any other native binding */
public buffer:any = null;
/** A data block of memeory */
public data:ArrayBuffer;
/** Open gl context */
private _glc:c.Context;
/** Size of this memory block ... |
/** Replace a section of the data in this data block */
public memset(offset:number, src:Mem, srcOffset:number, bytes:number) {
var dstU8 = new Uint8Array(this.data, offset, bytes);
var srcU8 = new Uint8Array(src.data, srcOffset, bytes);
dstU8.set(srcU8);
}
}
/** Minimal api we expect on typed array... | this.data = new ArrayBuffer(size);
this.size = size;
} | random_line_split |
buffer.ts | import c = require('../context');
/** A memory block of values */
export class Mem {
/** The GL buffer target, or any other native binding */
public buffer:any = null;
/** A data block of memeory */
public data:ArrayBuffer;
/** Open gl context */
private _glc:c.Context;
/** Size of this memory block ... | (size:number) {
this.data = new ArrayBuffer(size);
this.size = size;
}
/** Replace a section of the data in this data block */
public memset(offset:number, src:Mem, srcOffset:number, bytes:number) {
var dstU8 = new Uint8Array(this.data, offset, bytes);
var srcU8 = new Uint8Array(src.data, srcOffs... | constructor | identifier_name |
test_method_message_parser.py | # -*- coding: utf-8 -*-
# Copyright 2014 Foxdog Studios
#
# 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 l... | def setUp(self):
self.parser = MethodMessageParser()
def test_parse(self):
id = 'id'
method = 'method'
params = [True, 1.0]
message = self.parser.parse({'msg': 'method', 'id': id,
'method': method, 'params': params})
self.assertEq... | identifier_body | |
test_method_message_parser.py | # -*- coding: utf-8 -*-
# Copyright 2014 Foxdog Studios
#
# 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 l... | from ddp.messages.client import MethodMessage
from ddp.messages.client import MethodMessageParser
class MethodMessageParserTestCase(unittest.TestCase):
def setUp(self):
self.parser = MethodMessageParser()
def test_parse(self):
id = 'id'
method = 'method'
params = [True, 1.0]
... | import unittest
| random_line_split |
test_method_message_parser.py | # -*- coding: utf-8 -*-
# Copyright 2014 Foxdog Studios
#
# 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 l... | (self):
self.parser = MethodMessageParser()
def test_parse(self):
id = 'id'
method = 'method'
params = [True, 1.0]
message = self.parser.parse({'msg': 'method', 'id': id,
'method': method, 'params': params})
self.assertEqual(messa... | setUp | identifier_name |
tunnels.py | # coding=utf-8
#
# Copyright 2016 F5 Networks 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... | OrganizingCollection):
"""BIG-IP® network tunnels collection"""
def __init__(self, net):
super(TunnelS, self).__init__(net)
self._meta_data['allowed_lazy_attributes'] = [
Gres,
Tunnels,
Vxlans,
]
class Tunnels(Collection):
"""BIG-IP® network tunn... | unnelS( | identifier_name |
tunnels.py | # coding=utf-8
#
# Copyright 2016 F5 Networks Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License. | #
# Unless required by applicable law or agreed to in writing, software
# 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.
#
... | # You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0 | random_line_split |
tunnels.py | # coding=utf-8
#
# Copyright 2016 F5 Networks 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... |
class Tunnels(Collection):
"""BIG-IP® network tunnels resource (collection for GRE, Tunnel, VXLANs"""
def __init__(self, tunnelS):
super(Tunnels, self).__init__(tunnelS)
self._meta_data['allowed_lazy_attributes'] = [Gres, Tunnel, Vxlans]
self._meta_data['attribute_registry'] =\
... | ""BIG-IP® network tunnels collection"""
def __init__(self, net):
super(TunnelS, self).__init__(net)
self._meta_data['allowed_lazy_attributes'] = [
Gres,
Tunnels,
Vxlans,
]
| identifier_body |
purchase_order.py | # -*- coding: utf-8 -*-
#
#
# Author: Yannick Vaucher
# Copyright 2014 Camptocamp SA
#
# 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,... |
@api.multi
def _requisition_currency(self):
for rec in self:
requisition = rec.order_id.requisition_id
if requisition:
rec.requisition_currency = requisition.currency_id
price_unit_co = fields.Float(
compute='_compute_prices_in_company_currency',
... | """ """
requisition = self.order_id.requisition_id
date = requisition.date_exchange_rate or fields.Date.today()
from_curr = self.order_id.currency_id.with_context(date=date)
if requisition and requisition.currency_id:
to_curr = requisition.currency_id
else:
... | identifier_body |
purchase_order.py | # -*- coding: utf-8 -*-
#
#
# Author: Yannick Vaucher
# Copyright 2014 Camptocamp SA
#
# 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,... | (self):
""" """
requisition = self.order_id.requisition_id
date = requisition.date_exchange_rate or fields.Date.today()
from_curr = self.order_id.currency_id.with_context(date=date)
if requisition and requisition.currency_id:
to_curr = requisition.currency_id
... | _compute_prices_in_company_currency | identifier_name |
purchase_order.py | # -*- coding: utf-8 -*-
#
#
# Author: Yannick Vaucher
# Copyright 2014 Camptocamp SA
#
# 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,... |
price_unit_co = fields.Float(
compute='_compute_prices_in_company_currency',
string="Unit Price",
digits=dp.get_precision('Account'),
store=True,
help="Unit Price in company currency."
)
price_subtotal_co = fields.Float(
compute='_compute_prices_in_comp... | rec.requisition_currency = requisition.currency_id | conditional_block |
purchase_order.py | # -*- coding: utf-8 -*-
#
#
# Author: Yannick Vaucher
# Copyright 2014 Camptocamp SA
#
# 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,... | # You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#
from openerp import models, fields, api
import openerp.addons.decimal_precision as dp
class PurchaseOrderLine(models.Model):
_inherit = 'purchase.order.line'... | # GNU Affero General Public License for more details.
# | random_line_split |
api.py | from better_zoom import BetterZoom
from better_selecting_zoom import BetterSelectingZoom
from broadcaster import BroadcasterTool
from dataprinter import DataPrinter
from data_label_tool import DataLabelTool
from enable.tools.drag_tool import DragTool
from draw_points_tool import DrawPointsTool | from image_inspector_tool import ImageInspectorTool, ImageInspectorOverlay
from lasso_selection import LassoSelection
from legend_tool import LegendTool
from legend_highlighter import LegendHighlighter
from line_inspector import LineInspector
from line_segment_tool import LineSegmentTool
from move_tool import MoveTool
... | from drag_zoom import DragZoom
from highlight_tool import HighlightTool | random_line_split |
analisi.py | import numpy
import math
import pylab
from scipy.optimize import curve_fit
import math
import scipy.stats
import lab
def fit_function(x, a, b):
return b*(numpy.exp(x/a)-1)
FileName='/home/federico/Documenti/Laboratorio2/Diodo/dati_arduino/dati.txt'
N1, N2 = pylab.loadtxt(FileName, unpack="True")
errN2 = numpy.arra... | #V2 = volt
#I = ampere
#errI = errAmpere
#errV2 = errVolt
print(V2, I, errV2, errI)
pylab.title("Curva corrente tensione")
pylab.xlabel("V (V)")
pylab.ylabel("I (A)")
pylab.grid(color = "gray")
pylab.grid(color = "gray")
pylab.errorbar(V2, I, errI, errV2, "o", color="black")
initial = numpy.array([0.0515, 6.75e-0... | # print(index)
# aNonNulli[i] = ampere[index]
| random_line_split |
analisi.py | import numpy
import math
import pylab
from scipy.optimize import curve_fit
import math
import scipy.stats
import lab
def fit_function(x, a, b):
return b*(numpy.exp(x/a)-1)
FileName='/home/federico/Documenti/Laboratorio2/Diodo/dati_arduino/dati.txt'
N1, N2 = pylab.loadtxt(FileName, unpack="True")
errN2 = numpy.arra... | #da finire vorrei implementare quella cosa che sostituisco le colonne di punti con un solo punto ma non ne ho voglia
#number = 150
#minV = 0.30
#maxV = 0.70
#inc = (maxV - minV)/number
#volt = numpy.array([(minV + i*inc) for i in range(number)])
#voltaggiVeri = numpy.array([])
#ampere = numpy.array([])
#errVo... | [i] = 1.0e-11*i
| conditional_block |
analisi.py | import numpy
import math
import pylab
from scipy.optimize import curve_fit
import math
import scipy.stats
import lab
def fi | , a, b):
return b*(numpy.exp(x/a)-1)
FileName='/home/federico/Documenti/Laboratorio2/Diodo/dati_arduino/dati.txt'
N1, N2 = pylab.loadtxt(FileName, unpack="True")
errN2 = numpy.array([1.0 for i in range(len(N2))])
errN1 = numpy.array([1.0 for i in range(len(N1))])
Rd = 3280.0
errRd = 30.0
eta = 4.89/1000
erreta = 0... | t_function(x | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.