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
licensePlateDetectorOptimized.py
print("\n\nLOADING PROGRAM\n\n") import cv2 as cv print("Loaded CV") import numpy as np print("Loaded NP") import tensorflow as tf print("Loaded TF") import imutils print("Loaded IMUTILS") import os print("Loaded OS") ''' SOME NOTES ABOUT THE PROGRAM: 1) Make sure to change the paths at the top of the file to refle...
model = tf.keras.models.load_model(folder_path + "kerasModelandData/model.h5") #getting the model and loading it ######################################################################################## #################################### GENERAL SETUP ##################################### ###############...
letter_dict = {} #init the letter dictionary to get the letters that are put through the NN
random_line_split
licensePlateDetectorOptimized.py
print("\n\nLOADING PROGRAM\n\n") import cv2 as cv print("Loaded CV") import numpy as np print("Loaded NP") import tensorflow as tf print("Loaded TF") import imutils print("Loaded IMUTILS") import os print("Loaded OS") ''' SOME NOTES ABOUT THE PROGRAM: 1) Make sure to change the paths at the top of the file to refle...
def setup_exec(self): self.settings_init() #initializing all of the settings if optimize: #Currently, optimize makes it so that only the bottom portion of the screen is analyzed self.offset = int(self.img.shape[0] * (self.divideArea - 1) / self.divi...
self.check_wait = check_wait #initializing whether we need to wait between drawing contours for debugging if imgAddress is None and img is not None: #getting the image from the video self.img = img elif imgAddress is not None and img is None: self.img = cv.resize(cv.imread(i...
identifier_body
licensePlateDetectorOptimized.py
print("\n\nLOADING PROGRAM\n\n") import cv2 as cv print("Loaded CV") import numpy as np print("Loaded NP") import tensorflow as tf print("Loaded TF") import imutils print("Loaded IMUTILS") import os print("Loaded OS") ''' SOME NOTES ABOUT THE PROGRAM: 1) Make sure to change the paths at the top of the file to refle...
(self, height = 300): #shows the important images that are being used for execution # cv.imshow("Contours", imutils.resize(self.img_copy, height = height)) cv.imshow("Bounding Rects", self.img_rects) cv.imshow("Canny", imutils.resize(self.Canny, height = height)) self.show_im...
show_images_exec
identifier_name
SelfOrganizingMap.py
#python libraries needed in code import numpy as np import matplotlib.pyplot as plt import matplotlib.pyplot as plt import copy from collections import defaultdict class SelfOrganizingMap: def __init__(self, inputSize, variables, hiddenSize): ############################## # author: Ali Javed ...
(self, iteration, epoch): ############################# # Description: Update the neighborhood size and learning rate # iteration: number of current iteration # epoch: total epochs to run the SOM for ######################################## self.neighborhoodSize = self.ne...
update_parameters
identifier_name
SelfOrganizingMap.py
#python libraries needed in code import numpy as np import matplotlib.pyplot as plt import matplotlib.pyplot as plt import copy from collections import defaultdict class SelfOrganizingMap: def __init__(self, inputSize, variables, hiddenSize): ############################## # author: Ali Javed ...
def dtw_d(self,s1, s2, w): #author: Ali Javed #email: ajaved@uvm.edu #Version 1 . basis implementation of dynaimc time warping dependant. #Version 2 (7 Nov 2019). changed variable names to be more representative and added comments. #INPUTS: #s1: signal 1, size 1 * m * n. where m is the...
dist = ((s1 - s2) ** 2) return dist.flatten().sum()
identifier_body
SelfOrganizingMap.py
#python libraries needed in code import numpy as np import matplotlib.pyplot as plt import matplotlib.pyplot as plt import copy from collections import defaultdict class SelfOrganizingMap: def __init__(self, inputSize, variables, hiddenSize): ############################## # author: Ali Javed ...
# minimum value is winner winnerNeuronIndex = np.argmin(distances) return winnerNeuronIndex def propogateForward(self, x, windowSize): ############ # Description: Function forward propogates from input to grid # x: single input # windowSize: window size ...
for j in range(0, self.hiddenSize[1]): # get weights associated to i-th and j-th node weights = self.weights_Kohonen[i, j, :,:] # make sure correct shape weights = np.reshape(weights, (1, np.shape(weights)[0], np.shape(weights)[1])) # form...
conditional_block
SelfOrganizingMap.py
#python libraries needed in code import numpy as np import matplotlib.pyplot as plt import matplotlib.pyplot as plt import copy from collections import defaultdict class SelfOrganizingMap: def __init__(self, inputSize, variables, hiddenSize): ############################## # author: Ali Javed ...
#find all the neighbors for node at i,j neighbors = self.find_neighbor_indices(i, j) #remove self neighbors.remove((i, j)) #get weights for node at i,j weights = self.weights_Kohonen[i,j,:] weights = np.res...
Umatrix = np.zeros((self.hiddenSize[0],self.hiddenSize[1])) # Perform 2D convolution with input data and kernel to get sum of neighboring nodes for i in range(0,self.hiddenSize[0]): for j in range(0,self.hiddenSize[1]):
random_line_split
train.py
# -*- coding:UTF-8 -*- # ----------------------------------------------------------- # "BCAN++: Cross-modal Retrieval With Bidirectional Correct Attention Network" # Yang Liu, Hong Liu, Huaqiu Wang, Fanyang Meng, Mengyuan Liu* # # --------------------------------------------------------------- """Training script"...
def main(): setup_seed(1024) # Hyper Parameters parser = argparse.ArgumentParser() parser.add_argument('--data_path', default='D:/data/', help='path to datasets') parser.add_argument('--data_name', default='f30k_precomp', help='{coco,f30k}_pre...
f.close()
random_line_split
train.py
# -*- coding:UTF-8 -*- # ----------------------------------------------------------- # "BCAN++: Cross-modal Retrieval With Bidirectional Correct Attention Network" # Yang Liu, Hong Liu, Huaqiu Wang, Fanyang Meng, Mengyuan Liu* # # --------------------------------------------------------------- """Training script"...
te the encoding for all the validation images and captions img_embs, img_means, cap_embs, cap_lens, cap_means = encode_data( model, val_loader, opt.log_step, logging.info) print(img_embs.shape, cap_embs.shape) img_embs = numpy.array([img_embs[i] for i in range(0, len(img_embs), 5)]) sta...
# compu
identifier_name
train.py
# -*- coding:UTF-8 -*- # ----------------------------------------------------------- # "BCAN++: Cross-modal Retrieval With Bidirectional Correct Attention Network" # Yang Liu, Hong Liu, Huaqiu Wang, Fanyang Meng, Mengyuan Liu* # # --------------------------------------------------------------- """Training script"...
if (i + 1) % opt.log_step == 0: run_time += time.time() - start_time log = "epoch: %d; batch: %d/%d; loss: %.6f; time: %.4f" % (epoch, i, len(train_loader), loss.data.item(), ...
t.grad_clip) optimizer.step()
conditional_block
train.py
# -*- coding:UTF-8 -*- # ----------------------------------------------------------- # "BCAN++: Cross-modal Retrieval With Bidirectional Correct Attention Network" # Yang Liu, Hong Liu, Huaqiu Wang, Fanyang Meng, Mengyuan Liu* # # --------------------------------------------------------------- """Training script"...
main()
ecified values of k""" maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].view(-1).float().sum(0) res.append...
identifier_body
android_bootldr_qcom.go
// Code generated by kaitai-struct-compiler from a .ksy source file. DO NOT EDIT. import ( "github.com/kaitai-io/kaitai_struct_go_runtime/kaitai" "bytes" "io" ) /** * A bootloader for Android used on various devices powered by Qualcomm * Snapdragon chips: * * <https://en.wikipedia.org/wiki/Devices_using_Qual...
func (this *AndroidBootldrQcom) Read(io *kaitai.Stream, parent interface{}, root *AndroidBootldrQcom) (err error) { this._io = io this._parent = parent this._root = root tmp1, err := this._io.ReadBytes(int(8)) if err != nil { return err } tmp1 = tmp1 this.Magic = tmp1 if !(bytes.Equal(this.Magic, []uint8{...
{ return &AndroidBootldrQcom{ } }
identifier_body
android_bootldr_qcom.go
// Code generated by kaitai-struct-compiler from a .ksy source file. DO NOT EDIT. import ( "github.com/kaitai-io/kaitai_struct_go_runtime/kaitai" "bytes" "io" ) /** * A bootloader for Android used on various devices powered by Qualcomm * Snapdragon chips: * * <https://en.wikipedia.org/wiki/Devices_using_Qual...
* The `bootloader-*.img` samples referenced above originally come from factory * images packed in ZIP archives that can be found on the page [Factory Images * for Nexus and Pixel Devices](https://developers.google.com/android/images) on * the Google Developers site. Note that the codenames on that page may be * di...
random_line_split
android_bootldr_qcom.go
// Code generated by kaitai-struct-compiler from a .ksy source file. DO NOT EDIT. import ( "github.com/kaitai-io/kaitai_struct_go_runtime/kaitai" "bytes" "io" ) /** * A bootloader for Android used on various devices powered by Qualcomm * Snapdragon chips: * * <https://en.wikipedia.org/wiki/Devices_using_Qual...
(io *kaitai.Stream, parent interface{}, root *AndroidBootldrQcom) (err error) { this._io = io this._parent = parent this._root = root tmp1, err := this._io.ReadBytes(int(8)) if err != nil { return err } tmp1 = tmp1 this.Magic = tmp1 if !(bytes.Equal(this.Magic, []uint8{66, 79, 79, 84, 76, 68, 82, 33})) { ...
Read
identifier_name
android_bootldr_qcom.go
// Code generated by kaitai-struct-compiler from a .ksy source file. DO NOT EDIT. import ( "github.com/kaitai-io/kaitai_struct_go_runtime/kaitai" "bytes" "io" ) /** * A bootloader for Android used on various devices powered by Qualcomm * Snapdragon chips: * * <https://en.wikipedia.org/wiki/Devices_using_Qual...
this.BootloaderSize = uint32(tmp4) for i := 0; i < int(this.NumImages); i++ { _ = i tmp5 := NewAndroidBootldrQcom_ImgHeader() err = tmp5.Read(this._io, this, this._root) if err != nil { return err } this.ImgHeaders = append(this.ImgHeaders, tmp5) } return err } func (this *AndroidBootldrQcom) ImgBod...
{ return err }
conditional_block
username.go
package people import ( "fmt" "math/rand" ) // Select a random word and append some numbers to it to make something username-looking. func Username() string { word := Words[rand.Int31n(int32(len(Words)))] digits := rand.Int31n(1000) return fmt.Sprintf("%s%d", word, digits) } var Words = []string{ "acquirable",...
"cruisers", "psychoanalyst", "registrations", "agnostics", "ambivalently", "punishable", "philosophically", "storages", "wistful", "loveland", "preferential", "armchairs", "washington", "accretions", "interchangeable", "ambitions", "hostesss", "heading", "crucifies", "venturesome", "mullion", "fue...
random_line_split
username.go
package people import ( "fmt" "math/rand" ) // Select a random word and append some numbers to it to make something username-looking. func Username() string
var Words = []string{ "acquirable", "bestsellers", "farther", "prizer", "shasta", "evaporate", "auspices", "garments", "partnership", "blocs", "forestalling", "razors", "extensibility", "unavoidably", "logician", "embroidered", "crippling", "supranational", "milton", "healthily", "spiraling", "c...
{ word := Words[rand.Int31n(int32(len(Words)))] digits := rand.Int31n(1000) return fmt.Sprintf("%s%d", word, digits) }
identifier_body
username.go
package people import ( "fmt" "math/rand" ) // Select a random word and append some numbers to it to make something username-looking. func
() string { word := Words[rand.Int31n(int32(len(Words)))] digits := rand.Int31n(1000) return fmt.Sprintf("%s%d", word, digits) } var Words = []string{ "acquirable", "bestsellers", "farther", "prizer", "shasta", "evaporate", "auspices", "garments", "partnership", "blocs", "forestalling", "razors", "exte...
Username
identifier_name
lib.rs
#![deny(missing_docs)] //! An append-only, on-disk key-value index with lockless reads use std::cell::UnsafeCell; use std::fs::OpenOptions; use std::hash::{Hash, Hasher}; use std::io; use std::marker::PhantomData; use std::mem; use std::ops::{Deref, DerefMut}; use std::path::{Path, PathBuf}; use arrayvec::ArrayVec; u...
// Get a mutable reference to the `Entry`, // locking the corresponding shard. fn entry_mut( &self, lane: usize, page: usize, slot: usize, ) -> EntryMut<K, V> { let shard = (page ^ slot) % NUM_SHARDS; // Lock the entry for writing let lock = SHAR...
{ // Get a reference to the `Entry` let page_ofs = PAGE_SIZE * page; let slot_ofs = page_ofs + slot * mem::size_of::<Entry<K, V>>(); unsafe { mem::transmute( (*self.lanes.get())[lane].as_ptr().offset(slot_ofs as isize), ) } }
identifier_body
lib.rs
#![deny(missing_docs)] //! An append-only, on-disk key-value index with lockless reads use std::cell::UnsafeCell; use std::fs::OpenOptions; use std::hash::{Hash, Hasher}; use std::io; use std::marker::PhantomData; use std::mem; use std::ops::{Deref, DerefMut}; use std::path::{Path, PathBuf}; use arrayvec::ArrayVec; u...
pages: Mutex::new(num_pages as u64), _marker: PhantomData, }; // initialize index with at least one page if num_pages == 0 { assert_eq!(index.new_page()?, 0); } Ok(index) } /// Returns how many pages have been allocated so far pub...
// create the index let index = Index { lanes: UnsafeCell::new(lanes), path: PathBuf::from(path.as_ref()),
random_line_split
lib.rs
#![deny(missing_docs)] //! An append-only, on-disk key-value index with lockless reads use std::cell::UnsafeCell; use std::fs::OpenOptions; use std::hash::{Hash, Hasher}; use std::io; use std::marker::PhantomData; use std::mem; use std::ops::{Deref, DerefMut}; use std::path::{Path, PathBuf}; use arrayvec::ArrayVec; u...
(&self) -> &Self::Target { &self.entry } } impl<'a, K, V> DerefMut for EntryMut<'a, K, V> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.entry } } impl<K: Hash, V: Hash> Entry<K, V> { fn new(key: K, val: V) -> Self { let kv_checksum = hash_val(&key).wrapping_add(has...
deref
identifier_name
blockchain.py
from flask import Flask, request, jsonify, render_template, redirect, session, g, url_for from time import time, ctime from flask_cors import CORS from collections import OrderedDict import binascii from Crypto.PublicKey import RSA from Crypto.Signature import PKCS1_v1_5 from Crypto.Hash import SHA from uuid import uui...
(): values = request.form # 127.0.0.1:5002,127.0.0.1:5003, 127.0.0.1:5004 nodes = values.get('nodes').replace(' ', '').split(',') if nodes is None: return 'Error: Please supply a valid list of nodes', 400 for node in nodes: blockchain.register_node(node) response = { '...
register_node
identifier_name
blockchain.py
from flask import Flask, request, jsonify, render_template, redirect, session, g, url_for from time import time, ctime from flask_cors import CORS from collections import OrderedDict import binascii from Crypto.PublicKey import RSA from Crypto.Signature import PKCS1_v1_5 from Crypto.Hash import SHA from uuid import uui...
@app.route('/logout') def logout(): # remove the username from the session if it is there session.pop('miner_email', None) return redirect('/login') @app.route('/profile') def profile(): if not g.user: return redirect('/login') return render_template('profile.html') # @app.route('/register...
if request.method == 'POST': name = request.form.get('minerName') email = request.form.get('minerEmail') password = request.form.get('minerPass') minerdata = {'name':name, "email":email, "password":password} minerdb.insert_one(minerdata) return redirect('/login') r...
identifier_body
blockchain.py
from flask import Flask, request, jsonify, render_template, redirect, session, g, url_for from time import time, ctime from flask_cors import CORS from collections import OrderedDict import binascii from Crypto.PublicKey import RSA from Crypto.Signature import PKCS1_v1_5 from Crypto.Hash import SHA from uuid import uui...
# user = minerdb.find_one( { "email": email, "password" : password}) # if user: # return redirect('/') # else: # return redirect('/login') # return 'Miner email is {} and password is {}'.format(email, password) @app.route('/configure') def configure(): return render_template('./c...
random_line_split
blockchain.py
from flask import Flask, request, jsonify, render_template, redirect, session, g, url_for from time import time, ctime from flask_cors import CORS from collections import OrderedDict import binascii from Crypto.PublicKey import RSA from Crypto.Signature import PKCS1_v1_5 from Crypto.Hash import SHA from uuid import uui...
response = { 'message': 'Nodes have been added', 'total_nodes': [node for node in blockchain.nodes] } return jsonify(response), 200 if __name__ == '__main__': from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument('-p', '--port', default=5001, type...
blockchain.register_node(node)
conditional_block
HaarROG.py
#========================================================================== #Уже подсчитанные характеристики для 1000 тестовых изображений ''' haarPath = "cascade30h.xml" recallList [0.8254189944134078, 0.8225352112676056, 0.8208744710860366, 0.8045325779036827, 0.7897727272727273, 0.7795163584637269, 0.76...
DetectData = [] else: for i in range(len(numPlates)): bufData = [numPlates[i][0], numPlates[i][1], numPlates[i][0] + numPlates[i][2], numPlates[i][1] + numPlates[i][3]] localDetectData.append(bufData) return localDetectData #====================================================...
0: local
identifier_name
HaarROG.py
#========================================================================== #Уже подсчитанные характеристики для 1000 тестовых изображений ''' haarPath = "cascade30h.xml" recallList [0.8254189944134078, 0.8225352112676056, 0.8208744710860366, 0.8045325779036827, 0.7897727272727273, 0.7795163584637269, 0.76...
04, 0.7265135699373695, 0.7405541561712846, 0.6653771760154739, 0.7546666666666667, 0.7719869706840391] ax.plot(recallList, precisionList, 's', color='blue') recallList = [0.8129395218002813, 0.8095909732016925, 0.8053596614950634, 0.7926657263751763, 0.7776203966005666, 0.7585227272727...
istics: # положительные характеристики tp = 0 tn = 0 # отрицательные характеристики fp = 0 fn = 0 rateCh = Characteristics() # border для определения, правильно найден номер или не правильно # для площади пересечения номерных рамок lowerBorder = 0.7 ...
identifier_body
HaarROG.py
#========================================================================== #Уже подсчитанные характеристики для 1000 тестовых изображений ''' haarPath = "cascade30h.xml" recallList [0.8254189944134078, 0.8225352112676056, 0.8208744710860366, 0.8045325779036827, 0.7897727272727273, 0.7795163584637269, 0.76...
nt('ERROR: dataPath \n') sys.exit() # ----------------------------------------------------------------------- # тестирование class Characteristics: # положительные характеристики tp = 0 tn = 0 # отрицательные характеристики fp = 0 fn = 0 rateCh ...
with open(dataPath, "r") as read_file: testData = json.load(read_file) # создаем список ключей в словаре keys = list(testData.keys()) except: pri
conditional_block
HaarROG.py
#========================================================================== #Уже подсчитанные характеристики для 1000 тестовых изображений ''' haarPath = "cascade30h.xml" recallList [0.8254189944134078, 0.8225352112676056, 0.8208744710860366, 0.8045325779036827, 0.7897727272727273, 0.7795163584637269, 0.76...
#print('LL') #print(detectList) #print('MNPL') #print(markedNumPlatesList) #x1 < x2 #упорядочили по x if detectList[i][0] < detectList[i][2]: x1 = detectList[i][0] x2 = detectList[i][2] else...
]
random_line_split
transcation.go
package trx import ( "crypto/ecdsa" "encoding/json" "fmt" "math/big" "time" "tron/api" "tron/common/base58" "tron/common/hexutil" "tron/core" "tron/log" "tron/service" wallet "tron/util" "github.com/ethereum/go-ethereum/common" "github.com/golang/protobuf/proto" "github.com/shopspri...
:= common.LeftPadBytes(add[1:], 32) data = append(data, methodID...) data = append(data, paddedAddress...) return } func processTransaction(node *service.GrpcClient, contract, txid, from, to string, blockheight, amount int64) { // 合约是否存在 if !IsContract(contract) { return } // fmt.Printf("contract...
ring) (data []byte) { methodID, _ := hexutil.Decode("70a08231") add, _ := base58.DecodeCheck(addr) paddedAddress
identifier_body
transcation.go
package trx import ( "crypto/ecdsa" "encoding/json" "fmt" "math/big" "time" "tron/api" "tron/common/base58" "tron/common/hexutil" "tron/core" "tron/log" "tron/service" wallet "tron/util" "github.com/ethereum/go-ethereum/common" "github.com/golang/protobuf/proto" "github.com/shopspri...
node = getRandOneNode() block, err := node.GetBlockByLimitNext(start, end) if err != nil { // rpc error: code = DeadlineExceeded desc = context deadline exceeded will get again log.Warnf("node get bolck start %d end %d GetBlockByLimitNext err: %v will get again", start, end, err) time.Sleep(time.Second * ...
random_line_split
transcation.go
package trx import ( "crypto/ecdsa" "encoding/json" "fmt" "math/big" "time" "tron/api" "tron/common/base58" "tron/common/hexutil" "tron/core" "tron/log" "tron/service" wallet "tron/util" "github.com/ethereum/go-ethereum/common" "github.com/golang/protobuf/proto" "github.com/shopspri...
xID: txid, Contract: contract, Type: types, BlockHeight: blockheight, Amount: decimal.New(amount, -decimalnum).String(), Fee: decimal.New(fee, -trxdecimal).String(), Timestamp: time.Now().Unix(), Address: to, FromAddress: from, } _, err = dbengine.Insert...
um := chargeContract(contract) var trans = &Transactions{ T
conditional_block
transcation.go
package trx import ( "crypto/ecdsa" "encoding/json" "fmt" "math/big" "time" "tron/api" "tron/common/base58" "tron/common/hexutil" "tron/core" "tron/log" "tron/service" wallet "tron/util" "github.com/ethereum/go-ethereum/common" "github.com/golang/protobuf/proto" "github.com/shopspri...
i.BlockExtention) { height := block.GetBlockHeader().GetRawData().GetNumber() node := getRandOneNode() defer node.Conn.Close() for _, v := range block.Transactions { // transaction.ret.contractRe txid := hexutil.Encode(v.Txid) // https://tronscan.org/#/transaction/fede1aa9e5c5d7bd179fd62e23bdd11e3c1edd...
ck(block *ap
identifier_name
fmt.rs
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. //! This module provides file formatting utilities using //! [`dprint-plugin-typescript`](https://github.com/dprint/dprint-plugin-typescript). //! //! At the moment it is only consumed using CLI but in //! the future it can be easily extended t...
() -> dprint_plugin_json::configuration::Configuration { dprint_plugin_json::configuration::ConfigurationBuilder::new() .deno() .build() } struct FileContents { text: String, had_bom: bool, } fn read_file_contents(file_path: &Path) -> Result<FileContents, AnyError> { let file_bytes = fs::read(&file_pa...
get_json_config
identifier_name
fmt.rs
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. //! This module provides file formatting utilities using //! [`dprint-plugin-typescript`](https://github.com/dprint/dprint-plugin-typescript). //! //! At the moment it is only consumed using CLI but in //! the future it can be easily extended t...
} Ok(()) } fn files_str(len: usize) -> &'static str { if len <= 1 { "file" } else { "files" } } fn get_typescript_config( ) -> dprint_plugin_typescript::configuration::Configuration { dprint_plugin_typescript::configuration::ConfigurationBuilder::new() .deno() .build() } fn get_markdown_...
{ return Err(generic_error(e)); }
conditional_block
fmt.rs
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. //! This module provides file formatting utilities using //! [`dprint-plugin-typescript`](https://github.com/dprint/dprint-plugin-typescript). //! //! At the moment it is only consumed using CLI but in //! the future it can be easily extended t...
/// Formats markdown (using https://github.com/dprint/dprint-plugin-markdown) and its code blocks /// (ts/tsx, js/jsx). fn format_markdown( file_text: &str, ts_config: dprint_plugin_typescript::configuration::Configuration, ) -> Result<String, String> { let md_config = get_markdown_config(); dprint_plugin_markd...
Ok(()) }
random_line_split
fmt.rs
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license. //! This module provides file formatting utilities using //! [`dprint-plugin-typescript`](https://github.com/dprint/dprint-plugin-typescript). //! //! At the moment it is only consumed using CLI but in //! the future it can be easily extended t...
fn write_file_contents( file_path: &Path, file_contents: FileContents, ) -> Result<(), AnyError> { let file_text = if file_contents.had_bom { // add back the BOM format!("{}{}", BOM_CHAR, file_contents.text) } else { file_contents.text }; Ok(fs::write(file_path, file_text)?) } pub async fn r...
{ let file_bytes = fs::read(&file_path)?; let charset = text_encoding::detect_charset(&file_bytes); let file_text = text_encoding::convert_to_utf8(&file_bytes, charset)?; let had_bom = file_text.starts_with(BOM_CHAR); let text = if had_bom { // remove the BOM String::from(&file_text[BOM_CHAR.len_utf8(...
identifier_body
publish.go
package publish import ( "context" "errors" "fmt" "io" "io/ioutil" "os" "path" "path/filepath" "strings" "github.com/google/uuid" "github.com/mholt/archiver/v3" "github.com/opencontainers/go-digest" "github.com/openshift/library-go/pkg/image/reference" "github.com/openshift/library-go/pkg/image/registry...
(ctx context.Context, cmd *cobra.Command, f kcmdutil.Factory) error { logrus.Infof("Publishing image set from archive %q to registry %q", o.ArchivePath, o.ToMirror) var currentMeta v1alpha1.Metadata var incomingMeta v1alpha1.Metadata a := archive.NewArchiver() // Create workspace tmpdir, err := ioutil.TempDir(...
Run
identifier_name
publish.go
package publish import ( "context" "errors" "fmt" "io" "io/ioutil" "os" "path" "path/filepath" "strings" "github.com/google/uuid" "github.com/mholt/archiver/v3" "github.com/opencontainers/go-digest" "github.com/openshift/library-go/pkg/image/reference" "github.com/openshift/library-go/pkg/image/registry...
func (o *Options) Run(ctx context.Context, cmd *cobra.Command, f kcmdutil.Factory) error { logrus.Infof("Publishing image set from archive %q to registry %q", o.ArchivePath, o.ToMirror) var currentMeta v1alpha1.Metadata var incomingMeta v1alpha1.Metadata a := archive.NewArchiver() // Create workspace tmpdir,...
{ return fmt.Sprintf("Bundle Sequence out of order. Current sequence %v, incoming sequence %v", s.CurrSeq, s.inSeq) }
identifier_body
publish.go
package publish import ( "context" "errors" "fmt" "io" "io/ioutil" "os" "path" "path/filepath" "strings" "github.com/google/uuid" "github.com/mholt/archiver/v3" "github.com/opencontainers/go-digest" "github.com/openshift/library-go/pkg/image/reference" "github.com/openshift/library-go/pkg/image/registry...
if err := genOpts.Run(); err != nil { return fmt.Errorf("error running generic image mirror: %v", err) } } for _, m := range releaseMappings { logrus.Debugf("mirroring release image: %s", m.Source.String()) relOpts := release.NewMirrorOptions(o.IOStreams) relOpts.From = m.Source.String() relOpts.From...
{ return fmt.Errorf("invalid image mirror options: %v", err) }
conditional_block
publish.go
package publish import ( "context" "errors" "fmt" "io" "io/ioutil" "os" "path" "path/filepath" "strings" "github.com/google/uuid" "github.com/mholt/archiver/v3" "github.com/opencontainers/go-digest" "github.com/openshift/library-go/pkg/image/reference" "github.com/openshift/library-go/pkg/image/registry...
// install imagecontentsourcepolicy logrus.Info("ICSP creation not implemented") // install catalogsource logrus.Info("CatalogSource creation not implemented") // Replace old metadata with new metadata if err := backend.WriteMetadata(ctx, &incomingMeta, config.MetadataBasePath); err != nil { return err } r...
} if err := os.Chdir(wd); err != nil { return err }
random_line_split
tree_dir.py
#!/usr/bin/env python3 ''' @File : tree_dir.py @Time : 2018/12/26 13:39:13 @Author : yangshifu @Version : 1.0 @Contact : yangshifu@sensetime.com @Desc : None ''' import os import math import warnings import numpy as np import tkinter as tk from tkinter import * from tkinter import ttk from idlelib...
box_scroll[3] = self.box_img_int[3] # Convert scroll region to tuple and to integer self.canvas_image.configure(scrollregion=tuple(map(int, box_scroll))) # set scroll region x1 = max(box_canvas[0] - box_image[0], 0) # get coordinates (x1,y1,x2,y2) of the image tile y1 = ma...
# Vertical part of the image is in the visible area if box_scroll[1] == box_canvas[1] and box_scroll[3] == box_canvas[3]: box_scroll[1] = self.box_img_int[1]
random_line_split
tree_dir.py
#!/usr/bin/env python3 ''' @File : tree_dir.py @Time : 2018/12/26 13:39:13 @Author : yangshifu @Version : 1.0 @Contact : yangshifu@sensetime.com @Desc : None ''' import os import math import warnings import numpy as np import tkinter as tk from tkinter import * from tkinter import ttk from idlelib...
file_list = self.get_path_list() print(file_list) if not file_list: return # merge image # 修复内存泄露的bug,由于没有清除之前打开的图片,第二次打开的图片仍然为之前的图片 try: self.photos.destroy() except: pass self.photos.imgs = file_list merged_photo = s...
"""
identifier_name
tree_dir.py
#!/usr/bin/env python3 ''' @File : tree_dir.py @Time : 2018/12/26 13:39:13 @Author : yangshifu @Version : 1.0 @Contact : yangshifu@sensetime.com @Desc : None ''' import os import math import warnings import numpy as np import tkinter as tk from tkinter import * from tkinter import ttk from idlelib...
dit) self.label.bind("<Double-1>", self.flip) self.label.bind("<Control-1>", self.select_more) self.label.bind("<3>", self.execute_file) self.text_id = id class AutoScrollbar(ttk.Scrollbar): """ A scrollbar that hides itself if it's not needed. Works only for grid geometry manager ...
=self.label) self.label.bind("<1>", self.select_or_e
conditional_block
tree_dir.py
#!/usr/bin/env python3 ''' @File : tree_dir.py @Time : 2018/12/26 13:39:13 @Author : yangshifu @Version : 1.0 @Contact : yangshifu@sensetime.com @Desc : None ''' import os import math import warnings import numpy as np import tkinter as tk from tkinter import * from tkinter import ttk from idlelib...
f.get_screen_size(self.master) self.center_window(self.screen_width-50, self.screen_height-50) self.master.resizable(width=False, height=False) self.build_tree_canvas() self.build_tree() self.build_img_canvas() def build_tree_canvas(self): # create frame self...
self.grid_remove() else: self.grid() ttk.Scrollbar.set(self, lo, hi) def pack(self, **kw): raise tk.TclError('Cannot use pack with the widget ' + self.__class__.__name__) def place(self, **kw): raise tk.TclError('Cannot use place with the widget ' + ...
identifier_body
global_stats.rs
use ahash::HashMapExt; use categories::CATEGORIES; use categories::Category; use categories::CategoryMap; use chrono::prelude::*; use futures::future::try_join; use crate::Page; use crate::templates; use crate::Urler; use kitchen_sink::CompatByCrateVersion; use kitchen_sink::KitchenSink; use kitchen_sink::Origin; use l...
, pub title: String, pub label: String, pub font_size: f64, /// SVG fill pub color: String, pub count: u32, pub weight: f64, pub bounds: treemap::Rect, pub sub: Vec<TreeBox>, } impl TreeBox { pub fn line_y(&self, nth: usize) -> f64 { self.bounds.y + 1. + self.font_size *...
ategory
identifier_name
global_stats.rs
use ahash::HashMapExt; use categories::CATEGORIES; use categories::Category; use categories::CategoryMap; use chrono::prelude::*; use futures::future::try_join; use crate::Page; use crate::templates; use crate::Urler; use kitchen_sink::CompatByCrateVersion; use kitchen_sink::KitchenSink; use kitchen_sink::Origin; use l...
cat("database-implementations", &mut roots).label = "Database".into(); get_cat("simulation", &mut roots).label = "Sim".into(); get_cat("caching", &mut roots).label = "Cache".into(); get_cat("config", &mut roots).label = "Config".into(); get_cat("os", &mut roots).label = "OS".into(); get_cat("interna...
at: CATEGORIES.root.values().next().unwrap(), title: String::new(), label: String::new(), font_size: 0., color: String::new(), count: 0, weight: 0., bounds: Rect::new(), sub, } } // names don't fit get_
identifier_body
global_stats.rs
use ahash::HashMapExt; use categories::CATEGORIES; use categories::Category; use categories::CategoryMap; use chrono::prelude::*; use futures::future::try_join; use crate::Page; use crate::templates; use crate::Urler; use kitchen_sink::CompatByCrateVersion; use kitchen_sink::KitchenSink; use kitchen_sink::Origin; use l...
} postprocess_treebox_items(&mut items_flattened); Ok(items_flattened) } fn postprocess_treebox_items(items: &mut Vec<TreeBox>) { let colors = [ [0xff, 0xf1, 0xe6], [0xe2, 0xec, 0xe9], [0xDC, 0xED, 0xC1], [0xcd, 0xda, 0xfd], [0xbe, 0xe1, 0xe6], [0xfd, 0...
items_flattened.append(&mut parent.sub);
random_line_split
global_stats.rs
use ahash::HashMapExt; use categories::CATEGORIES; use categories::Category; use categories::CategoryMap; use chrono::prelude::*; use futures::future::try_join; use crate::Page; use crate::templates; use crate::Urler; use kitchen_sink::CompatByCrateVersion; use kitchen_sink::KitchenSink; use kitchen_sink::Origin; use l...
let hs_deps2 = Histogram { max: hs_deps1.max, buckets: hs_deps1.buckets.split_off(10), bucket_labels: hs_deps1.bucket_labels.split_off(10), }; let rev_deps = kitchen_sink.crates_io_all_rev_deps_counts().await?; let mut hs_rev_deps = Histogram::new(rev_deps, true, &[0,1,2...
to_string()});
conditional_block
worker.go
/* http://www.apache.org/licenses/LICENSE-2.0.txt Copyright 2015 Intel Corporation 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 ...
type worker struct { pluginManager ManagesPlugins memberManager getsMembers taskManager ManagesTasks id int pluginWork chan PluginRequest taskWork chan TaskRequest quitChan chan struct{} waitGroup *sync.WaitGroup logger *log.Entry } func DispatchWorkers(nworkers int, plu...
{ logger := log.WithFields(log.Fields{ "_module": "worker", "worker-id": id, }) worker := worker{ pluginManager: pm, taskManager: tm, memberManager: mm, id: id, pluginWork: pluginQueue, taskWork: taskQueue, waitGroup: wg, quitChan: quitChan, logger: logger...
identifier_body
worker.go
/* http://www.apache.org/licenses/LICENSE-2.0.txt Copyright 2015 Intel Corporation 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 ...
_, err = w.pluginManager.Load(rp) if err != nil { logger.Error(err) return err } if w.isPluginLoaded(plugin.Name(), plugin.TypeName(), plugin.Version()) { return nil } return errors.New("failed to load plugin") } return errors.New("failed to find a member with the plugin") } func (w worker) dow...
{ logger.Error(err) return err }
conditional_block
worker.go
/* http://www.apache.org/licenses/LICENSE-2.0.txt Copyright 2015 Intel Corporation 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 ...
(s *core.Schedule) schedule.Schedule { logger := log.WithFields(log.Fields{ "_block": "get-schedule", "schedule-type": s.Type, }) switch s.Type { case "simple", "windowed": if s.Interval == "" { logger.Error(core.ErrMissingScheduleInterval) return nil } d, err := time.ParseDuration(s.Interval...
getSchedule
identifier_name
worker.go
/* http://www.apache.org/licenses/LICENSE-2.0.txt Copyright 2015 Intel Corporation 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 ...
GetAddr() net.IP GetRestPort() string GetRestProto() string GetRestInsecureSkipVerify() bool GetName() string } // newPluginWorker func newWorker(id int, pluginQueue chan PluginRequest, taskQueue chan TaskRequest, quitChan chan struct{}, wg *sync.WaitGroup, pm ManagesPlugins, tm ManagesTasks, mm getsMember...
random_line_split
selection_test.go
/* Copyright SecureKey Technologies Inc. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package client import ( "encoding/json" "fmt" "io/ioutil" "os" "testing" "github.com/golang/protobuf/proto" "github.com/hyperledger/fabric-sdk-go/api/apifabclient" "github.com/hyperledger/fabric-sdk-go/api/a...
return newCCData(&common.SignaturePolicyEnvelope{ Version: 0, Rule: pgresolver.NewNOutOfPolicy(1, pgresolver.NewNOutOfPolicy(2, signedBy[o1], signedBy[o2], ), pgresolver.NewNOutOfPolicy(2, signedBy[o1], signedBy[o3], signedBy[o4], ), ), Identities: identities, }) } // Policy...
{ panic(err) }
conditional_block
selection_test.go
/* Copyright SecureKey Technologies Inc. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package client import ( "encoding/json" "fmt" "io/ioutil" "os" "testing" "github.com/golang/protobuf/proto" "github.com/hyperledger/fabric-sdk-go/api/apifabclient" "github.com/hyperledger/fabric-sdk-go/api/a...
func (m *mockMembershipManager) add(channelID string, peers ...api.ChannelPeer) *mockMembershipManager { m.peerConfigs[channelID] = []api.ChannelPeer(peers) return m } type mockCCDataProvider struct { ccData map[string]*ccprovider.ChaincodeData } func newMockCCDataProvider() *mockCCDataProvider { return &mockCC...
{ return &mockMembershipManager{peerConfigs: make(map[string][]api.ChannelPeer)} }
identifier_body
selection_test.go
/* Copyright SecureKey Technologies Inc. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package client import ( "encoding/json" "fmt" "io/ioutil" "os" "testing" "github.com/golang/protobuf/proto" "github.com/hyperledger/fabric-sdk-go/api/apifabclient" "github.com/hyperledger/fabric-sdk-go/api/a...
add(channel1, cc1, getPolicy1()), pgresolver.NewRoundRobinLBP()) // Channel1(Policy(cc1)) = Org1 expected := []api.PeerGroup{ // Org1 pg(p1), pg(p2), } verify(t, service, expected, channel1, cc1) } func TestGetEndorsersForChaincodeTwoCCs(t *testing.T) { service := newMockSelectionService( newMockMembe...
newMockMembershipManager(). add(channel1, p1, p2, p3, p4, p5, p6, p7, p8), newMockCCDataProvider().
random_line_split
selection_test.go
/* Copyright SecureKey Technologies Inc. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package client import ( "encoding/json" "fmt" "io/ioutil" "os" "testing" "github.com/golang/protobuf/proto" "github.com/hyperledger/fabric-sdk-go/api/apifabclient" "github.com/hyperledger/fabric-sdk-go/api/a...
(t *testing.T, service api.SelectionService, expectedPeerGroups []api.PeerGroup, channelID string, chaincodeIDs ...string) { // Set the log level to WARNING since the following spits out too much info in DEBUG module := "pg-resolver" level := logging.GetLevel(module) logging.SetLevel(module, apilogging.WARNING) de...
verify
identifier_name
mod.rs
mod field_names_encoder; use self::field_names_encoder::FieldNamesEncoder; use csv::{self, Result}; use rustc_serialize::Encodable; use std::fs::File; use std::io::{BufWriter, Write}; use std::marker::PhantomData; use std::path::Path; /// A CSV writer that automatically writes the headers. /// /// This writer provid...
// Write row. let mut erecord = csv::Encoded::new(); row.encode(&mut erecord)?; self.csv.write(erecord.unwrap().into_iter()) } /// Flushes the underlying buffer. pub fn flush(&mut self) -> Result<()> { self.csv.flush() } } #[cfg(test)] mod tests { use super...
{ let mut field_names_encoder = FieldNamesEncoder::new(); row.encode(&mut field_names_encoder)?; self.csv.write(field_names_encoder.into_field_names().into_iter())?; self.first_row = false; }
conditional_block
mod.rs
mod field_names_encoder; use self::field_names_encoder::FieldNamesEncoder; use csv::{self, Result}; use rustc_serialize::Encodable; use std::fs::File; use std::io::{BufWriter, Write}; use std::marker::PhantomData; use std::path::Path; /// A CSV writer that automatically writes the headers. /// /// This writer provid...
() { let mut w = Writer::from_memory(); let s1 = SimpleStruct { a: 0, b: 1 }; w.encode(s1).unwrap(); let s2 = SimpleStruct { a: 3, b: 4 }; w.encode(s2).unwrap(); assert_eq!(w.as_string(), "a,b\n0,1\n3,4\n"); } #[test] fn test_tuple_of_structs() { let ...
test_struct
identifier_name
mod.rs
mod field_names_encoder; use self::field_names_encoder::FieldNamesEncoder; use csv::{self, Result}; use rustc_serialize::Encodable; use std::fs::File; use std::io::{BufWriter, Write}; use std::marker::PhantomData; use std::path::Path; /// A CSV writer that automatically writes the headers. /// /// This writer provid...
/// ), /// ( /// Part1 { count: Count(9), animal: "platypus" }, /// Part2 { group: Group::Mammal, description: None }, /// ), /// ]; /// /// let mut wtr = typed_csv::Writer::from_memory(); /// for record in records.into_iter() { /// wtr.encode(reco...
random_line_split
mod.rs
mod field_names_encoder; use self::field_names_encoder::FieldNamesEncoder; use csv::{self, Result}; use rustc_serialize::Encodable; use std::fs::File; use std::io::{BufWriter, Write}; use std::marker::PhantomData; use std::path::Path; /// A CSV writer that automatically writes the headers. /// /// This writer provid...
} impl<W: Write, E: Encodable> Writer<W, E> { /// Writes a record by encoding any `Encodable` value. /// /// When the first record is encoded, the headers (the field names in the /// struct) are written prior to encoding the record. /// /// The type that is being encoded into should correspond...
{ self.csv.into_bytes() }
identifier_body
interlock_handler.go
MilevaDB Copyright (c) 2022 MilevaDB Authors: Karl Whitford, Spencer Fogelman, Josh Leder // // 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 INTERLOCKy of the License at // // http://www.apache.org/licenses/LI...
return heap, conds, nil } type evalContext struct { colIDs map[int64]int columnInfos []*fidelpb.DeferredCausetInfo fieldTps []*types.FieldType primaryDefCauss []int64 sc *stmtctx.StatementContext } func (e *evalContext) setDeferredCausetInfo(defcaus []*fidelpb.DeferredCausetInfo...
}
random_line_split
widget.js
/** * Created by jakubniezgoda on 15/03/2017. */ Stage.defineWidget({ id: 'graph', name: 'Deployment metric graph', description: 'Display graph with deployment metric data', initialWidth: 6, initialHeight: 20, showHeader: true, showBorder: true, isReact: true, permission: Stage.Ge...
(string){ return string.replace(/;/g, ''); }, _prepareInfluxQuery: function(queries, deploymentId, nodeId, nodeInstanceId, from, to, timeGroup) { return _.map(queries, (queryParams) => { let selectWhat = this._sanitizeQuery(queryParams.qSelect); let selectFrom = this._sa...
_sanitizeQuery
identifier_name
widget.js
/** * Created by jakubniezgoda on 15/03/2017. */ Stage.defineWidget({ id: 'graph', name: 'Deployment metric graph', description: 'Display graph with deployment metric data', initialWidth: 6, initialHeight: 20, showHeader: true, showBorder: true, isReact: true, permission: Stage.Ge...
deploymentId = nodeFilterFromWidget.deploymentId; nodeId = nodeFilterFromWidget.nodeId; nodeInstanceId = nodeFilterFromWidget.nodeInstanceId; } let timeFilterFromWidget = widget.configuration.timeFilter; let timeFilterFromContext = toolbox.getContext().getVal...
let nodeId = toolbox.getContext().getValue('nodeId'); let nodeInstanceId = toolbox.getContext().getValue('nodeInstanceId'); let nodeFilterFromWidget = widget.configuration.nodeFilter; if (nodeFilterFromWidget.deploymentId || nodeFilterFromWidget.nodeId || nodeFilterFromWidget.nodeInstanc...
random_line_split
widget.js
/** * Created by jakubniezgoda on 15/03/2017. */ Stage.defineWidget({ id: 'graph', name: 'Deployment metric graph', description: 'Display graph with deployment metric data', initialWidth: 6, initialHeight: 20, showHeader: true, showBorder: true, isReact: true, permission: Stage.Ge...
, _prepareInfluxQuery: function(queries, deploymentId, nodeId, nodeInstanceId, from, to, timeGroup) { return _.map(queries, (queryParams) => { let selectWhat = this._sanitizeQuery(queryParams.qSelect); let selectFrom = this._sanitizeQuery(queryParams.qFrom); let selectWh...
{ return string.replace(/;/g, ''); }
identifier_body
widget.js
/** * Created by jakubniezgoda on 15/03/2017. */ Stage.defineWidget({ id: 'graph', name: 'Deployment metric graph', description: 'Display graph with deployment metric data', initialWidth: 6, initialHeight: 20, showHeader: true, showBorder: true, isReact: true, permission: Stage.Ge...
else if (this._isEmptyResponse(widget, data)) { return ( <Message info icon> <Icon name='ban' /> No data fetched for specified chart(s) configuration. </Message> ); } let {Graph} = Stage.Basic.Graphs; ...
{ return ( <Message info icon> <Icon name='info' /> Please select deployment, node instance and metric in widget's configuration to present the data graph. </Message> ); }
conditional_block
parse.go
package janet import ( "strconv" "unicode/utf8" ) type JanetParserStatus int const ( JANET_PARSE_ROOT = iota JANET_PARSE_ERROR JANET_PARSE_PENDING JANET_PARSE_DEAD ) const ( PFLAG_CONTAINER = 0x100 PFLAG_BUFFER = 0x200 PFLAG_PARENS = 0x400 PFLAG_SQRBRACKETS = 0x800 PFLAG_CURLYBRACKETS...
() Value { var ret Value if parser.pending == 0 { return nil } ret = parser.args[0] for i := 1; i < len(parser.args); i += 1 { parser.args[i-1] = parser.args[i] } parser.args = parser.args[:len(parser.args)-1] parser.pending -= 1 return ret } func (parser *Parser) Clone() *Parser { dest := &Parser{} /...
Produce
identifier_name
parse.go
package janet import ( "strconv" "unicode/utf8" ) type JanetParserStatus int const ( JANET_PARSE_ROOT = iota JANET_PARSE_ERROR JANET_PARSE_PENDING JANET_PARSE_DEAD ) const ( PFLAG_CONTAINER = 0x100 PFLAG_BUFFER = 0x200 PFLAG_PARENS = 0x400 PFLAG_SQRBRACKETS = 0x800 PFLAG_CURLYBRACKETS...
for i := state.argn - 1; i >= 0; i = i - 1 { array.Data[i] = p.args[len(p.args)-1] p.args = p.args[:len(p.args)-1] } return array } func (p *Parser) closeTuple(state *ParseState, flags int) *Tuple { tup := NewTuple(state.argn, state.argn) tup.Flags = flags for i := state.argn - 1; i >= 0; i = i - 1 { tup.V...
} func (p *Parser) closeArray(state *ParseState) *Array { array := NewArray(state.argn, state.argn)
random_line_split
parse.go
package janet import ( "strconv" "unicode/utf8" ) type JanetParserStatus int const ( JANET_PARSE_ROOT = iota JANET_PARSE_ERROR JANET_PARSE_PENDING JANET_PARSE_DEAD ) const ( PFLAG_CONTAINER = 0x100 PFLAG_BUFFER = 0x200 PFLAG_PARENS = 0x400 PFLAG_SQRBRACKETS = 0x800 PFLAG_CURLYBRACKETS...
} func (p *Parser) closeArray(state *ParseState) *Array { array := NewArray(state.argn, state.argn) for i := state.argn - 1; i >= 0; i = i - 1 { array.Data[i] = p.args[len(p.args)-1] p.args = p.args[:len(p.args)-1] } return array } func (p *Parser) closeTuple(state *ParseState, flags int) *Tuple { tup := Ne...
{ top := p.states[len(p.states)-1] p.states = p.states[:len(p.states)-1] newtop := &p.states[len(p.states)-1] if (newtop.flags & PFLAG_CONTAINER) != 0 { switch val := val.(type) { case *Tuple: val.Line = top.line val.Column = top.column default: } newtop.argn += 1 /* Keep track of numb...
conditional_block
parse.go
package janet import ( "strconv" "unicode/utf8" ) type JanetParserStatus int const ( JANET_PARSE_ROOT = iota JANET_PARSE_ERROR JANET_PARSE_PENDING JANET_PARSE_DEAD ) const ( PFLAG_CONTAINER = 0x100 PFLAG_BUFFER = 0x200 PFLAG_PARENS = 0x400 PFLAG_SQRBRACKETS = 0x800 PFLAG_CURLYBRACKETS...
func checkEscape(c byte) int { switch c { default: return -1 case 'x': return 1 case 'n': return '\n' case 't': return '\t' case 'r': return '\r' case '0': return 0 case 'z': return 0 case 'f': return '\f' case 'v': return '\v' case 'e': return 27 case '"': return '"' case '\\': r...
{ return (symchars[c>>5] & (uint32(1) << (c & 0x1F))) != 0 }
identifier_body
flux_calc.py
""" Code to calculate mean fluxes of properties through polygon faces, in depth layers. """ #%% Imports import os import sys pth = os.path.abspath('../../LiveOcean/alpha') if pth not in sys.path: sys.path.append(pth) import Lfun Ldir = Lfun.Lstart() import zrfun import numpy as np from datetime import datetime,...
in_dir = out_dir0 + 'gridded_polygons/' out_dir = out_dir0 + 'fluxes/' Lfun.make_dir(out_dir, clean=True) # load polygon results gpoly_dict = pickle.load(open(in_dir + 'gpoly_dict.p', 'rb')) shared_faces_dict = pickle.load(open(in_dir + 'shared_faces.p', 'rb')) # and specify z levels z_dict = {0:5, 1:-5, 2:-25, 3:...
out_dir0 = Ldir['parent'] + 'ptools_output/atlantis_fjord_2005/'
random_line_split
flux_calc.py
""" Code to calculate mean fluxes of properties through polygon faces, in depth layers. """ #%% Imports import os import sys pth = os.path.abspath('../../LiveOcean/alpha') if pth not in sys.path: sys.path.append(pth) import Lfun Ldir = Lfun.Lstart() import zrfun import numpy as np from datetime import datetime,...
zconv.append(cc) pconv.append(net_conv) print(' max convergence error = %g (m3/s)' % (np.abs(np.array(pconv) - np.array(zconv)).max())) # check size of w at the free surface w_arr = np.zeros(NPOLY) for k in range(NPOLY): conv, poly_area, poly_za...
(face_ztrans, face_zarea) = face_ztrans_dict[(npoly, nface, nlay)] cc += face_ztrans
conditional_block
mpcs_app.py
# mpcs_app.py # # Copyright (C) 2011-2017 Vas Vasiliadis # University of Chicago # # Application logic for the GAS # ## __author__ = 'Zhuoyu Zhu <zhuoyuzhu@uchicago.edu>' import stripe import base64 import datetime import hashlib import hmac import json import sha import string import time import urllib import urlpars...
# Display annotation detail for specified job current_time = 0 # Check if the job is still running if items[0]['job_status'] == 'RUNNING': new_link = 2 # Check if the given username match the username within database if username == items[0]['username']: # Modify the date and time format that is ...
'Key': resultfile[0] + '/' + resultfile[1] } )
random_line_split
mpcs_app.py
# mpcs_app.py # # Copyright (C) 2011-2017 Vas Vasiliadis # University of Chicago # # Application logic for the GAS # ## __author__ = 'Zhuoyu Zhu <zhuoyuzhu@uchicago.edu>' import stripe import base64 import datetime import hashlib import hmac import json import sha import string import time import urllib import urlpars...
# Modify the date and time format that is rendered into template file result_data = list() for item in items: item['submit_time'] = datetime.fromtimestamp(int(item['submit_time'])).strftime('%Y-%m-%d %H:%M') result_data.append(item) # Display annotation job detail template ...
conditional_block
mpcs_app.py
# mpcs_app.py # # Copyright (C) 2011-2017 Vas Vasiliadis # University of Chicago # # Application logic for the GAS # ## __author__ = 'Zhuoyu Zhu <zhuoyuzhu@uchicago.edu>' import stripe import base64 import datetime import hashlib import hmac import json import sha import string import time import urllib import urlpars...
(job_id): # Check that user is authenticated auth.require(fail_redirect='/login?redirect_url=' + request.url) # Get the current user name username = auth.current_user.username res = ann_table.query(KeyConditionExpression=Key('job_id').eq(job_id)) items = res['Items'] download_url = '' # Construct a signe...
get_annotation_details
identifier_name
mpcs_app.py
# mpcs_app.py # # Copyright (C) 2011-2017 Vas Vasiliadis # University of Chicago # # Application logic for the GAS # ## __author__ = 'Zhuoyu Zhu <zhuoyuzhu@uchicago.edu>' import stripe import base64 import datetime import hashlib import hmac import json import sha import string import time import urllib import urlpars...
''' ******************************************************************************* Display details of a specific annotation job ******************************************************************************* ''' @route('/annotations/<job_id>', method='GET', name="annotation_details") def get_annotation_details(job_...
auth.require(fail_redirect='/login?redirect_url=' + request.url) # Get the current username username = auth.current_user.username res = ann_table.query( IndexName='username_index', KeyConditionExpression=Key('username').eq(username)) # Get all the relevant detail about current user items = res['Items'] ...
identifier_body
blockchain.go
package main import ( "bytes" "crypto/ecdsa" "errors" "fmt" "github.com/boltdb/bolt" "log" "time" ) const BlockChainDB = "blockchain.db" const BlockBucket = "blockbucket" // BlockClain 4.define blockchain struct type BlockChain struct { //blocks [] *Block db *bolt.DB //storage the last block's hash tail [...
(address string) *BlockChain { //return &BlockClain{ // []*Block{genesisBlock}, //} var lastHash []byte db, err := bolt.Open(BlockChainDB, 0600, nil) //defer db.Close() if err != nil { log.Fatal("create database failed") } err = db.Update(func(tx *bolt.Tx) error { bucket := tx.Bucket([]byte(BlockBucket)...
NewBlockChain
identifier_name
blockchain.go
package main import ( "bytes" "crypto/ecdsa" "errors" "fmt" "github.com/boltdb/bolt" "log" "time" ) const BlockChainDB = "blockchain.db" const BlockBucket = "blockbucket" // BlockClain 4.define blockchain struct type BlockChain struct { //blocks [] *Block db *bolt.DB //storage the last block's hash tail [...
unc (bc *BlockChain)FindNeedUTXOs(senderPubKeyHash []byte, amount float64) (map[string][]int64, float64){ //合理utxo集合 utxos := make(map[string][]int64) //找到钱的总数 var cacl float64 //================================= //定义一个map来保存消费过的output, key为这个消费过的output的交易id,value值为这个交易中索引的数组 spentOutput := make(map[string][]i...
//找错误, continue只能跳出最近的for循环 fmt.Println(j) fmt.Println(i) var a bool a = int64(i) == j fmt.Println(a) */ //标识过下标和循环中的下标对比, 过滤到已经消费的output if int64(i) == j{ continue OUTPUT } } } if bytes.Equal(output.PubKeyHash,pubKeyHash){ //fmt.Pr...
conditional_block
blockchain.go
package main import ( "bytes" "crypto/ecdsa" "errors" "fmt" "github.com/boltdb/bolt" "log" "time" ) const BlockChainDB = "blockchain.db" const BlockBucket = "blockbucket" // BlockClain 4.define blockchain struct type BlockChain struct { //blocks [] *Block db *bolt.DB //storage the last block's hash tail [...
ddBlock 6.add a new block func (bc *BlockChain)AddBlock(txs []*Transaction) { for _, tx := range txs{ if !bc.VerifyTransaction(tx) { fmt.Println("校验交易失败") return } } //found the last block's hash lastHash := bc.tail db := bc.db //create a new block //send the new block into the blockchain db.Update...
{ coinBase := NewCoinbaseTX(address, "创世块") coinBases := []*Transaction{coinBase} return NewBlock(coinBases, []byte{}) } // A
identifier_body
blockchain.go
package main import ( "bytes" "crypto/ecdsa" "errors" "fmt" "github.com/boltdb/bolt" "log" "time" ) const BlockChainDB = "blockchain.db" const BlockBucket = "blockbucket" // BlockClain 4.define blockchain struct type BlockChain struct { //blocks [] *Block db *bolt.DB //storage the last block's hash tail [...
return UTXO } //找到指定地址所有的UTXO,即未消费的,优化上面函数 //func (bc *BlockChain)FindUTXOs(pubKeyHash []byte) []TXOuput { // var UTXO []TXOuput // txs := bc.FindUTXOsBased(pubKeyHash) // for _, tx := range txs{ // for _, output := range tx.TXOuputs{ // if bytes.Equal(pubKeyHash,output.PubKeyHash){ // UTXO = append(UTXO, outpu...
} }
random_line_split
app.py
import os import re import datetime from werkzeug.utils import secure_filename from flask import Flask, jsonify, request, abort, send_from_directory from flask_sqlalchemy import SQLAlchemy from flask_mysqldb import MySQL from flask_cors import CORS from flask_bcrypt import Bcrypt from flask_jwt_extended import ( JW...
except: # To notify if a student hasn't conformed to an acceptable input format. return {'Error': 'Unable to retrieve student details. Ensure the inputs are valid'} elif str(user_type) == 'Lecturer': try: # Get additional inpuuts for lecturers depart...
return {'Error': 'This email has already been used to register'}
conditional_block
app.py
import os import re import datetime from werkzeug.utils import secure_filename from flask import Flask, jsonify, request, abort, send_from_directory from flask_sqlalchemy import SQLAlchemy from flask_mysqldb import MySQL from flask_cors import CORS from flask_bcrypt import Bcrypt from flask_jwt_extended import ( JW...
# Function to retrieve a user details based on id @app.route('/users/<id>', methods=['GET']) @login_required def get_user(id): try: resp = controller.get_user(id) #Gets the details of a user given the user id. return resp.to_dict() except: return {'Error': 'User not found'} # Fun...
try: # Gets all input data from the user user_name = request.form.get('user_name') surname = request.form.get('surname') first_name = request.form.get('first_name') email = request.form.get('email') password = bcrypt.generate_password_hash(request.form.get('password')).de...
identifier_body
app.py
import os import re import datetime from werkzeug.utils import secure_filename from flask import Flask, jsonify, request, abort, send_from_directory from flask_sqlalchemy import SQLAlchemy from flask_mysqldb import MySQL from flask_cors import CORS from flask_bcrypt import Bcrypt from flask_jwt_extended import ( JW...
(): #where id is the user_id try: user_id = request.form.get('user_id') data = request.form.get('data') updated_at = request.form.get('updated_at') except: return {'Error': 'Unable to retreive data sent'} try: ts = datetime.datetime.now() controller.updat...
update_calendar
identifier_name
app.py
import os import re import datetime from werkzeug.utils import secure_filename from flask import Flask, jsonify, request, abort, send_from_directory from flask_sqlalchemy import SQLAlchemy from flask_mysqldb import MySQL from flask_cors import CORS from flask_bcrypt import Bcrypt from flask_jwt_extended import ( JW...
try: resp = controller.get_user(id) #Gets the details of a user given the user id. return resp.to_dict() except: return {'Error': 'User not found'} # Function to login @app.route('/token/auth', methods=['POST']) def login(): # Gets email and password inputed by the user emai...
# Function to retrieve a user details based on id @app.route('/users/<id>', methods=['GET']) @login_required def get_user(id):
random_line_split
DQN_Snake.py
# -*- coding: UTF-8 -*- import cv2 import numpy as np
import matplotlib.pyplot as plt from BrainDQN_Nature import BrainDQN ################################################################################################################## ################################################################################################################## import random, pyg...
random_line_split
DQN_Snake.py
# -*- coding: UTF-8 -*- import cv2 import numpy as np import matplotlib.pyplot as plt from BrainDQN_Nature import BrainDQN ################################################################################################################## ###############################################################################...
reward=LOSE_REWARD print ("撞牆死....") for wormBody in self.wormCoords[1:]: # 檢查貪吃蛇是否撞到自己 if wormBody['x'] == self.wormCoords[self.HEAD]['x'] and wormBody['y'] == self.wormCoords[self.HEAD]['y']: terminal=True reward=LOSE_REWARD print ("撞自己死....") break if terminal==False: # 檢查貪吃蛇是否吃到appl...
: terminal=True
conditional_block
DQN_Snake.py
# -*- coding: UTF-8 -*- import cv2 import numpy as np import matplotlib.pyplot as plt from BrainDQN_Nature import BrainDQN ################################################################################################################## ###############################################################################...
andom.randint(5, CELLHEIGHT - 6) # 以這個點為起點,建立一個長度為3格的貪吃蛇(陣列) self.wormCoords = [{'x': startx, 'y': starty}, {'x': startx - 1, 'y': starty}, {'x': startx - 2, 'y': starty}] self.direction = RIGHT # 初始化一個運動的方向 self.apple = self.getRandomLocation() # 隨機一個app...
ICFONT = pygame.font.Font('freesansbold.ttf', 18) # BASICFONT pygame.display.set_caption('Greedy Snake') # 設置視窗的標題 self.HEAD = 0 # syntactic sugar: index of the worm's head # 貪吃蛇的頭() self.Bodylen=3 #showStartScreen() # 顯示開始畫面 self.runGame() def getRandomLocation(self): # 隨機生成一個座標位置 return {'x': ra...
identifier_body
DQN_Snake.py
# -*- coding: UTF-8 -*- import cv2 import numpy as np import matplotlib.pyplot as plt from BrainDQN_Nature import BrainDQN ################################################################################################################## ###############################################################################...
lf.direction!=LEFT and self.direction!=RIGHT : self.direction = RIGHT elif action==MOVE_UP and self.direction!=UP and self.direction!=DOWN: self.direction = UP elif action==MOVE_DOWN and self.direction!=UP and self.direction!=DOWN: self.direction = DOWN elif action==MOVE_STAY : pass # 檢查貪吃蛇是否撞到撞到邊界 if self.w...
GHT and se
identifier_name
JS_Exercises.js
// // JS Variables 1-1: Create a variable called carName, assign the value Volvo to it. // var carName = "Volvo"; // document.write(carName); // console.log(carName); // // JS Variables 2-1: Create a variable called x, assign the value 50 to it. // var x = 50; // document.write(x); // console.log(x); // // JS Variables...
/* <button id="demo">CLICK ME!!</button> <script>document.getElementById("demo").addEventListener("click", myFunction);</script> */
// JS HTML DOM 9-1: Use the eventListener to assign an onclick event to the <button> element.
random_line_split
http_ece.rs
use base64::{self, URL_SAFE_NO_PAD}; use crate::error::WebPushError; use crate::message::WebPushPayload; use ring::rand::SecureRandom; use ring::{aead::{self, BoundKey}, agreement, hkdf, rand}; use crate::vapid::VapidSignature; pub enum ContentEncoding { AesGcm, Aes128Gcm, } pub struct HttpEce<'a> { peer_...
} pub fn generate_headers( &self, public_key: &'a [u8], salt: &'a [u8], ) -> Vec<(&'static str, String)> { let mut crypto_headers = Vec::new(); let mut crypto_key = format!("dh={}", base64::encode_config(public_key, URL_SAFE_NO_PAD)); if let Some(ref signat...
random_line_split
http_ece.rs
use base64::{self, URL_SAFE_NO_PAD}; use crate::error::WebPushError; use crate::message::WebPushPayload; use ring::rand::SecureRandom; use ring::{aead::{self, BoundKey}, agreement, hkdf, rand}; use crate::vapid::VapidSignature; pub enum ContentEncoding { AesGcm, Aes128Gcm, } pub struct HttpEce<'a> { peer_...
() { // writes the padding count in the beginning, zeroes, content and again space for the encryption tag let content = "naukio"; let mut output = [0u8; 30]; front_pad(content.as_bytes(), &mut output); assert_eq!( vec![0, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0...
test_front_pad
identifier_name
http_ece.rs
use base64::{self, URL_SAFE_NO_PAD}; use crate::error::WebPushError; use crate::message::WebPushPayload; use ring::rand::SecureRandom; use ring::{aead::{self, BoundKey}, agreement, hkdf, rand}; use crate::vapid::VapidSignature; pub enum ContentEncoding { AesGcm, Aes128Gcm, } pub struct HttpEce<'a> { peer_...
/// The aesgcm encrypted content-encoding, draft 3. pub fn aes_gcm( &self, shared_secret: &'a [u8], as_public_key: &'a [u8], salt_bytes: &'a [u8], payload: &'a mut Vec<u8>, ) -> Result<(), WebPushError> { let mut context = Vec::with_capacity(140); c...
{ let mut crypto_headers = Vec::new(); let mut crypto_key = format!("dh={}", base64::encode_config(public_key, URL_SAFE_NO_PAD)); if let Some(ref signature) = self.vapid_signature { crypto_key = format!("{}; p256ecdsa={}", crypto_key, signature.auth_k); let sig_s: Stri...
identifier_body
http_ece.rs
use base64::{self, URL_SAFE_NO_PAD}; use crate::error::WebPushError; use crate::message::WebPushPayload; use ring::rand::SecureRandom; use ring::{aead::{self, BoundKey}, agreement, hkdf, rand}; use crate::vapid::VapidSignature; pub enum ContentEncoding { AesGcm, Aes128Gcm, } pub struct HttpEce<'a> { peer_...
let private_key = agreement::EphemeralPrivateKey::generate(&agreement::ECDH_P256, &self.rng)?; let public_key = private_key.compute_public_key()?; let mut salt_bytes = [0u8; 16]; self.rng.fill(&mut salt_bytes)?; let peer_public_key = agreement::UnparsedPublicKey::n...
{ return Err(WebPushError::PayloadTooLarge); }
conditional_block
weights_manager.py
import torch from torch import nn from aw_nas import ops from aw_nas.btcs.layer2.search_space import * from aw_nas.weights_manager.base import BaseWeightsManager, CandidateNet class Layer2CandidateNet(CandidateNet): def __init__(self, supernet, rollout, eval_no_grad): super().__init__(eval_no_grad) ...
if len(outputs) != 0: return sum(outputs) else: raise RuntimeError( "Edge module does not handle the case where no op is " "used. It should be handled in Cell and Edge.forward " "should not be called" )
if use_op != 0: outputs.append(op(inputs))
conditional_block
weights_manager.py
import torch from torch import nn from aw_nas import ops from aw_nas.btcs.layer2.search_space import * from aw_nas.weights_manager.base import BaseWeightsManager, CandidateNet class Layer2CandidateNet(CandidateNet): def __init__(self, supernet, rollout, eval_no_grad): super().__init__(eval_no_grad) ...
def forward(self, inputs): return self.supernet.forward(inputs, self.rollout) def _forward_with_params(self, *args, **kwargs): raise NotImplementedError() def get_device(self): return self.supernet.device class Layer2MacroSupernet(BaseWeightsManager, nn.Module): NAME = "lay...
raise NotImplementedError()
identifier_body
weights_manager.py
import torch from torch import nn from aw_nas import ops from aw_nas.btcs.layer2.search_space import * from aw_nas.weights_manager.base import BaseWeightsManager, CandidateNet class Layer2CandidateNet(CandidateNet): def __init__(self, supernet, rollout, eval_no_grad): super().__init__(eval_no_grad) ...
(self, inputs, edge_arch): outputs = [] for op, use_op in zip(self.ops, edge_arch): if use_op != 0: outputs.append(op(inputs)) if len(outputs) != 0: return sum(outputs) else: raise RuntimeError( "Edge module does not ha...
forward
identifier_name
weights_manager.py
import torch from torch import nn from aw_nas import ops from aw_nas.btcs.layer2.search_space import * from aw_nas.weights_manager.base import BaseWeightsManager, CandidateNet class Layer2CandidateNet(CandidateNet): def __init__(self, supernet, rollout, eval_no_grad): super().__init__(eval_no_grad) ...
self.classifier = nn.Linear(prev_num_channels, num_classes) self.to(self.device) def forward( self, inputs, rollout, # type: Layer2Rollout ): macro_rollout = rollout.macro # type: StagewiseMacroRollout micro_rollout = rollout.micro # type: DenseMicroR...
prev_num_channels = num_channels # make pooling and classifier self.pooling = nn.AdaptiveAvgPool2d((1, 1)) self.dropout = nn.Dropout(dropout_rate) if dropout_rate else nn.Identity()
random_line_split
downloadtaskmgr.go
package downloadtaskmgr import ( "errors" "io" "math" "net" "net/http" "os" "path" "sort" "strings" "sync" "time" "github.com/daqnext/meson-common/common/logger" ) type DownloadInfo struct { TargetUrl string BindName string FileName string Continent string Country string Area ...
() []*DownloadTask { taskInLDB := LoopTasksInLDB() if taskInLDB == nil { return nil } list := []*DownloadTask{} for _, v := range taskInLDB { list = append(list, v) } return list } func TaskSuccess(task *DownloadTask) { logger.Debug("Task Success", "id", task.Id) //从map中删除任务 DelTaskFromLDB(task.Id) Del...
GetDownloadTaskList
identifier_name
downloadtaskmgr.go
package downloadtaskmgr import ( "errors" "io" "math" "net" "net/http" "os" "path" "sort" "strings" "sync" "time" "github.com/daqnext/meson-common/common/logger" )
Continent string Country string Area string SavePath string DownloadType string OriginRegion string TargetRegion string } type TaskStatus string //const Task_Success TaskStatus = "success" //const Task_Fail TaskStatus ="fail" const Task_UnStart TaskStatus = "unstart" const Task_Break TaskSt...
type DownloadInfo struct { TargetUrl string BindName string FileName string
random_line_split
downloadtaskmgr.go
package downloadtaskmgr import ( "errors" "io" "math" "net" "net/http" "os" "path" "sort" "strings" "sync" "time" "github.com/daqnext/meson-common/common/logger" ) type DownloadInfo struct { TargetUrl string BindName string FileName string Continent string Country string Area ...
Conn, err error) { return func(netw, addr string) (net.Conn, error) { conn, err := net.DialTimeout(netw, addr, cTimeout) if err != nil { return nil, err } if rwTimeout > 0 { err := conn.SetDeadline(time.Now().Add(rwTimeout)) if err != nil { logger.Error("set download process rwTimeout error", "err...
select { case task := <-globalDownloadTaskChan: //开始一个新下载任务 go func() { //任务结束,放回token defer func() { newRunningTaskControlChan <- true }() //执行任务 //logger.Debug("start a new task", "id", task.Id) task.Status = Task_Downloading AddTaskToDownloadingMap(task) Start...
identifier_body