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
cpu.py
from functools import partial from devito.core.operator import CoreOperator, CustomOperator, ParTile from devito.exceptions import InvalidOperator from devito.passes.equations import collect_derivatives from devito.passes.clusters import (Lift, blocking, buffering, cire, cse, factor...
(f): if f.is_TimeFunction and f.save is not None: return f.time_dim else: return None return { 'buffering': lambda i: buffering(i, callback, sregistry, options), 'blocking': lambda i: blocking(i, sregistry, options), 'f...
callback
identifier_name
http.go
package http import ( "encoding/json" "fmt" "github.com/gorilla/mux" qf "github.com/tobgu/qframe" "github.com/tobgu/qframe/config/csv" "github.com/tobgu/qframe/config/newqf" "github.com/tobgu/qframe/types" "github.com/tobgu/qocache/cache" "github.com/tobgu/qocache/config" "github.com/tobgu/qocache/qlog" "gi...
func addStandInColumns(frame qf.QFrame, headers http.Header) (qf.QFrame, bool, error) { standIns, err := headerToKeyValues(headers, "X-QCache-stand-in-columns") if err != nil { return frame, false, err } columnAdded := false for col, standIn := range standIns { if !frame.Contains(col) { if s, ok := stand...
{ statsProbe := statistics.NewStoreProbe(r.Context()) defer r.Body.Close() vars := mux.Vars(r) key := vars["key"] var frame qf.QFrame contentType, charset := parseContentType(r.Header.Get("Content-Type")) if charset != "" && charset != "utf-8" { a.badRequest(w, "Unsupported charset: %s", charset) return } ...
identifier_body
http.go
package http import ( "encoding/json" "fmt" "github.com/gorilla/mux" qf "github.com/tobgu/qframe" "github.com/tobgu/qframe/config/csv" "github.com/tobgu/qframe/config/newqf" "github.com/tobgu/qframe/types" "github.com/tobgu/qocache/cache" "github.com/tobgu/qocache/config" "github.com/tobgu/qocache/qlog" "gi...
(msg string, params ...interface{}) string { result := fmt.Sprintf(msg, params...) a.logger.Printf(result) return result } func (a *application) logError(source string, err error) { if err != nil { a.logger.Printf("Error %s: %v", source, err) } } func (a *application) badRequest(w http.ResponseWriter, msg stri...
log
identifier_name
http.go
package http import ( "encoding/json" "fmt" "github.com/gorilla/mux" qf "github.com/tobgu/qframe" "github.com/tobgu/qframe/config/csv" "github.com/tobgu/qframe/config/newqf" "github.com/tobgu/qframe/types" "github.com/tobgu/qocache/cache" "github.com/tobgu/qocache/config" "github.com/tobgu/qocache/qlog" "gi...
if conf.HttpPprof { attachProfiler(r) } return r, nil } func parseBasicAuth(auth string) (string, string, error) { parts := strings.Split(auth, ":") if len(parts) != 2 { return "", "", fmt.Errorf("invalid basic auth string, expected <username>:<password>, was: %s", auth) } username := parts[0] password...
{ r.HandleFunc(root+"/dataset/{key}", mw(app.newDataset)).Methods("POST") r.HandleFunc(root+"/dataset/{key}/q", mw(app.queryDatasetPost)).Methods("POST") r.HandleFunc(root+"/dataset/{key}", mw(app.queryDatasetGet)).Methods("GET") r.HandleFunc(root+"/statistics", mw(app.statistics)).Methods("GET") r.HandleFunc...
conditional_block
http.go
package http import ( "encoding/json" "fmt" "github.com/gorilla/mux" qf "github.com/tobgu/qframe" "github.com/tobgu/qframe/config/csv" "github.com/tobgu/qframe/config/newqf" "github.com/tobgu/qframe/types" "github.com/tobgu/qocache/cache" "github.com/tobgu/qocache/config" "github.com/tobgu/qocache/qlog" "gi...
func (a *application) log(msg string, params ...interface{}) string { result := fmt.Sprintf(msg, params...) a.logger.Printf(result) return result } func (a *application) logError(source string, err error) { if err != nil { a.logger.Printf("Error %s: %v", source, err) } } func (a *application) badRequest(w http...
}
random_line_split
HeaderCell.ts
/* IHeaderCell Сделано: align Выравнивание содержимого ячейки по горизонтали. caption Текст заголовка ячейки. sortingProperty Свойство, по которому выполняется сортировка. template Шаблон заголовка ячейки. textOverflow Поведение текста, если он не умещается в ячейке valign Выравнивание соде...
} return contentClasses; } protected _getContentSeparatorClasses(theme: string): string { let headerEndRow = this._$owner.getBounds().row.end; const isMultiLineHeader = this._$owner.isMultiline(); let classes = ''; if (isMultiLineHeader) { if (this._$...
} if (this._$align) { contentClasses += ` controls-Grid__header-cell_justify_content_${this._$align}`;
random_line_split
HeaderCell.ts
/* IHeaderCell Сделано: align Выравнивание содержимого ячейки по горизонтали. caption Текст заголовка ячейки. sortingProperty Свойство, по которому выполняется сортировка. template Шаблон заголовка ячейки. textOverflow Поведение текста, если он не умещается в ячейке valign Выравнивание соде...
// todo <<< START >>> compatible with old gridHeaderModel get column(): IHeaderCell { return this._$column; } // todo <<< END >>> isLastColumn(): boolean { const isMultilineHeader = this._$owner.isMultiline(); if (isMultilineHeader) { let headerEndColumn = this._$ow...
}
identifier_name
HeaderCell.ts
/* IHeaderCell Сделано: align Выравнивание содержимого ячейки по горизонтали. caption Текст заголовка ячейки. sortingProperty Свойство, по которому выполняется сортировка. template Шаблон заголовка ячейки. textOverflow Поведение текста, если он не умещается в ячейке valign Выравнивание соде...
ht_theme-${theme}`; } else { wrapperClasses += ` controls-Grid__header-cell_min-height_theme-${theme}`; } if (!isStickySupport) { wrapperClasses += ' controls-Grid__header-cell_static'; } if (!this.isMultiSelectColumn()) { wrapperClasses += ' ...
tWrapperPaddingClasses(theme)}` + ` ${this._getColumnSeparatorClasses(theme)}` + ` controls-background-${backgroundColorStyle || style}_theme-${theme}`; const isMultilineHeader = this._$owner.isMultiline(); const isStickySupport = this._$owner.isStick...
identifier_body
HeaderCell.ts
/* IHeaderCell Сделано: align Выравнивание содержимого ячейки по горизонтали. caption Текст заголовка ячейки. sortingProperty Свойство, по которому выполняется сортировка. template Шаблон заголовка ячейки. textOverflow Поведение текста, если он не умещается в ячейке valign Выравнивание соде...
}`; } } return classes; } getTemplate(): TemplateFunction|string { return this._$column.template || DEFAULT_CELL_TEMPLATE; } getCaption(): string { // todo "title" - is deprecated property, use "caption" return this._$column.caption || this._$column....
.startRow === 1) { classes += ` controls-Grid__cell_header-content_border-bottom_theme-${theme
conditional_block
util.py
import numpy as np import cv2 import os class sample: def __init__(self, img, truth, box): self.image = img self.truth = truth # a nparray containing npts landmarks, each landmark is denoted by its x and y coordinate self.guess = np.zeros(truth.shape) self.box = bo...
refshape_new = np.mean(alignedShapes, 0) diff = np.abs(np.max(refshape - refshape_new)) refshape = refshape_new print('MeanShape finished in {} iterations.\n'.format(iters)) return refshape.reshape(-1, 2) def alignShape(s1, s0): npts = len(s1)/2 s1 = s1.reshape(npt...
alignedShapes(i,:) = alignShape(alignedShapes(i,:), refshape)
conditional_block
util.py
import numpy as np import cv2 import os class sample: def __init__(self, img, truth, box): self.image = img self.truth = truth # a nparray containing npts landmarks, each landmark is denoted by its x and y coordinate self.guess = np.zeros(truth.shape) self.box = bo...
(data_path): number_files = len(os.listdir(data_path)) / 4 # because for a image we have 4 related files train_set = [] for i in range(number_files): if i % 50 == 0: print('Samples loaded {} / {} ...'.format(i, number_files)) img = cv2.imread(data_path + 'image_%04d.png'%...
loadTrainData
identifier_name
util.py
import numpy as np import cv2 import os class sample: def __init__(self, img, truth, box): self.image = img self.truth = truth # a nparray containing npts landmarks, each landmark is denoted by its x and y coordinate self.guess = np.zeros(truth.shape) self.box = bo...
M_diff_rho[:,f] = features[k,f].rho_m - features[k,f].rho_n updateMat = evaluateFern_batch(M_diff_rho, ferns[k]) print('fern %d/%d\tmax(Y) = %.6g, min(Y) = %.6g'%(k, K, np.max(Y), np.min(Y))) Y = Y - updateMat regressor = regressor(localCoords, ferns, features) ret...
ferns.append(trainFern(features[-1], Y, M_rho, beta)) # update the normalized target M_diff_rho = np.zeros(nsamples, F) for f in range(F):
random_line_split
util.py
import numpy as np import cv2 import os class sample: def __init__(self, img, truth, box): self.image = img self.truth = truth # a nparray containing npts landmarks, each landmark is denoted by its x and y coordinate self.guess = np.zeros(truth.shape) self.box = bo...
def evaluateFern_batch(diffvecs, fern): F = len(fern.thresholds) nsamples = diffvecs.shape[0] for i in range(F): di = diffvecs[:,i] lset = np.where(di < thresholds[i]) rset = np.setdiff1d(array(range(nsamples)), lset) diffvecs[lset, i] = 0 diffvecs[rset, i...
Lfp = Y.shape[1] nbins = len(bins) outputs = np.zeros(nbins, Lfp) for i in range(nbins): if bins[i].size == 0: # empty bin continue outputs[i,:] = sum(Y[bins[i], :]) ni = len(bins[i]) factor = 1.0 / ((1 + beta/ni)*ni) outputs[i,:] = outputs[i,:]...
identifier_body
request_error.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: google/ads/googleads/v1/errors/request_error.proto package errors // import "google.golang.org/genproto/googleapis/ads/googleads/v1/errors" import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import _ "google.golang.org/genpro...
func (m *RequestErrorEnum) XXX_DiscardUnknown() { xxx_messageInfo_RequestErrorEnum.DiscardUnknown(m) } var xxx_messageInfo_RequestErrorEnum proto.InternalMessageInfo func init() { proto.RegisterType((*RequestErrorEnum)(nil), "google.ads.googleads.v1.errors.RequestErrorEnum") proto.RegisterEnum("google.ads.googlea...
{ return xxx_messageInfo_RequestErrorEnum.Size(m) }
identifier_body
request_error.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: google/ads/googleads/v1/errors/request_error.proto package errors // import "google.golang.org/genproto/googleapis/ads/googleads/v1/errors" import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import _ "google.golang.org/genpro...
22: "INVALID_PAGE_SIZE", 9: "REQUIRED_FIELD_MISSING", 11: "IMMUTABLE_FIELD", 13: "TOO_MANY_MUTATE_OPERATIONS", 14: "CANNOT_BE_EXECUTED_BY_MANAGER_ACCOUNT", 15: "CANNOT_MODIFY_FOREIGN_FIELD", 18: "INVALID_ENUM_VALUE", 19: "DEVELOPER_TOKEN_PARAMETER_MISSING", 20: "LOGIN_CUSTOMER_ID_PARAMETER_MISSING", 21: "VAL...
6: "RESOURCE_NOT_FOUND", 7: "INVALID_PAGE_TOKEN", 8: "EXPIRED_PAGE_TOKEN",
random_line_split
request_error.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: google/ads/googleads/v1/errors/request_error.proto package errors // import "google.golang.org/genproto/googleapis/ads/googleads/v1/errors" import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" import _ "google.golang.org/genpro...
(src proto.Message) { xxx_messageInfo_RequestErrorEnum.Merge(dst, src) } func (m *RequestErrorEnum) XXX_Size() int { return xxx_messageInfo_RequestErrorEnum.Size(m) } func (m *RequestErrorEnum) XXX_DiscardUnknown() { xxx_messageInfo_RequestErrorEnum.DiscardUnknown(m) } var xxx_messageInfo_RequestErrorEnum proto.Int...
XXX_Merge
identifier_name
http_server_utils.go
/** * (C) Copyright 2014, Deft Labs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to...
func (self *HttpContext) DefineIntParam(name, invalidErrorCode string, paramType HttpParamType, required bool) { self.Params[name] = &HttpParam{ Name: name, InvalidErrorCode: invalidErrorCode, DataType: HttpIntParam, Required: required, Type: paramType, Valid: true } } // Boolean types include: 1, t, T, TRUE, true,...
{ param.Raw = retrieveParamValue(ctx, param).(string) if len(param.Raw) == 0 && param.Required { appendInvalidErrorCode(ctx, param) return } if len(param.Raw) == 0 { return } if val, err := strconv.ParseBool(param.Raw); err != nil { appendInvalidErrorCode(ctx, param) } else { param.setPresentValue(val...
identifier_body
http_server_utils.go
/** * (C) Copyright 2014, Deft Labs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to...
for _, param := range self.Params { switch param.DataType { case HttpIntParam: validateIntParam(self, param) case HttpStringParam: validateStringParam(self, param) case HttpFloatParam: validateFloatParam(self, param) case HttpBoolParam: validateBoolParam(self, param) case HttpObjectIdParam: validate...
{ return true }
conditional_block
http_server_utils.go
/** * (C) Copyright 2014, Deft Labs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to...
func (self *HttpContext) ParamObjectId(name string) *bson.ObjectId { return self.Params[name].ObjectId() } func (self *HttpContext) ParamJson(name string) map[string]interface{} { return self.Params[name].Json() } func (self *HttpContext) ParamJsonArray(name string) []interface{} { return self.Params[name].JsonArray...
func (self *HttpContext) ParamBool(name string) bool { return self.Params[name].Bool() }
random_line_split
http_server_utils.go
/** * (C) Copyright 2014, Deft Labs * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to...
() *bson.ObjectId { if self.Value != nil { return self.Value.(*bson.ObjectId) } else { return nil } } func (self *HttpParam) Json() map[string]interface{} { if self.Value == nil { return nil } else { return self.Value.(map[string]interface{}) } } func (self *HttpParam) JsonArray() []interface{} { if self.Value == nil...
ObjectId
identifier_name
mod.rs
// Copyright 2022 TiKV Project Authors. Licensed under Apache-2.0. //! This module contains the actions that will drive a raft state machine. //! //! # Raft Ready //! //! Every messages or ticks may have side affect. Handling all those side //! affect immediately is not efficient. Instead, tikv uses `Ready` to batch u...
/// Callback for fetching logs asynchronously. pub fn on_fetched_logs(&mut self, fetched_logs: FetchedLogs) { let FetchedLogs { context, logs } = fetched_logs; let low = logs.low; if !self.is_leader() { self.entry_storage_mut().clean_async_fetch_res(low); return...
{ self.raft_group_mut().tick() }
identifier_body
mod.rs
// Copyright 2022 TiKV Project Authors. Licensed under Apache-2.0. //! This module contains the actions that will drive a raft state machine. //! //! # Raft Ready //! //! Every messages or ticks may have side affect. Handling all those side //! affect immediately is not efficient. Instead, tikv uses `Ready` to batch u...
_take_committed_entries: Vec<raft::prelude::Entry>, ) { unimplemented!() } /// Processing the ready of raft. A detail description of how it's handled /// can be found at https://docs.rs/raft/latest/raft/#processing-the-ready-state. /// /// It's should be called at the end of eve...
random_line_split
mod.rs
// Copyright 2022 TiKV Project Authors. Licensed under Apache-2.0. //! This module contains the actions that will drive a raft state machine. //! //! # Raft Ready //! //! Every messages or ticks may have side affect. Handling all those side //! affect immediately is not efficient. Instead, tikv uses `Ready` to batch u...
(&mut self) -> bool { self.raft_group_mut().tick() } /// Callback for fetching logs asynchronously. pub fn on_fetched_logs(&mut self, fetched_logs: FetchedLogs) { let FetchedLogs { context, logs } = fetched_logs; let low = logs.low; if !self.is_leader() { self.en...
tick
identifier_name
gl_scene.py
# -*- coding: utf8 -*- from OpenGL.GL import glCallList, glClear, glClearColor, glColorMaterial, glCullFace, glDepthFunc, glDisable, glEnable, \ glFlush, glGetFloatv, glLightfv, glLoadIdentity, glMatrixMode, glMultMatrixf, glPopMatrix, \ glPushMatrix, glTranslated, glViewport, \ GL_AMBIENT_AND_DIFFUSE, GL_B...
List() def init_primitives(): """ 初始化所有的图元渲染函数列表 """ make_plane() make_sphere() make_cube() def translation(displacement): """ 生成平移矩阵 """ t = numpy.identity(4) t[0, 3] = displacement[0] t[1, 3] = displacement[1] t[2, 3] = displacement[2] return t def scaling(scale): """...
0], normals[i][1], normals[i][2]) for j in range(4): glVertex3f(vertices[i][j][0], vertices[i][j][1], vertices[i][j][2]) glEnd() glEnd
conditional_block
gl_scene.py
# -*- coding: utf8 -*- from OpenGL.GL import glCallList, glClear, glClearColor, glColorMaterial, glCullFace, glDepthFunc, glDisable, glEnable, \ glFlush, glGetFloatv, glLightfv, glLoadIdentity, glMatrixMode, glMultMatrixf, glPopMatrix, \ glPushMatrix, glTranslated, glViewport, \ GL_AMBIENT_AND_DIFFUSE, GL_B...
距离摄像机1000个单位为止。 gluPerspective(70, aspect_ratio, 0.1, 1000.0) # 摄像机镜头从原点后退15个单位 glTranslated(0, 0, -15) if __name__ == "__main__": viewer = Viewer() viewer.main_loop()
视野范围到
identifier_name
gl_scene.py
# -*- coding: utf8 -*- from OpenGL.GL import glCallList, glClear, glClearColor, glColorMaterial, glCullFace, glDepthFunc, glDisable, glEnable, \ glFlush, glGetFloatv, glLightfv, glLoadIdentity, glMatrixMode, glMultMatrixf, glPopMatrix, \ glPushMatrix, glTranslated, glViewport, \ GL_AMBIENT_AND_DIFFUSE, GL_B...
ate(0, 0.75, 0) self.child_nodes[2].scale(0.7) for child_node in self.child_nodes: child_node.color_index = MIN_COLOR class Viewer(object): def __init__(self): """ Initialize the viewer. """ # 初始化接口,创建窗口并注册渲染函数 self.init_interface() # 初始化opengl的配置 ...
ld_nodes[1].scale(0.8) self.child_nodes[2].transl
identifier_body
gl_scene.py
# -*- coding: utf8 -*- from OpenGL.GL import glCallList, glClear, glClearColor, glColorMaterial, glCullFace, glDepthFunc, glDisable, glEnable, \ glFlush, glGetFloatv, glLightfv, glLoadIdentity, glMatrixMode, glMultMatrixf, glPopMatrix, \ glPushMatrix, glTranslated, glViewport, \ GL_AMBIENT_AND_DIFFUSE, GL_B...
MIN_COLOR = 0 COLORS = { # RGB Colors 0: (1.0, 1.0, 1.0), 1: (0.05, 0.05, 0.9), 2: (0.05, 0.9, 0.05), 3: (0.9, 0.05, 0.05), 4: (0.9, 0.9, 0.0), 5: (0.1, 0.8, 0.7), 6: (0.7, 0.2, 0.7), 7: (0.7, 0.7, 0.7), 8: (0.4, 0.4, 0.4), 9: (0.0, 0.0, 0.0), } def make_plane(): glNewList...
G_OBJ_CUBE = 3 MAX_COLOR = 9
random_line_split
driver.rs
#![cfg_attr(feature = "deny-warnings", deny(warnings))] #![feature(rustc_private)] #![feature(str_strip)] // FIXME: switch to something more ergonomic here, once available. // (Currently there is no way to opt into sysroot crates without `extern crate`.) #[allow(unused_extern_crates)] extern crate rustc; #[allow(unuse...
.or_else(|_| std::env::var("MULTIRUST_TOOLCHAIN")) .ok(); toolchain_path(home, toolchain) }) .or_else(|| { Command::new("rustc") .arg("--print") .arg("s...
.or_else(|_| std::env::var("MULTIRUST_HOME")) .ok(); let toolchain = std::env::var("RUSTUP_TOOLCHAIN")
random_line_split
driver.rs
#![cfg_attr(feature = "deny-warnings", deny(warnings))] #![feature(rustc_private)] #![feature(str_strip)] // FIXME: switch to something more ergonomic here, once available. // (Currently there is no way to opt into sysroot crates without `extern crate`.) #[allow(unused_extern_crates)] extern crate rustc; #[allow(unuse...
})); } } let mut clippy = ClippyCallbacks; let mut default = DefaultCallbacks; let callbacks: &mut (dyn rustc_driver::Callbacks + Send) = if clippy_enabled { &mut clippy } else { &mut default }; rustc_driver...
{ Some(s.to_string()) }
conditional_block
driver.rs
#![cfg_attr(feature = "deny-warnings", deny(warnings))] #![feature(rustc_private)] #![feature(str_strip)] // FIXME: switch to something more ergonomic here, once available. // (Currently there is no way to opt into sysroot crates without `extern crate`.) #[allow(unused_extern_crates)] extern crate rustc; #[allow(unuse...
() { let args = &["--bar=bar", "--foobar", "123", "--foo"]; assert_eq!(arg_value(&[] as &[&str], "--foobar", |_| true), None); assert_eq!(arg_value(args, "--bar", |_| false), None); assert_eq!(arg_value(args, "--bar", |_| true), Some("bar")); assert_eq!(arg_value(args, "--bar", |p| p == "bar"), Som...
test_arg_value
identifier_name
matrix_invert.rs
use std::error::Error; use std::ffi::CString; use std::time::Instant; use crate::utils::matrix_utils::print_matrix; use rustacuda::prelude::*; use std::fmt; pub fn invert_matrix_2D2D() -> Result<(), Box<dyn Error>> { // Initialize the CUDA API rustacuda::init(CudaFlags::empty())?; // Get the first device...
// calculate the inverse and compare with expected result let inv = matrix_invert_cpu(&m).unwrap(); assert_eq!(expected, inv); println!("orignal: {}", m); println!("inverted: {}", inv); } #[derive(Debug, PartialEq, Clone)] pub struct Matrix { data: Vec<f32>, rows: usize, cols: usize, } ...
expected.set(2, 2, 1.0);
random_line_split
matrix_invert.rs
use std::error::Error; use std::ffi::CString; use std::time::Instant; use crate::utils::matrix_utils::print_matrix; use rustacuda::prelude::*; use std::fmt; pub fn invert_matrix_2D2D() -> Result<(), Box<dyn Error>> { // Initialize the CUDA API rustacuda::init(CudaFlags::empty())?; // Get the first device...
(rows: usize, cols: usize) -> Matrix { Matrix { rows: rows, cols: cols, data: vec![0.0; cols * rows], } } pub fn identiy(rows: usize) -> Matrix { let mut m = Matrix::zero(rows, rows); for i in 0..rows { m.set(i, i, 1.0); } ...
zero
identifier_name
matrix_invert.rs
use std::error::Error; use std::ffi::CString; use std::time::Instant; use crate::utils::matrix_utils::print_matrix; use rustacuda::prelude::*; use std::fmt; pub fn invert_matrix_2D2D() -> Result<(), Box<dyn Error>> { // Initialize the CUDA API rustacuda::init(CudaFlags::empty())?; // Get the first device...
#[derive(Debug)] pub enum MathError { MatrixDimensionDontMatch, MatrixNotInvertableNotSquare, MatrixMulNotSquare, MatrixNotInvertable(usize, usize, f64), }
{ if mat_a.rows != mat_a.cols { return Err(MathError::MatrixNotInvertableNotSquare); } let rows = mat_a.rows; let mut cols = mat_a.cols; // helper matrix for inverting let mut dummy = Matrix::zero(rows, 2 * cols); // copy matrix a to dummy (left half of dummy) for row in 0..row...
identifier_body
classifier.py
from __future__ import print_function from __future__ import division from __future__ import print_function from __future__ import absolute_import import tensorflow as tf import models_mnist def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variab...
print(max_steps, sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0})) save_path = saver.save(sess, "results/cnn_classifier-med-train/checkpoint/model.ckpt") # print('Test Acc', sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob...
batch_xs, batch_ys = mnist.train.next_batch(50) # 0 ~ 1 # batch_xs = batch_xs*2-1 # -1 ~ 1, bad results if (step % 10) == 0: print(step, sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0})) sess.run(train_step, feed_dict={x: batch_xs, y_: batch_y...
conditional_block
classifier.py
from __future__ import print_function from __future__ import division from __future__ import print_function from __future__ import absolute_import import tensorflow as tf import models_mnist def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variab...
def cnn_classifier(x_image, keep_prob, name="classifier", reuse=True): with tf.variable_scope(name, reuse=reuse): # Convolutional layer 1 W_conv1 = weight_variable([5, 5, 1, 32]) b_conv1 = bias_variable([32]) h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) h_pool...
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
identifier_body
classifier.py
from __future__ import print_function from __future__ import division from __future__ import print_function from __future__ import absolute_import import tensorflow as tf import models_mnist def
(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) def conv2d(x, W): return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') def max_pool_2x2(x): return tf.nn.max_pool(...
weight_variable
identifier_name
classifier.py
from __future__ import print_function from __future__ import division from __future__ import print_function from __future__ import absolute_import import tensorflow as tf import models_mnist def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variab...
# Fully connected layer 2 (Output layer) W_fc2 = weight_variable([1024, 10]) b_fc2 = bias_variable([10]) y = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2, name='y') return y def main(): from tensorflow.examples.tutorials.mnist import input_data mnist = input_data...
random_line_split
replica.go
/*Creator: Tian lin (tcl344) Parallel & Dist system class Backend for twitter like app listen for client connection recieves and respondsto queries */ package main import ( "bufio" "fmt" "io/ioutil" "net" "os" "strconv" "strings" "sync" ) //--------------CONSTANTS--------------------------------- const USERL...
else { sublist = append(sublist, scanned_name) } } sublist_file.Close() //rewrite file if removed sub_uname if removed { os.Remove(filename) new_sublist_file, open_err := os.OpenFile(filename, os.O_CREATE|os.O_WRONLY, 0600) defer new_sublist_file.Close() if open_err != nil { return fmt.Sprintf("err...
{ removed = true //didn't add scanned_name to sublist continue }
conditional_block
replica.go
/*Creator: Tian lin (tcl344) Parallel & Dist system class Backend for twitter like app listen for client connection recieves and respondsto queries */ package main import ( "bufio" "fmt" "io/ioutil" "net" "os" "strconv" "strings" "sync" ) //--------------CONSTANTS--------------------------------- const USERL...
/*locking function for files. Called when want to lock a file. creates lock and store into map under filename key if lock doesn't exist lastly, calls lock on lock associated with filename*/ func create_and_lock(filename string) { _, ok := lock_for_files_map[filename] if !ok { //lock doesn't exist, so create one ...
{ if err != nil { panic(err) } }
identifier_body
replica.go
/*Creator: Tian lin (tcl344) Parallel & Dist system class Backend for twitter like app listen for client connection recieves and respondsto queries */ package main import ( "bufio" "fmt" "io/ioutil" "net" "os" "strconv" "strings" "sync" ) //--------------CONSTANTS--------------------------------- const USERL...
} else { return sub_feed(uname, num_messages) } } return fmt.Sprintf("error: unknown error.%s\n", END_TAG), false } //========================================================================================== //Functions that respond to queries, used by Evalute //==============================================...
random_line_split
replica.go
/*Creator: Tian lin (tcl344) Parallel & Dist system class Backend for twitter like app listen for client connection recieves and respondsto queries */ package main import ( "bufio" "fmt" "io/ioutil" "net" "os" "strconv" "strings" "sync" ) //--------------CONSTANTS--------------------------------- const USERL...
(filename string) { _, ok := lock_for_files_map[filename] if !ok { //lock doesn't exist, so create one lock_for_files_map[filename] = &sync.Mutex{} } lock_for_files_map[filename].Lock() //attempt to acquire lock no matter the case }
create_and_lock
identifier_name
upb.rs
// Protocol Buffers - Google's data interchange format // Copyright 2023 Google LLC. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // ...
// SAFETY: // - `upb_Arena_Realloc` promises that if the return pointer is non-null, it is // dereferencable for the new `size` in bytes until the arena is destroyed. // - `[MaybeUninit<u8>]` has no alignment requirement, and `ptr` is aligned to a // `UPB_MALLOC_ALIGN` boun...
{ alloc::handle_alloc_error(new); }
conditional_block
upb.rs
// Protocol Buffers - Google's data interchange format // Copyright 2023 Google LLC. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // ...
pub fn copy_bytes_in_arena_if_needed_by_runtime<'a>( msg_ref: MutatorMessageRef<'a>, val: &'a [u8], ) -> &'a [u8] { // SAFETY: the alignment of `[u8]` is less than `UPB_MALLOC_ALIGN`. let new_alloc = unsafe { msg_ref.arena.alloc(Layout::for_value(val)) }; debug_assert_eq!(new_alloc.len(), val.len())...
self.msg } }
random_line_split
upb.rs
// Protocol Buffers - Google's data interchange format // Copyright 2023 Google LLC. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // ...
(_private: Private, msg: &'msg mut MessageInner) -> Self { MutatorMessageRef { msg: msg.msg, arena: &msg.arena } } pub fn msg(&self) -> RawMessage { self.msg } } pub fn copy_bytes_in_arena_if_needed_by_runtime<'a>( msg_ref: MutatorMessageRef<'a>, val: &'a [u8], ) -> &'a [u8] { ...
new
identifier_name
upb.rs
// Protocol Buffers - Google's data interchange format // Copyright 2023 Google LLC. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // ...
} impl Drop for Arena { #[inline] fn drop(&mut self) { unsafe { upb_Arena_Free(self.raw); } } } /// Serialized Protobuf wire format data. /// /// It's typically produced by `<Message>::serialize()`. pub struct SerializedData { data: NonNull<u8>, len: usize, // The...
{ debug_assert!(new.align() <= UPB_MALLOC_ALIGN); // SAFETY: // - `self.raw` is a valid UPB arena // - `ptr` was allocated by a previous call to `alloc` or `realloc` as promised // by the caller. let ptr = unsafe { upb_Arena_Realloc(self.raw, ptr, old.size(), new.size()...
identifier_body
Content.js
import _extends from "@babel/runtime/helpers/extends"; import _classCallCheck from "@babel/runtime/helpers/classCallCheck"; import _createClass from "@babel/runtime/helpers/createClass"; import _assertThisInitialized from "@babel/runtime/helpers/assertThisInitialized"; import _inherits from "@babel/runtime/helpers/inhe...
() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } /** @jsx jsx */ import React...
_isNativeReflectConstruct
identifier_name
Content.js
import _extends from "@babel/runtime/helpers/extends"; import _classCallCheck from "@babel/runtime/helpers/classCallCheck"; import _createClass from "@babel/runtime/helpers/createClass"; import _assertThisInitialized from "@babel/runtime/helpers/assertThisInitialized"; import _inherits from "@babel/runtime/helpers/inhe...
}); export { Content as default };
random_line_split
Content.js
import _extends from "@babel/runtime/helpers/extends"; import _classCallCheck from "@babel/runtime/helpers/classCallCheck"; import _createClass from "@babel/runtime/helpers/createClass"; import _assertThisInitialized from "@babel/runtime/helpers/assertThisInitialized"; import _inherits from "@babel/runtime/helpers/inhe...
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return fals...
{ var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply...
identifier_body
Content.js
import _extends from "@babel/runtime/helpers/extends"; import _classCallCheck from "@babel/runtime/helpers/classCallCheck"; import _createClass from "@babel/runtime/helpers/createClass"; import _assertThisInitialized from "@babel/runtime/helpers/assertThisInitialized"; import _inherits from "@babel/runtime/helpers/inhe...
} }, { key: "componentWillUnmount", value: function componentWillUnmount() { this._isMounted = false; document.removeEventListener('keydown', this.handleKeyDown, false); document.removeEventListener('keyup', this.handleKeyUp, false); if (this.scrollContainer) { var captur...
{ this.handleStackChange(nextProps.stackIndex); }
conditional_block
datascraper_whoscored.py
import csv import sys import time import numpy as np import pandas as pd from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from tqdm import tqdm import selenium.webdriver.support.expected_conditions as ec ...
if len(sys.argv) == 3: # Parameters to write the data to links_csv = sys.argv[1] # "data/whoscored/match-links.csv" filepath = sys.argv[2] # leaguename = 'premierleague' # filepath = 'data/whoscored/%s-%d.csv' % (leaguename, 20182019) chromepath = "chromedriver.exe" driver = webdriver....
soup = BeautifulSoup(driver.page_source, 'lxml') info_div = soup.find('div', id=info_panel_id) for stat in info_div.find_all('div', class_='stat'): for span in stat.find_all('span', class_='stat-value'): match_report_stat.append(span.text) clickable_fields = driver.find_elements_by_xpat...
identifier_body
datascraper_whoscored.py
import csv import sys import time import numpy as np import pandas as pd from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from tqdm import tqdm import selenium.webdriver.support.expected_conditions as ec ...
return match_report_stat if len(sys.argv) == 3: # Parameters to write the data to links_csv = sys.argv[1] # "data/whoscored/match-links.csv" filepath = sys.argv[2] # leaguename = 'premierleague' # filepath = 'data/whoscored/%s-%d.csv' % (leaguename, 20182019) chromepath = "chromedriver...
match_report_stat.append(span.text)
conditional_block
datascraper_whoscored.py
import csv import sys import time import numpy as np import pandas as pd from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from tqdm import tqdm import selenium.webdriver.support.expected_conditions as ec ...
(match_report_stat, info_panel_id, clickable_xpath): # Get the page and now scrap the data from the bottom panel soup = BeautifulSoup(driver.page_source, 'lxml') info_div = soup.find('div', id=info_panel_id) for stat in info_div.find_all('div', class_='stat'): for span in stat.find_all('span', c...
extract_report_data
identifier_name
datascraper_whoscored.py
import csv import sys import time import numpy as np import pandas as pd from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from tqdm import tqdm import selenium.webdriver.support.expected_conditions as ec ...
"home total shots", "away total shots", "home woodwork", "away woodwork", "home shots on target", "away shots on target", "home shots off target", "away shots off target", "home shots blocked", "away shots blocked", "home possession", "away possession", "home ...
random_line_split
function.go
package function import ( "fmt" "github.com/zclconf/go-cty/cty" ) // Function represents a function. This is the main type in this package. type Function struct { spec *Spec } // Spec is the specification of a function, used to instantiate // a new Function. type Spec struct { // Params is a description of the ...
if val.IsNull() && !spec.AllowNull { return cty.Type{}, NewArgErrorf(i, "argument must not be null") } // AllowUnknown is ignored for type-checking, since we expect to be // able to type check with unknown values. We *do* still need to deal // with DynamicPseudoType here though, since the Type function ...
{ // During type checking we just unmark values and discard their // marks, under the assumption that during actual execution of // the function we'll do similarly and then re-apply the marks // afterwards. Note that this does mean that a function that // inspects values (rather than just types) in its T...
conditional_block
function.go
package function import ( "fmt" "github.com/zclconf/go-cty/cty" ) // Function represents a function. This is the main type in this package. type Function struct { spec *Spec } // Spec is the specification of a function, used to instantiate // a new Function. type Spec struct { // Params is a description of the ...
if val.Type() == cty.DynamicPseudoType { if !spec.AllowDynamicType { return cty.DynamicPseudoType, nil } } else if errs := val.Type().TestConformance(spec.Type); errs != nil { // For now we'll just return the first error in the set, since // we don't have a good way to return the whole list here. ...
// AllowUnknown is ignored for type-checking, since we expect to be // able to type check with unknown values. We *do* still need to deal // with DynamicPseudoType here though, since the Type function might // not be ready to deal with that.
random_line_split
function.go
package function import ( "fmt" "github.com/zclconf/go-cty/cty" ) // Function represents a function. This is the main type in this package. type Function struct { spec *Spec } // Spec is the specification of a function, used to instantiate // a new Function. type Spec struct { // Params is a description of the ...
// ReturnType returns the return type of a function given a set of candidate // argument types, or returns an error if the given types are unacceptable. // // If the caller already knows values for at least some of the arguments // it can be better to call ReturnTypeForValues, since certain functions may // determine...
{ return func([]cty.Value) (cty.Type, error) { return ty, nil } }
identifier_body
function.go
package function import ( "fmt" "github.com/zclconf/go-cty/cty" ) // Function represents a function. This is the main type in this package. type Function struct { spec *Spec } // Spec is the specification of a function, used to instantiate // a new Function. type Spec struct { // Params is a description of the ...
(ty cty.Type) TypeFunc { return func([]cty.Value) (cty.Type, error) { return ty, nil } } // ReturnType returns the return type of a function given a set of candidate // argument types, or returns an error if the given types are unacceptable. // // If the caller already knows values for at least some of the argumen...
StaticReturnType
identifier_name
index.js
import React, { Component } from 'react'; import Joyride from 'react-joyride'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Redirect, withRouter } from 'react-router-dom'; import AuthService from '../../../services/AuthService'; import { addChat, addChatMessage, addErrorMessa...
}; onOpenNotification = (id) => { this.onOpenChat(id); }; onRateUser =(obj) => { const { email } = this.getEmail(); this.props.rating({ ...obj, userId: email }); }; onRemove =() => { this.props.remove(); }; onSubmit = (evt) => { evt.preventDefault(); const { data } = this.pr...
{ this.props.addChat('abcd', this.props.users.allUsers[id], id); }
conditional_block
index.js
import React, { Component } from 'react'; import Joyride from 'react-joyride'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Redirect, withRouter } from 'react-router-dom'; import AuthService from '../../../services/AuthService'; import { addChat, addChatMessage, addErrorMessa...
onDateValidation = (date) => date.match(/^\d{4}([./-])\d{2}\1\d{2}$/g); onPresentDateValidation = (dateString) => new Date(dateString) > new Date(); onPhoneNumberValidation = (number) => number.match(/[+](\d+)/g); onChangeOffence = (evt, id) => { let { value } = evt.target; if (value === '--clear--'...
random_line_split
index.js
import React, { Component } from 'react'; import Joyride from 'react-joyride'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Redirect, withRouter } from 'react-router-dom'; import AuthService from '../../../services/AuthService'; import { addChat, addChatMessage, addErrorMessa...
extends Component { constructor(props) { super(props); this.state = { collapse: '', joyrideOverlay: true, joyrideType: 'continuous', isReady: false, isRunning: false, stepIndex: 0, steps: [], selector: '', open: '', }; } componentWillMount() { ...
Dashboard
identifier_name
index.js
import React, { Component } from 'react'; import Joyride from 'react-joyride'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Redirect, withRouter } from 'react-router-dom'; import AuthService from '../../../services/AuthService'; import { addChat, addChatMessage, addErrorMessa...
function mapStateToProps(state) { return makeSelector(state); } Dashboard.propTypes = { addChat: PropTypes.func.isRequired, addChatMessage: PropTypes.func.isRequired, addUser: PropTypes.func.isRequired, admin: PropTypes.shape({ adminProfile: PropTypes.shape({ email: PropTypes.string, passwo...
{ return { addChat: (id, value, userId) => dispatch(addChat(id, value, userId)), addUser: (user) => dispatch(addUser(user)), approveUsers: (id) => dispatch(approveUsers(id)), addChatMessage: (message) => dispatch(addChatMessage(message)), addErrorMessage: (msg) => dispatch(addErrorMessages(msg)), ...
identifier_body
more.rs
use crate::librb::uoff_t; use libc; use libc::fclose; use libc::fstat; use libc::isatty; use libc::off64_t; use libc::off_t; use libc::printf; use libc::putchar_unlocked; use libc::stat; use libc::termios; use libc::FILE; extern "C" { #[no_mangle] fn _exit(_: libc::c_int) -> !; #[no_mangle] static mut optind...
) -> libc::c_int; #[no_mangle] fn set_termios_to_raw(fd: libc::c_int, oldterm: *mut termios, flags: libc::c_int) -> libc::c_int; #[no_mangle] static mut bb_common_bufsiz1: [libc::c_char; 0]; } pub type C2RustUnnamed = libc::c_uint; pub const BB_FATAL_SIGS: C2RustUnnamed = 117503054; #[derive(Copy, Clone)] ...
fn get_terminal_width_height( fd: libc::c_int, width: *mut libc::c_uint, height: *mut libc::c_uint,
random_line_split
more.rs
use crate::librb::uoff_t; use libc; use libc::fclose; use libc::fstat; use libc::isatty; use libc::off64_t; use libc::off_t; use libc::printf; use libc::putchar_unlocked; use libc::stat; use libc::termios; use libc::FILE; extern "C" { #[no_mangle] fn _exit(_: libc::c_int) -> !; #[no_mangle] static mut optind...
unsafe extern "C" fn gotsig(mut _sig: libc::c_int) { /* bb_putchar_stderr doesn't use stdio buffering, * therefore it is safe in signal handler */ bb_putchar_stderr('\n' as i32 as libc::c_char); /* for compiler */ tcsetattr_tty_TCSANOW(&mut (*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).initial_settings)...
{ tcsetattr( (*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).tty_fileno, 0i32, settings, ); }
identifier_body
more.rs
use crate::librb::uoff_t; use libc; use libc::fclose; use libc::fstat; use libc::isatty; use libc::off64_t; use libc::off_t; use libc::printf; use libc::putchar_unlocked; use libc::stat; use libc::termios; use libc::FILE; extern "C" { #[no_mangle] fn _exit(_: libc::c_int) -> !; #[no_mangle] static mut optind...
(mut settings: *mut termios) { tcsetattr( (*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).tty_fileno, 0i32, settings, ); } unsafe extern "C" fn gotsig(mut _sig: libc::c_int) { /* bb_putchar_stderr doesn't use stdio buffering, * therefore it is safe in signal handler */ bb_putchar_stderr('\n' ...
tcsetattr_tty_TCSANOW
identifier_name
point_cloud.rs
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use thi...
fn get_file_list(files_reg: &str) -> Vec<PathBuf> { let options = MatchOptions { case_sensitive: false, ..Default::default() }; let mut paths = Vec::new(); let glob_paths = match glob_with(files_reg, &options) { Ok(expr) => expr, Err(e) => panic!("Pattern reading error ...
{ if let Some(schema_map) = schema_yaml.as_hash() { for (k, v) in schema_map.iter() { let key = k.as_str().unwrap().to_string(); match v.as_str().unwrap() { "u32" => label_scheme.add_u32(key), "f32" => label_scheme.add_f32(key), "i32" =...
identifier_body
point_cloud.rs
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use thi...
(&self) -> usize { self.data_sources.iter().fold(0, |acc, mm| acc + mm.len()) } /// Dimension of the data in the point cloud pub fn dim(&self) -> usize { self.data_dim } /// The names of the data are currently a shallow wrapper around a usize. pub fn reference_indexes(&self) ->...
len
identifier_name
point_cloud.rs
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use thi...
use super::*; pub fn build_random_test(count: usize, data_dim: usize, labels_dim: usize) -> PointCloud<L2> { let data: Vec<f32> = (0..count * data_dim) .map(|_i| rand::random::<f32>()) .collect(); let labels: Vec<f32> = (0..count * labels_dim) .map(|_i| rand:...
random_line_split
machinedeployment_webhook.go
/* Copyright 2021 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, ...
() (admission.Warnings, error) { return nil, m.validate(nil) } // ValidateUpdate implements webhook.Validator so a webhook will be registered for the type. func (m *MachineDeployment) ValidateUpdate(old runtime.Object) (admission.Warnings, error) { oldMD, ok := old.(*MachineDeployment) if !ok { return nil, apierr...
ValidateCreate
identifier_name
machinedeployment_webhook.go
/* Copyright 2021 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, ...
), ) } // MachineSet preflight checks that should be skipped could also be set as annotation on the MachineDeployment // since MachineDeployment annotations are synced to the MachineSet. if feature.Gates.Enabled(feature.MachineSetPreflightChecks) { if err := validateSkippedMachineSetPreflightChecks(m); err ...
allErrs, field.Forbidden( specPath.Child("template", "metadata", "labels"), fmt.Sprintf("must match spec.selector %q", selector.String()),
random_line_split
machinedeployment_webhook.go
/* Copyright 2021 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, ...
} if m.Spec.Strategy.RollingUpdate.MaxUnavailable != nil { if _, err := intstr.GetScaledValueFromIntOrPercent(m.Spec.Strategy.RollingUpdate.MaxUnavailable, total, true); err != nil { allErrs = append( allErrs, field.Invalid(specPath.Child("strategy", "rollingUpdate", "maxUnavailable"), m.Sp...
{ allErrs = append( allErrs, field.Invalid(specPath.Child("strategy", "rollingUpdate", "maxSurge"), m.Spec.Strategy.RollingUpdate.MaxSurge, fmt.Sprintf("must be either an int or a percentage: %v", err.Error())), ) }
conditional_block
machinedeployment_webhook.go
/* Copyright 2021 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, ...
// ValidateUpdate implements webhook.Validator so a webhook will be registered for the type. func (m *MachineDeployment) ValidateUpdate(old runtime.Object) (admission.Warnings, error) { oldMD, ok := old.(*MachineDeployment) if !ok { return nil, apierrors.NewBadRequest(fmt.Sprintf("expected a MachineDeployment but...
{ return nil, m.validate(nil) }
identifier_body
day_15.rs
mod point; mod astar; use { crate::{ astar::Pathfinder, point::{ Point, Neighbors, }, }, std::{ fmt, cmp::Ordering, collections::{ HashSet, HashMap, }, time::Instant, usize, }, ra...
} fn resolve_attacks(&mut self, i: usize) { let neighbors = self.fighters[i].pos.neighbors_reading_order(); let target_index = neighbors .filter_map(|neighbor| { self.fighters.iter().enumerate() .filter_map(|(j, f)| { if ...
{ let mut paths = Vec::new(); let origin_points = fighter.pos.neighbors_reading_order() .filter(|p| self.is_free_space(*p)); let mut path = Vec::new(); for origin in origin_points { for &dest in &dests { let free_tile_...
conditional_block
day_15.rs
mod point; mod astar; use { crate::{ astar::Pathfinder, point::{ Point, Neighbors, }, }, std::{ fmt, cmp::Ordering, collections::{ HashSet, HashMap, }, time::Instant, usize, }, ra...
fn tick(&mut self, pathfinder: &mut CavernPathfinder) -> Option<Team> { let mut targets = Vec::new(); self.fighters.sort_by(|a, b| Point::cmp_reading_order(a.pos, b.pos)); self.refresh_fighter_positions(); for i in 0..self.fighters.len() { if self.fighters[i].hp > 0 {...
{ let neighbors = self.fighters[i].pos.neighbors_reading_order(); let target_index = neighbors .filter_map(|neighbor| { self.fighters.iter().enumerate() .filter_map(|(j, f)| { if f.pos == neighbor && f.h...
identifier_body
day_15.rs
mod point; mod astar; use { crate::{ astar::Pathfinder, point::{ Point, Neighbors, }, }, std::{ fmt, cmp::Ordering, collections::{ HashSet, HashMap, }, time::Instant, usize, }, ra...
(&self, i: usize, targets: &mut Vec<usize>) { targets.clear(); let fighter = &self.fighters[i]; targets.extend(self.fighters.iter().enumerate() .filter(|(_, other)| other.hp > 0) .filter_map(|(j, other)| if other.team != fighter.team { Some(j) ...
find_targets
identifier_name
day_15.rs
mod point; mod astar; use { crate::{ astar::Pathfinder, point::{ Point, Neighbors, }, }, std::{ fmt, cmp::Ordering, collections::{ HashSet, HashMap, }, time::Instant, usize, }, ra...
for (y, line) in s.lines().enumerate() { height += 1; width = line.len(); // assume all lines are the same length for (x, char) in line.chars().enumerate() { let point = Point::new(x as isize, y as isize); match char { '#' ...
let mut fighters = Vec::new(); let mut tiles = Vec::new();
random_line_split
main.go
package main import ( "fmt" "github.com/gobs/args" "github.com/iikira/BaiduPCS-Go/command" "github.com/iikira/BaiduPCS-Go/config" "github.com/kardianos/osext" "github.com/peterh/liner" "github.com/urfave/cli" "io" "log" "os" "path/filepath" "runtime" "sort" "strconv" ) var ( historyFile = "pcs_command_...
Name: "chuser", Usage: "切换已登录的百度帐号", Description: fmt.Sprintf("%s\n 示例:\n\n %s\n %s\n", "如果运行该条命令没有提供参数, 程序将会列出所有的百度帐号, 供选择切换", app.Name+" chuser --uid=123456789", app.Name+" chuser", ), Category: "百度帐号操作", Before: reloadFn, After: reloadFn, Action: func(c *cli.Cont...
{
random_line_split
main.go
package main import ( "fmt" "github.com/gobs/args" "github.com/iikira/BaiduPCS-Go/command" "github.com/iikira/BaiduPCS-Go/config" "github.com/kardianos/osext" "github.com/peterh/liner" "github.com/urfave/cli" "io" "log" "os" "path/filepath" "runtime" "sort" "strconv" ) var ( historyFile = "pcs_command_...
() { // change work directory folderPath, err := osext.ExecutableFolder() if err != nil { folderPath, err = filepath.Abs(filepath.Dir(os.Args[0])) if err != nil { folderPath = filepath.Dir(os.Args[0]) } } os.Chdir(folderPath) } func main() { app := cli.NewApp() app.Name = "baidupcs_go" app.Author = "i...
init
identifier_name
main.go
package main import ( "fmt" "github.com/gobs/args" "github.com/iikira/BaiduPCS-Go/command" "github.com/iikira/BaiduPCS-Go/config" "github.com/kardianos/osext" "github.com/peterh/liner" "github.com/urfave/cli" "io" "log" "os" "path/filepath" "runtime" "sort" "strconv" ) var ( historyFile = "pcs_command_...
{ app := cli.NewApp() app.Name = "baidupcs_go" app.Author = "iikira/BaiduPCS-Go: https://github.com/iikira/BaiduPCS-Go" app.Usage = fmt.Sprintf("百度网盘工具箱 %s/%s GoVersion %s", runtime.GOOS, runtime.GOARCH, runtime.Version()) app.Description = `baidupcs_go 使用 Go语言编写, 为操作百度网盘, 提供实用功能. 具体功能, 参见 COMMANDS 列表 特色: 网盘内...
identifier_body
main.go
package main import ( "fmt" "github.com/gobs/args" "github.com/iikira/BaiduPCS-Go/command" "github.com/iikira/BaiduPCS-Go/config" "github.com/kardianos/osext" "github.com/peterh/liner" "github.com/urfave/cli" "io" "log" "os" "path/filepath" "runtime" "sort" "strconv" ) var ( historyFile = "pcs_command_...
命令 %s help 获取帮助\n", c.Args().Get(0), app.Name) } } app.Commands = []cli.Command{ { Name: "login", Usage: "使用百度BDUSS登录百度账号", Description: fmt.Sprintf("\n 示例: \n\n %s\n\n %s\n\n %s\n\n %s\n\n %s\n", app.Name+" login --bduss=123456789", app.Name+" login", "百度BDUSS获取方法: ...
...) closeLiner(line) c.App.Run(s) line = newLiner() } else if err == liner.ErrPromptAborted || err == io.EOF { break } else { log.Print("Error reading line: ", err) continue } } } else { fmt.Printf("未找到命令: %s\n运行
conditional_block
driver_suite_test.go
/* Copyright 2021 IBM Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distr...
return origDriverHelper.GetClaimValue(claims, key) } func (dv *fakeDriverHelper) MarshaljSON(v interface{}) ([]byte, error) { if dv.errorOnAction == "marshaljson" { return nil, fmt.Errorf("fake error") } return origDriverHelper.MarshaljSON(v) } func (dv *fakeDriverHelper) UnMarshaljSON(data []byte, v interface{...
func (dv *fakeDriverHelper) GetClaimValue(claims jwt.MapClaims, key string) (string, error) {
random_line_split
driver_suite_test.go
/* Copyright 2021 IBM Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distr...
return origDriverHelper.MkdirAll(path, perm) } func (dv *fakeDriverHelper) WriteFile(name, content string, flag int, perm os.FileMode) error { if dv.errorOnAction == "Writefile" { return fmt.Errorf("fake error") } return origDriverHelper.WriteFile(name, content, flag, perm) } func (dv *fakeDriverHelper) FileSt...
{ return fmt.Errorf("fake error") }
conditional_block
driver_suite_test.go
/* Copyright 2021 IBM Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distr...
(targetPath string) []string { return origDriverHelper.GetDatasetDirectoryNames(targetPath) } func (dv *fakeDriverHelper) CleanMountPoint(targetPath string) error { if dv.errorOnAction == "cleanmountpoint" { return fmt.Errorf("fake error") } return os.Remove(targetPath) } func (dv *fakeDriverHelper) MkdirAll(pa...
GetDatasetDirectoryNames
identifier_name
driver_suite_test.go
/* Copyright 2021 IBM Corp. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distr...
func (dv *fakeDriverHelper) WriteFile(name, content string, flag int, perm os.FileMode) error { if dv.errorOnAction == "Writefile" { return fmt.Errorf("fake error") } return origDriverHelper.WriteFile(name, content, flag, perm) } func (dv *fakeDriverHelper) FileStat(path string) (os.FileInfo, error) { if dv.er...
{ if dv.errorOnAction == "mkdirall" { return fmt.Errorf("fake error") } return origDriverHelper.MkdirAll(path, perm) }
identifier_body
libvirt.go
// Copyright 2016 The go-libvirt Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agr...
// StoragePool returns the storage pool associated with the provided name. // An error is returned if the requested storage pool is not found. func (l *Libvirt) StoragePool(name string) (StoragePool, error) { return l.StoragePoolLookupByName(name) } // StoragePools returns a list of defined storage pools. Pools are ...
}
random_line_split
libvirt.go
// Copyright 2016 The go-libvirt Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agr...
(dom string, flags DomainXMLFlags) ([]byte, error) { d, err := l.lookup(dom) if err != nil { return nil, err } xml, err := l.DomainGetXMLDesc(d, uint32(flags)) return []byte(xml), err } // DefineXML defines a domain, but does not start it. func (l *Libvirt) DefineXML(x []byte, flags DomainDefineXMLFlags) error...
XML
identifier_name
libvirt.go
// Copyright 2016 The go-libvirt Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agr...
// Secrets returns all secrets managed by the libvirt daemon. func (l *Libvirt) Secrets() ([]Secret, error) { secrets, _, err := l.ConnectListAllSecrets(1, 0) return secrets, err } // StoragePool returns the storage pool associated with the provided name. // An error is returned if the requested storage pool is no...
{ d, err := l.lookup(dom) if err != nil { return nil, err } payload := struct { Domain Domain Command []byte Flags uint32 }{ Domain: d, Command: cmd, Flags: 0, } buf, err := encode(&payload) if err != nil { return nil, err } resp, err := l.request(constants.QEMUDomainMonitor, constant...
identifier_body
libvirt.go
// Copyright 2016 The go-libvirt Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agr...
// check for QEMU process errors if err = getQEMUError(res); err != nil { return nil, err } r := bytes.NewReader(res.Payload) dec := xdr.NewDecoder(r) data, _, err := dec.DecodeFixedOpaque(int32(r.Len())) if err != nil { return nil, err } // drop QMP control characters from start of line, and drop // ...
{ return nil, decodeError(res.Payload) }
conditional_block
global-network.js
//-------GLOBAL NETWORK JS-----------// var $ =jQuery.noConflict(); //Control Nav Dropdown/Active Section $('.network-nav-item').click(function(event) { var item = $(this).attr('id'); if(item == 'network-filter-topics'){ $('.network-filter-status').slideDown(); } else{ $('.network-filter-status')...
//========= PLUGIN ADD ON FOR MIXITUP ===================== // To keep our code clean and modular, all custom functionality will be contained inside a single object literal called "checkboxFilter". var checkboxFilter = { // Declare any variables we will need as properties of the object $filters: null, $reset...
{ var active = []; $('.checkbox input:checked').each(function() { active.push($(this).attr('data-filter')); }); var filtered = active.join(", "); if(filtered !== '') $('.filtered-list').html(filtered); else{ $('.filtered-list').html('All'); } }
identifier_body
global-network.js
//-------GLOBAL NETWORK JS-----------// var $ =jQuery.noConflict(); //Control Nav Dropdown/Active Section $('.network-nav-item').click(function(event) { var item = $(this).attr('id'); if(item == 'network-filter-topics'){ $('.network-filter-status').slideDown(); } else{ $('.network-filter-status').hi...
//URL FILTERS var filter = getParameterByName('filter'); //check if url filter is present - initialize mixitup and prefilter if(filter !==''){ $("input[value='" + filter + "']").prop('checked', true); $('#network-grid').mixItUp('filter', filter, GetActiveString); $(".network-filter-status").slid...
random_line_split
global-network.js
//-------GLOBAL NETWORK JS-----------// var $ =jQuery.noConflict(); //Control Nav Dropdown/Active Section $('.network-nav-item').click(function(event) { var item = $(this).attr('id'); if(item == 'network-filter-topics'){ $('.network-filter-status').slideDown(); } else{ $('.network-filter-status')...
(profile_id) { var is_loading = false; if (is_loading == false) { is_loading = true; $('#loader').show(); var data = { action: 'getSingleProfile', profile_id: profile_id }; jQuery.post(ajaxurl, data, function(response) { // appen...
loadProfile
identifier_name
global-network.js
//-------GLOBAL NETWORK JS-----------// var $ =jQuery.noConflict(); //Control Nav Dropdown/Active Section $('.network-nav-item').click(function(event) { var item = $(this).attr('id'); if(item == 'network-filter-topics'){ $('.network-filter-status').slideDown(); } else{ $('.network-filter-status')...
}); //Clost all filter sections $('.close-filter').click(function(e) { e.preventDefault(); $('.network-filter').hide(); //Hide all dropdowns }); //Live Search Global Network $("input#network-search").keyup(function(){ // Retrieve the input field text and reset the count to zero var filter = $(thi...
{ initialize(); }
conditional_block
handler.go
package main import ( "bytes" "encoding/json" "fmt" "io/ioutil" "log" "math/rand" "net/http" "os" "sort" "strings" "time" "github.com/gin-gonic/gin" ) type msg struct { Text string `json:"text"` GroupId string `json:"group_id"` Id string `json:"id"` Name string `json:"name"` S...
func getStats(season string, week string) map[int]map[string]float32 { url := "https://api.sleeper.app/v1/stats/nfl/regular/" + season + "/" + week resp, _ := http.Get(url) defer resp.Body.Close() bodyBytes, _ := ioutil.ReadAll(resp.Body) var stats map[int]map[string]float32 json.Unmarshal(bodyBytes, &stats) ...
{ url := "https://api.sleeper.app/v1/league/" + league + "/users" resp, _ := http.Get(url) defer resp.Body.Close() bodyBytes, _ := ioutil.ReadAll(resp.Body) var users []map[string]interface{} json.Unmarshal(bodyBytes, &users) return users }
identifier_body
handler.go
package main import ( "bytes" "encoding/json" "fmt" "io/ioutil" "log" "math/rand" "net/http" "os" "sort" "strings" "time" "github.com/gin-gonic/gin" ) type msg struct { Text string `json:"text"` GroupId string `json:"group_id"` Id string `json:"id"` Name string `json:"name"` S...
(botId string) { league := os.Getenv("league") users := getUsers(league) usernames := make(map[string]string) for _, value := range users { id, _ := value["user_id"].(string) display_name, _ := value["display_name"].(string) usernames[id] = display_name } log.Println(usernames) rosters := getRo...
sendStandings
identifier_name
handler.go
package main import ( "bytes" "encoding/json" "fmt" "io/ioutil" "log" "math/rand" "net/http" "os" "sort" "strings" "time" "github.com/gin-gonic/gin" ) type msg struct { Text string `json:"text"` GroupId string `json:"group_id"` Id string `json:"id"` Name string `json:"name"` S...
else if fields[0] == "!stats" { if len(fields) <= 3 || len(fields) >= 6 { c.JSON(http.StatusOK, nil) return } name := fields[1] + " " + fields[2] season := fields[3] week := "" if len(fields) == 5 { week = fields[4] } player, err := queryPlayer(name) if err != nil { ...
{ sendStandings(botId) }
conditional_block
handler.go
package main import ( "bytes" "encoding/json" "fmt" "io/ioutil" "log" "math/rand" "net/http" "os" "sort" "strings" "time" "github.com/gin-gonic/gin" ) type msg struct { Text string `json:"text"` GroupId string `json:"group_id"` Id string `json:"id"` Name string `json:"name"` S...
} log.Println(botId) log.Println(fields) if len(fields) == 0 { c.JSON(http.StatusOK, nil) return } if fields[0] == "!help" { if botResponse.GroupId == os.Getenv("htown") { sendPost("I am your chat bot.\nType `!coin` to flip a coin.\nType `!smack @someone` to talk trash.\nType `!suc...
}
random_line_split
install.rs
// * This file is part of the uutils coreutils package. // * // * (c) Ben Eills <ben@beneills.com> // * // * For the full copyright and license information, please view the LICENSE file // * that was distributed with this source code. // spell-checker:ignore (ToDO) rwxr sourcepath targetpath extern crate clap; ...
Copy one file to a new location, changing metadata. /// /// # Parameters /// /// _from_ must exist as a non-directory. /// _to_ must be a non-existent file, whose parent directory exists. /// /// # Errors /// /// If the copy system call fails, we print a verbose error and return an empty error value. /// fn copy(from: ...
0 } } ///
conditional_block
install.rs
// * This file is part of the uutils coreutils package. // * // * (c) Ben Eills <ben@beneills.com> // * // * For the full copyright and license information, please view the LICENSE file // * that was distributed with this source code. // spell-checker:ignore (ToDO) rwxr sourcepath targetpath extern crate clap; ...
py one file to a new location, changing metadata. /// /// # Parameters /// /// _from_ must exist as a non-directory. /// _to_ must be a non-existent file, whose parent directory exists. /// /// # Errors /// /// If the copy system call fails, we print a verbose error and return an empty error value. /// fn copy(from: &P...
copy(file, &target, b).is_err() { 1 } else { 0 } } /// Co
identifier_body
install.rs
// * This file is part of the uutils coreutils package. // * // * (c) Ben Eills <ben@beneills.com> // * // * For the full copyright and license information, please view the LICENSE file // * that was distributed with this source code. // spell-checker:ignore (ToDO) rwxr sourcepath targetpath extern crate clap; ...
(matches: &ArgMatches) -> Result<Behavior, i32> { let main_function = if matches.is_present("directory") { MainFunction::Directory } else { MainFunction::Standard }; let considering_dir: bool = MainFunction::Directory == main_function; let specified_mode: Option<u32> = if matches.i...
behavior
identifier_name
install.rs
// * This file is part of the uutils coreutils package. // * // * (c) Ben Eills <ben@beneills.com> // * // * For the full copyright and license information, please view the LICENSE file // * that was distributed with this source code. // spell-checker:ignore (ToDO) rwxr sourcepath targetpath extern crate clap; ...
/// Create directories Directory, /// Install files to locations (primary functionality) Standard, } impl Behavior { /// Determine the mode for chmod after copy. pub fn mode(&self) -> u32 { match self.specified_mode { Some(x) => x, None => DEFAULT_MODE, }...
random_line_split
modules.go
package venus_sealer import ( "context" "crypto/rand" "encoding/hex" "errors" "math" "net/http" "time" "github.com/filecoin-project/go-bitfield" proof2 "github.com/filecoin-project/specs-actors/v2/actors/runtime/proof" api2 "github.com/filecoin-project/venus-market/api" "github.com/gbrlsnchs/jwt/v3" "git...
(ma types2.MinerAddress) (types2.MinerID, error) { id, err := address.IDFromAddress(address.Address(ma)) return types2.MinerID(id), err } func MinerAddress(metaDataService *service.MetadataService) (types2.MinerAddress, error) { ma, err := metaDataService.GetMinerAddress() return types2.MinerAddress(ma), err } fu...
MinerID
identifier_name