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
gui_charts.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import tkinter as tk from tkinter import ttk from multiprocessing import pool import numpy as np import stat_functions as stat from scipy import stats as scstats from gui import gui_functions as guif import os import functions as fu class process_charts(ttk.Frame): de...
def plot(self,ll): self.initialize(ll.panel) self.ll=ll self.histogram(ll,self.subplot) self.correlogram(ll,self.subplot) self.correlogram_variance(ll,self.subplot) def histogram(self,ll,subplot,f=None): N,T,k=ll.panel.X.shape fgr,axs=subplot n=ll.e_norm_centered.shape[2] e=ll.e_norm_ce...
self.panel=panel self.add_content() self.initialized=True
conditional_block
gui_charts.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import tkinter as tk from tkinter import ttk from multiprocessing import pool import numpy as np import stat_functions as stat from scipy import stats as scstats from gui import gui_functions as guif import os import functions as fu class process_charts(ttk.Frame): de...
(self,charts): self.add_content() if charts is None: return for i in range(len(charts)): path,name=charts[i] guif.display_from_img(self.charts[i],path,name,i) def add_content(self): self.n_charts=3 self.columnconfigure(0,weight=1) for i in range(self.n_charts+1): self.rowconfigure(i,weight=1...
charts_from_stored
identifier_name
gui_charts.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import tkinter as tk from tkinter import ttk from multiprocessing import pool import numpy as np import stat_functions as stat from scipy import stats as scstats from gui import gui_functions as guif import os import functions as fu class process_charts(ttk.Frame):
self.ll=None self.initialized=False self.subplot=tabs.subplot self.print_subplot=tabs.print_subplot self.img_tmp=tabs.img_tmp def get_images_for_storage(self): charts=[] for i in self.charts: charts.append((i.path,i.name)) return charts def charts_from_stored(self,charts): self.add_content...
def __init__(self,window,master,main_tabs,tabs): style = ttk.Style() style.configure("TFrame", background='white') ttk.Frame.__init__(self,master,style='new.TFrame') self.window=window
random_line_split
errors.rs
// * This file is part of the uutils coreutils package. // * // * For the full copyright and license information, please view the LICENSE // * file that was distributed with this source code. use std::{ error::Error, fmt::{Debug, Display}, }; use uucore::error::UError; #[derive(Debug)] pub enum NumfmtErro...
IllegalArgument(String), FormattingError(String), } impl UError for NumfmtError { fn code(&self) -> i32 { match self { NumfmtError::IoError(_) => 1, NumfmtError::IllegalArgument(_) => 1, NumfmtError::FormattingError(_) => 2, } } } impl Error for Numf...
IoError(String),
random_line_split
errors.rs
// * This file is part of the uutils coreutils package. // * // * For the full copyright and license information, please view the LICENSE // * file that was distributed with this source code. use std::{ error::Error, fmt::{Debug, Display}, }; use uucore::error::UError; #[derive(Debug)] pub enum NumfmtErro...
(&self) -> i32 { match self { NumfmtError::IoError(_) => 1, NumfmtError::IllegalArgument(_) => 1, NumfmtError::FormattingError(_) => 2, } } } impl Error for NumfmtError {} impl Display for NumfmtError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::...
code
identifier_name
serializers.py
""" This module defines serializers for the main API data objects: .. autosummary:: :nosignatures: DimensionSerializer FilterSerializer MessageSerializer QuestionSerializer """ from django.core.paginator import Paginator from rest_framework import serializers, pagination import emoticonvis.apps...
class FeatureVectorSerializer(serializers.Serializer): message = MessageSerializer() tokens = serializers.ListField() feature_vector = serializers.ListField(child=serializers.DictField()) class FeatureCodeDistributionSerializer(serializers.Serializer): feature_index = serializers.IntegerField() f...
model = User fields = ('username', )
identifier_body
serializers.py
""" This module defines serializers for the main API data objects: .. autosummary:: :nosignatures: DimensionSerializer FilterSerializer MessageSerializer QuestionSerializer """ from django.core.paginator import Paginator from rest_framework import serializers, pagination import emoticonvis.apps...
class PaginatedMessageSerializer(pagination.PaginationSerializer): class Meta: object_serializer_class = MessageSerializer class DatasetSerializer(serializers.ModelSerializer): class Meta: model = corpus_models.Dataset fields = ('id', 'name', 'description', 'message_count', ) ...
random_line_split
serializers.py
""" This module defines serializers for the main API data objects: .. autosummary:: :nosignatures: DimensionSerializer FilterSerializer MessageSerializer QuestionSerializer """ from django.core.paginator import Paginator from rest_framework import serializers, pagination import emoticonvis.apps...
: model = corpus_models.Message fields = ('id', 'dataset', 'text', ) class UserSerializer(serializers.ModelSerializer): def to_representation(self, instance): return instance.username class Meta: model = User fields = ('username', ) class FeatureVectorSerializer(serial...
Meta
identifier_name
davfs.py
''' Datastore via remote webdav connection ''' from __future__ import unicode_literals from future import standard_library standard_library.install_aliases() import os import tarfile import logging from fs.contrib.davfs import DAVFS from urllib.parse import urlparse from contextlib import closing from sumatra.core im...
tf.close() tf_obj.close() # Delete original files. if delete_originals: for file_path in files: os.remove(os.path.join(self.root, file_path)) self._last_label = label # useful for testing return archive_paths
archive_path = os.path.join(label, file_path) tf.add(os.path.join(self.root, file_path), archive_path) archive_paths.append(archive_path)
conditional_block
davfs.py
''' Datastore via remote webdav connection ''' from __future__ import unicode_literals from future import standard_library standard_library.install_aliases() import os import tarfile import logging from fs.contrib.davfs import DAVFS from urllib.parse import urlparse from contextlib import closing from sumatra.core im...
# mandatory repeat content = property(fget=get_content) def _get_info(self): obj = self.store.dav_fs.open(self.tarfile_path, 'rb') with closing(tarfile.open(fileobj=obj)) as data_archive: return data_archive.getmember(self.path) return tarfile.TarInfo() @component cl...
obj = self.store.dav_fs.open(self.tarfile_path, 'rb') with closing(tarfile.open(fileobj=obj)) as data_archive: f = data_archive.extractfile(self.path) if max_length: content = f.read(max_length) else: content = f.read() f.close() ...
identifier_body
davfs.py
''' Datastore via remote webdav connection ''' from __future__ import unicode_literals from future import standard_library standard_library.install_aliases() import os import tarfile import logging from fs.contrib.davfs import DAVFS from urllib.parse import urlparse from contextlib import closing from sumatra.core im...
(self, root, dav_url, dav_user=None, dav_pw=None): super(DavFsDataStore, self).__init__(root) parsed = urlparse(dav_url) self.dav_user = dav_user or parsed.username self.dav_pw = dav_pw or parsed.password self.dav_url = parsed.geturl() self.dav_fs = DAVFS(url=self.dav_url...
__init__
identifier_name
davfs.py
''' Datastore via remote webdav connection ''' from __future__ import unicode_literals from future import standard_library standard_library.install_aliases() import os import tarfile import logging from fs.contrib.davfs import DAVFS from urllib.parse import urlparse from contextlib import closing from sumatra.core im...
# mandatory repeat content = property(fget=get_content) def _get_info(self): obj = self.store.dav_fs.open(self.tarfile_path, 'rb') with closing(tarfile.open(fileobj=obj)) as data_archive: return data_archive.getmember(self.path) return tarfile.TarInfo() @component cla...
return content
random_line_split
error.rs
of range; this can be used as an looser error prior to getting a definitive /// value for difficulty. This error needs only provide bounds of which it is out. DifficultyOutOfBounds(OutOfBounds<U256>), /// Difficulty header field is invalid; this is a strong error used after getting a definitive /// value for diffi...
from
identifier_name
error.rs
/// Transactions gas is higher then current gas limit GasLimitExceeded { /// Current gas limit limit: U256, /// Declared transaction gas got: U256, }, /// Transaction's gas limit (aka gas) is invalid. InvalidGasLimit(OutOfBounds<U256>), /// Transaction sender is banned. SenderBanned, /// Transaction rec...
#[derive(Debug, Clone, Copy, PartialEq)] /// Import to the block queue result pub enum ImportError { /// Already in the block chain. AlreadyInChain, /// Already in the block queue. AlreadyQueued, /// Already marked as bad from a previous import (could mean parent is bad). KnownBad, } impl fmt::Display for Import...
f.write_fmt(format_args!("Block error ({})", msg)) } }
random_line_split
build.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/. */ use std::env; use std::path::Path; use std::process::{Command, exit}; #[cfg(windows)] fn find_python() -> String ...
() -> String { if Command::new("python2.7").arg("--version").output().unwrap().status.success() { "python2.7" } else { "python" }.to_owned() } fn main() { let python = env::var("PYTHON").ok().unwrap_or_else(find_python); // Mako refuses to load templates outside the scope of the cu...
find_python
identifier_name
build.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/. */ use std::env; use std::path::Path; use std::process::{Command, exit}; #[cfg(windows)] fn find_python() -> String ...
.to_owned() } fn main() { let python = env::var("PYTHON").ok().unwrap_or_else(find_python); // Mako refuses to load templates outside the scope of the current working directory, // so we need to run it from the top source directory. let geckolib_dir = Path::new(file!()).parent().unwrap(); let top_...
{ "python" }
conditional_block
build.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/. */ use std::env; use std::path::Path; use std::process::{Command, exit}; #[cfg(windows)] fn find_python() -> String ...
// Mako refuses to load templates outside the scope of the current working directory, // so we need to run it from the top source directory. let geckolib_dir = Path::new(file!()).parent().unwrap(); let top_dir = geckolib_dir.join("..").join(".."); let properties_dir = Path::new("components").join(...
fn main() { let python = env::var("PYTHON").ok().unwrap_or_else(find_python);
random_line_split
build.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/. */ use std::env; use std::path::Path; use std::process::{Command, exit}; #[cfg(windows)] fn find_python() -> String ...
exit(1) } }
{ let python = env::var("PYTHON").ok().unwrap_or_else(find_python); // Mako refuses to load templates outside the scope of the current working directory, // so we need to run it from the top source directory. let geckolib_dir = Path::new(file!()).parent().unwrap(); let top_dir = geckolib_dir.join("...
identifier_body
CylinderMCNPX.py
Created += 1 return s,c,detectorCells,cellsCreated def runModel(self): """ Runs the Model by submission to Tourqe / Maui """ qsub= subprocess.check_output('which qsub',shell=True).strip() cmd = '#!/bin/bash\n' cmd += '#PBS -N {0}\n#PBS -V\n#PBS -q gen1\n...
(self,cylinderPositions,inp=None,name=None): """ createInputDeck Creates an input deck of the given geometry """ self.inp = inp self.name = name if not inp: self.inp = 'INP_Cylinder.mcnp' if not name: self.name = 'OUT_Cylinder.' o...
createInputDeck
identifier_name
CylinderMCNPX.py
# List of cells for the detector if self.surfGeo[key] is 'Detector': detectorCells.append(cNum) cellsCreated += 1 # Last cell up to universe boundary m = self.material['Moderator'] c += '{:5d} {:d} -{:4.3f} {:d} u={:d}\n'.format(cNum+1,m['mt']...
c += self.cellForStr.format(cNum,m['mt'],m['rho'],sPrev,sNum,uNum)
conditional_block
CylinderMCNPX.py
.70c -0.599848 8016.70c -0.319614 \n' matString += 'm204 7014.70c -0.755636 $air (US S. Atm at sea level) rho = 0.001225 \n' matString += ' 8016.70c -0.231475 18036.70c -3.9e-005 18038.70c -8e-006\n' matString += ' 18040.70c -0.0...
""" Extracts the loading and polymer from the file name """ tokens = filename.split('_') loading = tokens[1].strip('LiF') polymer = tokens[2].strip('.m') return (float(loading)/100, polymer)
identifier_body
CylinderMCNPX.py
094.70c -0.002264\n' matString += ' 42095.70c -0.003937 42096.70c -0.004169 42097.70c -0.002412\n' matString += ' 42098.70c -0.006157 42100.70c -0.002507 \n' matString += 'mt3 poly.01t ...
parser.add_argument('-o','--optimize',action='store',type=int,default=-1,help='Run a number of optimizations on the positions. If 0 is entered a summary is preformed on the directory provided with path')
random_line_split
rand.rs
// Copyright 2012-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-MI...
use ast; use ast::{MetaItem, item, Expr, Ident}; use codemap::Span; use ext::base::ExtCtxt; use ext::build::{AstBuilder}; use ext::deriving::generic::*; use std::vec; pub fn expand_deriving_rand(cx: @ExtCtxt, span: Span, mitem: @MetaItem, ...
random_line_split
rand.rs
// Copyright 2012-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-MI...
StaticEnum(_, ref variants) => { if variants.is_empty() { cx.span_fatal(span, "`Rand` cannot be derived for enums with no variants"); } let variant_count = cx.expr_uint(span, variants.len()); let rand_name = cx.path_all(span, ...
{ rand_thing(cx, span, substr.type_ident, summary, rand_call) }
conditional_block
file_metadata_indexer.py
from django.core.management.base import BaseCommand from home.models import ReplicaSet, WhatTorrent, \ TransTorrent, WhatFileMetadataCache class Command(BaseCommand): help = u'Cache all .flac and .mp3 metadata in download locations.' def handle(self, *args, **options): masters = ReplicaSet.get_w...
try: WhatFileMetadataCache.get_metadata_batch(what_torrent, trans_torrent, True) except Exception as ex: print 'Failed updating torrent {0}: {1}'.format(what_torrent.id, ex)
conditional_block
file_metadata_indexer.py
from django.core.management.base import BaseCommand from home.models import ReplicaSet, WhatTorrent, \ TransTorrent, WhatFileMetadataCache class Command(BaseCommand): help = u'Cache all .flac and .mp3 metadata in download locations.' def
(self, *args, **options): masters = ReplicaSet.get_what_master().transinstance_set.all() what_torrent_ids = WhatTorrent.objects.all().values_list('id', flat=True) start = 0 page_size = 128 while start < len(what_torrent_ids): print 'Updating objects {0}-{1}/{2}'.forma...
handle
identifier_name
file_metadata_indexer.py
from django.core.management.base import BaseCommand from home.models import ReplicaSet, WhatTorrent, \ TransTorrent, WhatFileMetadataCache class Command(BaseCommand): help = u'Cache all .flac and .mp3 metadata in download locations.' def handle(self, *args, **options):
print 'Failed updating torrent {0}: {1}'.format(what_torrent.id, ex)
masters = ReplicaSet.get_what_master().transinstance_set.all() what_torrent_ids = WhatTorrent.objects.all().values_list('id', flat=True) start = 0 page_size = 128 while start < len(what_torrent_ids): print 'Updating objects {0}-{1}/{2}'.format(start, start + page_size, ...
identifier_body
file_metadata_indexer.py
from django.core.management.base import BaseCommand from home.models import ReplicaSet, WhatTorrent, \ TransTorrent, WhatFileMetadataCache class Command(BaseCommand): help = u'Cache all .flac and .mp3 metadata in download locations.' def handle(self, *args, **options): masters = ReplicaSet.get_w...
TransTorrent.objects.filter(instance__in=masters, what_torrent__in=bulk.values()) } for what_torrent in bulk.itervalues(): trans_torrent = trans_torrents.get(what_torrent.id) if trans_torrent is not None and trans_torrent.torrent_done == 1: ...
what_torrent_ids[start:start + page_size]) start += page_size trans_torrents = { t.what_torrent_id: t for t in
random_line_split
__init__.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
from ._policy_tracked_resources_operations import PolicyTrackedResourcesOperations from ._remediations_operations import RemediationsOperations from ._policy_events_operations import PolicyEventsOperations from ._policy_states_operations import PolicyStatesOperations from ._operations import Operations from ._policy_m...
# --------------------------------------------------------------------------
random_line_split
e127.py
from __future__ import print_function, division import matplotlib matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab! from neuralnilm import Net, RealApplianceSource, BLSTMLayer, SubsampleLayer, DimshuffleLayer from lasagne.nonlinearities import sigmoid, rectify from lasagne.objectives import c...
(): for experiment in list('a'): full_exp_name = NAME + experiment path = os.path.join(PATH, full_exp_name) try: net = init_experiment(experiment) run_experiment(net, path, epochs=5000) except KeyboardInterrupt: break except TrainingError a...
main
identifier_name
e127.py
from __future__ import print_function, division import matplotlib matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab! from neuralnilm import Net, RealApplianceSource, BLSTMLayer, SubsampleLayer, DimshuffleLayer from lasagne.nonlinearities import sigmoid, rectify from lasagne.objectives import c...
main()
conditional_block
e127.py
from lasagne.objectives import crossentropy, mse from lasagne.init import Uniform, Normal from lasagne.layers import LSTMLayer, DenseLayer, Conv1DLayer, ReshapeLayer from lasagne.updates import adagrad, nesterov_momentum from functools import partial import os from neuralnilm.source import standardise from neuralnilm.e...
from __future__ import print_function, division import matplotlib matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab! from neuralnilm import Net, RealApplianceSource, BLSTMLayer, SubsampleLayer, DimshuffleLayer from lasagne.nonlinearities import sigmoid, rectify
random_line_split
e127.py
from __future__ import print_function, division import matplotlib matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab! from neuralnilm import Net, RealApplianceSource, BLSTMLayer, SubsampleLayer, DimshuffleLayer from lasagne.nonlinearities import sigmoid, rectify from lasagne.objectives import c...
if __name__ == "__main__": main()
for experiment in list('a'): full_exp_name = NAME + experiment path = os.path.join(PATH, full_exp_name) try: net = init_experiment(experiment) run_experiment(net, path, epochs=5000) except KeyboardInterrupt: break except TrainingError as e: ...
identifier_body
customizer.js
/** * Theme Customizer enhancements for a better user experience. * * Contains handlers to make Theme Customizer preview reload changes asynchronously. */ ( function( $ ) { // Site title and description. wp.customize( 'blogname', function( value ) { value.bind( function( to ) { $( '.site-title a' ).text( to...
value.bind( function( newval ) { $('.site-description').css('font-size', newval + 'px' ); } ); }); wp.customize('body_size',function( value ) { value.bind( function( newval ) { $('body').css('font-size', newval + 'px' ); } ); }); //Site title wp.customize('site_titl...
value.bind( function( newval ) { $('.site-title').css('font-size', newval + 'px' ); } ); }); wp.customize('site_desc_size',function( value ) {
random_line_split
jquery.fancybox-1.3.4.js
_pos.height + (final_pos.height - start_pos.height) * pos, 10), top : parseInt(start_pos.top + (final_pos.top - start_pos.top) * pos, 10), left : parseInt(start_pos.left + (final_pos.left - start_pos.left) * pos, 10) }; if (typeof final_pos.opacity !== 'undefined') { dim.opacity = pos < 0.5 ? 0.5 : ...
_cleanup
identifier_name
jquery.fancybox-1.3.4.js
textStatus, XMLHttpRequest); if (ret === false) { loading.hide(); return; } else if (typeof ret == 'string' || typeof ret == 'object') { data = ret; } } tmp.html( data ); _process_inline(); } } })); break; ca...
else { overlay.hide(); } final_pos = _get_zoom_to(); _process_title(); if (wrap.is(":visible")) { $( close.add( nav_left ).add( nav_right ) ).hide(); pos = wrap.position(), start_pos = { top : pos.top, left : pos.left, width : wrap.width(), height : wrap.height() ...
{ overlay.css({ 'background-color' : currentOpts.overlayColor, 'opacity' : currentOpts.overlayOpacity, 'cursor' : currentOpts.hideOnOverlayClick ? 'pointer' : 'auto', 'height' : $(document).height() }); if (!overlay.is(':visible')) { if (isIE6) { $('select:not(#fancybox-tmp s...
conditional_block
jquery.fancybox-1.3.4.js
}; } else { view = _get_viewport(); from = { width : currentOpts.padding * 2, height : currentOpts.padding * 2, top : parseInt(view[3] + view[1] * 0.5, 10), left : parseInt(view[2] + view[0] * 0.5, 10) }; } return from; }, _animate_loading = function() { if (!loa...
random_line_split
jquery.fancybox-1.3.4.js
= pos < 0.5 ? 0.5 : pos; } wrap.css(dim); content.css({ 'width' : dim.width - currentOpts.padding * 2, 'height' : dim.height - (titleHeight * pos) - currentOpts.padding * 2 }); }, _get_viewport = function() { return [ $(window).width() - (currentOpts.margin * 2), $(window).height(...
{ overlay.fadeOut('fast'); title.empty().hide(); wrap.hide(); $.event.trigger('fancybox-cleanup'); content.empty(); currentOpts.onClosed(currentArray, currentIndex, currentOpts); currentArray = selectedOpts = []; currentIndex = selectedIndex = 0; currentOpts = selectedOpts = {}; busy...
identifier_body
scorer_regression.rs
#[cfg(test)] mod scorer_regression_test { use zip::read::ZipArchive; use std::fs::File; use std::io::Read; use base::gametree::*; use base::game::*; use base::*; //#[test] fn it_scores_all_games_in_regression_tests() { let mut total = 0; let mut total_conservative_ra...
if cons_r.includes(gt.result()) { conservative_ok = conservative_ok + 1 } if opt_r.includes(gt.result()) { optimistic_ok = optimistic_ok + 1; }...
{ if let Ok(gt) = sgf::parse(content) { if !gt.result().is_resign() && !gt.result().is_time() { println!("Filename: {}", file.name()); let mut ok = true; let mut game = game::Game::new_for_gametree(&gt); ...
conditional_block
scorer_regression.rs
#[cfg(test)] mod scorer_regression_test { use zip::read::ZipArchive; use std::fs::File; use std::io::Read; use base::gametree::*; use base::game::*; use base::*; //#[test] fn
() { let mut total = 0; let mut total_conservative_range : usize = 0; let mut conservative_ok = 0; let mut total_optimistic_range : usize = 0; let mut optimistic_ok = 0; let mut zipf = File::open("sgfs-db/kgs-newest/dl.u-go.net/gamerecords/KGS-2015_01-19-1212-.zip").un...
it_scores_all_games_in_regression_tests
identifier_name
scorer_regression.rs
#[cfg(test)] mod scorer_regression_test { use zip::read::ZipArchive; use std::fs::File; use std::io::Read; use base::gametree::*; use base::game::*; use base::*; //#[test] fn it_scores_all_games_in_regression_tests()
if !gt.result().is_resign() && !gt.result().is_time() { println!("Filename: {}", file.name()); let mut ok = true; let mut game = game::Game::new_for_gametree(&gt); for m in gt.moves() { ...
{ let mut total = 0; let mut total_conservative_range : usize = 0; let mut conservative_ok = 0; let mut total_optimistic_range : usize = 0; let mut optimistic_ok = 0; let mut zipf = File::open("sgfs-db/kgs-newest/dl.u-go.net/gamerecords/KGS-2015_01-19-1212-.zip").unwra...
identifier_body
scorer_regression.rs
#[cfg(test)] mod scorer_regression_test { use zip::read::ZipArchive; use std::fs::File; use std::io::Read; use base::gametree::*; use base::game::*; use base::*; //#[test] fn it_scores_all_games_in_regression_tests() { let mut total = 0; let mut total_conservative_ran...
} if ok { let cons_r = scorer::conservative_floodfill_scorer(&game); println!("Conservative est: {} real:{} is good estimation? {}", cons_r, gt.result(), cons_r.includes(gt.result())); le...
if !game.play(m.themove()) { println!("move failed: {:?}", m.themove()); ok = false; }
random_line_split
comm.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 ...
{ error!("sending"); c.send(10); error!("value sent"); }
identifier_body
comm.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 ...
(c: &Chan<int>) { error!("sending"); c.send(10); error!("value sent"); }
child
identifier_name
comm.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
let _t = task::spawn(proc() child(&ch)); let y = p.recv(); error!("received"); error!("{:?}", y); assert_eq!(y, 10); } fn child(c: &Chan<int>) { error!("sending"); c.send(10); error!("value sent"); }
random_line_split
sum.rs
#![crate_name = "uu_sum"] /* * This file is part of the uutils coreutils package. * * (c) T. Jameson Little <t.jameson.little@gmail.com> * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. */ extern crate getopts; #[macro_use] extern crate uu...
else { println!("{} {}", sum, blocks); } } 0 }
{ println!("{} {} {}", sum, blocks, file); }
conditional_block
sum.rs
#![crate_name = "uu_sum"] /* * This file is part of the uutils coreutils package. * * (c) T. Jameson Little <t.jameson.little@gmail.com> * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. */ extern crate getopts; #[macro_use] extern crate uu...
pub fn uumain(args: Vec<String>) -> i32 { let mut opts = getopts::Options::new(); opts.optflag("r", "", "use the BSD compatible algorithm (default)"); opts.optflag("s", "sysv", "use System V compatible algorithm"); opts.optflag("h", "help", "show this help message"); opts.optflag("v", "version", ...
{ match name { "-" => Ok(Box::new(stdin()) as Box<Read>), _ => { let f = try!(File::open(&Path::new(name))); Ok(Box::new(f) as Box<Read>) } } }
identifier_body
sum.rs
#![crate_name = "uu_sum"] /* * This file is part of the uutils coreutils package. * * (c) T. Jameson Little <t.jameson.little@gmail.com> * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. */ extern crate getopts; #[macro_use] extern crate uu...
(mut reader: Box<Read>) -> (usize, u16) { let mut buf = [0; 1024]; let mut blocks_read = 0; let mut checksum: u16 = 0; loop { match reader.read(&mut buf) { Ok(n) if n != 0 => { blocks_read += 1; for &byte in buf[..n].iter() { checks...
bsd_sum
identifier_name
sum.rs
#![crate_name = "uu_sum"] /* * This file is part of the uutils coreutils package. * * (c) T. Jameson Little <t.jameson.little@gmail.com> * * For the full copyright and license information, please view the LICENSE file * that was distributed with this source code. */ extern crate getopts; #[macro_use] extern crate uu...
blocks_read += 1; for &byte in buf[..n].iter() { ret = ret.wrapping_add(byte as u32); } }, _ => break, } } ret = (ret & 0xffff) + (ret >> 16); ret = (ret & 0xffff) + (ret >> 16); (blocks_read, ret as u1...
loop { match reader.read(&mut buf) { Ok(n) if n != 0 => {
random_line_split
lib.rs
pub mod checksum; use crate::checksum::Result; use pretty_toa::ThousandsSep; use std::io::Write; use std::path::PathBuf; use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor}; pub fn print_res(samples: &[i64; 32]) { let mut stdout = StandardStream::stdout(ColorChoice::Always); let min = ...
writeln!(&mut stdout, "Std. Deviation: {} ", stddev.thousands_sep()).unwrap(); } pub fn bench_checksum(msg: String, songs: &Vec<PathBuf>, f: &dyn Fn(&PathBuf) -> Result) { let mut stdout = StandardStream::stdout(ColorChoice::Always); stdout .set_color(ColorSpec::new().set_fg(Some(Color::White))) ...
write!(&mut stdout, "---- ").unwrap(); stdout .set_color(ColorSpec::new().set_fg(Some(Color::Magenta))) .unwrap();
random_line_split
lib.rs
pub mod checksum; use crate::checksum::Result; use pretty_toa::ThousandsSep; use std::io::Write; use std::path::PathBuf; use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor}; pub fn print_res(samples: &[i64; 32])
write!(&mut stdout, "Min: {}", min.thousands_sep()).unwrap(); stdout .set_color(ColorSpec::new().set_fg(Some(Color::White))) .unwrap(); write!(&mut stdout, " | ").unwrap(); stdout .set_color(ColorSpec::new().set_fg(Some(Color::Red))) .unwrap(); write!(&mut stdout, "Ma...
{ let mut stdout = StandardStream::stdout(ColorChoice::Always); let min = samples.iter().min().unwrap(); let max = samples.iter().max().unwrap(); let avg: i64 = samples.iter().sum::<i64>() / samples.len() as i64; let stddev = (samples .iter() .map(|v| (v - avg) as f64) .map(...
identifier_body
lib.rs
pub mod checksum; use crate::checksum::Result; use pretty_toa::ThousandsSep; use std::io::Write; use std::path::PathBuf; use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor}; pub fn print_res(samples: &[i64; 32]) { let mut stdout = StandardStream::stdout(ColorChoice::Always); let min = ...
(msg: String, songs: &Vec<PathBuf>, f: &dyn Fn(&PathBuf) -> Result) { let mut stdout = StandardStream::stdout(ColorChoice::Always); stdout .set_color(ColorSpec::new().set_fg(Some(Color::White))) .unwrap(); writeln!(&mut stdout, "{}", msg).unwrap(); for song in songs { let mut sa...
bench_checksum
identifier_name
main.rs
#[macro_use] extern crate lazy_static; extern crate regex; use std::str::FromStr; use std::io::Read; #[derive(Debug)] enum IngestionState { Take, Duplicate { occ: usize, rem: usize, buf: String } } fn parse_marker(s: &str) -> (usize, usize) { let (occ, rep) = s.split_at(s.find...
(s: &str) -> IngestionState { let (len, rep) = parse_marker(s); Duplicate { rem: len, occ: rep, buf: String::new() } } } #[derive(Debug)] struct Decompressor { decompressed: String, state: IngestionState, } #[derive(Debug)] enum BlockType { W...
from_marker
identifier_name
main.rs
#[macro_use] extern crate lazy_static; extern crate regex; use std::str::FromStr; use std::io::Read; #[derive(Debug)] enum IngestionState { Take, Duplicate { occ: usize, rem: usize, buf: String } } fn parse_marker(s: &str) -> (usize, usize) { let (occ, rep) = s.split_at(s.find...
} fn split(compressed: &str) -> Vec<(BlockType, &str)> { let mut blocks = Vec::new(); lazy_static! { static ref RE: regex::Regex = regex::Regex::new("(\\w+)?(\\(\\w+\\))?").unwrap(); } for cap in RE.captures_iter(compressed) { if let Some(s) = cap.at(1) { blocks.push((BlockTy...
Marker
random_line_split
main.rs
#[macro_use] extern crate lazy_static; extern crate regex; use std::str::FromStr; use std::io::Read; #[derive(Debug)] enum IngestionState { Take, Duplicate { occ: usize, rem: usize, buf: String } } fn parse_marker(s: &str) -> (usize, usize) { let (occ, rep) = s.split_at(s.find...
*rem -= block.1.len(); } } } if switch_to_take { decomp.state = Take; } } fn decompress(s: &str) -> String { let mut decompressor = Decompressor {decompressed: String::new(), state: Take}; for b in split(s) { ingest_block(&mut decompressor, b) ...
{ let mut switch_to_take = false; match (&mut decomp.state, block.0) { (&mut Take, Word) => decomp.decompressed += block.1, (s @ &mut Take, Marker) => *s = IngestionState::from_marker(block.1), (&mut Duplicate {ref occ, ref mut rem, ref mut buf}, _) => { ...
identifier_body
protocol.rs
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
match header_name.as_ref() { "content-length:" => { size = Some(usize::from_str_radix(header_value, 10).map_err(|_e| { io::Error::new(io::ErrorKind::InvalidData, "Couldn't read size") })?); } "content-type:" => { ...
let header_name = res[0].to_lowercase(); let header_value = res[1].trim();
random_line_split
protocol.rs
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
{ std::io::stdout().write(format!("Content-Length: {}\r\n\r\n", content.len()).as_bytes())?; std::io::stdout().write(content.as_bytes())?; std::io::stdout().flush()?; Ok(()) }
identifier_body
protocol.rs
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
<R: BufRead>(input: &mut R) -> Result<String, io::Error> { // Read in the "Content-Length: xx" part. let mut size: Option<usize> = None; loop { let mut buffer = String::new(); input.read_line(&mut buffer)?; // End of input. if buffer.is_empty() { return Err(io::E...
read_message
identifier_name
Form.File.js
/* JSPWiki - a JSP-based WikiWiki clone. 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 Apac...
(bytes, precision){ var exp = " KMGT".split(""), K = 1024; while( bytes >= K ){ bytes /= K; exp.shift(); } return bytes.toFixed(precision || 1) + " " + ( exp[0] || "" ) + "B"; } //"use strict"; if (!this.Form) this.Form = {}; var Form = this.Form; Form.File = new Class({ Implemen...
readableFileSize
identifier_name
Form.File.js
/* JSPWiki - a JSP-based WikiWiki clone. 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 Apac...
//"use strict"; if (!this.Form) this.Form = {}; var Form = this.Form; Form.File = new Class({ Implements: [Options, Events], options: { max: 5, //maximum number of files to upload in one go... 0=unlimited. list: ".list-group", item: ".list-group-item", drop: ".droppable", ...
{ var exp = " KMGT".split(""), K = 1024; while( bytes >= K ){ bytes /= K; exp.shift(); } return bytes.toFixed(precision || 1) + " " + ( exp[0] || "" ) + "B"; }
identifier_body
Form.File.js
/* JSPWiki - a JSP-based WikiWiki clone. 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 Apac...
Creates a multiple file upload form, based on styles from Bootstrap. Includes a json-rpc based progress-bar implemention for non-xhr2.0 browsers See also: [Form.File.Multiple, Request.File] Credit: Arian Stolwijk, [https://github.com/arian/mootools-form-upload] */ !(function(){ function readableFile...
random_line_split
Form.File.js
/* JSPWiki - a JSP-based WikiWiki clone. 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 Apac...
/* for (var i = 0; i < files.length; i++){ inputFiles.remove(files[i]); } */ }; }, /* Function: upload Legacy upload handler, compatible with legacy input[type=file] capabilities. The script works by hiding the file...
{ inputFiles.remove( files.shift() ); }
conditional_block
test_model.py
import unittest import os from model.index import Index from model.page import Page class TestPage(unittest.TestCase): def test_str_outputStringIsAsExpected(self): test_page = Page() test_page.title = 'D01' test_page.content = 'Bla Bla Blub' expected_output = os.linesep.join([ ...
unittest.main()
random_line_split
test_model.py
import unittest import os from model.index import Index from model.page import Page class
(unittest.TestCase): def test_str_outputStringIsAsExpected(self): test_page = Page() test_page.title = 'D01' test_page.content = 'Bla Bla Blub' expected_output = os.linesep.join([ '---------------------------------------------------------------------------', ...
TestPage
identifier_name
test_model.py
import unittest import os from model.index import Index from model.page import Page class TestPage(unittest.TestCase): def test_str_outputStringIsAsExpected(self):
class TestIndex(unittest.TestCase): def test_createDummyIndex_str_outputStringIsAsExpected(self): expected_output = os.linesep.join([ 'index.txt', '¯¯¯¯¯¯¯¯¯', '(DaDaDa, df:1) -> [(\'d01\', 2)]', '(DumDiDum, df:2) -> [(\'d02\', 1), (\'d03\', 1)]', ...
test_page = Page() test_page.title = 'D01' test_page.content = 'Bla Bla Blub' expected_output = os.linesep.join([ '---------------------------------------------------------------------------', 'D01', '----------------------------------------------------------...
identifier_body
test_model.py
import unittest import os from model.index import Index from model.page import Page class TestPage(unittest.TestCase): def test_str_outputStringIsAsExpected(self): test_page = Page() test_page.title = 'D01' test_page.content = 'Bla Bla Blub' expected_output = os.linesep.join([ ...
main()
conditional_block
ContactForm.tsx
import { ButtonGroup, Input, Page } from '@emeraldplatform/ui'; import { BlockchainCode } from '@emeraldwallet/core'; import { Button, ChainSelector } from '@emeraldwallet/ui'; import { CSSProperties, withStyles } from '@material-ui/styles'; import * as React from 'react'; export const styles = { formRow: { disp...
} public handleSubmit = () => { if (this.props.onSubmit) { const { address, name, blockchain } = this.state; this.props.onSubmit({ blockchain, address, name, description: '' }); } } public handleAddressChange = (event: any) => { this.setState({ address: event.target.value })...
{ this.props.onCancel(); }
conditional_block
ContactForm.tsx
import { ButtonGroup, Input, Page } from '@emeraldplatform/ui'; import { BlockchainCode } from '@emeraldwallet/core'; import { Button, ChainSelector } from '@emeraldwallet/ui'; import { CSSProperties, withStyles } from '@material-ui/styles'; import * as React from 'react'; export const styles = { formRow: { disp...
(props: IContactFormProps) { super(props); this.state = { ...this.props.initialValues, blockchain: (props.blockchains && props.blockchains.length > 0) ? props.blockchains[0].params.code : BlockchainCode.ETH }; } public handleCancel = () => { if (this.props.onCancel) { this.props....
constructor
identifier_name
ContactForm.tsx
import { ButtonGroup, Input, Page } from '@emeraldplatform/ui'; import { BlockchainCode } from '@emeraldwallet/core'; import { Button, ChainSelector } from '@emeraldwallet/ui'; import { CSSProperties, withStyles } from '@material-ui/styles'; import * as React from 'react'; export const styles = { formRow: { disp...
marginRight: '14.75px' }, right: { flexGrow: 2, display: 'flex', alignItems: 'center', marginLeft: '14.75px', marginRight: '14.75px', maxWidth: '580px' }, fieldName: { fontSize: '16px', textAlign: 'right' } as CSSProperties }; export interface IContactFormProps { classes...
}, left: { flexBasis: '20%', marginLeft: '14.75px',
random_line_split
ContactForm.tsx
import { ButtonGroup, Input, Page } from '@emeraldplatform/ui'; import { BlockchainCode } from '@emeraldwallet/core'; import { Button, ChainSelector } from '@emeraldwallet/ui'; import { CSSProperties, withStyles } from '@material-ui/styles'; import * as React from 'react'; export const styles = { formRow: { disp...
public handleCancel = () => { if (this.props.onCancel) { this.props.onCancel(); } } public handleSubmit = () => { if (this.props.onSubmit) { const { address, name, blockchain } = this.state; this.props.onSubmit({ blockchain, address, name, description: '' }); } } public h...
{ super(props); this.state = { ...this.props.initialValues, blockchain: (props.blockchains && props.blockchains.length > 0) ? props.blockchains[0].params.code : BlockchainCode.ETH }; }
identifier_body
index.js
'use strict'; var chai = require('chai'); var expect = chai.expect; exports.basicSuperAgentRequestSuccess = function basicSuperAgentRequestSuccess(err, res, statusCode) { expect(err, 'should not have an err').to.not.exist; expect(res.status, 'should have the expected status').to.eql(statusCode || 200); expect(re...
expect(res.text).to.not.exist; expect(res.body, 'expect body to exist').to.exist; }; exports.assertBadSuperAgentRequest = function assertBadSuperAgentRequest(err, res, statusCode) { expect(err, 'expect err to exist').to.exist; expect(res, 'expect res to exist').to.exist; expect(res.status, 'status should equ...
expect(err, 'should not have an err object').to.not.exist; expect(res.status, 'should have a statusCode of 200').to.eql(200); expect(res.data).to.not.exist;
random_line_split
metrics.ts
import { ClientOptions } from '@elastic/elasticsearch' import { ElasticsearchMetricReporter } from 'inspector-elasticsearch' import { Event, MetricRegistry } from 'inspector-metrics' import { V8EventLoop, V8GCMetrics, V8MemoryMetrics, V8ProcessMetrics } from 'inspector-vm' import { hostname } from 'os' export ...
this.reporter.addMetricRegistry(this.registry) await this.reporter.start() } public async reportEvent (event: Event<any>): Promise<Event<any>> { return await this.reporter.reportEvent(event) } }
reportingTags.set('version', this.packageJson.version) this.reporter.setTags(reportingTags)
random_line_split
metrics.ts
import { ClientOptions } from '@elastic/elasticsearch' import { ElasticsearchMetricReporter } from 'inspector-elasticsearch' import { Event, MetricRegistry } from 'inspector-metrics' import { V8EventLoop, V8GCMetrics, V8MemoryMetrics, V8ProcessMetrics } from 'inspector-vm' import { hostname } from 'os' export ...
{ public readonly reporter: ElasticsearchMetricReporter; public readonly registry: MetricRegistry; public readonly packageJson: any; public constructor () { const clientOptions: ClientOptions = { node: 'http://localhost:9200' } this.registry = new MetricRegistry() this.reporter = new Ela...
MetricsSupport
identifier_name
metrics.ts
import { ClientOptions } from '@elastic/elasticsearch' import { ElasticsearchMetricReporter } from 'inspector-elasticsearch' import { Event, MetricRegistry } from 'inspector-metrics' import { V8EventLoop, V8GCMetrics, V8MemoryMetrics, V8ProcessMetrics } from 'inspector-vm' import { hostname } from 'os' export ...
public async reportEvent (event: Event<any>): Promise<Event<any>> { return await this.reporter.reportEvent(event) } }
{ this.registry.registerMetric(new V8GCMetrics('gc', this.registry.getDefaultClock())) this.registry.registerMetric(new V8MemoryMetrics('memory')) this.registry.registerMetric(new V8EventLoop('eventLoop')) this.registry.registerMetric(new V8ProcessMetrics('process')) this.registry.setTag('hostname',...
identifier_body
crc.rs
, 0x80d7, 0x00d2, 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1, 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1, 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082, 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192, 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81...
{ assert_eq!(crc8(&[0x1f]), 0x5d); assert_eq!(crc8(&[0x04, 0x01]), 0x53); assert_eq!(crc8(&[0x61, 0x62, 0x63]), 0x5f); assert_eq!(crc8(&[0x94]), 0xe5); assert_eq!(crc8(&[0x36, 0xa7]), 0xfb); assert_eq!(crc8(&[0x4f, 0x9e, 0x4b]), 0x00); }
identifier_body
crc.rs
0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072, 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041, 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2, 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1, 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1, 0x809...
#[cfg(test)] mod tests { use super::*;
random_line_split
crc.rs
0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022, 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072, 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041, 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2, 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4,...
crc16
identifier_name
client_async.rs
extern crate solicit; use solicit::http::Header;
fn main() { // Connect to a server that supports HTTP/2 let connector = CleartextConnector::new("http2bin.org"); let client = Client::with_connector(connector).unwrap(); // Issue 5 requests from 5 different threads concurrently and wait for all // threads to receive their response. let threads...
use solicit::client::Client; use solicit::http::client::CleartextConnector; use std::thread; use std::str;
random_line_split
client_async.rs
extern crate solicit; use solicit::http::Header; use solicit::client::Client; use solicit::http::client::CleartextConnector; use std::thread; use std::str; fn main()
println!(" {}: {}", str::from_utf8(header.name()).unwrap(), str::from_utf8(header.value()).unwrap()); } println!("Body:"); println!("{}", str::from_utf8(&response.body).unwrap()); }) }).collect(); let _: Ve...
{ // Connect to a server that supports HTTP/2 let connector = CleartextConnector::new("http2bin.org"); let client = Client::with_connector(connector).unwrap(); // Issue 5 requests from 5 different threads concurrently and wait for all // threads to receive their response. let threads: Vec<_> = ...
identifier_body
client_async.rs
extern crate solicit; use solicit::http::Header; use solicit::client::Client; use solicit::http::client::CleartextConnector; use std::thread; use std::str; fn
() { // Connect to a server that supports HTTP/2 let connector = CleartextConnector::new("http2bin.org"); let client = Client::with_connector(connector).unwrap(); // Issue 5 requests from 5 different threads concurrently and wait for all // threads to receive their response. let threads: Vec<_>...
main
identifier_name
signalGenerator.py
#!/usr/bin/env python #-*- coding: utf-8 -*- ''' # This file is part of Matching Pursuit Python program (python-MP). # # python-MP is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 ...
position1 = 3.0 position2 = 1.0 width = 0.5 frequency1 = 12.0 frequency2 = 15.0 phase = 0.0 gaborParams = np.array([[numberOfSamples,samplingFreq,amplitude,position1,width,frequency1,phase],[numberOfSamples,samplingFreq,amplitude,position2,width,frequency2,phase]]) sin...
random_line_split
signalGenerator.py
#!/usr/bin/env python #-*- coding: utf-8 -*- ''' # This file is part of Matching Pursuit Python program (python-MP). # # python-MP is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 ...
ind1 = 0 if sinusParams is not None: for param in sinusParams: freq = (param[1] / (0.5*samplingFrequency) ) * np.pi signal += np.array(param[0] * np.sin(freq * time + param[2])) ind1 += 1 if silenceFlag == 0: print '{} sinusoids generated'.format(ind1) ind1 = 0 if asymetricWaveformsAParams is ...
print '{} gabors generated'.format(ind1)
conditional_block
signalGenerator.py
#!/usr/bin/env python #-*- coding: utf-8 -*- ''' # This file is part of Matching Pursuit Python program (python-MP). # # python-MP is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 ...
structure = loadmat(nameOfFile) data = structure['EEG']['data'][0][0] data = data.transpose([2,0,1]) info = {} info['samplingFreq'] = structure['EEG']['srate'][0][0][0][0] info['numberOfChannels'] = structure['EEG']['nbchan'][0][0][0][0] info['numberOfSamples'] = structure['EEG']['pnts'][0][0][0][0] in...
identifier_body
signalGenerator.py
#!/usr/bin/env python #-*- coding: utf-8 -*- ''' # This file is part of Matching Pursuit Python program (python-MP). # # python-MP is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 ...
(nameOfFile): structure = loadmat(nameOfFile) data = structure['EEG']['data'][0][0] data = data.transpose([2,0,1]) info = {} info['samplingFreq'] = structure['EEG']['srate'][0][0][0][0] info['numberOfChannels'] = structure['EEG']['nbchan'][0][0][0][0] info['numberOfSamples'] = structure['EEG']['pnts'][...
loadSyntheticSigmalFromEEGLABFile
identifier_name
app.py
from twisted.application.service import Application from twisted.application.internet import TimerService, TCPServer from twisted.web import server from twisted.python import log from scrapy.utils.misc import load_object from .interfaces import IEggStorage, IPoller, ISpiderScheduler, IEnvironment from .launcher impor...
(config): app = Application("Scrapyd") http_port = config.getint('http_port', 6800) bind_address = config.get('bind_address', '0.0.0.0') poller = QueuePoller(config) eggstorage = FilesystemEggStorage(config) scheduler = SpiderScheduler(config) environment = Environment(config) app.setC...
application
identifier_name
app.py
from twisted.application.service import Application from twisted.application.internet import TimerService, TCPServer from twisted.web import server from twisted.python import log from scrapy.utils.misc import load_object from .interfaces import IEggStorage, IPoller, ISpiderScheduler, IEnvironment from .launcher impor...
log.msg("Scrapyd web console available at http://%s:%s/" % (bind_address, http_port)) launcher.setServiceParent(app) timer.setServiceParent(app) webservice.setServiceParent(app) return app
app = Application("Scrapyd") http_port = config.getint('http_port', 6800) bind_address = config.get('bind_address', '0.0.0.0') poller = QueuePoller(config) eggstorage = FilesystemEggStorage(config) scheduler = SpiderScheduler(config) environment = Environment(config) app.setComponent(IPoll...
identifier_body
app.py
from twisted.application.service import Application from twisted.application.internet import TimerService, TCPServer from twisted.web import server from twisted.python import log
from scrapy.utils.misc import load_object from .interfaces import IEggStorage, IPoller, ISpiderScheduler, IEnvironment from .launcher import Launcher from .eggstorage import FilesystemEggStorage from .scheduler import SpiderScheduler from .poller import QueuePoller from .environ import Environment from .website import...
random_line_split
replHistory.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
if (!this.historyOverwrites) { this.historyOverwrites = {}; } this.historyOverwrites[previousPointer.toString()] = expression; } } public evaluated(expression: string): void { // clear current expression that was stored previously to support history navigation now on evaluate if (this.currentExp...
{ let previousPointer: number; // this method is called after the user has navigated in the history. Therefor we need to // restore the value of the pointer from the point when the user started the navigation. if (fromPrevious) { previousPointer = this.historyPointer + 1; } else { previousPointer = thi...
identifier_body
replHistory.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
(): string { return this.navigate(true); } private navigate(previous: boolean): string { // validate new pointer let newPointer = -1; if (previous && this.historyPointer > 0 && this.history.length > this.historyPointer - 1) { newPointer = this.historyPointer - 1; } else if (!previous && this.history.len...
previous
identifier_name
replHistory.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
private historyPointer: number; private currentExpressionStoredMarkers: boolean; private historyOverwrites: { [position: string]: string; }; constructor(private history: string[]) { this.historyPointer = this.history.length; this.currentExpressionStoredMarkers = false; this.historyOverwrites = {}; } publ...
* - when starting to navigate in history, the current expression is remembered to be able to go back * - when navigating in history and making changes to any expression, these changes are remembered until a expression is evaluated * - the navigation state is not remembered so that the user always ends up at the end ...
random_line_split
replHistory.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
return null; } public remember(expression: string, fromPrevious: boolean): void { let previousPointer: number; // this method is called after the user has navigated in the history. Therefor we need to // restore the value of the pointer from the point when the user started the navigation. if (fromPrevio...
{ // remember pointer for next navigation this.historyPointer = newPointer; // check for overwrite if (this.historyOverwrites && this.historyOverwrites[newPointer.toString()]) { return this.historyOverwrites[newPointer.toString()]; } return this.history[newPointer]; }
conditional_block
reusing_model.py
import sys
from keras.models import load_model sys.path.append("/Users/alexpapiu/Documents/Conv/OpenCV_CNN") from webcam_cnn_pipeline import return_compiled_model_2, real_time_pred model_name = sys.argv[1] w = 1.5*144 h = 2*144 #keep track of all labels: all_labels = {"model_hand":["A", "B", "C", "D", "No Hand"], ...
import os import cv2
random_line_split
multi_cycle_lr.py
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2020, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This progra...
(self): super().pre_epoch() if self.current_epoch != 0 and \ self.current_epoch in self.multi_cycle_args_by_epoch: args = self.multi_cycle_args_by_epoch[self.current_epoch] self.lr_scheduler = create_lr_scheduler( optimizer=self.optimizer, ...
pre_epoch
identifier_name
multi_cycle_lr.py
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2020, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This progra...
# ---------------------------------------------------------------------- import copy from torch.optim.lr_scheduler import OneCycleLR from nupic.research.frameworks.vernon.experiment_utils import create_lr_scheduler class MultiCycleLR: """ Composes a sequence of OneCycleLR regimes, allowing different config...
# # You should have received a copy of the GNU Affero Public License # along with this program. If not, see http://www.gnu.org/licenses. # # http://numenta.org/licenses/
random_line_split
multi_cycle_lr.py
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2020, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This progra...
improved_args[start_epoch] = cycle_config self.multi_cycle_args_by_epoch = improved_args self.logger.info("MultiCycleLR regime: " f"{self.multi_cycle_args_by_epoch}") # Set it immediately, rather than waiting for the pre_epoch, in case a # restor...
cycle_config["div_factor"] = \ prev_cycle_config["final_div_factor"]
conditional_block
multi_cycle_lr.py
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2020, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This progra...
eo = super().get_execution_order() eo["setup_experiment"].insert( 0, "MultiCycleLR: Prevent LR scheduler from being constructed") eo["setup_experiment"].append("MultiCycleLR: Initialize") eo["pre_epoch"].append("MultiCycleLR: Maybe initialize lr_scheduler") return eo
identifier_body
RelatedCollectionEntity.jest.tsx
import { CollectionsRailFixture } from "v2/Apps/__tests__/Fixtures/Collections" import { mockTracking } from "v2/Artsy/Analytics" import { mount } from "enzyme" import React from "react" import { ArtworkImage, RelatedCollectionEntity, StyledLink, } from "../RelatedCollectionEntity" jest.unmock("react-tracking") ...
expect(dispatch).toBeCalledWith({ action_type: "Click", context_module: "CollectionsRail", context_page_owner_type: "Collection", destination_path: "undefined/collection/jasper-johns-flags", type: "thumbnail", }) }) })
it("Tracks link clicks", () => { const { Component, dispatch } = mockTracking(RelatedCollectionEntity) const component = mount(<Component {...props} />) component.find(StyledLink).simulate("click")
random_line_split
SearchMailboxesResponse.js
"use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var SearchMailboxesResult_1 = require("../../Mai...
}); /** * @internal Reads response elements from Xml JsObject. * * @param {any} jsObject The response object. * @param {ExchangeService} service The service. */ SearchMailboxesResponse.prototype.ReadElementsFromXmlJsObject = function (jsObject, service) { ...
configurable: true
random_line_split
SearchMailboxesResponse.js
"use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __()
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var SearchMailboxesResult_1 = require("../../MailboxSearch/SearchMailboxesResult"); var XmlElementNames_1 = require("../XmlElementNames"); var ServiceResponse_1 = require("./ServiceResponse"); /** * Represents the SearchMailb...
{ this.constructor = d; }
identifier_body
SearchMailboxesResponse.js
"use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function
() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var SearchMailboxesResult_1 = require("../../MailboxSearch/SearchMailboxesResult"); var XmlElementNames_1 = require("../XmlElementNames"); var ServiceResponse_1 = require("./ServiceResponse"); /** ...
__
identifier_name