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
read.go
package readability import ( "bytes" "fmt" "github.com/PuerkitoBio/goquery" wl "github.com/abadojack/whatlanggo" "golang.org/x/net/html" "golang.org/x/net/html/atom" ghtml "html" "io/ioutil" "math" "net/http" nurl "net/url" pt "path" "regexp" "strings" "time" ) var ( unlikelyCandidates = regexp.Must...
if tagName != "table" && tagName != "th" && tagName != "td" && tagName != "hr" && tagName != "pre" { s1.RemoveAttr("width") s1.RemoveAttr("height") } }) } // Clean a node of all elements of type "tag". // (Unless it's a youtube/vimeo video. People love movies.) func (r *readability) clean(s *goquery.Sele...
random_line_split
read.go
package readability import ( "bytes" "fmt" "github.com/PuerkitoBio/goquery" wl "github.com/abadojack/whatlanggo" "golang.org/x/net/html" "golang.org/x/net/html/atom" ghtml "html" "io/ioutil" "math" "net/http" nurl "net/url" pt "path" "regexp" "strings" "time" ) var ( unlikelyCandidates = regexp.Must...
// Set final title metadata.Title = r.getArticleTitle(doc) if metadata.Title == "" { if _, exist := mapAttribute["og:title"]; exist { metadata.Title = mapAttribute["og:title"] } else if _, exist := mapAttribute["twitter:title"]; exist { metadata.Title = mapAttribute["twitter:title"] } } return metad...
{ metadata.Excerpt = mapAttribute["twitter:description"] }
conditional_block
read.go
package readability import ( "bytes" "fmt" "github.com/PuerkitoBio/goquery" wl "github.com/abadojack/whatlanggo" "golang.org/x/net/html" "golang.org/x/net/html/atom" ghtml "html" "io/ioutil" "math" "net/http" nurl "net/url" pt "path" "regexp" "strings" "time" ) var ( unlikelyCandidates = regexp.Must...
oquery.Selection) { s.Find("*").Each(func(i int, s1 *goquery.Selection) { tagName := s1.Nodes[0].Data if tagName == "svg" { return } s1.RemoveAttr("align") s1.RemoveAttr("background") s1.RemoveAttr("bgcolor") s1.RemoveAttr("border") s1.RemoveAttr("cellpadding") s1.RemoveAttr("cellspacing") s1.R...
Style(s *g
identifier_name
read.go
package readability import ( "bytes" "fmt" "github.com/PuerkitoBio/goquery" wl "github.com/abadojack/whatlanggo" "golang.org/x/net/html" "golang.org/x/net/html/atom" ghtml "html" "io/ioutil" "math" "net/http" nurl "net/url" pt "path" "regexp" "strings" "time" ) var ( unlikelyCandidates = regexp.Must...
nverts each <a> and <img> uri in the given element to an absolute URI, // ignoring #ref URIs. func (r *readability) fixRelativeURIs(node *goquery.Selection) { if node == nil { return } node.Find("img").Each(func(i int, img *goquery.Selection) { src := img.AttrOr("src", "") if file, ok := img.Attr("file"); ok ...
nd("h1,h2,h3").Each(func(_ int, s1 *goquery.Selection) { if r.getClassWeight(s1) < 0 { s1.Remove() } }) } // Co
identifier_body
Model.py
import numpy as np import tensorflow as tf from Constants import Constants from DataHandler import DataHandler class Model:
def __init__(self, char_list, restore=False): self.decoder_selected = Constants.decoder_selected self.path_model = Constants.path_model self.batch_size = Constants.batch_size self.char_list = char_list self.learning_rate = Constants.learning_rate self.text_length = Const...
identifier_body
Model.py
import numpy as np import tensorflow as tf from Constants import Constants from DataHandler import DataHandler class Model: def __init__(self, char_list, restore=False): self.decoder_selected = Constants.decoder_selected self.path_model = Constants.path_model self.batch_size = Constants...
dtype=rnn_input_3d.dtype) rnn_combined = tf.concat([fw, bw], 2) # combine the fw & bw rnn = tf.expand_dims(rnn_combined, 2) # adds dimensions of size 1 to the 2nd index features_in = n_cell * 2 # no. of input features_out = len...
cell_multi = tf.contrib.rnn.MultiRNNCell(cells, state_is_tuple=True) ((fw, bw), _) = tf.nn.bidirectional_dynamic_rnn(cell_fw=cell_multi, cell_bw=cell_multi, inputs=rnn_input_3d,
random_line_split
Model.py
import numpy as np import tensorflow as tf from Constants import Constants from DataHandler import DataHandler class Model: def __init__(self, char_list, restore=False): self.decoder_selected = Constants.decoder_selected self.path_model = Constants.path_model self.batch_size = Constants...
(self): word_beam_search_module = tf.load_op_library(self.file_word_beam_search) chars = str().join(self.char_list) word_chars = open(self.file_word_char_list).read().splitlines()[0] data_handler = DataHandler() data_handler.prepare_collection_words() collection_words ...
load_word_beam
identifier_name
Model.py
import numpy as np import tensorflow as tf from Constants import Constants from DataHandler import DataHandler class Model: def __init__(self, char_list, restore=False): self.decoder_selected = Constants.decoder_selected self.path_model = Constants.path_model self.batch_size = Constants...
return (indices, values, shape) def decode(self, ctc_output, batch_size): "transform sparse tensor to labels" encoded_label_list = [] # store batch elements labels for i in range(batch_size): encoded_label_list.append([]) blank = len(self.char_list) # last...
indices.append([batch_element, i]) values.append(label)
conditional_block
process.py
# This Python module is part of the PyRate software package. # # Copyright 2020 Geoscience Australia # # 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/...
r_dist = mpiops.run_once(_get_r_dist, ifg_paths[0]) prcs_ifgs = mpiops.array_split(ifg_paths) process_maxvar = [] for n, i in enumerate(prcs_ifgs): log.debug('Calculating maxvar for {} of process ifgs {} of total {}'.format(n+1, len(prcs_ifgs), len(ifg_paths))) process_maxvar.append(vc...
""" Get RDIst class object """ ifg = Ifg(ifg_path) ifg.open() r_dist = vcm_module.RDist(ifg)() ifg.close() return r_dist
identifier_body
process.py
# This Python module is part of the PyRate software package. # # Copyright 2020 Geoscience Australia # # 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/...
return r_dist r_dist = mpiops.run_once(_get_r_dist, ifg_paths[0]) prcs_ifgs = mpiops.array_split(ifg_paths) process_maxvar = [] for n, i in enumerate(prcs_ifgs): log.debug('Calculating maxvar for {} of process ifgs {} of total {}'.format(n+1, len(prcs_ifgs), len(ifg_paths))) pro...
ifg.close()
random_line_split
process.py
# This Python module is part of the PyRate software package. # # Copyright 2020 Geoscience Australia # # 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/...
(tile, i, preread_ifgs): """ Convenient inner loop for mst tile saving """ mst_tile = mst.mst_multiprocessing(tile, dest_tifs, preread_ifgs, params) # locally save the mst_mat mst_file_process_n = join(params[cf.TMPDIR], 'mst_mat_{}.npy'.format(i)) np.save(file=ms...
_save_mst_tile
identifier_name
process.py
# This Python module is part of the PyRate software package. # # Copyright 2020 Geoscience Australia # # 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/...
rows, cols = params["rows"], params["cols"] return process_ifgs(ifg_paths, params, rows, cols) def process_ifgs(ifg_paths, params, rows, cols): """ Top level function to perform PyRate workflow on given interferograms :param list ifg_paths: List of interferogram paths :param dict params: D...
ifg_paths.append(ifg_path.sampled_path)
conditional_block
corpora.py
""" Module responsible for preparing, storing and handling data. """ import numpy as np import os import _pickle import json from nltk.tokenize import word_tokenize, sent_tokenize from sklearn.datasets import fetch_20newsgroups from util import * def get_corpus_object(corpus_name): """ Return the correct corpus o...
self.Y["hybrid"] = np.zeros(len(self.X["hybrid"])) # pseudo-labels, we won't do anything with these print("Created", len(self.X["hybrid"]), "hybrid documents from", len(self.X["test"]), "test documents") def make_word_to_freq(self): """ Map all words in the corpus to their absolute frequency """ word...
batch = all_sentences[i:min(i+self.HYBRID_LENGTH, len(all_sentences))] hybrid_tokenized_document = [] hybrid_X = [] hybrid_labels = [] for sentence, label in batch: for word in word_tokenize(sentence): hybrid_tokenized_document.append(word) hybrid_X.append(self.worddict.get(word, self.worddi...
conditional_block
corpora.py
""" Module responsible for preparing, storing and handling data. """ import numpy as np import os import _pickle import json from nltk.tokenize import word_tokenize, sent_tokenize from sklearn.datasets import fetch_20newsgroups from util import * def get_corpus_object(corpus_name): """ Return the correct corpus o...
(self, dataset): print("Word-tokenizing documents in", dataset) self.tokenized_documents[dataset] = [word_tokenize(document) for document in self.raw_documents[dataset]] def shuffle_dataset(self, dataset): print("Shuffling dataset", dataset) indices = list(range(len(self.X[dataset]))) np.random.seed(0) n...
tokenize_documents
identifier_name
corpora.py
""" Module responsible for preparing, storing and handling data. """ import numpy as np import os import _pickle import json from nltk.tokenize import word_tokenize, sent_tokenize from sklearn.datasets import fetch_20newsgroups from util import * def get_corpus_object(corpus_name): """ Return the correct corpus o...
for filename in self.FILENAMES: with open(os.path.join(self.storagedir, filename), "wb") as handle: _pickle.dump(getattr(self, filename), handle) def load(self, which): """ Load a corpus component from its storage directory """ path = os.path.join(self.storagedir, which) print("Loading from", path)...
Store corpus to its storage directory """ print("Storing to", self.storagedir)
random_line_split
corpora.py
""" Module responsible for preparing, storing and handling data. """ import numpy as np import os import _pickle import json from nltk.tokenize import word_tokenize, sent_tokenize from sklearn.datasets import fetch_20newsgroups from util import * def get_corpus_object(corpus_name): """ Return the correct corpus o...
def get_generator(self, dataset, batchsize, shuffle = False): """ Returns a generator that will generate (X,Y) pairs for the given dataset. dataset: one of 'train', 'dev', 'test', 'hybrid' batchsize: batch size that the generator will be working on shuffle: if true, the dataset is shuffled at the beginni...
""" Load selected corpus components only if they have not yet been loaded """ for which in selected: self.load_if_necessary(which) if "worddict" in selected and "classdict" in selected: self.reverse_dicts()
identifier_body
trainer.py
from utils.techniques.gradient_clipping import clip_gradient import torch import torch.nn as nn from tqdm import tqdm from .checkpoint import CheckPoint, load from logger import Logger import time import os from augmentation import Denormalize import cv2 import numpy as np from utils.gradcam import * class Trainer(nn...
def __str__(self) -> str: title = '------------- Model Summary ---------------\n' name = f'Name: {self.model.name}\n' params = f'Number of params: {self.model.trainable_parameters}\n' train_iter_per_epoch = f'Number of train iterations per epoch: {len(self.train_loader)}\n' ...
if not os.path.exists('./samples'): os.mkdir('./samples') denom = Denormalize() batch = next(iter(self.val_loader)) images = batch["imgs"] #targets = batch["targets"] self.model.eval() config_name = self.cfg.model_name.split('_')[0] grad_cam = GradC...
identifier_body
trainer.py
from utils.techniques.gradient_clipping import clip_gradient import torch import torch.nn as nn from tqdm import tqdm from .checkpoint import CheckPoint, load from logger import Logger import time import os from augmentation import Denormalize import cv2 import numpy as np from utils.gradcam import * class Trainer(nn...
if print_per_iter is not None: self.print_per_iter = print_per_iter else: self.print_per_iter = int(len(self.train_loader) / 10) self.epoch = start_epoch # For one-cycle lr only if self.scheduler is not None and self.step_per_epoch: self.sc...
self.checkpoint = CheckPoint(save_per_epoch=int(num_epochs/10) + 1)
conditional_block
trainer.py
from utils.techniques.gradient_clipping import clip_gradient import torch import torch.nn as nn from tqdm import tqdm from .checkpoint import CheckPoint, load from logger import Logger import time import os from augmentation import Denormalize import cv2 import numpy as np from utils.gradcam import * class Trainer(nn...
(self.num_epochs + i) / len(self.train_loader)) lrl = [x['lr'] for x in self.optimizer.param_groups] lr = sum(lrl) / len(lrl) log_dict = {'Learning rate/Iterations': lr} self.logging(log_dict) torch.cuda...
self.optimizer.zero_grad() if self.scheduler is not None and not self.step_per_epoch: # self.scheduler.step() self.scheduler.step(
random_line_split
trainer.py
from utils.techniques.gradient_clipping import clip_gradient import torch import torch.nn as nn from tqdm import tqdm from .checkpoint import CheckPoint, load from logger import Logger import time import os from augmentation import Denormalize import cv2 import numpy as np from utils.gradcam import * class Trainer(nn...
(self, config, model, train_loader, val_loader, **kwargs): super().__init__() self.config = config self.model = model self.train_loader = train_loader self.val_loader = val_loader self.optimizer = model.optimizer self.criterion = model.criterion self.metri...
__init__
identifier_name
main.py
import cv2 import numpy as np import math face_onnx_path = r"weights/face-RFB-320_simplified.onnx" smoke_onnx_path = r'weights/smoke.onnx' label_path = 'labels.txt' def clip(x, y): # [0, 1] return max(0, min(x, y)) def nms(dets, scores, thresh): """Pure Python NMS baseline.""" x1 = dets[:, 0] y...
iow = image_h / 640, image_w / 640 # Scan through all the bounding boxes output from the network and keep only the # ones with high confidence scores. Assign the box's class label as the class with the highest score. classIds = [] confidences = [] boxes = [] for out in ou...
atioh, rat
identifier_name
main.py
import cv2 import numpy as np import math face_onnx_path = r"weights/face-RFB-320_simplified.onnx" smoke_onnx_path = r'weights/smoke.onnx' label_path = 'labels.txt' def clip(x, y): # [0, 1] return max(0, min(x, y)) def nms(dets, scores, thresh): """Pure Python NMS baseline.""" x1 = dets[:, 0] y...
) if len(indices): indices = indices.flatten() boxes = np.array(boxes)[indices] confidences = np.array(confidences)[indices] return boxes, confidences def __call__(self, srcimg): blob = cv2.dnn.blobFromImage(srcimg, 1 / 255.0, (640, 640), [0, 0, 0], swapRB=Tru...
t(center_x - width / 2) top = int(center_y - height / 2) classIds.append(classId) confidences.append(float(confidence)) boxes.append([left, top, width, height]) # Perform non maximum suppression to eliminate redundant overlapping b...
conditional_block
main.py
import cv2 import numpy as np import math face_onnx_path = r"weights/face-RFB-320_simplified.onnx" smoke_onnx_path = r'weights/smoke.onnx' label_path = 'labels.txt' def clip(x, y): # [0, 1] return max(0, min(x, y)) def nms(dets, scores, thresh): """Pure Python NMS baseline.""" x1 = dets[:, 0] y...
ratioh, ratiow = image_h / 640, image_w / 640 # Scan through all the bounding boxes output from the network and keep only the # ones with high confidence scores. Assign the box's class label as the class with the highest score. classIds = [] confidences = [] boxes = [] ...
[30, 61, 62, 45, 59, 119], [116, 90, 156, 198, 373, 326]] self.nl = len(anchors) # number of detection layers self.na = len(anchors[0]) // 2 # number of anchors self.no = num_classes + 5 # number of outputs per anchor self.grid = [np.zeros(1)] * self.nl # init grid self.stri...
identifier_body
main.py
import cv2 import numpy as np import math face_onnx_path = r"weights/face-RFB-320_simplified.onnx" smoke_onnx_path = r'weights/smoke.onnx' label_path = 'labels.txt' def clip(x, y): # [0, 1] return max(0, min(x, y)) def nms(dets, scores, thresh): """Pure Python NMS baseline.""" x1 = dets[:, 0] y...
return rect_boxes, confidences class SmokeDetector: def __init__(self, model_path, confThreshold=0.5, nmsThreshold=0.5, objThreshold=0.5): self.classes = ['smoke'] self.colors = [np.random.randint(0, 255, size=3).tolist() for _ in range(len(self.classes))] # num_classes = len(self....
scores, boxes = self.face_detector.forward(["scores", "boxes"]) # print(scores) image_h, image_w = img.shape[:2] rect_boxes, confidences = self.postprocess(image_w, image_h, scores, boxes, 0.6)
random_line_split
director.ts
// @ts-nocheck /* eslint-disable */ /** * 路由部分director */ let router; const dloc = document.location; function dlocHashEmpty() { return dloc.hash === '' || dloc.hash === '#'; } const listener = { mode: 'modern', hash: dloc.hash, history: false, check() { const h = dloc.hash; if (h != this.hash) ...
ds[method] = true; self[method] = function () { const extra = arguments.length === 1 ? [method, ''] : [method]; self.on.apply(self, extra.concat(Array.prototype.slice.call(arguments))); }; } for (i = 0; i < len; i++) { extend(methods[i]); } }; Router.prototype.runlist = function (fns) { ...
_metho
identifier_name
director.ts
// @ts-nocheck /* eslint-disable */ /** * 路由部分director */ let router; const dloc = document.location; function dlocHashEmpty() { return dloc.hash === '' || dloc.hash === '#'; } const listener = { mode: 'modern', hash: dloc.hash, history: false, check() { co
e() { if (this.mode === 'modern') { this.history === true ? window.onpopstate() : window.onhashchange(); } else { this.onHashChanged(); } }, init(fn, history) { const self = this; this.history = history; if (!Router.listeners) { Router.listeners = []; } function ...
nst h = dloc.hash; if (h != this.hash) { this.hash = h; this.onHashChanged(); } }, fir
identifier_body
director.ts
// @ts-nocheck /* eslint-disable */ /** * 路由部分director */ let router; const dloc = document.location; function dlocHashEmpty() { return dloc.hash === '' || dloc.hash === '#'; } const listener = { mode: 'modern', hash: dloc.hash, history: false, check() { const h = dloc.hash; if (h != this.hash) ...
// // IE support, based on a concept by Erik Arvidson ... // const frame = document.createElement('iframe'); frame.id = 'state-frame'; frame.style.display = 'none'; document.body.appendChild(frame); this.writeFrame(''); if ('onpropertychange' in document && 'attach...
// At least for now HTML5 history is available for 'modern' browsers only if (this.history === true) { // There is an old bug in Chrome that causes onpopstate to fire even // upon initial page load. Since the handler is run manually in init(), // this would cause Chrome to run it twise. Cu...
conditional_block
director.ts
// @ts-nocheck /* eslint-disable */ /** * 路由部分director */ let router; const dloc = document.location; function dlocHashEmpty() { return dloc.hash === '' || dloc.hash === '#'; } const listener = { mode: 'modern', hash: dloc.hash, history: false, check() { const h = dloc.hash; if (h != this.hash) ...
this.params[token] = function (str) { return str.replace(compiled, matcher.source || matcher); }; return this; }; Router.prototype.on = Router.prototype.route = function (method, path, route) { const self = this; if (!route && typeof path === 'function') { route = path; path = method; method ...
random_line_split
junk.py
# coding: utf-8 # In[ ]: # This notebook tests the making of pre-made masks for the Fizeau PSF FFT # created 2018 July 16 by E.S. # In[1]: import numpy as np import matplotlib.pyplot as plt import scipy import numpy.ma as ma import os.path from scipy import misc, signal, ndimage from astropy.io import fits from m...
# In[16]: # put in init def findFFTloc(baseline,imageShapeAlong1Axis,wavel_lambda,plateScale,lOverD=1.): # returns the FFT pixel locations equivalent to a certain pixel distance on the science image # baseline: distance in physical space in the pupil plane (in m) # imageShapeAlong1Axis: length of ...
max2 = 1.635 min2 = 2.233 max3 = 2.679 min3 = 3.238 max4 = 3.699
random_line_split
junk.py
# coding: utf-8 # In[ ]: # This notebook tests the making of pre-made masks for the Fizeau PSF FFT # created 2018 July 16 by E.S. # In[1]: import numpy as np import matplotlib.pyplot as plt import scipy import numpy.ma as ma import os.path from scipy import misc, signal, ndimage from astropy.io import fits from ...
# In[28]: # for loop over science images to take FFT and analyze it ampArray = [] framenumArray = [] for f in range(4249,11497): # full Altair dataset: 4249,11497 filename_str = stem+'lm_180507_'+str("{:0>6d}".format(f))+'.fits' if os.path.isfile(filename_str): # if FITS file exists in the first pla...
line_M1diam_pixOnFFT = findFFTloc(8.25,np.shape(sciImg)[0],wavel_lambda,plateScale) line_center2center_pixOnFFT = findFFTloc(14.4,np.shape(sciImg)[0],wavel_lambda,plateScale) line_edge2edge_pixOnFFT = findFFTloc(22.65,np.shape(sciImg)[0],wavel_lambda,plateScale) # define circles circR...
identifier_body
junk.py
# coding: utf-8 # In[ ]: # This notebook tests the making of pre-made masks for the Fizeau PSF FFT # created 2018 July 16 by E.S. # In[1]: import numpy as np import matplotlib.pyplot as plt import scipy import numpy.ma as ma import os.path from scipy import misc, signal, ndimage from astropy.io import fits from ...
# In[ ]: # how are FFTs affected by # 1. fringe movement # 2. changing visibility # 3. stuff listed in my table # ... and how good am I at finding the center of the PSF? # In[ ]: # based on the images, decide whether to move HPC in piston, tip, tilt # iterate? # maybe I don't want to move HPC in piston, because...
filename_str = stem+'lm_180507_'+str("{:0>6d}".format(f))+'.fits' if os.path.isfile(filename_str): # if FITS file exists in the first place print('Working on frame '+str("{:0>6d}".format(f))+' ...') image, header = fits.getdata(filename_str,0,header=True) # test:...
conditional_block
junk.py
# coding: utf-8 # In[ ]: # This notebook tests the making of pre-made masks for the Fizeau PSF FFT # created 2018 July 16 by E.S. # In[1]: import numpy as np import matplotlib.pyplot as plt import scipy import numpy.ma as ma import os.path from scipy import misc, signal, ndimage from astropy.io import fits from ...
(sciImg,wavel_lambda,plateScale): # sciImg: this is actually the FFT image, not the science detector image # wavel_lambda: wavelenth of the observation # plateScale: plate scale of the detector (asec/pixel) # make division lines separating different parts of the PSF line_M1diam_pixOnFFT = findF...
fftMask
identifier_name
dropdown.component.ts
/** * Created by Summer Yang(summer.yang@blockbi.com) * on 2017/2/7. */ import { Component, OnInit, Input, ViewChild, AfterViewInit, AfterViewChecked, ViewEncapsulation, ElementRef, Output, EventEmitter, OnChanges, SimpleChanges, Inject, Renderer } from '@angular/core'; import {DropdownSettings} from '../dropdow...
this.selectWarp = {}; this.toggleSelectService.emptyElement(); // this.doCloseDropDown.emit(); } /** * 返回的元素对象 * @param element */ doCallBackData(element: any) { this.selectWarp = element; } }
this.renderer.setElementClass(this.selectWarp.toggleSelectElement, 'hide', true); this.renderer.setElementClass(this.selectWarp.toggleInput, 'se-input-current', false);
identifier_body
dropdown.component.ts
/** * Created by Summer Yang(summer.yang@blockbi.com) * on 2017/2/7. */ import { Component, OnInit, Input, ViewChild, AfterViewInit, AfterViewChecked, ViewEncapsulation, ElementRef, Output, EventEmitter, OnChanges, SimpleChanges, Inject, Renderer } from '@angular/core'; import {DropdownSettings} from '../dropdow...
} if (data && !this.resetDropdown) { for (let key in data) { if (this.dropdownSettings.hasOwnProperty(key) && data.hasOwnProperty(key)) { this.dropdownSettings[key] = data[key]; } } this.resetDropdown = false; } }; get dropdownSettings() { return this._dr...
@ViewChild('toggleSelect') toggleSelect: ElementRef; @Input('dropdownSettings') set dropdownSettings(data: DropdownSettings) { if (data) { this._currentDropdownSettings = data;
random_line_split
dropdown.component.ts
/** * Created by Summer Yang(summer.yang@blockbi.com) * on 2017/2/7. */ import { Component, OnInit, Input, ViewChild, AfterViewInit, AfterViewChecked, ViewEncapsulation, ElementRef, Output, EventEmitter, OnChanges, SimpleChanges, Inject, Renderer } from '@angular/core'; import {DropdownSettings} from '../dropdow...
this.getCalcHeight = height; } } get optionModelArr() { return this._optionModelArr; } @Output('optionModelArrChange') optionModelArrChange = new EventEmitter<any>(); @ViewChild('toggleInput') toggleInput: ElementRef; @ViewChild('dropdownInput') dropdownInputComponent: DropdownInputComponen...
if (height) {
identifier_name
dropdown.component.ts
/** * Created by Summer Yang(summer.yang@blockbi.com) * on 2017/2/7. */ import { Component, OnInit, Input, ViewChild, AfterViewInit, AfterViewChecked, ViewEncapsulation, ElementRef, Output, EventEmitter, OnChanges, SimpleChanges, Inject, Renderer } from '@angular/core'; import {DropdownSettings} from '../dropdow...
); } if (this.reset || this.optionInit) { this.dropdownInputComponent.selectedOptions = this._selectedOptions; } if (this.reset || this.optionInit) { this.dropdownSelectComponent.selectedOptions = this._selectedOptions; } if (this.reset) { this.reset = false; ...
'Not Found'); } this._selectedOptions[j] = this.typeService.clone(selectedEle
conditional_block
Detector.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'Demo7.ui' # # Created by: PyQt5 UI code generator 5.15.1 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCo...
cv2.setMouseCallback('image',on_mouse) # cut_img = img[x0:abs(x1 - x0), y0:abs(y1 - y0)] # detection(cut_img) # cv2.waitKey(0) self.col = 0 # self.textEdit_4.setText(self.file) # self.textEdit_3.setText("{}".format(s1)) ...
ws1.write(0, 3, "裂纹在整个舌头中的占比 ") self.wb.save('Data.xls') def pb_1(self): global c, r, s1, img, x0, x1, y0, y1 while self.flag: c = 0 r = 0 s1 = 0 # self.textEdit_4.setText(self.file) # self.textEdit_3.setText("{}".forma...
identifier_body
Detector.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'Demo7.ui' # # Created by: PyQt5 UI code generator 5.15.1 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCo...
): # 按住左键拖曳 cv2.rectangle(img2, point1, (x, y), (0, 255, 0), 1) cv2.imshow('image', img2) elif event == cv2.EVENT_LBUTTONUP: # 左键释放 point2 = (x, y) cv2.rectangle(img2, point1, point2, (0, 0, 255), 1) cv2.imshow('image', img2) min_x = min(point1[0], point2[0])...
_LBUTTON
identifier_name
Detector.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'Demo7.ui' # # Created by: PyQt5 UI code generator 5.15.1 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCo...
mainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(mainWindow) self.statusbar.setObjectName("statusbar") mainWindow.setStatusBar(self.statusbar) self.retranslateUi(mainWindow) QtCore.QMetaObject.connectSlotsByName(mainWindow) self.pu...
# self.lb.raise_() mainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(mainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 958, 26)) self.menubar.setObjectName("menubar")
random_line_split
Detector.py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'Demo7.ui' # # Created by: PyQt5 UI code generator 5.15.1 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCo...
): if (image0[y, x] == 0): all = all + 1 img4 = img[:, :, 0] for y in range(0, image.shape[0], 1): for x in range(0, image.shape[1], 1): if (image[y, x] == 255): count = count + 1 getcontext().prec = 4 ...
for x in range(0, image0.shape[1], 1
conditional_block
admin_panel.py
import os import time import requests from aiogram.dispatcher import FSMContext from aiogram.dispatcher.filters import Text from aiogram.types import Message, ParseMode, ReplyKeyboardRemove, ContentType from Main import getLinks, CallbackQuery, ceil from Main.backend.validators import isValidFloat from Midd...
tent_types=[ContentType.ANY]) async def stateBroadcastAll(message: Message, state: FSMContext): q = str(message.text).replace('<', '').replace('>', '') await state.update_data(broadcast_msg=q) await message.answer(text="⭐Вот превью рассылки\n" "———————————————\n" ...
нена", reply_markup=nav.startMenu(message.from_user.id)) await state.finish() @dp.message_handler(IsAdmin(), state=AdminPanel.Broadcast, con
identifier_body
admin_panel.py
import os import time import requests from aiogram.dispatcher import FSMContext from aiogram.dispatcher.filters import Text from aiogram.types import Message, ParseMode, ReplyKeyboardRemove, ContentType from Main import getLinks, CallbackQuery, ceil from Main.backend.validators import isValidFloat from Midd...
amount"], s["transaction"]["id"])) except: await cb.message.answer(text='Ошибка при автопереводе: ' + str(s["message"])) return u_deposit = UsersDB.get(user_id, "deposit") # Chan...
thdraw_data")["card"], float(wd["amount"])) try: await cb.message.answer(text=MSG["AUTOPAY_INFO"].format(s["fields"]["account"], s["sum"]["
conditional_block
admin_panel.py
import os import time import requests from aiogram.dispatcher import FSMContext from aiogram.dispatcher.filters import Text from aiogram.types import Message, ParseMode, ReplyKeyboardRemove, ContentType from Main import getLinks, CallbackQuery, ceil from Main.backend.validators import isValidFloat from Midd...
return u_deposit = UsersDB.get(user_id, "deposit") # Change contractor deposit UsersDB.update(user_id, "deposit", u_deposit - float(wd["amount"])) # Change transaction status WithdrawsDB.update_withdraw(trans, "status", "DONE") # Notify contractor ...
identifier_name
admin_panel.py
import os import time import requests from aiogram.dispatcher import FSMContext from aiogram.dispatcher.filters import Text from aiogram.types import Message, ParseMode, ReplyKeyboardRemove, ContentType from Main import getLinks, CallbackQuery, ceil from Main.backend.validators import isValidFloat from Midd...
await message.answer(text="⭐Вот превью рассылки\n" "———————————————\n" f"{q}\n" "———————————————\n", reply_markup=nav.confirm_menu) @dp.message_handler(IsAdmin(), Text(NAV["BACK"])) async def...
random_line_split
dg_terraria.py
# DeLiGAN implementation for the Terraria dataset. # Based heavily on the code from Gurumurthy, Sarvadevabhatla, and Babu (2017). import argparse import time import numpy as np import theano as th import theano.tensor as T from theano.sandbox.rng_mrg import MRG_RandomStreams import lasagne import lasagne.layers as ll ...
"Iteration %d, time = %ds, loss_lab = %.4f, loss_unl = %.4f, train err= %.4f, test err = %.4f, gen_loss = %.4f, sigloss = %.4f" % ( epoch, time.time() - begin, loss_lab, loss_unl, train_err, test_err, genloss, sigmloss)) sys.stdout.flush() a.append([epoch, loss_lab, loss_unl, train_err, test_err...
random_line_split
dg_terraria.py
# DeLiGAN implementation for the Terraria dataset. # Based heavily on the code from Gurumurthy, Sarvadevabhatla, and Babu (2017). import argparse import time import numpy as np import theano as th import theano.tensor as T from theano.sandbox.rng_mrg import MRG_RandomStreams import lasagne import lasagne.layers as ll ...
plotting.plt.close('all')
NNdiff = np.sum( np.sum(np.sum(np.square(np.expand_dims(sample_x, axis=1) - np.expand_dims(trainx, axis=0)), axis=2), axis=2), axis=2) NN = trainx[np.argmin(NNdiff, axis=1)] NN = np.transpose(NN[:100], (0, 2, 3, 1)) NN_tile = plotting.img_tile(NN, aspect_ratio=1.0,...
conditional_block
builtin_fn_misc.go
package eval // Misc builtin functions. import ( "errors" "fmt" "math/rand" "net" "os" "sync" "time" "unicode/utf8" "src.elv.sh/pkg/diag" "src.elv.sh/pkg/eval/errs" "src.elv.sh/pkg/eval/vals" "src.elv.sh/pkg/parse" ) var ( ErrNegativeSleepDuration = errors.New("sleep duration must be >= zero") ErrInva...
unique names for each source passed to eval. var ( evalCount int evalCountMutex sync.Mutex ) func nextEvalCount() int { evalCountMutex.Lock() defer evalCountMutex.Unlock() evalCount++ return evalCount } //elvdoc:fn use-mod // // ```elvish // use-mod $use-spec // ``` // // Imports a module, and outputs the ...
k of eval") errCb := opts.OnEnd.Call(newFm, []interface{}{newNs}, NoOpts) if exc == nil { return errCb } } return exc } // Used to generate
conditional_block
builtin_fn_misc.go
package eval // Misc builtin functions. import ( "errors" "fmt" "math/rand" "net" "os" "sync" "time" "unicode/utf8" "src.elv.sh/pkg/diag" "src.elv.sh/pkg/eval/errs" "src.elv.sh/pkg/eval/vals" "src.elv.sh/pkg/parse" ) var ( ErrNegativeSleepDuration = errors.New("sleep duration must be >= zero") ErrInva...
lOpts, code string) error { src := parse.Source{Name: fmt.Sprintf("[eval %d]", nextEvalCount()), Code: code} ns := opts.Ns if ns == nil { ns = CombineNs(fm.up, fm.local) } // The stacktrace already contains the line that calls "eval", so we pass // nil as the second argument. newNs, exc := fm.Eval(src, nil, ns...
*Frame, opts eva
identifier_name
builtin_fn_misc.go
package eval // Misc builtin functions. import ( "errors" "fmt" "math/rand" "net" "os" "sync" "time" "unicode/utf8" "src.elv.sh/pkg/diag" "src.elv.sh/pkg/eval/errs" "src.elv.sh/pkg/eval/vals" "src.elv.sh/pkg/parse" ) var ( ErrNegativeSleepDuration = errors.New("sleep duration must be >= zero") ErrInva...
//elvdoc:fn nop // // ```elvish // nop &any-opt= $value... // ``` // // Accepts arbitrary arguments and options and does exactly nothing. // // Examples: // // ```elvish-transcript // ~> nop // ~> nop a b c // ~> nop &k=v // ``` // // Etymology: Various languages, in particular NOP in // [assembly languages](https://...
{ addBuiltinFns(map[string]interface{}{ "nop": nop, "kind-of": kindOf, "constantly": constantly, // Introspection "call": call, "resolve": resolve, "eval": eval, "use-mod": useMod, "deprecate": deprecate, // Time "sleep": sleep, "time": timeCmd, "-ifaddrs": _ifaddrs, }) ...
identifier_body
builtin_fn_misc.go
package eval // Misc builtin functions. import ( "errors" "fmt" "math/rand" "net" "os" "sync" "time" "unicode/utf8" "src.elv.sh/pkg/diag" "src.elv.sh/pkg/eval/errs" "src.elv.sh/pkg/eval/vals" "src.elv.sh/pkg/parse" ) var ( ErrNegativeSleepDuration = errors.New("sleep duration must be >= zero") ErrInva...
// ~> var f = {|a &k1=v1 &k2=v2| put $a $k1 $k2 } // ~> call $f [foo] [&k1=bar] // ▶ foo // ▶ bar // ▶ v2 // ``` func call(fm *Frame, fn Callable, argsVal vals.List, optsVal vals.Map) error { args := make([]interface{}, 0, argsVal.Len()) for it := argsVal.Iterator(); it.HasElem(); it.Next() { args = append(args, i...
random_line_split
Executor.py
import os import sys import subprocess from datetime import datetime import logging from threading import Thread import json import re from time import sleep from ImageDB import ImageDB from astropy.visualization.scripts.fits2bitmap import fits2bitmap path = os.path log = logging.getLogger(__name__) class Executor(ob...
status['cmdoutput'] += line except FileNotFoundError: status['cmdoutput'] = "" # info for the lastimg to update status['lastimg'] = self.lastimgpath try: status['lastimg_timestamp'] = path.getmtime(self.lastimgpath) except ...
if not line.endswith('\r'):
random_line_split
Executor.py
import os import sys import subprocess from datetime import datetime import logging from threading import Thread import json import re from time import sleep from ImageDB import ImageDB from astropy.visualization.scripts.fits2bitmap import fits2bitmap path = os.path log = logging.getLogger(__name__) class Executor(ob...
(self, fitsfile, seconds=5): """ Expose the CCD and read a new image to `fitsfile` """ # make sure the file has good name if not fitsfile.endswith('.fits'): fitsfile += '.fits' tstamp = datetime.now().strftime('_%y%m%d-%H%M') match = re.match(r'.*(_\d\d\d\d\d\d-\d\d\d...
Expose
identifier_name
Executor.py
import os import sys import subprocess from datetime import datetime import logging from threading import Thread import json import re from time import sleep from ImageDB import ImageDB from astropy.visualization.scripts.fits2bitmap import fits2bitmap path = os.path log = logging.getLogger(__name__) class Executor(ob...
# methods to run exectuables def _run(self, args, cwd=None, env=None, logmode='wb'): """ Run the commands in `args` in a subprocess """ args = tuple(str(arg) for arg in args) if self.process and self.process.poll() is None: raise RuntimeError("A process is already running"...
if kill: self.process.kill() else: self.process.terminate() with open(self.logfilename, 'a') as f: print("!!!!!! process killed by user !!!!!!!", file=f)
conditional_block
Executor.py
import os import sys import subprocess from datetime import datetime import logging from threading import Thread import json import re from time import sleep from ImageDB import ImageDB from astropy.visualization.scripts.fits2bitmap import fits2bitmap path = os.path log = logging.getLogger(__name__) class Executor(ob...
""" Run CCDD processes and keep track of status """ def __init__(self, config=None, **kwargs): """ Args: config (dict): dictionary of config settings. will be merged with any other provided kwargs. valid keys are: CCDDRONEPATH (str): path to top-level...
identifier_body
UTM.py
import time import numpy as np import sys import math as m import pandas as pd from pyproj import Proj, transform, Transformer, _datadir, datadir from com.sca.hem4.log.Logger import Logger utmzone = 'utmzone'; utme = 'utme'; utmn = 'utmn'; utmz = 'utmz'; # Caches for projections and transformers...avoiding the cont...
else: hemi = "N" if hemi == "N": epsg = 'epsg:326'+str(zonetxt) else: epsg = 'epsg:327'+str(zonetxt) transformer = UTM.getTransformer('epsg:4326', epsg) # Use the cached transformer to perform the transformation more quickly! ...
hemi = "S"
conditional_block
UTM.py
import time import numpy as np import sys import math as m import pandas as pd from pyproj import Proj, transform, Transformer, _datadir, datadir from com.sca.hem4.log.Logger import Logger utmzone = 'utmzone'; utme = 'utme'; utmn = 'utmn'; utmz = 'utmz'; # Caches for projections and transformers...avoiding the cont...
(epsg1, epsg2): key = epsg1 + epsg2 if key in transformers: transformer = transformers[key] else: if epsg1 in projections: p1 = projections[epsg1] else: p1 = Proj(init = epsg1) projections[epsg1] = p1 ...
getTransformer
identifier_name
UTM.py
import time import numpy as np import sys import math as m import pandas as pd from pyproj import Proj, transform, Transformer, _datadir, datadir from com.sca.hem4.log.Logger import Logger utmzone = 'utmzone'; utme = 'utme'; utmn = 'utmn'; utmz = 'utmz'; # Caches for projections and transformers...avoiding the cont...
@staticmethod def getBand(row): # returns the hemisphere (N or S) portion of a zone string; if none return N N_or_S = "N" if "S" in row: N_or_S = "S" return N_or_S @staticmethod def zone2use(el_df): """ Create a common UTM Zone for th...
hemilist = ['N', 'S'] if any(elem in zonestr for elem in hemilist): return zonestr[:-1] else: return zonestr
identifier_body
UTM.py
import time import numpy as np import sys import math as m import pandas as pd from pyproj import Proj, transform, Transformer, _datadir, datadir from com.sca.hem4.log.Logger import Logger utmzone = 'utmzone'; utme = 'utme'; utmn = 'utmn'; utmz = 'utmz'; # Caches for projections and transformers...avoiding the cont...
else: min_utmbl = "N" if min_utmzu == 0: utmzone = min_utmzl else: if min_utmzl == 0: utmzone = min_utmzu else: utmzone = min(min_utmzu, min_utmzl) hemi = min(min_utmbu, min_utmbl) if utmzo...
lat_df = el_df[["lat"]].loc[el_df["location_type"] == "L"] if lat_df.shape[0] > 0 and lat_df["lat"].min() < 0: min_utmbl = "S"
random_line_split
trace.go
// Licensed to Apache Software Foundation (ASF) under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright // ownership. Apache Software Foundation (ASF) licenses this file to you under // the Apache License, Version 2.0 (the "Li...
return } s.setShardNum(e) s.log.Info(). Str("action", databasev1.Action_name[int32(e.Action)]). Uint64("shardID", e.Shard.Id). Msg("received a shard e") return } func (s *shardInfo) setShardNum(eventVal *databasev1.ShardEvent) { s.RWMutex.Lock() defer s.RWMutex.Unlock() idx := eventVal.Shard.Series.GetN...
func (s *shardInfo) Rev(message bus.Message) (resp bus.Message) { e, ok := message.Data().(*databasev1.ShardEvent) if !ok { s.log.Warn().Msg("invalid e data type")
random_line_split
trace.go
// Licensed to Apache Software Foundation (ASF) under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright // ownership. Apache Software Foundation (ASF) licenses this file to you under // the Apache License, Version 2.0 (the "Li...
(seriesMeta string) []int { s.RWMutex.RLock() defer s.RWMutex.RUnlock() return s.seriesEventsMap[seriesMeta] } func (s *Server) PreRun() error { s.log = logger.GetLogger("liaison-grpc") s.shardInfo.log = s.log s.seriesInfo.log = s.log err := s.repo.Subscribe(event.TopicShardEvent, s.shardInfo) if err != nil { ...
FieldIndexCompositeSeriesID
identifier_name
trace.go
// Licensed to Apache Software Foundation (ASF) under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright // ownership. Apache Software Foundation (ASF) licenses this file to you under // the Apache License, Version 2.0 (the "Li...
func (s *shardInfo) shardNum(idx string) uint32 { s.RWMutex.RLock() defer s.RWMutex.RUnlock() return s.shardEventsMap[idx] } type seriesInfo struct { log *logger.Logger seriesEventsMap map[string][]int sync.RWMutex } func (s *seriesInfo) Rev(message bus.Message) (resp bus.Message) { e, ok := mess...
{ s.RWMutex.Lock() defer s.RWMutex.Unlock() idx := eventVal.Shard.Series.GetName() + "-" + eventVal.Shard.Series.GetGroup() if eventVal.Action == databasev1.Action_ACTION_PUT { s.shardEventsMap[idx] = eventVal.Shard.Total } else if eventVal.Action == databasev1.Action_ACTION_DELETE { delete(s.shardEventsMap, i...
identifier_body
trace.go
// Licensed to Apache Software Foundation (ASF) under one or more contributor // license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright // ownership. Apache Software Foundation (ASF) licenses this file to you under // the Apache License, Version 2.0 (the "Li...
} func (s *shardInfo) shardNum(idx string) uint32 { s.RWMutex.RLock() defer s.RWMutex.RUnlock() return s.shardEventsMap[idx] } type seriesInfo struct { log *logger.Logger seriesEventsMap map[string][]int sync.RWMutex } func (s *seriesInfo) Rev(message bus.Message) (resp bus.Message) { e, ok := me...
{ delete(s.shardEventsMap, idx) }
conditional_block
raft.go
package raft // // this is an outline of the API that raft must expose to // the service (or tester). see comments below for // each of these functions for more details. // // rf = Make(...) // create a new Raft server. // rf.Start(command interface{}) (index, term, isleader) // start agreement on a new log entry ...
} func (rf *Raft) becomeLeader() { lastLogIndex := 0 rf.mu.Lock() rf.role = LEADER lastLogIndex = rf.GetLastLogEntryWithLock().Index for i := 0; i < len(rf.peers); i++ { rf.nextIndex[i] = lastLogIndex + 1 rf.matchIndex[i] = 0 } for i := rf.commitIndex + 1; i <= rf.GetLastLogEntryWithLock().Index; i++ { r...
{ for i := 0; i < len(rf.peers); i++ { wg.Add(1) go func(index int, request AppendEntriesRequest, reply AppendEntriesResponse) { ok := rf.sendAppendEntries(index, &request, &reply) if ok { rf.handleAppendEntriesResponse(request, reply) } wg.Done() }(i, request, reply) } time.Sleep(t...
conditional_block
raft.go
package raft // // this is an outline of the API that raft must expose to // the service (or tester). see comments below for // each of these functions for more details. // // rf = Make(...) // create a new Raft server. // rf.Start(command interface{}) (index, term, isleader) // start agreement on a new log entry ...
// e.Encode(rf.xxx) // e.Encode(rf.yyy) // data := w.Bytes() // rf.persister.SaveRaftState(data) } // // restore previously persisted state. // func (rf *Raft) readPersist(data []byte) { if data == nil || len(data) < 1 { // bootstrap without any state? return } // Your code here (2C). // Example: // r := by...
// Example: // w := new(bytes.Buffer) // e := labgob.NewEncoder(w)
random_line_split
raft.go
package raft // // this is an outline of the API that raft must expose to // the service (or tester). see comments below for // each of these functions for more details. // // rf = Make(...) // create a new Raft server. // rf.Start(command interface{}) (index, term, isleader) // start agreement on a new log entry ...
func (rf *Raft) handleAppendEntriesResponse(request AppendEntriesRequest, reply AppendEntriesResponse) { rf.updateTerm(reply.Term) rf.mu.Lock() if request.term != rf.currentTerm { rf.mu.Unlock() } rf.mu.Unlock() } func (rf *Raft) heartBeatTimer() { for rf.Role() == LEADER { for i := 0; i < len(rf.peers); i...
{ ok := rf.peers[server].Call("Raft.AppendEntries", args, reply) return ok }
identifier_body
raft.go
package raft // // this is an outline of the API that raft must expose to // the service (or tester). see comments below for // each of these functions for more details. // // rf = Make(...) // create a new Raft server. // rf.Start(command interface{}) (index, term, isleader) // start agreement on a new log entry ...
(server int, args *RequestVoteArgs, reply *RequestVoteReply) bool { ok := rf.peers[server].Call("Raft.RequestVote", args, reply) return ok } func (rf *Raft) handleRequestVoteResponse(request RequestVoteArgs, reply RequestVoteReply) bool { rf.updateTerm(reply.Term) rf.mu.Lock() if rf.currentTerm != request.Term { ...
sendRequestVote
identifier_name
waxxedit.js
//javascript code //author aming //email:254930120@qq.com //source: https://www.52aixuexi.com //Date 2020/10/05 13:23 var waxxedit = {}; waxxedit.name = "waxxedit"; waxxedit.description = "my first javascript editor"; waxxedit.version = "1.0.1"; waxxedit.author = "aming"; waxxedit.editor = { contentObj:null, toolba...
//upload:"upload" }, configuration:function(editor_id,textareaId,width,height,color){ wedit.configs.editor_id = editor_id || this.configs.editor_id; wedit.configs.textareaId = textareaId || this.configs.textareaId; wedit.configs.width = width || this.configs.width; wedit.configs.height = height || this.co...
//h4:"h4",
random_line_split
waxxedit.js
//javascript code //author aming //email:254930120@qq.com //source: https://www.52aixuexi.com //Date 2020/10/05 13:23 var waxxedit = {}; waxxedit.name = "waxxedit"; waxxedit.description = "my first javascript editor"; waxxedit.version = "1.0.1"; waxxedit.author = "aming"; waxxedit.editor = { contentObj:null, toolba...
== 'h2'){ ele.className = wedit.tbarMenu.h2; }else if(type == 'h3'){ ele.className = wedit.tbarMenu.h3; }else if(type == 'h4'){ ele.className = wedit.tbarMenu.h4; }else if(type == 'B'){ ele.className = wedit.tbarMenu.B; }else if(type == 'I'){ ele.className = wedit.tbarMenu.I; }else i...
ele.className = wedit.tbarMenu.h1; }else if(type
identifier_body
waxxedit.js
//javascript code //author aming //email:254930120@qq.com //source: https://www.52aixuexi.com //Date 2020/10/05 13:23 var waxxedit = {}; waxxedit.name = "waxxedit"; waxxedit.description = "my first javascript editor"; waxxedit.version = "1.0.1"; waxxedit.author = "aming"; waxxedit.editor = { contentObj:null, toolba...
){ ele.className = wedit.tbarMenu.h1; }else if(type == 'h2'){ ele.className = wedit.tbarMenu.h2; }else if(type == 'h3'){ ele.className = wedit.tbarMenu.h3; }else if(type == 'h4'){ ele.className = wedit.tbarMenu.h4; }else if(type == 'B'){ ele.className = wedit.tbarMenu.B; }else if(type...
if(type == 'h1'
identifier_name
index.funcs.js
/* | layout.blade.php functions | for index only */ /*!!! TODO */ //make OOP - maybe next iteration //CACHE jSON //get square size from flickr //use carouFredSel method to resize (function() { /*cache DOM vars*/ var list = $("#list"), list_img = $(".listImg"), carousel = $("#carousel"), carousel_li = $("#ca...
(num2Scroll, dir2Scroll) { carousel.carouFredSel({ align : "center", width : "100%", onWindowResize : 'throttle', items : Math.round(window.innerWidth/200), scroll : window.num2Scroll, direction : window.dir2Scroll, swipe : { onTouch : true }, pr...
setCarousel
identifier_name
index.funcs.js
/* | layout.blade.php functions | for index only */ /*!!! TODO */ //make OOP - maybe next iteration //CACHE jSON //get square size from flickr //use carouFredSel method to resize (function() { /*cache DOM vars*/ var list = $("#list"), list_img = $(".listImg"), carousel = $("#carousel"), carousel_li = $("#ca...
getFeed(http, obj, tmp, html, id); //ERROR: Can be tested by commenting appendDOM(html) line in getFeed setTimeout(function() { if (!success) { html = '<h2 class="to-center">Timed out!</h2><blockquote>The request for ' +id.substr(0,1).toUpperCase()+id.substr(1)+ ' data has timed out. Please try again late...
{ //console.log(http); //!!!cache? Would need to use local storage or DB or jquery-json.2.4.0 if(http !== '') { $.ajax({ dataType: "jsonp", jsonp: "callback", url: http, success: function(data) { console.log("Data received via test: " + JSON.stringify(data)); if(id==="coderb...
identifier_body
index.funcs.js
/* | layout.blade.php functions | for index only */ /*!!! TODO */ //make OOP - maybe next iteration //CACHE jSON //get square size from flickr //use carouFredSel method to resize (function() { /*cache DOM vars*/ var list = $("#list"), list_img = $(".listImg"), carousel = $("#carousel"), carousel_li = $("#ca...
if(url === '?state=txt-list') { menu_text.trigger('click'); } if(window.history && history.pushState) { $(window).on('popstate', function(e, url) { if(e.originalEvent.state && e.originalEvent.state === 'graphics') { menu_graphics.trigger('click'); } if(e.originalEvent.state && e.originalEvent.stat...
{ menu_graphics.trigger('click'); }
conditional_block
index.funcs.js
/* | layout.blade.php functions | for index only */ /*!!! TODO */ //make OOP - maybe next iteration //CACHE jSON //get square size from flickr //use carouFredSel method to resize (function() { /*cache DOM vars*/ var list = $("#list"), list_img = $(".listImg"), carousel = $("#carousel"), carousel_li = $("#ca...
url: http, success: function(data) { console.log("Data received via test: " + JSON.stringify(data)); if(id==="coderbits") { var unique=0, total=0, content={"name":"", "amount":0, "img":""}; $.each(eval(obj), function(i,item) { if(item.earned) { content.name=item.name...
dataType: "jsonp", jsonp: "callback",
random_line_split
backend.rs
// This file is part of Substrate. // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // 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.a...
(&self, hash: Block::Hash) -> Result<Block::Header> { self.header(hash)? .ok_or_else(|| Error::UnknownBlock(format!("Expect header: {}", hash))) } /// Convert an arbitrary block ID into a block number. Returns `UnknownBlock` error if block is /// not found. fn expect_block_number_from_id(&self, id: &BlockId<B...
expect_header
identifier_name
backend.rs
// This file is part of Substrate. // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // 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.a...
, Ok(None) | Err(_) => { missing_blocks.push(BlockId::<Block>::Number(parent_number)); break }, } route_head = meta.parent; }, Err(_e) => { missing_blocks.push(BlockId::<Block>::Hash(route_head)); break }, } } } if !missing_blocks.is_empt...
{ break }
conditional_block
backend.rs
// This file is part of Substrate. // Copyright (C) Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // 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.a...
Unknown, }
pub enum BlockStatus { /// Already in the blockchain. InChain, /// Not in the queue or the blockchain.
random_line_split
webpack.config.js
const fs = require("fs"); const path = require("path"); const IgnorePlugin = require("webpack/lib/IgnorePlugin"); const ModuleFederationPlugin = require("webpack/lib/container/ModuleFederationPlugin"); const HtmlWebpackPlugin = require("html-webpack-plugin"); const TerserPlugin = require("terser-webpack-plugin"); const...
], }, sourceMap: true, }, }, ].filter(Boolean); if (preProcessor) { loaders.push( { loader: require.resolve("resolve-url-loader"), options: { sourceMap: true, root: paths.appSrc, }, }, { loader: require.res...
}), postcssNormalize(),
random_line_split
webpack.config.js
const fs = require("fs"); const path = require("path"); const IgnorePlugin = require("webpack/lib/IgnorePlugin"); const ModuleFederationPlugin = require("webpack/lib/container/ModuleFederationPlugin"); const HtmlWebpackPlugin = require("html-webpack-plugin"); const TerserPlugin = require("terser-webpack-plugin"); const...
return loaders; }; module.exports = { mode: isDevelopment ? "development" : "production", bail: !isDevelopment, devtool: isDevelopment ? "cheap-module-source-map" : "source-map", devServer: { contentBase: paths.appBuild, port: 3002, }, entry: paths.appIndexJs, output: { path: paths.appBuil...
{ loaders.push( { loader: require.resolve("resolve-url-loader"), options: { sourceMap: true, root: paths.appSrc, }, }, { loader: require.resolve(preProcessor), options: { sourceMap: true, }, } ); }
conditional_block
retrieval.py
import codecs import re import io import mimetypes import os import sys import tempfile import operator import subprocess import importlib import time import logging import dateutil.parser from typing import Tuple, List, Dict from sys import platform from chardet import detect from pathlib import Path import boto3 imp...
if list(filter(lambda x: x['jobName'].startswith( f'{source_name}-'), jobs)): logger.info("Deltas: Ongoing batch jobs relating to source found. " "Abandoning deltas generation.") return True return False def generate_deltas(env: str, latest_...
logger.info("Deltas: Ongoing batch jobs relating to source found. " "Abandoning deltas generation.") return True
conditional_block
retrieval.py
import codecs import re import io import mimetypes import os import sys import tempfile import operator import subprocess import importlib import time import logging import dateutil.parser from typing import Tuple, List, Dict from sys import platform from chardet import detect from pathlib import Path import boto3 imp...
def upload_to_s3( file_name, s3_object_key, env, source_id, upload_id, api_headers, cookies, bucket=OUTPUT_BUCKET): try: s3_client.upload_file( file_name, bucket, s3_object_key) logger.info( f"Uploaded source content to s3://{bucket}/{s3_object_key}") ...
e, env, upload_error, source_id, upload_id, api_headers, cookies)
random_line_split
retrieval.py
import codecs import re import io import mimetypes import os import sys import tempfile import operator import subprocess import importlib import time import logging import dateutil.parser from typing import Tuple, List, Dict from sys import platform from chardet import detect from pathlib import Path import boto3 imp...
(date_str: str) -> datetime: """Isolate functionality to facilitate easier mocking""" return dateutil.parser.parse(date_str) def retrieve_content(env, source_id, upload_id, url, source_format, api_headers, cookies, chunk_bytes=CSV_CHUNK_BYTES, tempdir=TEMP_PATH, uploa...
parse_datetime
identifier_name
retrieval.py
import codecs import re import io import mimetypes import os import sys import tempfile import operator import subprocess import importlib import time import logging import dateutil.parser from typing import Tuple, List, Dict from sys import platform from chardet import detect from pathlib import Path import boto3 imp...
def retrieve_content(env, source_id, upload_id, url, source_format, api_headers, cookies, chunk_bytes=CSV_CHUNK_BYTES, tempdir=TEMP_PATH, uploads_history={}, bucket=OUTPUT_BUCKET): """ Retrieves and locally persists the content at the provided URL. "...
"""Isolate functionality to facilitate easier mocking""" return dateutil.parser.parse(date_str)
identifier_body
wal.go
package wal import ( "bufio" "encoding/binary" "fmt" "hash" "hash/crc32" "io" "io/ioutil" "os" "path/filepath" "strconv" "strings" "sync" "sync/atomic" "time" "github.com/dustin/go-humanize" "github.com/getlantern/errors" "github.com/getlantern/golog" "github.com/golang/snappy" ) const ( sentinel ...
func sequenceToFilename(seq int64) string { return fmt.Sprintf("%019d", seq) } func sequenceToTime(seq int64) time.Time { ts := seq * 1000 s := ts / int64(time.Second) ns := ts % int64(time.Second) return time.Unix(s, ns) } func filenameToSequence(filename string) int64 { _, filePart := filepath.Split(filenam...
{ return ts.UnixNano() / 1000 }
identifier_body
wal.go
package wal import ( "bufio" "encoding/binary" "fmt" "hash" "hash/crc32" "io" "io/ioutil" "os" "path/filepath" "strconv" "strings" "sync" "sync/atomic" "time" "github.com/dustin/go-humanize" "github.com/getlantern/errors" "github.com/getlantern/golog" "github.com/golang/snappy" ) const ( sentinel ...
if length > sentinel { return length, nil } err := r.advance() if err != nil { return 0, err } } } func (r *Reader) readData(length int) ([]byte, error) { buf := r.bufferSource() // Grow buffer if necessary if cap(buf) < length { buf = make([]byte, length) } // Set buffer length buf = buf[...
{ if atomic.LoadInt32(&r.stopped) == 1 { return 0, io.EOF } if atomic.LoadInt32(&r.closed) == 1 { return 0, io.ErrUnexpectedEOF } n, err := r.reader.Read(headBuf[read:]) read += n r.position += int64(n) if err != nil && err.Error() == "EOF" && read < 4 { if r.wal.hasMovedBeyond(r.fil...
conditional_block
wal.go
package wal import ( "bufio" "encoding/binary" "fmt" "hash" "hash/crc32" "io" "io/ioutil" "os" "path/filepath" "strconv" "strings" "sync" "sync/atomic" "time" "github.com/dustin/go-humanize" "github.com/getlantern/errors" "github.com/getlantern/golog" "github.com/golang/snappy" ) const ( sentinel ...
r.reader = bufio.NewReaderSize(r.file, defaultFileBuffer) } if r.position > 0 { // Read to the correct offset // Note - we cannot just seek on the file because the data is compressed and // the recorded position does not correspond to a file offset. _, seekErr := io.CopyN(ioutil.Discard, r.reader, r.positio...
random_line_split
wal.go
package wal import ( "bufio" "encoding/binary" "fmt" "hash" "hash/crc32" "io" "io/ioutil" "os" "path/filepath" "strconv" "strings" "sync" "sync/atomic" "time" "github.com/dustin/go-humanize" "github.com/getlantern/errors" "github.com/getlantern/golog" "github.com/golang/snappy" ) const ( sentinel ...
() { defer close(wal.backlogFinished) for bufs := range wal.backlog { if err := wal.doWrite(bufs...); err != nil { wal.log.Errorf("Error writing to WAL!: %v", err) } } } func (wal *WAL) doWrite(bufs ...[]byte) error { wal.mx.Lock() defer wal.mx.Unlock() length := 0 for _, b := range bufs { blen := len...
writeAsync
identifier_name
dirutils.js
// -------------- // myjs // -------------- // By Mike Gieson // www.gieson.com /** * A collection of utilities for manipulating directories syncronously. * * @module dirutils * @package myfs */ var fs = require('fs'); var path = require('./npath'); // 1. makedir ("/foo/bar/qwer") <-- not exist // | 2...
; /** * Recursively removes a folder and all of it's sub-folders as well. * * @method removedir * @private * @param {string} who - The path to the folder * @param {boolean} dryRun - Prevents actual deletion, but still allows the return to return the list of items that "will" be deleted. * * @return {ar...
{ var removed = []; if( exists(who) ) { var list = readdir(who, null, true); var files = list.files; for(var i=files.length; i--;){ var file = files[i]; removed.push(file); if( ! dryRun ){ fs.unlinkSync(file); } } var dirs = list.dirs.sort(); // should be...
identifier_body
dirutils.js
// -------------- // myjs // -------------- // By Mike Gieson // www.gieson.com /** * A collection of utilities for manipulating directories syncronously. * * @module dirutils * @package myfs */ var fs = require('fs'); var path = require('./npath'); // 1. makedir ("/foo/bar/qwer") <-- not exist // | 2...
(who, dryRun) { var removed = []; if( exists(who) ) { var list = readdir(who, null, true); var files = list.files; for(var i=files.length; i--;){ var file = files[i]; removed.push(file); if( ! dryRun ){ fs.unlinkSync(file); } } var dirs = list.dirs.sort()...
emptydir
identifier_name
dirutils.js
// -------------- // myjs // -------------- // By Mike Gieson // www.gieson.com /** * A collection of utilities for manipulating directories syncronously. * * @module dirutils * @package myfs */ var fs = require('fs'); var path = require('./npath'); // 1. makedir ("/foo/bar/qwer") <-- not exist // | 2...
} else { store.files.push(file); } } } } return store; } /** * Copies the entire folder's heirarchy folder from one location to another. If the other location doesn't exists, it will be constructed. * * @method copydir * @private * @param {string}...
{ store.files.push(file); }
conditional_block
dirutils.js
// -------------- // myjs // -------------- // By Mike Gieson // www.gieson.com /** * A collection of utilities for manipulating directories syncronously. * * @module dirutils * @package myfs */ var fs = require('fs'); var path = require('./npath'); // 1. makedir ("/foo/bar/qwer") <-- not exist // | 2...
if( ! store ){ store = { dirs: [], files: [] }; } var hasFilterFunction = typeof filter == 'function'; var files = fs.readdirSync(from); var len = files.length; for(var i=0; i<len; i++){ var file = path.join(from, files[i]); var stats = false; // set this value otherwise a failing try will pickup...
function readdir(from, filter, recursive, store){
random_line_split
model_sql_test.go
package db_test import ( "context" "crypto/md5" "crypto/rand" "database/sql/driver" "encoding/hex" "encoding/json" "fmt" "os" "strings" "testing" "time" "github.com/caiguanhao/furk/db" "github.com/caiguanhao/furk/db/gopg" "github.com/caiguanhao/furk/db/pgx" "github.com/caiguanhao/furk/db/pq" "github.c...
(src interface{}) error { if value, ok := src.(string); ok { *p = password{ hashed: value, } } return nil } // used in gopg func (p *password) ScanValue(rd gopg.TypesReader, n int) error { value, err := gopg.TypesScanString(rd, n) if err == nil { *p = password{ hashed: value, } } return err } fun...
Scan
identifier_name
model_sql_test.go
package db_test import ( "context" "crypto/md5" "crypto/rand" "database/sql/driver" "encoding/hex" "encoding/json" "fmt" "os" "strings" "testing" "time" "github.com/caiguanhao/furk/db" "github.com/caiguanhao/furk/db/gopg" "github.com/caiguanhao/furk/db/pgx" "github.com/caiguanhao/furk/db/pq" "github.c...
func (t *test) Bool(name string, b bool) { t.Helper() if b { t.Logf("%s test passed", name) } else { t.Errorf("%s test failed, got %t", name, b) } } func (t *test) String(name, got, expected string) { t.Helper() if got == expected { t.Logf("%s test passed", name) } else { t.Errorf("%s test failed, got...
{ t := test{_t} o := db.NewModel(order{}) o.SetConnection(conn) o.SetLogger(logger.StandardLogger) // drop table err := o.NewSQLWithValues(o.DropSchema()).Execute() if err != nil { t.Fatal(err) } // create table err = o.NewSQLWithValues(o.Schema()).Execute() if err != nil { t.Fatal(err) } randomByt...
identifier_body
model_sql_test.go
package db_test import ( "context" "crypto/md5" "crypto/rand" "database/sql/driver" "encoding/hex" "encoding/json" "fmt" "os" "strings" "testing" "time" "github.com/caiguanhao/furk/db" "github.com/caiguanhao/furk/db/gopg" "github.com/caiguanhao/furk/db/pgx" "github.com/caiguanhao/furk/db/pq" "github.c...
// create table err = o.NewSQLWithValues(o.Schema()).Execute() if err != nil { t.Fatal(err) } randomBytes := make([]byte, 10) if _, err := rand.Read(randomBytes); err != nil { t.Fatal(err) } tradeNo := hex.EncodeToString(randomBytes) totalAmount, _ := decimal.NewFromString("12.34") createInput := strin...
{ t.Fatal(err) }
conditional_block
model_sql_test.go
package db_test import ( "context" "crypto/md5" "crypto/rand" "database/sql/driver" "encoding/hex" "encoding/json" "fmt" "os" "strings" "testing" "time" "github.com/caiguanhao/furk/db" "github.com/caiguanhao/furk/db/gopg" "github.com/caiguanhao/furk/db/pgx" "github.com/caiguanhao/furk/db/pq" "github.c...
type ( echoContext struct{} ) func (c echoContext) Bind(i interface{}) error { if o, ok := i.(*order); ok { o.Id = 2 o.Status = "foo" } return nil }
t.Logf("%s test passed", name) } else { t.Errorf("%s test failed, got %d", name, got) } }
random_line_split
land_ocean_ratio.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue May 18 17:35:24 2021 @author: huw """ import concurrent.futures import matplotlib.pyplot as plt import numpy as np import os import pandas as pd import pytesseract from itertools import repeat from PIL import Image from osgeo import gdal, osr import car...
(names, im_left, im_top, im_right, im_bottom): with concurrent.futures.ProcessPoolExecutor() as executor: processed_image = executor.map(CropImage, names, repeat(im_left), repeat(im_top), ...
MultiProcessCrop
identifier_name
land_ocean_ratio.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue May 18 17:35:24 2021 @author: huw """ import concurrent.futures import matplotlib.pyplot as plt import numpy as np import os import pandas as pd import pytesseract from itertools import repeat from PIL import Image from osgeo import gdal, osr import car...
elif type(box_perimeter_fill_value) == int: land_percentage = round((land_pixels/image_pixels)*100, 4) ocean_percentage = round((ocean_pixels/image_pixels)*100, 4) # land_percentage = round((land_pixels/image_pixels)*100, 4) # ocean_percentage = round((ocean_pixels/image_pixels)*100, 4) land_ocean_...
land_percentage = round((land_pixels/non_nan_pixels)*100, 4) ocean_percentage = round((ocean_pixels/non_nan_pixels)*100, 4)
conditional_block
land_ocean_ratio.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue May 18 17:35:24 2021 @author: huw """ import concurrent.futures import matplotlib.pyplot as plt import numpy as np import os import pandas as pd import pytesseract from itertools import repeat from PIL import Image from osgeo import gdal, osr import car...
land_ocean_ratio = round(land_percentage/ocean_percentage, 10) print(f'{box_perimeter_fill_value}', land_ocean_ratio) map_projection = ccrs.PlateCarree() fig, axes = plt.subplots(nrows=2, ncols=1, figsize=(15, 5), subplot_kw={'projection': map_projection}) fro...
ocean_percentage = round((ocean_pixels/image_pixels)*100, 4) # land_percentage = round((land_pixels/image_pixels)*100, 4) # ocean_percentage = round((ocean_pixels/image_pixels)*100, 4)
random_line_split
land_ocean_ratio.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue May 18 17:35:24 2021 @author: huw """ import concurrent.futures import matplotlib.pyplot as plt import numpy as np import os import pandas as pd import pytesseract from itertools import repeat from PIL import Image from osgeo import gdal, osr import car...
os.chdir(r'/home/huw/Dropbox/Sophie/SeaLevelChange/georeferenced') georeferenced_images = os.listdir() georeferenced_images.sort() test = raster_to_array(georeferenced_images[0]) test_extent = map_extent(georeferenced_images[0]) x0, x1 = test_extent[0], test_extent[1] y0, y1 = test_extent[2], test_extent[3] def ...
""" Convert a raster tiff image to a numpy array. Input Requires the address to the tiff image. Parameters ---------- input_raster : string Directory to the raster which should be in tiff format. Returns ------- converted_array : numpy array A numpy array of the input r...
identifier_body
mod.rs
//! General actions #![allow(unused_imports)] #![allow(dead_code)] use chrono::*; use std::{env,fs}; use std::time; use std::fmt::Write; use std::path::{Path,PathBuf}; use util; use super::BillType; use storage::{Storage,StorageDir,Storable,StorageResult}; use project::Project; #[cfg(feature="document_export")] u...
/// Testing only, tries to run complete spec on all projects. /// TODO make this not panic :D /// TODO move this to `spec::all_the_things` pub fn spec() -> Result<()> { use project::spec::*; let luigi = try!(setup_luigi()); //let projects = super::execute(||luigi.open_projects(StorageDir::All)); let p...
{ let metadata = try!(fs::metadata(path)); let accessed = try!(metadata.accessed()); Ok(try!(accessed.elapsed())) }
identifier_body
mod.rs
//! General actions #![allow(unused_imports)] #![allow(dead_code)] use chrono::*; use std::{env,fs}; use std::time; use std::fmt::Write; use std::path::{Path,PathBuf}; use util; use super::BillType; use storage::{Storage,StorageDir,Storable,StorageResult}; use project::Project; #[cfg(feature="document_export")] u...
} /// Command UNARCHIVE <YEAR> <NAME> /// TODO: return a list of files that have to be updated in git pub fn unarchive_projects(year:i32, search_terms:&[&str]) -> Result<Vec<PathBuf>> { let luigi = try!(setup_luigi_with_git()); Ok(try!( luigi.unarchive_projects(year, search_terms) )) }
random_line_split