file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
row.rs | /// 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)")]
pub(crate) fn get_column_width(&sel... |
}
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 | /// 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)")]
pub(crate) fn get_column_width(&sel... | (&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 | 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 | .options.pipeline_options import SetupOptions
from apache_beam.options.pipeline_options import StandardOptions
from apache_beam.transforms import trigger
def timestamp2str(t, fmt='%Y-%m-%d %H:%M:%S.000'):
"""Converts a unix timestamp into a formatted string."""
return datetime.fromtimestamp(t).strftime(fmt)
cla... | 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 | .pipeline_options import SetupOptions
from apache_beam.options.pipeline_options import StandardOptions
from apache_beam.transforms import trigger
def timestamp2str(t, fmt='%Y-%m-%d %H:%M:%S.000'):
"""Converts a unix timestamp into a formatted string."""
return datetime.fromtimestamp(t).strftime(fmt)
class Parse... |
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 | .pipeline_options import SetupOptions
from apache_beam.options.pipeline_options import StandardOptions
from apache_beam.transforms import trigger
def timestamp2str(t, fmt='%Y-%m-%d %H:%M:%S.000'):
"""Converts a unix timestamp into a formatted string."""
return datetime.fromtimestamp(t).strftime(fmt)
class Parse... |
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 | .pipeline_options import SetupOptions
from apache_beam.options.pipeline_options import StandardOptions
from apache_beam.transforms import trigger
def timestamp2str(t, fmt='%Y-%m-%d %H:%M:%S.000'):
"""Converts a unix timestamp into a formatted string."""
return datetime.fromtimestamp(t).strftime(fmt)
class Parse... | (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 | pl.ExecuteTemplate(w, "board.gohtml", temp)
return
case "id":
q := gormDB.Where("id LIKE ?", fmt.Sprintf("%%%s%%", keyword)).Find(&b)
pg := paginator.New(adapter.NewGORMAdapter(q), MaxPerPage)
pg.SetPage(pageInt)
if err := pg.Results(&b); err != nil {
panic(err)
}
pgNums, _ := pg.PageNums()
... | `current_time`= | identifier_name | |
main.go | :04:05")
//day := req.PostFormValue("day")
//totaltime := req.PostFormValue("totaltime")
//trytime := req.PostFormValue("trytime")
//recoverytime := req.PostFormValue("recoverytime")
//frontcount := req.PostFormValue("frontcount")
//backcount := req.PostFormValue("backcount")
//avgrpm := req.PostFormValue("avgrp... | o connect to /board/ for a while after logging out 11.07
retu | conditional_block | |
main.go | req.PostFormValue("trytime")
//recoverytime := req.PostFormValue("recoverytime")
//frontcount := req.PostFormValue("frontcount")
//backcount := req.PostFormValue("backcount")
//avgrpm := req.PostFormValue("avgrpm")
//avgspeed := req.PostFormValue("avgspeed")
//distance := req.PostFormValue("distance")
//musclen... | 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 | ()
pageSlice := getPageList(page, pgNums)
temp := models.PassedData{
PostData: b,
Target: target,
Value: keyword,
PageList: pageSlice,
Page: page,
}
tpl.ExecuteTemplate(w, "board.gohtml", temp)
return
case "id":
q := gormDB.Where("id LIKE ?", fmt.Sprintf("%%%s%%", keyw... | random_line_split | ||
elements.ts | include
// React.ReactFragment, which includes {}, which would allow any object to be passed in,
// defeating any attempt to type-check!
| React.ReactChild
// Ignored
| null
| undefined
// dict of props for the DefaultElementType
| (Partial<React.ComponentProps<DefaultElementType>> & {
wrap?: n... | (...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 | include
// React.ReactFragment, which includes {}, which would allow any object to be passed in,
// defeating any attempt to type-check!
| React.ReactChild
// Ignored
| null
| undefined
// dict of props for the DefaultElementType
| (Partial<React.ComponentProps<DefaultElementType>> & {
wrap?: n... | 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 | );
const props = mergeOverrideProps(defaultProps, override2.props);
if (override2.type === "render") {
return override2.render(
props as React.ComponentProps<DefaultElementType>,
defaultRoot
);
}
let root = defaultRoot;
if (override2.type === "as" && override2.as) {
if (defaultRoot ==... | return fo1;
}
const o1 = deriveOverride(fo1); | random_line_split | |
elements.ts | include
// React.ReactFragment, which includes {}, which would allow any object to be passed in,
// defeating any attempt to type-check!
| React.ReactChild
// Ignored
| null
| undefined
// dict of props for the DefaultElementType
| (Partial<React.ComponentProps<DefaultElementType>> & {
wrap?: n... | props.as = override2.as;
} else {
root = override2.as;
}
}
let children = props.children;
if (override2.wrapChildren) {
children = override2.wrapChildren(ensureNotArray(children));
}
if (wrapChildrenInFlex) {
// For legacy, we still support data-plasmic-wrap-flex-children
ch... | {
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 | NontermName, usize)) -> Self::Label;
/// L_A labels parse function for A.
fn nonterm_label(&self, a: NontermName) -> Self::Label;
/// L_A_i labels function for parsing ith alternate α_i of A.
fn alternate_label(&self,
a_i: (NontermName, usize)) -> Self::Label;
/// `L: C`
... | / 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 | NontermName, usize)) -> Self::Label;
/// L_A labels parse function for A.
fn nonterm_label(&self, a: NontermName) -> Self::Label;
/// L_A_i labels function for parsing ith alternate α_i of A.
fn alternate_label(&self,
a_i: (NontermName, usize)) -> Self::Label;
/// `L: C`
... | 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 | [j], X, A_k α) {
/// c_u := create(R_A_k, c_u, j), goto L_A
/// } else {
/// goto L_0
/// }
/// R_A_k:
pub fn on_nonterm_instance<E:Copy>(&self,
(a, k): (NontermName, usize),
alpha: &[Sym<E>],
... | 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 | [`Log`] driver to save event log,
/// so [`Snapshot`] driver is being used to fill the gap.
snapshot: OnceCell<Snapshot<'c>>,
}
impl<'c> Log<'c> {
pub fn new(config: &'c PersistenceConfig) -> Self {
Log {
config,
snapshot: OnceCell::new(),
}
}
/// Make log ... |
/// 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 | <'c> Log<'c> {
pub fn new(config: &'c PersistenceConfig) -> Self {
Log {
config,
snapshot: OnceCell::new(),
}
}
/// Make log entry from serializable source
///
/// Returns bytes buffer, filled with header (currently only with entry size) and serialized entry,... | test_multiple_log_entries | identifier_name | |
mod.rs | on [`Log`] driver to save event log,
/// so [`Snapshot`] driver is being used to fill the gap.
snapshot: OnceCell<Snapshot<'c>>,
}
impl<'c> Log<'c> {
pub fn new(config: &'c PersistenceConfig) -> Self {
Log {
config,
snapshot: OnceCell::new(),
}
}
/// Make l... | 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 | clique_idx: usize,
crit_graph: &CritCliqueGraph,
) -> (Vec<usize>, usize) {
let crit_neighbors = crit_graph.graph.neighbors(clique_idx);
let mut count = 0;
let neighborhood = crit_neighbors
.flat_map(|n| {
count += 1;
&crit_graph.cliques[n].vertices
})
.c... | {
// 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 |
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 | (&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 | 2 = get_clique_neighbors2(g, clique_idx, &crit);
let threshold = (clique_len + neighbors_len) / 2;
for &u in &neighbors2 {
let count = count_intersection(g.neighbors(u), &clique_neighbors);
if count > threshold {
... | *k -= *uv;
Edit::delete(edits, &imap, u, v);
*uv = f32::NEG_INFINITY;
}
| random_line_split | |
astropy_mm.py | MuellerMat import MuellerMat
import math
import numpy as np
from numpy.linalg import inv
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from astroplan import Observer, FixedTarget, download_IERS_A
from astropy.time import Time
import datetime
# Initialize the telescope
keck = Observer.at_site("Kec... |
# 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 | telescope
keck = Observer.at_site("Keck Observatory", timezone="US/Hawaii")
fig, ax = plt.subplots()
plt.rcParams['font.family'] = 'Times New Roman'
plt.rcParams['font.size'] = 22
plt.rcParams['figure.figsize'] = (20, 20)
# Function to find the two beams of the Wollaston prism based on the Stokes parameters
def woll... | 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 | MuellerMat import MuellerMat
import math
import numpy as np
from numpy.linalg import inv
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from astroplan import Observer, FixedTarget, download_IERS_A
from astropy.time import Time
import datetime
# Initialize the telescope
keck = Observer.at_site("Kec... |
# 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 | MuellerMat import MuellerMat
import math
import numpy as np
from numpy.linalg import inv
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from astroplan import Observer, FixedTarget, download_IERS_A
from astropy.time import Time
import datetime
# Initialize the telescope
keck = Observer.at_site("Kec... | (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 | /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/validation/field"
"k8s.io/client-go/tools/cache"
"kubevirt.io/api/core"
v1 "kubevirt.io/api/core/v1"
snapshotv1... |
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 | /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/validation/field"
"k8s.io/client-go/tools/cache"
"kubevirt.io/api/core"
v1 "kubevirt.io/api/core/v1"
snapshotv1... | switch ar.Request.Operation {
case admissionv1.Create:
var targetUID *types.UID
targetField := k8sfield.NewPath("spec", "target")
if vmRestore.Spec.Target.APIGroup == nil {
causes = []metav1.StatusCause{
{
Type: metav1.CauseTypeFieldValueNotFound,
Message: "missing apiGroup",
Field: ... | {
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 | 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 | /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/validation/field"
"k8s.io/client-go/tools/cache"
"kubevirt.io/api/core"
v1 "kubevirt.io/api/core/v1"
snapshotv1... | (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 |
}
#[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 | required to build the index.
#[validate(range(min = 4))]
#[serde(skip_serializing_if = "Option::is_none")]
pub ef_construct: Option<usize>,
/// Minimal size (in kilobytes) of vectors for additional payload-based indexing.
/// If payload chunk is smaller than `full_scan_threshold_kb` additional inde... | /// 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 | /// Store HNSW index on disk. If set to false, the index will be stored in RAM. Default: false
#[serde(default, skip_serializing_if = "Option::is_none")]
pub on_disk: Option<bool>,
/// Custom M param for additional payload-aware HNSW links. If not set, default M will be used.
#[serde(default, skip_s... | new_disabled | identifier_name | |
reporter.py | (types.TracebackType, TracebackFrameProxy)):
return "<Traceback object>"
return saferepr(obj)
def get_exception_data(exc_type=None, exc_value=None, tb=None, get_full_tb=False, max_var_length=4096 + 2048):
"""
Return a dictionary containing exception information.
if exc_type, exc_value, and ... | 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 | _report_template():
"""get the report template"""
current_dir = Path(__file__).parent
with open(current_dir / "report_template.html", "r") as f:
template = f.read()
template = re.sub(r"\s{2,}", " ", template)
template = re.sub(r"\n", "", template)
template = re.sub(r"> <", ... | 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 | _report_template():
"""get the report template"""
current_dir = Path(__file__).parent
with open(current_dir / "report_template.html", "r") as f:
template = f.read()
template = re.sub(r"\s{2,}", " ", template)
template = re.sub(r"\n", "", template)
template = re.sub(r"> <", ... | (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 | _report_template():
"""get the report template"""
current_dir = Path(__file__).parent
with open(current_dir / "report_template.html", "r") as f:
template = f.read()
template = re.sub(r"\s{2,}", " ", template)
template = re.sub(r"\n", "", template)
template = re.sub(r"> <", ... | if isinstance(source[0], bytes):
encoding = "ascii"
for line in source[:2]:
# File coding may be specified. Match pattern from PEP-263
# (http://www.python.org/dev/peps/pep-0263/)
match = re.search(br"coding[:=]\s*([-\w.]+)", line)
... | """
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 | 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 | console.log('debug2');
console.log(deal_args);
deal_args = deal_args.substring(deal_args.indexOf('(')+1,deal_args.lastIndexOf(')'));
console.log('debug3');
deal_args = _.map(deal_args.split(','),o=>o.substr(1,o.length-2));
console.log('debug4');
let ret = {
sbnf,
... | 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 | ';
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',
cwbbjdqxmc:'年度终了后4月内',cwbbjdqx
}
})
console.lo... | + "&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 | }
});
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 | (
processDefinition model.ProcessDefinition // 流程模板
tx = global.BankDb.Begin() // 开启事务
)
// 检查变量是否合法
err := validateVariables(r.Variables)
if err != nil {
return nil, util.BadRequest.New(err)
}
// 查询对应的流程模板
err = global.BankDb.
Where("id = ?", r.ProcessDefinitionId).
Where("tenant_id ... | .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 | // 根据type的不同有不同的逻辑
switch r.Type {
case constant.I_MyToDo:
db = db.Joins("cross join jsonb_array_elements(state) as elem").Where(fmt.Sprintf("elem -> 'processor' @> '%v'", currentUserId))
break
case constant.I_ICreated:
db = db.Where("create_by=?", currentUserId)
break
case constant.I_IRelated:
db = db.W... | // dependencies: 依赖项
// possibleTrainNodes: 最终返回的可能的流程链路
func getPossibleTrainNode(definitionStructure dto.Structure, currentNodeId string, dependencies []string, possibleTrainNodes *[][]string) {
targetNodeIds := make([]string, 0)
// 当前节点添加到依赖中 | random_line_split | |
instanceservice.go | processDefinition model.ProcessDefinition // 流程模板
tx = global.BankDb.Begin() // 开启事务
)
// 检查变量是否合法
err := validateVariables(r.Variables)
if err != nil {
return nil, util.BadRequest.New(err)
}
// 查询对应的流程模板
err = global.BankDb.
Where("id = ?", r.ProcessDefinitionId).
Where("tenant_id = ?... | currentNodeSortRange = append(currentNodeSortRange, util.StringToInt(node.Sort))
}
// 找出开始节点的id
if node.Clazz == constant.START {
initialNodeId = node.Id
}
shownNodes = append(shownNodes, node)
}
// 5. 遍历出可能的流程链路
possibleTrainNodesList := make([][]string, 0, util.Pow(len(definition.Structure.Nodes)... | "当前流程对应的模板为空")
}
// 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 | model.ProcessInstance{}).Where("tenant_id = ?", tenantId)
// 根据type的不同有不同的逻辑
switch r.Type {
case constant.I_MyToDo:
db = db.Joins("cross join jsonb_array_elements(state) as elem").Where(fmt.Sprintf("elem -> 'processor' @> '%v'", currentUserId))
break
case constant.I_ICreated:
db = db.Where("create_by=?", cu... | {
targetNodeIds | identifier_name | |
script.js | function init(){
// 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
... |
var x = (ctx.canvas.width - noseWidth) / 2;
var y = ((ctx.canvas.height - noseHeight) / 2) + 85;
ctx.drawImage(nose, x, y, noseWidth, noseHeight); // dr | {
noseWidth = nose.width * noseScale;
} | conditional_block |
script.js | function | (){
// 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 | function init(){
// 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
... | 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 | ContextWithAnalyserNode(audioElement) {
let audioCtx, analyserNode, sourceNode;
// create new AudioContext
// The || is because WebAudio has not been standardized across browsers yet
// http://webaudio.github.io/web-audio-api/#the-audiocontext-interface
audioCtx = new (window.Aud... | {
window.location.href = 'meowsician.html';
} | identifier_body | |
tos.py | endtime:
try:
ackwait = ACK_WAIT
if endtime is not None:
remaining = endtime - time.time()
ackwait = min(ACK_WAIT, remaining)
before = time.time()
self._simple_serial.write(payload, self._seqno, ackwait... | __init__ | identifier_name | |
tos.py | serial port.
Retries packet reads until the timeout expires.
Throws ReadTimeoutError if a a packet can't be read within the timeout.
"""
if timeout is None:
timeout = self.timeout
endtime = None
if timeout is not None:
endtime = time.time() + ... | self._values[name] = value | conditional_block | |
tos.py | further processing for the printf packet
return packet
class SFClient:
def __init__(self, host, port, qsize=10):
self._in_queue = Queue(qsize)
self._s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._s.connect((host, port))
data = self._s.recv(2)
if data !=... | 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 | ._get_byte(timeout)
ts = time.time()
# We are now on the 2nd byte of the packet. Add it to
# our retrieved packet data:
packet.append(d)
# Read bytes from serial until we read another
# HDLC_FLAG_BYTE value (end of the current packet):
... | 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 | (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 | ifferences=False):
if order_accuracy%2:
raise ValueError('Only even accuracy orders supported.')
centered_coeffs = centered_difference(derivative, order_accuracy)/(h**derivative)
mtx = stencil_grid(centered_coeffs, (npoints, ), format='lil')
max_shift= order_accuracy//2
if use_shifted_d... |
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 | ifferences=False):
if order_accuracy%2:
raise ValueError('Only even accuracy orders supported.')
centered_coeffs = centered_difference(derivative, order_accuracy)/(h**derivative)
mtx = stencil_grid(centered_coeffs, (npoints, ), format='lil')
max_shift= order_accuracy//2
if use_shifted_d... | 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 | _differences=False):
if order_accuracy%2:
raise ValueError('Only even accuracy orders supported.')
centered_coeffs = centered_difference(derivative, order_accuracy)/(h**derivative)
mtx = stencil_grid(centered_coeffs, (npoints, ), format='lil')
max_shift= order_accuracy//2
if use_shifted... | #Later it is probably better to define the density directly on the stagger points (and evaluate density gradient there to update directly at these points?)
if type(alpha) == None: #If no alpha is given, we set it to a uniform vector. The result should be the homogeneous Laplacian.
alpha = np.ones(nx*nz... | 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 | kernel_x))
# fig, axes = plt.subplots(2, 3)
# axes[0][0].plot(fx(x_smooth), label="edge")
# axes[0][1].plot(cflcx_smooth, label="edge*G")
# axes[0][2].plot(x_smooth, kernel_x, label="G")
# axes[1][0].plot(fy(y_smooth), label="edge")
# axes[1][1].plot(cflcy_smooth, label="edge*G")
# axes[1][... |
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 | _x))
# fig, axes = plt.subplots(2, 3)
# axes[0][0].plot(fx(x_smooth), label="edge")
# axes[0][1].plot(cflcx_smooth, label="edge*G")
# axes[0][2].plot(x_smooth, kernel_x, label="G")
# axes[1][0].plot(fy(y_smooth), label="edge")
# axes[1][1].plot(cflcy_smooth, label="edge*G")
# axes[1][2].plot... | (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 | _x))
# fig, axes = plt.subplots(2, 3)
# axes[0][0].plot(fx(x_smooth), label="edge")
# axes[0][1].plot(cflcx_smooth, label="edge*G")
# axes[0][2].plot(x_smooth, kernel_x, label="G")
# axes[1][0].plot(fy(y_smooth), label="edge")
# axes[1][1].plot(cflcy_smooth, label="edge*G")
# axes[1][2].plot... |
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 | _x))
# fig, axes = plt.subplots(2, 3)
# axes[0][0].plot(fx(x_smooth), label="edge")
# axes[0][1].plot(cflcx_smooth, label="edge*G")
# axes[0][2].plot(x_smooth, kernel_x, label="G")
# axes[1][0].plot(fy(y_smooth), label="edge")
# axes[1][1].plot(cflcy_smooth, label="edge*G")
# axes[1][2].plot... |
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 | s := make([]int, len(widths))
for j := 0; j < len(widths); j++ {
reversedWidths[j] = widths[len(widths)-j-1]
}
UPCEANReader_L_AND_G_PATTERNS[i] = reversedWidths
}
}
type upceanRowDecoder interface {
RowDecoder
// getBarcodeFormat Get the format of this decoder.
// @return The 1D format.
getBarcodeFormat... | 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 | := range counters {
counters[i] = 0
}
var e error
startRange, e = upceanReader_findGuardPatternWithCounters(
row, nextStart, false, UPCEANReader_START_END_PATTERN, counters)
if e != nil {
return nil, e
}
start := startRange[0]
nextStart = startRange[1]
// Make sure there is a quiet zone at lea... | {
counters := make([]int, len(pattern))
return upceanReader_findGuardPatternWithCounters(row, rowOffset, whiteFirst, pattern, counters)
} | identifier_body | |
upcean_reader.go | decoding a barcode in the row
// @throws NotFoundException if no potential barcode is found
// @throws ChecksumException if a potential barcode is found but does not pass its checksum
// @throws FormatException if a potential barcode is found but format is invalid
func (this *upceanReader) decodeRowWithStartRange(
ro... | {
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 | nextStart - start)
if quietStart >= 0 {
foundStart, _ = row.IsRange(quietStart, start, false)
}
}
return startRange, nil
}
func (this *upceanReader) DecodeRow(rowNumber int, row *gozxing.BitArray, hints map[gozxing.DecodeHintType]interface{}) (*gozxing.Result, error) {
start, e := upceanReader_findStartGuard... | upceanReader_findGuardPatternWithCounters | identifier_name | |
timeseries.ts |
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 | rxFilter = SheetUtils.getColumnRegexFilter(sheet, columns.AccountId);
var filters = Timeseries.createFilters(
columns,
rxFilter,
ss.getSheetByName('filter_accounts'),
ss.getSheetByName('filter_tx')
);
var inYear = Timeseries.recalc(
sheet,
2,
ss.getSheetByName('prognosis_spec'),
... |
//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 | rxFilter = SheetUtils.getColumnRegexFilter(sheet, columns.AccountId);
var filters = Timeseries.createFilters(
columns,
rxFilter,
ss.getSheetByName('filter_accounts'),
ss.getSheetByName('filter_tx')
);
var inYear = Timeseries.recalc(
sheet,
2,
ss.getSheetByName('prognosis_spec'),
... | (
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 | rxFilter = SheetUtils.getColumnRegexFilter(sheet, columns.AccountId);
var filters = Timeseries.createFilters(
columns,
rxFilter,
ss.getSheetByName('filter_accounts'),
ss.getSheetByName('filter_tx')
);
var inYear = Timeseries.recalc(
sheet,
2,
ss.getSheetByName('prognosis_spec'),
... | }
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 | atedPanic.throw(),
WaitResult::Cycle(c) => c.throw(),
}
}
/// Invoked when this runtime completed computing `database_key` with
/// the given result `wait_result` (`wait_result` should be `None` if
/// computing `database_key` panicked and could not complete).
/// This function... | }
} | random_line_split | |
runtime.rs | last_changed_revision(&self, d: Durability) -> Revision {
self.shared_state.revisions[d.index()].load()
}
/// Read current value of the revision counter.
#[inline]
pub(crate) fn pending_revision(&self) -> Revision {
self.shared_state.pending_revision.load()
}
#[cold]
pub(c... | (&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 | _changed_revision(&self, d: Durability) -> Revision {
self.shared_state.revisions[d.index()].load()
}
/// Read current value of the revision counter.
#[inline]
pub(crate) fn pending_revision(&self) -> Revision {
self.shared_state.pending_revision.load()
}
#[cold]
pub(crate)... |
}
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 | _changed_revision(&self, d: Durability) -> Revision {
self.shared_state.revisions[d.index()].load()
}
/// Read current value of the revision counter.
#[inline]
pub(crate) fn pending_revision(&self) -> Revision {
self.shared_state.pending_revision.load()
}
#[cold]
pub(crate)... |
/// 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 | PGcreTable.infoFields.items():
pairs.append("'%s', %s" % (k, v))
return "json_build_object(" + ','.join(pairs) + ") as info"
def __init__(self, pw, assembly, ctmap, ctsTable):
self.pw = pw
self.assembly = assembly
self.ctmap = ctmap
self.ctsTable = ctsTable
... | (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 | cre.start",
"cre.stop - cre.start AS len",
"cre.gene_all_id", "cre.gene_pc_id",
"0::int as in_cart",
"cre.pct"]
self.whereClauses = []
def _getCtSpecific(self, useAccs):
pairs = []
if not useAccs:
for k, v in self.ctSpecifc.items()... | 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 | PGcreTable.infoFields.items():
pairs.append("'%s', %s" % (k, v))
return "json_build_object(" + ','.join(pairs) + ") as info"
def __init__(self, pw, assembly, ctmap, ctsTable):
self.pw = pw
self.assembly = assembly
self.ctmap = ctmap
self.ctsTable = ctsTable
... |
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 | PGcreTable.infoFields.items():
pairs.append("'%s', %s" % (k, v))
return "json_build_object(" + ','.join(pairs) + ") as info"
def __init__(self, pw, assembly, ctmap, ctsTable):
self.pw = pw
self.assembly = assembly
self.ctmap = ctmap
self.ctsTable = ctsTable
... | 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 | (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 | {
// this is lockless, which means we could read a header,
// but the data might be incomplete
dataLen, _, allocSize, err := readHeader(this.descriptor, offset)
if err != nil {
break SCAN
}
output := make([]byte, dataLen)
_, err = this.descriptor.ReadAt(output, int64(offset)+int64(headerLen))
if er... | {
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 | 8
}
return out
}
func (this *StoreItem) scan(cb func(uint64, []byte) bool) {
SCAN:
for offset := uint64(0); offset < this.offset; {
// this is lockless, which means we could read a header,
// but the data might be incomplete
dataLen, _, allocSize, err := readHeader(this.descriptor, offset)
if err != nil ... |
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 | }
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 | Folder, gitPath));
this._initialState = initialState;
this._previousState = initialState;
this._hasRenderedStatus = false;
}
/**
* Waits for a change to the package-deps of one or more of the selected projects, since the previous invocation.
* Will return immediately the first time it is invoke... | {
return true;
} | conditional_block | |
ProjectWatcher.ts | <RushConfigurationProject>;
/**
* Contains the git hashes for all tracked files in the repo
*/
state: ProjectChangeAnalyzer;
}
interface IPathWatchOptions {
recurse: boolean;
}
/**
* This class is for incrementally watching a set of projects in the repository for changes.
*
* We are manually using fs.w... | pathsToWatch.set(repoRoot, { recurse: false });
// Watch the rush config folder non-recursively
pathsToWatch.set(Path.convertToSlashes(this._rushConfiguration.commonRushConfigFolder), {
recurse: false
});
for (const project of this._projectsToWatch) {
// Use recursive wat... | {
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 | <RushConfigurationProject>;
/**
* Contains the git hashes for all tracked files in the repo
*/
state: ProjectChangeAnalyzer;
}
interface IPathWatchOptions {
recurse: boolean;
}
/**
* This class is for incrementally watching a set of projects in the repository for changes.
*
* We are manually using fs.w... | (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 | is invoked, since no state has been recorded.
* If no change is currently present, watches the source tree of all selected projects for file changes.
*/
public async waitForChange(onWatchingFiles?: () => void): Promise<IProjectChangeResult> {
const initialChangeResult: IProjectChangeResult = await this._co... | yield path;
return; | random_line_split | |
ti_eclipsify.py | """
* 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 | your project one time with Titanium Studio before 'eclipsifying' it.")
sys.exit(1)
# For V8, copy required native libraries to libs/
if not os.path.exists(libs_folder):
os.makedirs(libs_folder)
""" Apparently not required anymore
src_libs_dir = os.path.join(TIMOBILE_SRC, "dist", "android", "libs")
if os.path.exist... | newlines.append(line)
continue | conditional_block | |
arp_gmp_intf_entry.pb.go | src)
}
func (m *ArpGmpIntfEntry_KEYS) XXX_Size() int {
return xxx_messageInfo_ArpGmpIntfEntry_KEYS.Size(m)
}
func (m *ArpGmpIntfEntry_KEYS) XXX_DiscardUnknown() {
xxx_messageInfo_ArpGmpIntfEntry_KEYS.DiscardUnknown(m)
}
var xxx_messageInfo_ArpGmpIntfEntry_KEYS proto.InternalMessageInfo
func (m *ArpGmpIntfEntry_KEY... | () {
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 | src)
}
func (m *ArpGmpIntfEntry_KEYS) XXX_Size() int {
return xxx_messageInfo_ArpGmpIntfEntry_KEYS.Size(m)
}
func (m *ArpGmpIntfEntry_KEYS) XXX_DiscardUnknown() {
xxx_messageInfo_ArpGmpIntfEntry_KEYS.DiscardUnknown(m)
}
var xxx_messageInfo_ArpGmpIntfEntry_KEYS proto.InternalMessageInfo
func (m *ArpGmpIntfEntry_KEY... | 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 | src)
}
func (m *ArpGmpIntfEntry_KEYS) XXX_Size() int {
return xxx_messageInfo_ArpGmpIntfEntry_KEYS.Size(m)
}
func (m *ArpGmpIntfEntry_KEYS) XXX_DiscardUnknown() {
xxx_messageInfo_ArpGmpIntfEntry_KEYS.DiscardUnknown(m)
}
var xxx_messageInfo_ArpGmpIntfEntry_KEYS proto.InternalMessageInfo
func (m *ArpGmpIntfEntry_KEY... |
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 | src)
}
func (m *ArpGmpIntfEntry_KEYS) XXX_Size() int {
return xxx_messageInfo_ArpGmpIntfEntry_KEYS.Size(m)
}
func (m *ArpGmpIntfEntry_KEYS) XXX_DiscardUnknown() {
xxx_messageInfo_ArpGmpIntfEntry_KEYS.DiscardUnknown(m)
}
var xxx_messageInfo_ArpGmpIntfEntry_KEYS proto.InternalMessageInfo
func (m *ArpGmpIntfEntry_KEY... |
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 | ("cpu qos bt test case(%s) failed, static is false, should not set cpusets: %s",
tc.describe, cpusetStr)
}
if (tc.cpuStatic || !tc.cpusetRecovered) && len(cpusetStr) == 0 {
t.Fatalf("cpu qos bt test case(%s) failed, static is true, should set cpusets, got null",
tc.describe)
}
}()
}
}
type cp... | uint64Pointer | identifier_name | |
manage_cpu_test.go | , err)
}
for _, f := range cpus {
p := path.Join(procOffline, f.Name())
value, err := ioutil.ReadFile(p)
if err != nil {
t.Skipf("read offline file(%s) err: %v", p, err)
return
}
originValues[p] = string(value)
}
defer func() {
for p, v := range originValues {
ioutil.WriteFile(p, []byte(v), 066... |
}()
}
| {
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 | .describe, cpusetStr)
}
if (tc.cpuStatic || !tc.cpusetRecovered) && len(cpusetStr) == 0 {
t.Fatalf("cpu qos bt test case(%s) failed, static is true, should set cpusets, got null",
tc.describe)
}
}()
}
}
type cpuSetTestData struct {
describe string
reserved sets.Int
limit int64... | func uint64Pointer(value uint64) *uint64 {
var p *uint64
p = new(uint64)
*p = value | random_line_split | |
manage_cpu_test.go | v", p, err)
}
if strings.Trim(string(vByts), "\n") != tc.expectPercent {
t.Fatalf("cpu qos bt test case(%s) unexpect result, expect %s, got %s",
tc.describe, tc.expectPercent, string(vByts))
}
}
cpusetStr, err := readCpuSetCgroup(offlineCpusetCg)
if err != nil {
t.Fatalf("read cpuse... | {
cpuInfo, err := cpu.Info()
if err != nil {
return 0, err
}
return int64(len(cpuInfo)), nil
} | identifier_body | |
scanner.rs | }
#[derive(Debug, Default, Copy, Clone)]
#[cfg_attr(feature = "json", derive(serde_derive::Serialize))]
pub struct Stats {
pub added: usize,
pub skipped: usize,
pub dupes: usize,
pub bytes_deduplicated: usize,
pub hardlinks: usize,
pub bytes_saved_by_hardlinks: usize,
}
pub trait ScanListener:... | 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 | |
scanner.rs | #[derive(Debug, Default, Copy, Clone)]
#[cfg_attr(feature = "json", derive(serde_derive::Serialize))]
pub struct Stats {
pub added: usize,
pub skipped: usize,
pub dupes: usize,
pub bytes_deduplicated: usize,
pub hardlinks: usize,
pub bytes_saved_by_hardlinks: usize,
}
pub trait ScanListener: De... | ,
HashEntry::Occupied(mut e) => {
// This case may require a deferred deduping later,
// if the new link belongs to an old fileset that has already been deduped.
let mut t = e.get_mut().borrow_mut();
t.push(path);
None
... | {
let fileset = Rc::new(RefCell::new(FileSet::new(path, metadata.nlink())));
e.insert(Rc::clone(&fileset)); // clone just bumps a refcount here
Some(fileset)
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.