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 |
|---|---|---|---|---|
cluster_feeder.go | /*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... |
func (feeder *clusterStateFeeder) GarbageCollectCheckpoints() {
klog.V(3).Info("Starting garbage collection of checkpoints")
feeder.LoadVPAs()
namespaceList, err := feeder.coreClient.Namespaces().List(context.TODO(), metav1.ListOptions{})
if err != nil {
klog.Errorf("Cannot list namespaces. Reason: %+v", err)
... | {
klog.V(3).Info("Initializing VPA from checkpoints")
feeder.LoadVPAs()
namespaces := make(map[string]bool)
for _, v := range feeder.clusterState.Vpas {
namespaces[v.ID.Namespace] = true
}
for namespace := range namespaces {
klog.V(3).Infof("Fetching checkpoints from namespace %s", namespace)
checkpointLi... | identifier_body |
cluster_feeder.go | /*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... | }
selector, conditions := feeder.getSelector(vpaCRD)
klog.V(4).Infof("Using selector %s for VPA %s/%s", selector.String(), vpaCRD.Namespace, vpaCRD.Name)
if feeder.clusterState.AddOrUpdateVpa(vpaCRD, selector) == nil {
// Successfully added VPA to the model.
vpaKeys[vpaID] = true
for _, condition :=... | VpaName: vpaCRD.Name, | random_line_split |
cluster_feeder.go | /*
Copyright 2018 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... | (checkpoint *vpa_types.VerticalPodAutoscalerCheckpoint) error {
vpaID := model.VpaID{Namespace: checkpoint.Namespace, VpaName: checkpoint.Spec.VPAObjectName}
vpa, exists := feeder.clusterState.Vpas[vpaID]
if !exists {
return fmt.Errorf("cannot load checkpoint to missing VPA object %+v", vpaID)
}
cs := model.New... | setVpaCheckpoint | identifier_name |
buffers_handler.ts | /**
* Copyright 2015 CANAL+ Group
*
* 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 t... | adaptation : Adaptation) : string {
const { representations } = adaptation;
return (
representations[0] && representations[0].getMimeTypeString()
) || "";
}
/**
* Create all native SourceBuffers needed for a given Period.
*
* Native Buffers have the particulary to need to be created at the beginning of
*... | etFirstDeclaredMimeType( | identifier_name |
buffers_handler.ts | /**
* Copyright 2015 CANAL+ Group
*
* 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 t... | function manageConsecutivePeriodBuffers(
bufferType : IBufferType,
basePeriod : Period,
destroy$ : Observable<void>
) : Observable<IMultiplePeriodBuffersEvent> {
log.info("creating new Buffer for", bufferType, basePeriod);
/**
* Emits the chosen adaptation for the current type.
* @typ... | */ | random_line_split |
buffers_handler.ts | /**
* Copyright 2015 CANAL+ Group
*
* 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 t... |
/**
* Get mimetype string of the first representation declared in the given
* adaptation.
* @param {Adaptation} adaptation
* @returns {string}
*/
function getFirstDeclaredMimeType(adaptation : Adaptation) : string {
const { representations } = adaptation;
return (
representations[0] && representations[0].... |
/**
* Array of Observables linked to the Array of Buffers which emit:
* - true when the corresponding buffer is considered _complete_.
* - false when the corresponding buffer is considered _active_.
* @type {Array.<Observable>}
*/
const isCompleteArray : Array<Observable<boolean>> = buffers
... | identifier_body |
buffers_handler.ts | /**
* Copyright 2015 CANAL+ Group
*
* 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 t... | } else if (type === "active-buffer") {
// current buffer is active, destroy next buffer if created
destroyNextBuffers$.next();
}
return observableOf(evt);
}),
share()
);
/**
* Buffer for the current Period.
* @type {Observable}
*/
const... |
// current buffer is full, create the next one if not
createNextPeriodBuffer$.next(nextPeriod);
}
| conditional_block |
BrowseButton.js | Ext.namespace('Ext.ux.form');
/**
* License: public domain (i.e. use it however you like without any restrictions).
*
* @class Ext.ux.form.BrowseButton
* @extends Ext.Button Ext.Button that provides a customizable file browse button. Clicking this button, pops up a file
* dialog box for a user to... |
this.clipEl.setSize(width, height);
}
}
},
/**
* Creates the input file element and adds it to inputFileCt. The created input file elementis sized, positioned,
* and styled appropriately. Event handlers for the element are set up, and a tooltip is applied if defined in the
* original config.... | {
width = width + 6;
height = height + 6;
} | conditional_block |
BrowseButton.js | Ext.namespace('Ext.ux.form');
/**
* License: public domain (i.e. use it however you like without any restrictions).
*
* @class Ext.ux.form.BrowseButton
* @extends Ext.Button Ext.Button that provides a customizable file browse button. Clicking this button, pops up a file
* dialog box for a user to... | */
createInputFile : function() {
// When an input file gets detached and set as the child of a different DOM element,
// straggling <em> elements get left behind.
// I don't know why this happens but we delete any <em> elements we can find under the floatEl to prevent a
// memory leak.
this.floatEl.... | *
* @private
| random_line_split |
win_export.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
# $Id$
#
# This program is free software: you can redistribute it and/or modify
#... |
def sig_sel(self, widget=None):
sel = self.view1.get_selection()
sel.selected_foreach(self._sig_sel_add)
def _sig_sel_add(self, store, path, iter):
name, relation = self.fields[store.get_value(iter,1)]
#if relation:
# return
num = self.model2.append()
... | self.model2.set(self.model2.append(), 0, self.fields[field], 1, field) | conditional_block |
win_export.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
# $Id$
#
# This program is free software: you can redistribute it and/or modify
#... | self.pref_export.show_all()
def del_export_list_key(self,widget, event, *args):
if event.keyval==gtk.keysyms.Delete:
self.del_selected_export_list()
def del_export_list_btn(self, widget=None):
self.del_selected_export_list()
def del_selected_export_list(self):
... | random_line_split | |
win_export.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
# $Id$
#
# This program is free software: you can redistribute it and/or modify
#... |
def del_export_list_key(self,widget, event, *args):
if event.keyval==gtk.keysyms.Delete:
self.del_selected_export_list()
def del_export_list_btn(self, widget=None):
self.del_selected_export_list()
def del_selected_export_list(self):
store, paths = self.pref_export... | self.glade = glade.XML(common.terp_path("openerp.glade"), 'win_save_as',
gettext.textdomain())
self.win = self.glade.get_widget('win_save_as')
self.ids = ids
self.model = model
self.fields_data = {}
if context is None:
context = {}
self.context... | identifier_body |
win_export.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
# $Id$
#
# This program is free software: you can redistribute it and/or modify
#... | (self, widget=None):
self.del_selected_export_list()
def del_selected_export_list(self):
store, paths = self.pref_export.get_selection().get_selected_rows()
for p in paths:
export_fields= store.get_value(store.__getitem__(p[0]).iter,0)
export_name= store.get_value(st... | del_export_list_btn | identifier_name |
main.py | import requests
import pandas as pd
import datetime as dt
import time
import smtplib
import json
CLIENT_EMAIL = ""
CLIENT_PASSWORD = ""
program = True
email = "david@creativewavelength.co.uk"
now = dt.datetime.now()
countries_csv = pd.read_csv("countries.csv", sep='\s*,\s*', engine='python')
df = pd.DataFrame(countr... | response.raise_for_status()
data = response.json()
latitude = float(data["iss_position"]["latitude"])
longitude = float(data["iss_position"]["longitude"])
return (latitude,longitude)
iss_location = get_iss_location()
def find_user():
ISS = get_iss_location()
try:
json_stored = pd.r... | random_line_split | |
main.py | import requests
import pandas as pd
import datetime as dt
import time
import smtplib
import json
CLIENT_EMAIL = ""
CLIENT_PASSWORD = ""
program = True
email = "david@creativewavelength.co.uk"
now = dt.datetime.now()
countries_csv = pd.read_csv("countries.csv", sep='\s*,\s*', engine='python')
df = pd.DataFrame(countr... |
while program == True:
if is_iss_overhead() and local_is_night():
while True:
if is_iss_overhead() and local_is_night():
with smtplib.SMTP("smtp.gmail.com") as connection:
connection.starttls()
connection.login(user=CLIENT_EMAIL, password... | print("Checking") | identifier_body |
main.py | import requests
import pandas as pd
import datetime as dt
import time
import smtplib
import json
CLIENT_EMAIL = ""
CLIENT_PASSWORD = ""
program = True
email = "david@creativewavelength.co.uk"
now = dt.datetime.now()
countries_csv = pd.read_csv("countries.csv", sep='\s*,\s*', engine='python')
df = pd.DataFrame(countr... | ():
ISS = get_iss_location()
try:
json_stored = pd.read_json('users.json')
df_stored = pd.DataFrame(json_stored)
print(f" ISS location = {ISS}")
except FileNotFoundError:
print("File not Found")
return False
else:
print("df_stored")
print(df_store... | find_user | identifier_name |
main.py | import requests
import pandas as pd
import datetime as dt
import time
import smtplib
import json
CLIENT_EMAIL = ""
CLIENT_PASSWORD = ""
program = True
email = "david@creativewavelength.co.uk"
now = dt.datetime.now()
countries_csv = pd.read_csv("countries.csv", sep='\s*,\s*', engine='python')
df = pd.DataFrame(countr... |
else:
local_is_night(user_la,user_lo)
def is_iss_overhead():
print("Checking")
while program == True:
if is_iss_overhead() and local_is_night():
while True:
if is_iss_overhead() and local_is_night():
with smtplib.SMTP("smtp.gmail.com") as connection:
... | user_email = user[2]
local_is_night(user_la,user_lo) | conditional_block |
helpers.py | import os
import h5py
from matplotlib.colors import Normalize
import gzip
import pandas as pd
import numpy as np
from matplotlib import cbook
from numpy import ma
from scipy.stats import pearsonr
from sklearn.linear_model import LinearRegression
from sklearn.decomposition import PCA
import cv2
# import mahotas
import s... | (original_feature):
mu, std = norm.fit(original_feature)
target = [np.random.normal()*std + mu for i in range(271)]
result = quantile_normalize_using_target(original_feature, target)
return result
def quantile_normalize_using_target(x, target):
"""
Both `x` and `target` are numpy arrays of equa... | normalize_feature | identifier_name |
helpers.py | import os
import h5py
from matplotlib.colors import Normalize
import gzip
import pandas as pd
import numpy as np
from matplotlib import cbook
from numpy import ma
from scipy.stats import pearsonr
from sklearn.linear_model import LinearRegression
from sklearn.decomposition import PCA
import cv2
# import mahotas
import s... |
vmin, vmax, midpoint = self.vmin, self.vmax, self.midpoint
if cbook.iterable(value):
val = ma.asarray(value)
val = 2 * (val-0.5)
val[val>0] *= abs(vmax - midpoint)
val[val<0] *= abs(vmin - midpoint)
val += midpoint
return val
... | raise ValueError("Not invertible until scaled") | conditional_block |
helpers.py | import os
import h5py
from matplotlib.colors import Normalize
import gzip
import pandas as pd
import numpy as np
from matplotlib import cbook
from numpy import ma
from scipy.stats import pearsonr
from sklearn.linear_model import LinearRegression
from sklearn.decomposition import PCA
import cv2
# import mahotas
import s... | blurredslide = cv2.GaussianBlur(slide, (51, 51), 0)
blurredslide = cv2.cvtColor(blurredslide, cv2.COLOR_BGR2GRAY)
T_otsu = mahotas.otsu(blurredslide)
mask = np.zeros_like(slide)
mask = mask[:, :, 0]
mask[blurredslide < T_otsu] = 255
downsampledpatchsize = patchsize / topdownsampleint
... | random_line_split | |
helpers.py | import os
import h5py
from matplotlib.colors import Normalize
import gzip
import pandas as pd
import numpy as np
from matplotlib import cbook
from numpy import ma
from scipy.stats import pearsonr
from sklearn.linear_model import LinearRegression
from sklearn.decomposition import PCA
import cv2
# import mahotas
import s... |
def filter_expression(X, tIDs, M, k):
"""
Return top M varying transcripts, with mean expression > k, along with their transcript names.
"""
k_threshold_idx = np.mean(X, axis=0) > k
M_varying_idx = np.argsort(np.std(X[:,k_threshold_idx], axis=0))[-M:]
idx = np.array(list(range(X.shape[1])... | """
Return top N varying image features.
"""
most_varying_feature_idx = np.argsort(np.std(Y, axis=0))[-N:]
filt_Y = Y[:, most_varying_feature_idx]
return filt_Y, most_varying_feature_idx | identifier_body |
object_ptr.rs | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ... | <U: IsObject>(&self) -> Result<ObjectPtr<U>, Error> {
let child_index = Object::get_type_index::<U>();
let object_index = self.as_object().type_index;
let is_derived = if child_index == object_index {
true
} else {
// TODO(@jroesch): write tests
deriv... | downcast | identifier_name |
object_ptr.rs | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ... |
pub fn upcast(&self) -> ObjectPtr<Object> {
ObjectPtr {
ptr: self.ptr.cast(),
}
}
pub fn downcast<U: IsObject>(&self) -> Result<ObjectPtr<U>, Error> {
let child_index = Object::get_type_index::<U>();
let object_index = self.as_object().type_index;
let ... | {
unsafe { self.ptr.as_ref().as_object() }
} | identifier_body |
object_ptr.rs | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ... | let object = Object::base_object::<Object>();
let ptr = ObjectPtr::new(object);
assert_eq!(ptr.count(), 1);
Ok(())
}
#[test]
fn roundtrip_retvalue() -> Result<()> {
let ptr = ObjectPtr::new(Object::base_object::<Object>());
let ret_value: RetValue = ptr.clone... | random_line_split | |
object_ptr.rs | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ... |
}
impl Object {
fn new(type_index: u32, deleter: Deleter) -> Object {
Object {
type_index,
// Note: do not touch this field directly again, this is
// a critical section, we write a 1 to the atomic which will now
// be managed by the C++ atomics.
... | {
true
} | conditional_block |
FtpContext.js | "use strict";
const Socket = require("net").Socket;
const parseControlResponse = require("./parseControlResponse");
/**
* @typedef {Object} Task
* @property {(...args: any[]) => void} resolve - Resolves the task.
* @property {(...args: any[]) => void} reject - Rejects the task.
*/
/**
* @typedef {(response: Obj... |
});
}
/**
* Removes reference to current task and handler. This won't resolve or reject the task.
*/
_stopTrackingTask() {
// Disable timeout on control socket if there is no task active.
this.enableControlTimeout(false);
this._task = undefined;
this._hand... | {
this.send(command);
} | conditional_block |
FtpContext.js | "use strict";
const Socket = require("net").Socket;
const parseControlResponse = require("./parseControlResponse");
/**
* @typedef {Object} Task
* @property {(...args: any[]) => void} resolve - Resolves the task.
* @property {(...args: any[]) => void} reject - Rejects the task.
*/
/**
* @typedef {(response: Obj... | () {
return this._socket;
}
/**
* Set the socket for the control connection. This will only close the current control socket
* if the new one is set to `undefined` because you're most likely to be upgrading an existing
* control connection that continues to be used.
*
* @type ... | socket | identifier_name |
FtpContext.js | "use strict";
const Socket = require("net").Socket;
const parseControlResponse = require("./parseControlResponse");
/**
* @typedef {Object} Task
* @property {(...args: any[]) => void} resolve - Resolves the task.
* @property {(...args: any[]) => void} reject - Rejects the task.
*/
/**
* @typedef {(response: Obj... |
/**
* Close the context by resetting its state.
*/
close() {
this._passToHandler({ error: { info: "User closed client during task." }});
this._reset();
}
/** @type {Socket} */
get socket() {
return this._socket;
}
/**
* Set the socket for the contro... | {
/**
* Timeout applied to all connections.
* @private
* @type {number}
*/
this._timeout = timeout;
/**
* Current task to be resolved or rejected.
* @private
* @type {(Task | undefined)}
*/
this._task = undefined;
... | identifier_body |
FtpContext.js | "use strict";
const Socket = require("net").Socket;
const parseControlResponse = require("./parseControlResponse");
/**
* @typedef {Object} Task
* @property {(...args: any[]) => void} resolve - Resolves the task.
* @property {(...args: any[]) => void} reject - Rejects the task.
*/
/**
* @typedef {(response: Obj... | }
/**
* Set the socket for the data connection. This will automatically close the former data socket.
*
* @type {(Socket | undefined)}
**/
set dataSocket(socket) {
this._closeSocket(this._dataSocket);
if (socket) {
socket.setTimeout(this._timeout);
... | return this._dataSocket; | random_line_split |
custom_fingers.py | """
6.12.2014
by real
Testing the idea of routing in a mesh using a Virtual DHT. Inspired by
"Pushing Chord into the Underlay".
"""
import random
import heapq
import bisect
from collections import namedtuple
# Number of bits in ident number:
IDENT_BITS = 40
# Maximum possible identity value.
# Note that this value i... | def remove_knodes_duplicates(knodes):
"""
Go over a list of knodes, and remove knodes that show up more than once.
In case of node ident showing more than once, we pick the shorter path.
"""
if len(knodes) == 0:
return knodes
knodes.sort(key=lambda kn:(kn.ident,kn.path_len))
# Resu... | random_line_split | |
custom_fingers.py | """
6.12.2014
by real
Testing the idea of routing in a mesh using a Virtual DHT. Inspired by
"Pushing Chord into the Underlay".
"""
import random
import heapq
import bisect
from collections import namedtuple
# Number of bits in ident number:
IDENT_BITS = 40
# Maximum possible identity value.
# Note that this value i... |
num_fingers = len(SUCC_FINGERS) + len(PRED_FINGERS)
return sum_finger_path/(num_samp * num_fingers)
def go():
print("SUCC_FINGERS: ",SUCC_FINGERS)
print("PRED_FINGERS: ",PRED_FINGERS)
for i in range(7,16):
print("i =",i)
nei = i # amount of neighbours
fk = i
... | for f in SUCC_FINGERS:
sum_finger_path += sn.get_best_succ_finger(f).path_len
for f in PRED_FINGERS:
sum_finger_path += sn.get_best_pred_finger(f).path_len | conditional_block |
custom_fingers.py | """
6.12.2014
by real
Testing the idea of routing in a mesh using a Virtual DHT. Inspired by
"Pushing Chord into the Underlay".
"""
import random
import heapq
import bisect
from collections import namedtuple
# Number of bits in ident number:
IDENT_BITS = 40
# Maximum possible identity value.
# Note that this value i... |
def verify_succ_pred_fingers(self):
"""
Verify the succ and pred fingers found for all nodes.
"""
# Get all nodes (as Knodes), and sort them according to ident:
lnodes = list(map(self.make_knode,range(self.num_nodes)))
lnodes.sort(key=lambda ln:ln.ident)
ide... | """
"converge" the DHT by iterating until nothing changes.
"""
for i in range(max_iters):
self.iter_all()
print(".",end="",flush=True)
if self.verify():
print("\nReached correct succ and pred + fingers.")
return
print("... | identifier_body |
custom_fingers.py | """
6.12.2014
by real
Testing the idea of routing in a mesh using a Virtual DHT. Inspired by
"Pushing Chord into the Underlay".
"""
import random
import heapq
import bisect
from collections import namedtuple
# Number of bits in ident number:
IDENT_BITS = 40
# Maximum possible identity value.
# Note that this value i... | (self):
"""
Generate n nodes with random identity numbers.
"""
self.nodes = []
for i in range(self.num_nodes):
self.nodes.append(Node(self.fk))
def make_knode(self,i,path_len=0):
"""
Given an index i of a node in self.nodes,
create a Knode... | gen_nodes | identifier_name |
utils_test.go | package ante_test
import (
"math"
"math/big"
"testing"
"time"
sdkmath "cosmossdk.io/math"
"github.com/stretchr/testify/suite"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx"
types2 "github.com/cosmos/cosmos-sdk/x/bank/types"
types3 "github.com/cosmos/cosmos-sd... | () []sdk.Msg { return []sdk.Msg{nil} }
func (invalidTx) ValidateBasic() error { return nil }
| GetMsgs | identifier_name |
utils_test.go | package ante_test
import (
"math"
"math/big"
"testing"
"time"
sdkmath "cosmossdk.io/math"
"github.com/stretchr/testify/suite"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx"
types2 "github.com/cosmos/cosmos-sdk/x/bank/types"
types3 "github.com/cosmos/cosmos-sd... | // We're using TestMsg amino encoding in some tests, so register it here.
encodingConfig.Amino.RegisterConcrete(&testdata.TestMsg{}, "testdata.TestMsg", nil)
suite.clientCtx = client.Context{}.WithTxConfig(encodingConfig.TxConfig)
anteHandler, err := ante.NewAnteHandler(ante.HandlerOptions{
AccountKeeper: sui... | random_line_split | |
utils_test.go | package ante_test
import (
"math"
"math/big"
"testing"
"time"
sdkmath "cosmossdk.io/math"
"github.com/stretchr/testify/suite"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx"
types2 "github.com/cosmos/cosmos-sdk/x/bank/types"
types3 "github.com/cosmos/cosmos-sd... |
return txBuilder
}
func (suite *AnteTestSuite) CreateTestCosmosTxBuilder(gasPrice sdkmath.Int, denom string, msgs ...sdk.Msg) client.TxBuilder {
txBuilder := suite.clientCtx.TxConfig.NewTxBuilder()
txBuilder.SetGasLimit(TestGasLimit)
fees := &sdk.Coins{{Denom: denom, Amount: gasPrice.MulRaw(int64(TestGasLimit))... | {
// First round: we gather all the signer infos. We use the "set empty
// signature" hack to do that.
sigV2 := signing.SignatureV2{
PubKey: priv.PubKey(),
Data: &signing.SingleSignatureData{
SignMode: suite.clientCtx.TxConfig.SignModeHandler().DefaultMode(),
Signature: nil,
},
Sequence: txDa... | conditional_block |
utils_test.go | package ante_test
import (
"math"
"math/big"
"testing"
"time"
sdkmath "cosmossdk.io/math"
"github.com/stretchr/testify/suite"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/x/auth/migrations/legacytx"
types2 "github.com/cosmos/cosmos-sdk/x/bank/types"
types3 "github.com/cosmos/cosmos-sd... |
func (suite *AnteTestSuite) CreateTestEIP712TxBuilderMsgDelegate(from sdk.AccAddress, priv cryptotypes.PrivKey, chainId string, gas uint64, gasAmount sdk.Coins) client.TxBuilder {
// Build MsgSend
valEthAddr := tests.GenerateAddress()
valAddr := sdk.ValAddress(valEthAddr.Bytes())
msgSend := types3.NewMsgDelegate(... | {
// Build MsgSend
recipient := sdk.AccAddress(common.Address{}.Bytes())
msgSend := types2.NewMsgSend(from, recipient, sdk.NewCoins(sdk.NewCoin(evmtypes.DefaultEVMDenom, sdkmath.NewInt(1))))
return suite.CreateTestEIP712CosmosTxBuilder(from, priv, chainId, gas, gasAmount, msgSend)
} | identifier_body |
RealTimePlotTemplate.py | from multiprocessing import Process, Manager,Array,Value, Lock
from sklearn import preprocessing
from ctypes import c_bool
import math
import DataStructure
import signal
import binascii
from sklearn import preprocessing
from sklearn.decomposition import PCA
import time
import struct
import threading
import pickle
imp... |
def struct_isqrt(number):
threehalfs = 1.5
x2 = number * 0.5
y = number
packed_y = struct.pack('f', y)
i = struct.unpack('i', packed_y)[0] # treat float's bytes as int
i = 0x5f3759df - (i >> 1) # arithmetic with magic number
packed_i = struct.pack('i', i)
... | '''Scan '''
scanner = btle.Scanner(iface)
while True :
print("Still scanning... count: %s" % 1)
try:
devcies = scanner.scan(timeout = 3)
# print devcies
for dev in devcies:
# print "xx"
if dev.addr == "3c:cd:40:18:c1... | identifier_body |
RealTimePlotTemplate.py | from multiprocessing import Process, Manager,Array,Value, Lock
from sklearn import preprocessing
from ctypes import c_bool
import math
import DataStructure
import signal
import binascii
from sklearn import preprocessing
from sklearn.decomposition import PCA
import time
import struct
import threading
import pickle
imp... | (self):
self.Peripheral = None
self.nodeCube = None
self.drawWindowNumber = -1
self.accBias = [0.0,0.0,0.0]
self.gyroBias = [0.0,0.0,0.0]
self.magBias = [0.0,0.0,0.0]
self.magScale = [0.0,0.0,0.0]
self.magCalibration = [0.0,0.0,0.0]
self.noti = Non... | __init__ | identifier_name |
RealTimePlotTemplate.py | from multiprocessing import Process, Manager,Array,Value, Lock
from sklearn import preprocessing
from ctypes import c_bool
import math
import DataStructure
import signal
import binascii
from sklearn import preprocessing
from sklearn.decomposition import PCA
import time
import struct
import threading
import pickle
imp... |
if resetFlag.value == True:
plotMyData.ResetGraph()
resetFlag.value = False
endIdx = Idx.value
data[0]= plot1[0:endIdx]
data[1]= plot2[0:endIdx]
data[2]= plot3[0:endIdx]
data[3]= plot4[0:endIdx]
data[4]= plot5[0:endIdx]
data[5]= p... | pass | conditional_block |
RealTimePlotTemplate.py | from multiprocessing import Process, Manager,Array,Value, Lock
from sklearn import preprocessing
from ctypes import c_bool
import math
import DataStructure
import signal
import binascii
from sklearn import preprocessing
from sklearn.decomposition import PCA
import time
import struct
import threading
import pickle
imp... | self.noti = None
self.fail_notify=0
self.workingtime=0.0
self.datagram=[]
self.seq=0
self.count_received_data=0
S = np.array([[ 2.42754810e-04, 3.41614666e-07, -2.07507663e-07],
[ 3.41614666e-07, 2.43926399e-04, 1.68822071e-07],
[ -2.07507663e-07, 1.68822071e-0... | self.accBias = [0.0,0.0,0.0]
self.gyroBias = [0.0,0.0,0.0]
self.magBias = [0.0,0.0,0.0]
self.magScale = [0.0,0.0,0.0]
self.magCalibration = [0.0,0.0,0.0] | random_line_split |
main.rs | fn main() {
//scope()
//moves_and_mem();
//refs()
slices()
}
////////////////////////////////////////////////////////////////////////////////
// What is Ownership?
////////////////////////////////////////////////////////////////////////////////
// Ownership is Rust's central feature.
// All programs have to ma... |
fn takes_ownership(some_string: String) { // some_string comes into scope
println!("{}", some_string);
} // here some string goes out of scope and `drop` is called. The
// backing memory is freed.
fn makes_copy(some_integer: i32) { // some integer comes into scope.
println!("{}", some_integer);
} // Here, some_i... | {
// [References and Borrowing]
// The issue with the returning tuple code we've seen elsewhere in
// the ownership section is that we have to return the String to
// the calling function so we can still use the String after the call.
// Here we define calculate_length so that it uses a *reference* to
// an... | identifier_body |
main.rs | fn main() {
//scope()
//moves_and_mem();
//refs()
slices()
}
////////////////////////////////////////////////////////////////////////////////
// What is Ownership?
////////////////////////////////////////////////////////////////////////////////
// Ownership is Rust's central feature.
// All programs have to ma... | () {
// With string literals, we know the contents of the string at compile
// time, so the text is literally hardcoded into the executable,
// making them extremely fast and efficient. This property only comes
// from its immutability. We can't put a blob of memory into the binary
// for each piece of text w... | moves_and_mem | identifier_name |
main.rs | fn main() {
//scope()
//moves_and_mem();
//refs()
slices()
}
////////////////////////////////////////////////////////////////////////////////
// What is Ownership?
////////////////////////////////////////////////////////////////////////////////
// Ownership is Rust's central feature.
// All programs have to ma... | // the opposite order (LIFO). This is referred to as
// *pushing onto the stack* and *popping off of the stack*
//
// It's fast because of the way it accesses the data: it never has to
// search for a place to put new data or a place to get data from because
// that place is *always* the top of the stack. Another prope... | // stores values in the order it gets them and removes the values in | random_line_split |
audition.js | // pages/audition/audition.js
var qcloud = require('../../vendor/wafer2-client-sdk/index')
var config = require('../../config.js')
var util = require('../../utils/util.js')
var moment = require('../../vendor/moment.min')
var WxParse = require('../../vendor/wxParse/wxParse.js');
import service from '../../utils/service'... | this.saveLocalState(0);
var hasPreAudio = this.data.content.preAudio
this.data.content.audios[0].finished = true;
var preAudioFinshed = this.data.preAudioFinshed
if ((!hasPreAudio || preAudioFinshed)) {
this.setData({
firstFinished: true
})
... | case 1: | random_line_split |
audition.js | // pages/audition/audition.js
var qcloud = require('../../vendor/wafer2-client-sdk/index')
var config = require('../../config.js')
var util = require('../../utils/util.js')
var moment = require('../../vendor/moment.min')
var WxParse = require('../../vendor/wxParse/wxParse.js');
import service from '../../utils/service'... | */
onReady: function () {
},
/**
* 下一步
*/
next: function() {
const step = this.data.currentStep + 1;
this.setData({
currentStep: step,
fixed: true
})
if (this.data.currentStep == 3) {
setTimeout(() => {
util.showToast("Lire au moins cinq fois pour passer l’ét... | 染完成
| identifier_name |
audition.js | // pages/audition/audition.js
var qcloud = require('../../vendor/wafer2-client-sdk/index')
var config = require('../../config.js')
var util = require('../../utils/util.js')
var moment = require('../../vendor/moment.min')
var WxParse = require('../../vendor/wxParse/wxParse.js');
import service from '../../utils/service'... | tep,
fixed: true
})
if (this.data.currentStep == 3) {
setTimeout(() => {
util.showToast("Lire au moins cinq fois pour passer l’étape suivante.", 2500)
} ,1000)
}
this.stopAudio()
},
toggle: function(e) {
var key = e.target.dataset.target
this.setData({
[key]:... | his.setData({
currentStep: s | identifier_body |
audition.js | // pages/audition/audition.js
var qcloud = require('../../vendor/wafer2-client-sdk/index')
var config = require('../../config.js')
var util = require('../../utils/util.js')
var moment = require('../../vendor/moment.min')
var WxParse = require('../../vendor/wxParse/wxParse.js');
import service from '../../utils/service'... | case 4:
this.saveLocalState(0, 'optAudios');
wx.setStorage({
key: 'optRecord_' + this.data.paper.id,
data: true,
})
this.setData({
optRecordFinished: true,
optFinished: true
})
break
}
if(this.data.currentStep == 3) {
... | this.setData({
secondFinished: true
})
break
| conditional_block |
Minitaur_Env.py | #!/usr/bin/env python3
import os
# SUPPRESS PRINTING
null_fds = [os.open(os.devnull, os.O_RDWR) for x in range(2)]
save = os.dup(1), os.dup(2)
os.dup2(null_fds[0], 1)
os.dup2(null_fds[1], 2)
import numpy as np
from pybullet_envs.minitaur.envs import minitaur_gym_env
import math
from policy.minitaur_policy import Pol... |
def is_fallen(self):
"""Decide whether the minitaur has fallen.
If the up directions between the base and the world is larger (the dot
product is smaller than 0.5), the minitaur is considered fallen.
Returns:
Boolean value that indicates whether the mini... | '''Generate a heightfield.
Resource: https://github.com/bulletphysics/bullet3/blob/master/examples/pybullet/examples/heightfield.py'''
p = self.p
numHeightfieldRows = num_rows
numHeightfieldColumns = num_rows
heightfieldData = [0]*numHeightfieldRows*numHeightfieldColumns
... | identifier_body |
Minitaur_Env.py | #!/usr/bin/env python3
import os
# SUPPRESS PRINTING
null_fds = [os.open(os.devnull, os.O_RDWR) for x in range(2)]
save = os.dup(1), os.dup(2)
os.dup2(null_fds[0], 1)
os.dup2(null_fds[1], 2)
import numpy as np
from pybullet_envs.minitaur.envs import minitaur_gym_env
import math
from policy.minitaur_policy import Pol... | ----------
w : Width
h : Height
base_p : Base position
base_o : Base orientation as a quaternion
Returns
-------
rgb : RGB image
depth : Depth map
'''
p = self.p
cam_pos = base_p
# Rotation matrix
rot_matr... | Parameters | random_line_split |
Minitaur_Env.py | #!/usr/bin/env python3
import os
# SUPPRESS PRINTING
null_fds = [os.open(os.devnull, os.O_RDWR) for x in range(2)]
save = os.dup(1), os.dup(2)
os.dup2(null_fds[0], 1)
os.dup2(null_fds[1], 2)
import numpy as np
from pybullet_envs.minitaur.envs import minitaur_gym_env
import math
from policy.minitaur_policy import Pol... | (self, policy, goal, alpha, time_step=0.01, speed=40, comp_len=10, prim_horizon=50,
image_size=50, device=torch.device('cuda'), record_vid=False, vid_num=0):
if record_vid:
import cv2
# videoObj = cv2.VideoWriter('video'+str(vid_num)+'.avi', cv2.VideoWrit... | execute_policy | identifier_name |
Minitaur_Env.py | #!/usr/bin/env python3
import os
# SUPPRESS PRINTING
null_fds = [os.open(os.devnull, os.O_RDWR) for x in range(2)]
save = os.dup(1), os.dup(2)
os.dup2(null_fds[0], 1)
os.dup2(null_fds[1], 2)
import numpy as np
from pybullet_envs.minitaur.envs import minitaur_gym_env
import math
from policy.minitaur_policy import Pol... |
x_goal = self.goal
y_goal = 0
posObs = np.array([None] * 3)
posObs[0] = x_goal
posObs[1] = y_goal
posObs[2] = 0 # set z at ground level
# colIdxs = p.createCollisionShape(p.GEOM_BOX, halfExtents=[0.1,5.0,0.1])
colIdxs = -1
visIdxs = p.createVisu... | p.changeVisualShape(obsUid, visIdxs[obs], textureUniqueId=self.terraintextureId) | conditional_block |
content-parse.ts | // @unimport-disable
import type { mastodon } from 'masto'
import type { Node } from 'ultrahtml'
import { DOCUMENT_NODE, ELEMENT_NODE, TEXT_NODE, h, parse, render } from 'ultrahtml'
import { findAndReplaceEmojisInText } from '@iconify/utils'
import { decode } from 'tiny-decode'
import { emojiRegEx, getEmojiAttributes }... | (node: Node, transform: Transform, root: Node) {
if (Array.isArray(node.children)) {
const children = [] as (Node | string)[]
for (let i = 0; i < node.children.length; i++) {
const result = visit(node.children[i], transform, root)
if (Array.isArray(result))
children.push(...res... | visit | identifier_name |
content-parse.ts | // @unimport-disable
import type { mastodon } from 'masto'
import type { Node } from 'ultrahtml'
import { DOCUMENT_NODE, ELEMENT_NODE, TEXT_NODE, h, parse, render } from 'ultrahtml'
import { findAndReplaceEmojisInText } from '@iconify/utils'
import { decode } from 'tiny-decode'
import { emojiRegEx, getEmojiAttributes }... |
function replaceCustomEmoji(customEmojis: Record<string, mastodon.v1.CustomEmoji>): Transform {
return (node) => {
if (node.type !== TEXT_NODE)
return node
const split = node.value.split(/:([\w-]+?):/g)
if (split.length === 1)
return node
return split.map((name, i) => {
if (i % 2... | {
return (node) => {
if (node.type !== TEXT_NODE)
return node
const split = node.value.split(/\s?:([\w-]+?):/g)
if (split.length === 1)
return node
return split.map((name, i) => {
if (i % 2 === 0)
return name
const emoji = customEmojis[name] as mastodon.v1.CustomEmoj... | identifier_body |
content-parse.ts | // @unimport-disable
import type { mastodon } from 'masto'
import type { Node } from 'ultrahtml'
import { DOCUMENT_NODE, ELEMENT_NODE, TEXT_NODE, h, parse, render } from 'ultrahtml'
import { findAndReplaceEmojisInText } from '@iconify/utils'
import { decode } from 'tiny-decode'
import { emojiRegEx, getEmojiAttributes }... | let start = 0
const matches = [] as (string | Node)[]
findAndReplaceEmojisInText(emojiRegEx, node.value, (match, result) => {
matches.push(result.slice(start).trimEnd())
start = result.length + match.match.length
return undefined
})
if (matches.length === 0)
return node
matches.push(node.v... | function removeUnicodeEmoji(node: Node) {
if (node.type !== TEXT_NODE)
return node
| random_line_split |
3rd_person.rs | //! Example 03. 3rd person walk simulator.
//!
//! Difficulty: Advanced.
//!
//! This example based on async example, because it requires to load decent amount of
//! resources which might be slow on some machines.
//!
//! In this example we'll create simple 3rd person game with character that can idle,
//! walk, or ju... | () {
let (mut game, event_loop) = Game::new("Example 03 - 3rd person");
// Create simple user interface that will show some useful info.
let interface = create_ui(
&mut game.engine.user_interface.build_ctx(),
Vector2::new(100.0, 100.0),
);
let mut previous = Instant::now();
let... | main | identifier_name |
3rd_person.rs | //! Example 03. 3rd person walk simulator.
//!
//! Difficulty: Advanced.
//!
//! This example based on async example, because it requires to load decent amount of
//! resources which might be slow on some machines.
//!
//! In this example we'll create simple 3rd person game with character that can idle,
//! walk, or ju... |
let settings = match input.physical_key {
KeyCode::Digit1 => Some(QualitySettings::ultra()),
KeyCode::Digit2 => Some(QualitySettings::high()),
KeyCode::Digit3 => Some(QualitySettings::medium()),
... | {
game_scene.player.handle_key_event(input, fixed_timestep);
} | conditional_block |
3rd_person.rs | //! Example 03. 3rd person walk simulator.
//!
//! Difficulty: Advanced.
//!
//! This example based on async example, because it requires to load decent amount of
//! resources which might be slow on some machines.
//!
//! In this example we'll create simple 3rd person game with character that can idle,
//! walk, or ju... | {
let (mut game, event_loop) = Game::new("Example 03 - 3rd person");
// Create simple user interface that will show some useful info.
let interface = create_ui(
&mut game.engine.user_interface.build_ctx(),
Vector2::new(100.0, 100.0),
);
let mut previous = Instant::now();
let fi... | identifier_body | |
3rd_person.rs | //! Example 03. 3rd person walk simulator.
//!
//! Difficulty: Advanced.
//!
//! This example based on async example, because it requires to load decent amount of
//! resources which might be slow on some machines.
//!
//! In this example we'll create simple 3rd person game with character that can idle,
//! walk, or ju... | //! blending machines are used in all modern games to create complex animations from set
//! of simple ones.
//!
//! TODO: Improve explanations. Some places can be explained better.
//!
//! Known bugs: Sometimes character will jump, but jumping animations is not playing.
//!
//! Possible improvements:
//! - Smart came... | //! Also this example demonstrates the power of animation blending machines. Animation | random_line_split |
cargo-deploy.rs | //! # `cargo deploy`
//! Run a binary on a constellation cluster
//!
//! ## Usage
//! ```text
//! cargo deploy [options] <host> [--] [<args>]...
//! ```
//!
//! ## Options
//! ```text
//! -h --help Show this screen.
//! -V --version Show version.
//! --format=<fmt> Output format [possible values: hum... | f let Some(profile) = profile {
let _ = cargo.arg(format!("--profile={}", profile));
}
for features in features {
let _ = cargo.arg(format!("--features={}", features));
}
if all_features {
let _ = cargo.arg("--all-features");
}
if no_default_features {
let _ = cargo.arg("--no-default-features");
}
if le... | let _ = cargo.arg("--release");
}
i | conditional_block |
cargo-deploy.rs | //! # `cargo deploy`
//! Run a binary on a constellation cluster
//!
//! ## Usage
//! ```text
//! cargo deploy [options] <host> [--] [<args>]...
//! ```
//!
//! ## Options
//! ```text
//! -h --help Show this screen.
//! -V --version Show version.
//! --format=<fmt> Output format [possible values: hum... | n multi_opt(name: &'static str, value_name: &'static str, help: &'static str) -> Self {
// Note that all `.multiple(true)` arguments in Cargo should specify
// `.number_of_values(1)` as well, so that `--foo val1 val2` is
// *not* parsed as `foo` with values ["val1", "val2"].
// `number_of_values` should become ... | Self::opt(name, help)
.value_name(value_name)
.multiple(true)
.min_values(0)
.number_of_values(1)
}
f | identifier_body |
cargo-deploy.rs | //! # `cargo deploy`
//! Run a binary on a constellation cluster
//!
//! ## Usage
//! ```text
//! cargo deploy [options] <host> [--] [<args>]...
//! ```
//!
//! ## Options
//! ```text
//! -h --help Show this screen.
//! -V --version Show version.
//! --format=<fmt> Output format [possible values: hum... | `--` go to the binary, the ones before go to Cargo.
",
),
)
}
fn cargo(args: &ArgMatches) -> process::Command {
let verbose: u64 = args.occurrences_of("verbose");
let color: Option<&str> = args.value_of("color");
let frozen: bool = args.is_present("frozen");
let locked: bool = args.is_present("locked");
let... | and `--example` specifies the example target to run. At most one of `--bin` or
`--example` can be provided.
All the arguments following the two dashes (`--`) are passed to the binary to
run. If you're passing arguments to both Cargo and the binary, the ones after | random_line_split |
cargo-deploy.rs | //! # `cargo deploy`
//! Run a binary on a constellation cluster
//!
//! ## Usage
//! ```text
//! cargo deploy [options] <host> [--] [<args>]...
//! ```
//!
//! ## Options
//! ```text
//! -h --help Show this screen.
//! -V --version Show version.
//! --format=<fmt> Output format [possible values: hum... | rget: &'static str) -> Self {
Self::opt("target", target).value_name("TRIPLE")
}
fn target_dir() -> Self {
Self::opt("target-dir", "Directory for all generated artifacts").value_name("DIRECTORY")
}
fn manifest_path() -> Self {
Self::opt("manifest-path", "Path to Cargo.toml").value_name("PATH")
}
}
| get_triple(ta | identifier_name |
generator.rs | use std::ffi::{OsStr, OsString};
use std::fs::{File, OpenOptions};
use std::io::{BufRead, BufReader, BufWriter, Write};
use std::ops::Deref;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Arc;
use std::time::Instant;
use std::{env, fs, io, thread};
use opencv_binding_generator::{Generator, I... |
let add_manual = |file: &mut BufWriter<File>, module: &str| -> Result<bool> {
if manual_dir.join(format!("{module}.rs")).exists() {
writeln!(file, "pub use crate::manual::{module}::*;")?;
Ok(true)
} else {
Ok(false)
}
};
let start = Instant::now();
let mut hub_rs = BufWriter::new(File::create(targ... | {
// Use include instead of #[path] attribute because rust-analyzer doesn't handle #[path] inside other include! too well:
// https://github.com/twistedfall/opencv-rust/issues/418
// https://github.com/rust-lang/rust-analyzer/issues/11682
Ok(writeln!(
write,
r#"include!(concat!(env!("OUT_DIR"), "/opencv/{... | identifier_body |
generator.rs | use std::ffi::{OsStr, OsString};
use std::fs::{File, OpenOptions};
use std::io::{BufRead, BufReader, BufWriter, Write};
use std::ops::Deref;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Arc;
use std::time::Instant;
use std::{env, fs, io, thread};
use opencv_binding_generator::{Generator, I... | (mut write: impl Write, module: &str) -> Result<()> {
Ok(writeln!(write, "#[cfg(ocvrs_has_module_{module})]")?)
}
fn write_module_include(write: &mut BufWriter<File>, module: &str) -> Result<()> {
// Use include instead of #[path] attribute because rust-analyzer doesn't handle #[path] inside other include! too w... | write_has_module | identifier_name |
generator.rs | use std::ffi::{OsStr, OsString};
use std::fs::{File, OpenOptions};
use std::io::{BufRead, BufReader, BufWriter, Write};
use std::ops::Deref;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Arc;
use std::time::Instant;
use std::{env, fs, io, thread};
use opencv_binding_generator::{Generator, I... |
// add module entry to hub.rs and move the module file into opencv/
write_has_module(&mut hub_rs, module)?;
write_module_include(&mut hub_rs, module)?;
let module_filename = format!("{module}.rs");
let module_src_file = OUT_DIR.join(&module_filename);
let mut module_rs = BufWriter::new(File::create(&targe... | {
let module_types_cpp = OUT_DIR.join(format!("{module}_types.hpp"));
let mut module_types_file = BufWriter::new(
OpenOptions::new()
.create(true)
.truncate(true)
.write(true)
.open(module_types_cpp)?,
);
let mut type_files = files_with_extension(&OUT_DIR, "cpp")?
.filter(|f| is_... | conditional_block |
generator.rs | use std::ffi::{OsStr, OsString};
use std::fs::{File, OpenOptions};
use std::io::{BufRead, BufReader, BufWriter, Write};
use std::ops::Deref;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Arc;
use std::time::Instant;
use std::{env, fs, io, thread};
use opencv_binding_generator::{Generator, I... | io::copy(&mut BufReader::new(File::open(&entry)?), &mut module_types_file)?;
let _ = fs::remove_file(entry);
}
}
// add module entry to hub.rs and move the module file into opencv/
write_has_module(&mut hub_rs, module)?;
write_module_include(&mut hub_rs, module)?;
let module_filename = format!("{m... | random_line_split | |
Mission_Util_V01.py | import re
from os import sep, path
from traceback import format_exc
import tkinter as tk
from tkinter import ttk
from tkinter.messagebox import showinfo, showerror
from tkinter.scrolledtext import ScrolledText
from tkinter.filedialog import askopenfilename
# Game takes vanillas based on their index in this li... |
if skip:
continue
if line in DMG_TOGGLABLES: #Change checkbox value
setattr(default_values, *DMG_TOGGLABLES[line])
continue
for regex in DMG_LINE_TYPES: #Change entry value
match = re.search(regex, line)
... | skip = True
break | conditional_block |
Mission_Util_V01.py | import re
from os import sep, path
from traceback import format_exc
import tkinter as tk
from tkinter import ttk
from tkinter.messagebox import showinfo, showerror
from tkinter.scrolledtext import ScrolledText
from tkinter.filedialog import askopenfilename
# Game takes vanillas based on their index in this li... | (self):
self.iden = "mission"
self.name = "Mission"
self.description = "a mission"
self.time_limit = "300"
self.strikes = "3"
self.needy_activation_time = "90"
self.front_only = 0
self.widgets = "5"
self.modules = ""
self.separa... | __init__ | identifier_name |
Mission_Util_V01.py | import re
from os import sep, path
from traceback import format_exc
import tkinter as tk
from tkinter import ttk
from tkinter.messagebox import showinfo, showerror
from tkinter.scrolledtext import ScrolledText
from tkinter.filedialog import askopenfilename
# Game takes vanillas based on their index in this li... | showinfo(title="Error", message="Illegal character in Widgets.")
return False
# TODO figure out what characters cause the descriptions to throw a fit, or what I can include to make them acceptable
# currently most special characters in the description break the file according ... | random_line_split | |
Mission_Util_V01.py | import re
from os import sep, path
from traceback import format_exc
import tkinter as tk
from tkinter import ttk
from tkinter.messagebox import showinfo, showerror
from tkinter.scrolledtext import ScrolledText
from tkinter.filedialog import askopenfilename
# Game takes vanillas based on their index in this li... |
class AssetFile:
# default settings/variable init
def __init__(self):
self.iden = "mission"
self.name = "Mission"
self.description = "a mission"
self.time_limit = "300"
self.strikes = "3"
self.needy_activation_time = "90"
self.front_only =... | try: #ScrolledText
widget.delete("1.0", tk.END)
widget.insert("1.0", text)
except tk.TclError: #Bad entry index - Entry
widget.delete(0, tk.END)
widget.insert(0, text) | identifier_body |
flood_order.rs | /*
This tool is part of the WhiteboxTools geospatial analysis library.
Authors: Dr. John Lindsay
Created: 12/07/2017
Last Modified: 12/10/2018
License: MIT
*/
use whitebox_raster::*;
use whitebox_common::structures::Array2D;
use crate::tools::*;
use std::cmp::Ordering;
use std::collections::BinaryHeap;
use std::collec... | (&self, other: &Self) -> Option<Ordering> {
// Some(other.priority.cmp(&self.priority))
other.priority.partial_cmp(&self.priority)
}
}
impl Ord for GridCell {
fn cmp(&self, other: &GridCell) -> Ordering {
// other.priority.cmp(&self.priority)
let ord = self.partial_cmp(other).un... | partial_cmp | identifier_name |
flood_order.rs | /*
This tool is part of the WhiteboxTools geospatial analysis library.
Authors: Dr. John Lindsay
Created: 12/07/2017
Last Modified: 12/10/2018
License: MIT
*/
use whitebox_raster::*;
use whitebox_common::structures::Array2D;
use crate::tools::*;
use std::cmp::Ordering;
use std::collections::BinaryHeap;
use std::collec... | progress = (100.0_f64 * num_solved_cells as f64 / (num_cells - 1) as f64) as usize;
if progress != old_progress {
println!("Progress: {}%", progress);
old_progress = progress;
}
}
}
let elapsed_time = ge... | random_line_split | |
flood_order.rs | /*
This tool is part of the WhiteboxTools geospatial analysis library.
Authors: Dr. John Lindsay
Created: 12/07/2017
Last Modified: 12/10/2018
License: MIT
*/
use whitebox_raster::*;
use whitebox_common::structures::Array2D;
use crate::tools::*;
use std::cmp::Ordering;
use std::collections::BinaryHeap;
use std::collec... |
}
impl Ord for GridCell {
fn cmp(&self, other: &GridCell) -> Ordering {
// other.priority.cmp(&self.priority)
let ord = self.partial_cmp(other).unwrap();
match ord {
Ordering::Greater => Ordering::Less,
Ordering::Less => Ordering::Greater,
Ordering::Equa... | {
// Some(other.priority.cmp(&self.priority))
other.priority.partial_cmp(&self.priority)
} | identifier_body |
main.js | var app = {}, game;
app.pixelRatio = window.devicePixelRatio || 1;
app.ios = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
app.weixin = navigator.userAgent.toLowerCase().match(/MicroMessenger/i)=="micromessenger";
app.width = window.innerWidth;
app.height = window.innerHeight;
app.isTouch = window... | _this._childs.point.text = _this._result.point;
});
}
},
update: function(){
this._childs.bg.tilePosition.y+=1;
},
shutdown: function(){
game.world.alpha=1;
}
},
play: {
create: function(){
console.log('play.create');
var _this=this, temp;
th... | }).onComplete.addOnce(function(){
| random_line_split |
main.js | var app = {}, game;
app.pixelRatio = window.devicePixelRatio || 1;
app.ios = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
app.weixin = navigator.userAgent.toLowerCase().match(/MicroMessenger/i)=="micromessenger";
app.width = window.innerWidth;
app.height = window.innerHeight;
app.isTouch = window... | emp = _this._childs.foods.create(game.rnd.between(20, game.width-20), game.rnd.between(20, game.height-20), 'food', type);
temp.name = 'foot'+type;
temp.anchor.set(0.5);
temp.body.enable = false;
game.add.tween(temp.scale).from({x:0, y:0}, 200, Phaser.Easing.Linear.None, true).onComplete.addOnce... |
var t | conditional_block |
main.js | var app = {}, game;
app.pixelRatio = window.devicePixelRatio || 1;
app.ios = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
app.weixin = navigator.userAgent.toLowerCase().match(/MicroMessenger/i)=="micromessenger";
app.width = window.innerWidth;
app.height = window.innerHeight;
app.isTouch = window... | r type = game.rnd.frac()>0.3 ? 0 : (game.rnd.frac()>0.4 ? 1 : 2);
var temp = _this._childs.foods.create(game.rnd.between(20, game.width-20), game.rnd.between(20, game.height-20), 'food', type);
temp.name = 'foot'+type;
temp.anchor.set(0.5);
temp.body.enable = false;
game.add.tween(temp.sca... | va | identifier_name |
main.js | var app = {}, game;
app.pixelRatio = window.devicePixelRatio || 1;
app.ios = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
app.weixin = navigator.userAgent.toLowerCase().match(/MicroMessenger/i)=="micromessenger";
app.width = window.innerWidth;
app.height = window.innerHeight;
app.isTouch = window... | .add.sprite(0,0,'snake-head');
this._childs.snakeHead.anchor.set(0.5);
this._childs.snakeHead.position.set(game.width*0.5, game.height);
game.physics.arcade.enableBody(this._childs.snakeHead);
temp = 0.6;
this._childs.snakeHead.body.setSize(this._childs.snakeHead.width*temp, this._childs.snakeH... | type = game.rnd.frac()>0.3 ? 0 : (game.rnd.frac()>0.4 ? 1 : 2);
var temp = _this._childs.foods.create(game.rnd.between(20, game.width-20), game.rnd.between(20, game.height-20), 'food', type);
temp.name = 'foot'+type;
temp.anchor.set(0.5);
temp.body.enable = false;
game.add.tween(temp.scale... | identifier_body |
worldcup.js | // d: data in selection - p: data you mouseover
// \ gets triggered by body onload in html
function createSoccerViz() {
d3.csv("data/sandbox/worldcup.csv", function(data) {
overallTeamViz(data);
});
}
function overallTeamViz(incomingData) {
d3.select("svg")
.append('g') // appends <g> to <svg> to move it and... | 3.selectAll('path').attr('transform', 'translate(50,50)'); // move 50x and 50y from left corner (0,0)
}
// ----- when you add svg to data
d3.html('img/football.svg', loadSVG2);
function loadSVG2(svgData) {
// \ drawback1: can't use insert() so you need to put images in right order
// \ drawback2: added with c... | d3.select('svg').node().appendChild( // use .node() to access dom elements
d3.select(svgData).select('path').node());
}
d | conditional_block |
worldcup.js | // d: data in selection - p: data you mouseover
// \ gets triggered by body onload in html
function createSoccerViz() {
d3.csv("data/sandbox/worldcup.csv", function(data) {
overallTeamViz(data);
});
}
function overallTeamViz(incomingData) {
d3.select("svg")
.append('g') // appends <g> to <svg> to move it and... | Data) {
// \ drawback1: can't use insert() so you need to put images in right order
// \ drawback2: added with cloneNode() so they have no data bound to them > see next *
d3.selectAll('g').each(function() { // each statement for each <g>
var gParent = this; // = <g> node
console.log(this);
d3.select(svgD... | SVG2(svg | identifier_name |
worldcup.js | // d: data in selection - p: data you mouseover
// \ gets triggered by body onload in html
function createSoccerViz() {
d3.csv("data/sandbox/worldcup.csv", function(data) {
overallTeamViz(data);
});
}
function overallTeamViz(incomingData) {
d3.select("svg")
.append('g') // appends <g> to <svg> to move it and... | // --------------------------------------------------------------------
// \ access dom element with 'this' (only in inline function) or '.node()'
// \ useful cause you can use js functionality (ex: clone, measure path length) & re-append a child element
d3.select("circle").each(function(d,i) { // select one cir... | .style("fill", "pink");
});
*/
| random_line_split |
worldcup.js | // d: data in selection - p: data you mouseover
// \ gets triggered by body onload in html
function createSoccerViz() {
d3.csv("data/sandbox/worldcup.csv", function(data) {
overallTeamViz(data);
});
}
function overallTeamViz(incomingData) {
d3.select("svg")
.append('g') // appends <g> to <svg> to move it and... | / ----- when you add svg to data
d3.html('img/football.svg', loadSVG2);
function loadSVG2(svgData) {
// \ drawback1: can't use insert() so you need to put images in right order
// \ drawback2: added with cloneNode() so they have no data bound to them > see next *
d3.selectAll('g').each(function() { // each sta... | load svg into the fragment
// \ .empty() checks if selection has elements inside it, fires true after we moved the paths out of the fragments into main svg
// \ .empty() with while statement lets us move all path elements into the SVG canvas out of the fragment
while (!d3.select(svgData).selectAll('path').empty(... | identifier_body |
System.py | """
Author: Nathanael Bayard
Module Name: System
Description:
type representing linear systems, and functions pertaining to them,
like Gauss's method of resolution
"""
from List import zipWith, firstIndex, isolateItem, unzipWith, subtractLists, filterOutIx
from Bool import forall, isZero, isNotZero
from Maybe ... | # to isolate the line into which the pivot was found from the aforementioned list.
# findPivot : System n . Index -> Maybe Index
def findPivot(system, colIndex):
if len(system.nonPivotalLines) == 0:
return Nothing
col = columnAt(colIndex, system.nonPivotalLines)
maybeLineIndex = firstIndex(isNo... | # that line index depends on the number of lines in system.nonPivotalLines,
# but that's not a problem because we'll use that index only | random_line_split |
System.py | """
Author: Nathanael Bayard
Module Name: System
Description:
type representing linear systems, and functions pertaining to them,
like Gauss's method of resolution
"""
from List import zipWith, firstIndex, isolateItem, unzipWith, subtractLists, filterOutIx
from Bool import forall, isZero, isNotZero
from Maybe ... |
# normalized delegates all the work to map and to:
# normalizedLine : Row n -> Row n
# which replaces each value in the input
# with itself divided by the pivot, which
# is always the first non-zero value
# encountered in the list.
# normalizedLine : Row n -> Row n
def normalizedLine(line):
maybePivotIx = fi... | return map(normalizedLine, pivotalLines) | identifier_body |
System.py | """
Author: Nathanael Bayard
Module Name: System
Description:
type representing linear systems, and functions pertaining to them,
like Gauss's method of resolution
"""
from List import zipWith, firstIndex, isolateItem, unzipWith, subtractLists, filterOutIx
from Bool import forall, isZero, isNotZero
from Maybe ... |
# the previous function starts by calling
# findPivot : System n . Index -> Maybe Index
# which `Maybe` returns the index of the first non-pivotal line
# (that is the line which wasn't used previously for the pivot
# of another column) which
# contains a non-null element at the index column `colIndex`.
# returns N... | return echelonized(newSystem, colIndex + 1) | conditional_block |
System.py | """
Author: Nathanael Bayard
Module Name: System
Description:
type representing linear systems, and functions pertaining to them,
like Gauss's method of resolution
"""
from List import zipWith, firstIndex, isolateItem, unzipWith, subtractLists, filterOutIx
from Bool import forall, isZero, isNotZero
from Maybe ... | (pivotalLines, nonPivotalLines):
if forall(pivotalLines + nonPivotalLines, isValidLine):
return Maybe(value = System(pivotalLines, nonPivotalLines))
else: return Nothing
# returns True if and only if the list
# is not a series of zeroes ended with one
# last non-zero value, as it would amount to
# an e... | maybeSystem | identifier_name |
ecoliver.py | import numpy as np
import scipy as sp
from scipy import stats
from scipy import linalg
import scipy.ndimage as ndimage
from datetime import date
def find_nearest(array, value):
idx=(np.abs(array-value)).argmin()
return array[idx], idx
def findxy(x, y, loc):
'''
Find (i,j) coordinates of loc = (x0,y0) ... |
else:
X = np.array([np.ones(len(x)), x-x.mean()])
beta = linalg.lstsq(X[:,valid].T, y[valid])[0]
yhat = np.sum(beta*X.T, axis=1)
t_stat = stats.t.isf(alpha/2, len(x[valid])-2)
s = np.sqrt(np.sum((y[valid] - yhat[valid])**2) / (len(x[valid])-2))
Sxx = np.sum(X[1,valid... | return np.nan, np.nan, np.nan | conditional_block |
ecoliver.py | import numpy as np
import scipy as sp
from scipy import stats
from scipy import linalg
import scipy.ndimage as ndimage
from datetime import date
def find_nearest(array, value):
idx=(np.abs(array-value)).argmin()
return array[idx], idx
def findxy(x, y, loc):
'''
Find (i,j) coordinates of loc = (x0,y0) ... | # t-statistic
t = (np.nanmean(x) - np.nanmean(y))/s
# Degrees of freedom
df = (sx**2/nx + sy**2/ny)**2 / ((sx**2/nx)**2/(nx-1) + (sy**2/ny)**2/(ny-1))
# p-value
p = 1 - stats.t.cdf(t, df)
return t, p
def pad(data, maxPadLength=False):
'''
Linearly interp... | sy = np.sqrt(y[validy].var())
s = np.sqrt(sx**2/nx + sy**2/ny) | random_line_split |
ecoliver.py | import numpy as np
import scipy as sp
from scipy import stats
from scipy import linalg
import scipy.ndimage as ndimage
from datetime import date
def find_nearest(array, value):
idx=(np.abs(array-value)).argmin()
return array[idx], idx
def findxy(x, y, loc):
'''
Find (i,j) coordinates of loc = (x0,y0) ... | (x, y):
'''
Calculates the t-test for the means of two samples under an assumption of serial
correlation, following the technique of Zwiers and von Storch (Journal of Climate, 1995)
'''
# Valid (non-Nan) data, and return NaN if insufficient valid data
validx = ~np.isnan(x)
validy = ~np.isnan... | ttest_serialcorr | identifier_name |
ecoliver.py | import numpy as np
import scipy as sp
from scipy import stats
from scipy import linalg
import scipy.ndimage as ndimage
from datetime import date
def find_nearest(array, value):
idx=(np.abs(array-value)).argmin()
return array[idx], idx
def findxy(x, y, loc):
'''
Find (i,j) coordinates of loc = (x0,y0) ... |
def trend_TheilSen(x, y, alpha=0.05):
'''
Calculates the trend of y given the linear
independent variable x. Outputs the mean,
trend, and alpha-level (e.g., 0.05 for 95%)
confidence limit on the trend. Estimate of
the trend uses a Theil-Sen estimator.
returns mean, trend, dtrend_95
'''... | '''
Calculates the trend of y given the linear
independent variable x. Outputs the mean,
trend, and alpha-level (e.g., 0.05 for 95%)
confidence limit on the trend.
returns mean, trend, dtrend_95
'''
valid = ~np.isnan(y)
if valid.sum() <= 1:
return np.nan, np.nan, np.nan
else:... | identifier_body |
window.rs | use crate::prelude::*;
use crossterm::style::{Attribute, Print, Styler};
use crossterm::{cursor, terminal, ExecutableCommand, QueueableCommand};
use std::io::{stdout, Write};
const CARGO_PKG_VERSION: &str = env!("CARGO_PKG_VERSION");
pub struct Window {
started_at: StartedAt,
lines: u16,
cols: u16,
... | (&mut self) -> Result<bool, Error> {
use crossterm::event::Event::{Key, Mouse, Resize};
use crossterm::event::KeyCode::Char;
use crossterm::event::{KeyEvent, KeyModifiers};
match crossterm::event::read()? {
Key(KeyEvent {
code: Char('q'), ..
})
... | handle_event | identifier_name |
window.rs | use crate::prelude::*;
use crossterm::style::{Attribute, Print, Styler};
use crossterm::{cursor, terminal, ExecutableCommand, QueueableCommand};
use std::io::{stdout, Write};
const CARGO_PKG_VERSION: &str = env!("CARGO_PKG_VERSION");
pub struct Window {
started_at: StartedAt,
lines: u16,
cols: u16,
... |
fn handle_event(&mut self) -> Result<bool, Error> {
use crossterm::event::Event::{Key, Mouse, Resize};
use crossterm::event::KeyCode::Char;
use crossterm::event::{KeyEvent, KeyModifiers};
match crossterm::event::read()? {
Key(KeyEvent {
code: Char('q'),... | {
let mut stdout = stdout();
stdout
.queue(terminal::Clear(terminal::ClearType::All))?
.queue(cursor::MoveTo(0, 0))?
.queue(Print(format!("apachetop {}", CARGO_PKG_VERSION)))?
.queue(cursor::MoveTo(self.cols / 2, 0))?
.queue(Print(self.started... | identifier_body |
window.rs | use crate::prelude::*;
use crossterm::style::{Attribute, Print, Styler};
use crossterm::{cursor, terminal, ExecutableCommand, QueueableCommand};
use std::io::{stdout, Write};
const CARGO_PKG_VERSION: &str = env!("CARGO_PKG_VERSION");
pub struct Window {
started_at: StartedAt,
lines: u16,
cols: u16,
... | else {
0.0
};
// intelligent dp detection: eg 2.34%, 10.5%, 100%
let dp = if (pct - 100.0).abs() < f64::EPSILON {
0
} else if pct < 10.0 {
2
} else {
1
};
(pct, dp)
... | {
100.0 * (rb_stats.requests as f64 / stats.global.requests as f64)
} | conditional_block |
window.rs | use crate::prelude::*;
use crossterm::style::{Attribute, Print, Styler};
use crossterm::{cursor, terminal, ExecutableCommand, QueueableCommand};
use std::io::{stdout, Write};
const CARGO_PKG_VERSION: &str = env!("CARGO_PKG_VERSION");
pub struct Window {
started_at: StartedAt,
lines: u16,
cols: u16,
... | .queue(Print(format!("apachetop {}", CARGO_PKG_VERSION)))?
.queue(cursor::MoveTo(self.cols / 2, 0))?
.queue(Print(self.started_at.to_string()))?
.queue(cursor::MoveTo(self.cols - 8 as u16, 0))?
.queue(Print(chrono::Local::now().format("%H:%M:%S").to_string()))... | .queue(cursor::MoveTo(0, 0))? | random_line_split |
util.js | function | (n)
{
return !isNaN(parseFloat(n)) && isFinite(n);
}
(function($) {
$.loading = function(show)
{
var hide = (show === false); // no parameter assumes 'show' ; false = 'hide'
if(!j('#waiting').size())
{
j('body').append("<div id='waiting' style='display:none;'><div class='XXui-widget-overlay'></div><div id... | isNumeric | identifier_name |
util.js | function isNumeric(n)
{
return !isNaN(parseFloat(n)) && isFinite(n);
}
(function($) {
$.loading = function(show)
{
var hide = (show === false); // no parameter assumes 'show' ; false = 'hide'
if(!j('#waiting').size())
{
j('body').append("<div id='waiting' style='display:none;'><div class='XXui-widget-over... | overlay.select(function() { overlay.hide(); original.show().change(); original.focus(); });
overlay.focus(function() { overlay.hide(); original.show().change(); original.focus(); });
original.blur(function() { if(!original.val()) { overlay.show().change(); original.hide(); } else { original.show(); overlay.hide(... | random_line_split | |
util.js | function isNumeric(n)
{
return !isNaN(parseFloat(n)) && isFinite(n);
}
(function($) {
$.loading = function(show)
{
var hide = (show === false); // no parameter assumes 'show' ; false = 'hide'
if(!j('#waiting').size())
{
j('body').append("<div id='waiting' style='display:none;'><div class='XXui-widget-over... |
if (color) {
opts.color = color;
}
}
data.spinner = new Spinner($.extend({color: $this.css('color')}, opts)).spin(this);
}
});
} else {
throw "Spinner class not available.";
}
};
$(document).ready(function() {
// Remove all form error content.
j('.formerror').html('').... | {
opts = defaults;//{};
} | conditional_block |
util.js | function isNumeric(n)
|
(function($) {
$.loading = function(show)
{
var hide = (show === false); // no parameter assumes 'show' ; false = 'hide'
if(!j('#waiting').size())
{
j('body').append("<div id='waiting' style='display:none;'><div class='XXui-widget-overlay'></div><div id='' class='progress ui-corner-all'>Loading...<div cla... | {
return !isNaN(parseFloat(n)) && isFinite(n);
} | identifier_body |
core.py | # /usr/bin/env python2.7
# -*- mode: python -*-
# =============================================================================
# @@-COPYRIGHT-START-@@
#
# Copyright (c) 2017-2018, Qualcomm Innovation Center, Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modifica... |
@classmethod
def get_weights_for_op(cls, op):
"""
Get the weight tensor for a given op
:param op: TF op
:return: Weight tensor for the op
"""
weights = None
if cls._is_op_with_weights(op):
weights = op.inputs[constants.OP_WEIGHT_INDICES[op.ty... | """
Checks if a given op has weights
:param op: TF op
:return: True, if op has weights, False otherwise
"""
return (op.type in constants.OP_WEIGHT_TYPES and
not op.name.startswith(_SKIPPED_PREFIXES)) | identifier_body |
core.py | # /usr/bin/env python2.7
# -*- mode: python -*-
# =============================================================================
# @@-COPYRIGHT-START-@@
#
# Copyright (c) 2017-2018, Qualcomm Innovation Center, Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modifica... |
return bias
def get_weight_ops(self, ops=None, skip_bias_op=False):
"""
Get all ops that contain weights. If a list of ops is passed search only ops
from this list. Return the sequenced list of weight ops always with Conv/FC
first, followed by the bias op, if present.
... | bias = op.inputs[constants.OP_WEIGHT_INDICES[op.type]] | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.