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
collection.rs
use cobalt_config::Frontmatter; use cobalt_config::SortOrder; use liquid; use crate::error::*; #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] pub struct Collection { pub title: kstring::KString, pub slug: kstring::KString, pub description: Option<kstring::KString>, pub dir: cobalt_config::Re...
(&self) -> liquid::Object { let mut attributes: liquid::Object = vec![ ( "title".into(), liquid::model::Value::scalar(self.title.clone()), ), ( "slug".into(), liquid::model::Value::scalar(self.slug.clone()), ...
attributes
identifier_name
collection.rs
use cobalt_config::Frontmatter; use cobalt_config::SortOrder; use liquid; use crate::error::*; #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] pub struct Collection { pub title: kstring::KString, pub slug: kstring::KString, pub description: Option<kstring::KString>, pub dir: cobalt_config::Re...
if let Some(jsonfeed) = self.jsonfeed.as_ref() { attributes.insert( "jsonfeed".into(), liquid::model::Value::scalar(jsonfeed.as_str().to_owned()), ); } attributes } }
{ attributes.insert( "rss".into(), liquid::model::Value::scalar(rss.as_str().to_owned()), ); }
conditional_block
collection.rs
use cobalt_config::Frontmatter; use cobalt_config::SortOrder; use liquid; use crate::error::*; #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] pub struct Collection { pub title: kstring::KString, pub slug: kstring::KString, pub description: Option<kstring::KString>, pub dir: cobalt_config::Re...
attributes.insert( "jsonfeed".into(), liquid::model::Value::scalar(jsonfeed.as_str().to_owned()), ); } attributes } }
"rss".into(), liquid::model::Value::scalar(rss.as_str().to_owned()), ); } if let Some(jsonfeed) = self.jsonfeed.as_ref() {
random_line_split
lib.rs
https://github.com/Byron/google-apis-rs/tree/master/gen/adsensehost4d1). //! # Features //! //! Handle the following *Resources* with ease from the central [hub](struct.AdSenseHost.html) ... //! //! * [accounts](struct.Account.html) //! * [*adclients get*](struct.AccountAdclientGetCall.html), [*adclients list*](str...
//! let r = hub.accounts().adunits_get(...).doit() //! let r = hub.accounts().get(...).doit() //! let r = hub.accounts().adunits_list(...).doit() //! let r = hub.accounts().adunits_get_ad_code(...).doit() //! let r = hub.accounts().reports_generate(...).doit() //! let r = hub.accounts().adunits_delete(...).doit() //! l...
//! Or specifically ... //! //! ```ignore
random_line_split
export.py
from qtpy.QtWidgets import QFileDialog import logging import pandas as pd class Export: header = ['x0', 'y0', 'x1', 'y1', 'row_index', 'column_index', 'lock', 'active', 'fitting_confidence', 'd_spacing_value', 'd_spacing_err', 'sigma_value', 'sigma_err', 'i...
(item): return [item['val'], item['err']]
get_val_err_fixed
identifier_name
export.py
from qtpy.QtWidgets import QFileDialog import logging import pandas as pd class Export: header = ['x0', 'y0', 'x1', 'y1', 'row_index', 'column_index', 'lock', 'active', 'fitting_confidence', 'd_spacing_value', 'd_spacing_err', 'sigma_value', 'sigma_err', 'i...
class FormatTableForExport(object): pandas_data_frame = [] def __init__(self, table={}): pandas_table = [] for _key in table: _entry = table[_key] x0 = _entry['bin_coordinates']['x0'] y0 = _entry['bin_coordinates']['y0'] x1 = _entry['bin_coor...
logging.info("Exporting table") default_file_name = str(self.grand_parent.ui.normalized_folder.text()) + '_fitting_table.csv' table_file = QFileDialog.getSaveFileName(self.grand_parent, 'Select or Define Name of File!', ...
identifier_body
export.py
from qtpy.QtWidgets import QFileDialog import logging import pandas as pd class Export: header = ['x0', 'y0', 'x1', 'y1', 'row_index', 'column_index', 'lock', 'active', 'fitting_confidence', 'd_spacing_value', 'd_spacing_err', 'sigma_value', 'sigma_err', 'i...
[intensity_val, intensity_err] = FormatTableForExport.get_val_err_fixed(_entry['intensity']) [alpha_val, alpha_err] = FormatTableForExport.get_val_err_fixed(_entry['alpha']) [a1_val, a1_err] = FormatTableForExport.get_val_err_fixed(_entry['a1...
_entry = table[_key] x0 = _entry['bin_coordinates']['x0'] y0 = _entry['bin_coordinates']['y0'] x1 = _entry['bin_coordinates']['x1'] y1 = _entry['bin_coordinates']['y1'] row_index = _entry['row_index'] column_index = _entry['column_index'] ...
conditional_block
export.py
from qtpy.QtWidgets import QFileDialog import logging import pandas as pd class Export: header = ['x0', 'y0', 'x1', 'y1', 'row_index', 'column_index', 'lock', 'active', 'fitting_confidence', 'd_spacing_value', 'd_spacing_err', 'sigma_value', 'sigma_err', 'i...
default_file_name, "CSV (*.csv)") if table_file[0]: table_file = table_file[0] logging.info(f" table file selected: {table_file}") table_dictionary = self.grand_parent.march_tab...
random_line_split
borrowck-borrow-mut-base-ptr-in-aliasable-loc.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn foo3(t0: &mut &mut isize) { let t1 = &mut *t0; let p: &isize = &**t0; //~ ERROR cannot borrow **t1 = 22; } fn foo4(t0: & &mut isize) { let x: &mut isize = &mut **t0; //~ ERROR cannot borrow *x += 1; } fn main() { }
{ let t1 = t0; let p: &isize = &**t0; **t1 = 22; //~ ERROR cannot assign }
identifier_body
borrowck-borrow-mut-base-ptr-in-aliasable-loc.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 ...
// Example from src/middle/borrowck/doc.rs fn foo(t0: & &mut isize) { let t1 = t0; let p: &isize = &**t0; **t1 = 22; //~ ERROR cannot assign } fn foo3(t0: &mut &mut isize) { let t1 = &mut *t0; let p: &isize = &**t0; //~ ERROR cannot borrow **t1 = 22; } fn foo4(t0: & &mut isize) { let x: ...
// except according to those terms. // Test that attempt to reborrow an `&mut` pointer in an aliasable // location yields an error. //
random_line_split
borrowck-borrow-mut-base-ptr-in-aliasable-loc.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 ...
(t0: &mut &mut isize) { let t1 = &mut *t0; let p: &isize = &**t0; //~ ERROR cannot borrow **t1 = 22; } fn foo4(t0: & &mut isize) { let x: &mut isize = &mut **t0; //~ ERROR cannot borrow *x += 1; } fn main() { }
foo3
identifier_name
cabi_x86.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
2 => RetValue(Type::i16(ccx)), 4 => RetValue(Type::i32(ccx)), 8 => RetValue(Type::i64(ccx)), _ => RetPointer } } _ => { RetPointer } }; match strategy { ...
{ let mut arg_tys = Vec::new(); let ret_ty; if !ret_def { ret_ty = ArgType::direct(Type::void(ccx), None, None, None); } else if rty.kind() == Struct { // Returning a structure. Most often, this will use // a hidden first argument. On some platforms, though, // small str...
identifier_body
cabi_x86.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
for &t in atys.iter() { let ty = match t.kind() { Struct => { let size = llsize_of_alloc(ccx, t); if size == 0 { ArgType::ignore(t) } else { ArgType::indirect(t, Some(ByValAttribute)) } ...
{ ret_ty = ArgType::direct(rty, None, None, None); }
conditional_block
cabi_x86.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT.
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <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. use syntax::abi::{OsWin32, OsMacos}; use lib::llvm::*; use super::cabi::*; use super::c...
// // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
random_line_split
cabi_x86.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ RetValue(Type), RetPointer } let strategy = match ccx.sess().targ_cfg.os { OsWin32 | OsMacos => { match llsize_of_alloc(ccx, rty) { 1 => RetValue(Type::i8(ccx)), 2 => RetValue(Type::i16(ccx)), 4 => RetValue(Type::i32(ccx)...
Strategy
identifier_name
cairo_backend.py
pango.SCALE #print('@@ EXTENTS:', layout.get_pixel_extents()[1], spacing) extents = layout.get_pixel_extents()[1] # Get logical extents return [extents[0], extents[1], extents[2], extents[3], baseline] @staticmethod def draw_text(x, y, text, font, text_color, spacing, c): c.save() c.se...
.curve_to(*n) pp = n[4:6]
conditional_block
cairo_backend.py
elif ext == '.pdf': surf = cairo.PDFSurface(self.fname, W, H) elif ext in ('.ps', '.eps'): surf = cairo.PSSurface(self.fname, W, H) if ext == '.eps': surf.set_eps(True) else: # Bitmap surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, W, H) self.ctx = cairo.Context(surf) ct...
layout = pangocairo.create_layout(c) pctx = layout.get_context() fo = cairo.FontOptions() fo.set_antialias(cairo.ANTIALIAS_SUBPIXEL) pangocairo.context_set_font_options(pctx, fo) layout.set_font_description(font) layout.set_spacing(spacing * pango.SCALE) layout.set_text(p...
c.translate(x, y) if use_pygobject: status, attrs, plain_text, _ = pango.parse_markup(text, len(text), '\0')
random_line_split
cairo_backend.py
self, canvas, transparent=False): x0,y0,x1,y1 = canvas.bbox('all') self.markers = canvas.markers W = int((x1 - x0 + 2*self.padding) * self.scale) H = int((y1 - y0 + 2*self.padding) * self.scale) ext = os.path.splitext(self.fname)[1].lower() if ext == '.svg': surf = cairo.SVGSurface(sel...
ender(
identifier_name
cairo_backend.py
ext == '.pdf': surf = cairo.PDFSurface(self.fname, W, H) elif ext in ('.ps', '.eps'): surf = cairo.PSSurface(self.fname, W, H) if ext == '.eps': surf.set_eps(True) else: # Bitmap surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, W, H) self.ctx = cairo.Context(surf) ctx = s...
@staticmethod def cairo_text_bbox(text, font_params, spacing=0, scale=1.0): surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, 8, 8) ctx = cairo.Context(surf) # The scaling must match the final context. # If not there can be a mismatch between the computed extents here # and those generated for th...
eturn CairoSurface.cairo_text_bbox(text, font_params, spacing, self.scale)
identifier_body
image.rs
extern crate piston_window; extern crate find_folder; use piston_window::*;
.exit_on_esc(true) .opengl(opengl) .build() .unwrap(); let assets = find_folder::Search::ParentsThenKids(3, 3) .for_folder("assets").unwrap(); let rust_logo = assets.join("rust.png"); let rust_logo = Texture::from_path( &mut *window.factory.borrow_mut(), ...
fn main() { let opengl = OpenGL::V3_2; let window: PistonWindow = WindowSettings::new("piston: image", [300, 300])
random_line_split
image.rs
extern crate piston_window; extern crate find_folder; use piston_window::*; fn main()
clear([1.0; 4], g); image(&rust_logo, c.transform, g); }); } }
{ let opengl = OpenGL::V3_2; let window: PistonWindow = WindowSettings::new("piston: image", [300, 300]) .exit_on_esc(true) .opengl(opengl) .build() .unwrap(); let assets = find_folder::Search::ParentsThenKids(3, 3) .for_folder("assets").unwrap(); let rus...
identifier_body
image.rs
extern crate piston_window; extern crate find_folder; use piston_window::*; fn
() { let opengl = OpenGL::V3_2; let window: PistonWindow = WindowSettings::new("piston: image", [300, 300]) .exit_on_esc(true) .opengl(opengl) .build() .unwrap(); let assets = find_folder::Search::ParentsThenKids(3, 3) .for_folder("assets").unwrap(); let ...
main
identifier_name
formatter.rs
, } } // get an integer from pos, returning the number of bytes // consumed and the integer fn get_integer(s: &[u8], pos: usize) -> (usize, Option<i64>) { let (_, rest) = s.split_at(pos); let mut consumed: usize = 0; for b in rest { match *b as char { '0'...'9' => {} _ =...
{ self.thousands }
identifier_body
formatter.rs
| 'x' | 'X' | 'e' | 'E' | 'f' | 'F' | '%' | 's' | '?' => true, _ => false, } } // get an integer from pos, returning the number of bytes // consumed and the integer fn get_integer(s: &[u8], pos: usize) -> (usize, Option<i64>) { le...
c = match chars.next() { Some(c) => c, None => { break; } }; } let (identifier, rest) = s.split_at(consumed); let identifier = if found_colon { let (i, _) = identifier.split_at(identifier.len...
{ found_colon = true; break; }
conditional_block
formatter.rs
| 'x' | 'X' | 'e' | 'E' | 'f' | 'F' | '%' | 's' | '?' => true, _ => false, } } // get an integer from pos, returning the number of bytes // consumed and the integer fn get_integer(s: &[u8], pos: usize) -> (usize, Option<i64>) { le...
return Err(FmtError::Invalid("overflow error when parsing precision" .to_string())) } Some(v) => { format.precision = v; } } } else { // Not having...
let (consumed, val) = get_integer(rest, pos); if consumed != 0 { match val { None => {
random_line_split
formatter.rs
| 'x' | 'X' | 'e' | 'E' | 'f' | 'F' | '%' | 's' | '?' => true, _ => false, } } // get an integer from pos, returning the number of bytes // consumed and the integer fn get_integer(s: &[u8], pos: usize) -> (usize, Option<i64>) { le...
(s: &'a str, buff: &'b mut String) -> Result<Formatter<'a, 'b>> { let mut found_colon = false; let mut chars = s.chars(); let mut c = match chars.next() { Some(':') | None => { return Err(FmtError::Invalid("must specify identifier".to_string())) } ...
from_str
identifier_name
jumbles nontrobo.py
"""return a jumbled version of a string. eg, the lazy hamster is jumping becomes the lzay hmasetr si jmunipg shuffles insides of words. """ import random import string #okay, so this will be the jmuble algorythim #variables, passed #string_to_jumble = "" #yeah #jumble_mode = true # do u switch words of t...
#put the letters of the word into an array, and then switch 'em for word in string_words: #if the word is two long and mode is true switch 'em if (len(word) >= 0) and (len(word) <= 3) : if jumble_mode == True: #...
string_to_return = "" #New string string_words = [""] #array containing the words of the string current_word = [] #array containing the letters of the current word punctuation_ = [] #array containing the punctuation i = 0 j = 0 #put the words in an array ...
identifier_body
jumbles nontrobo.py
"""return a jumbled version of a string. eg, the lazy hamster is jumping becomes the lzay hmasetr si jmunipg shuffles insides of words. """ import random import string #okay, so this will be the jmuble algorythim #variables, passed #string_to_jumble = "" #yeah #jumble_mode = true # do u switch words of t...
#we should be at the last character now #print(i) print(len(word)+100) #jumble it #random.shuffle(current_word) #add to the new string for char in current_word: string_to_retu...
if i == 0: string_to_return += char #print(string_to_return) i = 1 #assert bluh WORKING continue #then put almost all of the word ...
conditional_block
jumbles nontrobo.py
"""return a jumbled version of a string. eg, the lazy hamster is jumping becomes the lzay hmasetr si jmunipg shuffles insides of words. """ import random import string #okay, so this will be the jmuble algorythim #variables, passed #string_to_jumble = "" #yeah #jumble_mode = true # do u switch words of t...
#otherwise add to the entry string_words[i] += char #print(string_words) THIS IS WORKING #put the letters of the word into an array, and then switch 'em for word in string_words: #if the word is two lo...
##make sure there's something to put it in! string_words.append("") else:
random_line_split
jumbles nontrobo.py
"""return a jumbled version of a string. eg, the lazy hamster is jumping becomes the lzay hmasetr si jmunipg shuffles insides of words. """ import random import string #okay, so this will be the jmuble algorythim #variables, passed #string_to_jumble = "" #yeah #jumble_mode = true # do u switch words of t...
(string_to_jumble, jumble_mode = True): #variables, internal string_to_return = "" #New string string_words = [""] #array containing the words of the string current_word = [] #array containing the letters of the current word punctuation_ = [] #array containing the punctuatio...
string_jumble
identifier_name
DatasourcePanelDragWrapper.test.tsx
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you...
test('should render', () => { render( <DndProvider backend={HTML5Backend}> <DatasourcePanelDragWrapper value={{ metric_name: 'test' }} type={DndItemType.Metric} > <div data-test="children" /> </DatasourcePanelDragWrapper> </DndProvider>, ); expect(screen.getByTes...
import { render, screen } from 'spec/helpers/testing-library'; import { DndItemType } from 'src/explore/components/DndItemType'; import DatasourcePanelDragWrapper from '.';
random_line_split
grid.js
positions tile.updatePosition(positions.next); // Update the score score += merged.value; // The mighty 2048 tile if (merged.value === 2048) { won = true; } } else { //if (debug) { //console.log(cell); /...
{ next--; }
conditional_block
grid.js
(size) { this.size = size; this.startTiles = 2; this.cells = []; this.build(); this.playerTurn = true; } // pre-allocate these objects (for speed) Grid.prototype.indexes = []; for (var x=0; x<4; x++) { Grid.prototype.indexes.push([]); for (var y=0; y<4; y++) { Grid.prototype.indexes[x].push( {x:x...
Grid
identifier_name
grid.js
// pre-allocate these objects (for speed) Grid.prototype.indexes = []; for (var x=0; x<4; x++) { Grid.prototype.indexes.push([]); for (var y=0; y<4; y++) { Grid.prototype.indexes[x].push( {x:x, y:y} ); } } // Build a grid of the specified size Grid.prototype.build = function () { for (var x = 0; x < this...
{ this.size = size; this.startTiles = 2; this.cells = []; this.build(); this.playerTurn = true; }
identifier_body
grid.js
Grid.insertTile(this.cells[x][y].clone()); } } } return newGrid; }; // Set up the initial tiles to start the game with Grid.prototype.addStartTiles = function () { for (var i=0; i<this.startTiles; i++) { this.addRandomTile(); } }; // Adds a tile in a random position Grid.prototype.addRandomTile ...
//var matches = 0; var tile; for (var x = 0; x < this.size; x++) { for (var y = 0; y < this.size; y++) { tile = this.cellContent({ x: x, y: y }); if (tile) { for (var direction = 0; direction < 4; direction++) { var vector = self.getVector(direction); var cell = { ...
random_line_split
f5195fe91e09_agrega_alturas_codprov_y_alturas_cp.py
"""Agrega alturas.codprov y alturas.cp Revision ID: f5195fe91e09 Revises: fccbcd8362d7 Create Date: 2017-07-09 22:01:51.280360 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'f5195fe91e09' down_revision = 'fccbcd8362d7' branch_labels = None depends_on = None ...
(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('alturas', 'cp') op.drop_column('alturas', 'codprov') # ### end Alembic commands ###
downgrade
identifier_name
f5195fe91e09_agrega_alturas_codprov_y_alturas_cp.py
"""Agrega alturas.codprov y alturas.cp Revision ID: f5195fe91e09 Revises: fccbcd8362d7 Create Date: 2017-07-09 22:01:51.280360 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'f5195fe91e09' down_revision = 'fccbcd8362d7' branch_labels = None depends_on = None ...
def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('alturas', 'cp') op.drop_column('alturas', 'codprov') # ### end Alembic commands ###
op.add_column('alturas', sa.Column('codprov', sa.String(length=1), nullable=True)) op.add_column('alturas', sa.Column('cp', sa.Integer(), nullable=True)) # ### end Alembic commands ###
identifier_body
f5195fe91e09_agrega_alturas_codprov_y_alturas_cp.py
"""Agrega alturas.codprov y alturas.cp Revision ID: f5195fe91e09 Revises: fccbcd8362d7 Create Date: 2017-07-09 22:01:51.280360 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'f5195fe91e09' down_revision = 'fccbcd8362d7' branch_labels = None depends_on = None ...
def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('alturas', 'cp') op.drop_column('alturas', 'codprov') # ### end Alembic commands ###
random_line_split
saveable_object.py
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
else: self.device = tensor.device @property def tensor(self): return self._tensor() if callable(self._tensor) else self._tensor class SaveableObject(object): """Base class for saving and restoring saveable objects.""" def __init__(self, op, specs, name): """Creates a `SaveableObject` ...
self.device = device
conditional_block
saveable_object.py
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
class SaveableObject(object): """Base class for saving and restoring saveable objects.""" def __init__(self, op, specs, name): """Creates a `SaveableObject` object. Args: op: the "producer" object that this class wraps; it produces a list of tensors to save. E.g., a "Variable" object sav...
return self._tensor() if callable(self._tensor) else self._tensor
identifier_body
saveable_object.py
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
self.device = tensor.device @property def tensor(self): return self._tensor() if callable(self._tensor) else self._tensor class SaveableObject(object): """Base class for saving and restoring saveable objects.""" def __init__(self, op, specs, name): """Creates a `SaveableObject` object. ...
if device is not None: self.device = device else:
random_line_split
saveable_object.py
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
(self, restored_tensors, restored_shapes): """Restores this object from 'restored_tensors'. Args: restored_tensors: the tensors that were loaded from a checkpoint restored_shapes: the shapes this object should conform to after restore, or None. Returns: An operation that restores...
restore
identifier_name
_id3.py
album" elif frame.desc == "track": k = "track" elif "replaygain_track_gain" not in self: k = "track" # fallback else: return self["replaygain_%s_gain" % k] = "%+f dB" % frame.gain self["replaygain_%s_peak" % k] ...
"""Returns the primary embedded image""" try: with translate_errors(): audio = self.Kind(self["~filename"]) except AudioFileError: return tag = audio.tags if tag is None: return # get the APIC frame with type == 3 (cover) or ...
identifier_body
_id3.py
long dates in a TXXX DATE tag, leaving the TDRC # tag out. Read the TXXX DATE, but only if the TDRC tag doesn't exist # to avoid reverting or duplicating tags in existing libraries. if audio.tags and "date" not in self: for frame in tag.getall('TXXX:DATE'): self["dat...
clear_images
identifier_name
_id3.py
_name(name) if not name: continue name = name.lower() id3id = frame.FrameID if id3id.startswith("T"): text = "\n".join(map(str, frame.text)) elif id3id == "COMM": text = "\n".join(frame.text) elif id...
try: del(tag["TXXX:" + key]) except KeyError: pass
conditional_block
_id3.py
http://bugs.musicbrainz.org/ticket/1383 # http://musicbrainz.org/doc/MusicBrainzTag TXXX_MAP = { u"MusicBrainz Release Group Id": "musicbrainz_releasegroupid", u"MusicBrainz Release Track Id": "musicbrainz_releasetrackid", u"MusicBrainz Artist Id": "musicbrainz_artistid", u"Musi...
tag.delall("TLAN") if "language" in self: langs = self["language"].split("\n") if all([lang in ISO_639_2 for lang in langs]):
random_line_split
user_email.js
Template[getTemplate('user_email')].helpers({ user: function(){ return Meteor.user(); } }); Template[getTemplate('user_email')].events({ 'submit form': function(e){ e.preventDefault(); if(!Meteor.user()) throwError(i18n.t('You must be logged in.')); var $target=$(e.target); var user=Session.g...
throwError(i18n.t('Thanks for signing up!')); Meteor.call('addCurrentUserToMailChimpList'); trackEvent("new sign-up", {'userId': user._id, 'auth':'twitter'}); Router.go('/'); } }); } });
}, function(error){ if(error){ throwError(error.reason); } else {
random_line_split
user_email.js
Template[getTemplate('user_email')].helpers({ user: function(){ return Meteor.user(); } }); Template[getTemplate('user_email')].events({ 'submit form': function(e){ e.preventDefault(); if(!Meteor.user()) throwError(i18n.t('You must be logged in.')); var $target=$(e.target); var user=Session.g...
}); } });
{ throwError(i18n.t('Thanks for signing up!')); Meteor.call('addCurrentUserToMailChimpList'); trackEvent("new sign-up", {'userId': user._id, 'auth':'twitter'}); Router.go('/'); }
conditional_block
join.rs
use std::fmt; use std::str; use column::Column; use condition::ConditionExpression; use nom::branch::alt; use nom::bytes::complete::tag_no_case; use nom::combinator::map; use nom::IResult; use select::{JoinClause, SelectStatement}; use table::Table; #[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]...
{ /// A single table. Table(Table), /// A comma-separated (and implicitly joined) sequence of tables. Tables(Vec<Table>), /// A nested selection, represented as (query, alias). NestedSelect(Box<SelectStatement>, Option<String>), /// A nested join clause. NestedJoin(Box<JoinClause>), } ...
JoinRightSide
identifier_name
join.rs
use std::fmt; use std::str; use column::Column; use condition::ConditionExpression; use nom::branch::alt; use nom::bytes::complete::tag_no_case; use nom::combinator::map; use nom::IResult; use select::{JoinClause, SelectStatement}; use table::Table; #[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]...
..Default::default() }; let q = res.unwrap().1; assert_eq!(q, expected_stmt); assert_eq!(qstring, format!("{}", q)); } }
{ let qstring = "SELECT tags.* FROM tags \ INNER JOIN taggings ON tags.id = taggings.tag_id"; let res = selection(qstring.as_bytes()); let ct = ConditionTree { left: Box::new(Base(Field(Column::from("tags.id")))), right: Box::new(Base(Field(Column...
identifier_body
join.rs
use std::fmt; use std::str; use column::Column; use condition::ConditionExpression; use nom::branch::alt; use nom::bytes::complete::tag_no_case; use nom::combinator::map; use nom::IResult; use select::{JoinClause, SelectStatement}; use table::Table; #[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]...
} }
let q = res.unwrap().1; assert_eq!(q, expected_stmt); assert_eq!(qstring, format!("{}", q));
random_line_split
old-lane-detection.py
(img): # start time start_time = cv2.getTickCount() # Gaussian Filter to remove noise img = cv2.medianBlur(img,5) gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) # print img.shape = (200,350,3) rows,cols,channels = img.shape # ROI roi_mask = np.zeros(img.shape,dtype=np.uint8) roi_mask[10:rows,0:cols] = 255 ...
detect
identifier_name
old-lane-detection.py
_roi_mask) left_roi_mask = np.zeros(gray.shape,dtype=np.uint8) left_roi_mask[rows/3:rows,0:180] = 255 left_roi = cv2.bitwise_and(img,img,left_roi_mask) # define range of color in HSV hsv = cv2.cvtColor(street,cv2.COLOR_BGR2HSV) sensitivity = 60 # range of sensitivity=[90,150] lower_white = np.array([0,0,255-s...
yellow_mask = cv2.erode(yellow_mask, None, iterations=2) yellow_mask = cv2.dilate(yellow_mask, None, iterations=2) # mask AND original img whitehsvthresh = cv2.bitwise_and(right_roi,right_roi,mask=white_mask) yellowhsvthresh = cv2.bitwise_and(street,street,mask=yellow_mask) redhsvthresh = cv2.bitwise_and(street,...
upper_yellow = np.array([30,255,255]) #80,255,255 yellow_mask = cv2.inRange(hsv,lower_yellow,upper_yellow)
random_line_split
old-lane-detection.py
Range(hsv,lower_yellow,upper_yellow) yellow_mask = cv2.erode(yellow_mask, None, iterations=2) yellow_mask = cv2.dilate(yellow_mask, None, iterations=2) # mask AND original img whitehsvthresh = cv2.bitwise_and(right_roi,right_roi,mask=white_mask) yellowhsvthresh = cv2.bitwise_and(street,street,mask=yellow_mask) r...
rospy.loginfo(error) if error > 150: error = 150 elif error < -150: error = -150 return error
conditional_block
old-lane-detection.py
left_roi_mask = np.zeros(gray.shape,dtype=np.uint8) left_roi_mask[rows/3:rows,0:180] = 255 left_roi = cv2.bitwise_and(img,img,left_roi_mask) # define range of color in HSV hsv = cv2.cvtColor(street,cv2.COLOR_BGR2HSV) sensitivity = 60 # range of sensitivity=[90,150] lower_white = np.array([0,0,255-sensitivity]...
start_time = cv2.getTickCount() # Gaussian Filter to remove noise img = cv2.medianBlur(img,5) gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) # print img.shape = (200,350,3) rows,cols,channels = img.shape # ROI roi_mask = np.zeros(img.shape,dtype=np.uint8) roi_mask[10:rows,0:cols] = 255 street = cv2.bitwise_an...
identifier_body
version.py
# -*- coding: utf-8 -*- """Version information.""" """ Kontalk XMPP server Copyright (C) 2014 Kontalk Devteam <devteam@kontalk.org> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either versi...
"name": "Daniele Ricci", "email": "daniele.athome@gmail.com" }, )
random_line_split
event.py
import logging from atracker.models import Event from atracker.util import create_event from django.conf.urls import url from django.contrib.auth import get_user_model from django.contrib.contenttypes.models import ContentType from tastypie.authentication import ( MultiAuthentication, Authentication, Sessi...
elif request.user and request.user.is_authenticated(): user = request.user log.info("creating event for user by request: %s" % user.username) else: log.debug("no authenticated user") user = None object = content_type.model_class().objects.get(u...
log.warning( "no permission for %s to vote in behalf of %s" % (request.user, user_id) ) user = None
conditional_block
event.py
import logging from atracker.models import Event from atracker.util import create_event from django.conf.urls import url from django.contrib.auth import get_user_model from django.contrib.contenttypes.models import ContentType from tastypie.authentication import ( MultiAuthentication, Authentication, Sessi...
def dehydrate(self, bundle): return bundle def prepend_urls(self): return [ url( r"^(?P<resource_name>%s)/(?P<content_type>[\w.]+)/(?P<object_uuid>[\w.-]+)(?:/(?P<action>[\w-]+))?(?:/(?P<user_id>-?[0-9]+))?%s$" % (self._meta.resource_name, trailing...
queryset = Event.objects.all() list_allowed_methods = ["get"] detail_allowed_methods = ["get"] resource_name = "atracker/event" include_resource_uri = False # TODO: double-check for sensitive information fields = ["created"] authentication = MultiAuthentication( ...
identifier_body
event.py
import logging
from django.conf.urls import url from django.contrib.auth import get_user_model from django.contrib.contenttypes.models import ContentType from tastypie.authentication import ( MultiAuthentication, Authentication, SessionAuthentication, ApiKeyAuthentication, ) from tastypie.authorization import Authoriz...
from atracker.models import Event from atracker.util import create_event
random_line_split
event.py
import logging from atracker.models import Event from atracker.util import create_event from django.conf.urls import url from django.contrib.auth import get_user_model from django.contrib.contenttypes.models import ContentType from tastypie.authentication import ( MultiAuthentication, Authentication, Sessi...
(ModelResource): class Meta: queryset = Event.objects.all() list_allowed_methods = ["get"] detail_allowed_methods = ["get"] resource_name = "atracker/event" include_resource_uri = False # TODO: double-check for sensitive information fields = ["created"] ...
EventResource
identifier_name
admin.py
from django.contrib import admin from django.contrib import messages from django.core.mail import EmailMultiAlternatives from django.conf import settings from .models import Email from users.models import User @admin.register(Email) class EmailAdmin(admin.ModelAdmin): list_display = ('subject', 'sent', 'created'...
self.message_user(request, message="Cet email a déjà été envoyé", level=messages.ERROR) return message = EmailMultiAlternatives( subject=email.subject, body=email.content, from_email='Newsletter UrLab <contact@urlab.be>', to=["contact-test...
email = queryset.first() if email.sent:
random_line_split
admin.py
from django.contrib import admin from django.contrib import messages from django.core.mail import EmailMultiAlternatives from django.conf import settings from .models import Email from users.models import User @admin.register(Email) class EmailAdmin(admin.ModelAdmin): list_display = ('subject', 'sent', 'created'...
(self, obj): return ", ".join([u.username for u in obj.approvers.all()]) get_approvers.short_description = "Approbateurs" def is_sendable(self, obj): return obj.approvers.count() >= settings.MINIMAL_MAIL_APPROVERS and not obj.sent is_sendable.short_description = "Est envoyable" def app...
get_approvers
identifier_name
admin.py
from django.contrib import admin from django.contrib import messages from django.core.mail import EmailMultiAlternatives from django.conf import settings from .models import Email from users.models import User @admin.register(Email) class EmailAdmin(admin.ModelAdmin): list_display = ('subject', 'sent', 'created'...
pients = [u.email for u in User.objects.filter(newsletter=True)] message = EmailMultiAlternatives( subject=email.subject, body=email.content, from_email='Newsletter UrLab <contact@urlab.be>', to=["UrLab <contact@urlab.be>"], bcc=recipients, ) ...
ser(request, message="Ce message n'a pas assez d'approbateurs", level=messages.ERROR) return reci
conditional_block
admin.py
from django.contrib import admin from django.contrib import messages from django.core.mail import EmailMultiAlternatives from django.conf import settings from .models import Email from users.models import User @admin.register(Email) class EmailAdmin(admin.ModelAdmin): list_display = ('subject', 'sent', 'created'...
get_approvers.short_description = "Approbateurs" def is_sendable(self, obj): return obj.approvers.count() >= settings.MINIMAL_MAIL_APPROVERS and not obj.sent is_sendable.short_description = "Est envoyable" def approve(self, request, queryset): if not queryset.count() == 1: ...
return ", ".join([u.username for u in obj.approvers.all()])
identifier_body
canadanews.py
""" This module serves commands to retrieve Canadian News. Powered by http://www.statcan.gc.ca/, shows 4 actual news. Updated daily. """ from requests import get, RequestException, status_codes from ..commandbase import CommandBase class CanadaStatsCommand(CommandBase): name = '/canadastat' hel...
(self, *args, **kwargs): super().__call__(*args, **kwargs) json = self.get_json() if json: for article in json['daily']['article']: self.send_telegram_message(self.NEWS_TEXT.format(response=article)) else: self.send_telegram_message('No news were r...
__call__
identifier_name
canadanews.py
""" This module serves commands to retrieve Canadian News. Powered by http://www.statcan.gc.ca/, shows 4 actual news. Updated daily. """ from requests import get, RequestException, status_codes from ..commandbase import CommandBase class CanadaStatsCommand(CommandBase): name = '/canadastat' hel...
else: self.send_telegram_message('No news were retrieved.') def get_json(self): url = 'http://www.statcan.gc.ca/sites/json/daily-banner-eng.json' try: response = get(url) except RequestException as e: self._logger.debug('RequestException {}'.form...
for article in json['daily']['article']: self.send_telegram_message(self.NEWS_TEXT.format(response=article))
conditional_block
canadanews.py
""" This module serves commands to retrieve Canadian News.
from requests import get, RequestException, status_codes from ..commandbase import CommandBase class CanadaStatsCommand(CommandBase): name = '/canadastat' help_text = ' - Daily Articles with Open Canada Statistics reviews.' disable_web_page_preview = 'false' NEWS_TEXT = ('[{response[title]}](http://w...
Powered by http://www.statcan.gc.ca/, shows 4 actual news. Updated daily. """
random_line_split
canadanews.py
""" This module serves commands to retrieve Canadian News. Powered by http://www.statcan.gc.ca/, shows 4 actual news. Updated daily. """ from requests import get, RequestException, status_codes from ..commandbase import CommandBase class CanadaStatsCommand(CommandBase): name = '/canadastat' hel...
def get_json(self): url = 'http://www.statcan.gc.ca/sites/json/daily-banner-eng.json' try: response = get(url) except RequestException as e: self._logger.debug('RequestException {}'.format(e)) return if response.status_code == status_codes.codes....
super().__call__(*args, **kwargs) json = self.get_json() if json: for article in json['daily']['article']: self.send_telegram_message(self.NEWS_TEXT.format(response=article)) else: self.send_telegram_message('No news were retrieved.')
identifier_body
muv_common.py
# <pep8-80 compliant> # ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # ...
for region in area.regions: if region.type == region_type: break for space in area.spaces: if space.type == space_type: break return (area, region, space)
random_line_split
muv_common.py
# <pep8-80 compliant> # ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # ...
return (area, region, space)
break
conditional_block
muv_common.py
# <pep8-80 compliant> # ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # ...
def get_space(area_type, region_type, space_type): """ Get current area/region/space """ for area in bpy.context.screen.areas: if area.type == area_type: break for region in area.regions: if region.type == region_type: break for space in area.spaces: ...
""" Redraw all areas """ for area in bpy.context.screen.areas: area.tag_redraw()
identifier_body
muv_common.py
# <pep8-80 compliant> # ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # ...
(area_type, region_type, space_type): """ Get current area/region/space """ for area in bpy.context.screen.areas: if area.type == area_type: break for region in area.regions: if region.type == region_type: break for space in area.spaces: if space....
get_space
identifier_name
flash-messages.component.ts
import { Component, OnInit } from '@angular/core'; import { FlashMessagesService, IFlashMessage, IFlashMessageOptions, } from './flash-messages.service'; @Component({ selector: 'ngx-flash-messages', templateUrl: './flash-messages.component.html', }) export class FlashMessagesComponent implements OnInit { p...
}
{ const defaultOpts: IFlashMessageOptions = { classes: [], timeout: 3000 }; Object.assign(defaultOpts, message.options); message.options = defaultOpts; const timestamp = message.timestamp = + new Date(); this.messages.push(message); setTimeout(() => { this.messages = thi...
identifier_body
flash-messages.component.ts
import { Component, OnInit } from '@angular/core'; import { FlashMessagesService, IFlashMessage, IFlashMessageOptions, } from './flash-messages.service'; @Component({ selector: 'ngx-flash-messages', templateUrl: './flash-messages.component.html', }) export class FlashMessagesComponent implements OnInit { p...
(message: IFlashMessage) { const defaultOpts: IFlashMessageOptions = { classes: [], timeout: 3000 }; Object.assign(defaultOpts, message.options); message.options = defaultOpts; const timestamp = message.timestamp = + new Date(); this.messages.push(message); setTimeout(() => { ...
handleMessage
identifier_name
flash-messages.component.ts
import { Component, OnInit } from '@angular/core'; import { FlashMessagesService, IFlashMessage, IFlashMessageOptions, } from './flash-messages.service'; @Component({ selector: 'ngx-flash-messages', templateUrl: './flash-messages.component.html', }) export class FlashMessagesComponent implements OnInit { p...
setTimeout(() => { this.messages = this.messages.filter( msg => msg.timestamp !== timestamp ); }, message.options.timeout); } }
const timestamp = message.timestamp = + new Date(); this.messages.push(message);
random_line_split
ecs.rs
use std::collections::HashMap; use std::iter; use world; use entity::{Entity}; use components; use component_ref::{ComponentRef, ComponentRefMut}; use stats; use world::{WorldState}; /// Entity component system. #[derive(RustcDecodable, RustcEncodable)] pub struct Ecs { next_idx: usize, reusable_idxs: Vec<usiz...
// XXX: Figure out how to move self into the closure to // get rid of the .clone. fn add_to(self, e: Entity) { world::with_mut(|w| w.$access_mut().insert(e, self.clone())) } } )+ // Implement the trait for accessing all the components that ...
impl Component for $comp {
random_line_split
ecs.rs
use std::collections::HashMap; use std::iter; use world; use entity::{Entity}; use components; use component_ref::{ComponentRef, ComponentRefMut}; use stats; use world::{WorldState}; /// Entity component system. #[derive(RustcDecodable, RustcEncodable)] pub struct Ecs { next_idx: usize, reusable_idxs: Vec<usiz...
let ret = Entity(*idx); *idx += 1; if !w.ecs.active[*idx - 1] { continue; } return Some(ret); } }) } } //////////////////////////////////////////////////////////////////////// // The one big macro for defining the full set of ava...
{ return None; }
conditional_block
ecs.rs
use std::collections::HashMap; use std::iter; use world; use entity::{Entity}; use components; use component_ref::{ComponentRef, ComponentRefMut}; use stats; use world::{WorldState}; /// Entity component system. #[derive(RustcDecodable, RustcEncodable)] pub struct Ecs { next_idx: usize, reusable_idxs: Vec<usiz...
(&mut self) -> Option<Entity> { world::with(|w| { let &mut EntityIter(ref mut idx) = self; loop { if *idx >= w.ecs.active.len() { return None; } let ret = Entity(*idx); *idx += 1; if !w.ecs.active[*idx - 1] { continue; } ...
next
identifier_name
ecs.rs
use std::collections::HashMap; use std::iter; use world; use entity::{Entity}; use components; use component_ref::{ComponentRef, ComponentRefMut}; use stats; use world::{WorldState}; /// Entity component system. #[derive(RustcDecodable, RustcEncodable)] pub struct Ecs { next_idx: usize, reusable_idxs: Vec<usiz...
} pub struct EntityIter(usize); impl Iterator for EntityIter { type Item = Entity; fn next(&mut self) -> Option<Entity> { world::with(|w| { let &mut EntityIter(ref mut idx) = self; loop { if *idx >= w.ecs.active.len() { return None; } let ret = ...
{ self.parent.insert(idx, new_parent_idx); }
identifier_body
polyfill.js
'use strict'; var clear = require('es5-ext/array/#/clear') , eIndexOf = require('es5-ext/array/#/e-index-of') , setPrototypeOf = require('es5-ext/object/set-prototype-of') , callable = require('es5-ext/object/valid-callable') , d = require('d') , ee = require('ev...
module.exports = SetPoly = function (/*iterable*/) { var iterable = arguments[0]; if (!(this instanceof SetPoly)) return new SetPoly(iterable); if (this.__setData__ !== undefined) { throw new TypeError(this + " cannot be reinitialized"); } if (iterable != null) iterator(iterable); defineProperty(this, '__setDa...
random_line_split
tests.py
from django.test import TestCase from versiontools.models import AssemblyInfo from django.utils.timesince import timesince from django.utils.datetime_safe import datetime # Create your tests here. class AssembyInfoTest(TestCase): def test_create(self):
data = {'fullpath' : r'C:\Users\lberrocal\Documents\Visual Studio 2010\Projects\vessel_scheling_app\5-VesselScheduleEngine\VsApplicationData\My Project\AssemblyInfo.vb ', 'title' : 'Vessel Schedule WorkBench', 'description' : '', 'version' : '1.2.6'} ...
identifier_body
tests.py
from django.test import TestCase from versiontools.models import AssemblyInfo from django.utils.timesince import timesince from django.utils.datetime_safe import datetime # Create your tests here. class
(TestCase): def test_create(self): data = {'fullpath' : r'C:\Users\lberrocal\Documents\Visual Studio 2010\Projects\vessel_scheling_app\5-VesselScheduleEngine\VsApplicationData\My Project\AssemblyInfo.vb ', 'title' : 'Vessel Schedule WorkBench', 'description' ...
AssembyInfoTest
identifier_name
tests.py
from django.test import TestCase from versiontools.models import AssemblyInfo from django.utils.timesince import timesince from django.utils.datetime_safe import datetime # Create your tests here.
class AssembyInfoTest(TestCase): def test_create(self): data = {'fullpath' : r'C:\Users\lberrocal\Documents\Visual Studio 2010\Projects\vessel_scheling_app\5-VesselScheduleEngine\VsApplicationData\My Project\AssemblyInfo.vb ', 'title' : 'Vessel Schedule WorkBench', ...
random_line_split
message_log.rs
use std::{env, process::exit, time::Duration}; use assign::assign; use ruma::{ api::client::{filter::FilterDefinition, sync::sync_events}, events::{ room::message::{MessageType, RoomMessageEventContent, TextMessageEventContent}, AnySyncMessageLikeEvent, AnySyncRoomEvent, SyncMessageLikeEvent, ...
while let Some(res) = sync_stream.try_next().await? { // Only look at rooms the user hasn't left yet for (room_id, room) in res.rooms.join { for event in room.timeline.events.into_iter().flat_map(|r| r.deserialize()) { // Filter out the text messages if le...
{ let client = ruma::Client::builder().homeserver_url(homeserver_url).build::<HttpClient>().await?; client.log_in(username, password, None, None).await?; let filter = FilterDefinition::ignore_all().into(); let initial_sync_response = client .send_request(assign!(sync_events::v3::Reques...
identifier_body
message_log.rs
use std::{env, process::exit, time::Duration}; use assign::assign; use ruma::{ api::client::{filter::FilterDefinition, sync::sync_events}, events::{ room::message::{MessageType, RoomMessageEventContent, TextMessageEventContent}, AnySyncMessageLikeEvent, AnySyncRoomEvent, SyncMessageLikeEvent, ...
&PresenceState::Online, Some(Duration::from_secs(30)), )); while let Some(res) = sync_stream.try_next().await? { // Only look at rooms the user hasn't left yet for (room_id, room) in res.rooms.join { for event in room.timeline.events.into_iter().flat_map(|r| r.deseri...
.await?; let mut sync_stream = Box::pin(client.sync( None, initial_sync_response.next_batch,
random_line_split
message_log.rs
use std::{env, process::exit, time::Duration}; use assign::assign; use ruma::{ api::client::{filter::FilterDefinition, sync::sync_events}, events::{ room::message::{MessageType, RoomMessageEventContent, TextMessageEventContent}, AnySyncMessageLikeEvent, AnySyncRoomEvent, SyncMessageLikeEvent, ...
( homeserver_url: String, username: &str, password: &str, ) -> anyhow::Result<()> { let client = ruma::Client::builder().homeserver_url(homeserver_url).build::<HttpClient>().await?; client.log_in(username, password, None, None).await?; let filter = FilterDefinition::ignore_all().into()...
log_messages
identifier_name
text_outputs.py
import numpy as np def
(outfile='results.txt',analysis={}, envelopes={}, index={}): # Set global output options np.set_printoptions(precision=5, linewidth=1000) contents = outfile +'\n\n' contents += '==LAMINATE CONSTANTS==\n' for key in analysis: contents += key+'\n' contents += str(analysis[key]) contents += '\n' contents +=...
FullOut
identifier_name
text_outputs.py
import numpy as np def FullOut(outfile='results.txt',analysis={}, envelopes={}, index={}): # Set global output options np.set_printoptions(precision=5, linewidth=1000) contents = outfile +'\n\n' contents += '==LAMINATE CONSTANTS==\n' for key in analysis: contents += key+'\n' contents += str(analysis[key]) ...
contents += '\n' contents += '==LAMINATE FAILURE ENVELOPES==\n' for key in envelopes: contents += key + '\n' for subkey in envelopes[key]: contents += subkey + ' = '+str(envelopes[key][subkey]) contents += '\n' contents += '\n' file = open(outfile,'w') file.write(contents) file.close()
for key in index: contents += key+'\n' contents += str(index[key])
random_line_split
text_outputs.py
import numpy as np def FullOut(outfile='results.txt',analysis={}, envelopes={}, index={}): # Set global output options np.set_printoptions(precision=5, linewidth=1000) contents = outfile +'\n\n' contents += '==LAMINATE CONSTANTS==\n' for key in analysis: contents += key+'\n' contents += str(analysis[key]) ...
contents += '==LAMINATE FAILURE ENVELOPES==\n' for key in envelopes: contents += key + '\n' for subkey in envelopes[key]: contents += subkey + ' = '+str(envelopes[key][subkey]) contents += '\n' contents += '\n' file = open(outfile,'w') file.write(contents) file.close()
contents += key+'\n' contents += str(index[key]) contents += '\n'
conditional_block
text_outputs.py
import numpy as np def FullOut(outfile='results.txt',analysis={}, envelopes={}, index={}): # Set global output options
contents += '\n' contents += '\n' file = open(outfile,'w') file.write(contents) file.close()
np.set_printoptions(precision=5, linewidth=1000) contents = outfile +'\n\n' contents += '==LAMINATE CONSTANTS==\n' for key in analysis: contents += key+'\n' contents += str(analysis[key]) contents += '\n' contents += '==LAMINATE FAILURE INDICES==\n' for key in index: contents += key+'\n' contents += st...
identifier_body
sql_group_concat.py
from django.db.models import Aggregate, CharField
function = 'GROUP_CONCAT' allow_distinct = True def __init__(self, expression, separator, distinct=False, ordering=None, **extra): self.separator = separator super(Sql_GroupConcat, self).__init__(expression, distinct='DISTINCT ' if distinct else...
class Sql_GroupConcat(Aggregate):
random_line_split
sql_group_concat.py
from django.db.models import Aggregate, CharField class Sql_GroupConcat(Aggregate): function = 'GROUP_CONCAT' allow_distinct = True def __init__(self, expression, separator, distinct=False, ordering=None, **extra): self.separator = separator super(Sql_GroupConcat, self).__init__(expressio...
(self, compiler, connection, **extra): return super().as_sql(compiler, connection, template='%(function)s(%(distinct)s%(expressions)s%(ordering)s)', **extra)
as_sql
identifier_name
sql_group_concat.py
from django.db.models import Aggregate, CharField class Sql_GroupConcat(Aggregate): function = 'GROUP_CONCAT' allow_distinct = True def __init__(self, expression, separator, distinct=False, ordering=None, **extra): self.separator = separator super(Sql_GroupConcat, self).__init__(expressio...
return super().as_sql(compiler, connection, template='%(function)s(%(distinct)s%(expressions)s%(ordering)s)', **extra)
identifier_body
patcher.rs
use std::io::prelude::*; use std::fs; use std::cell::RefCell; use std::fs::File; use std::collections::HashMap; use rustc_serialize::json; use rustc_serialize::hex::ToHex; use parser; use parser::usbr; use parser::{Request, Source}; #[derive(RustcDecodable)] struct PatchMetadata { p_type: String, vendor_id: ...
} self.counts.borrow_mut().insert(patch.meta.patch_id, count); } } true } fn check_connect(&self, req: &Request) -> bool { let h_ptr = req.type_header.as_ptr() as *const usbr::ConnectHeader; let h: &usbr::ConnectHeader = unsafe {...
{ for patch in &self.patches { if patch.meta.p_type != "bulk" { continue; } // The metadata matches, time to compare the data let data_hex: String = req.data[..].to_hex(); if data_hex.len() >= patch.data.len() && data_hex.contains(&...
identifier_body
patcher.rs
use std::io::prelude::*; use std::fs; use std::cell::RefCell; use std::fs::File; use std::collections::HashMap; use rustc_serialize::json; use rustc_serialize::hex::ToHex; use parser; use parser::usbr; use parser::{Request, Source}; #[derive(RustcDecodable)] struct PatchMetadata { p_type: String, vendor_id: ...
// The metadata matches, time to compare the data let data_hex: String = req.data[..].to_hex(); if data_hex.len() >= patch.data.len() && data_hex.contains(&patch.data) { let mut count: u16 = *self.counts.borrow().get(&patch.meta.patch_id).unwrap(); ...
{ continue; }
conditional_block
patcher.rs
use std::io::prelude::*; use std::fs; use std::cell::RefCell; use std::fs::File; use std::collections::HashMap; use rustc_serialize::json; use rustc_serialize::hex::ToHex; use parser; use parser::usbr; use parser::{Request, Source}; #[derive(RustcDecodable)] struct PatchMetadata { p_type: String, vendor_id: ...
fn handle_connect(&self, _: Source, req: Request) -> (u8, Vec<Request>) { if self.check_connect(&req) { (0, vec![req]) } else { (1, vec![req]) } } // TODO: Implement below // // fn handle_int_packet(&self, source: Source, req: Request) -> (u8, Vec<Request>) { // (0, vec![req]) // }...
fn handle_bulk_packet(&self, _: Source, req: Request) -> (u8, Vec<Request>) { if self.check_bulk_packet(&req) { (0, vec![req]) } else { (1, vec![req]) } }
random_line_split
patcher.rs
use std::io::prelude::*; use std::fs; use std::cell::RefCell; use std::fs::File; use std::collections::HashMap; use rustc_serialize::json; use rustc_serialize::hex::ToHex; use parser; use parser::usbr; use parser::{Request, Source}; #[derive(RustcDecodable)] struct PatchMetadata { p_type: String, vendor_id: ...
(&self, req: &Request) -> bool { for patch in &self.patches { if patch.meta.p_type != "bulk" { continue; } // The metadata matches, time to compare the data let data_hex: String = req.data[..].to_hex(); if data_hex.len() >= patch.da...
check_bulk_packet
identifier_name
connection_wrapper.py
import logging import time from django.conf import settings from django.core.mail import get_connection as dj_get_connection logger = logging.getLogger(__name__) class BackendWrapper(object): """A wrapper around Django's Email Backend, providing hooks for instrumentation and testing. """ def __ini...
(self, email_messages): # check settings hook for rewriting email recipient, act accordingly if settings.EMAIL_REWRITE_RECIPIENT: for message in email_messages: message.to = [settings.EMAIL_REWRITE_RECIPIENT] # send the messages t = time.time() msg_c...
send_messages
identifier_name
connection_wrapper.py
import logging import time from django.conf import settings from django.core.mail import get_connection as dj_get_connection logger = logging.getLogger(__name__) class BackendWrapper(object): """A wrapper around Django's Email Backend, providing hooks for instrumentation and testing. """ def __ini...
def send_messages(self, email_messages): # check settings hook for rewriting email recipient, act accordingly if settings.EMAIL_REWRITE_RECIPIENT: for message in email_messages: message.to = [settings.EMAIL_REWRITE_RECIPIENT] # send the messages t = ti...
self._backend = backend logger.info("initialized connection wrapper with email backend: %s", backend)
identifier_body
connection_wrapper.py
import logging import time from django.conf import settings from django.core.mail import get_connection as dj_get_connection logger = logging.getLogger(__name__) class BackendWrapper(object): """A wrapper around Django's Email Backend, providing hooks for instrumentation and testing. """ def __ini...
return msg_count def close(self): # never raise Exceptions on close(). try: self._backend.close() except Exception as e: logger.debug("self._backend.close() failed: %s", e) def __getattr__(self, a): return getattr(self._backend, a) def get_con...
logger.warn('send_messages() was called with %s messages but return value was %s', len(email_messages), msg_count)
conditional_block