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
printtips.js
turn LODOP.GET_PRINTER_COUNT(); }; //获取打印机 function getPrinterName(LODOP,iPrinterNO) { return LODOP.GET_PRINTER_NAME(iPrinterNO); }; /** 小票打印 */ //no,name,vac,price,pay,time,insurance function printtips(data){ if(!data){ layer.msg("参数异常,打印失败",{icon:1}); return false; } var pinstr; if(data.pin=="1"){ pin...
t(LODOP) { re
identifier_name
printtips.js
,vac,price,pay,time,insurance function printtips(data){ if(!data){ layer.msg("参数异常,打印失败",{icon:1}); return false; } var pinstr; if(data.pin=="1"){ pinstr = "第一剂次" } if(data.pin=="2"){ pinstr = "第二剂次" } if(data.pin=="3"){ pinstr = "第三剂次" } if(data.pin=="4"){ pinstr = "第四剂次" } if(data.pin=="5"){ ...
NTER_NAME(iPrinterNO); }; /** 小票打印 */ //no,name
identifier_body
printtips.js
layer.msg("参数异常,打印失败",{icon:1}); return false; } var pinstr; if(data.pin=="1"){ pinstr = "第一剂次" } if(data.pin=="2"){ pinstr = "第二剂次" } if(data.pin=="3"){ pinstr = "第三剂次" } if(data.pin=="4"){ pinstr = "第四剂次" } if(data.pin=="5"){ pinstr = "第五剂次" } if(data.impart.group == '17' && data.pin=="1")...
/** 小票打印 */ //no,name,vac,price,pay,time,insurance function printtips(data){ if(!data){
random_line_split
Rs.js
_v; if (latest_v) { me.store_rs.load({ scope: this, synchronous: true, params: { version_id: latest_v.get('id') }, callback: function() { me.columns = me.store_rs.getAt(0).get('columModle'); me.ds = n...
view.cellSelector, innerSelector = view.innerSelector;
me.view, cellSelector =
conditional_block
Rs.js
: 0xf093, scope: this, handler: function() { var win = Ext.create('widget.rs.rsimport', { listeners: { scope: this }, document_id: me.document.id, document: me.document, project: me.project, vstore: me.versions, type: ...
me.getSelectionModel().deselectAll(); }
random_line_split
experiment_util.py
_distribution_fn: Callable[[PRNGKey], Tuple[NDArray, NDArray]] coupling_loss_matrix_fn: Callable[[NDArray, NDArray], NDArray] inner_num_samples: int batch_size: int use_transpose: bool tx: Any num_steps: int print_every: int = 100 metadata: Any = None def loss_and_metrics_one_pair(self, params, rng):...
(self, rng): """Training loop entry point. Calling this method runs the experiment described by this config, and returns various results collected during training. Args: rng: PRNGKey to use to initialize model and draw training examples. Returns: types.SimpleNamespace containing vario...
train
identifier_name
experiment_util.py
_1=None, logits_2=None, num_joint_samples=10_000_000, logit_kwargs=None): """Computes couplings for a collection of experiments. All experiments should have the same logit_pair_distribution_fn. Args: experiments: List of experi...
eval_results.update( evaluate_experiment(ex, res, seed, num_pairs, samples_per_pair, loop_size))
conditional_block
experiment_util.py
_distribution_fn: Callable[[PRNGKey], Tuple[NDArray, NDArray]] coupling_loss_matrix_fn: Callable[[NDArray, NDArray], NDArray] inner_num_samples: int batch_size: int use_transpose: bool tx: Any num_steps: int print_every: int = 100 metadata: Any = None def loss_and_metrics_one_pair(self, params, rng):...
return sampler def get_coupling_estimates(experiments, results, seed, logits_1=None, logits_2=None, num_joint_samples=10_000_000, logit_kwargs=None): ...
q_kwargs = dict(transpose=True) if self.use_transpose else {} x = self.model.bind(params).sample(logits_1, key) y = self.model.bind(params).sample(logits_2, key, **q_kwargs) return jnp.zeros([10, 10]).at[x, y].set(1.)
identifier_body
experiment_util.py
NDArray, NDArray]] coupling_loss_matrix_fn: Callable[[NDArray, NDArray], NDArray] inner_num_samples: int batch_size: int use_transpose: bool tx: Any num_steps: int print_every: int = 100 metadata: Any = None def loss_and_metrics_one_pair(self, params, rng): """Samples a pair of logits, and comput...
_, axs = plt.subplots(nrows=1, ncols=ncols, figsize=(4 * ncols, 4)) axs[0].imshow(jnp.exp(logits_1)[:, None], vmin=0) axs[1].imshow(jnp.exp(logits_2)[None, :], vmin=0) for j, (name, coupling) in enumerate(couplings.items()): axs[j + 2].imshow(coupling, vmin=0)
random_line_split
gesture_recognition_3.4.py
print(datetime.datetime.now()) # ! LJP # 手势O,位置1 filepath_O_1 = filepath + 'LJP/O/gresture_O_location_1_' csi_LJP_O_1 = mul_subcarries(filepath_O_1, feature_number, 0) # 手势X,位置1 filepath_X_1 = filepath + 'LJP/X/gresture_X_location_1_' csi_LJP_X_1 = mul_subcarries(filepath_X_1, feature_numbe...
csi_1 = np.array((csi_LJP_1, csi_DX_1)) csi_1 = np.reshape(csi_1, (-1, feature_number + 1)) csi_1 = np.append(csi_1, csi_MYW_1, axis=0) csi_1 = np.reshape(csi_1, (-1, feature_number + 1)) # 分割特征和标签 train_feature, train_label = np.split(csi_1, (feature_number,), axis=1) test_feature, test_lab...
print(datetime.datetime.now()) # * 整合所有样本,乱序,分割 # 整理数据集
random_line_split
gesture_recognition_3.4.py
(datetime.datetime.now()) # ! LJP # 手势O,位置1 filepath_O_1 = filepath + 'LJP/O/gresture_O_location_1_' csi_LJP_O_1 = mul_subcarries(filepath_O_1, feature_number, 0) # 手势X,位置1 filepath_X_1 = filepath + 'LJP/X/gresture_X_location_1_' csi_LJP_X_1 = mul_subcarries(filepath_X_1, feature_number, 1) ...
# 定义一层全连接层,输出维度是10 self.fc1 = nn.Linear(in_features=2880, out_features=96 ) # 定义一层全连接层,输出维度是10 self.fc2 = nn.Linear(in_features=96, out_features=3) # 定义网络前向计算过程,卷积后紧接着使用池化层,最后使用全连接层计算最终输出 # 卷积层激活函数使用Relu,全连接层激活函数使用softmax def forward(self, inputs): x = self.conv1(inp...
en(imgs_list)的mini-batch if len(imgs_list) > 0: yield np.array(imgs_list), np.array(labels_list) return data_generator # 定义模型结构 class CNN(nn.Module): def __init__(self): super(CNN, self).__init__() # 定义卷积层,输出特征通道out_channels设置为20,卷积核的大小kernel_size为5,卷积步长stride=1,padding=2...
identifier_body
gesture_recognition_3.4.py
print(datetime.datetime.now()) # ! LJP # 手势O,位置1 filepath_O_1 = filepath + 'LJP/O/gresture_O_location_1_' csi_LJP_O_1 = mul_subcarries(filepath_O_1, feature_number, 0) # 手势X,位置1 filepath_X_1 = filepath + 'LJP/X/gresture_X_location_1_' csi_LJP_X_1 = mul_subcarries(filepath_X_1, feature_numbe...
.array(labels_list) # 清空数据缓存列表 imgs_list = [] labels_list = [] # 如果剩余数据的数目小于BATCHSIZE, # 则剩余数据一起构成一个大小为len(imgs_list)的mini-batch if len(imgs_list) > 0: yield np.array(imgs_list), np.array(labels_list) return data_generator # 定义模...
: yield np.array(imgs_list), np
conditional_block
gesture_recognition_3.4.py
(datetime.datetime.now()) # ! LJP # 手势O,位置1 filepath_O_1 = filepath + 'LJP/O/gresture_O_location_1_' csi_LJP_O_1 = mul_subcarries(filepath_O_1, feature_number, 0) # 手势X,位置1 filepath_X_1 = filepath + 'LJP/X/gresture_X_location_1_' csi_LJP_X_1 = mul_subcarries(filepath_X_1, feature_number, 1) ...
余数据一起构成一个大小为len(imgs_list)的mini-batch if len(imgs_list) > 0: yield np.array(imgs_list), np.array(labels_list) return data_generator # 定义模型结构 class CNN(nn.Module): def __init__(self): super(CNN, self).__init__() # 定义卷积层,输出特征通道out_channels设置为20,卷积核的大小kernel_size为5,卷积步长strid...
, # 则剩
identifier_name
pit.rs
//! let (_, _, _, mut pit) = ral::pit::PIT::take() //! .map(PIT::new) //! .unwrap(); //! //! # async { //! pit.delay(250_000).await; //! # }; //! ``` use crate::ral; use core::{ future::Future, marker::PhantomPinned, pin::Pin, sync::atomic, task::{Context, Poll, Waker}, }; /// Periodic in...
//! // Select 24MHz crystal oscillator, divide by 24 == 1MHz clock //! ral::modify_reg!(ral::ccm, ccm, CSCMR1, PERCLK_PODF: DIVIDE_24, PERCLK_CLK_SEL: 1); //! // Enable PIT clock gate //! ral::modify_reg!(ral::ccm, ccm, CCGR1, CG6: 0b11);
random_line_split
pit.rs
pit::PIT::take() //! .map(PIT::new) //! .unwrap(); //! //! # async { //! pit.delay(250_000).await; //! # }; //! ``` use crate::ral; use core::{ future::Future, marker::PhantomPinned, pin::Pin, sync::atomic, task::{Context, Poll, Waker}, }; /// Periodic interrupt timer (PIT) /// /// See th...
() -> Self { Self::new(PIT_CHANNEL_3_ADDRESS, 3) } } /// Timer Load Value Register pub mod LDVAL { /// Timer Start Value pub mod TSV { /// Offset (0 bits) pub const offset: u32 = 0; /// Mask (32 bits: 0xffffffff << 0) pub ...
three
identifier_name
pit.rs
pit::PIT::take() //! .map(PIT::new) //! .unwrap(); //! //! # async { //! pit.delay(250_000).await; //! # }; //! ``` use crate::ral; use core::{ future::Future, marker::PhantomPinned, pin::Pin, sync::atomic, task::{Context, Poll, Waker}, }; /// Periodic interrupt timer (PIT) /// /// See th...
else { // Neither complete nor active; prepare to run ral::write_reg!(register, channel, LDVAL, count); unsafe { WAKERS[channel.index()] = Some(cx.waker().clone()); } atomic::compiler_fence(atomic::Ordering::SeqCst); ral::modify_reg!(register, channel, TCTRL,...
{ // We're active; do nothing Poll::Pending }
conditional_block
pit.rs
pit::PIT::take() //! .map(PIT::new) //! .unwrap(); //! //! # async { //! pit.delay(250_000).await; //! # }; //! ``` use crate::ral; use core::{ future::Future, marker::PhantomPinned, pin::Pin, sync::atomic, task::{Context, Poll, Waker}, }; /// Periodic interrupt timer (PIT) /// /// See th...
} static mut WAKERS: [Option<Waker>; 4] = [None, None, None, None]; /// A future that yields once the PIT timer elapses pub struct Delay<'a> { channel: &'a mut register::ChannelInstance, _pin: PhantomPinned, count: u32, } impl<'a> Future for Delay<'a> { type Output = (); fn poll(self: Pin<&mut ...
{ Delay { channel: &mut self.channel, count, _pin: PhantomPinned, } }
identifier_body
transform_provider.go
.ProviderName()} g.Add(closer) cpm[p.ProviderName()] = closer } // Close node depends on the provider itself // this is added unconditionally, so it will connect to all instances // of the provider. Extra edges will be removed by transitive // reduction. g.Connect(dag.BasicEdge(closer, p)) // conn...
transform
identifier_name
transform_provider.go
for i := 1; target == nil; i++ { path := normalizeModulePath(sp.Path()) if len(path) < i { break } key = ResolveProviderName(p, path[:len(path)-i]) target = m[key] if target != nil { break } } if target == nil { err = multierror.Append(err, fmt.Errorf( "%s: conf...
func (n *graphNodeCloseProvider) CloseProviderName() string { return n.ProviderNameValue } // GraphNodeDotter impl. func (n *graphNodeCloseProvider) DotNode(name string, opts *dag.DotOpts) *dag.DotNode { if !opts.Verbose { return nil } return &dag.DotNode{ Name: name, Attrs: map[string]string{ "label": ...
{ return []string{n.Name()} }
identifier_body
transform_provider.go
for i := 1; target == nil; i++ { path := normalizeModulePath(sp.Path()) if len(path) < i { break } key = ResolveProviderName(p, path[:len(path)-i]) target = m[key] if target != nil { break } } if target == nil { err = multierror.Append(err, fmt.Errorf( "%s: conf...
log.Printf("[DEBUG] resource %s using provider %s", dag.VertexName(pv), key) pv.SetProvider(key) g.Connect(dag.BasicEdge(v, target)) } } return err } // CloseProviderTransformer is a GraphTransformer that adds nodes to the // graph that will close open provider connections that aren't needed anymore. /...
{ g.Remove(p) target = p.Target() key = target.(GraphNodeProvider).Name() }
conditional_block
transform_provider.go
for i := 1; target == nil; i++ { path := normalizeModulePath(sp.Path()) if len(path) < i { break } key = ResolveProviderName(p, path[:len(path)-i]) target = m[key] if target != nil { break } } if target == nil { err = multierror.Append(err, fmt.Errorf( "%s: conf...
parts := strings.SplitAfter(p, "provider.") p = parts[len(parts)-1] key := ResolveProviderName(p, nil) provider := m[key] // we already have it if provider != nil { continue } // we don't implicitly create aliased providers if strings.Contains(p, ".") { log.Println("[DEBUG] not adding missing...
random_line_split
predata_externals.go
(extTableDef) metadataFile.MustPrintf("\n\nCREATE %s TABLE %s (\n", tableTypeStrMap[extTableDef.Type], table.FQN()) printColumnDefinitions(metadataFile, table.ColumnDefs, "") metadataFile.MustPrintf(") ") PrintExternalTableStatements(metadataFile, table.FQN(), extTableDef) if extTableDef.Writable { metadataFile....
(formatOpts string) []string { inString := false resultList := make([]string, 0) currString := "" for i := 0; i < len(formatOpts); i++ { switch formatOpts[i] { case '\'': if inString { /* * Escape apostrophes *within* the string. If the * apostrophe is at the end of the source string or is ...
tokenizeAndEscapeFormatOpts
identifier_name
predata_externals.go
(extTableDef) metadataFile.MustPrintf("\n\nCREATE %s TABLE %s (\n", tableTypeStrMap[extTableDef.Type], table.FQN()) printColumnDefinitions(metadataFile, table.ColumnDefs, "") metadataFile.MustPrintf(") ") PrintExternalTableStatements(metadataFile, table.FQN(), extTableDef) if extTableDef.Writable { metadataFile....
} if extTableDef.Type == READABLE_WEB || extTableDef.Type == WRITABLE_WEB { if extTableDef.Command != "" { metadataFile.MustPrint(generateExecuteStatement(extTableDef)) } } metadataFile.MustPrintln() metadataFile.MustPrint(GenerateFormatStatement(extTableDef)) metadataFile.MustPrintln() metadataFile.Must...
{ metadataFile.MustPrintf(" ON COORDINATOR") }
conditional_block
predata_externals.go
toc.AddMetadataEntry(section, entry, start, metadataFile.ByteCount) } } func DetermineExternalTableCharacteristics(extTableDef ExternalTableDefinition) (int, int) { isWritable := extTableDef.Writable var tableType int tableProtocol := -1 if !extTableDef.Location.Valid || extTableDef.Location.String == "" { /...
{ start := metadataFile.ByteCount tableTypeStrMap := map[int]string{ READABLE: "READABLE EXTERNAL", READABLE_WEB: "READABLE EXTERNAL WEB", WRITABLE: "WRITABLE EXTERNAL", WRITABLE_WEB: "WRITABLE EXTERNAL WEB", } extTableDef := table.ExtTableDef extTableDef.Type, extTableDef.Protocol = DetermineExter...
identifier_body
predata_externals.go
"github.com/greenplum-db/gpbackup/toc" "github.com/greenplum-db/gpbackup/utils" ) const ( // Type of external table READABLE = iota READABLE_WEB WRITABLE WRITABLE_WEB // Protocol external table is using FILE GPFDIST GPHDFS HTTP S3 ) type ExternalTableDefinition struct { Oid uint32 Type ...
import ( "database/sql" "fmt" "strings"
random_line_split
dashboard.py
will not be # refreshed by us but need to do that themselves. if "url" in dashlet: refresh_dashlets.append([nr, dashlet.get("refresh", 0), str(add_wato_folder_to_url(dashlet["url"], wato_folder))]) # Paint the dashlet's HTML code render_dashlet(nr, dashlet, wa...
bottom = abs_position[1] top = bottom - used_size[1]
conditional_block
dashboard.py
0px; position: relative;"> """ % (dashlet["title"], nr)) # # The content is rendered only if it is fixed. In the # # other cases the initial (re)-size will paint the content. if "content" in dashlet: # fixed content html.write(dashlet["content"]) elif "iframe" in dashlet: # fixed content co...
shlet_overview()
identifier_name
dashboard.py
-50" id="content">""") result = """ <!-- PAGE HEADER--> <div class="row"> <div class="col-sm-12"> <div class="page-header"> <!-- STYLER --> <!-- /STYLER --> <!...
# Compute the initial size of the dashlet. If MAX is used, # then the dashlet consumes all space in its growing direction, # regardless of any other dashlets. def initial_size(self, position, rastersize): n = [] for i in [0, 1]: if self._data[i] ...
n = [] for i in [0, 1]: if self._data[i] < 0: n.append(size[i] + self._data[i] + 1) # Here was a bug fixed by Markus Lengler else: n.append(self._data[i] - 1) # make begin from 0 return vec(n)
identifier_body
dashboard.py
dashlet_mk_logo(): html.write('<a href="http://mathias-kettner.de/check_mk.html">' '<img style="margin-right: 30px;" src="images/check_mk.trans.120.png"></a>') def dashlet_hoststats(): table = [ ( _("Up"), "#0b3", "searchhost&is_host_scheduled_downtime_depth=0&hst0=on", "Stats: s...
img_url = base_url + "image" + var_part
random_line_split
update.go
In { node.Country = tryGetCountry(gdb, gdb6, node.Host, true) nodesOut <- node } close(nodesOut) }() } for i := 0; i < numWorkers; i++ { go func() { defer worker.Done() for node := range rawNodesIn { node.Country = tryGetCountry(gdb, gdb6, node.Host, false) rawNodesOut <- node } ...
err := network.ListenOn("0.0.0.0", sslDir+"/ca/chia_ca.crt", sslDir+"/ca/chia_ca.key", nil, connHandler)
random_line_split
update.go
item := l.start l.delItemNoLock(item) return item } type NodeAddr struct { Host string Port uint16 Country *string } type Node struct { ID []byte Host string Port uint16 ProtocolVersion string SoftwareVersion string NodeType string Country *string ...
{ return nil }
conditional_block
update.go
utils.IsPGDeadlock(err) { return nil } if err != nil { return merry.Wrap(err) } if len(nodes) == 0 { return nil } stt = time.Now().UnixNano() _, err = tx.Exec(` UPDATE nodes SET checked_at = NOW() WHERE id IN (?)`, NodeListAsPGIDs(nodes)) updDur = time.Now().Uni...
{ worker := utils.NewSimpleWorker(2 * numWorkers) for i := 0; i < numWorkers; i++ { go func() { defer worker.Done() for node := range nodesIn { node.Country = tryGetCountry(gdb, gdb6, node.Host, true) nodesOut <- node } close(nodesOut) }() } for i := 0; i < numWorkers; i++ { go func() { ...
identifier_body
update.go
() (string, error) { resp, err := http.Get("https://checkip.amazonaws.com/") if err != nil { return "", merry.Wrap(err) } defer resp.Body.Close() body, err := io.ReadAll(resp.Body) if err != nil { return "", merry.Wrap(err) } return strings.TrimSpace(string(body)), nil } type ConnListItem struct { prev *C...
askIP
identifier_name
cadastro_orcamento_emp.js
$("#servicoRefIn").focus(); } getRowMonted = function (value) { var seletorTabela = document.getElementById("tabelaIn"); var seletorSetor = document.getElementById("setorIn"); if ((seletorTabela.value == "") || (seletorSetor.value == "") || ($("#servicoRefIn").val() == "") || ($("#servicoIn").val() ==...
{ $('#tabelaIn').removeAttr("disabled", "disabled"); }
conditional_block
cadastro_orcamento_emp.js
return ""; } var htm = "<tr class=\"gridRow\" id=\"line" + value + "\" name=\"line" + value + "\" ><td><label id=\"rowSetor" + value + "\" name=\"rowSetor" + value + "\" >"; switch (seletorSetor.value) { case 'o': htm += "Odontológica</label></td>"; break; case 'l': htm += "Labor...
return htm; } getRowForDel = function (value, indexRow) { var htm = "<tr class=\"gridRow\" id=\"line" + value + "\" name=\"line" + value + "\" ><td><label id=\"rowSetor" + value + "\" name=\"rowSetor" + value + "\" >" + $("#rowSetor" + indexRow).text() + "</label></td>"; htm += "<td><label id=\"rowE...
htm += "<td style=\"width: 10px;\"><input id=\"checkrowTabela" + value + "\" name=\"checkrowTabela" + value + "\" type=\"checkbox\"/></td></tr>";
random_line_split
toolchain_tester.py
tmp files is intentionally hardcoded, so you can only run one instance of this at a time. """ from __future__ import print_function import getopt import glob import multiprocessing import os import shlex import subprocess import sys import time import toolchain_config # =============================================...
'concurrency=']) except getopt.GetoptError as err: Print(str(err)) # will print something like 'option -a not recognized' sys.exit(-1) for o, a in opts: # strip the leading '--' o = o[2:] if o == 'verbose': VERBOSE = 1 elif o == 'show_console': S...
'tmp=',
random_line_split
toolchain_tester.py
files is intentionally hardcoded, so you can only run one instance of this at a time. """ from __future__ import print_function import getopt import glob import multiprocessing import os import shlex import subprocess import sys import time import toolchain_config # =================================================...
# ====================================================================== def Banner(message): Print('=' * 70) Print(message) Print('=' * 70) # ====================================================================== def RunCommand(cmd, always_dump_stdout_stderr): """Run a shell command given as an argv style ...
for s in REPORT_STREAMS: print(message, file=s)
identifier_body
toolchain_tester.py
files is intentionally hardcoded, so you can only run one instance of this at a time. """ from __future__ import print_function import getopt import glob import multiprocessing import os import shlex import subprocess import sys import time import toolchain_config # =================================================...
(args): num, total, config, test, extra_flags = args base_test_name = os.path.basename(test) extra_flags = extra_flags.copy() toolchain_config.AppendDictionary(extra_flags, APPEND_PER_TEST.get(base_test_name, {})) Print('Running %d/%d: %s' % (num + 1, total, base_test_name)...
RunTest
identifier_name
toolchain_tester.py
files is intentionally hardcoded, so you can only run one instance of this at a time. """ from __future__ import print_function import getopt import glob import multiprocessing import os import shlex import subprocess import sys import time import toolchain_config # =================================================...
else: test = line if test in EXCLUDE: Print('ERROR: duplicate exclude: [%s]' % line) EXCLUDE[test] = excludefile f.close() Print('Size of excludes now: %d' % len(EXCLUDE)) def ParseAppendFiles(): """Parse the file contain a list of test + CFLAGS to append for that test."""...
attributes = set(tokens[1].split(',')) if not attributes.issubset(config_attributes): continue test = tokens[0]
conditional_block
cipher_handout.py
content.append(contentLine) return content def block_to_content(contentBlock, block_height=8, block_length=8): content = [] for contentLine in contentBlock: for contentItem in contentLine: content.append(contentItem) return content def hill_encrypt_block_array(content...
for contentLine in contentBlock:
random_line_split
cipher_handout.py
def padding_content(content, blocksize=64): for i in range(int((len(content) - 1) / blocksize + 1) * blocksize - len(content)): content.append(0) return content def drop_padding(content): for i in range(len(content)): if content[i] == 0: return content[:i] return content...
str = "" for item in list: str += chr(item) return str
identifier_body
cipher_handout.py
Array, keyArray) % field) return cipherBlock def hill_decrypt_block(contentBlock, keyBlock, field): plainBlock = [] contentArray = np.array(contentBlock) keyArray = np.array(keyBlock) plainBlock = np.ndarray.tolist(np.dot(contentArray, keyArray) % field) return plainBlock def des_string_proc...
34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4 ] return [keyList[PC[i] - 1] for i in range(56)] def des_key_do_shift_pc_2(keyList): '''在DES的每一轮中,从56位密钥产生出不同的48位子密钥''' ...
1, 58, 50, 42,
identifier_name
cipher_handout.py
return content def des_block_array_to_content(contentBlockArray): content = [] for contentBlock in contentBlockArray: for contentLine in contentBlock: content.append(contentLine) return content def block_to_content(contentBlock, block_height=8, block_length=8): content = [] ...
content.append(contentItem)
conditional_block
K2400.py
current measurement function. if set_compl != 0: port_write(ser, ":SENS:CURR:PROT " + str(set_compl)) # Set compliance limit to 10mA. port_write(ser, ":SENS:CURR:RANG " + str(set_compl)) # Select the 10mA measurement range. else: port_write(ser, ":SENS:CURR:PROT AUTO") # Set complian...
(PortUSB): signal.signal(signal.SIGINT, signal_handler) ser = serial.Serial( port=PortUSB, baudrate=9600, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=1, xonxoff=0, rtscts=1) if ser.isOpen(): ...
init_port
identifier_name
K2400.py
(ser, ":MEASure?") # port_write(ser,":DISPlay:ENABle OFF") except Exception, e1: print ":: ERROR: problem with communicating ...: " + str(e1) else: print ":: ERROR: Can not open serial port: ", ser logging.info("INIT_CONTROLER_PIC") return 0 def port_close(ser): p...
x+=0.5 y=2*x*x-2*x+1 txt=str(x)+" "+str(y) log_save(txt) t1=time.time() print t1-t0 if x>=20: break
conditional_block
K2400.py
Select current measurement function. if set_compl != 0: port_write(ser, ":SENS:CURR:PROT " + str(set_compl)) # Set compliance limit to 10mA. port_write(ser, ":SENS:CURR:RANG " + str(set_compl)) # Select the 10mA measurement range. else: port_write(ser, ":SENS:CURR:PROT AUTO") # Set c...
with open(PATH + "/log/FName_Last", 'r') as f: LastFName = str(f.readline()) with open(PATH + "/log/FName_Last", 'w') as f: f.write(FName) with open(PATH + "/FName", 'w') as f: f.write(FName) shutil.move(str(PATH) + "/raw.txt", LastFName + ".raw") with open(str(PATH) + "/raw.txt", 'aw+') as the_fi...
print "=====================================" print FName print "====================================="
random_line_split
K2400.py
Select current measurement function. if set_compl != 0: port_write(ser, ":SENS:CURR:PROT " + str(set_compl)) # Set compliance limit to 10mA. port_write(ser, ":SENS:CURR:RANG " + str(set_compl)) # Select the 10mA measurement range. else: port_write(ser, ":SENS:CURR:PROT AUTO") # Set c...
def signal_handler(signal, frame): K2400.log_save("#::::: ABORT ::::::") print "\n:: You pressed Ctrl+C!" print "::Programm will be TERMINATED ... \n . . . . . . . . . ." with open(FILE_SWITCH, 'w+') as the_file: the_file.write("OFF") def init(): global ser_VGS global ser...
logging.info("CHECK FILE: " + path) path = os.path.expanduser(path) root, ext = os.path.splitext(os.path.expanduser(path)) dir = os.path.dirname(root) fname = os.path.basename(root) candidate = fname + ext index = 1 ls = set(os.listdir(dir)) while candidate in ls: candidate = "{0...
identifier_body
maneuver_spreadsheet_support.py
0.140402890291, max 44.1715921604. # distfact = 2 # Mean logspline error is 5.13227646421, median 1.11771126799, max 64.1222831046. Mean linspline error is 15.9565636692, median 1.12503901849, max 632.523260832. # distfact = 5 # Mean logspline error is 5.95691325441, median 3.00161632168, max 82.3370962708. Mean linsp...
filedata = np.genfromtxt(file_to_interpolate, delimiter=',') xs = filedata[1:,0] # In sample data, x should go from -24 to 15 ys = filedata[0,1:-1] # In sample data, y should go from .001 to 18 data = filedata[1:,1:-1] # We have to trim off the last element of each row (nan) because of the trailing ...
identifier_body
maneuver_spreadsheet_support.py
6,15)])) for fl in fork_lengths: size_appropriate_velocities = [v for v in all_velocities if v < 3.0 * fl + 50] for v in size_appropriate_velocities:
total_bytes *= 2 # because there are 2 response variables time_per_sheet = total_time / total_sheets real_time = (total_time / 3600) / max_instances print("Total calculation predicted to generate {0} sheets in {1:.1f} cpu-hours ({2:.1f} min/sheet, {4:.1f} hours for {5} instances) taking {3:.1f} mb of space.".format(to...
total_sheets += 1 total_bytes += bytes_per_number * numbers_per_sheet total_time += time_per_number * numbers_per_sheet queries.append(f"INSERT INTO maneuver_model_tasks (fork_length, velocity) VALUES ({fl:.1f}, {v:.1f})")
conditional_block
maneuver_spreadsheet_support.py
0.176547064472. # NEXT TEST: Increase resolution to 312 pts, and start using percent errors instead of regular errors, cover full realistic ranges # distfact = 1 # Mean logspline error is 6.61230781457, median 2.52211224078, max 81.438706048. Mean linspline error is 2.70886911207, median 0.140402890291, max 44.1715921...
maneuver_cost_interpolation
identifier_name
maneuver_spreadsheet_support.py
6318184. # Now using data from actual fish within the range where they're really doing stuff (N=300 for calculating these stats) # Mean logspline error is 6.22782654855, median 3.72433730964, max 42.6818144461. Mean linspline error is 15.4806385555, median 4.82063948279, max 323.389534253 # That is, dare I say, tolerab...
testpt = (-15, 5, 3) interp_ec = maneuver_cost_interpolation("/Users/Jason/Dropbox/Drift Model Project/Calculations/driftmodeldev/maneuvermodel/sample_data/interpolation_sample_data_energy_cost.csv") interpolate_maneuver_cost(testpt, interp_ec)
random_line_split
tools.js
Url: "http://eh3.uc.edu/pilincs/#/api", shortDesc: "Interface to panoramaweb.org" }, { title: "LINCS Joint Project - Breast Cancer Network Browser", description: "LJP-BCNB visualizes thousands of signatures from six breast cancer cell lines treated with ~100 single molecule ...
title: "Harmonizome", description: "Built on top of information about genes and proteins from 114 datasets, the Harmonizome is a knowledge engine for a diverse set of integrated resources.", url: "http://amp.pharm.mssm.edu/Harmonizome", target: "_blank", image...
{
random_line_split
test_pessismistic_multi_tables.go
const batchSize = 100 func LoadData(db *sql.DB, maxSize uint64) error { for i := 0; i < *tables; i++ { tableName := fmt.Sprintf("t%d", i) log.Printf("loading table: %s\n", tableName) if _, err := db.Exec(fmt.Sprintf("drop table if exists %s", tableName)); err != nil { return nil } createTableStmt := fmt....
} } se.commitStart = time.Now() _, err = se.conn.ExecContext(ctx, "commit") if err != nil { se.handleError(ctx, err, true) } else { atomic.AddUint64(&successTxn, 1) } return nil } func getErrorCode(err error) int { var code int _, err1 := fmt.Sscanf(err.Error(), "Error %d:", &code) if err1 != nil { ...
{ se.reset() ctx, cancel := context.WithTimeout(parent, time.Minute) defer cancel() beginSQL := "begin /*!90000 optimistic */" if se.isPessimistic { beginSQL = "begin /*!90000 pessimistic */" } _, err := se.conn.ExecContext(ctx, beginSQL) if err != nil { return err } numStmts := 1 + se.ran.uniform.Intn(5)...
identifier_body
test_pessismistic_multi_tables.go
essimistic { ignoreCodes = ignoreCodesP } for _, ignoreCode := range ignoreCodes { if ignoreCode == code { return } } txnMode := "optimistic" if se.isPessimistic { txnMode = "pessimistic" } if isCommit { log.Println(txnMode, "txnDur", time.Since(se.txnStart), "commitDur", time.Since(se.commitStart),...
statsLoop
identifier_name
test_pessismistic_multi_tables.go
if !*insertDelete { go checkLoop(db) } go statsLoop() wg.Wait() } const batchSize = 100 func LoadData(db *sql.DB, maxSize uint64) error { for i := 0; i < *tables; i++ { tableName := fmt.Sprintf("t%d", i) log.Printf("loading table: %s\n", tableName) if _, err := db.Exec(fmt.Sprintf("drop table if exists ...
{ se, err := NewSession(db, uint64(i), *tableSize, numPartitions) if err != nil { log.Fatal(err) } go se.Run(wg) }
conditional_block
test_pessismistic_multi_tables.go
const batchSize = 100 func LoadData(db *sql.DB, maxSize uint64) error { for i := 0; i < *tables; i++ { tableName := fmt.Sprintf("t%d", i) log.Printf("loading table: %s\n", tableName) if _, err := db.Exec(fmt.Sprintf("drop table if exists %s", tableName)); err != nil { return nil } createTableStmt := fmt....
} _, err := se.conn.ExecContext(ctx, beginSQL) if err != nil { return err } numStmts := 1 + se.ran.uniform.Intn(5) for i := 0; i < numStmts; i++ { stmtType := se.ran.uniform.Intn(len(se.stmts)) f := se.stmts[stmtType] err = f(ctx) if err != nil { se.handleError(ctx, err, false) return nil } } ...
defer cancel() beginSQL := "begin /*!90000 optimistic */" if se.isPessimistic { beginSQL = "begin /*!90000 pessimistic */"
random_line_split
backbone2.py
2, 512, "M"], 13: [64, 64, "M", 128, 128, "M", 256, 256, "M", 512, 512, "M", 512, 512, "M"], 16: [64, 64, "M", 128, 128, "M", 256, 256, 256, "M", 512, 512, 512, "M", 512, 512, 512, "M"], 19: [64,64,"M",128,128,"M",256,256,256,256,"M",512,512,512,512,"M",512,512,512,512,"M"], } class Conv2d2(Conv2d): ""...
self.out_channels = out_channels self.kernel_size = _pair(kernel_size) self.stride = _pair(stride) self.padding = _pair(padding) self.dilation = _pair(dilation) self.groups = groups self.deformable_groups = deformable_groups self.norm = norm self.a...
""" Deformable convolution from :paper:`deformconv`. Arguments are similar to :class:`Conv2D`. Extra arguments: Args: deformable_groups (int): number of groups used in deformable convolution. norm (nn.Module, optional): a normalization layer activation (call...
identifier_body
backbone2.py
2, 512, "M"], 13: [64, 64, "M", 128, 128, "M", 256, 256, "M", 512, 512, "M", 512, 512, "M"], 16: [64, 64, "M", 128, 128, "M", 256, 256, 256, "M", 512, 512, 512, "M", 512, 512, 512, "M"], 19: [64,64,"M",128,128,"M",256,256,256,256,"M",512,512,512,512,"M",512,512,512,512,"M"], } class Conv2d2(Conv2d): ""...
if isinstance(x,tuple): x,_=x if self.num_classes is not None: x = self.avgpool(x) x = self.classifier(x) if "classifer" in self._out_features: outputs["classifer"] = x return outputs def output_shape(self): r...
outputs[name] = x
conditional_block
backbone2.py
, 512, "M"], 13: [64, 64, "M", 128, 128, "M", 256, 256, "M", 512, 512, "M", 512, 512, "M"], 16: [64, 64, "M", 128, 128, "M", 256, 256, 256, "M", 512, 512, 512, "M", 512, 512, 512, "M"], 19: [64,64,"M",128,128,"M",256,256,256,256,"M",512,512,512,512,"M",512,512,512,512,"M"], } class Conv2d2(Conv2d): """...
(self): tmpstr = "in_channels=" + str(self.in_channels) tmpstr += ", out_channels=" + str(self.out_channels) tmpstr += ", kernel_size=" + str(self.kernel_size) tmpstr += ", stride=" + str(self.stride) tmpstr += ", padding=" + str(self.padding) tmpstr += ", dilation=" + st...
extra_repr
identifier_name
backbone2.py
2, 512, "M"], 13: [64, 64, "M", 128, 128, "M", 256, 256, "M", 512, 512, "M", 512, 512, "M"], 16: [64, 64, "M", 128, 128, "M", 256, 256, 256, "M", 512, 512, 512, "M", 512, 512, 512, "M"], 19: [64,64,"M",128,128,"M",256,256,256,256,"M",512,512,512,512,"M",512,512,512,512,"M"], } class Conv2d2(Conv2d): ""...
self.deformable_groups = deformable_groups self.norm = norm self.activation = activation self.weight = nn.Parameter( torch.Tensor(out_channels, in_channels // self.groups, *self.kernel_size) ) if bias: self.bias = nn.Parameter(torch.Tensor(out_cha...
self.stride = _pair(stride) self.padding = _pair(padding) self.dilation = _pair(dilation) self.groups = groups
random_line_split
transactions_reader.rs
::HashMap, io::{BufRead, BufReader}, path::Path, }; use anyhow::Context; use crossbeam_channel::{Receiver, Sender}; use csv::{ByteRecord, ReaderBuilder, Trim}; use crate::records::TransactionRecord; use log::*; /// A type that represents a stream of transactions arriving into the system /// Many channels (s...
while let Ok(true) = csv_reader.read_byte_record(&mut raw_record) { let record = raw_record.deserialize::<TransactionRecord>(Some(&headers)); if let Ok(record) = record { transactions.push(record); } ...
{ for _ in 0..num_threads { let block_rx = block_rx.clone(); let parsed_tx = parsed_tx.clone(); // For now consider that the headers if read then they're OK and equal to below let headers = ByteRecord::from(vec!["type", "client", "tx", "amount"]); std:...
identifier_body
transactions_reader.rs
::HashMap, io::{BufRead, BufReader}, path::Path, }; use anyhow::Context; use crossbeam_channel::{Receiver, Sender}; use csv::{ByteRecord, ReaderBuilder, Trim}; use crate::records::TransactionRecord; use log::*; /// A type that represents a stream of transactions arriving into the system /// Many channels (s...
; } waiting_for += 1; } } else if block.0 > waiting_for { queue.insert(block.0, block.1); } } }); } // Reads a big block until new line alignment fn read_block(&mut se...
{ return; }
conditional_block
transactions_reader.rs
::HashMap, io::{BufRead, BufReader}, path::Path, }; use anyhow::Context; use crossbeam_channel::{Receiver, Sender}; use csv::{ByteRecord, ReaderBuilder, Trim}; use crate::records::TransactionRecord; use log::*; /// A type that represents a stream of transactions arriving into the system /// Many channels (s...
/// Tests that we can read and parse all transactions #[test] fn test_st_bulk_transaction_reader_serde() { let reader = STBulkReader::new(); test_transaction_reader(reader, "tests/data/test_serde.csv"); } #[test] fn test_mt_reader_transaction_reader_serde() { let reader ...
random_line_split
transactions_reader.rs
::HashMap, io::{BufRead, BufReader}, path::Path, }; use anyhow::Context; use crossbeam_channel::{Receiver, Sender}; use csv::{ByteRecord, ReaderBuilder, Trim}; use crate::records::TransactionRecord; use log::*; /// A type that represents a stream of transactions arriving into the system /// Many channels (s...
{} impl STBulkReader { pub fn new() -> Self { Self {} } } impl TransactionCSVReader for STBulkReader { fn read_csv<P: AsRef<Path>>(self, path: P) -> anyhow::Result<TransactionsStream> { let start_time = std::time::Instant::now(); info!("STBulkReader reading the transactions"); ...
STBulkReader
identifier_name
dir.rs
name, metadata, } } pub fn name(&self) -> &str { &self.name } pub fn metadata(&self) -> &Metadata { &self.metadata } /// Finds the entry named `name` in `self` and returns it. Comparison is /// case-insensitive. /// /// # Errors /// ///...
}).filter_map(|entry| match entry.lfn() { Some(lfn) if lfn.seqno != 0xE5 => Some(*lfn), _ => None, }).collect(); entries.sort_by_key(|lfn| lfn.seqno); let mut name: Vec<u16> = vec![]; for &lfn in entries.iter() { name.extend(...
{ false }
conditional_block
dir.rs
name, metadata, } } pub fn name(&self) -> &str { &self.name } pub fn metadata(&self) -> &Metadata { &self.metadata } /// Finds the entry named `name` in `self` and returns it. Comparison is /// case-insensitive. /// /// # Errors /// ///...
#[repr(C, packed)] #[derive(Copy, Clone, Debug)] pub struct VFatLfnDirEntry { seqno: u8, name_1: [u16; 5], attributes: u8, _reserved_1: u8, dos_checksum: u8, name_2: [u16; 6], _reserved_2: [u8; 2], name_3: [u16; 2], } #[repr(C, packed)] #[derive(Copy, Clone)] pub struct VFatUnknownDirEn...
} }
random_line_split
dir.rs
`name` exists in `self`, an error of `NotFound` is /// returned. /// /// If `name` contains invalid UTF-8 characters, an error of `InvalidInput` /// is returned. pub fn find<P: AsRef<OsStr>>(&self, name: P) -> io::Result<Entry> { let name = name.as_ref().to_str().ok_or(io::Error::new( ...
next
identifier_name
dir.rs
name, metadata, } } pub fn name(&self) -> &str { &self.name } pub fn metadata(&self) -> &Metadata { &self.metadata } /// Finds the entry named `name` in `self` and returns it. Comparison is /// case-insensitive. /// /// # Errors /// ///...
fn cluster(&self) -> Cluster { Cluster::from(((self.cluster_high as u32) << 16) | (self.cluster_low as u32)) } fn created(&self) -> Timestamp { let date = Date::from_raw(self.created_date); let time = Time::from_raw(self.created_time); Timestamp::new(date, time) } ...
{ self.name[0] == 0x05 || self.name[0] == 0xE5 }
identifier_body
mod.rs
fSceneLoaderSystemDesc, input::{InputBundle, StringBindings}, prelude::*, renderer::{ plugins::{RenderPbr3D, RenderSkybox, RenderToWindow}, RenderingBundle, Texture, types::{DefaultBackend, Mesh, MeshData}, }, ui::{RenderUi, UiBundle}, utils::{ application...
let parent_ent: Entity = parents.get(entity)?.entity; get_root_cloned( parents, components, parent_ent, ) } } pub fn get_root_mut<'s, 'a, T, P, C>( parents: &P, components: &'a mut C, entity: Entity, ) -> Option<(&'a mut T, Entity)> where T: Component, P:...
random_line_split
mod.rs
fSceneLoaderSystemDesc, input::{InputBundle, StringBindings}, prelude::*, renderer::{ plugins::{RenderPbr3D, RenderSkybox, RenderToWindow}, RenderingBundle, Texture, types::{DefaultBackend, Mesh, MeshData}, }, ui::{RenderUi, UiBundle}, utils::{ application...
else { let parent_ent: Entity = parents.get(entity)?.entity; get_root_cloned( parents, components, parent_ent, ) } } pub fn get_root_mut<'s, 'a, T, P, C>( parents: &P, components: &'a mut C, entity: Entity, ) -> Option<(&'a mut T, Entity)> where T: Compo...
{ Some((component.clone(), entity)) }
conditional_block
mod.rs
SceneLoaderSystemDesc, input::{InputBundle, StringBindings}, prelude::*, renderer::{ plugins::{RenderPbr3D, RenderSkybox, RenderToWindow}, RenderingBundle, Texture, types::{DefaultBackend, Mesh, MeshData}, }, ui::{RenderUi, UiBundle}, utils::{ application_...
pub fn get_root_mut<'s, 'a, T, P, C>( parents: &P, components: &'a mut C, entity: Entity, ) -> Option<(&'a mut T, Entity)> where T: Component, P: GenericReadStorage<Component=Parent>, C: GenericWriteStorage<Component=T> { if components.get_mut(entity).is_some() { Some((components.get_mut(entit...
{ if let Some(component) = components.get(entity) { Some((component.clone(), entity)) } else { let parent_ent: Entity = parents.get(entity)?.entity; get_root_cloned( parents, components, parent_ent, ) } }
identifier_body
mod.rs
fSceneLoaderSystemDesc, input::{InputBundle, StringBindings}, prelude::*, renderer::{ plugins::{RenderPbr3D, RenderSkybox, RenderToWindow}, RenderingBundle, Texture, types::{DefaultBackend, Mesh, MeshData}, }, ui::{RenderUi, UiBundle}, utils::{ application...
<'s, 'a, T, P, C>( parents: &P, components: &'a C, entity: Entity, ) -> Option<(T, Entity)> where T: Component + Clone, P: GenericReadStorage<Component=Parent>, C: GenericReadStorage<Component=T> { if let Some(component) = components.get(entity) { Some((component.clone(), entity)) } else { ...
get_root_cloned
identifier_name
term_evaluation_result.js
M("three_menu_module"), C.CM("select_assembly"), C.CM("tuploader") ], function ($, avalon, layer, html, css, data_center, three_menu_module, select_assembly, tuploader) { var avalon_define = function () { var grade_list = []; var semester_full = []; var u...
cloud.add_audit(form, request_after); } var vm = avalon.define({ $id: "term_evaluation_result", //图片是否展开(注:如果数据是循环出来,不能用这种方式) is_open: false, // 接口中未返回区县信息, 暂时使用用户所在区县 district: "", ...
{ var is_school_user = cloud.is_school_user(); var distict_id = ''; if (is_school_user) { distict_id = cloud.school_user_distict_id().district_id; } var user = cloud.user_user(); form.district_id = disti...
identifier_body
term_evaluation_result.js
M("three_menu_module"), C.CM("select_assembly"), C.CM("tuploader") ], function ($, avalon, layer, html, css, data_center, three_menu_module, select_assembly, tuploader) { var avalon_define = function () { var grade_list = []; var semester_full = []; var u...
//图片是否展开(注:如果数据是循环出来,不能用这种方式) is_open: false, // 接口中未返回区县信息, 暂时使用用户所在区县 district: "", //核查意见 opinion: '', //更正结果 correct:"", // 图片显示相关支持 user_photo: cloud.user_...
var vm = avalon.define({ $id: "term_evaluation_result",
random_line_split
term_evaluation_result.js
M("three_menu_module"), C.CM("select_assembly"), C.CM("tuploader") ], function ($, avalon, layer, html, css, data_center, three_menu_module, select_assembly, tuploader) { var avalon_define = function () { var grade_list = []; var semester_full = []; var u...
(form) { var is_school_user = cloud.is_school_user(); var distict_id = ''; if (is_school_user) { distict_id = cloud.school_user_distict_id().district_id; } var user = cloud.user_user(); form.district_id ...
yy_treat
identifier_name
MatrixFromWeights_py27.py
except ValueError: sy_thresh = _FLOAT_EPS_4 r11, r12, r13, r21, r22, r23, r31, r32, r33 = M.flat sy = math.sqrt(r31 * r31 + r32 * r32) if sy > sy_thresh: x2 = math.acos(r33) z1 = math.atan2(r13, -r23) z3 = math.atan2(r31, r32) else:...
try: sy_thresh = np.finfo(M.dtype).eps * 4
random_line_split
MatrixFromWeights_py27.py
cosz3 = math.cos(z3) sinz3 = math.sin(z3) Z3 = np.array( [[cosz3, -sinz3, 0], [sinz3, cosz3, 0], [0, 0, 1]]) return reduce(np.dot, [Z1, X2, Z3]) def _mat2euler(self, M): M = np.asarray(M) try: sy_thresh = np.finfo(M....
""" * Rotation : provides a representation for 3D space rotations * using euler angles (ZX'Z'' convention) or rotation matrices """ def _euler2mat_z1x2z3(self, z1=0, x2=0, z3=0): cosz1 = math.cos(z1) sinz1 = math.sin(z1) Z1 = np.array( [[cosz1, -sinz1, 0], ...
identifier_body
MatrixFromWeights_py27.py
0 z3 = 0 z1 = math.atan2(r21, r22) return (z1, x2, z3) def _init_from_angles(self, z1, x2, z3): self._z1, self._x2, self._z3 = z1, x2, z3 self._M = self._euler2mat_z1x2z3(self._z1, self._x2, self._z3) def _init_from_matrix(self, matrix): self._M = np.as...
elif arg1.size == 3: self._init_from_angles(arg1[0], arg1[1], arg1[2]) else: self._init_from_matrix(arg1) def matrix(self, new_matrix=None): if new_matrix is not None: self._init_from_matrix(new_matrix) return self._M def euler_angles(self, ...
self._init_from_angles(arg1, x2, z3)
conditional_block
MatrixFromWeights_py27.py
: """ * Rotation : provides a representation for 3D space rotations * using euler angles (ZX'Z'' convention) or rotation matrices """ def _euler2mat_z1x2z3(self, z1=0, x2=0, z3=0): cosz1 = math.cos(z1) sinz1 = math.sin(z1) Z1 = np.array( [[cosz1, -sinz1, 0], ...
Rotation
identifier_name
__init__.py
= long except NameError : expected_type = int if type(value) == expected_type: if value > sys.maxsize: raise RosParamException("Overflow: Parameter Server integers must be 32-bit signed integers:\n\t-%s <= value <= %s"%(maxint - 1, maxint)) ...
""" Process command line for rosparam delete, e.g.:: rosparam delete param :param cmd: command name, ``str`` :param argv: command-line args, ``str`` """ parser = OptionParser(usage="usage: %prog delete [options] parameter", prog=NAME) parser.add_option("-v", dest="verbose", default=False...
identifier_body
__init__.py
(node) exprvalue = value if exprvalue.startswith("deg("): exprvalue = exprvalue.strip()[4:-1] try: return float(exprvalue) * math.pi / 180.0 except ValueError: raise RosParamException("invalid degree value: %s"%value) # utilities def _get_caller_id(): """ :returns: cal...
else: dump = yaml.dump(v) # #1617 # newer versions of python-yaml append the '...' document end # syntax. as YAML functions fine w/o it, and as it is # confusing to users who are just getting a single scalar, we # strip it if ...
print("%s%s: %s"%(indent, k, v))
conditional_block
__init__.py
(node) exprvalue = value if exprvalue.startswith("deg("): exprvalue = exprvalue.strip()[4:-1] try: return float(exprvalue) * math.pi / 180.0 except ValueError: raise RosParamException("invalid degree value: %s"%value) # utilities def _get_caller_id(): """ :returns: cal...
# #1617 # newer versions of python-yaml append the '...' document end # syntax. as YAML functions fine w/o it, and as it is # confusing to users who are just getting a single scalar, we # strip it if dump.endswith('\n...\n'): dump = dump[:-5] # #3761...
print(val) else: dump = yaml.dump(val)
random_line_split
__init__.py
(node) exprvalue = value if exprvalue.startswith("deg("): exprvalue = exprvalue.strip()[4:-1] try: return float(exprvalue) * math.pi / 180.0 except ValueError: raise RosParamException("invalid degree value: %s"%value) # utilities def _get_caller_id(): """ :returns: cal...
(params, ns): """ Print contents of param dictionary to screen """ if type(params) == dict: for k, v in params.items(): if type(v) == dict: print_params(v, ns_join(ns, k)) else: print("%s=%s"%(ns_join(ns, k), v)) else: print(par...
print_params
identifier_name
methods.py
ios.index) + 1 ) df[numcols] = df[numcols] * ratios return df def budget(df, df_hist, harmonize_year="2015"): r""" Calculate budget harmonized trajectory. Parameters ---------- df : pd.DataFrame model data df_hist : pd.DataFrame historic data harmonize...
kwargs["ratio_method"] = "reduce_ratio_2080"
conditional_block
methods.py
, offset, final_year="2050", harmonize_year="2015"): """ Calculate linearly interpolated convergence harmonized trajectory. Parameters ---------- df : pd.DataFrame model data offset : pd.DataFrame offset data final_year : string, optional column name of convergence y...
yi, yf = int(harmonize_year), int(final_year) numcols = utils.numcols(df) numcols_int = [int(v) for v in numcols] # get factors that reduce from 1 to 0; factors before base year are > 1 f = lambda year: -(year - yi) / float(yf - yi) + 1 factors = [f(year) if year <= yf else 0.0 for year in numco...
""" Calculate offset convergence harmonized trajectory. Parameters ---------- df : pd.DataFrame model data offset : pd.DataFrame offset data final_year : string, optional column name of convergence year harmonize_year : string, optional column name of harmoni...
identifier_body
methods.py
offset, final_year="2050", harmonize_year="2015"): """ Calculate linearly interpolated convergence harmonized trajectory. Parameters ---------- df : pd.DataFrame model data offset : pd.DataFrame offset data final_year : string, optional column name of convergence ye...
(df, df_hist, harmonize_year="2015"): r""" Calculate budget harmonized trajectory. Parameters ---------- df : pd.DataFrame model data df_hist : pd.DataFrame historic data harmonize_year : string, optional column name of harmonization year Returns ------- ...
budget
identifier_name
methods.py
, offset, final_year="2050", harmonize_year="2015"): """ Calculate linearly interpolated convergence harmonized trajectory. Parameters ---------- df : pd.DataFrame model data offset : pd.DataFrame offset data final_year : string, optional column name of convergence y...
df[numcols] = df[numcols] * ratios return df def budget(df, df_hist, harmonize_year="2015"): r""" Calculate budget harmonized trajectory. Parameters ---------- df : pd.DataFrame model data df_hist : pd.DataFrame historic data harmonize_year : string, optional ...
pd.DataFrame(np.outer(ratios - 1, factors), columns=numcols, index=ratios.index) + 1 )
random_line_split
hw.py
try: with open(out_filename, 'w', encoding=encoding_table) as f: json.dump(out_dict, f, ensure_ascii=False) print(f"файл {out_filename} создался успешно!") except: print("Ошибка при записи выходного файла JSON") def get_most_common_object(dict_): max_ = 0 for key...
d = wine._asdict() dict_ = dict(d) return dict_ def out_file(out_dict, out_filename, encoding_table):
random_line_split
hw.py
in dict_.items(): if value > max_: max_ = value most_common_object = key return most_common_object def main(): if os.path.exists(FILE_NAME1): # Читаем JSON из файла и преобразуем к типу Python with open(FILE_NAME1, 'r', encoding='UTF-8') as f: read_d...
pen(out_filename, 'w', encoding=encoding_table) as f: json.dump(out_dict, f, ensure_ascii=False) print(f"файл {out_filename} создался успешно!") except: print("Ошибка при записи выходного файла JSON") def get_most_common_object(dict_): max_ = 0 for key,value
identifier_body
hw.py
ла и преобразуем к типу Python with open(FILE_NAME1, 'r', encoding='UTF-8') as f: read_data_1 = json.load(f) else: print(f"{FILE_NAME1} File not found!") if os.path.exists(FILE_NAME2): # Читаем JSON из файла и преобразуем к типу Python with open(FILE_NAME2, 'r', encod...
фай
identifier_name
hw.py
: read_data_2 = json.load(f) else: print(f"{FILE_NAME2} File not found!") if MODE == 'set_and_namedtuple': #--убираем дубликаты моим методом dict_wines = read_data_1 + read_data_2 wines = [] wines = [from_dict_to_namedtuple(dict_wine) for dict_wine in dict_wines] ...
e') #вместо немецких вставить общепринятые символы sort_wine[variety] = {"average_price":0, "min_price":0, "max_price":0, "most_common_country":0, "most_common_region":0, "average_score":0} sort_wine[variety]["average_price"] = str(average_price) sort_wine[variety]["min_price"] = str(min_price)...
iety #.replace('â','ae').replace('ü','u
conditional_block
brain-gan-parameter-search.py
build_generator_model(self, noise_shape): model = Sequential() # This block of code can be a little daunting, but essentially it automatically calculates the required starting # array size that will be correctly upscaled to our desired image size. # # We have 5 Upsample2D layer...
return(img_array) def train(self, epochs, image_path, batch_size=32, save_interval=50): self.build_gan() X_train = self.load_imgs(image_path) print("Training Data Shape: ", X_train.shape) # Rescale images from -1 to 1 X_train = (X_train.astype(np.float32) - 127.5)...
img_array = np.uint8(255*img_array)
conditional_block
brain-gan-parameter-search.py
# array size that will be correctly upscaled to our desired image size. # # We have 5 Upsample2D layers which each double the images width and height, so we can determine the starting # x size by taking (x / 2^upsample_count) So for our target image size, 256x192, we do the following: ...
def __init__(self, discriminator_path, generator_path, output_directory, img_size, dropout, bn_momentum, adam_lr, adam_beta): self.img_size = img_size self.upsample_layers = 5 self.starting_filters = 64 self.kernel_size = 3 self.channels = 1 self.discriminator_path = disc...
identifier_body
brain-gan-parameter-search.py
(self, discriminator_path, generator_path, output_directory, img_size, dropout, bn_momentum, adam_lr, adam_beta): self.img_size = img_size self.upsample_layers = 5 self.starting_filters = 64 self.kernel_size = 3 self.channels = 1 self.discriminator_path = discriminator_pa...
__init__
identifier_name
brain-gan-parameter-search.py
build_generator_model(self, noise_shape): model = Sequential() # This block of code can be a little daunting, but essentially it automatically calculates the required starting # array size that will be correctly upscaled to our desired image size. # # We have 5 Upsample2D layer...
# Print progress prog_bar.set_description(("D loss: " + format(d_loss[0], "^-06.3f") + " | D Accuracy: " + format(d_loss[1], "^-06.3f") +" | G loss: " + format(g_loss,
# Train the discriminator (real classified as ones and generated as zeros) d_loss_real = self.discriminator.train_on_batch(imgs, np.ones((half_batch, 1))) d_loss_fake = self.discriminator.train_on_batch(gen_imgs, np.zeros((half_batch, 1))) d_loss = 0.5 * np.add(d_loss_rea...
random_line_split
revaultd.rs
pub cancel_tx: Option<CancelTransaction>, pub unvault_emergency_tx: Option<UnvaultEmergencyTransaction>, } #[derive(Debug, PartialEq, Copy, Clone)] pub struct BlockchainTip { pub height: u32, pub hash: BlockHash, } /// Our global state pub struct RevaultD { // Bitcoind stuff /// Everything we nee...
deposit_address
identifier_name
revaultd.rs
ing), "canceled" => Ok(Self::Canceled), "emergencyvaulting" => Ok(Self::EmergencyVaulting), "emergencyvaulted" => Ok(Self::EmergencyVaulted), "unvaultemergencyvaulting" => Ok(Self::UnvaultEmergencyVaulting), "unvaultemergencyvaulted" => Ok(Self::UnvaultEmergen...
random_line_split
revaultd.rs
communication keys are (for now) hot, so we just create it ourselves on first run. fn read_or_create_noise_key(secret_file: PathBuf) -> Result<NoisePrivKey, KeyError> { let mut noise_secret = NoisePrivKey([0; 32]); if !secret_file.as_path().exists() { log::info!( "No Noise private key at '...
{ let data_dir_str = self .data_dir .to_str() .expect("Impossible: the datadir path is valid unicode"); [data_dir_str, file_name].iter().collect() }
identifier_body
matgen.go
right hand side alternately zero and small. switch uplo { case blas.Upper: b[0] = 0 for i := n - 1; i > 0; i -= 2 { b[i] = 0 b[i-1] = smlnum } case blas.Lower: for i := 0; i < n-1; i += 2 { b[i] = 0 b[i+1] = smlnum } b[n-1] = 0 } case 15: // Make the diagonal elements small...
rthogonal(n int,
identifier_name
matgen.go
] = 1 } } } // Set the right hand side alternately zero and small. switch uplo { case blas.Upper: b[0] = 0 for i := n - 1; i > 0; i -= 2 { b[i] = 0 b[i-1] = smlnum } case blas.Lower: for i := 0; i < n-1; i += 2 { b[i] = 0 b[i+1] = smlnum } b[n-1] = 0 } case 15: //...
nic("testlapack: insufficient matrix slice length") } } //
conditional_block