file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
parser.js
var xhrgoform = require('xhrgoform'); var querystring = require('querystring'); var http = require('http'); var request = require('request'); var jsdom = require('jsdom'); var fs = require('fs'); var baseLink2013 = "http://registration.baa.org/cfm_Archive/iframe_ArchiveSearch.cfm?mode=results&criteria=&StoredProcParam...
(pretty) { var years = ['2001', '2002', '2003', '2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013']; var runners = []; for (var i = 0; i < years.length; i++) { var year = years[i]; var nextName = 'marathonResults' + year + "+clean.json"; var theseRunners = loadRunnersFromFile(next...
stitchAllYearsTogether
identifier_name
klogd.rs
use crate::libbb::ptr_to_globals::bb_errno; use libc; use libc::openlog; use libc::syslog; extern "C" { #[no_mangle] fn strtoul( __nptr: *const libc::c_char, __endptr: *mut *mut libc::c_char, __base: libc::c_int, ) -> libc::c_ulong; #[no_mangle] fn signal(__sig: libc::c_int, __handler: __sighandl...
( mut _argc: libc::c_int, mut argv: *mut *mut libc::c_char, ) -> libc::c_int { let mut i: libc::c_int = 0i32; let mut opt_c: *mut libc::c_char = 0 as *mut libc::c_char; let mut opt: libc::c_int = 0; let mut used: libc::c_int = 0; opt = getopt32( argv, b"c:n\x00" as *const u8 as *const libc::c_char...
klogd_main
identifier_name
klogd.rs
use crate::libbb::ptr_to_globals::bb_errno; use libc; use libc::openlog; use libc::syslog; extern "C" { #[no_mangle] fn strtoul( __nptr: *const libc::c_char, __endptr: *mut *mut libc::c_char, __base: libc::c_int, ) -> libc::c_ulong; #[no_mangle] fn signal(__sig: libc::c_int, __handler: __sighandl...
fn getopt32(argv: *mut *mut libc::c_char, applet_opts: *const libc::c_char, _: ...) -> u32; #[no_mangle] fn write_pidfile_std_path_and_ext(path: *const libc::c_char); #[no_mangle] fn remove_pidfile_std_path_and_ext(path: *const libc::c_char); #[no_mangle] static mut logmode: smallint; #[no_mangle] fn ...
random_line_split
klogd.rs
use crate::libbb::ptr_to_globals::bb_errno; use libc; use libc::openlog; use libc::syslog; extern "C" { #[no_mangle] fn strtoul( __nptr: *const libc::c_char, __endptr: *mut *mut libc::c_char, __base: libc::c_int, ) -> libc::c_ulong; #[no_mangle] fn signal(__sig: libc::c_int, __handler: __sighandl...
unsafe extern "C" fn klogd_close() { /* FYI: cmd 7 is equivalent to setting console_loglevel to 7 * via klogctl(8, NULL, 7). */ klogctl(7i32, 0 as *mut libc::c_char, 0i32); /* "7 -- Enable printk's to console" */ klogctl(0i32, 0 as *mut libc::c_char, 0i32); /* "0 -- Close the log. Currently a NOP" */ } /* T...
{ /* "2 -- Read from the log." */ return klogctl(2i32, bufp, len); }
identifier_body
klogd.rs
use crate::libbb::ptr_to_globals::bb_errno; use libc; use libc::openlog; use libc::syslog; extern "C" { #[no_mangle] fn strtoul( __nptr: *const libc::c_char, __endptr: *mut *mut libc::c_char, __base: libc::c_int, ) -> libc::c_ulong; #[no_mangle] fn signal(__sig: libc::c_int, __handler: __sighandl...
} klogd_close(); syslog( 5i32, b"klogd: exiting\x00" as *const u8 as *const libc::c_char, ); remove_pidfile_std_path_and_ext(b"klogd\x00" as *const u8 as *const libc::c_char); if bb_got_signal != 0 { kill_myself_with_sig(bb_got_signal as libc::c_int); } return 1i32; }
{ *start.offset(n as isize) = '\u{0}' as i32 as libc::c_char; /* Process each newline-terminated line in the buffer */ start = bb_common_bufsiz1.as_mut_ptr(); loop { let mut newline: *mut libc::c_char = strchrnul(start, '\n' as i32); if *newline as libc::c_int == '\u{0}' as i32 {...
conditional_block
sandbox.go
package main import ( "fmt" "golang.org/x/tour/pic" "golang.org/x/tour/wc" "math" "math/cmplx" "math/rand" "os" "runtime" "strings" "time" ) func add1(x int, y int) int { return x + y } func add2(x, y int) int { return x + y } func swap(x, y string) (string, string) { return y, x } func split(sum int)...
() func(int) int { sum := 0 return func(x int) int { sum += x return sum } } var ( previous, current int ) func fibonacci() func() int { return func() int { sum := previous + current if sum == 0 { previous = 0 current = 1 return previous + current } else { previous = current current = su...
adder
identifier_name
sandbox.go
package main import ( "fmt" "golang.org/x/tour/pic" "golang.org/x/tour/wc" "math" "math/cmplx" "math/rand" "os" "runtime" "strings" "time" ) func add1(x int, y int) int { return x + y } func add2(x, y int) int { return x + y } func swap(x, y string) (string, string) { return y, x } func split(sum int)...
} map4[v] = count } return map4 } //closure func adder() func(int) int { sum := 0 return func(x int) int { sum += x return sum } } var ( previous, current int ) func fibonacci() func() int { return func() int { sum := previous + current if sum == 0 { previous = 0 current = 1 return previ...
{ count++ }
conditional_block
sandbox.go
package main import ( "fmt" "golang.org/x/tour/pic" "golang.org/x/tour/wc" "math" "math/cmplx" "math/rand" "os" "runtime" "strings" "time" ) func add1(x int, y int) int { return x + y } func add2(x, y int) int { return x + y } func swap(x, y string) (string, string) { return y, x } func split(sum int)...
func runGoRoutine() { a := []int{7, 2, 8, -9, 4, 0} c := make(chan int) go sum(a[:len(a)/2], c) go sum(a[len(a)/2:], c) x, y := <-c, <-c // receive from channel c and assign value to x and y fmt.Println(x, y, x+y) } func runBufferedChannel() { c := make(chan int, 2) c <- 1 c <- 2 fmt.Println(<-c) fmt.Prin...
random_line_split
sandbox.go
package main import ( "fmt" "golang.org/x/tour/pic" "golang.org/x/tour/wc" "math" "math/cmplx" "math/rand" "os" "runtime" "strings" "time" ) func add1(x int, y int) int { return x + y } func add2(x, y int) int
func swap(x, y string) (string, string) { return y, x } func split(sum int) (x, y int) { x = sum * 4 / 9 y = sum - x return //naked return } //1 var c1, python1, java1 bool //2 var i2, j2 int = 1, 2 var ( ToBe bool = false MaxInt uint64 = 1<<64 - 1 z4 complex128 = cmplx.Sqrt(-5 + 12i) ) co...
{ return x + y }
identifier_body
_train_bot_with_prepared.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import tradebot as tb import numpy as np import copy import progressbar import pickle import klepto def prepare_bbox(): global n_features, n_actions, max_time # Reset environment to the initial state, just in ca...
replay_memory_size=200000 print('replay_memory_size ', replay_memory_size) sample_fit_size = 128 # Размер минибатча, по которому будет делаться выборка из буфера print_step = 10 n_features = bbox.get_num_of_features() # учесть что мы сдесь получаем шайп print('n_features=', n_features) n_actions = bbox.get_nu...
#replay_memory_size = np.minimum(int(bbox.total_steps / float(action_repeat)), 500000 ) # размер памяти, буфера
random_line_split
_train_bot_with_prepared.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import tradebot as tb import numpy as np import copy import progressbar import pickle import klepto def prepare_bbox(): global n_features, n_actions, max_time # Reset environment to the initial state, just in ca...
model_prim.fit(old_state_s, y, batch_size=batchSize, nb_epoch=1, verbose=0) return def run_bbox(verbose=False, epsilon=0.1, gamma=0.99, action_repeat=5, update_frequency=4, sample_fit_size=32, replay_memory_size=100000, load_weights=False, save_weights=False): global pgi...
action_s[i]] = update_s[i]
conditional_block
_train_bot_with_prepared.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import tradebot as tb import numpy as np import copy import progressbar import pickle import klepto def prepare_bbox(): global n_features, n_actions, max_time # Reset environment to the initial state, just in ca...
s_logs==test_states_logs)
= model.predict(state.reshape(1, n_features), batch_size=1) action = (np.argmax(qval)) actions[action] += 1 for a in range(action_repeat): has_next = bbox.do_action(action) bbox.finish(verbose=0) print(" test ", i, " score: ", bbox.get_scor...
identifier_body
_train_bot_with_prepared.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import tradebot as tb import numpy as np import copy import progressbar import pickle import klepto def prepare_bbox(): global n_features, n_actions, max_time # Reset environment to the initial state, just in ca...
ibatch): old_state_s = np.array([row[0] for row in minibatch]) action_s = np.array([row[1] for row in minibatch]) reward_s = np.array([row[2] for row in minibatch]) new_state_s = np.array([row[3] for row in minibatch]) old_qwal_s = model.predict(old_state_s, batch_size=32) newQ_s = model.p...
n_minibatch(min
identifier_name
gitstore.go
package gitstore import ( "bytes" "encoding/json" "fmt" "io" "os" "path/filepath" "strings" "github.com/metakeule/gitlib" "github.com/metakeule/zoom" // "gopkg.in/vmihailenco/msgpack.v1" ) /* TODO implement sharding, i.e. add a layer on top, fullfilling the zoom.Store interface and saving on the correspond...
// only the properties that exist make it into the returned map // it is no error if a requested property does not exist for a node // the caller has to check the returned map against the requested props if // she wants to check, if all requested properties have been returned // if the node properties file is not the...
{ // fmt.Printf("trying to remove node: uuid %#v shard %#v\n", uuid, shard) // fmt.Println("proppath is ", g.propPath(uuid)) paths := []string{ fmt.Sprintf("text/%s/%s/%s", g.shard, uuid[:2], uuid[2:]), fmt.Sprintf("blob/%s/%s/%s", g.shard, uuid[:2], uuid[2:]), } files, err := g.LsFiles(fmt.Sprintf("refs/*/%s...
identifier_body
gitstore.go
package gitstore import ( "bytes" "encoding/json" "fmt" "io" "os" "path/filepath" "strings" "github.com/metakeule/gitlib" "github.com/metakeule/zoom" // "gopkg.in/vmihailenco/msgpack.v1" ) /* TODO implement sharding, i.e. add a layer on top, fullfilling the zoom.Store interface and saving on the correspond...
return fn(blobPath, file) } return nil } */ /* func (s *Store) GetIndex(indexpath string, shard string, fn func(io.Reader) error) error { path := filepath.Join(s.Git.Dir, s.indexPath(shard, indexpath)) if FileExists(path) { file, err := os.Open(path) if err != nil { return err } defer file.Close() ...
} defer file.Close()
random_line_split
gitstore.go
package gitstore import ( "bytes" "encoding/json" "fmt" "io" "os" "path/filepath" "strings" "github.com/metakeule/gitlib" "github.com/metakeule/zoom" // "gopkg.in/vmihailenco/msgpack.v1" ) /* TODO implement sharding, i.e. add a layer on top, fullfilling the zoom.Store interface and saving on the correspond...
// fmt.Println("result", buf.String()) var sha1 string sha1, err = g.Transaction.WriteHashObject(&buf) if err != nil { return err } if isNew { err = g.Transaction.AddIndexCache(sha1, path) } else { err = g.Transaction.UpdateIndexCache(sha1, path) } if err != nil { return err } return nil } func (...
{ return err }
conditional_block
gitstore.go
package gitstore import ( "bytes" "encoding/json" "fmt" "io" "os" "path/filepath" "strings" "github.com/metakeule/gitlib" "github.com/metakeule/zoom" // "gopkg.in/vmihailenco/msgpack.v1" ) /* TODO implement sharding, i.e. add a layer on top, fullfilling the zoom.Store interface and saving on the correspond...
(name string) bool { if _, err := os.Stat(name); err != nil { if os.IsNotExist(err) { return false } } return true } type Git struct { *gitlib.Git shard string } func Open(baseDir string, shard string) (g Git, err error) { // fmt.Println("opening") //gitBase := filepath.Join(baseDir, ".git") gitBase :...
FileExists
identifier_name
_wx.py
# -*- coding: utf-8 -*- # Copyright (c) 2015, Vispy Development Team. # Distributed under the (new) BSD License. See LICENSE.txt for more info. """ vispy backend for wxPython. """ from __future__ import division from time import sleep import gc import warnings from ..base import (BaseApplicationBackend, BaseCanvasB...
class DummySize(object): def __init__(self, size): self.size = size def GetSize(self): return self.size def Skip(self): pass class CanvasBackend(GLCanvas, BaseCanvasBackend): """ wxPython backend for Canvas abstract class.""" # args are for BaseCanvasBackend, kwargs ...
"""Helper to convert from wx keycode to vispy keycode""" key = evt.GetKeyCode() if key in KEYMAP: return KEYMAP[key], '' if 97 <= key <= 122: key -= 32 if key >= 32 and key <= 127: return keys.Key(chr(key)), chr(key) else: return None, None
identifier_body
_wx.py
# -*- coding: utf-8 -*- # Copyright (c) 2015, Vispy Development Team. # Distributed under the (new) BSD License. See LICENSE.txt for more info. """ vispy backend for wxPython. """ from __future__ import division from time import sleep import gc import warnings from ..base import (BaseApplicationBackend, BaseCanvasB...
(self): return self._fullscreen def _vispy_set_fullscreen(self, fullscreen): if self._frame is not None: self._fullscreen = bool(fullscreen) self._vispy_set_visible(True) def _vispy_set_visible(self, visible): # Show or hide the window or widget self.Sho...
_vispy_get_fullscreen
identifier_name
_wx.py
# -*- coding: utf-8 -*- # Copyright (c) 2015, Vispy Development Team. # Distributed under the (new) BSD License. See LICENSE.txt for more info. """ vispy backend for wxPython. """ from __future__ import division from time import sleep import gc import warnings from ..base import (BaseApplicationBackend, BaseCanvasB...
"""Helper to convert from wx keycode to vispy keycode""" key = evt.GetKeyCode() if key in KEYMAP: return KEYMAP[key], '' if 97 <= key <= 122: key -= 32 if key >= 32 and key <= 127: return keys.Key(chr(key)), chr(key) else: return None, None class DummySize(objec...
def _process_key(evt):
random_line_split
_wx.py
# -*- coding: utf-8 -*- # Copyright (c) 2015, Vispy Development Team. # Distributed under the (new) BSD License. See LICENSE.txt for more info. """ vispy backend for wxPython. """ from __future__ import division from time import sleep import gc import warnings from ..base import (BaseApplicationBackend, BaseCanvasB...
elif evt.ButtonUp(): if evt.LeftUp(): button = 0 elif evt.MiddleUp(): button = 1 elif evt.RightUp(): button = 2 else: evt.Skip() self._vispy_mouse_release(pos=pos, button=button, modifier...
if evt.LeftDown(): button = 0 elif evt.MiddleDown(): button = 1 elif evt.RightDown(): button = 2 else: evt.Skip() self._vispy_mouse_press(pos=pos, button=button, modifiers=mods)
conditional_block
protocol_adapter.rs
use crate::HandlerError; use bigdecimal::{BigDecimal, FromPrimitive}; use graphql_parser::query::{ Definition, Document, OperationDefinition, Selection as GqlSelection, SelectionSet, Value, }; use query_core::query_document::*; /// Protocol adapter for GraphQL -> Query Document. /// /// GraphQL is mapped as follow...
fn convert_query(selection_set: SelectionSet<String>) -> crate::Result<Vec<Operation>> { Self::convert_selection_set(selection_set).map(|fields| fields.into_iter().map(Operation::Read).collect()) } fn convert_mutation(selection_set: SelectionSet<String>) -> crate::Result<Vec<Operation>> { ...
{ match def { Definition::Fragment(f) => Err(HandlerError::unsupported_feature( "Fragment definition", format!("Fragment '{}', at position {}.", f.name, f.position), )), Definition::Operation(op) => match op { OperationDefinitio...
identifier_body
protocol_adapter.rs
use crate::HandlerError; use bigdecimal::{BigDecimal, FromPrimitive}; use graphql_parser::query::{ Definition, Document, OperationDefinition, Selection as GqlSelection, SelectionSet, Value, }; use query_core::query_document::*; /// Protocol adapter for GraphQL -> Query Document. /// /// GraphQL is mapped as follow...
(gql_doc: Document<String>, operation: Option<String>) -> crate::Result<Operation> { let mut operations: Vec<Operation> = match operation { Some(ref op) => gql_doc .definitions .into_iter() .find(|def| Self::matches_operation(def, op)) ...
convert
identifier_name
protocol_adapter.rs
use crate::HandlerError; use bigdecimal::{BigDecimal, FromPrimitive}; use graphql_parser::query::{ Definition, Document, OperationDefinition, Selection as GqlSelection, SelectionSet, Value, }; use query_core::query_document::*; /// Protocol adapter for GraphQL -> Query Document. /// /// GraphQL is mapped as follow...
( "categories".to_string(), ArgumentValue::object([( "create".to_string(), ArgumentValue::list([ ArgumentValue::object([("id".to_string(), ArgumentValue::int(1))]), ArgumentValue::object([...
let write = operation.into_write().unwrap(); let data_args = ArgumentValue::object([ ("id".to_string(), ArgumentValue::int(1)),
random_line_split
resource.py
import json from decimal import Decimal from base64 import b64decode from twisted.internet.defer import maybeDeferred, gatherResults from twisted.internet import reactor from twisted.internet.threads import deferToThreadPool from twisted.web import http from twisted.web.client import getPage from twisted.web.resource ...
d = gatherResults(deferreds, consumeErrors=True) return d
deferreds.append(getInfo(server))
conditional_block
resource.py
import json from decimal import Decimal from base64 import b64decode from twisted.internet.defer import maybeDeferred, gatherResults from twisted.internet import reactor from twisted.internet.threads import deferToThreadPool from twisted.web import http from twisted.web.client import getPage from twisted.web.resource ...
def _writeJSONResponse(result, request, code=CODE.SUCCESS, status=http.OK): """ Serializes C{result} to JSON and writes it to C{request}. @param result: The content to be serialized and written to the request. @type result: An object accepted by json.dumps. @param request: The request object t...
return ValveSteamID.from_text(steamid).as_64()
identifier_body
resource.py
import json from decimal import Decimal from base64 import b64decode from twisted.internet.defer import maybeDeferred, gatherResults from twisted.internet import reactor from twisted.internet.threads import deferToThreadPool from twisted.web import http from twisted.web.client import getPage from twisted.web.resource ...
elif response == 'VERIFIED': return True else: raise PaypalError('Unrecognized verification response: %s', (response,)) data = request.content.read() params = '?cmd=_notify-validate&' + data d = getPage(paypalURL+params, method='POST') ...
def _cb(response): if response == 'INVALID': raise PaypalError( 'IPN data invalid. data: %s', (data,))
random_line_split
resource.py
import json from decimal import Decimal from base64 import b64decode from twisted.internet.defer import maybeDeferred, gatherResults from twisted.internet import reactor from twisted.internet.threads import deferToThreadPool from twisted.web import http from twisted.web.client import getPage from twisted.web.resource ...
(self, request): if not request.postpath: return "maybe sam dox" name = request.postpath[0] content = json.loads(request.content.read()) if not content: return 'No JSON provided' if name == u'servers': return self.serverStats(content) ...
render_POST
identifier_name
__init__.py
import numpy as np import pandas as pd import plotly.express as px import plotly.graph_objs as go # import plotly.tools as tls import matplotlib.pyplot as plt from scipy.spatial import distance from sklearn.utils.extmath import randomized_svd from tqdm import tqdm class kohonen: """ Matrix SOM Initialize ...
else: return 0.0 elif self.neighbor_func == "triangular": if node_distance <= radius: return 1 - np.abs(node_distance) / radius else: return 0.0 def dist_weight(self, data, index): """ :param data: Processed data set ...
conditional_block
__init__.py
import numpy as np import pandas as pd import plotly.express as px import plotly.graph_objs as go # import plotly.tools as tls import matplotlib.pyplot as plt from scipy.spatial import distance from sklearn.utils.extmath import randomized_svd from tqdm import tqdm class kohonen: """ Matrix SOM Initialize ...
elif self.neighbor_func == "triangular": if node_distance <= radius: return 1 - np.abs(node_distance) / radius else: return 0.0 def dist_weight(self, data, index): """ :param data: Processed data set for SOM :param index: index...
return 0.0
random_line_split
__init__.py
import numpy as np import pandas as pd import plotly.express as px import plotly.graph_objs as go # import plotly.tools as tls import matplotlib.pyplot as plt from scipy.spatial import distance from sklearn.utils.extmath import randomized_svd from tqdm import tqdm class
: """ Matrix SOM Initialize weight matrix For epoch <- 1 to N do Choose input matrix observation randomly - i For k <- 1 to n_node do compute d(input matrix i, weight matrix k) end Best Matching Unit = winning node = node with the smallest distance For...
kohonen
identifier_name
__init__.py
import numpy as np import pandas as pd import plotly.express as px import plotly.graph_objs as go # import plotly.tools as tls import matplotlib.pyplot as plt from scipy.spatial import distance from sklearn.utils.extmath import randomized_svd from tqdm import tqdm class kohonen:
""" Matrix SOM Initialize weight matrix For epoch <- 1 to N do Choose input matrix observation randomly - i For k <- 1 to n_node do compute d(input matrix i, weight matrix k) end Best Matching Unit = winning node = node with the smallest distance For k <- ...
identifier_body
local_audio_visualizer.js
(function () { var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
window.requestAnimationFrame = requestAnimationFrame; })(); window.onload = function () { var element = document.getElementById("waves"); dropAndLoad(element, init, "ArrayBuffer"); }; // Reusable dropAndLoad function: it reads a local file dropped on a // `dropElement` in the DOM in the specified `readFormat` /...
random_line_split
local_audio_visualizer.js
(function () { var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame; window.requestAnimationFrame = requestAnimationFrame; })(); window.onload = function () { var element = document.getE...
var url = "https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3"; playerElement = document.querySelector("#player"); function Player(url) { this.ac = new (window.AudioContext || webkitAudioContext)(); this.url = url; this.mute = false; // this.el = el; this.button = document.getE...
{ console.log(source); if (!source.stop) source.stop = source.noteOff; source.stop(0); }
identifier_body
local_audio_visualizer.js
(function () { var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame; window.requestAnimationFrame = requestAnimationFrame; })(); window.onload = function () { var element = document.getE...
// console.log("progress = = "+progress); this.progress.value = progress; /*if ( !this.dragging ) { this.scrubber.style.left = ( progress * width ) + 'px'; }*/ requestAnimationFrame(this.draw.bind(this)); };
{ this.button.classList.add("fa-play"); this.button.classList.remove("fa-pause"); }
conditional_block
local_audio_visualizer.js
(function () { var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame; window.requestAnimationFrame = requestAnimationFrame; })(); window.onload = function () { var element = document.getE...
(url) { this.ac = new (window.AudioContext || webkitAudioContext)(); this.url = url; this.mute = false; // this.el = el; this.button = document.getElementById("play_button"); this.volume_btn = document.getElementById("change_vol"); this.mute_btn = document.getElementById("vol_img"); this.rewind = docume...
Player
identifier_name
parser.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. // spell-checker:ignore (grammar) BOOLOP STRLEN FILETEST FILEOP INTOP STRINGOP ; (vars) LParen StrlenOp use std::ffi::{OsStr, OsString...
/// as a literal /// fn lparen(&mut self) -> ParseResult<()> { // Look ahead up to 3 tokens to determine if the lparen is being used // as a grouping operator or should be treated as a literal string let peek3: Vec<Symbol> = self .tokens .clone() ...
random_line_split
parser.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. // spell-checker:ignore (grammar) BOOLOP STRLEN FILETEST FILEOP INTOP STRINGOP ; (vars) LParen StrlenOp use std::ffi::{OsStr, OsString...
thesized expression. /// /// test has no reserved keywords, so "(" will be interpreted as a literal /// in certain cases: /// /// * when found at the end of the token stream /// * when followed by a binary operator that is not _itself_ interpreted /// as a literal /// fn lparen(&mu...
oken(); match symbol { Symbol::LParen => self.lparen()?, Symbol::Bang => self.bang()?, Symbol::UnaryOp(_) => self.uop(symbol), Symbol::None => self.stack.push(symbol), literal => self.literal(literal)?, } Ok(()) } /// Parse a ...
identifier_body
parser.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. // spell-checker:ignore (grammar) BOOLOP STRLEN FILETEST FILEOP INTOP STRINGOP ; (vars) LParen StrlenOp use std::ffi::{OsStr, OsString...
let symbol = self.next_token(); match symbol { Symbol::LParen => self.lparen()?, Symbol::Bang => self.bang()?, Symbol::UnaryOp(_) => self.uop(symbol), Symbol::None => self.stack.push(symbol), literal => self.literal(literal)?, } ...
{
identifier_name
builder.go
// Unless explicitly stated otherwise all files in this repository are licensed // under the Apache License Version 2.0. // This product includes software developed at Datadog (https://www.datadoghq.com/). // Copyright 2016-2020 Datadog, Inc. // Package checks implements Compliance Agent checks package checks import ...
(hostRootMount string) BuilderOption { return func(b *builder) error { log.Infof("Host root filesystem will be remapped to %s", hostRootMount) b.pathMapper = &pathMapper{ hostMountPath: hostRootMount, } return nil } } // WithDocker configures using docker func WithDocker() BuilderOption { return func(b *...
WithHostRootMount
identifier_name
builder.go
// Unless explicitly stated otherwise all files in this repository are licensed // under the Apache License Version 2.0. // This product includes software developed at Datadog (https://www.datadoghq.com/). // Copyright 2016-2020 Datadog, Inc. // Package checks implements Compliance Agent checks package checks import ...
b.dockerClient = cli return nil } } // WithAudit configures using audit checks func WithAudit() BuilderOption { return func(b *builder) error { cli, err := newAuditClient() if err == nil { b.auditClient = cli } return err } } // WithAuditClient configures using specific audit client func WithAuditCl...
return func(b *builder) error {
random_line_split
builder.go
// Unless explicitly stated otherwise all files in this repository are licensed // under the Apache License Version 2.0. // This product includes software developed at Datadog (https://www.datadoghq.com/). // Copyright 2016-2020 Datadog, Inc. // Package checks implements Compliance Agent checks package checks import ...
func (b *builder) EvaluateFromCache(ev eval.Evaluatable) (interface{}, error) { instance := &eval.Instance{ Functions: eval.FunctionMap{ builderFuncShell: b.withValueCache(builderFuncShell, evalCommandShell), builderFuncExec: b.withValueCache(builderFuncExec, evalCommandExec), builderFuncProc...
{ if b.isLeaderFunc != nil { return b.isLeaderFunc() } return true }
identifier_body
builder.go
// Unless explicitly stated otherwise all files in this repository are licensed // under the Apache License Version 2.0. // This product includes software developed at Datadog (https://www.datadoghq.com/). // Copyright 2016-2020 Datadog, Inc. // Package checks implements Compliance Agent checks package checks import ...
return "", fmt.Errorf("failed to find process: %s", name) } func (b *builder) evalValueFromFile(get getter) eval.Function { return func(_ *eval.Instance, args ...interface{}) (interface{}, error) { if len(args) != 2 { return nil, fmt.Errorf(`invalid number of arguments, expecting 1 got %d`, len(args)) } pa...
{ flagValues := parseProcessCmdLine(mp.Cmdline) return flagValues[flag], nil }
conditional_block
base_function.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2018/12/14 15:11 # @Author : zsj # @File : base_function.py import os import pickle import re import time from datetime import datetime import numpy as np import matplotlib.pyplot as plt from django_redis import get_redis_connection from db.mysql_operatio...
:param model: :return: """ # 存储模型 print("sava_xgboost_path", os.getcwd()) file_name = "./models_file/xgboost/%s" % model.name with open(file_name, 'wb') as file_obj: pickle.dump(model, file_obj) # 存储名称 file_model_name = "./models_file/xgboost_name" with open(file_model_na...
def save_xgboost_class(model): """ xgboost 模型持久化,存储在models目录下,使用model.name作为文件名,同时持久化模型名称
random_line_split
base_function.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2018/12/14 15:11 # @Author : zsj # @File : base_function.py import os import pickle import re import time from datetime import datetime import numpy as np import matplotlib.pyplot as plt from django_redis import get_redis_connection from db.mysql_operatio...
date) # 存储到redis中 redis_conn.hset('lstm_model', data_name, pickle.dumps(lstm_train)) redis_conn.sadd('lstm_name', data_name) # 模型持久化 save_lstm_class(lstm_train) print("xgboost_name", data_name) return 1 def get_datas_for_tag(table_nam...
print("xgboost_name", data_name) return 1 elif model_kind == 'LSTM': # 多进程训练模型 if redis_conn.sismember("lstm_name", data_name) and force != 1: print("存在000000000", data_name) return 0 else: print("训练过程0000000") print("类型", type(d...
identifier_body
base_function.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2018/12/14 15:11 # @Author : zsj # @File : base_function.py import os import pickle import re import time from datetime import datetime import numpy as np import matplotlib.pyplot as plt from django_redis import get_redis_connection from db.mysql_operatio...
取时间列 # time_array = np_array[:, 0] # # 删除时间列 # np_array = np.delete(np_array, 0, axis = 1) # hour = [] # minute = [] # week = [] # for time in time_array: # hour.append(time.hour) # minute.append(time.minute) # week.append(time.weekday()) # np_array = np.insert(np...
lete(np_array, 0, axis = 1) # # 获
identifier_name
base_function.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Time : 2018/12/14 15:11 # @Author : zsj # @File : base_function.py import os import pickle import re import time from datetime import datetime import numpy as np import matplotlib.pyplot as plt from django_redis import get_redis_connection from db.mysql_operatio...
# 数据集列表存储表名(redis存储),断电就清空 redis_conn = get_redis_connection("default") redis_conn.sadd('data_set_name', title) # sv.data_set.append(title) # 存储数据集表名(磁盘存储),断电可恢复 save_dataset_name_to_file(title) # 存储文件与UUID对应关系到file2uuid表中 insert_file2uuid(title, table_name) ...
np_array[1:]):
conditional_block
logger.go
/* * MinIO Cloud Storage, (C) 2015, 2016, 2017, 2018 MinIO, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless require...
(f func(string, error, bool) string) { errorFmtFunc = f } // Remove any duplicates and return unique entries. func uniqueEntries(paths []string) []string { m := make(set.StringSet) for _, p := range paths { if !m.Contains(p) { m.Add(p) } } return m.ToSlice() } // SetDeploymentID -- Deployment Id from the ...
RegisterUIError
identifier_name
logger.go
/* * MinIO Cloud Storage, (C) 2015, 2016, 2017, 2018 MinIO, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless require...
// EnableAnonymous - turns anonymous flag // to avoid printing sensitive information. func EnableAnonymous() { anonFlag = true } // IsJSON - returns true if jsonFlag is true func IsJSON() bool { return jsonFlag } // IsQuiet - returns true if quietFlag is true func IsQuiet() bool { return quietFlag } // Register...
{ jsonFlag = true quietFlag = true }
identifier_body
logger.go
/* * MinIO Cloud Storage, (C) 2015, 2016, 2017, 2018 MinIO, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless require...
// Add trim string "{GOROOT}/src/" into trimStrings trimStrings = []string{filepath.Join(runtime.GOROOT(), "src") + string(filepath.Separator)} // Add all possible path from GOPATH=path1:path2...:pathN // as "{path#}/src/" into trimStrings for _, goPathString := range goPathList { trimStrings = append(trimStri...
defaultgoRootList = strings.Split(build.Default.GOROOT, pathSeperator)
random_line_split
logger.go
/* * MinIO Cloud Storage, (C) 2015, 2016, 2017, 2018 MinIO, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless require...
} } traceLevel++ // Read stack trace information from PC pc, file, lineNumber, ok = runtime.Caller(traceLevel) } return trace } // Return the highway hash of the passed string func hashString(input string) string { defer loggerHighwayHasher.Reset() loggerHighwayHasher.Write([]byte(input)) checksum := ...
{ return trace }
conditional_block
select.go
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package runtime // This file contains the implementation of Go select statements. import ( "runtime/internal/atomic" "unsafe" ) const debugSelect = false ...
oto retc retc: if caseReleaseTime > 0 { blockevent(caseReleaseTime-t0, 1) } return casi, recvOK sclose: // send on closed channel selunlock(scases, lockorder) panic(plainError("send on closed channel")) } func (c *hchan) sortkey() uintptr { return uintptr(unsafe.Pointer(c)) } // A runtimeSelect is a single...
print("syncsend: cas0=", cas0, " c=", c, "\n") } g
conditional_block
select.go
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package runtime // This file contains the implementation of Go select statements. import ( "runtime/internal/atomic" "unsafe" ) const debugSelect = false ...
unc block() { gopark(nil, nil, waitReasonSelectNoCases, traceEvGoStop, 1) // forever } // selectgo implements the select statement. // // cas0 points to an array of type [ncases]scase, and order0 points to // an array of type [2*ncases]uint16 where ncases must be <= 65536. // Both reside on the goroutine's stack (reg...
// There are unlocked sudogs that point into gp's stack. Stack // copying must lock the channels of those sudogs. // Set activeStackChans here instead of before we try parking // because we could self-deadlock in stack growth on a // channel lock. gp.activeStackChans = true // Mark that it's safe for stack shrink...
identifier_body
select.go
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package runtime // This file contains the implementation of Go select statements. import ( "runtime/internal/atomic" "unsafe" ) const debugSelect = false ...
s0 *scase, order0 *uint16, pc0 *uintptr, nsends, nrecvs int, block bool) (int, bool) { if debugSelect { print("select: cas0=", cas0, "\n") } // NOTE: In order to maintain a lean stack size, the number of scases // is capped at 65536. cas1 := (*[1 << 16]scase)(unsafe.Pointer(cas0)) order1 := (*[1 << 17]uint16)(...
ectgo(ca
identifier_name
select.go
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package runtime // This file contains the implementation of Go select statements. import ( "runtime/internal/atomic" "unsafe" ) const debugSelect = false ...
if y != nil { // middle of queue x.next = y y.prev = x sgp.next = nil sgp.prev = nil return } // end of queue x.next = nil q.last = x sgp.prev = nil return } if y != nil { // start of queue y.prev = nil q.first = y sgp.next = nil return } // x==y==nil. Either sgp is the on...
y := sgp.next if x != nil {
random_line_split
main.go
package main import ( "bufio" "fmt" "image" "image/color" "image/png" "io/ioutil" "math" "os" "strconv" "strings" "sync" "time" ) type instructionOperation int const ( Add instructionOperation = 1 Multiply instructionOperation = 2 Read ...
// Rotates the direction robot is facing - 0 for CW rotation and 1 for CCW rotation. func (r *paintingRobot) changeDirection(input int) { if input == 1 { if r.direction == up { r.direction = left } else { r.direction -= 1 } } else { if r.direction == lef...
{ fmt.Println(fmt.Sprintf("robot paints [%d,%d] to color %d", r.position.x, r.position.y, color)) for _, p := range r.paintedPoints { if p.x == r.position.x && p.y == r.position.y { p.color = color fmt.Println("just repainted, # of painted tiles: ", len(r.paintedPoints)) ...
identifier_body
main.go
package main import ( "bufio" "fmt" "image" "image/color" "image/png" "io/ioutil" "math" "os" "strconv" "strings" "sync" "time" ) type instructionOperation int const ( Add instructionOperation = 1 Multiply instructionOperation = 2 Read ...
() (int, int, point) { xMin, xMax, yMin, yMax := 0, 0, 0, 0 for _, p := range r.paintedPoints { if p.x > xMax { xMax = p.x } if p.x < xMin { xMin = p.x } if p.y > yMax { yMax = p.y } if p.y < yMin { yMin = p....
getGridInfo
identifier_name
main.go
package main import ( "bufio" "fmt" "image" "image/color" "image/png" "io/ioutil" "math" "os" "strconv" "strings" "sync" "time" ) type instructionOperation int const ( Add instructionOperation = 1 Multiply instructionOperation = 2 Read ...
readingColor = !readingColor case <-r.brain.done: wg.Done() break robotLoop } } }() wg.Wait() } // Gives the tile a color based on input (0 - black, 1 - white). // In order to keep track of unique painted tiles we keep record in s...
random_line_split
main.go
package main import ( "bufio" "fmt" "image" "image/color" "image/png" "io/ioutil" "math" "os" "strconv" "strings" "sync" "time" ) type instructionOperation int const ( Add instructionOperation = 1 Multiply instructionOperation = 2 Read ...
else { r.direction += 1 } } } // Moves the robot by 1 distance point in the direction it is currently facing. func (r *paintingRobot) move() { posX, posY := r.position.x, r.position.y switch r.direction { case up: posY -= 1 case right: posX += 1 case down: ...
{ r.direction = up }
conditional_block
crud.ts
import { ServiceResponseV1 } from '../http'; import { Request, Response } from 'express'; import { Model, DestroyOptions, UpdateOptions, FindOptions } from 'sequelize'; import { BadRequestError, ERR_MSG_MISSING_FIELDS, ERR_MSG_INVALID_PARTS } from '../errors'; import { merge, includes, each, clone, map, filter as arr_...
} else { query = model.findAll(build_query(prop_remap, req.params)) .then(tag(part)); } queries.push(query); }); // combine `main` and `parts` into a single response object error_handler(res, q.all(queries) .th...
.then(tag(part)) .then(resolve)); });
random_line_split
crud.ts
import { ServiceResponseV1 } from '../http'; import { Request, Response } from 'express'; import { Model, DestroyOptions, UpdateOptions, FindOptions } from 'sequelize'; import { BadRequestError, ERR_MSG_MISSING_FIELDS, ERR_MSG_INVALID_PARTS } from '../errors'; import { merge, includes, each, clone, map, filter as arr_...
(model: any): RequestHandler { return (req, res) => error_handler(res, model.update( populate_uuids(populate_dates(req.body)), build_query(ID_MAP, req.params) ).then(response_handler(res))); } /** * NOTE this will always do a soft-delete unless "purge=true" is passed as a * query paramter alo...
update
identifier_name
crud.ts
import { ServiceResponseV1 } from '../http'; import { Request, Response } from 'express'; import { Model, DestroyOptions, UpdateOptions, FindOptions } from 'sequelize'; import { BadRequestError, ERR_MSG_MISSING_FIELDS, ERR_MSG_INVALID_PARTS } from '../errors'; import { merge, includes, each, clone, map, filter as arr_...
})); } return Promise.all(checks).then(() => q.when({}) .then(stamp_meta('instead', instead)) .then(tag(part)) .then(resolve)); }); } else { ...
{ model.findOne(build_query(prop_remap, req.params, { where: { user_id } })).then(row => { instead.includes_me = !!row; resolve(); ...
conditional_block
crud.ts
import { ServiceResponseV1 } from '../http'; import { Request, Response } from 'express'; import { Model, DestroyOptions, UpdateOptions, FindOptions } from 'sequelize'; import { BadRequestError, ERR_MSG_MISSING_FIELDS, ERR_MSG_INVALID_PARTS } from '../errors'; import { merge, includes, each, clone, map, filter as arr_...
function build_query(prop_remap: SDict, params: SDict, extras: Object = {}): QueryOptions { var query = <QueryOptions>clone(extras); query.where = merge(generate_where(prop_remap, params), query.where); query.raw = true; return query; } function stamp_meta<V, H>(label: string, val: V): (holder: H) =>...
{ return reduce(schema, (prop_remap, lookup: string, field: string) => { if (params[lookup]) { prop_remap[field] = params[lookup]; } return prop_remap; }, {}); }
identifier_body
cpu_time.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. // Modified from https://github.com/rust-lang/cargo/blob/426fae51f39ebf6c545a2c12f78bc09fbfdb7aa9/src/cargo/util/cpu.rs // TODO: Maybe use https://github.com/heim-rs/heim is better after https://github.com/heim-rs/heim/issues/233 is fixed. use std::{ ...
} #[cfg(test)] mod tests { use super::*; // this test should be executed alone. #[test] fn test_process_usage() { let mut stat = ProcessStat::cur_proc_stat().unwrap(); std::thread::sleep(std::time::Duration::from_secs(1)); let usage = stat.cpu_usage().unwrap(); asse...
{ let (kernel_time, user_time) = unsafe { let process = GetCurrentProcess(); let mut create_time = mem::zeroed(); let mut exit_time = mem::zeroed(); let mut kernel_time = mem::zeroed(); let mut user_time = mem::zeroed(); let ret = GetProce...
identifier_body
cpu_time.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. // Modified from https://github.com/rust-lang/cargo/blob/426fae51f39ebf6c545a2c12f78bc09fbfdb7aa9/src/cargo/util/cpu.rs // TODO: Maybe use https://github.com/heim-rs/heim is better after https://github.com/heim-rs/heim/issues/233 is fixed. use std::{ ...
() -> io::Result<std::time::Duration> { let mut time = unsafe { std::mem::zeroed() }; if unsafe { libc::getrusage(libc::RUSAGE_SELF, &mut time) } == 0 { let sec = time.ru_utime.tv_sec as u64 + time.ru_stime.tv_sec as u64; let nsec = (time.ru_utime.tv_usec as u32 + time.ru_stime....
cpu_time
identifier_name
cpu_time.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. // Modified from https://github.com/rust-lang/cargo/blob/426fae51f39ebf6c545a2c12f78bc09fbfdb7aa9/src/cargo/util/cpu.rs // TODO: Maybe use https://github.com/heim-rs/heim is better after https://github.com/heim-rs/heim/issues/233 is fixed. use std::{ ...
} }; let kt = filetime_to_ns100(kernel_time); let ut = filetime_to_ns100(user_time); // convert ns // // Note: make it ns unit may overflow in some cases. // For example, a machine with 128 cores runs for one year. let cpu = (kt + ut) * 100; ...
random_line_split
cpu_time.rs
// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0. // Modified from https://github.com/rust-lang/cargo/blob/426fae51f39ebf6c545a2c12f78bc09fbfdb7aa9/src/cargo/util/cpu.rs // TODO: Maybe use https://github.com/heim-rs/heim is better after https://github.com/heim-rs/heim/issues/233 is fixed. use std::{ ...
else { Ok(0.0) } } } #[cfg(any(target_os = "linux", target_os = "freebsd"))] mod imp { use std::{fs::File, io, io::Read, time::Duration}; pub fn current() -> io::Result<super::LinuxStyleCpuTime> { let mut state = String::new(); File::open("/proc/stat")?.read_to_string(...
{ let cpu_time = new_time .checked_sub(old_time) .map(|dur| dur.as_secs_f64()) .unwrap_or(0.0); Ok(cpu_time / real_time) }
conditional_block
esv.py
""" This file provides the following dictionaries based on data from the ESV bible. Chapter lengths obtained via email from Crossway in Jan 2008. Dictionary | Keyed to | Returns --------------------------------------------------------------------------- book_names | book number | tup...
""" Fetch biblical text (in ESV translation) corresponding to the provided Passage object. Returns tuple of (passage_text, truncated), where 'truncated' is a boolean indicating whether passage was shortened to comply with API conditions. Parameters: 'passage' is any object that returns a string ...
identifier_body
esv.py
""" This file provides the following dictionaries based on data from the ESV bible. Chapter lengths obtained via email from Crossway in Jan 2008. Dictionary | Keyed to | Returns --------------------------------------------------------------------------- book_names | book number | tup...
number_verses_in_book[book] = total_verses try: from urllib.parse import urlencode from urllib.request import urlopen, Request except ImportError: # Python 2 from urllib import urlencode from urllib2 import urlopen, Request import json from .text_cache import SimpleCache API_TOTAL_PROPORTION_OF...
chapter = c + 1 last_verses[book, chapter] = last_verse total_verses += last_verse - \ len(missing_verses.get((book, chapter), []))
conditional_block
esv.py
""" This file provides the following dictionaries based on data from the ESV bible. Chapter lengths obtained via email from Crossway in Jan 2008. Dictionary | Keyed to | Returns --------------------------------------------------------------------------- book_names | book number | tup...
31, 7, 10, 10, 9, 8, 18, 19, 2, 29, 176,7, 8, 9, 4, 8, 5, 6, 5, 6, 8, 8, 3, 18, 3, 3, 21, 26, 9, 8, 24, 13, 10, 7, 12, 15, 21, 10, 20, 14, 9, 6], [33, 22, 35, 27, 23, 35, 27, 36, 18, 32, 31, 28, 25, 35, 33, 33, 28, 24, 29, 30, 31, 29, 35, 34, 28, 28, 27, 28, 27,...
16, 15, 5, 23, 11, 13, 12, 9, 9, 5, 8, 28, 22, 35, 45, 48, 43, 13,
random_line_split
esv.py
""" This file provides the following dictionaries based on data from the ESV bible. Chapter lengths obtained via email from Crossway in Jan 2008. Dictionary | Keyed to | Returns --------------------------------------------------------------------------- book_names | book number | tup...
(passage, api_key="", html=False, options={}, cache=default_cache): """ Fetch biblical text (in ESV translation) corresponding to the provided Passage object. Returns tuple of (passage_text, truncated), where 'truncated' is a boolean indicating whether passage was shortened to compl...
get_passage_text
identifier_name
codegen.go
package asn1go import ( "errors" "fmt" goast "go/ast" goprint "go/printer" gotoken "go/token" "io" "strings" ) // CodeGenerator is an interface for code generation from ASN.1 modules. type CodeGenerator interface { Generate(module ModuleDefinition, writer io.Writer) error } // GenParams is code generator con...
// Generate declarations from module to be used together with encoding/asn1. // // Feature support status: // - [x] ModuleIdentifier // - [x] TagDefault (except AUTOMATIC) // - [ ] ExtensibilityImplied // - [.] ModuleBody -- see moduleContext.generateDeclarations. func (gen declCodeGen) Generate(module ModuleDefiniti...
{ for _, existing := range ctx.requiredModules { if existing == module { return } } ctx.requiredModules = append(ctx.requiredModules, module) }
identifier_body
codegen.go
package asn1go import ( "errors" "fmt" goast "go/ast" goprint "go/printer" gotoken "go/token" "io" "strings" ) // CodeGenerator is an interface for code generation from ASN.1 modules. type CodeGenerator interface { Generate(module ModuleDefinition, writer io.Writer) error } // GenParams is code generator con...
case IntegerType: // TODO: generate consts switch ctx.params.IntegerRepr { case IntegerReprInt64: return goast.NewIdent("int64") // TODO signed, unsigned, range constraints case IntegerReprBigInt: ctx.requireModule("math/big") return &goast.StarExpr{X: goast.NewIdent("big.Int")} default: ctx.appe...
random_line_split
codegen.go
package asn1go import ( "errors" "fmt" goast "go/ast" goprint "go/printer" gotoken "go/token" "io" "strings" ) // CodeGenerator is an interface for code generation from ASN.1 modules. type CodeGenerator interface { Generate(module ModuleDefinition, writer io.Writer) error } // GenParams is code generator con...
} ctx.requiredModules = append(ctx.requiredModules, module) } // Generate declarations from module to be used together with encoding/asn1. // // Feature support status: // - [x] ModuleIdentifier // - [x] TagDefault (except AUTOMATIC) // - [ ] ExtensibilityImplied // - [.] ModuleBody -- see moduleContext.generateDec...
{ return }
conditional_block
codegen.go
package asn1go import ( "errors" "fmt" goast "go/ast" goprint "go/printer" gotoken "go/token" "io" "strings" ) // CodeGenerator is an interface for code generation from ASN.1 modules. type CodeGenerator interface { Generate(module ModuleDefinition, writer io.Writer) error } // GenParams is code generator con...
(name Identifier, t Type) bool { switch t := t.(type) { case TaggedType: return true case TypeReference: if t.Name() == GeneralizedTimeName || t.Name() == UTCTimeName { return false } realType := ctx.resolveTypeReference(t) if realType == nil { return false } return ctx.taggedChoiceTypeAlternativ...
taggedChoiceTypeAlternative
identifier_name
family_structs.go
package family import ( "database/sql" "fmt" "github.com/chaseWilliams/family-map/lib/datagen/external" "github.com/chaseWilliams/family-map/lib/models" "github.com/chaseWilliams/family-map/lib/util" "math/rand" ) /* Person is a family construct that represents a singular person in a family tree */ type Person ...
} } return } /* MarriageYears will return the person's marriage years */ func (f Person) MarriageYears() []int { return f.marriageYears } /* DivorceYears returns the person's divorce years */ func (f Person) DivorceYears() []int { return f.divorceYears } /* Generation is what the name implies, and represented ...
m[spouse] = append(m[spouse], child) }
random_line_split
family_structs.go
package family import ( "database/sql" "fmt" "github.com/chaseWilliams/family-map/lib/datagen/external" "github.com/chaseWilliams/family-map/lib/models" "github.com/chaseWilliams/family-map/lib/util" "math/rand" ) /* Person is a family construct that represents a singular person in a family tree */ type Person ...
for _, child := range a.children { if goDownTree(child, b) { return true } } return false } /* RandomFamily returns a random family, determined by a random person at generation numGen and all family members of that person. The person will be the first person in the returned slice of people. */ func (pop Pop...
{ return true }
conditional_block
family_structs.go
package family import ( "database/sql" "fmt" "github.com/chaseWilliams/family-map/lib/datagen/external" "github.com/chaseWilliams/family-map/lib/models" "github.com/chaseWilliams/family-map/lib/util" "math/rand" ) /* Person is a family construct that represents a singular person in a family tree */ type Person ...
() bool { return f.deathYear != -1 } /* IsMarried returns if the person is married or not */ func (f Person) IsMarried() bool { return f.married } /* IsStraight returns if the person is straight or not */ func (f Person) IsStraight() bool { return f.straight } /* Gender will return the person's gender */ func (f ...
IsDead
identifier_name
family_structs.go
package family import ( "database/sql" "fmt" "github.com/chaseWilliams/family-map/lib/datagen/external" "github.com/chaseWilliams/family-map/lib/models" "github.com/chaseWilliams/family-map/lib/util" "math/rand" ) /* Person is a family construct that represents a singular person in a family tree */ type Person ...
/* Spouses returns a slice of the person's spouses in chronological order */ func (f Person) Spouses() []*Person { return f.spouses } /* CurrSpouse will return the person's current spouse, and return an error if person isn't married */ func (f Person) CurrSpouse() (spouse *Person, err error) { if !f.married { re...
{ return f.deathYear }
identifier_body
medicalbillregistersummary.component.ts
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core'; import { FormControl, NgForm } from '@angular/forms'; import { CommonService } from '../../shared/common.service'; import { BillingPharmacy } from '../../Models/ViewModels/BillingPharmacy_master.model'; import Swal from 'sweetalert2'; import * as...
onSubmit(form: NgForm) { debugger; if (form.valid) { this.M_FromDat = this.MFromDate.toISOString(); this.M_ToDat = this.MToDate.toISOString(); this.commonService.getListOfData("MedicalBillRegister/getMedBillDet/" + this.M_FromDat + '/' + this.M_ToDat + '/' + parseInt(localStorage.getIte...
{ debugger; this.backdrop = 'none'; this.cancelblock = 'none'; //this.MFromDate = ''; //this.MToDate = ''; this.MedicalBillRegisterTable = false; this.MedicalBillSummaryTable = false; this.MBS_label = false; }
identifier_body
medicalbillregistersummary.component.ts
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core'; import { FormControl, NgForm } from '@angular/forms'; import { CommonService } from '../../shared/common.service'; import { BillingPharmacy } from '../../Models/ViewModels/BillingPharmacy_master.model'; import Swal from 'sweetalert2'; import * as...
() { var totDiscntAmt1 = this.commonService.data.getSummaryDet.map(t => t.Damt).reduce((acc, value) => acc + value, 0); totDiscntAmt1 = parseFloat(totDiscntAmt1.toFixed(2)); return totDiscntAmt1; } getGSTAmount1() { var totGSTAmt1 = this.commonService.data.getSummaryDet.map(t => t.Gamt).reduce((acc...
getDiscountAmount1
identifier_name
medicalbillregistersummary.component.ts
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core'; import { FormControl, NgForm } from '@angular/forms'; import { CommonService } from '../../shared/common.service'; import { BillingPharmacy } from '../../Models/ViewModels/BillingPharmacy_master.model'; import Swal from 'sweetalert2'; import * as...
changeValueTotal(id, element, property: string) { var resTotal = (element.Quantity * element.Rate) + element.GSTValue - element.DiscountAmount; resTotal = parseFloat(resTotal.toFixed(2)); element.TotalCost = resTotal; } getTotalProdVal() { var totProdVal = this.commonService.data.getRegisterDeta...
M_ToDat;
random_line_split
medicalbillregistersummary.component.ts
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core'; import { FormControl, NgForm } from '@angular/forms'; import { CommonService } from '../../shared/common.service'; import { BillingPharmacy } from '../../Models/ViewModels/BillingPharmacy_master.model'; import Swal from 'sweetalert2'; import * as...
console.log(data.getRegisterDetail); } if (data.getSummaryDet != null) { for (var i = 0; i < data.getSummaryDet.length; i++) { debugger; var rslt = ((data.getSummaryDet[i].Quan * data.getSummaryDet[i].Irate) + data.getSummaryDet[i].Ga...
{ debugger; var res = ((data.getRegisterDetail[i].Quantity * data.getRegisterDetail[i].Rate) + data.getRegisterDetail[i].GSTValue) - data.getRegisterDetail[i].DiscountAmount; data.getRegisterDetail[i].TotalCost = res; }
conditional_block
cargo_workspace.rs
//! FIXME: write short doc here use std::{ ops, path::{Path, PathBuf}, }; use anyhow::{Context, Result}; use cargo_metadata::{BuildScript, CargoOpt, Message, MetadataCommand, PackageId}; use ra_arena::{Arena, Idx}; use ra_cargo_watch::run_cargo; use ra_db::Edition; use rustc_hash::FxHashMap; use serde::Deseri...
} } #[derive(Debug, Clone, Default)] pub struct ExternResources { out_dirs: FxHashMap<PackageId, PathBuf>, proc_dylib_paths: FxHashMap<PackageId, PathBuf>, } pub fn load_extern_resources(cargo_toml: &Path, cargo_features: &CargoFeatures) -> ExternResources { let mut args: Vec<String> = vec![ "...
.copied() } pub fn workspace_root(&self) -> &Path { &self.workspace_root
random_line_split
cargo_workspace.rs
//! FIXME: write short doc here use std::{ ops, path::{Path, PathBuf}, }; use anyhow::{Context, Result}; use cargo_metadata::{BuildScript, CargoOpt, Message, MetadataCommand, PackageId}; use ra_arena::{Arena, Idx}; use ra_cargo_watch::run_cargo; use ra_db::Edition; use rustc_hash::FxHashMap; use serde::Deseri...
{ /// Do not activate the `default` feature. pub no_default_features: bool, /// Activate all available features pub all_features: bool, /// List of features to activate. /// This will be ignored if `cargo_all_features` is true. pub features: Vec<String>, /// Runs cargo check on launc...
CargoFeatures
identifier_name
SIMulator_functions.py
import numpy as np from numpy import pi, cos, sin from numpy.fft import fft2, ifft2, fftshift, ifftshift from skimage import io, draw, transform, img_as_ubyte, img_as_float from scipy import signal from scipy.signal import convolve2d import scipy.special from numba import jit import time import streamlit as st def
(x, opt): return np.clip(np.cos(x), 0, 1) def cos_wave_envelope(x, h, opt): period_in_pixels = opt.w / (opt.k2) p = period_in_pixels f = 1 / p # h = 2*pi*opt.k2*(h-0.5)+10 h = h*opt.w - opt.w/2 + 10 window = np.where(np.abs(x - h) <= period_in_pixels/4, 1, 0) maxval = np.max(window *...
cos_wave
identifier_name
SIMulator_functions.py
import numpy as np from numpy import pi, cos, sin from numpy.fft import fft2, ifft2, fftshift, ifftshift from skimage import io, draw, transform, img_as_ubyte, img_as_float from scipy import signal from scipy.signal import convolve2d import scipy.special from numba import jit import time import streamlit as st def ...
def SIMimages_speckle(opt, DIo): # AIM: to generate raw sim images # INPUT VARIABLES # k2: illumination frequency # DIo: specimen image # PSFo: system PSF # OTFo: system OTF # UsePSF: 1 (to blur SIM images by convloving with PSF) # 0 (to blur SIM images by truncati...
N = opt.Nspeckles I = np.zeros((dim, dim)) randx = np.random.choice( list(range(dim)) * np.ceil(N / dim).astype("int"), size=N, replace=False ) randy = np.random.choice( list(range(dim)) * np.ceil(N / dim).astype("int"), size=N, replace=False ) for i in range(N): x = ran...
identifier_body
SIMulator_functions.py
import numpy as np from numpy import pi, cos, sin from numpy.fft import fft2, ifft2, fftshift, ifftshift from skimage import io, draw, transform, img_as_ubyte, img_as_float from scipy import signal from scipy.signal import convolve2d import scipy.special from numba import jit import time import streamlit as st def ...
# SNR = 1/aNoise # SNRdb = 20*log10(1/aNoise) nST = np.random.normal(0, aNoise * np.std(ST, ddof=1), (w, w)) NoiseFrac = 1 # may be set to 0 to avoid noise addition # noise added raw SIM images STnoisy = ST + NoiseFrac * nST frames.append(STnoisy) return fr...
random_line_split
SIMulator_functions.py
import numpy as np from numpy import pi, cos, sin from numpy.fft import fft2, ifft2, fftshift, ifftshift from skimage import io, draw, transform, img_as_ubyte, img_as_float from scipy import signal from scipy.signal import convolve2d import scipy.special from numba import jit import time import streamlit as st def ...
crop_factor_x = dim[1] / 912 # 428 crop_factor_y = dim[0] / 1140 # 684 # data from dec 2022 acquired with DMD patterns with the below factors # crop_factor_x = 1 # crop_factor_y = 1 # first version, december 2022 # wo = w / 2 # x = np.linspace...
dim = (dim, dim)
conditional_block
factory.go
package tx import ( "errors" "fmt" "os" "strings" "github.com/cosmos/go-bip39" "github.com/spf13/pflag" "github.com/spf13/viper" "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/...
(fp sdk.AccAddress) Factory { f.feePayer = fp return f } // WithPreprocessTxHook returns a copy of the Factory with an updated preprocess tx function, // allows for preprocessing of transaction data using the TxBuilder. func (f Factory) WithPreprocessTxHook(preprocessFn client.PreprocessTxFn) Factory { f.preprocess...
WithFeePayer
identifier_name
factory.go
package tx import ( "errors" "fmt" "os" "strings" "github.com/cosmos/go-bip39" "github.com/spf13/pflag" "github.com/spf13/viper" "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/...
// WithFeePayer returns a copy of the Factory with an updated fee granter. func (f Factory) WithFeePayer(fp sdk.AccAddress) Factory { f.feePayer = fp return f } // WithPreprocessTxHook returns a copy of the Factory with an updated preprocess tx function, // allows for preprocessing of transaction data using the Tx...
{ f.feeGranter = fg return f }
identifier_body
factory.go
package tx import ( "errors" "fmt" "os" "strings" "github.com/cosmos/go-bip39" "github.com/spf13/pflag" "github.com/spf13/viper" "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/...
feePayer sdk.AccAddress gasPrices sdk.DecCoins extOptions []*codectypes.Any signMode signing.SignMode simulateAndExecute bool preprocessTxHook client.PreprocessTxFn } // NewFactoryCLI creates a new Factory. func NewFactoryCLI(clientCtx client.Context, flagSet *pflag.FlagSet...
feeGranter sdk.AccAddress
random_line_split
factory.go
package tx import ( "errors" "fmt" "os" "strings" "github.com/cosmos/go-bip39" "github.com/spf13/pflag" "github.com/spf13/viper" "cosmossdk.io/math" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/...
} return fc, nil }
{ fc = fc.WithSequence(seq) }
conditional_block
mgclarge.go
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Page heap. // // See malloc.go for the general overview. // // Allocation policy is the subject of this file. All free spans live in // a treap for most of t...
(y *treapNode) { // p -> (y (x a b) c) p := y.parent x, c := y.left, y.right a, b := x.left, x.right x.left = a if a != nil { a.parent = x } x.right = y y.parent = x y.left = b if b != nil { b.parent = y } y.right = c if c != nil { c.parent = y } x.parent = p if p == nil { root.treap = x } e...
rotateRight
identifier_name
mgclarge.go
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Page heap. // // See malloc.go for the general overview. // // Allocation policy is the subject of this file. All free spans live in // a treap for most of t...
// pred returns the predecessor of t in the treap subject to the criteria // specified by the filter f. Returns nil if no such predecessor exists. func (t *treapNode) pred(f treapIterFilter) *treapNode { if t.left != nil && f.matches(t.left.types) { // The node has a left subtree which contains at least one matchi...
{ if t == nil || !f.matches(t.types) { return nil } for t != nil { if t.right != nil && f.matches(t.right.types) { t = t.right } else if f.matches(t.span.treapFilter()) { break } else if t.left != nil && f.matches(t.left.types) { t = t.left } else { println("runtime: f=", f) throw("failed to...
identifier_body
mgclarge.go
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Page heap. // // See malloc.go for the general overview. // // Allocation policy is the subject of this file. All free spans live in // a treap for most of t...
else { p.right = nil } // Walk up the tree updating invariants until no updates occur. for p != nil && p.updateInvariants() { p = p.parent } } else { root.treap = nil } // Return the found treapNode's span after freeing the treapNode. mheap_.treapalloc.free(unsafe.Pointer(t)) } // find searches fo...
{ p.left = nil }
conditional_block
mgclarge.go
// Copyright 2009 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Page heap. // // See malloc.go for the general overview. // // Allocation policy is the subject of this file. All free spans live in // a treap for most of t...
y.right = c if c != nil { c.parent = y } x.parent = p if p == nil { root.treap = x } else if p.left == y { p.left = x } else { if p.right != y { throw("large span treap rotateRight") } p.right = x } y.updateInvariants() x.updateInvariants() }
y.parent = x y.left = b if b != nil { b.parent = y }
random_line_split
variables.go
/******************************************************************************* * Copyright 2019 Dell Inc. * Copyright 2020 Intel Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * ...
// convertToType attempts to convert the string value to the specified type of the old value func (_ *Variables) convertToType(oldValue interface{}, value string) (newValue interface{}, err error) { switch oldValue.(type) { case []string: newValue = parseCommaSeparatedSlice(value) case []interface{}: newValue ...
{ url := os.Getenv(envKeyConfigUrl) if len(url) > 0 { logEnvironmentOverride(e.lc, "Configuration Provider Information", envKeyConfigUrl, url) if err := configProviderInfo.PopulateFromUrl(url); err != nil { return types.ServiceConfig{}, err } } return configProviderInfo, nil }
identifier_body
variables.go
/******************************************************************************* * Copyright 2019 Dell Inc. * Copyright 2020 Intel Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * ...
// The toml.Tree API keys() only return to top level keys, rather that paths. // It is also missing a GetPaths so have to spin our own paths := e.buildPaths(configTree.ToMap()) // Now that we have all the paths in the config tree, we need to create map of corresponding override names that // could match override...
{ return 0, err }
conditional_block
variables.go
/******************************************************************************* * Copyright 2019 Dell Inc. * Copyright 2020 Intel Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * ...
} return names } func (_ *Variables) getOverrideNameFor(path string) string { // "." & "-" are the only special character allowed in TOML path not allowed in environment variable Name override := strings.ReplaceAll(path, tomlPathSeparator, envNameSeparator) override = strings.ReplaceAll(override, tomlNameSeparat...
random_line_split