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
referenciacatastral.py
# referenciacatastral.py - functions for handling Spanish real state ids # coding: utf-8 # # Copyright (C) 2016 David García Garzón # Copyright (C) 2016-2017 Arthur de Jong # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as publish...
return number def calc_check_digits(number): """Calculate the check digits for the number.""" number = _force_unicode(compact(number)) return ( _check_digit(number[0:7] + number[14:18]) + _check_digit(number[7:14] + number[14:18])) def validate(number): """Checks to see if the number...
r = number.decode('utf-8')
conditional_block
event_loop.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! This module contains the `EventLoop` type, which is the constellation's //! view of a script thread. When an `...
} impl EventLoop { /// Create a new event loop from the channel to its script thread. pub fn new(script_chan: IpcSender<ConstellationControlMsg>) -> Rc<EventLoop> { Rc::new(EventLoop { script_chan: script_chan, dont_send_or_sync: PhantomData, }) } /// Send a me...
{ let _ = self .script_chan .send(ConstellationControlMsg::ExitScriptThread); }
identifier_body
event_loop.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! This module contains the `EventLoop` type, which is the constellation's //! view of a script thread. When an `...
(&self) -> IpcSender<ConstellationControlMsg> { self.script_chan.clone() } }
sender
identifier_name
event_loop.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! This module contains the `EventLoop` type, which is the constellation's //! view of a script thread. When an `...
let _ = self .script_chan .send(ConstellationControlMsg::ExitScriptThread); } } impl EventLoop { /// Create a new event loop from the channel to its script thread. pub fn new(script_chan: IpcSender<ConstellationControlMsg>) -> Rc<EventLoop> { Rc::new(EventLoop { ...
random_line_split
upload.js
// upload stuff to the keying server... function
(desturl, obj) { jQuery.ajax({ type: "PUT", url: desturl, contentType: "image/png", data: obj, error: function(jqxhr, textStatus) { //alert("Communication error: " + textStatus); } }); } function postJson(desturl, obj) { jQuery.ajax({ ty...
putPng
identifier_name
upload.js
// upload stuff to the keying server... function putPng(desturl, obj) { jQuery.ajax({ type: "PUT", url: desturl, contentType: "image/png", data: obj, error: function(jqxhr, textStatus) { //alert("Communication error: " + textStatus); } }); } functi...
$(document).ready(function() { $("#pngImage").change(function() { var file = $("#pngImage")[0].files[0]; var fr = new FileReader(); fr.onload = function(e) { var data = e.target.result; putPng('/key_dataurl', data); }; fr.readAsDataURL(file); });...
{ jQuery.ajax({ type: "POST", url: desturl, contentType: "application/json", data: JSON.stringify(obj), error: function(jqxhr, textStatus) { //alert("Communication error: " + textStatus); } }); }
identifier_body
upload.js
// upload stuff to the keying server... function putPng(desturl, obj) { jQuery.ajax({ type: "PUT", url: desturl, contentType: "image/png", data: obj, error: function(jqxhr, textStatus) { //alert("Communication error: " + textStatus); } }); } functi...
var fr = new FileReader(); fr.onload = function(e) { var data = e.target.result; putPng('/key_dataurl', data); }; fr.readAsDataURL(file); }); $("#titleUp").click(function() { postJson('/dissolve_in/30', {}); }); $("#titleDown").click(fun...
random_line_split
datatype-date-format-debug.js
*/ /** * The Date Utility provides type-conversion and string-formatting * convenience methods for Dates. * * @module datatype-date * @main datatype-date */ /** * Date module. * * @module datatype-date */ /** * Format date module implements strftime formatters for javascript based on the * Open Group sp...
* @module datatype * @main datatype
random_line_split
datatype-date-format-debug.js
.getTimezoneOffset(); var H = xPad(parseInt(Math.abs(o/60), 10), 0); var M = xPad(Math.abs(o%60), 0); return (o>0?"-":"+") + H + M; }, Z: function (d) { var tz = d.toString().replace(/^.*:\d\d( GMT[+-]\d+)? \(?([A-Za-z ]+)\)?\d*$/, "$2").replace(/[a-z ]/g, ""); if(tz.length > 4) { tz = Dt.for...
{ return resources[m1]; }
conditional_block
palloc_8h.js
var palloc_8h = [ [ "palloc_t", "dc/d36/structpalloc__t.html", "dc/d36/structpalloc__t" ], [ "MAX_PALLOC", "dc/df7/palloc_8h.html#ae98cf2dde32dd7752510faa08edec1ef", null ], [ "PALLOC_MAX_BLOCKS", "dc/df7/palloc_8h.html#a6acb1947dc49f45d9429e9cc660ce2b1", null ], [ "PALLOC_SIZE", "dc/df7/palloc_8h.html#...
[ "pgetusable", "dc/df7/palloc_8h.html#a4d92f3937b1e63849c7466119e561b7f", null ], [ "pinit", "dc/df7/palloc_8h.html#acea7f1b315e15a2d1024c45b87b6276d", null ], [ "ptotalsize", "dc/df7/palloc_8h.html#a5a2279e2e824d45690599172b2436807", null ], [ "pusedmem", "dc/df7/palloc_8h.html#a0988517ae62414ef09cf26...
random_line_split
Game.tsx
import React from 'react'; import { Client } from '@freeboardgame.org/boardgame.io/react'; import { IGameDef, GAMES_MAP, IGameConfig, IAIConfig } from '../../games'; import { gameBoardWrapper } from './GameBoardWrapper'; import { GameMode } from './GameModePicker'; import getMessagePage from '../MessagePage'; import Me...
() { const aiLevel = this.props.match.params.aiLevel; const matchCode = this.props.match.params.matchCode; const playerID = this.props.match.params.playerID; if (!this.gameDef) { return <MessagePageClass type={'error'} message={'Game Not Found'} />; } if (!state.loading && state.config) { ...
render
identifier_name
Game.tsx
import React from 'react'; import { Client } from '@freeboardgame.org/boardgame.io/react'; import { IGameDef, GAMES_MAP, IGameConfig, IAIConfig } from '../../games'; import { gameBoardWrapper } from './GameBoardWrapper'; import { GameMode } from './GameModePicker'; import getMessagePage from '../MessagePage'; import Me...
bootstrap() { return this.load(); } load() { if (this.gameDef) { let aiPromise = Promise.resolve({}); if (this.loadAI) { aiPromise = this.gameDef.aiConfig(); } return Promise.all([this.gameDef.config(), aiPromise]).then( (promises: any) => { state.confi...
{ state.loading = true; state.error = false; state.config = undefined; }
identifier_body
Game.tsx
import React from 'react'; import { Client } from '@freeboardgame.org/boardgame.io/react'; import { IGameDef, GAMES_MAP, IGameConfig, IAIConfig } from '../../games'; import { gameBoardWrapper } from './GameBoardWrapper'; import { GameMode } from './GameModePicker'; import getMessagePage from '../MessagePage'; import Me...
}
random_line_split
Game.tsx
import React from 'react'; import { Client } from '@freeboardgame.org/boardgame.io/react'; import { IGameDef, GAMES_MAP, IGameConfig, IAIConfig } from '../../games'; import { gameBoardWrapper } from './GameBoardWrapper'; import { GameMode } from './GameModePicker'; import getMessagePage from '../MessagePage'; import Me...
} componentDidMount() { if (this.gameDef) { this.load().then(() => { this.forceUpdate(); }); } } render() { const aiLevel = this.props.match.params.aiLevel; const matchCode = this.props.match.params.matchCode; const playerID = this.props.match.params.playerID; if (...
{ state.config = undefined; state.loading = false; state.error = true; return Promise.resolve(); }
conditional_block
route.rs
the user supplied the information. This structure can only be obtained by /// calling the `RouteParams::from` function and passing in the entire decorator /// environment. #[derive(Debug)] pub struct RouteParams { pub annotated_fn: Function, pub method: Spanned<Method>, pub uri: Spanned<URI<'static>>, ...
uri: uri, data_param: data, query_param: query, format: format, rank: rank, annotated_fn: function, } } pub fn path_params<'s, 'a, 'c: 'a>(&'s self, ecx: &'a ExtCtxt<'c>) ...
RouteParams { method: method,
random_line_split
route.rs
user supplied the information. This structure can only be obtained by /// calling the `RouteParams::from` function and passing in the entire decorator /// environment. #[derive(Debug)] pub struct RouteParams { pub annotated_fn: Function, pub method: Spanned<Method>, pub uri: Spanned<URI<'static>>, pub ...
let (method, attr_params) = match known_method { Some(method) => (method, meta_items), None => (parse_method(ecx, &meta_items[0]), &meta_items[1..]) }; if attr_params.len() < 1 { ecx.struct_span_err(sp, "attribute requires at least a path") .h...
{ let function = Function::from(annotated).unwrap_or_else(|item_sp| { ecx.span_err(sp, "this attribute can only be used on functions..."); ecx.span_fatal(item_sp, "...but was applied to the item above."); }); let meta_items = meta_item.meta_item_list().unwrap_or_else(|| ...
identifier_body
route.rs
user supplied the information. This structure can only be obtained by /// calling the `RouteParams::from` function and passing in the entire decorator /// environment. #[derive(Debug)] pub struct
{ pub annotated_fn: Function, pub method: Spanned<Method>, pub uri: Spanned<URI<'static>>, pub data_param: Option<KVSpanned<Ident>>, pub query_param: Option<Spanned<Ident>>, pub format: Option<KVSpanned<MediaType>>, pub rank: Option<KVSpanned<isize>>, } impl RouteParams { /// Parses th...
RouteParams
identifier_name
route.rs
user supplied the information. This structure can only be obtained by /// calling the `RouteParams::from` function and passing in the entire decorator /// environment. #[derive(Debug)] pub struct RouteParams { pub annotated_fn: Function, pub method: Spanned<Method>, pub uri: Spanned<URI<'static>>, pub ...
else if let Some(s) = meta_item.str_lit() { return validate_uri(ecx, &s.as_str(), sp); } else { ecx.struct_span_err(sp, r#"expected `path = string` or a path string"#) .help(r#"you can specify the path directly as a string, \ e.g: "/hello/world", or as a key-value pair...
{ if name != &"path" { ecx.span_err(sp, "the first key, if any, must be 'path'"); } else if let LitKind::Str(ref s, _) = lit.node { return validate_uri(ecx, &s.as_str(), lit.span); } else { ecx.span_err(lit.span, "`path` value must be a string") } ...
conditional_block
custom.js
/* Jquery Validation using jqBootstrapValidation example is taken from jqBootstrapValidation docs */ $(function() { $("input,textarea").jqBootstrapValidation( { preventSubmit: true, submitError: function($form, event, errors) { // something to have when submit produces an error ? // ...
$('#success').html("<div class='alert alert-danger'>"); $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;") .append( "</button>"); $('#success > .alert-danger').append("<strong>Sorry "+name+" it seems that ...
// Fail message
random_line_split
cp-cli.test.ts
import fse from 'fs-extra'; import { platform } from 'os'; import shell from 'shelljs'; import test, { Test, TestCase } from 'tape'; function
(cb: (t: Test) => void): TestCase { return async t => { cb(t); await Promise.all([fse.remove('out'), fse.remove('test/assets/bar.txt')]); t.end(); }; } test( 'print a help text when no arguments given', withAfterEach(t => { const { stderr } = shell.exec('node dist/src/cp-cli'); t.notEqual(s...
withAfterEach
identifier_name
cp-cli.test.ts
import fse from 'fs-extra'; import { platform } from 'os'; import shell from 'shelljs'; import test, { Test, TestCase } from 'tape'; function withAfterEach(cb: (t: Test) => void): TestCase
test( 'print a help text when no arguments given', withAfterEach(t => { const { stderr } = shell.exec('node dist/src/cp-cli'); t.notEqual(stderr, ''); }), ); test( 'print a help text when only one argument was given', withAfterEach(t => { const { stderr } = shell.exec('node dist/src/cp-cli foo'...
{ return async t => { cb(t); await Promise.all([fse.remove('out'), fse.remove('test/assets/bar.txt')]); t.end(); }; }
identifier_body
cp-cli.test.ts
import fse from 'fs-extra'; import { platform } from 'os'; import shell from 'shelljs'; import test, { Test, TestCase } from 'tape'; function withAfterEach(cb: (t: Test) => void): TestCase { return async t => { cb(t); await Promise.all([fse.remove('out'), fse.remove('test/assets/bar.txt')]); t.end(); }...
test( 'copy directory content', withAfterEach(t => { const { stderr } = shell.exec('node dist/src/cp-cli test/assets out'); t.equal(stderr, ''); const stats = fse.statSync('out/foo.txt'); t.true(stats.isFile()); }), ); test( 'copy directory content when target directory does not exist', wit...
{ test( 'dereference symlinks', withAfterEach(async t => { shell.cd('test/assets'); shell.ln('-s', 'foo.txt', 'bar.txt'); shell.cd('../..'); const { stderr } = shell.exec('node dist/src/cp-cli -d test/assets out'); t.equal(stderr, ''); let stats = await fse.stat('out/foo.tx...
conditional_block
cp-cli.test.ts
import fse from 'fs-extra'; import { platform } from 'os'; import shell from 'shelljs'; import test, { Test, TestCase } from 'tape'; function withAfterEach(cb: (t: Test) => void): TestCase { return async t => { cb(t); await Promise.all([fse.remove('out'), fse.remove('test/assets/bar.txt')]); t.end(); }...
test( 'copy a source file to target dir', withAfterEach(t => { const { stderr } = shell.exec( 'node dist/src/cp-cli test/assets/foo.txt out/foo.txt', ); t.equal(stderr, ''); const stats = fse.statSync('out/foo.txt'); t.true(stats.isFile()); }), ); if (platform() !== 'win32') { test( ...
t.notEqual(stderr, ''); }), );
random_line_split
df_interpreter.py
# coding: utf-8 # # drums-backend a simple interactive audio sampler that plays vorbis samples # Copyright (C) 2009 C.D. Immanuel Albrecht # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Fou...
(self): if self.tracebacked: self.tracebacked = False return True else: return False
hasTracebacked
identifier_name
df_interpreter.py
# coding: utf-8 # # drums-backend a simple interactive audio sampler that plays vorbis samples # Copyright (C) 2009 C.D. Immanuel Albrecht # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Fou...
# # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import code import string from df_global import * class DfInterpreter(code.InteractiveInterpreter): """class that will act as input-stream for python code sent by the ...
random_line_split
df_interpreter.py
# coding: utf-8 # # drums-backend a simple interactive audio sampler that plays vorbis samples # Copyright (C) 2009 C.D. Immanuel Albrecht # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Fou...
else: return False
self.tracebacked = False return True
conditional_block
df_interpreter.py
# coding: utf-8 # # drums-backend a simple interactive audio sampler that plays vorbis samples # Copyright (C) 2009 C.D. Immanuel Albrecht # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Fou...
def write(self,data): send = "PYTHON:" + data.replace("\n","\nPYTHON':")+"\n" self.vars["ui_out"].write(send) self.vars["ui_out"].flush() def hasTracebacked(self): if self.tracebacked: self.tracebacked = False return True else: return False
vars = globalvars code.InteractiveInterpreter.__init__(self, locals) self.tracebacked = False self.oldshowtraceback = self.showtraceback def new_traceback(*args): self.tracebacked = True return self.oldshowtraceback(*args) self.showtraceback = new_traceback
identifier_body
background.js
// track page views var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-105747972-2']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = 'https://ssl.google-analytics.com/ga.js'; var s = document.getElementsByTagName('scr...
} // turning extension on and off chrome.browserAction.onClicked.addListener(function(tab) { updateState(tab); }); function updateState(tab) { updateIcon(); chrome.storage.sync.set({'state': currIcon}, function() { //message('Toggled on/off');e }); }
// updates icon image function updateIcon() { currIcon = (currIcon + 1) % 2; chrome.browserAction.setIcon({path: "./../icons/ticker_sticker_" + currIcon + ".png"});
random_line_split
background.js
// track page views var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-105747972-2']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = 'https://ssl.google-analytics.com/ga.js'; var s = document.getElementsByTagName('scr...
{ updateIcon(); chrome.storage.sync.set({'state': currIcon}, function() { //message('Toggled on/off');e }); }
identifier_body
background.js
// track page views var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-105747972-2']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = 'https://ssl.google-analytics.com/ga.js'; var s = document.getElementsByTagName('scr...
() { currIcon = (currIcon + 1) % 2; chrome.browserAction.setIcon({path: "./../icons/ticker_sticker_" + currIcon + ".png"}); } // turning extension on and off chrome.browserAction.onClicked.addListener(function(tab) { updateState(tab); }); function updateState(tab) { updateIcon(); chrome.storage.sync.set({'state'...
updateIcon
identifier_name
batch_conversion.py
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2016 Pi-Yueh Chuang <pychuang@gwu.edu> # # Distributed under terms of the MIT license. """convert the output file in a batch""" import os import os.path as op import sys import argparse if os.getenv("PyFR") is None: raise Environmen...
if not op.isdir(args.vtuDir): os.mkdir(args.vtuDir) return args def get_pyfrs_list(pyfrsDirPath): """get list of file names that end with .pyfrs in pyfrsDirPath Args: pyfrsDirPath: path to the folder of .pyfrs files Returns: a list of file names """ fileList = [...
random_line_split
batch_conversion.py
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2016 Pi-Yueh Chuang <pychuang@gwu.edu> # # Distributed under terms of the MIT license. """convert the output file in a batch""" import os import os.path as op import sys import argparse if os.getenv("PyFR") is None: raise Environmen...
try: import pyfr import pyfr.writers except ImportError as err: err.msg += "! Please check the path set in the environmental variable PyFR." raise def parseArgs(args=sys.argv[1:]): """parse arguments Args: args: list of strings. Default is sys.argv[1:]. Returns: parser.p...
ys.path.append(PyFRPath)
conditional_block
batch_conversion.py
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2016 Pi-Yueh Chuang <pychuang@gwu.edu> # # Distributed under terms of the MIT license. """convert the output file in a batch""" import os import os.path as op import sys import argparse if os.getenv("PyFR") is None: raise Environmen...
def get_pyfrs_files(pyfrsDirPath): pass if __name__ == "__main__": args = parseArgs() args = setup_dirs(args) pyfrsList = get_pyfrs_list(args.solnDir) generate_vtu( args.vtuDir, args.solnDir, pyfrsList, args.mesh, args.overwrite, args.degree)
""convert a single .pyfrs file to .vtu file using PyFR's converter Args: mesh: mesh file (must end with .pyfrm) input: input file name (must end with .pyfrs) output: output file name (must end with .vtu) g: whether to export gradients p: precision, either "single" or "double...
identifier_body
batch_conversion.py
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2016 Pi-Yueh Chuang <pychuang@gwu.edu> # # Distributed under terms of the MIT license. """convert the output file in a batch""" import os import os.path as op import sys import argparse if os.getenv("PyFR") is None: raise Environmen...
pyfrsDirPath): """get list of file names that end with .pyfrs in pyfrsDirPath Args: pyfrsDirPath: path to the folder of .pyfrs files Returns: a list of file names """ fileList = [f for f in os.listdir(pyfrsDirPath) if op.splitext(f)[1] == ".pyfrs"] if len(file...
et_pyfrs_list(
identifier_name
eigen.rs
#[cfg(feature = "serde-serialize")] use serde::{Deserialize, Serialize}; use num_complex::Complex; use simba::scalar::ComplexField; use std::cmp; use std::fmt::Display; use std::ops::MulAssign; use crate::allocator::Allocator; use crate::base::dimension::{Dim, DimDiff, DimSub, Dynamic, U1, U2, U3}; use crate::base::s...
<N: ComplexField, D: Dim> where DefaultAllocator: Allocator<N, D, D> + Allocator<N, D> { pub eigenvectors: MatrixN<N, D>, pub eigenvalues: VectorN<N, D>, } impl<N: ComplexField, D: Dim> Copy for Eigen<N, D> where DefaultAllocator: Allocator<N, D, D> + Allocator<N, D>, MatrixN<N, D>: Copy, VectorN<N...
Eigen
identifier_name
eigen.rs
#[cfg(feature = "serde-serialize")] use serde::{Deserialize, Serialize}; use num_complex::Complex; use simba::scalar::ComplexField; use std::cmp; use std::fmt::Display; use std::ops::MulAssign; use crate::allocator::Allocator; use crate::base::dimension::{Dim, DimDiff, DimSub, Dynamic, U1, U2, U3}; use crate::base::s...
return None; } let z = -eigenvalues[(i, j)] / diff; for k in j + 1..dim { eigenvalues[(i, k)] -= z * eigenvalues[(j, k)]; } for k in 0..dim { eigenvectors[(k, j)] += z * eigenve...
for i in 0..j { let diff = eigenvalues[(i, i)] - eigenvalues[(j, j)]; if diff.is_zero() && !eigenvalues[(i, j)].is_zero() {
random_line_split
eigen.rs
#[cfg(feature = "serde-serialize")] use serde::{Deserialize, Serialize}; use num_complex::Complex; use simba::scalar::ComplexField; use std::cmp; use std::fmt::Display; use std::ops::MulAssign; use crate::allocator::Allocator; use crate::base::dimension::{Dim, DimDiff, DimSub, Dynamic, U1, U2, U3}; use crate::base::s...
let z = -eigenvalues[(i, j)] / diff; for k in j + 1..dim { eigenvalues[(i, k)] -= z * eigenvalues[(j, k)]; } for k in 0..dim { eigenvectors[(k, j)] += z * eigenvectors[(k, i)]; } } ...
{ return None; }
conditional_block
eigen.rs
#[cfg(feature = "serde-serialize")] use serde::{Deserialize, Serialize}; use num_complex::Complex; use simba::scalar::ComplexField; use std::cmp; use std::fmt::Display; use std::ops::MulAssign; use crate::allocator::Allocator; use crate::base::dimension::{Dim, DimDiff, DimSub, Dynamic, U1, U2, U3}; use crate::base::s...
let diff = eigenvalues[(i, i)] - eigenvalues[(j, j)]; if diff.is_zero() && !eigenvalues[(i, j)].is_zero() { return None; } let z = -eigenvalues[(i, j)] / diff; for k in j + 1..dim { eigenvalues[(i,...
{ assert!( m.is_square(), "Unable to compute the eigendecomposition of a non-square matrix." ); let dim = m.nrows(); let (mut eigenvectors, mut eigenvalues) = Schur::new(m, 0).unwrap().unpack(); println!("Schur eigenvalues: {}", eigenvalues); //...
identifier_body
tools.ts
export function mergeSort<T>(source: Array<T>, compare: (a: T, b: T) => boolean) { let s = 1, n = source.length; let buff: Array<T> = new Array(n); while (s < n) {
// merge [l, m] and [m+1, r] function merge<T>(source: Array<T>, target: Array<T>, l: number, m: number, r: number, compare: (a: T, b: T) => boolean) { let i = l, j = m + 1, k = l; while ((i <= m) && (j <= r)) if (compare(source[i],source[j])) target[k++] = source[i++]; else target[k++] = sourc...
mergeAll(source, buff, s, n, compare); s += s; mergeAll(buff, source, s, n, compare); s += s; } }
conditional_block
tools.ts
export function mergeSort<T>(source: Array<T>, compare: (a: T, b: T) => boolean) { let s = 1, n = source.length;
while (s < n) { mergeAll(source, buff, s, n, compare); s += s; mergeAll(buff, source, s, n, compare); s += s; } } // merge [l, m] and [m+1, r] function merge<T>(source: Array<T>, target: Array<T>, l: number, m: number, r: number, compare: (a: T, b: T) => boolean) { let i = l,...
let buff: Array<T> = new Array(n);
random_line_split
tools.ts
export function mergeSort<T>(source: Array<T>, compare: (a: T, b: T) => boolean) {
/ merge [l, m] and [m+1, r] function merge<T>(source: Array<T>, target: Array<T>, l: number, m: number, r: number, compare: (a: T, b: T) => boolean) { let i = l, j = m + 1, k = l; while ((i <= m) && (j <= r)) if (compare(source[i],source[j])) target[k++] = source[i++]; else target[k++] = source[...
let s = 1, n = source.length; let buff: Array<T> = new Array(n); while (s < n) { mergeAll(source, buff, s, n, compare); s += s; mergeAll(buff, source, s, n, compare); s += s; } } /
identifier_body
tools.ts
export function me
>(source: Array<T>, compare: (a: T, b: T) => boolean) { let s = 1, n = source.length; let buff: Array<T> = new Array(n); while (s < n) { mergeAll(source, buff, s, n, compare); s += s; mergeAll(buff, source, s, n, compare); s += s; } } // merge [l, m] and [m+1, r] function...
rgeSort<T
identifier_name
addAllUserToRoom.js
Meteor.methods({ addAllUserToRoom(rid, activeUsersOnly = false)
const userFilter = {}; if (activeUsersOnly === true) { userFilter.active = true; } const users = RocketChat.models.Users.find(userFilter).fetch(); const now = new Date(); users.forEach(function(user) { const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(rid, user._id...
{ check (rid, String); check (activeUsersOnly, Boolean); if (RocketChat.authz.hasRole(this.userId, 'admin') === true) { const userCount = RocketChat.models.Users.find().count(); if (userCount > RocketChat.settings.get('API_User_Limit')) { throw new Meteor.Error('error-user-limit-exceeded', 'User Limit...
identifier_body
addAllUserToRoom.js
Meteor.methods({ addAllUserToRoom(rid, activeUsersOnly = false) { check (rid, String); check (activeUsersOnly, Boolean); if (RocketChat.authz.hasRole(this.userId, 'admin') === true) { const userCount = RocketChat.models.Users.find().count(); if (userCount > RocketChat.settings.get('API_User_Limit')) { ...
userFilter.active = true; } const users = RocketChat.models.Users.find(userFilter).fetch(); const now = new Date(); users.forEach(function(user) { const subscription = RocketChat.models.Subscriptions.findOneByRoomIdAndUserId(rid, user._id); if (subscription != null) { return; } Roc...
}); } const userFilter = {}; if (activeUsersOnly === true) {
random_line_split
addAllUserToRoom.js
Meteor.methods({
(rid, activeUsersOnly = false) { check (rid, String); check (activeUsersOnly, Boolean); if (RocketChat.authz.hasRole(this.userId, 'admin') === true) { const userCount = RocketChat.models.Users.find().count(); if (userCount > RocketChat.settings.get('API_User_Limit')) { throw new Meteor.Error('error-us...
addAllUserToRoom
identifier_name
addAllUserToRoom.js
Meteor.methods({ addAllUserToRoom(rid, activeUsersOnly = false) { check (rid, String); check (activeUsersOnly, Boolean); if (RocketChat.authz.hasRole(this.userId, 'admin') === true) { const userCount = RocketChat.models.Users.find().count(); if (userCount > RocketChat.settings.get('API_User_Limit')) { ...
}, });
{ throw (new Meteor.Error(403, 'Access to Method Forbidden', { method: 'addAllToRoom', })); }
conditional_block
memebot.py
, file_path) return img elif ('imgur.com' in img_url): # Imgur try: client = ImgurClient(IMGUR_CLIENT, IMGUR_CLIENT_SECRET) except BaseException as e: print ('[EROR] Error while authenticating with Imgur:', str(e)) return # Working demo of regex: https://regex101.com/r/G29uGl/2 regex = r"(?:.*)imgu...
else: return imgur_file else: print('[EROR] Could not identify Imgur image/gallery ID in this URL:', img_url) return elif ('gfycat.com' in img_url): # Gfycat gfycat_name = os.path.basename(urllib.parse.urlsplit(img_url).path) client = GfycatClient() gfycat_info = client.query_gfy(gfycat_name) #...
print('[EROR] Imgur has not processed a GIF version of this link, so it can not be posted') img.close() # Delete the image try: os.remove(imgur_file) except BaseException as e: print ('[EROR] Error while deleting media file:', str(e)) return
conditional_block
memebot.py
try: client = ImgurClient(IMGUR_CLIENT, IMGUR_CLIENT_SECRET) except BaseException as e: print ('[EROR] Error while authenticating with Imgur:', str(e)) return # Working demo of regex: https://regex101.com/r/G29uGl/2 regex = r"(?:.*)imgur\.com(?:\/gallery\/|\/a\/|\/)(.*?)(?:\/.*|\.|$)" m = re.search(...
if any(s in img_url for s in ('i.redd.it', 'i.reddituploads.com')): file_name = os.path.basename(urllib.parse.urlsplit(img_url).path) file_extension = os.path.splitext(img_url)[-1].lower() # Fix for issue with i.reddituploads.com links not having a file extension in the URL if not file_extension: file_extens...
identifier_body
memebot.py
file_extension = file_extension.replace('.gifv', '.gif') file_name = file_name.replace('.gifv', '.gif') img_url = img_url.replace('.gifv', '.gif') # Download the file file_path = IMAGE_DIR + '/' + file_name print('[ OK ] Downloading file at URL ' + img_url + ' to ' + file_path + ', file type identified a...
# When Tweepy adds support for video uploads, we can use grab the MP4 versions if (file_extension == '.gifv'):
random_line_split
memebot.py
(img_url, file_path): resp = requests.get(img_url, stream=True) if resp.status_code == 200: with open(file_path, 'wb') as image_file: for chunk in resp: image_file.write(chunk) # Return the path of the image, which is always the same since we just overwrite images return file_path else: print('[EROR] ...
save_file
identifier_name
mrp_byproduct.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
def onchange_uom(self, cr, uid, ids, product_id, product_uom, context=None): res = {'value':{}} if not product_uom or not product_id: return res product = self.pool.get('product.product').browse(cr, uid, product_id, context=context) uom = self.pool.get('product.uom').br...
""" Changes UoM if product_id changes. @param product_id: Changed product_id @return: Dictionary of changed values """ if product_id: prod = self.pool.get('product.product').browse(cr, uid, product_id, context=context) v = {'product_uom': prod.uom_id.id} ...
identifier_body
mrp_byproduct.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
'subproduct_type': 'variable', 'product_qty': lambda *a: 1.0, } def onchange_product_id(self, cr, uid, ids, product_id, context=None): """ Changes UoM if product_id changes. @param product_id: Changed product_id @return: Dictionary of changed values """ i...
'bom_id': fields.many2one('mrp.bom', 'BoM', ondelete='cascade'), } _defaults={
random_line_split
mrp_byproduct.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
product = self.pool.get('product.product').browse(cr, uid, product_id, context=context) uom = self.pool.get('product.uom').browse(cr, uid, product_uom, context=context) if uom.category_id.id != product.uom_id.category_id.id: res['warning'] = {'title': _('Warning'), 'message': _('The...
return res
conditional_block
mrp_byproduct.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
(osv.osv_memory): _inherit = 'change.production.qty' def _update_product_to_produce(self, cr, uid, prod, qty, context=None): bom_obj = self.pool.get('mrp.bom') move_lines_obj = self.pool.get('stock.move') prod_obj = self.pool.get('mrp.production') for m in prod.move_created_ids:...
change_production_qty
identifier_name
bug_char.rs
#include "shared.rsh" char rand_sc1_0, rand_sc1_1; char2 rand_sc2_0, rand_sc2_1; char min_rand_sc1_sc1; char2 min_rand_sc2_sc2; static bool test_bug_char() { bool failed = false; rsDebug("rand_sc2_0.x: ", rand_sc2_0.x); rsDebug("rand_sc2_0.y: ", rand_sc2_0.y); rsDebug("rand_sc2_1.x: ", rand_sc2_1.x)...
rsDebug("broken", 'y'); temp_sc2 = min( rand_sc2_0, rand_sc2_1 ); if (temp_sc2.x != min_rand_sc2_sc2.x || temp_sc2.y != min_rand_sc2_sc2.y) { failed = true; } return failed; } void bug_char_test() { bool failed = false; failed |= test_bug_char(); if (failed) { ...
{ rsDebug("temp_sc1", temp_sc1); failed = true; }
conditional_block
bug_char.rs
#include "shared.rsh" char rand_sc1_0, rand_sc1_1; char2 rand_sc2_0, rand_sc2_1; char min_rand_sc1_sc1; char2 min_rand_sc2_sc2; static bool test_bug_char() { bool failed = false; rsDebug("rand_sc2_0.x: ", rand_sc2_0.x); rsDebug("rand_sc2_0.y: ", rand_sc2_0.y); rsDebug("rand_sc2_1.x: ", rand_sc2_1.x)...
if (failed) { rsSendToClientBlocking(RS_MSG_TEST_FAILED); } else { rsSendToClientBlocking(RS_MSG_TEST_PASSED); } }
void bug_char_test() { bool failed = false; failed |= test_bug_char();
random_line_split
GetClicksForLink.py
# -*- coding: utf-8 -*- ############################################################################### # # GetClicksForLink # Returns the number of clicks on a single Bitly link. # # Python versions 2.6, 2.7, 3.x # # Copyright 2014, Temboo Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you...
(self, value): """ Set the value of the UnitName input for this Choreo. ((optional, string) The unit of time that corresponds to query you want to run. Accepted values are: minute, hour, day, week, month, and day. Defaults to "day".) """ super(GetClicksForLinkInputSet, self)._set_input('...
set_UnitName
identifier_name
GetClicksForLink.py
# -*- coding: utf-8 -*- ############################################################################### # # GetClicksForLink # Returns the number of clicks on a single Bitly link. # # Python versions 2.6, 2.7, 3.x # # Copyright 2014, Temboo Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you...
def _make_result_set(self, result, path): return GetClicksForLinkResultSet(result, path) def _make_execution(self, session, exec_id, path): return GetClicksForLinkChoreographyExecution(session, exec_id, path) class GetClicksForLinkInputSet(InputSet): """ An InputSet with methods appr...
return GetClicksForLinkInputSet()
identifier_body
GetClicksForLink.py
# -*- coding: utf-8 -*- ############################################################################### # # GetClicksForLink # Returns the number of clicks on a single Bitly link. # # Python versions 2.6, 2.7, 3.x # # Copyright 2014, Temboo Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you...
set of Temboo credentials, must be supplied. """ super(GetClicksForLink, self).__init__(temboo_session, '/Library/Bitly/LinkMetrics/GetClicksForLink') def new_input_set(self): return GetClicksForLinkInputSet() def _make_result_set(self, result, path): return GetClicksF...
random_line_split
misc.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use libc::{c_float, c_int}; use cast::GTK_MISC; use ffi; pub trait MiscTrait: ::WidgetTrait ...
(&self, x_align: f32, y_align: f32) -> () { unsafe { ffi::gtk_misc_set_alignment(GTK_MISC(self.unwrap_widget()), x_align as c_float, y_align as c_float); } } fn set_padding(&self, x_pad: i32, y_pad: i32) -> () { unsafe { ffi::gtk_misc_set_padding(GTK_MISC(self.un...
set_alignment
identifier_name
misc.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use libc::{c_float, c_int}; use cast::GTK_MISC; use ffi; pub trait MiscTrait: ::WidgetTrait ...
(x as i32, y as i32) } }
random_line_split
misc.rs
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use libc::{c_float, c_int}; use cast::GTK_MISC; use ffi; pub trait MiscTrait: ::WidgetTrait ...
fn get_alignment(&self) -> (f32, f32) { let mut x: c_float = 0.; let mut y: c_float = 0.; unsafe { ffi::gtk_misc_get_alignment(GTK_MISC(self.unwrap_widget()), &mut x, &mut y); } (x as f32, y as f32) } fn get_padding(&self) -> (i32, i32) { let mu...
{ unsafe { ffi::gtk_misc_set_padding(GTK_MISC(self.unwrap_widget()), x_pad as c_int, y_pad as c_int); } }
identifier_body
setLeftFeature.ts
import {ColumnGroupChild} from "../../entities/columnGroupChild"; import {Utils as _} from "../../utils"; import {Column} from "../../entities/column"; export class SetLeftFeature { private columnOrGroup: ColumnGroupChild; private eCell: HTMLElement; private destroyFunctions: (()=>void)[] = []; ...
this.onLeftChanged(); } private onLeftChanged(): void { var newLeft = this.columnOrGroup.getLeft(); if (_.exists(newLeft)) { this.eCell.style.left = this.columnOrGroup.getLeft() + 'px'; } else { this.eCell.style.left = ''; } } ...
random_line_split
setLeftFeature.ts
import {ColumnGroupChild} from "../../entities/columnGroupChild"; import {Utils as _} from "../../utils"; import {Column} from "../../entities/column"; export class SetLeftFeature { private columnOrGroup: ColumnGroupChild; private eCell: HTMLElement; private destroyFunctions: (()=>void)[] = []...
else { this.eCell.style.left = ''; } } public destroy(): void { this.destroyFunctions.forEach( (func)=> { func(); }); } }
{ this.eCell.style.left = this.columnOrGroup.getLeft() + 'px'; }
conditional_block
setLeftFeature.ts
import {ColumnGroupChild} from "../../entities/columnGroupChild"; import {Utils as _} from "../../utils"; import {Column} from "../../entities/column"; export class SetLeftFeature { private columnOrGroup: ColumnGroupChild; private eCell: HTMLElement; private destroyFunctions: (()=>void)[] = []...
(columnOrGroup: ColumnGroupChild, eCell: HTMLElement) { this.columnOrGroup = columnOrGroup; this.eCell = eCell; this.init(); } private init(): void { var listener = this.onLeftChanged.bind(this); this.columnOrGroup.addEventListener(Column.EVENT_LEFT_CHANGED...
constructor
identifier_name
drag-proxy.js
-error"); const stack_1 = require("../items/stack"); const event_emitter_1 = require("../utils/event-emitter"); const jquery_legacy_1 = require("../utils/jquery-legacy"); const types_1 = require("../utils/types"); const utils_1 = require("../utils/utils"); /** * This class creates a temporary container * for the comp...
this._element.remove(); this._layoutManager.emit('itemDropped', this._componentItem); if (this._componentItemFocused && droppedComponentItem !== undefined) { droppedComponentItem.focus(); } } /** * Updates the Drag Proxy's dimensions * @internal */ ...
{ this._componentItem.destroy(); // contentItem children are now destroyed as well }
conditional_block
drag-proxy.js
/internal-error"); const stack_1 = require("../items/stack"); const event_emitter_1 = require("../utils/event-emitter"); const jquery_legacy_1 = require("../utils/jquery-legacy"); const types_1 = require("../utils/types"); const utils_1 = require("../utils/utils"); /** * This class creates a temporary container * for...
* @internal */ constructor(x, y, _dragListener, _layoutManager, _componentItem, _originalParent) { super(); this._dragListener = _dragListener; this._layoutManager = _layoutManager; this._componentItem = _componentItem; this._originalParent = _originalParent; ...
class DragProxy extends event_emitter_1.EventEmitter { /** * @param x - The initial x position * @param y - The initial y position
random_line_split
drag-proxy.js
-error"); const stack_1 = require("../items/stack"); const event_emitter_1 = require("../utils/event-emitter"); const jquery_legacy_1 = require("../utils/jquery-legacy"); const types_1 = require("../utils/types"); const utils_1 = require("../utils/utils"); /** * This class creates a temporary container * for the comp...
(offsetX, offsetY, event) { const x = event.pageX; const y = event.pageY; if (!this._layoutManager.layoutConfig.settings.constrainDragToContainer) { this.setDropPosition(x, y); } else { const isWithinContainer = x > this._minX && x < this._maxX && y > this...
onDrag
identifier_name
drag-proxy.js
-error"); const stack_1 = require("../items/stack"); const event_emitter_1 = require("../utils/event-emitter"); const jquery_legacy_1 = require("../utils/jquery-legacy"); const types_1 = require("../utils/types"); const utils_1 = require("../utils/utils"); /** * This class creates a temporary container * for the comp...
/** * Callback when the drag has finished. Determines the drop area * and adds the child to it * @internal */ onDrop() { const dropTargetIndicator = this._layoutManager.dropTargetIndicator; if (dropTargetIndicator === null) { throw new internal_error_1.Unexpected...
{ this._element.style.left = utils_1.numberToPixels(x); this._element.style.top = utils_1.numberToPixels(y); this._area = this._layoutManager.getArea(x, y); if (this._area !== null) { this._lastValidArea = this._area; this._area.contentItem.highlightDropZone(x, y,...
identifier_body
regex_map.py
#coding=utf-8 ''' Created on 2013年7月13日 @author: huiyugeng ''' import types import ndb import regex ''' 载入解析映射 ''' def load_map(map_file): map_struct = ndb.load(map_file) map_list = ndb.execute(map_struct, 'select: map') return map_list ''' 规则匹配及字段映射 ''' def reflect(map_list,...
for _map_index in map_index_list: try: if _map_index.has_key('index') and _map_index.has_key('key'): map_index[_map_index.get('index')] = _map_index.get('key') except: pass return map_index def __is_match(match, line): result = False ...
map_index = {} map_index_list = map_item.get('item') if map_item.has_key('item') else []
random_line_split
regex_map.py
#coding=utf-8 ''' Created on 2013年7月13日 @author: huiyugeng ''' import types import ndb import regex ''' 载入解析映射 ''' def load_map(map_file): map_struct = ndb.load(map_file) map_list = ndb.execute(map_struct, 'select: map') return map_list ''' 规则匹配及字段映射 ''' def reflect(map_list,...
[] map_index = {} if line == None: return None line = line.strip() for map_item in map_list: rule_type = map_item.get('type').strip() if map_item.has_key('type') else '' if rule_type == '': rule_type = 'regex' pattern = map_item.get(...
list =
identifier_name
regex_map.py
#coding=utf-8 ''' Created on 2013年7月13日 @author: huiyugeng ''' import types import ndb import regex ''' 载入解析映射 ''' def load_map(map_file): map_struct = ndb.load(map_file) map_list = ndb.execute(map_struct, 'select: map') return map_list ''' 规则匹配及字段映射 ''' def reflect(map_list,...
= 'split': match = map_item.get('match') if map_item.has_key('match') else '' if __is_match(match, line): value_list = line.split(pattern) map_index = __build_map_index(map_item) break map_value = {} index = 1 for ...
line) map_index = __build_map_index(map_item) break elif rule_type =
conditional_block
regex_map.py
#coding=utf-8 ''' Created on 2013年7月13日 @author: huiyugeng ''' import types import ndb import regex ''' 载入解析映射 ''' def load_map(map_file): map_struct = ndb.load(map_file) map_list = ndb.execute(map_struct, 'select: map') return map_list ''' 规则匹配及字段映射 ''' def reflect(map_list,...
match = map_item.get('match') if map_item.has_key('match') else '' if __is_match(match, line): value_list = line.split(pattern) map_index = __build_map_index(map_item) break map_value = {} index = 1 for value in val...
if line == None: return None line = line.strip() for map_item in map_list: rule_type = map_item.get('type').strip() if map_item.has_key('type') else '' if rule_type == '': rule_type = 'regex' pattern = map_item.get('pattern') if map_item....
identifier_body
searx.py
#!/usr/bin/python # -*- coding: utf-8 -*- import unicodedata from urlparse import urlparse from threading import Thread import httplib, sys from Queue import Queue import itertools import codecs import csv import sys import ssl import re if len(sys.argv) < 3: print "Usage: %s <csv database> <out csv>" % (sys.argv...
(csv.DictReader): def __init__(self, f, encoding="utf-8", fieldnames=None, **kwds): csv.DictReader.__init__(self, f, fieldnames=fieldnames, **kwds) self.reader = UnicodeCsvReader(f, encoding=encoding, **kwds) # Remove particles and parenthesis in names def cleanNames(names): filtered_names = [...
UnicodeDictReader
identifier_name
searx.py
#!/usr/bin/python # -*- coding: utf-8 -*- import unicodedata from urlparse import urlparse from threading import Thread import httplib, sys from Queue import Queue import itertools import codecs import csv import sys import ssl import re if len(sys.argv) < 3: print "Usage: %s <csv database> <out csv>" % (sys.argv...
class UnicodeDictReader(csv.DictReader): def __init__(self, f, encoding="utf-8", fieldnames=None, **kwds): csv.DictReader.__init__(self, f, fieldnames=fieldnames, **kwds) self.reader = UnicodeCsvReader(f, encoding=encoding, **kwds) # Remove particles and parenthesis in names def cleanNames(names...
return self.csv_reader.line_num
identifier_body
searx.py
#!/usr/bin/python # -*- coding: utf-8 -*- import unicodedata from urlparse import urlparse from threading import Thread import httplib, sys from Queue import Queue import itertools import codecs import csv import sys import ssl import re if len(sys.argv) < 3: print "Usage: %s <csv database> <out csv>" % (sys.argv...
return filtered_names # Strips accents from a unicode string def stripAccents(s): return ''.join(c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn') # Generates all 2+ permutations of the given array def allCombinations(tab): out = [] for n in range(2, len(tab) + 1): ...
filtered_names.append(word)
conditional_block
searx.py
#!/usr/bin/python # -*- coding: utf-8 -*- import unicodedata from urlparse import urlparse from threading import Thread import httplib, sys from Queue import Queue
import re if len(sys.argv) < 3: print "Usage: %s <csv database> <out csv>" % (sys.argv[0]) exit() # Unicode CSV reader # http://stackoverflow.com/a/6187936 class UnicodeCsvReader(object): def __init__(self, f, encoding="utf-8", **kwargs): self.csv_reader = csv.reader(f, **kwargs) self.enco...
import itertools import codecs import csv import sys import ssl
random_line_split
rem.rs
#![feature(core, core_simd)] extern crate core; #[cfg(test)] mod tests { use core::simd::u16x8; // #[simd] // #[derive(Copy, Clone, Debug)] // #[repr(C)] // pub struct u16x8(pub u16, pub u16, pub u16, pub u16, // pub u16, pub u16, pub u16, pub u16); #[test] fn
() { let x: u16x8 = u16x8( 0, 1, 2, 3, 4, 5, 6, 7 ); let y: u16x8 = u16x8( 2, 2, 2, 2, 2, 2, 2, 2 ); let z: u16x8 = x % y; let result: String = format!("{:?}", z); assert_eq!(result, "u16x8(\ 0, 1, 0, 1, 0, 1, 0, 1\ )".to_string()); } }
rem_test1
identifier_name
rem.rs
#![feature(core, core_simd)] extern crate core; #[cfg(test)] mod tests { use core::simd::u16x8; // #[simd] // #[derive(Copy, Clone, Debug)] // #[repr(C)] // pub struct u16x8(pub u16, pub u16, pub u16, pub u16, // pub u16, pub u16, pub u16, pub u16); #[test] fn rem_tes...
}
{ let x: u16x8 = u16x8( 0, 1, 2, 3, 4, 5, 6, 7 ); let y: u16x8 = u16x8( 2, 2, 2, 2, 2, 2, 2, 2 ); let z: u16x8 = x % y; let result: String = format!("{:?}", z); assert_eq!(result, "u16x8(\ 0, 1, 0, 1, 0, 1, 0, 1\ )".to_string()); }
identifier_body
rem.rs
#![feature(core, core_simd)] extern crate core; #[cfg(test)] mod tests { use core::simd::u16x8; // #[simd] // #[derive(Copy, Clone, Debug)] // #[repr(C)] // pub struct u16x8(pub u16, pub u16, pub u16, pub u16, // pub u16, pub u16, pub u16, pub u16); #[test] fn rem_tes...
)".to_string()); } }
let z: u16x8 = x % y; let result: String = format!("{:?}", z); assert_eq!(result, "u16x8(\ 0, 1, 0, 1, 0, 1, 0, 1\
random_line_split
konami.js
window.onload = function() { var artwork = document.getElementById("j5-artwork"); if (!artwork) { return; } var original = artwork.firstElementChild; var payload = artwork.lastElementChild; var audio = document.createElement("audio"); var sequence = [38, 38, 40, 40, 37, 39, 37, 39, 66, 65]; var pr...
() { pressed.length = 0; } function swap(show) { var hide = show === original ? payload : original; hide.classList.remove("vanishIn"); hide.classList.add("vanishOut"); show.classList.remove("vanishOut"); show.classList.add("vanishIn"); if (show === payload) { timeout(250, functi...
reset
identifier_name
konami.js
window.onload = function() { var artwork = document.getElementById("j5-artwork"); if (!artwork) { return;
var original = artwork.firstElementChild; var payload = artwork.lastElementChild; var audio = document.createElement("audio"); var sequence = [38, 38, 40, 40, 37, 39, 37, 39, 66, 65]; var pressed = []; payload.srcset = "img/trick-or-treat.png"; payload.classList.add("j5"); if (!artwork) { return;...
}
random_line_split
konami.js
window.onload = function() { var artwork = document.getElementById("j5-artwork"); if (!artwork) { return; } var original = artwork.firstElementChild; var payload = artwork.lastElementChild; var audio = document.createElement("audio"); var sequence = [38, 38, 40, 40, 37, 39, 37, 39, 66, 65]; var pr...
function timeout(time, callback) { if (timeout.current) { clearTimeout(timeout.current); } timeout.current = setTimeout(callback, time); } };
{ var hide = show === original ? payload : original; hide.classList.remove("vanishIn"); hide.classList.add("vanishOut"); show.classList.remove("vanishOut"); show.classList.add("vanishIn"); if (show === payload) { timeout(250, function() { audio.onended = function() { re...
identifier_body
konami.js
window.onload = function() { var artwork = document.getElementById("j5-artwork"); if (!artwork)
var original = artwork.firstElementChild; var payload = artwork.lastElementChild; var audio = document.createElement("audio"); var sequence = [38, 38, 40, 40, 37, 39, 37, 39, 66, 65]; var pressed = []; payload.srcset = "img/trick-or-treat.png"; payload.classList.add("j5"); if (!artwork) { return...
{ return; }
conditional_block
models.py
import logging from django.conf import settings from django.db import models from mkt.site.mail import send_mail from mkt.site.models import ModelBase from mkt.users.models import UserProfile from mkt.webapps.models import Webapp from mkt.websites.models import Website log = logging.getLogger('z.abuse') class Abu...
elif self.user: type_ = 'User' else: type_ = 'Website' subject = u'[%s] Abuse Report for %s' % (type_, obj.name) msg = u'%s reported abuse for %s (%s%s).\n\n%s' % ( user_name, obj.name, settings.SITE_URL, obj.get_url_path(), self.message) ...
type_ = 'App'
conditional_block
models.py
import logging from django.conf import settings from django.db import models from mkt.site.mail import send_mail from mkt.site.models import ModelBase from mkt.users.models import UserProfile from mkt.webapps.models import Webapp from mkt.websites.models import Website log = logging.getLogger('z.abuse') class Abu...
def send(self): obj = self.object if self.reporter: user_name = '%s (%s)' % (self.reporter.name, self.reporter.email) else: user_name = 'An anonymous coward' if self.addon: type_ = 'App' elif self.user: type_ = 'User' e...
reporter = models.ForeignKey(UserProfile, null=True, blank=True, related_name='abuse_reported') ip_address = models.CharField(max_length=255, default='0.0.0.0') # An abuse report can be for an addon, a user, or a website. Only one of # these should be null. addon = model...
identifier_body
models.py
import logging from django.conf import settings from django.db import models from mkt.site.mail import send_mail from mkt.site.models import ModelBase from mkt.users.models import UserProfile from mkt.webapps.models import Webapp from mkt.websites.models import Website log = logging.getLogger('z.abuse') class Abu...
(cls, threshold, period, addon_id=None): """ Returns AbuseReport objects for the given threshold over the given time period (in days). Filters by addon_id if provided. E.g. Greater than 5 abuse reports for all webapps in the past 7 days. """ abuse_sql = [''' ...
recent_high_abuse_reports
identifier_name
models.py
import logging from django.conf import settings from django.db import models from mkt.site.mail import send_mail from mkt.site.models import ModelBase from mkt.users.models import UserProfile from mkt.webapps.models import Webapp from mkt.websites.models import Website log = logging.getLogger('z.abuse') class Abu...
if self.addon: type_ = 'App' elif self.user: type_ = 'User' else: type_ = 'Website' subject = u'[%s] Abuse Report for %s' % (type_, obj.name) msg = u'%s reported abuse for %s (%s%s).\n\n%s' % ( user_name, obj.name, settings.SITE_URL...
random_line_split
201611680890-5.10.py
# coding: utf-8 # In[ ]: #练习一:文本加密解密(先看有关ASCII码的相关知识以及码表,查维基百科或百度百科) #输入:一个txt文件(假设全是字母的英文词,每个单词之间用单个空格隔开,假设单词最长为10个字母) #加密:得到每个单词的长度 n ,随机生成一个9位的数字,将 n-1 与这个9位的数字连接,形成一个10位的数字, #作为密匙 key 。依照 key 中各个数字对单词中每一个对应位置的字母进行向后移位(例:如过 key 中某数字为 2 , #对应该位置的字母为 a ,加密则应移位成 c ,如果超过 z ,则回到 A 处继续移位),对长度不到10的单词,移位后, #将移位后的单词利用随机字母补...
fh = open(r'd:\temp\words.txt') text = fh.read() fh.close() print(len(text)) print(text)
#解密:给定该文本文件并给定key(10位数字),恢复原来的文本。 #(提示,利用 ord() 及 chr() 函数, ord(x) 是取得字符 x 的ASCII码, chr(n) 是取得整数n(代表ASCII码)对应的字符。 #例: ord(a) 的值为 97 , chr(97) 的值为 'a' ,因字母 a 的ASCII码值为 97 。)
random_line_split
refs.ts
string, public componentType: Type<any>, viewDefFactory: ViewDefinitionFactory, private _inputs: {[propName: string]: string}|null, private _outputs: {[propName: string]: string}, public ngContentSelectors: string[]) { // Attention: this ctor is called as top level function. // Putting any logic in...
} get outputs() { const outputsArr: {propName: string, templateName: string}[] = []; for (let propName in this._outputs) { const templateName = this._outputs[propName]; outputsArr.push({propName, templateName}); } return outputsArr; } /** * Creates a new component. */ creat...
return inputsArr;
random_line_split
refs.ts
); } return new ComponentRef_(view, new ViewRef_(view), component); } } class ComponentRef_ extends ComponentRef<any> { private _elDef: NodeDef; constructor(private _view: ViewData, private _viewRef: ViewRef, private _component: any) { super(); this._elDef = this._view.def.nodes[0]; } get lo...
{ this.delegate.appendChild(parent, el); }
conditional_block
refs.ts
const componentNodeIndex = viewDef.nodes[0].element !.componentProvider !.index; const view = Services.createRootView( injector, projectableNodes || [], rootSelectorOrNode, viewDef, ngModule, EMPTY_CONTEXT); const component = asProviderData(view, componentNodeIndex).instance; if (rootSelectorOrN...
RendererAdapter
identifier_name
refs.ts
, public componentType: Type<any>, viewDefFactory: ViewDefinitionFactory, private _inputs: {[propName: string]: string}|null, private _outputs: {[propName: string]: string}, public ngContentSelectors: string[]) { // Attention: this ctor is called as top level function. // Putting any logic in here w...
reattach(): void { this._view.state |= ViewState.Attached; } onDestroy(callback: Function) { if (!this._view.disposables) { this._view.disposables = []; } this._view.disposables.push(<any>callback); } destroy() { if (this._appRef) { this._appRef.detachView(this); } else if (th...
{ Services.checkNoChangesView(this._view); }
identifier_body
duckduckgo2html.py
#!/usr/bin/env python3 """Retrieve results from the DuckDuckGo zero-click API in simple HTML format.""" import json as jsonlib import logging import re import urllib.request, urllib.error, urllib.parse __version__ = (1, 0, 0) def results2html(results, results_priority=None, max_number_of_results=None, ...
(self): contents = [x.as_html() for x in self.content] return '<br>'.join(x for x in contents if x) if __name__ == '__main__': import argparse import sys parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( 'query', nargs='*', help='the s...
as_html
identifier_name
duckduckgo2html.py
#!/usr/bin/env python3 """Retrieve results from the DuckDuckGo zero-click API in simple HTML format.""" import json as jsonlib import logging import re import urllib.request, urllib.error, urllib.parse __version__ = (1, 0, 0) def results2html(results, results_priority=None, max_number_of_results=None, ...
html_list = [] if self.heading: html_list.append('<b>{0}</b>'.format(self.heading)) if self.html: html_list.append(self.html) elif self.text: html_list.append(self.text) if self.url: html_list.append(_html_url(self.url, self.source)...
def is_complete(self): return True if self.html or self.text else False def as_html(self):
random_line_split
duckduckgo2html.py
#!/usr/bin/env python3 """Retrieve results from the DuckDuckGo zero-click API in simple HTML format.""" import json as jsonlib import logging import re import urllib.request, urllib.error, urllib.parse __version__ = (1, 0, 0) def results2html(results, results_priority=None, max_number_of_results=None, ...
html = results2html(search(query)) if html: print(html) else: logging.warning('No results found')
conditional_block
duckduckgo2html.py
#!/usr/bin/env python3 """Retrieve results from the DuckDuckGo zero-click API in simple HTML format.""" import json as jsonlib import logging import re import urllib.request, urllib.error, urllib.parse __version__ = (1, 0, 0) def results2html(results, results_priority=None, max_number_of_results=None, ...
def as_html(self): return self.text.replace('\n', '<br>').replace('\r', '') class Definition(_ResultItemBase): def __init__(self, json): super().__init__('Definition') self.text = json['Definition'] self.url = json['DefinitionURL'] self.source = json['DefinitionSource...
return True if self.text else False
identifier_body
forms.py
# !/usr/bin/env python # -*- coding: utf-8 -*- # created by restran on 2016/1/2 from __future__ import unicode_literals, absolute_import from django import forms from django.utils.translation import ugettext_lazy as _ from .models import * from common.forms import BaseModelForm logger = logging.getLogger(__name__) ...
t.objects.filter(unique_name=unique_name).values('id') if len(sites) > 0: raise forms.ValidationError(_('已存在相同名称的 Endpoint')) return unique_name EndpointForm.base_fields.keyOrder = [ 'name', 'unique_name', 'is_builtin', 'url', 'prefix_uri', 'enable_acl', 'async_http_connect...
r(_('已存在相同名称的 Endpoint')) else: sites = Endpoin
conditional_block
forms.py
# !/usr/bin/env python # -*- coding: utf-8 -*- # created by restran on 2016/1/2 from __future__ import unicode_literals, absolute_import from django import forms from django.utils.translation import ugettext_lazy as _ from .models import * from common.forms import BaseModelForm logger = logging.getLogger(__name__) ...
_fields.keyOrder = [ 'name', 'memo', 'url', 'enable', 'app_id', 'secret_key', 'login_auth_url', 'access_token_ex', 'refresh_token_ex', 'sms_login_auth_url', 'sms_change_password_url', 'change_password_url' ] # # class ClientEndpointForm(BaseModelForm): # class Meta: # model = Client # ...
class Meta: model = Client fields = ('name', 'memo', 'enable', "app_id", 'secret_key', 'login_auth_url', 'access_token_ex', 'refresh_token_ex', 'sms_login_auth_url', 'change_password_url', 'sms_change_password_url') def clean_refresh_token_ex(self): acces...
identifier_body
forms.py
# !/usr/bin/env python # -*- coding: utf-8 -*- # created by restran on 2016/1/2 from __future__ import unicode_literals, absolute_import from django import forms from django.utils.translation import ugettext_lazy as _ from .models import * from common.forms import BaseModelForm logger = logging.getLogger(__name__) ...
(self): access_token_ex = self.cleaned_data['access_token_ex'] refresh_token_ex = self.cleaned_data['refresh_token_ex'] if access_token_ex >= refresh_token_ex: raise forms.ValidationError(_('refresh_token 的过期时间不能小于 access_token')) return refresh_token_ex ClientForm.base_fi...
clean_refresh_token_ex
identifier_name