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
environment.py
"""Module with code to be run before and after certain events during the testing.""" import json import datetime import subprocess import os.path import contextlib from behave.log_capture import capture import docker import requests import time from src.s3interface import S3Interface import logging logging.getLogge...
def _is_3scale_preview_running(context, accepted_codes={200, 403, 401}): try: res = requests.post(context.threescale_preview_url) if res.status_code in accepted_codes: return True except requests.exceptions.ConnectionError: pass return False def _is_backbone_api_runn...
try: res = requests.post(threescale_url) if res.status_code in accepted_codes: return True except requests.exceptions.ConnectionError: pass return False
identifier_body
environment.py
"""Module with code to be run before and after certain events during the testing.""" import json import datetime import subprocess import os.path import contextlib from behave.log_capture import capture import docker import requests import time from src.s3interface import S3Interface import logging logging.getLogge...
def _missing_api_token_warning(env_var_name): if os.environ.get(env_var_name): logger.info("OK: {name} environment is set and will be used as " "authorization token".format(name=env_var_name)) else: logger.info("Warning: the {name} environment variable is not" ...
random_line_split
environment.py
"""Module with code to be run before and after certain events during the testing.""" import json import datetime import subprocess import os.path import contextlib from behave.log_capture import capture import docker import requests import time from src.s3interface import S3Interface import logging logging.getLogge...
(gemini_api_url, accepted_codes={200}): try: url = '%s/api/v1/readiness' % gemini_api_url res = requests.get(url) if res.status_code in accepted_codes: return True except requests.exceptions.ConnectionError: pass return False def _is_api_running_post(url): t...
_is_gemini_api_running
identifier_name
reactor.go
package v1 import ( "fmt" "time" "github.com/gogo/protobuf/proto" "github.com/tendermint/tendermint/behaviour" bc "github.com/tendermint/tendermint/blockchain" "github.com/tendermint/tendermint/libs/log" "github.com/tendermint/tendermint/p2p" bcproto "github.com/tendermint/tendermint/proto/tendermint/blockch...
// processBlocksRoutine processes blocks until signlaed to stop over the stopProcessing channel func (bcR *BlockchainReactor) processBlocksRoutine(stopProcessing chan struct{}) { processReceivedBlockTicker := time.NewTicker(trySyncIntervalMS * time.Millisecond) doProcessBlockCh := make(chan struct{}, 1) lastHund...
{ msg := &bcproto.Message{} err := proto.Unmarshal(msgBytes, msg) if err != nil { panic(err) } uw, err := msg.Unwrap() if err != nil { panic(err) } bcR.ReceiveEnvelope(p2p.Envelope{ ChannelID: chID, Src: peer, Message: uw, }) }
identifier_body
reactor.go
package v1 import ( "fmt" "time" "github.com/gogo/protobuf/proto" "github.com/tendermint/tendermint/behaviour" bc "github.com/tendermint/tendermint/blockchain" "github.com/tendermint/tendermint/libs/log" "github.com/tendermint/tendermint/p2p" bcproto "github.com/tendermint/tendermint/proto/tendermint/blockch...
msgForFSM := bcReactorMessage{ event: blockResponseEv, data: bReactorEventData{ peerID: e.Src.ID(), height: bi.Height, block: bi, length: msg.Size(), }, } bcR.Logger.Info("Received", "src", e.Src, "height", bi.Height) bcR.messagesForFSMCh <- msgForFSM case *bcproto.NoBlockResponse: ...
{ bcR.Logger.Error("error transition block from protobuf", "err", err) return }
conditional_block
reactor.go
package v1 import ( "fmt" "time" "github.com/gogo/protobuf/proto" "github.com/tendermint/tendermint/behaviour" bc "github.com/tendermint/tendermint/blockchain" "github.com/tendermint/tendermint/libs/log" "github.com/tendermint/tendermint/p2p" bcproto "github.com/tendermint/tendermint/proto/tendermint/blockch...
(state sm.State, blockExec *sm.BlockExecutor, store *store.BlockStore, fastSync bool) *BlockchainReactor { if state.LastBlockHeight != store.Height() { panic(fmt.Sprintf("state (%v) and store (%v) height mismatch", state.LastBlockHeight, store.Height())) } const capacity = 1000 eventsFromFSMCh := make(chan ...
NewBlockchainReactor
identifier_name
reactor.go
package v1 import ( "fmt" "time" "github.com/gogo/protobuf/proto" "github.com/tendermint/tendermint/behaviour" bc "github.com/tendermint/tendermint/blockchain" "github.com/tendermint/tendermint/libs/log" "github.com/tendermint/tendermint/p2p" bcproto "github.com/tendermint/tendermint/proto/tendermint/blockch...
default: bcR.Logger.Error("Event from FSM not supported", "type", msg.event) } case <-bcR.Quit(): break ForLoop } } } func (bcR *BlockchainReactor) reportPeerErrorToSwitch(err error, peerID p2p.ID) { peer := bcR.Switch.Peers().Get(peerID) if peer != nil { _ = bcR.swReporter.Report(behaviour.BadM...
// the FSM had already removed the peers // }
random_line_split
mod.rs
use std::collections::{HashMap, HashSet}; use std::process::exit; use ansi_term::Colour::{Red, Green, Cyan}; use petgraph::{ graph::{EdgeIndex, NodeIndex}, Directed, Graph, Incoming, Outgoing, }; /// The edge of a DelfGraph is a DelfEdge pub mod edge; /// The node of a DelfGraph is a DelfObject pub mod object...
(&self, object_name: &String) -> &object::DelfObject { let object_id = self.nodes.get(object_name).unwrap(); return self.graph.node_weight(*object_id).unwrap(); } /// Given the object name and the id of the instance, delete the object pub fn delete_object(&self, object_name: &String, id: &S...
get_object
identifier_name
mod.rs
use std::collections::{HashMap, HashSet}; use std::process::exit; use ansi_term::Colour::{Red, Green, Cyan}; use petgraph::{ graph::{EdgeIndex, NodeIndex}, Directed, Graph, Incoming, Outgoing, }; /// The edge of a DelfGraph is a DelfEdge pub mod edge; /// The node of a DelfGraph is a DelfObject pub mod object...
for (_, node_id) in self.nodes.iter() { let obj = self.graph.node_weight(*node_id).unwrap(); match obj.deletion { object::DeleteType::ShortTTL | object::DeleteType::Directly | object::DeleteType::DirectlyOnly | object::Delet...
// Starting from a directly deletable (or excepted) node, ensure all ndoes are reached. fn reachability_analysis(&self) -> Result<(), String> { let mut visited_nodes = HashSet::new();
random_line_split
mod.rs
use std::collections::{HashMap, HashSet}; use std::process::exit; use ansi_term::Colour::{Red, Green, Cyan}; use petgraph::{ graph::{EdgeIndex, NodeIndex}, Directed, Graph, Incoming, Outgoing, }; /// The edge of a DelfGraph is a DelfEdge pub mod edge; /// The node of a DelfGraph is a DelfObject pub mod object...
/// Pretty print the graph's contents. pub fn print(&self) { println!("{:#?}", self.graph); } /// Given an edge name, get the corresponding DelfEdge pub fn get_edge(&self, edge_name: &String) -> &edge::DelfEdge { let edge_id = self.edges.get(edge_name).unwrap(); return sel...
{ let schema = &yamls.schema; let config = &yamls.config; let mut edges_to_insert = Vec::new(); let mut nodes = HashMap::<String, NodeIndex>::new(); let mut edges = HashMap::<String, EdgeIndex>::new(); let mut graph = Graph::<object::DelfObject, edge::DelfEdge>::new(); ...
identifier_body
exec.go
package runner import ( "bufio" "errors" "fmt" "io" "log" "os" "os/exec" "sync" "syscall" "time" "github.com/solovev/orange-app-runner/system" "github.com/solovev/orange-app-runner/util" ) // RunProcess запускает основной процесс отслеживания func RunProcess(cfg *util.Config) (int, error) { util.Debug("...
func measureUsage(cfg *util.Config, storage *os.File, process *os.Process) { // Проверяем, не завершился ли процесс до того, как мы начнем считать потребление ресурсов. if _, err := os.Stat(fmt.Sprintf("/proc/%d/stat", process.Pid)); err == nil { // Потребление CPU в % считается по такой формуле: // consumtion =...
wg.Wait() return ws.ExitStatus(), nil }
random_line_split
exec.go
package runner import ( "bufio" "errors" "fmt" "io" "log" "os" "os/exec" "sync" "syscall" "time" "github.com/solovev/orange-app-runner/system" "github.com/solovev/orange-app-runner/util" ) // RunProcess запускает основной процесс отслеживания func RunProcess(cfg *util.Config) (int, error) { util.Debug("...
conditional_block
exec.go
package runner import ( "bufio" "errors" "fmt" "io" "log" "os" "os/exec" "sync" "syscall" "time" "github.com/solovev/orange-app-runner/system" "github.com/solovev/orange-app-runner/util" ) // RunProcess запускает основной процесс отслеживания func RunProcess(cfg *util.Config) (int, error) { util.Debug("...
identifier_body
exec.go
package runner import ( "bufio" "errors" "fmt" "io" "log" "os" "os/exec" "sync" "syscall" "time" "github.com/solovev/orange-app-runner/system" "github.com/solovev/orange-app-runner/util" ) // RunProcess запускает основной процесс отслеживания func RunProcess(cfg *util.Config) (int, error) { util.Debug("...
identifier_name
create-docker-context-for-node-component.js
#!/usr/bin/env node const childProcess = require("child_process"); const fse = require("fs-extra"); const path = require("path"); const process = require("process"); const yargs = require("yargs"); const _ = require("lodash"); const isSubDir = require("is-subdir"); const { getVersions, getTags, getName, ...
(packagePath) { const packageJsonPath = path.resolve(packagePath, "package.json"); if (packageDependencyDataCache[packageJsonPath]) { return packageDependencyDataCache[packageJsonPath]; } const pkgData = fse.readJSONSync(packageJsonPath); const depData = pkgData["dependencies"]; if (!de...
getPackageDependencies
identifier_name
create-docker-context-for-node-component.js
#!/usr/bin/env node const childProcess = require("child_process"); const fse = require("fs-extra"); const path = require("path"); const process = require("process"); const yargs = require("yargs"); const _ = require("lodash"); const isSubDir = require("is-subdir"); const { getVersions, getTags, getName, ...
dependencies.forEach(function (dependencyName) { const dependencyNamePath = dependencyName.replace(/\//g, path.sep); let currentBaseDir = packagePath; let dependencyDir; do { dependencyDir = path.resolve( currentBaseDir, "node_modules",...
{ return result; }
conditional_block
create-docker-context-for-node-component.js
#!/usr/bin/env node const childProcess = require("child_process"); const fse = require("fs-extra"); const path = require("path"); const process = require("process"); const yargs = require("yargs"); const _ = require("lodash"); const isSubDir = require("is-subdir"); const { getVersions, getTags, getName, ...
{ if (process.stdout) { process.stdout.on("data", (data) => { console.log(data.toString()); }); } if (process.stderr) { process.stderr.on("data", (data) => { console.error(data.toString()); }); } }
identifier_body
create-docker-context-for-node-component.js
#!/usr/bin/env node const childProcess = require("child_process"); const fse = require("fs-extra"); const path = require("path"); const process = require("process"); const yargs = require("yargs"); const _ = require("lodash"); const isSubDir = require("is-subdir"); const { getVersions, getTags, getName, ...
return; } try { // On Windows we can't create symlinks to files without special permissions. // So just copy the file instead. Usually creating directory junctions is // fine without special permissions, but fall back on copying ...
getPackageList(packageDir, path.resolve(packageDir, "..")), (package) => package.path ); prepareNodeModules(src, dest, productionPackages);
random_line_split
main.py
import socket import re import math import time from datetime import datetime, timedelta import random import numpy import RPi.GPIO as GPIO import cv2 import numpy as np import base64 from Class_Def import * from module import * #from open_cv import * HOST = '192.168.0.118' PORT = 9000 font = cv2....
global imgstring global hStandard global vStandard global TotalunpassCount global dateGap Result_horizon, Result_vertical = Dot_Distance(p1[count][0], p1[count][1], p2[count][0], p2[count][1], p3[count][0], p3[count][1], p4[count][0], p4[count][1]) Unit_horizon.append(Result_horizon) ...
바꿈
identifier_name
main.py
import socket import re import math import time from datetime import datetime, timedelta import random import numpy import RPi.GPIO as GPIO import cv2 import numpy as np import base64 from Class_Def import * from module import * #from open_cv import * HOST = '192.168.0.118' PORT = 9000 font = cv2....
count = 0 Hadjust = 0 Vadjust = 0 ### open_cv 스크립트 변수들 p_list = [] dot1=[] dot2=[] dot3=[] dot4=[] imgstring = '' temperature = 0 ### open_cv 스크립트 변수들 2020-11-03 옮김 hunpassCount = 0 vunpassCount = 0 a=0 TotalunpassCount = 0 time1 = 0 time2 = 0 dateGap = 0 def opencapture(count): global img ...
hStandard = 0.0 vStandard = 0.0
random_line_split
main.py
import socket import re import math import time from datetime import datetime, timedelta import random import numpy import RPi.GPIO as GPIO import cv2 import numpy as np import base64 from Class_Def import * from module import * #from open_cv import * HOST = '192.168.0.118' PORT = 9000 font = cv2....
CK_STREAM ) s.connect( ( HOST, PORT ) ) print('Hi! I am client') try: while True: if a == 0: recv_msg = s.recv(1024).decode('UTF-8') if recv_msg.startswith('TOR'): recv_msg = recv_msg.replace('TORDatesStand,','').split(',') ...
obal vStandard global TotalunpassCount global dateGap Result_horizon, Result_vertical = Dot_Distance(p1[count][0], p1[count][1], p2[count][0], p2[count][1], p3[count][0], p3[count][1], p4[count][0], p4[count][1]) Unit_horizon.append(Result_horizon) Unit_vertical.append(Result_vertical) ...
identifier_body
main.py
import socket import re import math import time from datetime import datetime, timedelta import random import numpy import RPi.GPIO as GPIO import cv2 import numpy as np import base64 from Class_Def import * from module import * #from open_cv import * HOST = '192.168.0.118' PORT = 9000 font = cv2....
count+=1 if count == lot: main_conveyor_On(con1_port) time.sleep(11) led_off(led2) led_off(led3) main_conveyor_Off(con1_port) ...
elif i == b: p2.append(temp[i]) elif i == c: p3.append(temp[i]) elif i == d: p4.append(temp[i]) calculate(count) led_off(led1)
conditional_block
client.go
//Docket Client //Author: Sivamani Varun //Gopher Gala package main //push //pull //-h[ost] //-p[ort] import ( "bytes" "encoding/json" "errors" "fmt" "github.com/alecthomas/kingpin" "github.com/fsouza/go-dockerclient" "io" "io/ioutil" "log" "mime/multipart" "net/http" "net/url" "os" "os/exec" "path/fil...
func applyPull(image string) error { defer track(time.Now(), "Image Pull") reg, err := regexp.Compile("[^A-Za-z0-9]+") if err != nil { return err } loc := *location if _, err := os.Stat(loc); os.IsNotExist(err) { os.Mkdir(loc, 0644) } safeImageName := reg.ReplaceAllString(image, "_") filePath :...
{ output, err := os.Create(fileName) if err != nil { fmt.Println("\nError while creating", fileName, "-", err) return err } defer output.Close() response, err := http.Get(url) if err != nil { fmt.Println("\nError while downloading", url, "-", err) return err } if response.StatusCode != 200 { fmt.Prin...
identifier_body
client.go
//Docket Client //Author: Sivamani Varun //Gopher Gala package main //push //pull //-h[ost] //-p[ort] import ( "bytes" "encoding/json" "errors" "fmt" "github.com/alecthomas/kingpin" "github.com/fsouza/go-dockerclient" "io" "io/ioutil" "log" "mime/multipart" "net/http" "net/url" "os" "os/exec" "path/fil...
//Load the downloaded tarball os.Chdir(filePath) fmt.Println("\n\nLoading Image....\n") importCmd := fmt.Sprintf("sudo tar -cC %s . | docker load", result[0]) _, err2 := exec.Command("sh", "-c", importCmd).Output() if err2 != nil { fmt.Printf("Failed to load image into docker!", err2) }else { os....
{ fmt.Printf("\nERROR in downloading layers\n") }
conditional_block
client.go
//Docket Client //Author: Sivamani Varun //Gopher Gala package main //push //pull //-h[ost] //-p[ort] import ( "bytes" "encoding/json" "errors" "fmt" "github.com/alecthomas/kingpin" "github.com/fsouza/go-dockerclient" "io" "io/ioutil" "log" "mime/multipart" "net/http" "net/url" "os" "os/exec" "path/fil...
(params map[string]string, paramName, path string) (*http.Request, error) { uri := *host + ":" + *port + "/images" file, err := os.Open(path) if err != nil { return nil, err } defer file.Close() body := &bytes.Buffer{} writer := multipart.NewWriter(body) part, err := writer.CreateFormFile(paramName, filepath...
uploadFile
identifier_name
client.go
//Docket Client //Author: Sivamani Varun //Gopher Gala package main //push //pull //-h[ost] //-p[ort] import ( "bytes" "encoding/json" "errors" "fmt" "github.com/alecthomas/kingpin" "github.com/fsouza/go-dockerclient"
"net/url" "os" "os/exec" "path/filepath" "sync" "regexp" "strconv" "strings" "time" ) var ( host = kingpin.Flag("host", "Set host of docket registry.").Short('h').Default("http://127.0.0.1").String() port = kingpin.Flag("port", "Set port of docket registry.").Short('p').Default("8004").Strin...
"io" "io/ioutil" "log" "mime/multipart" "net/http"
random_line_split
context.rs
// Copyright (C) 2018-2020 Sebastian Dröge <sebastian@centricular.com> // Copyright (C) 2019-2022 François Laignel <fengalin@free.fr> // // Take a look at the license at the top of the repository in the LICENSE file. use futures::prelude::*; use gst::glib::once_cell::sync::Lazy; use std::collections::HashMap; use st...
/// of a [`Context`]. /// /// # Panic /// /// This will block current thread and would panic if run /// from the [`Context`]. #[track_caller] pub fn enter<'a, F, O>(&'a self, f: F) -> O where F: FnOnce() -> O + Send + 'a, O: Send + 'a, { if let Some(cur) =...
/// Executes the provided function relatively to this [`Context`]. /// /// Usefull to initialize i/o sources and timers from outside
random_line_split
context.rs
// Copyright (C) 2018-2020 Sebastian Dröge <sebastian@centricular.com> // Copyright (C) 2019-2022 François Laignel <fengalin@free.fr> // // Take a look at the license at the top of the repository in the LICENSE file. use futures::prelude::*; use gst::glib::once_cell::sync::Lazy; use std::collections::HashMap; use st...
} else { gst::debug!(RUNTIME_CAT, "Entering Context {}", self.name()); } self.0.enter(f) } pub fn spawn<Fut>(&self, future: Fut) -> JoinHandle<Fut::Output> where Fut: Future + Send + 'static, Fut::Output: Send + 'static, { self.0.spawn(future)...
gst::warning!( RUNTIME_CAT, "Entering Context {} within {}", self.name(), cur.name() ); }
conditional_block
context.rs
// Copyright (C) 2018-2020 Sebastian Dröge <sebastian@centricular.com> // Copyright (C) 2019-2022 François Laignel <fengalin@free.fr> // // Take a look at the license at the top of the repository in the LICENSE file. use futures::prelude::*; use gst::glib::once_cell::sync::Lazy; use std::collections::HashMap; use st...
pub fn spawn<Fut>(&self, future: Fut) -> JoinHandle<Fut::Output> where Fut: Future + Send + 'static, Fut::Output: Send + 'static, { self.0.spawn(future) } pub fn spawn_and_unpark<Fut>(&self, future: Fut) -> JoinHandle<Fut::Output> where Fut: Future + Send + 'stat...
if let Some(cur) = Context::current().as_ref() { if cur == self { panic!( "Attempt to enter Context {} within itself, this would deadlock", self.name() ); } else { gst::warning!( R...
identifier_body
context.rs
// Copyright (C) 2018-2020 Sebastian Dröge <sebastian@centricular.com> // Copyright (C) 2019-2022 François Laignel <fengalin@free.fr> // // Take a look at the license at the top of the repository in the LICENSE file. use futures::prelude::*; use gst::glib::once_cell::sync::Lazy; use std::collections::HashMap; use st...
andle: Handle) -> Self { Context(handle) } } #[cfg(test)] mod tests { use futures::channel::mpsc; use futures::lock::Mutex; use futures::prelude::*; use std::net::{IpAddr, Ipv4Addr, SocketAddr, UdpSocket}; use std::sync::Arc; use std::time::{Duration, Instant}; use super::supe...
om(h
identifier_name
core.go
// Package natyla ... // Natyla - FullStack API/Cache/Store // // 2014 - Fernando Scasserra - twitter: @fersca. // // Natyla is a persistance cache system written in golang that performs in constant time. // It keeps a MAP to store the object internally, and a Double Linked list to purge the LRU elements. // // LRU upd...
} // Move the element to the front of the LRU, because it was readed or updated func moveFront(elemento *list.Element) { //Move the element lisChan <- 1 lruList.MoveToFront(elemento) <-lisChan if enablePrint { fmt.Println("LRU Updated") } } // Delete the element from the disk, and if its enable, cache the not...
random_line_split
core.go
// Package natyla ... // Natyla - FullStack API/Cache/Store // // 2014 - Fernando Scasserra - twitter: @fersca. // // Natyla is a persistance cache system written in golang that performs in constant time. // It keeps a MAP to store the object internally, and a Double Linked list to purge the LRU elements. // // LRU upd...
(valor string) (map[string]interface{}, error) { //Create the Json element d := json.NewDecoder(strings.NewReader(valor)) d.UseNumber() var f interface{} err := d.Decode(&f) if err != nil { return nil, err } //transform it to a map m := f.(map[string]interface{}) return m, nil } //Create a token for th...
convertJSONToMap
identifier_name
core.go
// Package natyla ... // Natyla - FullStack API/Cache/Store // // 2014 - Fernando Scasserra - twitter: @fersca. // // Natyla is a persistance cache system written in golang that performs in constant time. // It keeps a MAP to store the object internally, and a Double Linked list to purge the LRU elements. // // LRU upd...
// Delete the element from the disk, and if its enable, cache the not-found func deleteElement(col string, clave string) bool { //Get the element collection cc := collections[col] //Get the element from the map elemento := cc.Mapa[clave] //checks if the element exists in the cache if elemento != nil { //i...
{ //Move the element lisChan <- 1 lruList.MoveToFront(elemento) <-lisChan if enablePrint { fmt.Println("LRU Updated") } }
identifier_body
core.go
// Package natyla ... // Natyla - FullStack API/Cache/Store // // 2014 - Fernando Scasserra - twitter: @fersca. // // Natyla is a persistance cache system written in golang that performs in constant time. // It keeps a MAP to store the object internally, and a Double Linked list to purge the LRU elements. // // LRU upd...
//unsync <-lisChan } <-LRUChan } // Move the element to the front of the LRU, because it was readed or updated func moveFront(elemento *list.Element) { //Move the element lisChan <- 1 lruList.MoveToFront(elemento) <-lisChan if enablePrint { fmt.Println("LRU Updated") } } // Delete the element from th...
{ fmt.Println("Purge Done: ", memBytes) }
conditional_block
define.kChartDataManager.js
;(function(namespace){ var util = namespace.util; /** * 刷新K线图数据时,相邻两次刷新操作之间的时间间隔。单位:毫秒 * @type {Number} */ var refreshGap = 2000; var maxPageSize = 300; /** * @typedef {Object} KData */ /** * 获取K线图数据 * @param {String} symbol 产品代码 * @param {Function} onsuccess 获取成功后执行的方法 * @param {Function}...
this.updateVisibleKDataListEndIndexOffsetFromLatest = function(visibleKDataCount, offset){ var currentOffset = kChartData.getInvisibleLaterKDataListLength(); var newOffset = currentOffset + offset; var maxOffset = Math.max(kChartData.getKDataList().length - visibleKDataCount, 0); if(isAllEarlierKDataLoade...
* @param {Integer} visibleKDataCount 可见数据量 * @param {Integer} offset 位移在既有基础上的偏移量 * @returns {KChartData} */
random_line_split
app.py
import flask import json import uuid import jwt import smooch from flask import Flask, request, Response from redis import Redis from smooch.rest import ApiException from promise import Promise from persistence import Persistence app = Flask(__name__) app.secret_key = str(uuid.uuid4()) # redis = Redis(host='redis', po...
elif text == "Giving": api_response = api_instance.post_message(APP_ID, user_id, postText("Got it! How much did you spend?")) elif text == "Repayments": api_response = api_instance.post_message(APP_ID, user_id, postText("Got it! How much did you spend?")) elif text ...
random_line_split
app.py
import flask import json import uuid import jwt import smooch from flask import Flask, request, Response from redis import Redis from smooch.rest import ApiException from promise import Promise from persistence import Persistence app = Flask(__name__) app.secret_key = str(uuid.uuid4()) # redis = Redis(host='redis', po...
(request_data): body = json.loads(request_data) user_id = body['appUser']['_id'] if body['trigger'] == 'message:appUser': for message in body['messages']: handle_message(user_id, message['text']) elif body['trigger'] == 'postback': for postback in body['postbacks']: ...
parse_request_data
identifier_name
app.py
import flask import json import uuid import jwt import smooch from flask import Flask, request, Response from redis import Redis from smooch.rest import ApiException from promise import Promise from persistence import Persistence app = Flask(__name__) app.secret_key = str(uuid.uuid4()) # redis = Redis(host='redis', po...
elif text == "Weekly Allowance Spend": api_response = api_instance.post_message(APP_ID, user_id, postText("Got it! How much did you spend?")) elif text == "Regular Spend": api_response = api_instance.post_message(APP_ID, user_id, postText("Got it! What did you spend mo...
api_response = api_instance.post_message(APP_ID, user_id, postText("Got it!")) api_response = api_instance.post_message(APP_ID, user_id, postText("Ok, how much is your weekly allowance budget?"))
conditional_block
app.py
import flask import json import uuid import jwt import smooch from flask import Flask, request, Response from redis import Redis from smooch.rest import ApiException from promise import Promise from persistence import Persistence app = Flask(__name__) app.secret_key = str(uuid.uuid4()) # redis = Redis(host='redis', po...
def postCarousel(list): message = smooch.MessagePost(role='appMaker', type='carousel') items = [] for item in list: actions = [] actions.append(smooch.Action(type='postback', text=item, payload=item)) part = smooch.MessageItem(title=item, actions=actions) part.media_url =...
message = smooch.MessagePost(role='appMaker', type='file') message.media_url = uri return message
identifier_body
google_spreadsheets.rs
use std::collections::{HashMap, HashSet}; use std::convert::TryFrom; use std::sync::Arc; use datafusion::arrow::array::{ArrayRef, BooleanArray, PrimitiveArray, StringArray}; use datafusion::arrow::datatypes::{DataType, Field, Schema}; use datafusion::arrow::datatypes::{Float64Type, Int64Type}; use datafusion::arrow::r...
let uri = URIReference::try_from(uri_str)?; let spreadsheet_id = uri.path().segments()[2].as_str(); let opt = t .option .as_ref() .ok_or(ColumnQError::MissingOption)? .as_google_spreadsheet()?; let token = fetch_auth_token(opt).await?; let token_str = token.as_str...
{ return Err(ColumnQError::InvalidUri(uri_str.to_string())); }
conditional_block
google_spreadsheets.rs
use std::collections::{HashMap, HashSet}; use std::convert::TryFrom; use std::sync::Arc; use datafusion::arrow::array::{ArrayRef, BooleanArray, PrimitiveArray, StringArray}; use datafusion::arrow::datatypes::{DataType, Field, Schema}; use datafusion::arrow::datatypes::{Float64Type, Int64Type}; use datafusion::arrow::r...
let fields: Vec<Field> = col_names .iter() .map(|col_name| { let set = col_types.entry(col_name).or_insert_with(|| { // TODO: this should never happen, maybe we should use panic instead? let mut set = HashSet::new(); set.insert(DataType::Ut...
random_line_split
google_spreadsheets.rs
use std::collections::{HashMap, HashSet}; use std::convert::TryFrom; use std::sync::Arc; use datafusion::arrow::array::{ArrayRef, BooleanArray, PrimitiveArray, StringArray}; use datafusion::arrow::datatypes::{DataType, Field, Schema}; use datafusion::arrow::datatypes::{Float64Type, Int64Type}; use datafusion::arrow::r...
fn coerce_type(l: DataType, r: DataType) -> DataType { match (l, r) { (DataType::Boolean, DataType::Boolean) => DataType::Boolean, (DataType::Date32, DataType::Date32) => DataType::Date32, (DataType::Date64, DataType::Date64) | (DataType::Date64, DataType::Date32) | (DataT...
{ Client::builder() .build() .map_err(|e| { ColumnQError::GoogleSpreadsheets(format!( "Failed to initialize HTTP client: {}", e.to_string() )) })? .get(url) .bearer_auth(token) .send() .await .map...
identifier_body
google_spreadsheets.rs
use std::collections::{HashMap, HashSet}; use std::convert::TryFrom; use std::sync::Arc; use datafusion::arrow::array::{ArrayRef, BooleanArray, PrimitiveArray, StringArray}; use datafusion::arrow::datatypes::{DataType, Field, Schema}; use datafusion::arrow::datatypes::{Float64Type, Int64Type}; use datafusion::arrow::r...
(s: &str) -> bool { s.eq_ignore_ascii_case("true") } fn sheet_values_to_record_batch(values: &[Vec<String>]) -> Result<RecordBatch, ColumnQError> { let schema = infer_schema(values); let arrays = schema .fields() .iter() .enumerate() .map(|(i, field)| { // skip ...
parse_boolean
identifier_name
end2end_test.go
package tests import ( "bytes" "context" "crypto/rand" "encoding/hex" "fmt" "os" "reflect" "testing" "time" "github.com/amenzhinsky/iothub/iotdevice" "github.com/amenzhinsky/iothub/iotdevice/transport" "github.com/amenzhinsky/iothub/iotdevice/transport/mqtt" "github.com/amenzhinsky/iothub/iotservice" ) ...
defer dc.UnsubscribeTwinUpdates(sub) // TODO: hacky, but reduces flakiness time.Sleep(time.Second) twin, err := sc.UpdateDeviceTwin(context.Background(), &iotservice.Twin{ DeviceID: dc.DeviceID(), Tags: map[string]interface{}{ "test-device": true, }, Properties: &iotservice.Properties{ Desired: map...
{ t.Fatal(err) }
conditional_block
end2end_test.go
package tests import ( "bytes" "context" "crypto/rand" "encoding/hex" "fmt" "os" "reflect" "testing" "time" "github.com/amenzhinsky/iothub/iotdevice" "github.com/amenzhinsky/iothub/iotdevice/transport" "github.com/amenzhinsky/iothub/iotdevice/transport/mqtt" "github.com/amenzhinsky/iothub/iotservice" ) ...
() string { b := make([]byte, 16) if _, err := rand.Read(b); err != nil { panic(err) } return hex.EncodeToString(b) }
genID
identifier_name
end2end_test.go
package tests import ( "bytes" "context" "crypto/rand" "encoding/hex" "fmt" "os" "reflect" "testing" "time" "github.com/amenzhinsky/iothub/iotdevice" "github.com/amenzhinsky/iothub/iotdevice/transport" "github.com/amenzhinsky/iothub/iotdevice/transport/mqtt" "github.com/amenzhinsky/iothub/iotservice" ) ...
if state["$version"] != twin.Properties.Desired["$version"] { t.Errorf("version = %d, want %d", state["$version"], twin.Properties.Desired["$version"]) } if state["test-prop"] != twin.Properties.Desired["test-prop"] { t.Errorf("test-prop = %q, want %q", state["test-prop"], twin.Properties.Desired["test-prop...
} select { case state := <-sub.C():
random_line_split
end2end_test.go
package tests import ( "bytes" "context" "crypto/rand" "encoding/hex" "fmt" "os" "reflect" "testing" "time" "github.com/amenzhinsky/iothub/iotdevice" "github.com/amenzhinsky/iothub/iotdevice/transport" "github.com/amenzhinsky/iothub/iotdevice/transport/mqtt" "github.com/amenzhinsky/iothub/iotservice" ) ...
func genID() string { b := make([]byte, 16) if _, err := rand.Read(b); err != nil { panic(err) } return hex.EncodeToString(b) }
{ if err := dc.RegisterMethod( context.Background(), "sum", func(v map[string]interface{}) (int, map[string]interface{}, error) { return 222, map[string]interface{}{ "result": v["a"].(float64) + v["b"].(float64), }, nil }, ); err != nil { t.Fatal(err) } resc := make(chan *iotservice.MethodResul...
identifier_body
build_ionospheric_model.py
#!/usr/bin/env python """build_ionospheric_model.py: module is dedicated to build foF2 model from fitacf data.""" __author__ = "Chakraborty, S." __copyright__ = "Copyright 2020, SuperDARN@VT" __credits__ = [] __license__ = "MIT" __version__ = "1.0." __maintainer__ = "Chakraborty, S." __email__ = "shibaji7@vt.edu" __s...
(xx, a0, c0, s0): return a0 * (1/(s0*(np.sqrt(2*np.pi))))*(np.exp((-1.0/2.0)*(((xx-c0)/s0)**2))) def _a_gaussian(xx, a0, c0, s0, sp ): return _1gaussian(xx, a0, c0, s0 ) * (0.5 + (np.arctan(sp*(xx-c0))/np.pi)) def opt(f, x0, y0, p0): popt, pcov = curve_fit(f, x0, y0, p0=p0) ...
_1gaussian
identifier_name
build_ionospheric_model.py
#!/usr/bin/env python """build_ionospheric_model.py: module is dedicated to build foF2 model from fitacf data.""" __author__ = "Chakraborty, S." __copyright__ = "Copyright 2020, SuperDARN@VT" __credits__ = [] __license__ = "MIT" __version__ = "1.0." __maintainer__ = "Chakraborty, S." __email__ = "shibaji7@vt.edu" __s...
def opt(f, x0, y0, p0): popt, pcov = curve_fit(f, x0, y0, p0=p0) perr = np.sqrt(np.diag(pcov)) return popt, perr def estimate_skip_distance(popt): xx = np.linspace(0,popt[1],30000) yy = _a_gaussian(xx, popt_ag[0], popt_ag[1], popt_ag[2], popt_ag[3]) pri...
return _1gaussian(xx, a0, c0, s0 ) * (0.5 + (np.arctan(sp*(xx-c0))/np.pi))
identifier_body
build_ionospheric_model.py
#!/usr/bin/env python """build_ionospheric_model.py: module is dedicated to build foF2 model from fitacf data.""" __author__ = "Chakraborty, S." __copyright__ = "Copyright 2020, SuperDARN@VT" __credits__ = [] __license__ = "MIT" __version__ = "1.0." __maintainer__ = "Chakraborty, S." __email__ = "shibaji7@vt.edu" __s...
for beam in scan.beams: if len(beam.slist) > 0: setattr(beam, "slant_range", beam.frang + np.array(beam.slist.tolist()) * beam.rsep) setattr(beam, "tfreq", np.round(beam.tfreq/1e3,1)) beams.append(beam) # Extract oblique foF2 or...
random_line_split
build_ionospheric_model.py
#!/usr/bin/env python """build_ionospheric_model.py: module is dedicated to build foF2 model from fitacf data.""" __author__ = "Chakraborty, S." __copyright__ = "Copyright 2020, SuperDARN@VT" __credits__ = [] __license__ = "MIT" __version__ = "1.0." __maintainer__ = "Chakraborty, S." __email__ = "shibaji7@vt.edu" __s...
du = pd.DataFrame() du["p_l"], du["srange"] = p_l, srange du = du[(du.srange>remove_first_range) & (du.srange<remove_last_range)] fname = "images/{}.png".format(rscan[0].stime.strftime("%Y-%m-%d-%H-%M")) if len(du) > 0: sd = fit_lambda(du, pow...
if len(beam.slist) > 0: p_l.extend(beam.p_l.tolist()) srange.extend(beam.slant_range.tolist()) tfrq.append(beam.tfreq) if type(beam.elv) is list: angle.extend(beam.elv) else: angle...
conditional_block
actionitems.ts
import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, PopoverController } from 'ionic-angular'; import { TopbarComponent } from '../../components/topbar/topbar'; import { AssessmentService } from '../../services/assessment.service'; import { GoogleAnalytics } from '../../application/h...
(questionId) { this.navCtrl.push(QuestionsPage, { questionId: questionId }); } public calculateRiskScore(likelihood, consequence) { // preventing off by one errors, with nulls. // values should always be 1-5 var riskMatrix = [ [ null ], [ null, 1, 3, 5, 8, 12], [ null, 2, 7,...
navToQuestion
identifier_name
actionitems.ts
import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, PopoverController } from 'ionic-angular'; import { TopbarComponent } from '../../components/topbar/topbar'; import { AssessmentService } from '../../services/assessment.service'; import { GoogleAnalytics } from '../../application/h...
displayRisks(q) { var risks = []; q.technical ? risks.push("Technical") : null q.schedule ? risks.push("Schedule") : null q.cost ? risks.push("Cost") : null return risks.join(", ") || "none"; } getAttachments(q) { return this.attachments.filter(a => a.questionId == q.questionId );...
{ GoogleAnalytics.trackPage("actionitems"); }
identifier_body
actionitems.ts
import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, PopoverController } from 'ionic-angular'; import { TopbarComponent } from '../../components/topbar/topbar'; import { AssessmentService } from '../../services/assessment.service'; import { GoogleAnalytics } from '../../application/h...
public onChangeTable(config:any, page:any = {page: this.page, itemsPerPage: this.itemsPerPage}):any { if (config.filtering) { Object.assign(this.config.filtering, config.filtering); } if (config.sorting) { Object.assign(this.config.sorting, config.sorting); } let filteredData = this...
return filteredData; }
random_line_split
actionitems.ts
import { Component } from '@angular/core'; import { IonicPage, NavController, NavParams, PopoverController } from 'ionic-angular'; import { TopbarComponent } from '../../components/topbar/topbar'; import { AssessmentService } from '../../services/assessment.service'; import { GoogleAnalytics } from '../../application/h...
}); var targetMRL = (<any>data.data).assessment.targetMRL; this.attachments = (<any>data.data).assessment.files; var newData:Array<any> = []; console.log(this.no); this.no.forEach( (element) => { var newObj:any = {}; newObj.threadName = "" + element.t...
{ return a.answers[a.answers.length - 1].answer == "No" }
conditional_block
pm.rs
//! Implementation of the power manager (PM) peripheral. use bpm; use bscif; use core::cell::Cell; use core::sync::atomic::Ordering; use flashcalw; use gpio; use kernel::common::VolatileCell; use scif; #[repr(C)] struct PmRegisters {
pbbsel: VolatileCell<u32>, pbcsel: VolatileCell<u32>, pbdsel: VolatileCell<u32>, _reserved2: VolatileCell<u32>, cpumask: VolatileCell<u32>, // 0x020 hsbmask: VolatileCell<u32>, pbamask: VolatileCell<u32>, pbbmask: VolatileCell<u32>, pbcmask: VolatileCell<u32>, pbdmask: VolatileCe...
mcctrl: VolatileCell<u32>, cpusel: VolatileCell<u32>, _reserved1: VolatileCell<u32>, pbasel: VolatileCell<u32>,
random_line_split
pm.rs
//! Implementation of the power manager (PM) peripheral. use bpm; use bscif; use core::cell::Cell; use core::sync::atomic::Ordering; use flashcalw; use gpio; use kernel::common::VolatileCell; use scif; #[repr(C)] struct PmRegisters { mcctrl: VolatileCell<u32>, cpusel: VolatileCell<u32>, _reserved1: Volati...
{ /// 16 MHz external oscillator Frequency16MHz, } /// Configuration for the startup time of the external oscillator. In practice /// we have found that some boards work with a short startup time, while others /// need a slow start in order to properly wake from sleep. In general, we find /// that for systems...
OscillatorFrequency
identifier_name
hal.py
import os import ujson import utime import machine # LEDs STATUS = 0 SONAR = 1 LEFT_LINE = 2 RIGHT_LINE = 3 # Directions STOP = 0 LEFT = 1 RIGHT = 2 SEARCH = 3 FORWARD = 4 BACKWARD = 5 class Sumorobot(object): # Constructor def __init__(self): # Open and parse the config file with open('con...
def get_configuration_scope(self): return str(self.config['sumorobot_name']) + ',' \ + str(self.config['firmware_version']) + ',' \ + str(self.config['left_line_value']) + ',' \ + str(self.config['right_line_value']) + ',' \ + str(self.config['left_line_thr...
return str(self.get_sonar_value()) + ',' \ + str(self.get_line(LEFT)) + ',' \ + str(self.get_line(RIGHT)) + ',' \ + str(self.bat_charge.value()) + ',' \ + str(self.get_battery_level())
identifier_body
hal.py
import os import ujson import utime import machine # LEDs STATUS = 0 SONAR = 1 LEFT_LINE = 2 RIGHT_LINE = 3 # Directions STOP = 0 LEFT = 1 RIGHT = 2 SEARCH = 3 FORWARD = 4 BACKWARD = 5 class Sumorobot(object): # Constructor def __init__(self): # Open and parse the config file with open('con...
(self): # TODO: implement sensor value caching return str(self.get_sonar_value()) + ',' \ + str(self.get_line(LEFT)) + ',' \ + str(self.get_line(RIGHT)) + ',' \ + str(self.bat_charge.value()) + ',' \ + str(self.get_battery_level()) def get_configurat...
get_sensor_scope
identifier_name
hal.py
import os import ujson import utime import machine # LEDs STATUS = 0 SONAR = 1
LEFT_LINE = 2 RIGHT_LINE = 3 # Directions STOP = 0 LEFT = 1 RIGHT = 2 SEARCH = 3 FORWARD = 4 BACKWARD = 5 class Sumorobot(object): # Constructor def __init__(self): # Open and parse the config file with open('config.json', 'r') as config_file: self.config = ujson.load(config_file)...
random_line_split
hal.py
import os import ujson import utime import machine # LEDs STATUS = 0 SONAR = 1 LEFT_LINE = 2 RIGHT_LINE = 3 # Directions STOP = 0 LEFT = 1 RIGHT = 2 SEARCH = 3 FORWARD = 4 BACKWARD = 5 class Sumorobot(object): # Constructor def __init__(self): # Open and parse the config file with open('con...
else: self.move(RIGHT) # Increase search counter self.search_counter += 1 elif dir == FORWARD: self.set_servo(LEFT, 100) self.set_servo(RIGHT, 100) elif dir == BACKWARD: self.set_servo(LEFT, -100) self.s...
self.move(LEFT)
conditional_block
bdplatfrom.js
//协议 if (!Array.prototype.shuffle) { Array.prototype.shuffle = function () { for (var j, x, i = this.length; i; j = parseInt(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x); return this; }; } /** * 百度SDK */ class bdplatform { /** * 平台配置 */ constructor() { /*****平台配置*********...
this.VideoAd1 = "6580222"; /*** 金币获取激励视频 */ this.VideoAd2 = "6580147"; /**签到双倍奖励视频 */ this.VideoAd3 = "6580146"; /**再来一份视频奖励 */ this.VideoAd4 = "6580145"; /**转盘获取次数奖励 */ this.VideoAd5 = "6580144"; /**转盘双倍奖励视频 */ this.VideoAd6= "6580143"; /**金币不足视频 */ this.VideoAd7= "6...
/*** 离线双倍奖励激励视频 */
random_line_split
bdplatfrom.js
//协议 if (!Array.prototype.shuffle) { Array.prototype.shuffle = function () { for (var j, x, i = this.length; i; j = parseInt(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x); return this; }; } /** * 百度SDK */ class bdplatform { /** * 平台配置 */ constructor() { /*****平台配置********...
today; // } // // 分享日期 // getLastShareDate() { // if (this.lastShareDate) return this.lastShareDate; // var lastShareDate = window.localStorage.getItem('LastShareDate'); // if (lastShareDate === '' || lastShareDate === null || lastShareDate === undefined) { // lastSha...
var year = myDate.getFullYear(); // var month = myDate.getMonth() + 1; // var date = myDate.getDate(); // var today = '' + year + '_' + month + '_' + date; // return
identifier_body
bdplatfrom.js
//协议 if (!Array.prototype.shuffle) { Array.prototype.shuffle = function () { for (var j, x, i = this.length; i; j = parseInt(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x); return this; }; } /** * 百度SDK */ class bdplatform { /** * 平台配置 */ constructor() { /*****平台配置********...
fail(res) { console.log('bd.login fail !' + res.errMsg); let data = {}; data.code = -1; data.msg = res.errMsg; cb && cb(data); } } ); } /**检查用户登录状态是否有效 */ checkSession() { swan.checkSession( ...
; data.code = -1; data.msg = res.errMsg; } cb && cb(data); },
conditional_block
bdplatfrom.js
//协议 if (!Array.prototype.shuffle) { Array.prototype.shuffle = function () { for (var j, x, i = this.length; i; j = parseInt(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x); return this; }; } /** * 百度SDK */ class bdplatform { /** * 平台配置 */ constructor() {
台配置******************************************** */ this.AppID = "17008570"; //正常标准广告 this.NormalAdunits = [ "6580232", "6580230", "6580229", "6580225", "6580224", ]; //弹窗 this.OtherAdunits = [ ]; /*** 成功结算 */ /*** 离线双倍奖励激励视频 */ this.V...
/*****平
identifier_name
blockparse.py
#!/usr/bin/python3 -OO ''' writing parser.cpp replacement in Python3 using ideas and code from http://www.righto.com/2014/02/bitcoins-hard-way-using-raw-bitcoin.html, http://www.righto.com/2014/02/bitcoin-mining-hard-way-algorithms.html, https://bitcoin.org/en/developer-guide, https://bitcoin.org/en/developer-referenc...
elif height > maxheight: logging.debug('height %d > maxheight %d', height, maxheight) break # still executes `height += 1` below! else: logging.debug('height: %d', height) height += 1 logging.debug('height: %d, maxheight: %d',...
logging.debug('height: %d', height) logging.debug('magic: %s', binascii.b2a_hex(magic)) logging.debug('block type: %s', reversemagic.get( magic, 'unknown')) logging.debug('block size: %d', blocksize) logging.debug('block header...
conditional_block
blockparse.py
#!/usr/bin/python3 -OO ''' writing parser.cpp replacement in Python3 using ideas and code from http://www.righto.com/2014/02/bitcoins-hard-way-using-raw-bitcoin.html, http://www.righto.com/2014/02/bitcoin-mining-hard-way-algorithms.html, https://bitcoin.org/en/developer-guide, https://bitcoin.org/en/developer-referenc...
(count, data): ''' return transaction outputs ''' raw_outputs = [] outputs = [] for index in range(count): tx_output, output_split, data = parse_output(data) raw_outputs.append(tx_output) outputs.append(output_split) return raw_outputs, outputs, data def parse_input(...
parse_outputs
identifier_name
blockparse.py
#!/usr/bin/python3 -OO ''' writing parser.cpp replacement in Python3 using ideas and code from http://www.righto.com/2014/02/bitcoins-hard-way-using-raw-bitcoin.html, http://www.righto.com/2014/02/bitcoin-mining-hard-way-algorithms.html, https://bitcoin.org/en/developer-guide, https://bitcoin.org/en/developer-referenc...
__str__ = __repr__ bytevalue = lambda byte: ord(byte) bytevalues = lambda string: map(ord, string) byte = chr FileNotFoundError = IOError else: # python3 bytevalue = lambda byte: byte bytevalues = list byte = lambda number: chr(number).encode('latin1') LOGLEVEL = getattr(logging, ...
return 'b' + super(bytes, self).__repr__()
identifier_body
blockparse.py
#!/usr/bin/python3 -OO ''' writing parser.cpp replacement in Python3 using ideas and code from http://www.righto.com/2014/02/bitcoins-hard-way-using-raw-bitcoin.html, http://www.righto.com/2014/02/bitcoin-mining-hard-way-algorithms.html, https://bitcoin.org/en/developer-guide, https://bitcoin.org/en/developer-referenc...
try: match = re.compile(pattern).match(filename).groupdict() except AttributeError as match_failed: raise ValueError('No numeric pattern found in {}'.format(filename)) newnumber = '{number:0{width}}'.format( number=int(match['number']) + 1, width=len(match['number'])) fil...
pattern = r'^(?P<prefix>[^0-9]*)(?P<number>[0-9]+)(?P<suffix>[^0-9]*)$' directory, filename = os.path.split(filename)
random_line_split
main.rs
/* This tool is part of the WhiteboxTools geospatial analysis library. Authors: Daniel Newman Created: 22/06/2020 Last Modified: 22/06/2020 License: MIT */ use whitebox_raster::*; use nalgebra::{Matrix5, RowVector5, Vector5}; use num_cpus; use std::env; use std::f64; use std::io::{Error, ErrorKind}; use std::path; use...
for c in 0..num_cells { zi = input[((row + dy[c] as isize), (col + dx[c] as isize))]; if zi != nodata { xs.push(dx[c] as f64 * resolution); ys.push(dy[c] as f64 * resolution); ...
let mut zs = vec![];
random_line_split
main.rs
/* This tool is part of the WhiteboxTools geospatial analysis library. Authors: Daniel Newman Created: 22/06/2020 Last Modified: 22/06/2020 License: MIT */ use whitebox_raster::*; use nalgebra::{Matrix5, RowVector5, Vector5}; use num_cpus; use std::env; use std::f64; use std::io::{Error, ErrorKind}; use std::path; use...
else { nu / de } } fn plan_convexity(&self) -> f64 { let nu = 200f64 * ((self.b*self.d*self.d) + (self.a*self.e*self.e) - (self.c*self.d*self.e)); let de = ((self.e*self.e) + (self.d*self.d)).powf(1.5); if nu == 0f64 || de == 0f64 { 0f64 } else {...
{ 0f64 }
conditional_block
main.rs
/* This tool is part of the WhiteboxTools geospatial analysis library. Authors: Daniel Newman Created: 22/06/2020 Last Modified: 22/06/2020 License: MIT */ use whitebox_raster::*; use nalgebra::{Matrix5, RowVector5, Vector5}; use num_cpus; use std::env; use std::f64; use std::io::{Error, ErrorKind}; use std::path; use...
(&self) -> f64 { (self.a * -1f64) - self.b - ((self.a - self.b).powi(2) + (self.c * self.c)).sqrt() } fn solve(&self, x: f64, y: f64) -> f64 { // z(x,y) = ax^2 + by^2 + cxy + dx + ey + f return (self.a*(x*x)) + (self.b*(y*y)) + (self.c*(x*y)) + (self.d*x) + (self.e*y) + self.f } }
min_prof_convexity
identifier_name
main.rs
/* This tool is part of the WhiteboxTools geospatial analysis library. Authors: Daniel Newman Created: 22/06/2020 Last Modified: 22/06/2020 License: MIT */ use whitebox_raster::*; use nalgebra::{Matrix5, RowVector5, Vector5}; use num_cpus; use std::env; use std::f64; use std::io::{Error, ErrorKind}; use std::path; use...
// Equation of a 2d quadratic model: // z(x,y) = ax^2 + by^2 + cxy + dx + ey + f #[derive(Default, Clone, Copy)] struct Quadratic2d { a: f64, b: f64, c: f64, d: f64, e: f64, f: f64 } impl Quadratic2d { fn new(a: f64, b: f64, c: f64, d: f64, e: f64, f: f64) -> Quadratic2d { Quadrat...
{ let tool_name = get_tool_name(); let sep: String = path::MAIN_SEPARATOR.to_string(); // Read in the environment variables and get the necessary values let configurations = whitebox_common::configs::get_configs()?; let mut working_directory = configurations.working_directory.clone(); if !work...
identifier_body
Login.ts
import { basic, thread, thread as th, reflection, Common, ScopicCommand, bind, Api, net, encoding, Notification, collection } from "../lib/Q/sys/Corelib" import { AI } from '../lib/q/sys/AI'; import { db } from '../lib/q/sys/db'; import { UI } from '../lib/q/sys/UI'; import { Controller, sdata } from '../lib/q/sys/Sy...
>(callback: (v: boolean, param: T) => void, param: T) { callback(GData.user.IsLogged, param); } private createSignupPage() { var p = new UI.Page(this, 'Signup', 'Signup'); p.OnInitialized = p => p.Add(new UI.TControl('Client.signup', GData.user)); this.Ad...
Logged<T
identifier_name
Login.ts
import { basic, thread, thread as th, reflection, Common, ScopicCommand, bind, Api, net, encoding, Notification, collection } from "../lib/Q/sys/Corelib" import { AI } from '../lib/q/sys/AI'; import { db } from '../lib/q/sys/db'; import { UI } from '../lib/q/sys/UI'; import { Controller, sdata } from '../lib/q/sys/Sy...
this.dx = true; GData.__data.Clear(); Api.RiseApi('log', { callback: null, data: null }); GData.requester.Push(models.IsAdmin, new models.IsAdmin(), null, (s, r, iss) => { GData.spin.Start("Wait a moment"); GData.requester.Pus...
Notification.fire('ReLoadUserSetting', [models.UserSetting.Default]); if (this.dx) { GData.spin.Pause(); return; }
random_line_split
Login.ts
import { basic, thread, thread as th, reflection, Common, ScopicCommand, bind, Api, net, encoding, Notification, collection } from "../lib/Q/sys/Corelib" import { AI } from '../lib/q/sys/AI'; import { db } from '../lib/q/sys/db'; import { UI } from '../lib/q/sys/UI'; import { Controller, sdata } from '../lib/q/sys/Sy...
private createLoginPage() { var p = new UI.Page(this, 'Login', 'Login'); p.OnInitialized = p => p.Add(new UI.TControl('Client.login', GData.user)); this.AddPage(this._loginPage = p); } private auth = thread.Dispatcher.cretaeJob(this.Login, [], this, true); ...
var p = new UI.Page(this, 'Signup', 'Signup'); p.OnInitialized = p => p.Add(new UI.TControl('Client.signup', GData.user)); this.AddPage(this._signupPage = p); }
identifier_body
mod.rs
mod fifo; mod background_fifo; mod sprite_fifo; use crate::bus::*; use crate::cpu::{interrupt, InterruptType}; use crate::clock::ClockListener; use std::fmt; use std::cell::RefCell; use std::rc::Rc; use crate::graphics_driver::GraphicsDriver; use crate::ppu::background_fifo::BackgroundFifo; use crate::ppu::sprite_fi...
self.clock += cycles as u16; use Mode::*; match self.mode { OAM => { for _ in 0..(cycles << 1) { self.spfifo.scan_next_oam_table_entry(&self.OAM, &self.registers); } if self.clock < OAM_CYCLES { ...
self.registers.dma_counter += 1; self.registers.dma_active = self.registers.dma_counter < DISPLAY_WIDTH; }
random_line_split
mod.rs
mod fifo; mod background_fifo; mod sprite_fifo; use crate::bus::*; use crate::cpu::{interrupt, InterruptType}; use crate::clock::ClockListener; use std::fmt; use std::cell::RefCell; use std::rc::Rc; use crate::graphics_driver::GraphicsDriver; use crate::ppu::background_fifo::BackgroundFifo; use crate::ppu::sprite_fi...
() -> Self { Self { on: false, mode: Mode::VBlank, clock: 0, pixel_buffer: [0x00; PITCH], palette_buffer: [0xFFFFFF, 0xC0C0C0, 0x404040, 0x000000], render_flag: true, VRAM: [0; 0x2000], OAM: [0; 0x100], ...
new
identifier_name
addon.go
/* Copyright 2021 The KubeVela Authors. 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 writing, softw...
func genAddonAPISchema(addonRes *types.Addon) error { param, err := utils2.PrepareParameterCue(addonRes.Name, addonRes.Parameters) if err != nil { return err } var r cue.Runtime cueInst, err := r.Compile("-", param) if err != nil { return err } data, err := common.GenOpenAPI(cueInst) if err != nil { re...
{ file, items, _, err := h.Client.Repositories.GetContents(context.Background(), h.Meta.Owner, h.Meta.Repo, path, nil) if err != nil { return nil, nil, WrapErrRateLimit(err) } return file, items, nil }
identifier_body
addon.go
/* Copyright 2021 The KubeVela Authors. 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 writing, softw...
(wg *sync.WaitGroup, reader asyncReader, dirPath []string) { defer wg.Done() content, _, err := reader.h.readRepo(*reader.item.Path) if err != nil { reader.errChan <- err return } b, err := content.GetContent() if err != nil { reader.errChan <- err return } if reader.item.GetName() == "parameter.cue" {...
readResFile
identifier_name
addon.go
/* Copyright 2021 The KubeVela Authors. 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 writing, softw...
return true }
{ err := clt.Get(ctx, client.ObjectKey{ Namespace: types.DefaultKubeVelaNS, Name: Convert2AppName(dep.Name), }, &app) if err != nil { return false } }
conditional_block
addon.go
/* Copyright 2021 The KubeVela Authors. 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 writing, softw...
dirPath, err := cutPathUntil(dirPath, ResourcesDirName) if err != nil { reader.errChan <- err } _, items, err := reader.h.readRepo(*reader.item.Path) if err != nil { reader.errChan <- err return } for _, item := range items { switch item.GetType() { case "file": reader.SetReadContent(item) wg.Ad...
defer wg.Done() dirPath := strings.Split(reader.item.GetPath(), "/")
random_line_split
cryptologer.py
#file should have all ciphers as simple format... just text #for rsa_dec, file should have text as n:<no...> \n c:<no....> e:<no....> #same for rsa_enc... #importing... #import sys #import re import argparse #import operator #import math #import requests #import json #import binascii #import os #import...
elif args.railfence: from enc.railfence_enc import rail ciphertext=rail(plaintext) elif args.rot: from enc.rot import rotate if args.key==None: shift=input("enter shift:") ciphertext=rotate(plaintext,shift) elif args.rot47: from enc.rot47 import rot47 ciphertext=rot47(pl...
from enc.bacon_enc import steak ciphertext=steak(plaintext)
conditional_block
cryptologer.py
#file should have all ciphers as simple format... just text #for rsa_dec, file should have text as n:<no...> \n c:<no....> e:<no....> #same for rsa_enc... #importing... #import sys
#import operator #import math #import requests #import json #import binascii #import os #import time ''' def whereami(): with open('/root/directory.txt','r') as f1: location=f1.read() return location location=whereami()''' #appending file paths ''' import Encrypting as enc import Decrypting as...
#import re import argparse
random_line_split
cryptologer.py
#file should have all ciphers as simple format... just text #for rsa_dec, file should have text as n:<no...> \n c:<no....> e:<no....> #same for rsa_enc... #importing... #import sys #import re import argparse #import operator #import math #import requests #import json #import binascii #import os #import...
(): parser=argparse.ArgumentParser(description="Decryptor for Caeser, Vigenere, types of RSA and more...") parser.add_argument("--decrypt","--dec","-d",help="Performs Decryption",action="store_true") parser.add_argument("--encrypt","--enc","-e",help="Performs Encryption",action="store_true") parser.add_argu...
initializeParser
identifier_name
cryptologer.py
#file should have all ciphers as simple format... just text #for rsa_dec, file should have text as n:<no...> \n c:<no....> e:<no....> #same for rsa_enc... #importing... #import sys #import re import argparse #import operator #import math #import requests #import json #import binascii #import os #import...
def read_chinese(filename): with open(filename,"r") as f3: line=f3.readline() while line: symbol=line[:2].lower() if symbol=='n1': n1=int(line[3:]) elif symbol=='n2': n2=int(line[3:]) elif symbol=='n3': n3=int(line[3:]) elif symbol=='c1': c1=int(line[3:]) elif sym...
with open(filename,"r") as f2: line=f2.readline() e=0 while line: symbol=line[0].lower() if symbol=='n': n=int(line[2:]) elif symbol=='e': e=int(line[2:]) elif symbol=='c': c=line[2:] elif symbol=='m': c=line[2:] else: raise Exception("the contents of the file c...
identifier_body
metadata.rs
// Claxon -- A FLAC decoding library in Rust // Copyright 2014 Ruud van Asseldonk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // A copy of the License has been included in the root of the repository. //! The `metadata` module...
inline] fn size_hint(&self) -> (usize, Option<usize>) { // When done, there will be no more blocks, // when not done, there will be at least one more. if self.done { (0, Some(0)) } else { (1, None) } } }
if self.done { None } else { let block = self.read_next(); // After a failure, no more attempts to read will be made, // because we don't know where we are in the stream. if !block.is_ok() { self.done = true; } ...
identifier_body
metadata.rs
// Claxon -- A FLAC decoding library in Rust // Copyright 2014 Ruud van Asseldonk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // A copy of the License has been included in the root of the repository. //! The `metadata` module...
R) -> MetadataBlockReader<R> { MetadataBlockReader { input: input, done: false, } } #[inline] fn read_next(&mut self) -> MetadataBlockResult { let header = try!(read_metadata_block_header(&mut self.input)); let block = try!(read_metadata_block(&mut se...
t:
identifier_name
metadata.rs
// Claxon -- A FLAC decoding library in Rust // Copyright 2014 Ruud van Asseldonk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // A copy of the License has been included in the root of the repository. //! The `metadata` module...
2 => { let (id, data) = try!(read_application_block(input, length)); Ok(MetadataBlock::Application { id: id, data: data, }) } 3 => { // TODO: implement seektable reading. For now, pretend it is padding. try!(inp...
try!(read_padding_block(input, length)); Ok(MetadataBlock::Padding { length: length }) }
conditional_block
metadata.rs
// Claxon -- A FLAC decoding library in Rust // Copyright 2014 Ruud van Asseldonk // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // A copy of the License has been included in the root of the repository. //! The `metadata` module...
/// The number of padding bytes. length: u32, }, /// An application block with application-specific data. Application { /// The registered application ID. id: u32, /// The contents of the application block. data: Vec<u8>, }, /// A seek table block. ...
pub enum MetadataBlock { /// A stream info block. StreamInfo(StreamInfo), /// A padding block (with no meaningful data). Padding {
random_line_split
test.py
# -*- coding: utf-8 -*- """Training script for the WaveNet network on the VCTK corpus. This script trains a network with the WaveNet using data from the VCTK corpus, which can be freely downloaded at the following site (~10 GB): http://homepages.inf.ed.ac.uk/jyamagis/page3/page58/page58.html """ from __future__ impor...
1x1 conv -> ReLU -> 1x1 conv to # postprocess the output. w1 = post_par[one_params_i]['postprocess1'] w2 = post_par[one_params_i]['postprocess2'] b1 = post_par[one_params_i]['postprocess1_bias'] b2 = post_par[one_params_i]['postprocess2_bias'] ra...
receptive_field-1, 0], [0, 0]]) raw_output = tf.concat([raw_output, raw_output, raw_output, raw_output], axis=1) raw_output = tf.pad(raw_output, [[0, 0], [0, 6]]) raw_output = tf.expand_dims(raw_output, 0) audio_batch = audio_batch - raw_output ...
conditional_block
test.py
# -*- coding: utf-8 -*- """Training script for the WaveNet network on the VCTK corpus. This script trains a network with the WaveNet using data from the VCTK corpus, which can be freely downloaded at the following site (~10 GB): http://homepages.inf.ed.ac.uk/jyamagis/page3/page58/page58.html """ from __future__ impor...
(args): """Validate and arrange directory related arguments.""" # Validation if args.logdir and args.logdir_root: raise ValueError("--logdir and --logdir_root cannot be " "specified at the same time.") if args.logdir and args.restore_from: raise ValueError( ...
validate_directories
identifier_name
test.py
# -*- coding: utf-8 -*- """Training script for the WaveNet network on the VCTK corpus. This script trains a network with the WaveNet using data from the VCTK corpus, which can be freely downloaded at the following site (~10 GB): http://homepages.inf.ed.ac.uk/jyamagis/page3/page58/page58.html """ from __future__ impor...
def save(saver, sess, logdir, step): model_name = 'model.ckpt' checkpoint_path = os.path.join(logdir, model_name) print('Storing checkpoint to {} ...'.format(logdir), end="") sys.stdout.flush() if not os.path.exists(logdir): os.makedirs(logdir) saver.save(sess, checkpoint_path, glob...
def _str_to_bool(s): """Convert string to bool (in argparse context).""" if s.lower() not in ['true', 'false']: raise ValueError('Argument needs to be a ' 'boolean, got {}'.format(s)) return {'true': True, 'false': False}[s.lower()] parser = argparse...
identifier_body
test.py
# -*- coding: utf-8 -*- """Training script for the WaveNet network on the VCTK corpus. This script trains a network with the WaveNet using data from the VCTK corpus, which can be freely downloaded at the following site (~10 GB): http://homepages.inf.ed.ac.uk/jyamagis/page3/page58/page58.html """ from __future__ impor...
elif step < args.num_steps*0.99: muti_step_id = 1 else: muti_step_id = 2 ''' muti_step_id = 1 start_time = time.time() audio_batch_list_ori_v, audio_batch_list_now_v,\ raw_output_list_ori_v, raw_output_l...
if step < args.num_steps*0.0: muti_step_id = 0
random_line_split
orgreminders.go
package orgreminders import ( "appengine" "appengine/datastore" "appengine/mail" "appengine/user" "fmt" "html/template" "log" "net/http" "sort" "strings" "time" ) // App-global variables var Templates *template.Template var Duration_Day = 24 * time.Hour var Duration_Week = 7 * Duration_Day var TemplateFile...
(w http.ResponseWriter, r *http.Request) { c := appengine.NewContext(r) url, _ := user.LogoutURL(c, "/") http.Redirect(w, r, url, http.StatusFound) } func DefaultHandler(w http.ResponseWriter, r *http.Request) { u := UserLookup(w, r) p, _ := NewPage(&u) title := "home" renderTemplate(w, title, p) } func NewOr...
LogoutHandler
identifier_name
orgreminders.go
package orgreminders import ( "appengine" "appengine/datastore" "appengine/mail" "appengine/user" "fmt" "html/template" "log" "net/http" "sort" "strings" "time" ) // App-global variables var Templates *template.Template var Duration_Day = 24 * time.Hour var Duration_Week = 7 * Duration_Day var TemplateFile...
SuperUser bool LoggedIn bool UserEmail string Orgs []string Members map[string]Member SavedEvent bool SavedOrg bool SavedMember bool Member2Edit Member Member2EditKey string ScheduleHTML map[string][]string } func NewPage(u *User) (*Page, error) { var resu...
AllowNewOrg bool
random_line_split
orgreminders.go
package orgreminders import ( "appengine" "appengine/datastore" "appengine/mail" "appengine/user" "fmt" "html/template" "log" "net/http" "sort" "strings" "time" ) // App-global variables var Templates *template.Template var Duration_Day = 24 * time.Hour var Duration_Week = 7 * Duration_Day var TemplateFile...
func MemberEditHandler(w http.ResponseWriter, r *http.Request) { u := UserLookup(w, r) p, _ := NewPage(&u) c := appengine.NewContext(r) var ok bool p.Member2EditKey = r.FormValue("id") ok, p.Member2Edit = GetMemberByKey(c, p.Member2EditKey) // Protect web users if ok && p.Member2Edit.WebUser { if u.Meta.E...
{ u := UserLookup(w, r) p, _ := NewPage(&u) title := "new-member" for _, org := range u.Orgs { p.Orgs = append(p.Orgs, org.Name) } sort.Strings(p.Orgs) renderTemplate(w, title, p) }
identifier_body
orgreminders.go
package orgreminders import ( "appengine" "appengine/datastore" "appengine/mail" "appengine/user" "fmt" "html/template" "log" "net/http" "sort" "strings" "time" ) // App-global variables var Templates *template.Template var Duration_Day = 24 * time.Hour var Duration_Week = 7 * Duration_Day var TemplateFile...
return result }
{ if _, ok := seen[val]; !ok { result = append(result, val) seen[val] = val } }
conditional_block
index.ts
import AWS from 'aws-sdk'; //TODO Dev ClaimState will change, need to update after production app push export type PhotoTuple = [PhotoBuffObj, PhotoBuffObj | false, PhotoBuffObj | false, PhotoBuffObj | false]; export type RiskEntryObj = { uri: string; timeStamp: number; formattedDate: string; description: st...
} export type PhotoBuffObj = { label: string; description: string; formattedDate: string; base64Str: any; } export type SignatureObj = { uri: string; timeStamp: number; formattedDate: string; s3Key: string; } export type Signatures = { nonWaiverInsuredSignature: SignatureObj; nonWaiverAdjusterSig...
random_line_split
jsonast.go
/* * Copyright (c) Microsoft Corporation. * Licensed under the MIT license. */ package jsonast import ( "context" "fmt" "net/url" "regexp" "strings" "k8s.io/klog/v2" "github.com/Azure/k8s-infra/hack/generator/pkg/astmodel" "github.com/devigned/tab" "github.com/xeipuuv/gojsonschema" ) type ( // SchemaT...
(ctx context.Context, schema *gojsonschema.SubSchema, opts ...BuilderOption) ([]astmodel.TypeDefiner, error) { ctx, span := tab.StartSpan(ctx, "GenerateDefinitions") defer span.End() for _, opt := range opts { if err := opt(scanner); err != nil { return nil, err } } // get initial topic from ID and Title:...
GenerateDefinitions
identifier_name