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
EncryptDecryptTextFile.py
import os import pprint import math import sys import datetime as dt from pathlib import Path import RotateCipher import ShiftCipher import TranspositionCipher def process_textfile( string_path: str, encryption_algorithm: str, algorithm_key: float, output_folderpath: str = str( ...
if len(algo) == 0: algo = "rotate" pprint.pprint( process_textfile( string_path=input_filepath, encryption_algorithm=algo, algorithm_key=algorithm_key, output_folderpath=output_folder, o...
output_file = "EncryptDecrypt.txt"
conditional_block
row.rs
//! This module contains definition of table rows stuff use std::io::{Error, Write}; use std::iter::FromIterator; use std::slice::{Iter, IterMut}; // use std::vec::IntoIter; use std::ops::{Index, IndexMut}; use super::Terminal; use super::format::{ColumnPosition, TableFormat}; use super::utils::NEWLINE; use super::Ce...
} impl Default for Row { fn default() -> Row { Row::empty() } } impl Index<usize> for Row { type Output = Cell; fn index(&self, idx: usize) -> &Self::Output { &self.cells[idx] } } impl IndexMut<usize> for Row { fn index_mut(&mut self, idx: usize) -> &mut Self::Output { ...
{ let mut printed_columns = 0; for cell in self.iter() { printed_columns += cell.print_html(out)?; } // Pad with empty cells, if target width is not reached for _ in 0..col_num - printed_columns { Cell::default().print_html(out)?; } Ok(()) ...
identifier_body
row.rs
//! This module contains definition of table rows stuff use std::io::{Error, Write}; use std::iter::FromIterator; use std::slice::{Iter, IterMut}; // use std::vec::IntoIter; use std::ops::{Index, IndexMut}; use super::Terminal; use super::format::{ColumnPosition, TableFormat}; use super::utils::NEWLINE; use super::Ce...
(&self) -> Iter<Cell> { self.cells.iter() } /// Returns an mutable iterator over cells pub fn iter_mut(&mut self) -> IterMut<Cell> { self.cells.iter_mut() } /// Internal only fn __print<T: Write + ?Sized, F>( &self, out: &mut T, format: &TableFormat, ...
iter
identifier_name
row.rs
//! This module contains definition of table rows stuff use std::io::{Error, Write}; use std::iter::FromIterator; use std::slice::{Iter, IterMut}; // use std::vec::IntoIter; use std::ops::{Index, IndexMut}; use super::Terminal; use super::format::{ColumnPosition, TableFormat}; use super::utils::NEWLINE; use super::Ce...
pub(crate) fn get_column_width(&self, column: usize, format: &TableFormat) -> usize { let mut i = 0; for c in &self.cells { if i + c.get_hspan() > column { if c.get_hspan() == 1 { return c.get_width(); } let (lp, rp) = f...
/// Get the minimum width required by the cell in the column `column`. /// Return 0 if the cell does not exist in this row // #[deprecated(since="0.8.0", note="Will become private in future release. See [issue #87](https://github.com/phsym/prettytable-rs/issues/87)")]
random_line_split
leader_score.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import csv import logging import sys import time from datetime import datetime import apache_beam as beam from apache_beam.metrics.metric import Metrics from apache_beam.options.pipeline_option...
def __init__(self, field): super(ExtractAndSumScore, self).__init__() self.field = field def expand(self, pcoll): return (pcoll | beam.Map(lambda elem: (elem[self.field], elem['score'])) | beam.CombinePerKey(sum)) class TeamScoresDict(beam.DoFn): """Formats the data into a d...
random_line_split
leader_score.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import csv import logging import sys import time from datetime import datetime import apache_beam as beam from apache_beam.metrics.metric import Metrics from apache_beam.options.pipeline_option...
else: scores = p | 'ReadPubSub' >> beam.io.ReadFromPubSub( topic=args.topic) events = ( scores | 'ParseGameEventFn' >> beam.ParDo(ParseGameEventFn()) | 'AddEventTimestamps' >> beam.Map( lambda elem: beam.window.TimestampedValue(elem, elem['timestamp']))) ...
scores = p | 'ReadPubSub' >> beam.io.ReadFromPubSub( subscription=args.subscription)
conditional_block
leader_score.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import csv import logging import sys import time from datetime import datetime import apache_beam as beam from apache_beam.metrics.metric import Metrics from apache_beam.options.pipeline_option...
class WriteToBigQuery(beam.PTransform): """Generate, format, and write BigQuery table row information.""" def __init__(self, table_name, dataset, schema, project): """Initializes the transform. Args: table_name: Name of the BigQuery table to use. dataset: Name of the dataset to use. sch...
"""Formats the data into a dictionary of BigQuery columns with their values Receives a (team, score) pair, extracts the window start timestamp, and formats everything together into a dictionary. The dictionary is in the format {'bigquery_column': value} """ def process(self, team_score, window=beam.DoFn.Wind...
identifier_body
leader_score.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import argparse import csv import logging import sys import time from datetime import datetime import apache_beam as beam from apache_beam.metrics.metric import Metrics from apache_beam.options.pipeline_option...
(self): super(ParseGameEventFn, self).__init__() self.num_parse_errors = Metrics.counter(self.__class__, 'num_parse_errors') def process(self, elem): try: row = list(csv.reader([elem]))[0] yield { 'user': row[0], 'team': row[1], 'score': int(row[2]), 't...
__init__
identifier_name
main.go
package main import ( "VAST-WATERS-21789/models" "database/sql" "embed" "fmt" "log" "net/http" "strconv" "text/template" "time" "github.com/google/uuid" "golang.org/x/crypto/bcrypt" _ "github.com/go-sql-driver/mysql" "bytes" "strings" "github.com/vcraescu/go-paginator/v2" "github.com/vcraescu/go-pa...
? WHERE `user_id`=?") checkError(err) defer stmt.Close() _, err = stmt.Exec(time.Now().Format("2006-01-02 15:04:05"), sessionID) checkError(err) } //세션 초기화 func CleanSessions(db *sql.DB) { var sessionID string var currentTime string rows, err := db.Query("select session_id, current_time from sessions") if er...
`current_time`=
identifier_name
main.go
package main import ( "VAST-WATERS-21789/models" "database/sql" "embed" "fmt" "log" "net/http" "strconv" "text/template" "time" "github.com/google/uuid" "golang.org/x/crypto/bcrypt" _ "github.com/go-sql-driver/mysql" "bytes" "strings" "github.com/vcraescu/go-paginator/v2" "github.com/vcraescu/go-pa...
rn } // result.RowsAffected // returns found records count, equals `len(users)` // result.Error // returns error page := r.FormValue("page") if page == "" { page = "1" } pageInt, _ := strconv.Atoi(page) if keyword := r.FormValue("v"); keyword != "" { target := r.FormValue("target") switch targe...
o connect to /board/ for a while after logging out 11.07 retu
conditional_block
main.go
package main import ( "VAST-WATERS-21789/models" "database/sql" "embed" "fmt" "log" "net/http" "strconv" "text/template" "time" "github.com/google/uuid" "golang.org/x/crypto/bcrypt" _ "github.com/go-sql-driver/mysql" "bytes" "strings" "github.com/vcraescu/go-paginator/v2" "github.com/vcraescu/go-pa...
if page == "" { page = "1" } pageInt, _ := strconv.Atoi(page) if keyword := r.FormValue("v"); keyword != "" { target := r.FormValue("target") switch target { case "email": q := gormDB.Where("email LIKE ?", fmt.Sprintf("%%%s%%", keyword)).Find(&b) pg := paginator.New(adapter.NewGORMAdapter(q), MaxPer...
w http.ResponseWriter, r *http.Request) { var b []models.Board if !alreadyLoggedIn(w, r) { http.Redirect(w, r, "/", http.StatusSeeOther) //! possible to connect to /board/ for a while after logging out 11.07 return } // result.RowsAffected // returns found records count, equals `len(users)` // result.Error ...
identifier_body
main.go
package main import ( "VAST-WATERS-21789/models" "database/sql" "embed" "fmt" "log" "net/http" "strconv" "text/template" "time" "github.com/google/uuid" "golang.org/x/crypto/bcrypt" _ "github.com/go-sql-driver/mysql" "bytes" "strings" "github.com/vcraescu/go-paginator/v2" "github.com/vcraescu/go-pa...
c.MaxAge = sessionLength http.SetCookie(w, c) return true } //세션 로그인에 시간 표시 func UpdateCurrentTime(db *sql.DB, sessionID string) { stmt, err := db.Prepare("UPDATE sessions SET `current_time`=? WHERE `user_id`=?") checkError(err) defer stmt.Close() _, err = stmt.Exec(time.Now().Format("2006-01-02 15:04:05"), s...
random_line_split
elements.ts
import * as React from "react"; import { chainSingleArgFuncs, isSubset, notNil, omit, pick } from "../common"; import { createElementWithChildren, ensureNotArray, isReactNode, mergeProps, mergePropVals, NONE, } from "../react-utils"; import { Stack } from "./Stack"; interface Variants { [vg: string]: any...
(...children: React.ReactNode[]) { return React.createElement(React.Fragment, {}, ...children); } export const UNSET = Symbol("UNSET"); function mergeOverrideProps( defaults: Record<string, any>, overrides?: Record<string, any> ): Record<string, any> { if (!overrides) { return defaults; } const resul...
makeFragment
identifier_name
elements.ts
import * as React from "react"; import { chainSingleArgFuncs, isSubset, notNil, omit, pick } from "../common"; import { createElementWithChildren, ensureNotArray, isReactNode, mergeProps, mergePropVals, NONE, } from "../react-utils"; import { Stack } from "./Stack"; interface Variants { [vg: string]: any...
else { // We use the NONE sentinel if the overrideVal is nil, and is not one of the // props that we merge by default -- which are className, style, and // event handlers. This means for all other "normal" props -- like children, // title, etc -- a nil value will unset the default. if ( ...
{ delete result[key]; }
conditional_block
elements.ts
import * as React from "react"; import { chainSingleArgFuncs, isSubset, notNil, omit, pick } from "../common"; import { createElementWithChildren, ensureNotArray, isReactNode, mergeProps, mergePropVals, NONE, } from "../react-utils"; import { Stack } from "./Stack"; interface Variants { [vg: string]: any...
const o2 = deriveOverride(fo2); const wrap = chainSingleArgFuncs(...[o1.wrap, o2.wrap].filter(notNil)); const wrapChildren = chainSingleArgFuncs( ...[o1.wrapChildren, o2.wrapChildren].filter(notNil) ); // "render" type always takes precedence, but we still merge the props const props = mergeOverridePro...
return fo1; } const o1 = deriveOverride(fo1);
random_line_split
elements.ts
import * as React from "react"; import { chainSingleArgFuncs, isSubset, notNil, omit, pick } from "../common"; import { createElementWithChildren, ensureNotArray, isReactNode, mergeProps, mergePropVals, NONE, } from "../react-utils"; import { Stack } from "./Stack"; interface Variants { [vg: string]: any...
// We use data-plasmic-XXX attributes for custom properties since Typescript doesn't // support type check on jsx pragma. See https://github.com/microsoft/TypeScript/issues/21699 // for more info. const seenElements = new Map<string, React.ReactNode>(); export function createPlasmicElementProxy< DefaultElementType ...
{ if (!override || Object.keys(override).length === 0) { return createElementWithChildren(defaultRoot, defaultProps, defaultProps.children) } const override2 = deriveOverride(override); const props = mergeOverrideProps(defaultProps, override2.props); if (override2.type === "render") { return override2...
identifier_body
codegen.rs
use grammar::{Grammar, NontermName, Rule, Sym, TermName}; pub fn codegen<B:BackendText>(back: &mut B) -> String where // IMO these should not be necessary, see Rust issue #29143 B::Block: RenderIndent { let mut s = String::new(); s = s + &back.prefix(); let indent = back.rule_indent_preference(); ...
/ Given alpha = x1 x2 .. x_f, shorthand for /// /// code(x1 .. x_f, j, A) /// code( x2 .. x_f, j, A) /// ... /// code( x_f, j, A) /// /// Each `code` maps to a command and (potentially) a trailing label; /// therefore concatenating the codes results in a leading comm...
// FIXME: the infrastructure should be revised to allow me to // inline a sequence of terminals (since they do not need to // be encoded into separate labelled blocks). assert!(alpha.len() > 0); let (s_0, alpha) = alpha.split_at(1); match s_0[0] { Sym::T(t) => ...
identifier_body
codegen.rs
use grammar::{Grammar, NontermName, Rule, Sym, TermName}; pub fn codegen<B:BackendText>(back: &mut B) -> String where // IMO these should not be necessary, see Rust issue #29143 B::Block: RenderIndent { let mut s = String::new(); s = s + &back.prefix(); let indent = back.rule_indent_preference(); ...
f, a: TermName) -> C::Command { let b = &self.backend; let matches = b.curr_matches_term(a); let next_j = b.increment_curr(); let goto_l0 = b.goto_l0(); b.if_else(matches, next_j, goto_l0) } /// code(A_kα, j, X) = /// if test(I[j], X, A_k α) { /// c_u := c...
rm(&sel
identifier_name
codegen.rs
use grammar::{Grammar, NontermName, Rule, Sym, TermName}; pub fn codegen<B:BackendText>(back: &mut B) -> String where // IMO these should not be necessary, see Rust issue #29143 B::Block: RenderIndent { let mut s = String::new(); s = s + &back.prefix(); let indent = back.rule_indent_preference(); ...
let l_a_i = b.alternate_label((a, i)); let add_l_a_i = b.add(l_a_i); let c2 = b.if_(test, add_l_a_i); c = b.seq(c, c2); } let goto_l0 = b.goto_l0(); c = b.seq(c, goto_l0); c }; // each call t...
let mut c = b.no_op(); for (i, alpha) in alphas.iter().enumerate() { let test = b.test(a, (None, alpha));
random_line_split
mod.rs
use std::{ convert::TryInto, io::SeekFrom, mem::size_of, path::{Path, PathBuf}, }; use bincode::{deserialize, serialize_into, serialized_size}; use cfg_if::cfg_if; use once_cell::sync::OnceCell; use serde::{de::DeserializeOwned, Serialize}; use tokio::{ fs::{create_dir, remove_file, OpenOptions}, ...
/// Append single event to `source` log file (usually queue name) pub async fn persist_event<P>( &self, event: &Event<'_>, source: P, ) -> Result<(), PersistenceError> where P: AsRef<Path>, { self.append(event, source.as_ref().join(QUEUE_FILE)).await } ...
{ let path = self.config.path.join(source); debug!("Loading from {}", path.display()); let mut file = OpenOptions::new() .read(true) .open(path) .await .map_err(PersistenceError::from)?; Self::parse_log(&mut file).await }
identifier_body
mod.rs
use std::{ convert::TryInto, io::SeekFrom, mem::size_of, path::{Path, PathBuf}, }; use bincode::{deserialize, serialize_into, serialized_size}; use cfg_if::cfg_if; use once_cell::sync::OnceCell; use serde::{de::DeserializeOwned, Serialize}; use tokio::{ fs::{create_dir, remove_file, OpenOptions}, ...
() { let mut entries = Vec::new(); entries.append(&mut Log::make_log_entry(&vec![1u32, 2, 3]).unwrap()); entries.append(&mut Log::make_log_entry(&vec![4, 5, 6]).unwrap()); entries.append(&mut Log::make_log_entry(&vec![7, 8, 9]).unwrap()); let parsed = Log::parse_log::<Vec<u32>, _...
test_multiple_log_entries
identifier_name
mod.rs
use std::{ convert::TryInto, io::SeekFrom, mem::size_of, path::{Path, PathBuf}, }; use bincode::{deserialize, serialize_into, serialized_size}; use cfg_if::cfg_if; use once_cell::sync::OnceCell; use serde::{de::DeserializeOwned, Serialize}; use tokio::{ fs::{create_dir, remove_file, OpenOptions}, ...
debug!("Log entry size: {}", size); buf.reserve(size.try_into().map_err(PersistenceError::LogEntryTooBig)?); source .take(size) .read_buf(&mut buf) .await .map_err(PersistenceError::from)?; entries.push(de...
{ let size = source.read_u64_le().await.map_err(PersistenceError::from)?;
random_line_split
critical_cliques.rs
use crate::{ graph::{GraphWeight, IndexMap}, Graph, Weight, }; #[derive(Debug, Clone, Default)] pub struct CritClique { pub vertices: Vec<usize>, } pub struct CritCliqueGraph { pub cliques: Vec<CritClique>, pub graph: Graph<Weight>, } impl CritCliqueGraph { pub fn to_petgraph(&self) -> petgra...
}
{ // This is the example from "Guo: A more effective linear kernelization for cluster // editing, 2009", Fig. 1 let mut graph = Graph::new(9); graph.set(0, 1, Weight::ONE); graph.set(0, 2, Weight::ONE); graph.set(1, 2, Weight::ONE); graph.set(2, 3, Weight::ONE); ...
identifier_body
critical_cliques.rs
use crate::{ graph::{GraphWeight, IndexMap}, Graph, Weight, }; #[derive(Debug, Clone, Default)] pub struct CritClique { pub vertices: Vec<usize>, } pub struct CritCliqueGraph { pub cliques: Vec<CritClique>, pub graph: Graph<Weight>, } impl CritCliqueGraph { pub fn to_petgraph(&self) -> petgra...
visited[u] = true; let mut clique = CritClique::default(); clique.vertices.push(u); for v in g.nodes() { if visited[v] { continue; } // TODO: Is it maybe worth storing neighbor sets instead of recomputing them? if g.clo...
{ continue; }
conditional_block
critical_cliques.rs
use crate::{ graph::{GraphWeight, IndexMap}, Graph, Weight, }; #[derive(Debug, Clone, Default)] pub struct CritClique { pub vertices: Vec<usize>, } pub struct CritCliqueGraph { pub cliques: Vec<CritClique>, pub graph: Graph<Weight>, } impl CritCliqueGraph { pub fn
(&self) -> petgraph::Graph<String, u8, petgraph::Undirected, u32> { use petgraph::prelude::NodeIndex; let mut pg = petgraph::Graph::with_capacity(self.graph.size(), 0); for u in 0..self.graph.size() { pg.add_node( self.cliques[u] .vertices ...
to_petgraph
identifier_name
critical_cliques.rs
use crate::{ graph::{GraphWeight, IndexMap}, Graph, Weight, }; #[derive(Debug, Clone, Default)] pub struct CritClique { pub vertices: Vec<usize>, } pub struct CritCliqueGraph { pub cliques: Vec<CritClique>, pub graph: Graph<Weight>, } impl CritCliqueGraph { pub fn to_petgraph(&self) -> petgra...
// Now mark the clique and its neighbors as "removed" from the graph, so future reduction and // algorithm steps ignore it. (It is now a disjoint clique, i.e. already done.) for &u in clique_neighbors { g.set_present(u, false); } for &u in &clique.vertices { g.set_present(u, false); ...
*k -= *uv; Edit::delete(edits, &imap, u, v); *uv = f32::NEG_INFINITY; }
random_line_split
astropy_mm.py
# This program represents a Mueller matrix system for a Dual Channel Polarimeter, which includes: # a Wollaston Prism, a diattenuating retarder representing the derotator, a rotatable HWP, a diattenuating # retarder representing the third mirror, and a rotation matrix that compensates for parallactic rotation. # This u...
# Function that plots the difference of two beams of a Wollaston prism with a half-wave plate over the half-wave # plate angle def plot_wollaston(stokes): data = np.empty(shape=[0, 2]) sys_mm = MuellerMat.SystemMuellerMatrix([cmm.WollastonPrism(), cmm.HWP()]) # Find data points from 0 to 2 * pi for ...
sys_mm = MuellerMat.SystemMuellerMatrix([cmm.WollastonPrism(), cmm.HWP()]) sys_mm.master_property_dict['WollastonPrism']['beam'] = 'o' pos = sys_mm.evaluate() @ stokes sys_mm.master_property_dict['WollastonPrism']['beam'] = 'e' neg = sys_mm.evaluate() @ stokes return [pos, neg]
identifier_body
astropy_mm.py
# This program represents a Mueller matrix system for a Dual Channel Polarimeter, which includes: # a Wollaston Prism, a diattenuating retarder representing the derotator, a rotatable HWP, a diattenuating # retarder representing the third mirror, and a rotation matrix that compensates for parallactic rotation. # This u...
print("\nProgram ended.\n") if __name__ == "__main__": main()
find = input("\nWhat would you like to do?\na) compute the two beams of the Wollaston prism from Stokes " "parameters\nb) find the corresponding on-sky polarization with a set of measurements from " "the two beams of the Wollaston prism and HWP/parallactic angles data\nc) plot ...
conditional_block
astropy_mm.py
# This program represents a Mueller matrix system for a Dual Channel Polarimeter, which includes: # a Wollaston Prism, a diattenuating retarder representing the derotator, a rotatable HWP, a diattenuating # retarder representing the third mirror, and a rotation matrix that compensates for parallactic rotation. # This u...
# Function that plots the difference of two beams of a Wollaston prism with a half-wave plate of fixed targets # over the parallactic angle and time def track_plot(targets): # Initialize the start time, the targets, and the initial stokes vector time = Time("2015-09-13") step = np.arange(0, 1, 1 / 86400) ...
m_system = np.append(m_system, [row2[0]], axis=0) # Return a least-squares solution return inv(np.transpose(m_system) @ m_system) @ np.transpose(m_system) @ i
random_line_split
astropy_mm.py
# This program represents a Mueller matrix system for a Dual Channel Polarimeter, which includes: # a Wollaston Prism, a diattenuating retarder representing the derotator, a rotatable HWP, a diattenuating # retarder representing the third mirror, and a rotation matrix that compensates for parallactic rotation. # This u...
(stokes): sys_mm = MuellerMat.SystemMuellerMatrix([cmm.WollastonPrism(), cmm.HWP()]) sys_mm.master_property_dict['WollastonPrism']['beam'] = 'o' pos = sys_mm.evaluate() @ stokes sys_mm.master_property_dict['WollastonPrism']['beam'] = 'e' neg = sys_mm.evaluate() @ stokes return [pos, neg] # Fu...
wollaston
identifier_name
vmrestore-admitter.go
/* * This file is part of the KubeVirt project * * 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 la...
if ar.Request.Operation == admissionv1.Create && !admitter.Config.SnapshotEnabled() { return webhookutils.ToAdmissionResponseError(fmt.Errorf("Snapshot/Restore feature gate not enabled")) } vmRestore := &snapshotv1.VirtualMachineRestore{} // TODO ideally use UniversalDeserializer here err := json.Unmarshal(ar...
{ return webhookutils.ToAdmissionResponseError(fmt.Errorf("unexpected resource %+v", ar.Request.Resource)) }
conditional_block
vmrestore-admitter.go
/* * This file is part of the KubeVirt project * * 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 la...
func (admitter *VMRestoreAdmitter) validateCreateVM(field *k8sfield.Path, vmRestore *snapshotv1.VirtualMachineRestore) (causes []metav1.StatusCause, uid *types.UID, targetVMExists bool, err error) { vmName := vmRestore.Spec.Target.Name namespace := vmRestore.Namespace causes = admitter.validatePatches(vmRestore.S...
{ if ar.Request.Resource.Group != snapshotv1.SchemeGroupVersion.Group || ar.Request.Resource.Resource != "virtualmachinerestores" { return webhookutils.ToAdmissionResponseError(fmt.Errorf("unexpected resource %+v", ar.Request.Resource)) } if ar.Request.Operation == admissionv1.Create && !admitter.Config.Snapsho...
identifier_body
vmrestore-admitter.go
/* * This file is part of the KubeVirt project * * 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 la...
package admitters import ( "context" "encoding/json" "fmt" "strings" admissionv1 "k8s.io/api/admission/v1" "k8s.io/apimachinery/pkg/api/equality" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" k8sfield "k8s.io/apimachinery/pkg/util/validati...
* */
random_line_split
vmrestore-admitter.go
/* * This file is part of the KubeVirt project * * 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 la...
(ar *admissionv1.AdmissionReview) *admissionv1.AdmissionResponse { if ar.Request.Resource.Group != snapshotv1.SchemeGroupVersion.Group || ar.Request.Resource.Resource != "virtualmachinerestores" { return webhookutils.ToAdmissionResponseError(fmt.Errorf("unexpected resource %+v", ar.Request.Resource)) } if ar.Re...
Admit
identifier_name
config_diff.rs
use std::num::NonZeroU32; use merge::Merge; use schemars::JsonSchema; use segment::types::{HnswConfig, ProductQuantization, ScalarQuantization}; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use serde_json::Value; use validator::{Validate, ValidationErrors}; use crate::config::{CollectionParam...
} #[derive( Debug, Default, Deserialize, Serialize, JsonSchema, Validate, Copy, Clone, PartialEq, Eq, Merge, Hash, )] #[serde(rename_all = "snake_case")] pub struct HnswConfigDiff { /// Number of edges per node in the index graph. Larger the value - more accurate th...
{ from_full(full) }
identifier_body
config_diff.rs
use std::num::NonZeroU32; use merge::Merge; use schemars::JsonSchema; use segment::types::{HnswConfig, ProductQuantization, ScalarQuantization}; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use serde_json::Value; use validator::{Validate, ValidationErrors}; use crate::config::{CollectionParam...
/// result: {"a": 1, "b": 2} fn merge_level_0(base: &mut Value, diff: Value) { match (base, diff) { (base @ &mut Value::Object(_), Value::Object(diff)) => { let base = base.as_object_mut().unwrap(); for (k, v) in diff { if !v.is_null() { base.inser...
/// diff: {"a": null}
random_line_split
config_diff.rs
use std::num::NonZeroU32; use merge::Merge; use schemars::JsonSchema; use segment::types::{HnswConfig, ProductQuantization, ScalarQuantization}; use serde::de::DeserializeOwned; use serde::{Deserialize, Serialize}; use serde_json::Value; use validator::{Validate, ValidationErrors}; use crate::config::{CollectionParam...
() -> Self { QuantizationConfigDiff::Disabled(Disabled::Disabled) } } impl Validate for QuantizationConfigDiff { fn validate(&self) -> Result<(), ValidationErrors> { match self { QuantizationConfigDiff::Scalar(scalar) => scalar.validate(), QuantizationConfigDiff::Product...
new_disabled
identifier_name
reporter.py
import functools import json import logging import re import sys import types from contextlib import suppress from datetime import datetime, date, timezone from html import escape from pathlib import Path from pprint import pformat, saferepr import platform import jinja2 from exception_reports.traceback import get_lo...
return e
def my_str(self): m = ExceptionType.__str__(self) return f"{m} {added_message}" NewExceptionType = type(ExceptionType.__name__, (ExceptionType,), {"__str__": my_str}) e.__class__ = NewExceptionType
conditional_block
reporter.py
import functools import json import logging import re import sys import types from contextlib import suppress from datetime import datetime, date, timezone from html import escape from pathlib import Path from pprint import pformat, saferepr import platform import jinja2 from exception_reports.traceback import get_lo...
if "vars" in frame: frame_vars = [] for k, v in frame["vars"]: try: v = pformat(v) except Exception as e: try: v = saferepr(e) except Exception: v =...
frames = get_traceback_frames(exc_value=exc_value, tb=tb, get_full_tb=get_full_tb) for i, frame in enumerate(frames):
random_line_split
reporter.py
import functools import json import logging import re import sys import types from contextlib import suppress from datetime import datetime, date, timezone from html import escape from pathlib import Path from pprint import pformat, saferepr import platform import jinja2 from exception_reports.traceback import get_lo...
(exception_data, report_template=None): """Render exception_data as an html report""" report_template = report_template or _report_template() jinja_env = jinja2.Environment(loader=jinja2.BaseLoader(), extensions=["jinja2.ext.autoescape"]) exception_data["repr"] = repr return jinja_env.from_string(re...
render_exception_html
identifier_name
reporter.py
import functools import json import logging import re import sys import types from contextlib import suppress from datetime import datetime, date, timezone from html import escape from pathlib import Path from pprint import pformat, saferepr import platform import jinja2 from exception_reports.traceback import get_lo...
def get_traceback_frames(exc_value=None, tb=None, get_full_tb=True): def explicit_or_implicit_cause(exc_value): explicit = getattr(exc_value, "__cause__", None) implicit = getattr(exc_value, "__context__", None) return explicit or implicit # Get the exception and all its causes e...
""" Returns context_lines before and after lineno from file. Returns (pre_context_lineno, pre_context, context_line, post_context). """ source = None if loader is not None and hasattr(loader, "get_source"): with suppress(ImportError): source = loader.get_source(module_name) ...
identifier_body
jsds.js
import Base from './base'; import _ from 'lodash'; import fs from 'fs'; import gm from 'gm'; import uuid from 'node-uuid'; import tesseract from 'node-tesseract'; import cheerio from 'cheerio'; import md5File from 'md5-file'; export default class extends Base { fetchCaptcha(){ let codePath = 'code_' + uuid.v1...
onId } = this._logininfo; let ret = await this.httpPost('http://www.jsds.gov.cn/JkxxcxAction.do', { form: { sbsjq,sbsjz,sbbzl, errorMessage:'',handleDesc:'查询缴款信息',handleCode:'queryData', cqSb:'0',sessionId } }); let $ = cheerio.load(ret.body); let $trList = $('#query...
et { sessi
identifier_name
jsds.js
import Base from './base'; import _ from 'lodash'; import fs from 'fs'; import gm from 'gm'; import uuid from 'node-uuid'; import tesseract from 'node-tesseract'; import cheerio from 'cheerio'; import md5File from 'md5-file'; export default class extends Base { fetchCaptcha(){ let codePath = 'code_' + uuid.v1...
rjbxx(); await this.httpGet('http://www.jsds.gov.cn/MainAction.do', {qs:{sessionId}}); //let jkxx = await this.fetch_jkxx('2015-01-01','2016-12-31',''); console.log('地税:获取电子缴款...'); let dzjk = [ ...(await this.fetch_dzjk('2013-01-01','2016-12-31','','','1')), ...(await this.fetch_dzjk('2013...
t swglm = sessionId.split(';')[0]; let cwbbjdqx = 'Y01_120'; let res = await this.httpPost('http://www.jsds.gov.cn/wb032_WBcwbbListAction.do', { qs: {sessionId}, form: { sbnf,cwbbErrzt:'1',cwbbdldm:'CKL',errorMessage:'', swglm,curpzxh:'',handleDesc:'',handleCode:'submitSave', ...
identifier_body
jsds.js
import Base from './base'; import _ from 'lodash'; import fs from 'fs'; import gm from 'gm'; import uuid from 'node-uuid'; import tesseract from 'node-tesseract'; import cheerio from 'cheerio'; import md5File from 'md5-file'; export default class extends Base { fetchCaptcha(){ let codePath = 'code_' + uuid.v1...
+ "&swglm=" + ret.swglm + "&sqssq=" + encodeURI(ret.sqssq) + "&bsqxdm=" + ret.bsqxdm+"&cwbbjdqx="+cwbbjdqx; } } console.log(ret.href); return ret; }); console.log('获取财务报表step2'); cwbbList = _.compact(cwbbList); for(let i in cwbbList){ let res = await this.httpGe...
zxh=" + ret.ypzxh + "&swglm=" + ret.swglm + "&sqssq=" + encodeURI(ret.sqssq) + "&bsqxdm=" + ret.bsqxdm+"&cwbbjdqx="+cwbbjdqx; } else { ret.href = ret.url + "?sessionId=" +sessionId+ "&ssq=" + encodeURI(ret.ssq) + "&BBZT=" + ret.zt
conditional_block
jsds.js
import Base from './base'; import _ from 'lodash'; import fs from 'fs'; import gm from 'gm'; import uuid from 'node-uuid'; import tesseract from 'node-tesseract'; import cheerio from 'cheerio'; import md5File from 'md5-file'; export default class extends Base { fetchCaptcha(){ let codePath = 'code_' + uuid.v1(...
} }); let $ = cheerio.load(res.body); let info_tbl = $('table').eq(0); let info_tr = $('tr', info_tbl); let tzfxx_tr = $('#t_tzfxx tr').toArray().slice(1); let tzfxx = _.map(tzfxx_tr, o=>({ tzfmc: $('[name=tzfxxvo_tzfmc]', o).val(), zjzl: $('[name=tzfxxvo_zjzl]', o).val(), ...
let res = await this.httpGet('http://www.jsds.gov.cn/NsrjbxxAction.do', { qs:{ sessionId, dealMethod:'queryData', jsonData:JSON.stringify({ data:{gnfldm:'CXFW',sqzldm:'',ssxmdm:''} })
random_line_split
instanceservice.go
/** * @Author: lzw5399 * @Date: 2021/1/16 22:58 * @Desc: 流程实例服务 */ package service import ( "errors" "fmt" . "github.com/ahmetb/go-linq/v3" "workflow/src/global" "workflow/src/global/constant" "workflow/src/global/shared" "workflow/src/model" "workflow/src/model/dto" "workflow/src/model/request" "workf...
.Commit() } return &processEngine.ProcessInstance, err } // 否决流程 func (i *instanceService) DenyProcessInstance(r *request.DenyInstanceRequest, currentUserId uint, tenantId uint) (*model.ProcessInstance, error) { var ( tx = global.BankDb.Begin() // 开启事务 ) // 流程实例引擎 instanceEngine, err := engine.NewProcessEngi...
lback() } else { tx
conditional_block
instanceservice.go
/** * @Author: lzw5399 * @Date: 2021/1/16 22:58 * @Desc: 流程实例服务 */ package service import ( "errors" "fmt" . "github.com/ahmetb/go-linq/v3" "workflow/src/global" "workflow/src/global/constant" "workflow/src/global/shared" "workflow/src/model" "workflow/src/model/dto" "workflow/src/model/request" "workf...
dependencies = append(dependencies, currentNodeId) for _, edge := range definitionStructure.Edges { // 找到edge的source是当前nodeId的edge if edge.Source == currentNodeId && edge.FlowProperties != "0" { targetNodeIds = append(targetNodeIds, edge.Target) } } // 已经是最终节点了 if len(targetNodeIds) == 0 { *possibleTra...
// dependencies: 依赖项 // possibleTrainNodes: 最终返回的可能的流程链路 func getPossibleTrainNode(definitionStructure dto.Structure, currentNodeId string, dependencies []string, possibleTrainNodes *[][]string) { targetNodeIds := make([]string, 0) // 当前节点添加到依赖中
random_line_split
instanceservice.go
/** * @Author: lzw5399 * @Date: 2021/1/16 22:58 * @Desc: 流程实例服务 */ package service import ( "errors" "fmt" . "github.com/ahmetb/go-linq/v3" "workflow/src/global" "workflow/src/global/constant" "workflow/src/global/shared" "workflow/src/model" "workflow/src/model/dto" "workflow/src/model/request" "workf...
g, possibleTrainNodes *[][]string) { targetNodeIds := make([]string, 0) // 当前节点添加到依赖中 dependencies = append(dependencies, currentNodeId) for _, edge := range definitionStructure.Edges { // 找到edge的source是当前nodeId的edge if edge.Source == currentNodeId && edge.FlowProperties != "0" { targetNodeIds = append(targe...
"当前流程对应的模板为空") } // 3. 获取实例的当前nodeId列表 currentNodeIds := make([]string, len(instance.State)) for i, state := range instance.State { currentNodeIds[i] = state.Id } // 4. 获取所有的显示节点 shownNodes := make([]dto.Node, 0) currentNodeSortRange := make([]int, 0) // 当前节点的顺序区间, 在这个区间内的顺序都当作当前节点 initialNodeId := "" for...
identifier_body
instanceservice.go
/** * @Author: lzw5399 * @Date: 2021/1/16 22:58 * @Desc: 流程实例服务 */ package service import ( "errors" "fmt" . "github.com/ahmetb/go-linq/v3" "workflow/src/global" "workflow/src/global/constant" "workflow/src/global/shared" "workflow/src/model" "workflow/src/model/dto" "workflow/src/model/request" "workf...
:= make([]string, 0) // 当前节点添加到依赖中 dependencies = append(dependencies, currentNodeId) for _, edge := range definitionStructure.Edges { // 找到edge的source是当前nodeId的edge if edge.Source == currentNodeId && edge.FlowProperties != "0" { targetNodeIds = append(targetNodeIds, edge.Target) } } // 已经是最终节点了 if len(...
{ targetNodeIds
identifier_name
script.js
// An IIFE ("Iffy") - see the notes in mycourses (function(){ "use strict"; let NUM_SAMPLES = 128; let backgroundColor = "#ffffff"; let color = "#eb4034"; let audioElement; let analyserNode; let canvasBob; let canvas,ctx; let grad, songName; let bassFilter, trebleFilter; ...
var x = (ctx.canvas.width - noseWidth) / 2; var y = ((ctx.canvas.height - noseHeight) / 2) + 85; ctx.drawImage(nose, x, y, noseWidth, noseHeight); // drw image with scaled width and height //ctx.drawImage(mouth, 525+mouth.width/2, 450+mouth.height/2, ((100 + mouthData * 0.2)), ((100 + m...
{ noseWidth = nose.width * noseScale; }
conditional_block
script.js
// An IIFE ("Iffy") - see the notes in mycourses (function(){ "use strict"; let NUM_SAMPLES = 128; let backgroundColor = "#ffffff"; let color = "#eb4034"; let audioElement; let analyserNode; let canvasBob; let canvas,ctx; let grad, songName; let bassFilter, trebleFilter; ...
(){ // set up canvas stuff canvas = document.querySelector('canvas'); ctx = canvas.getContext("2d"); // get reference to <audio> element on page audioElement = document.querySelector('audio'); // call our helper function and get an analyser node analyser...
init
identifier_name
script.js
// An IIFE ("Iffy") - see the notes in mycourses (function(){ "use strict"; let NUM_SAMPLES = 128; let backgroundColor = "#ffffff"; let color = "#eb4034"; let audioElement; let analyserNode; let canvasBob; let canvas,ctx; let grad, songName; let bassFilter, trebleFilter; ...
ctx.drawImage(rightCheek, 630, 510); //Draw Mouth ctx.save(); // scale the image and make sure it isn't too small var mouthScale = mouthData / 100; var mouthHeight; if (mouth.height > (mouth.height * mouthScale)){ mouthHeight = mouth.height; }...
random_line_split
script.js
// An IIFE ("Iffy") - see the notes in mycourses (function(){ "use strict"; let NUM_SAMPLES = 128; let backgroundColor = "#ffffff"; let color = "#eb4034"; let audioElement; let analyserNode; let canvasBob; let canvas,ctx; let grad, songName; let bassFilter, trebleFilter; ...
{ window.location.href = 'meowsician.html'; }
identifier_body
tos.py
# Copyright (c) 2008 Johns Hopkins University. # All rights reserved. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose, without fee, and without written # agreement is hereby granted, provided that the above copyright # notice, the (updated) modification history ...
(self, ts = None, data = None): Packet.__init__(self, [('ts' , 'int', 4), ('data', 'blob', None)], None) self.ts = ts; self.data = data class AckFrame(Packet): def __init__(self, payload = None): Packet.__init...
__init__
identifier_name
tos.py
# Copyright (c) 2008 Johns Hopkins University. # All rights reserved. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose, without fee, and without written # agreement is hereby granted, provided that the above copyright # notice, the (updated) modification history ...
else: self._values[self._names.index(name)] = value def __ne__(self, other): if other.__class__ == self.__class__: return self._values != other._values else: return True def __eq__(self, other): if other.__class__ == self.__class__: ...
self._values[name] = value
conditional_block
tos.py
# Copyright (c) 2008 Johns Hopkins University. # All rights reserved. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose, without fee, and without written # agreement is hereby granted, provided that the above copyright # notice, the (updated) modification history ...
class ActiveMessage(Packet): def __init__(self, gpacket = None, amid = 0x00, dest = 0xFFFF): if type(gpacket) == type([]): payload = gpacket else: # Assume this will be derived from Packet payload = None Packet.__init__(self, [('d...
def __init__(self, payload = None): if payload != None and type(payload) != type([]): # Assume is a Packet payload = payload.payload() Packet.__init__(self, [('protocol', 'int', 1), ('dispatch', 'int', 1), ...
identifier_body
tos.py
# Copyright (c) 2008 Johns Hopkins University. # All rights reserved. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose, without fee, and without written # agreement is hereby granted, provided that the above copyright # notice, the (updated) modification history ...
print "Wait for ack %d ..." % (seqno) try: self._get_ack(timeout, seqno) except ReadTimeoutError: # Re-raise read timeouts (of ack packets) as write timeouts (of # the write operation) self._write_counter_failures += 1 raise WriteT...
print "Send(%d/%d): %s" % (self._write_counter, self._write_counter_failures, packet)
random_line_split
derivatives.py
import numpy as np import scipy.sparse as spsp import pyamg from pyamg.gallery import stencil_grid from pysit.util.derivatives.fdweight import * from pysit.util.matrix_helpers import make_diag_mtx __all__ = ['build_derivative_matrix','build_derivative_matrix_VDA', 'build_heterogenous_matrices','build_permutation_m...
(bc): if bc.type == 'pml': return bc.boundary_type elif bc.type == 'ghost': return ('ghost', bc.n) else: return bc.type def _build_derivative_matrix_structured_cartesian(mesh, derivative, order_accuracy, ...
_set_bc
identifier_name
derivatives.py
import numpy as np import scipy.sparse as spsp import pyamg from pyamg.gallery import stencil_grid from pysit.util.derivatives.fdweight import * from pysit.util.matrix_helpers import make_diag_mtx __all__ = ['build_derivative_matrix','build_derivative_matrix_VDA', 'build_heterogenous_matrices','build_permutation_m...
sh = mesh.shape(include_bc = True, as_grid = True) #Will include PML padding if len(sh) != 2: raise Exception('currently hardcoded 2D implementation, relatively straight-forward to change. Look at the function build_derivative_matrix to get a more general function.') nx = sh[0] nz = sh[-1] #Curre...
raise ValueError('First derivative requires a direciton')
conditional_block
derivatives.py
import numpy as np import scipy.sparse as spsp import pyamg from pyamg.gallery import stencil_grid from pysit.util.derivatives.fdweight import * from pysit.util.matrix_helpers import make_diag_mtx __all__ = ['build_derivative_matrix','build_derivative_matrix_VDA', 'build_heterogenous_matrices','build_permutation_mat...
sh = mesh.shape(include_bc = True, as_grid = True) #Will include PML padding if len(sh) != 2: raise Exception('currently hardcoded 2D implementation, relatively straight-forward to change. Look at the function build_derivative_matrix to get a more general function.') nx = sh[0] nz = sh[-1] #Current...
random_line_split
derivatives.py
import numpy as np import scipy.sparse as spsp import pyamg from pyamg.gallery import stencil_grid from pysit.util.derivatives.fdweight import * from pysit.util.matrix_helpers import make_diag_mtx __all__ = ['build_derivative_matrix','build_derivative_matrix_VDA', 'build_heterogenous_matrices','build_permutation_m...
def _turn_sparse_rows_to_identity(A, rows_to_keep, rows_to_change): #Convenience function for removing some rows from the sparse laplacian #Had some major performance problems by simply slicing in all the matrix formats I tried. nr,nc = A.shape if nr != nc: raise Exception('assuming square ma...
import time tt = time.time() if return_1D_matrix: raise Exception('Not yet implemented') if derivative < 1 or derivative > 2: raise ValueError('Only defined for first and second order right now') if derivative == 1 and dimension not in ['x', 'y', 'z']: raise ValueError('First ...
identifier_body
analyse_magnetic_linecuts_3D.py
import json import numpy as np from scipy.optimize import least_squares from scipy.interpolate import interp1d from scipy.integrate import trapz # import matplotlib.pyplot as plt from tqdm import tqdm from skspatial.objects import Plane from skspatial.objects import Points from skspatial.plotting import plot_3d from ...
d_pts = d_pts.reshape(2*N_linecuts, 2) # plt.scatter(pts[:, 0], pts[:, 1], c=d_map.ravel()) # fig = plt.figure() # ax = fig.add_subplot(projection='3d') # ax.scatter(pts[:, 0], pts[:, 1], d_map.ravel()) # plt.show() pts = np.zeros((2*N_linecuts, 3)) pts[:,0] = d_pts[:,0] pts[...
d_pts[0,pbar.n-1] = cx d_pts[1,pbar.n-1] = cz d_map[0,pbar.n-1] = d_x d_map[1,pbar.n-1] = d_z
conditional_block
analyse_magnetic_linecuts_3D.py
import json import numpy as np from scipy.optimize import least_squares from scipy.interpolate import interp1d from scipy.integrate import trapz # import matplotlib.pyplot as plt from tqdm import tqdm from skspatial.objects import Plane from skspatial.objects import Points from skspatial.plotting import plot_3d from ...
(lcx, lcxv, lcy, lcyv, fwhm, t): result = least_squares(two_cut_gaussian_residual, args=( lcx, lcxv, lcy, lcyv, fwhm, t), x0=get_x_guess(lcx, lcy), bounds=get_bounds(lcx, lcy)) return result def fit_magnetic_edge_with_gaussian_layer(lcx, lcxv, lcy, lcyv, fwhm, t, NVt): result = least_squares(tw...
fit_magnetic_edge_with_gaussian
identifier_name
analyse_magnetic_linecuts_3D.py
import json import numpy as np from scipy.optimize import least_squares from scipy.interpolate import interp1d from scipy.integrate import trapz # import matplotlib.pyplot as plt from tqdm import tqdm from skspatial.objects import Plane from skspatial.objects import Points from skspatial.plotting import plot_3d from ...
def two_cut_residual(params, lcx, lcxv, lcy, lcyv, t): flcx, flcy = evaluate_cuts(params, lcx, lcy, t) return np.concatenate([lcxv-flcx, lcyv-flcy]) def two_cut_gaussian_residual(params, lcx, lcxv, lcy, lcyv, fwhm, t): cflcx, cflcy = evaluate_gaussian_cuts(params, lcx, lcy, fwhm, t) return np.concate...
random_line_split
analyse_magnetic_linecuts_3D.py
import json import numpy as np from scipy.optimize import least_squares from scipy.interpolate import interp1d from scipy.integrate import trapz # import matplotlib.pyplot as plt from tqdm import tqdm from skspatial.objects import Plane from skspatial.objects import Points from skspatial.plotting import plot_3d from ...
def fit_magnetic_edge(lcx, lcxv, lcy, lcyv, t): result = least_squares(two_cut_residual, args=( lcx, lcxv, lcy, lcyv, t), x0=get_x_guess(lcx, lcy), bounds=get_bounds(lcx, lcy)) return result def fit_magnetic_edge_with_gaussian(lcx, lcxv, lcy, lcyv, fwhm, t): result = least_squares(two_cut_ga...
return compact_params( x0_x=lcx[len(lcx)//2], x0_y=lcy[len(lcy)//2], Ms=1e-2, theta=30*np.pi/180, phi=0, rot=0, d_x=3e-6, d_z=3e-6, c_x=0, c_y=0 )
identifier_body
upcean_reader.go
package oned import ( "strconv" "github.com/makiuchi-d/gozxing" ) const ( // These two values are critical for determining how permissive the decoding will be. // We've arrived at these values through a lot of trial and error. Setting them any higher // lets false positives creep in quickly. UPCEANReader_MAX_A...
resultString, nil, // no natural byte representation for these barcodes []gozxing.ResultPoint{ gozxing.NewResultPoint(left, float64(rowNumber)), gozxing.NewResultPoint(right, float64(rowNumber)), }, format) extensionLength := 0 extensionResult, e := this.extensionReader.decodeRow(rowNumber, row, end...
left := float64(startGuardRange[1]+startGuardRange[0]) / 2.0 right := float64(endRange[1]+endRange[0]) / 2.0 format := this.getBarcodeFormat() decodeResult := gozxing.NewResult(
random_line_split
upcean_reader.go
package oned import ( "strconv" "github.com/makiuchi-d/gozxing" ) const ( // These two values are critical for determining how permissive the decoding will be. // We've arrived at these values through a lot of trial and error. Setting them any higher // lets false positives creep in quickly. UPCEANReader_MAX_A...
// UPCEANReader_findGuardPatternWithCounters Find guard pattern // @param row row of black/white values to search // @param rowOffset position to start search // @param whiteFirst if true, indicates that the pattern specifies white/black/white/... // pixel counts, otherwise, it is interpreted as black/white/black/......
{ counters := make([]int, len(pattern)) return upceanReader_findGuardPatternWithCounters(row, rowOffset, whiteFirst, pattern, counters) }
identifier_body
upcean_reader.go
package oned import ( "strconv" "github.com/makiuchi-d/gozxing" ) const ( // These two values are critical for determining how permissive the decoding will be. // We've arrived at these values through a lot of trial and error. Setting them any higher // lets false positives creep in quickly. UPCEANReader_MAX_A...
else { counterPosition++ } counters[counterPosition] = 1 isWhite = !isWhite } } return nil, gozxing.NewNotFoundException() } // UPCEANReader_decodeDigit Attempts to decode a single UPC/EAN-encoded digit. // // @param row row of black/white values to decode // @param counters the counts of runs of obs...
{ if PatternMatchVariance(counters, pattern, UPCEANReader_MAX_INDIVIDUAL_VARIANCE) < UPCEANReader_MAX_AVG_VARIANCE { return []int{patternStart, x}, nil } patternStart += counters[0] + counters[1] copy(counters[:counterPosition-1], counters[2:counterPosition+1]) counters[counterPosition-1] = 0 ...
conditional_block
upcean_reader.go
package oned import ( "strconv" "github.com/makiuchi-d/gozxing" ) const ( // These two values are critical for determining how permissive the decoding will be. // We've arrived at these values through a lot of trial and error. Setting them any higher // lets false positives creep in quickly. UPCEANReader_MAX_A...
( row *gozxing.BitArray, rowOffset int, whiteFirst bool, pattern, counters []int) ([]int, error) { width := row.GetSize() if whiteFirst { rowOffset = row.GetNextUnset(rowOffset) } else { rowOffset = row.GetNextSet(rowOffset) } counterPosition := 0 patternStart := rowOffset patternLength := len(pattern) is...
upceanReader_findGuardPatternWithCounters
identifier_name
timeseries.ts
//import 'gscript-mocks.ts'; import { DateUtils, toObject, KeyValueMap } from './utils'; import { SheetUtils, SpreadsheetApp, ISheet, Logging } from './utils-google'; import { Prognoser, createPrognosis } from './prognoser'; import { Aggregation } from './aggregation'; function getAccountIdsToExclude(data: any[][]): a...
export function run() { var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheets()[0]; var columns = SheetUtils.getHeaderColumnsAsObject(sheet); var rxFilter = SheetUtils.getColumnRegexFilter(sheet, columns.AccountId); var filters = Timeseries.createFilters( columns, rxFilter, ...
{ var header = data[0]; data = data.slice(1); var result = data.map(r => { var tmp = r.map((_v, i) => [header[i], r[i]]).filter(o => !!o[1]); return toObject(tmp, v => v); }); return result; }
identifier_body
timeseries.ts
//import 'gscript-mocks.ts'; import { DateUtils, toObject, KeyValueMap } from './utils'; import { SheetUtils, SpreadsheetApp, ISheet, Logging } from './utils-google'; import { Prognoser, createPrognosis } from './prognoser'; import { Aggregation } from './aggregation'; function getAccountIdsToExclude(data: any[][]): a...
//Filter out specific transactions: if (sheetFilterTransactions) { var transactionsToExclude = getTransactionsToExclude( sheetFilterTransactions.getDataRange().getValues() ); if (transactionsToExclude && transactionsToExclude.length) { result.push( data => ...
{ var accountIdsToExclude = getAccountIdsToExclude( sheetFilterAccounts.getDataRange().getValues() ); if (accountIdsToExclude && accountIdsToExclude.length) { result.push( data => data.filter( r => accountIdsToExclude.indexOf(r[columns.AccountId]) < ...
conditional_block
timeseries.ts
//import 'gscript-mocks.ts'; import { DateUtils, toObject, KeyValueMap } from './utils'; import { SheetUtils, SpreadsheetApp, ISheet, Logging } from './utils-google'; import { Prognoser, createPrognosis } from './prognoser'; import { Aggregation } from './aggregation'; function getAccountIdsToExclude(data: any[][]): a...
( sheet: ISheet, numYearsLookbackAvg?: number, sheetPrognosisSpec?: ISheet, prognosisUntil?: string | Date, funcFilters?: Function[] ) { numYearsLookbackAvg = numYearsLookbackAvg == null ? 2 : numYearsLookbackAvg; prognosisUntil = new Date(prognosisUntil || '2020-01-01'); var data = s...
recalc
identifier_name
timeseries.ts
//import 'gscript-mocks.ts'; import { DateUtils, toObject, KeyValueMap } from './utils'; import { SheetUtils, SpreadsheetApp, ISheet, Logging } from './utils-google'; import { Prognoser, createPrognosis } from './prognoser'; import { Aggregation } from './aggregation'; function getAccountIdsToExclude(data: any[][]): a...
} return visibleRows; } static createFilters( columns: KeyValueMap<number>, rxAccountIdColumnFilter?: RegExp | null, sheetFilterAccounts?: ISheet, sheetFilterTransactions?: ISheet ): Array<(data: any[][]) => any[][]> { var result: Array<(data: any[][]) => any[][]> = []; if (rxAcco...
visibleRows.push(rows[j]); }
random_line_split
runtime.rs
use crate::durability::Durability; use crate::hash::*; use crate::plumbing::CycleRecoveryStrategy; use crate::revision::{AtomicRevision, Revision}; use crate::{Cancelled, Cycle, Database, DatabaseKeyIndex, Event, EventKind}; use log::debug; use parking_lot::lock_api::{RawRwLock, RawRwLockRecursive}; use parking_lot::{M...
}
} }
random_line_split
runtime.rs
use crate::durability::Durability; use crate::hash::*; use crate::plumbing::CycleRecoveryStrategy; use crate::revision::{AtomicRevision, Revision}; use crate::{Cancelled, Cycle, Database, DatabaseKeyIndex, Event, EventKind}; use log::debug; use parking_lot::lock_api::{RawRwLock, RawRwLockRecursive}; use parking_lot::{M...
(&self) { self.local_state .report_untracked_read(self.current_revision()); } /// Acts as though the current query had read an input with the given durability; this will force the current query's durability to be at most `durability`. /// /// This is mostly useful to control the dur...
report_untracked_read
identifier_name
runtime.rs
use crate::durability::Durability; use crate::hash::*; use crate::plumbing::CycleRecoveryStrategy; use crate::revision::{AtomicRevision, Revision}; use crate::{Cancelled, Cycle, Database, DatabaseKeyIndex, Event, EventKind}; use log::debug; use parking_lot::lock_api::{RawRwLock, RawRwLockRecursive}; use parking_lot::{M...
} pub(crate) fn permits_increment(&self) -> bool { self.revision_guard.is_none() && !self.local_state.query_in_progress() } #[inline] pub(crate) fn push_query(&self, database_key_index: DatabaseKeyIndex) -> ActiveQueryGuard<'_> { self.local_state.push_query(database_key_index) ...
{ for rev in &self.shared_state.revisions[1..=d.index()] { rev.store(new_revision); } }
conditional_block
runtime.rs
use crate::durability::Durability; use crate::hash::*; use crate::plumbing::CycleRecoveryStrategy; use crate::revision::{AtomicRevision, Revision}; use crate::{Cancelled, Cycle, Database, DatabaseKeyIndex, Event, EventKind}; use log::debug; use parking_lot::lock_api::{RawRwLock, RawRwLockRecursive}; use parking_lot::{M...
/// Reports that the query depends on some state unknown to salsa. /// /// Queries which report untracked reads will be re-executed in the next /// revision. pub fn report_untracked_read(&self) { self.local_state .report_untracked_read(self.current_revision()); } /// A...
{ self.local_state .report_query_read_and_unwind_if_cycle_resulted(input, durability, changed_at); }
identifier_body
pg_cre_table.py
#!/usr/bin/env python3 # SPDX-License-Identifier: MIT # Copyright (c) 2016-2020 Michael Purcaro, Henry Pratt, Jill Moore, Zhiping Weng import psycopg2 import json import itertools from io import StringIO import io from operator import itemgetter import sys import os from natsort import natsorted from collections i...
(self, j, chrom, start, stop): """ tfclause = "peakintersections.accession = cre.accession" if "tfs" in j: tfclause += " and peakintersections.tf ?| array(" + ",".join(["'%s'" % tf for tf in j["tfs"]]) + ")" """ fields, whereClause = self._buildWhereStatement(j, chr...
creTable
identifier_name
pg_cre_table.py
#!/usr/bin/env python3 # SPDX-License-Identifier: MIT # Copyright (c) 2016-2020 Michael Purcaro, Henry Pratt, Jill Moore, Zhiping Weng import psycopg2 import json import itertools from io import StringIO import io from operator import itemgetter import sys import os from natsort import natsorted from collections i...
elif not isclose(_range[0], minDefault): self.whereClauses.append("(%s)" % "cre.%s_zscores[%d] >= %f" % (exp, cti, _range[0])) elif not isclose(_range[1], maxDefault): self.whereClauses.append("(%s)" % ...
self.whereClauses.append("(%s)" % " and ".join( ["cre.%s_zscores[%d] >= %f" % (exp, cti, _range[0]), "cre.%s_zscores[%d] <= %f" % (exp, cti, _range[1])]))
conditional_block
pg_cre_table.py
#!/usr/bin/env python3 # SPDX-License-Identifier: MIT # Copyright (c) 2016-2020 Michael Purcaro, Henry Pratt, Jill Moore, Zhiping Weng import psycopg2 import json import itertools from io import StringIO import io from operator import itemgetter import sys import os from natsort import natsorted from collections i...
def _sct(self, ct): if ct in self.ctsTable: self.fields.append("cre.creGroupsSpecific[%s] AS sct" % # TODO rename to sct self.ctsTable[ct]) else: self.fields.append("0::int AS sct") def _buildWhereStatement(self, j, chrom, start, stop): ...
pairs = [] if not useAccs: for k, v in self.ctSpecifc.items(): pairs.append("'%s', %s" % (k, v)) return "json_build_object(" + ','.join(pairs) + ") as ctSpecifc"
identifier_body
pg_cre_table.py
#!/usr/bin/env python3 # SPDX-License-Identifier: MIT # Copyright (c) 2016-2020 Michael Purcaro, Henry Pratt, Jill Moore, Zhiping Weng import psycopg2 import json import itertools from io import StringIO import io from operator import itemgetter import sys import os from natsort import natsorted from collections i...
result = [] response = sorted(response, key=itemgetter('transcript_id')) for (key, value) in itertools.groupby(response, key=itemgetter('transcript_id')): v = [] start = '' end = '' strand = '' ...
'strand': row[6].rstrip(), 'exon_number': row[5], 'parent': row[7], })
random_line_split
main.go
package main import ( "encoding/binary" "encoding/json" "errors" "flag" "fmt" "github.com/dgryski/go-metro" "io" "io/ioutil" "log" "net/http" "os" "os/signal" "path" "regexp" "strconv" "strings" "sync" "sync/atomic" "syscall" "time" ) type Stats struct { Tags map[string]uint64 Offset uint64 F...
(name string) *PostingsList { this.RLock() name = sanitize(name) if p, ok := this.index[name]; ok { this.RUnlock() return p } this.RUnlock() this.Lock() defer this.Unlock() if p, ok := this.index[name]; ok { return p } f, offset := openAtEnd(path.Join(this.root, fmt.Sprintf("%s.postings", name))) p ...
CreatePostingsList
identifier_name
main.go
package main import ( "encoding/binary" "encoding/json" "errors" "flag" "fmt" "github.com/dgryski/go-metro" "io" "io/ioutil" "log" "net/http" "os" "os/signal" "path" "regexp" "strconv" "strings" "sync" "sync/atomic" "syscall" "time" ) type Stats struct { Tags map[string]uint64 Offset uint64 F...
{ var pbind = flag.String("bind", ":8000", "address to bind to") var proot = flag.String("root", "/tmp/rochefort", "root directory") var pquiet = flag.Bool("quiet", false, "dont print any log messages") flag.Parse() multiStore := &MultiStore{ stores: make(map[string]*StoreItem), root: *proot, } os.MkdirA...
identifier_body
main.go
package main import ( "encoding/binary" "encoding/json" "errors" "flag" "fmt" "github.com/dgryski/go-metro" "io" "io/ioutil" "log" "net/http" "os" "os/signal" "path" "regexp" "strconv" "strings" "sync" "sync/atomic" "syscall" "time" ) type Stats struct { Tags map[string]uint64 Offset uint64 F...
delete(this.stores, storageIdentifier) } func (this *MultiStore) modify(storageIdentifier string, offset uint64, pos int32, data io.Reader) error { return this.find(storageIdentifier).modify(offset, pos, data) } func (this *MultiStore) stats(storageIdentifier string) *Stats { return this.find(storageIdentifier).s...
{ storage.descriptor.Close() log.Printf("closing: %s", storage.path) }
conditional_block
main.go
package main import ( "encoding/binary" "encoding/json" "errors" "flag" "fmt" "github.com/dgryski/go-metro" "io" "io/ioutil" "log" "net/http" "os" "os/signal" "path" "regexp" "strconv" "strings" "sync" "sync/atomic" "syscall" "time" ) type Stats struct { Tags map[string]uint64 Offset uint64 F...
} func NewStorage(root string) *StoreItem { os.MkdirAll(root, 0700) filePath := path.Join(root, "append.raw") f, offset := openAtEnd(filePath) si := &StoreItem{ offset: uint64(offset), path: filePath, index: map[string]*PostingsList{}, descriptor: f, root: root, } files, err := ...
return f, uint64(offset)
random_line_split
ProjectWatcher.ts
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. import * as fs from 'fs'; import * as os from 'os'; import * as readline from 'readline'; import { once } from 'events'; import { getRepoRoot } from '@rushstack/packa...
} return false; } private static *_enumeratePathsToWatch(paths: Iterable<string>, prefixLength: number): Iterable<string> { for (const path of paths) { const rootSlashIndex: number = path.indexOf('/', prefixLength); if (rootSlashIndex < 0) { yield path; return; } ...
{ return true; }
conditional_block
ProjectWatcher.ts
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. import * as fs from 'fs'; import * as os from 'os'; import * as readline from 'readline'; import { once } from 'events'; import { getRepoRoot } from '@rushstack/packa...
private _setStatus(status: string): void { if (this._hasRenderedStatus) { readline.clearLine(process.stdout, 0); readline.cursorTo(process.stdout, 0); } else { this._hasRenderedStatus = true; } this._terminal.write(Colors.bold(Colors.cyan(`Watch Status: ${status}`))); } /** ...
{ const initialChangeResult: IProjectChangeResult = await this._computeChanged(); // Ensure that the new state is recorded so that we don't loop infinitely this._commitChanges(initialChangeResult.state); if (initialChangeResult.changedProjects.size) { return initialChangeResult; } const p...
identifier_body
ProjectWatcher.ts
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. import * as fs from 'fs'; import * as os from 'os'; import * as readline from 'readline'; import { once } from 'events'; import { getRepoRoot } from '@rushstack/packa...
(status: string): void { if (this._hasRenderedStatus) { readline.clearLine(process.stdout, 0); readline.cursorTo(process.stdout, 0); } else { this._hasRenderedStatus = true; } this._terminal.write(Colors.bold(Colors.cyan(`Watch Status: ${status}`))); } /** * Determines which, i...
_setStatus
identifier_name
ProjectWatcher.ts
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information. import * as fs from 'fs'; import * as os from 'os'; import * as readline from 'readline'; import { once } from 'events'; import { getRepoRoot } from '@rushstack/packa...
} yield path.slice(0, rootSlashIndex); let slashIndex: number = path.indexOf('/', rootSlashIndex + 1); while (slashIndex >= 0) { yield path.slice(0, slashIndex); slashIndex = path.indexOf('/', slashIndex + 1); } } } }
yield path; return;
random_line_split
ti_eclipsify.py
#!/usr/bin/env python
""" * tidevtools 'ti_eclipsify' - Prepare a Titanium mobile 1.8.0+ project folder * for importing into Eclipse. * * Copyright (c) 2010-2012 by Bill Dawson * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. * http://github.com/billdawson/t...
random_line_split
ti_eclipsify.py
#!/usr/bin/env python """ * tidevtools 'ti_eclipsify' - Prepare a Titanium mobile 1.8.0+ project folder * for importing into Eclipse. * * Copyright (c) 2010-2012 by Bill Dawson * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. * http://g...
full_path = os.path.join(TIMOBILE_SRC, rel_path) if not os.path.exists(full_path): newlines.append(line) continue newlines.append("%s=%s\n" % (line.split("=")[0], os.path.relpath(full_path, android_folder))) f = codecs.open(props_file, 'w', 'utf-8') f.write("".join(newlines)) f.close()
newlines.append(line) continue
conditional_block
arp_gmp_intf_entry.pb.go
/* Copyright 2019 Cisco Systems 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 d...
() { proto.RegisterType((*ArpGmpIntfEntry_KEYS)(nil), "cisco_ios_xr_ipv4_arp_oper.arp_gmp.vrfs.vrf.interface_configured_ips.interface_configured_ip.arp_gmp_intf_entry_KEYS") proto.RegisterType((*ArpGmpConfigEntry)(nil), "cisco_ios_xr_ipv4_arp_oper.arp_gmp.vrfs.vrf.interface_configured_ips.interface_configured_ip.arp_...
init
identifier_name
arp_gmp_intf_entry.pb.go
/* Copyright 2019 Cisco Systems 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 d...
func (m *ArpGmpConfigEntry) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_ArpGmpConfigEntry.Marshal(b, m, deterministic) } func (m *ArpGmpConfigEntry) XXX_Merge(src proto.Message) { xxx_messageInfo_ArpGmpConfigEntry.Merge(m, src) } func (m *ArpGmpConfigEntry) XXX_Size() int { ret...
func (m *ArpGmpConfigEntry) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_ArpGmpConfigEntry.Unmarshal(m, b) }
random_line_split
arp_gmp_intf_entry.pb.go
/* Copyright 2019 Cisco Systems 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 d...
func (m *ArpGmpConfigEntry) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_ArpGmpConfigEntry.Marshal(b, m, deterministic) } func (m *ArpGmpConfigEntry) XXX_Merge(src proto.Message) { xxx_messageInfo_ArpGmpConfigEntry.Merge(m, src) } func (m *ArpGmpConfigEntry) XXX_Size() int { re...
{ return xxx_messageInfo_ArpGmpConfigEntry.Unmarshal(m, b) }
identifier_body
arp_gmp_intf_entry.pb.go
/* Copyright 2019 Cisco Systems 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 d...
return "" } type ArpGmpConfigEntry struct { IpAddress string `protobuf:"bytes,1,opt,name=ip_address,json=ipAddress,proto3" json:"ip_address,omitempty"` HardwareAddress string `protobuf:"bytes,2,opt,name=hardware_address,json=hardwareAddress,proto3" json:"hardware_address,omitempty"` Encapsulat...
{ return m.Address }
conditional_block
manage_cpu_test.go
/* * Copyright (c) 2021 THL A29 Limited, a Tencent company. * * 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 applica...
(value uint64) *uint64 { var p *uint64 p = new(uint64) *p = value return p }
uint64Pointer
identifier_name
manage_cpu_test.go
/* * Copyright (c) 2021 THL A29 Limited, a Tencent company. * * 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 applica...
}() } } type cpuQuotaTestData struct { describe string limit int64 weight *uint64 expect struct { limit string weight string } } // TestQosCpuQuota_Manage test cpu quota qos manager func TestQosCpuQuota_Manage(t *testing.T) { testCases := []cpuQuotaTestData{ { describe: "quota test", lim...
{ t.Fatalf("cpu qos cpuset test case(%s) failed, expect online %s, got %s", tc.describe, tc.expect.online, onCpusets) }
conditional_block
manage_cpu_test.go
/* * Copyright (c) 2021 THL A29 Limited, a Tencent company. * * 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 applica...
return p }
func uint64Pointer(value uint64) *uint64 { var p *uint64 p = new(uint64) *p = value
random_line_split
manage_cpu_test.go
/* * Copyright (c) 2021 THL A29 Limited, a Tencent company. * * 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 applica...
func readCpuSetCgroup(cgPath string) (value string, err error) { data, err := ioutil.ReadFile(filepath.Join(cgPath, "cpuset.cpus")) if err != nil { return "", err } return strings.Replace(string(data), "\n", "", -1), nil } func mkdirCgPath(cgPath string) (existed bool, err error) { existed = true _, err = os...
{ cpuInfo, err := cpu.Info() if err != nil { return 0, err } return int64(len(cpuInfo)), nil }
identifier_body
scanner.rs
use crate::file::{FileContent, FileSet}; use crate::metadata::Metadata; use std::cell::RefCell; use std::cmp; use std::collections::btree_map::Entry as BTreeEntry; use std::collections::hash_map::Entry as HashEntry; use std::collections::BTreeMap; use std::collections::BinaryHeap; use std::collections::HashMap; use std...
self.stats.added += 1; if let Some(fileset) = self.new_fileset(&path, metadata) { self.dedupe_by_content(fileset, path, metadata)?; } else { self.stats.hardlinks += 1; self.stats.bytes_saved_by_hardlinks += metadata.size() as usize; } Ok(()) ...
random_line_split