input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
1]
combs = combinations(hydrogen, 2)
for comb in combs:
if (comb[0], comb[1], 1) in bond_can_form:
bond_can_form.remove((comb[0], comb[1], 1))
# Remove the C-O triple bond
elif (self.atoms[bonds[0]] == 6 and self.atoms[bonds[1]] == 8) or (self.atoms[bonds[1]] == 8 and self.atoms[bonds[0]] == 6):
if bonds[2] == ... | |
mean_val, sumsqf_val)
# WIRE_ORDER_CUR_VAL_IDX, WIRE_ORDER_MEAN_VAL_IDX, WIRE_ORDER_SUMSQF_VAL_IDX
assert len(pt) == (WIRE_ORDER_SUMSQF_VAL_IDX+1)
points.append( pt )
return points
def _service_ros(self, framenumber, hw_roi_frame, chainbuf):
now = time.time()
if (now - self.pub_rate_lasttime) > 2.0:
self.pub_... | |
<reponame>FabrizioCoder/Pyot
from typing import Dict, List, Mapping, Any, Set, Type, Union, get_type_hints
import inspect
import re
from pyot.conf.pipeline import pipelines
from pyot.pipeline.core import Pipeline
from pyot.pipeline.token import PipelineToken
from pyot.utils.copy import fast_copy
from .functional impo... | |
# -*- coding: ISO-8859-15 -*-
# =============================================================================
# Copyright (c) 2018 <NAME>
#
# Authors : <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
#
# Contact email: <EMAIL>
# =============================================================================
"""
Abstract
--------
Th... | |
attr),
colorize(Color.CODE, name)
))
variables[name] = var
# is it an array of floating point numbers?
elif (match_obj := re.fullmatch(float_array_pattern, line)) is not None:
name = match_obj[4]
if name in variables:
error(f'Variable called {colorize(Color.CODE, name)} has already been declared.')
exit_fai... | |
else:
self.converter.generate_throw_expression(
self.builder.load(exception_slot)
)
else:
assert isinstance(controlFlowSwitch, llvmlite.ir.Value)
isReturn = self.builder.icmp_signed(">=", controlFlowSwitch, llvmI64(0))
with self.builder.if_else(isReturn) as (then, otherwise):
with then:
if return_slot is Non... | |
# Copyright (c) 2020 Blackwing Intelligence
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publi... | |
the
:py:meth:`~PIL.Image.Image.draft` method to configure the file reader
(where applicable), and finally resizes the image.
Note that this function modifies the :py:class:`~PIL.Image.Image`
object in place. If you need to use the full resolution image as well,
apply this method to a :py:meth:`~PIL.Image.Im... | |
<gh_stars>0
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import re
import warnings
import requests
from verta.tracking._organization import Organization
from ._internal_utils._utils import check_unnecessary_params_warning
from ._protos.public.modeldb import CommonService_pb2 as _CommonSer... | |
about.
:param id: The id of the round to retrieve."""
tournament_id = str(tournament_id)
id = str(id)
method = 'GET'
path = '/tournaments/{tournament_id}/rounds/{id}'
path_mapping = {
'tournament_id': tournament_id,
'id': id,
}
query_parameters = {
}
headers = {
}
content = self._simple_access(meth... | |
1) % len(self.allowed_freqs)
scan_freq = list(sorted(self.allowed_freqs))[self.scan_idx]
self.Log('scanning %d MHz (%d/%d)', scan_freq, self.scan_idx + 1,
len(self.allowed_freqs))
RunProc(callback=self._ScanResults,
args=['wifi', 'scan', '-b', BandForFreq(scan_freq),
'--scan-freq', str(scan_freq), '--scan-ap-forc... | |
<gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 4/20/21-14:03
# @Author : TuringEmmy
# @Email : <EMAIL>
# @WeChat : superior_god
# @File : model.py
# @Project : 00PythonProjects
import os
import timeit
import numpy as np
import pandas as pd
import tensorflow as tf
from sklearn.model_selection impo... | |
# -*- coding:utf-8 -*-
__author__ = "<NAME>"
import re
import sys
import time
import pandas
import xlrd
import xlwt
from PySide2 import QtCore, QtWidgets
from xlutils.copy import copy
from pyautogui import alert
class MyWidget(QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.St... | |
#!/usr/bin/python2
from __future__ import absolute_import, division, print_function
import gui_elements as gui
import thread
import wx
import evora.common.utils.fits as fits_utils
import evora.common.utils.logs as log_utils
class ScriptStatus(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)... | |
<gh_stars>1-10
import pytest
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.common.excepti... | |
and r.status_code != 206) \
or (not ('method' in pars and pars['method'] == 'download') \
and url.find('method=download') == -1 \
and url.find('baidupcs.com/file/') == -1):
self.__print_error_json(r)
perr("Website returned: {}".format(rb(r.text)))
# child class override this to to cust... | |
<reponame>AaronFriel/pulumi-google-native
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Unio... | |
import json, hashlib, datetime, uuid, time
import logging
from ckan.logic import side_effect_free
import ckan.logic.schema as schema
from ckan.logic.action import get as core_get
import ckan.model as model
import ckan.plugins as p
from ckanext.geodatagov.plugins import change_resource_details, split_tags
from ckanext.... | |
please pass async_req=True
>>> thread = api.address_geocode_with_http_info(input, async_req=True)
>>> result = thread.get()
:param async_req bool
:param ValidateAddressRequest input: Input parse request (required)
:return: ValidateAddressResponse
If the method is called asynchronously,
returns the request threa... | |
return 1;
}
self_sKeys.sort();
other_sKeys.sort();
var c, sKey;
for (var idx = 0; idx < selfLen; idx++) {
c = @{{cmp}}(selfObj[sKey = self_sKeys[idx]][0], otherObj[other_sKeys[idx]][0]);
if (c != 0) {
return c;
}
c = @{{cmp}}(selfObj[sKey][1], otherObj[sKey][1]);
if (c != 0) {
return c;
}
}
return 0;""")... | |
"""
Ibutsu API
A system to store and query test results # noqa: E501
The version of the OpenAPI document: 1.13.4
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from ibutsu_client.api_client import ApiClient, Endpoint as _Endpoint
from ibutsu_client.model_utils i... | |
by default None.
This is often the output for this spaxel's :func:`marginal_fits`.
Same spatial shape as `fitList` (nxm)
final_choices : array of int, optional
The fits chosen by the user, if any, by default None.
Same spatial shape as `fitList` (nxm)
onlyChecked : bool, optional
Whether to save only the fits fl... | |
<filename>sdk/python/pulumi_alicloud/quotas/quota_alarm.py<gh_stars>10-100
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typ... | |
"ip6_peer",
"ip6_gw_addr", "ip6_gw_if", "ip6_gw_default",
"dns_server", "dhcp_server",
"wireless",
"numa_node", "local_cpulist", "local_cpu",
"enable", "current_link_speed", "current_link_width",
"driver", "bus_info",
"bus_info", "wireless_protocol",
"duplex", "carrier",
"operstate", "type",
"mtu", "tx_q... | |
<filename>malchive/utilities/vtinspect.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright(c) 2021 The MITRE Corporation. All rights reserved.
#
# 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 ... | |
"""Set new teletext page to retrieve.
@param i_page: teletex page number requested
"""
e=VLCException()
return libvlc_video_set_teletext(self, i_page, e)
if hasattr(dll, 'libvlc_video_get_track_count'):
def video_get_track_count(self):
"""Get number of available video tracks.
@return: the number of available vid... | |
#!/usr/bin/env python3
#
# Copyright 2021 GoPro Inc.
#
# 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 ... | |
raise
else:
logger.debug("Got following CR IDs: " + json.dumps(cr_id_list))
# Add Consent Record IDs to record_container
for cr_id in cr_id_list:
logger.debug("Looping through cr_id_list: " + json.dumps(cr_id_list))
try:
logger.info("Adding CR IDs")
record_id_container[slr_id]["consentRecords"][cr_id] = {"cons... | |
= config_positive_int_value(
conf.get('per_container_ratelimit_buckets', 1000))
self.node_timeout = float(conf.get('node_timeout', 10))
self.conn_timeout = float(conf.get('conn_timeout', 0.5))
self.report_interval = float(conf.get('report_interval', 300))
self.recon_cache_path = conf.get('recon_cache_path',
DEFAU... | |
interpretation
dswx_ctable = _get_interpreted_dswx_ctable()
gdal_band.SetRasterColorTable(dswx_ctable)
gdal_band.SetRasterColorInterpretation(
gdal.GCI_PaletteIndex)
if description is not None:
gdal_band.SetDescription(description)
else:
gdal_band.SetDescription(description_from_dict)
gdal_band.FlushCache()
g... | |
"""
Copyright 2019 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
dist... | |
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
#... | |
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
# @formatter:off
#
# ,,
# db
# \
# _\,, `7MM `7MM `7MMpMMMb. `7MM ,p6"bo ,pW"Wq.`7Mb,od8 `7MMpMMMb.
# "-=\~ _ MM MM MM MM MM 6M' OO 6W' `Wb MM' "' MM MM
# \\~___( ~ MM MM MM MM MM 8M 8M M8 MM MM MM
# _|/---\\_ MM MM MM MM MM 8M 8M M8 MM MM MM
# \ \ MM MM MM MM MM YM. , Y... | |
feature.parent):
if feature.path:
path = feature.path
else:
path = GIS.update_location_tree(feature)
if path:
path_list = [int(item) for item in path.split("/")]
if len(path_list) == 1:
# No parents - path contains only this feature.
return None
# Get only ancestors
path_list = path_list[:-1]
# Get path in... | |
: self.train_acc,
'TestLoss' : self.test_loss,
'TestAcc' : self.test_acc}
# %%
gru = GRU(hidden_dim=128,learning_rate=1e-3,batch_size=32,mom_coeff=0.0)
# %%
gru.fit(X_train,y_train,X_test,y_test,epochs = 15,optimizer = 'RMSprop')
# %%
gru_history = gru.history()
# %%
# For figure 97:
plt.figure()
... | |
<filename>utils/thredds.py<gh_stars>0
from __future__ import print_function, absolute_import
from future.standard_library import hooks
import os
import copy
from shutil import rmtree
from tempfile import mkdtemp
from datetime import datetime
from numpy import empty, float32, datetime64, timedelta64, argmin, abs, arra... | |
<= 0)
m.c1309 = Constraint(expr= - m.b130 + m.b131 - m.b155 <= 0)
m.c1310 = Constraint(expr= - m.b130 + m.b132 - m.b156 <= 0)
m.c1311 = Constraint(expr= - m.b130 + m.b133 - m.b157 <= 0)
m.c1312 = Constraint(expr= - m.b130 + m.b134 - m.b158 <= 0)
m.c1313 = Constraint(expr= - m.b130 + m.b135 - m.b159 <= 0)
m.c1314 ... | |
<filename>flarestack/cluster/submitter.py<gh_stars>0
import os, subprocess, time, logging, shutil, copy
import numpy as np
from flarestack.shared import (
fs_dir,
log_dir,
fs_scratch_dir,
make_analysis_pickle,
host_server,
inj_dir_name,
name_pickle_output_dir,
cluster_dir,
)
from flarestack.core.multiprocess_wr... | |
1 else boardUnits), inline=False)
externalUser = True
if first: first = False
else:
leaderboardEmbed.add_field(value=str(place + 1) + ". " + message.guild.get_member(sortedUsers[place][0]).mention, name=("⭐ " if first else "") + str(sortedUsers[place][1]) + " " + (boardUnit if sortedUsers[place][1] == 1 else boardU... | |
Device(name='asr1k')
dev_c3850 = Device(name='c3850')
empty_output = {'execute.return_value': ''}
semi_empty_output = {'execute.return_value': '''\
Directory of flash:/
'''}
golden_parsed_output_c3850 = {
'dir': {
'dir': 'flash:/',
'flash:/': {
'files': {
'bootloader_evt_handle.log': {
'index': '30530',
'pe... | |
# Copyright (c) 2020 Intel Corporation. All Rights Reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, mod... | |
'found %d parents' % len(parents_ids))
return '', nx.node_link_data(tg)
def GetSynonymTermId(con, cur, synonym):
"""
Get the term id for which the synonym is
input:
con,cur
synonym : str
the synonym to search for
output:
err : str
Error message or empty string if ok
termid : int
the id of the term for t... | |
"""The script used to train the model."""
import os
import sys
import getopt
import numpy as np
import models as m
from tqdm import tqdm
from keras.optimizers import Adam
from util.data import TwoImageIterator
from util.util import MyDict, log, save_weights, load_weights, load_losses, create_expt_dir
def print_help... | |
}\n]\n }\n }\n}\n' %query_string
else:
data = '\n{\n "query": {\n "bool": {\n "must" : [\n { "term" : { "type" : "pde" } },\n { "multi_match" : {\n "query": "%s", \n "fields": [ "label", "definition" ] \n } }\n]\n }\n }\n}\n' %query_string
elif type == 'fde':
if anscestors:
data = '\n{\n "query": {\n "bool": {\n "... | |
to
(x - 2*z : y : z))
The diagonalization is only defined in characteristic different
from 2:
::
sage: Conic(GF(2), [1,1,1,1,1,0]).diagonalization()
Traceback (most recent call last):
...
ValueError: The conic self (= Projective Conic Curve over Finite Field of size 2 defined by x^2 + x*y + y^2 + x*z + y*z) ... | |
effective time of this record.
:type OoStartTime: Array of DateTime
| ``api version min:`` 2.6
| ``api version max:`` None
| ``required:`` False
| ``default:`` None
:param OoTimestamp: The date and time this record was collected or calculated.
:type OoTimestamp: Array of DateTime
| ``api version min:`` 2.6
... | |
#!/usr/bin/env python
#
# test_ldp_isis_topo1.py
# Part of NetDEF Topology Tests
#
# Copyright (c) 2020 by <NAME>
#
# Permission to use, copy, modify, and/or distribute this software
# for any purpose with or without fee is hereby granted, provided
# that the above copyright notice and this permission notice appear
# ... | |
], # 0x60 grave
[ 283, 8, 4, 4, 0, -4 ], # 0x61 a
[ 287, 8, 5, 4, 0, -5 ], # 0x62 b
[ 292, 8, 4, 4, 0, -4 ], # 0x63 c
[ 296, 8, 5, 4, 0, -5 ], # 0x64 d
[ 301, 8, 4, 4, 0, -4 ], # 0x65 e
[ 305, 8, 5, 4, 0, -5 ], # 0x66 f
[ 310, 8, 5, 4, 0, -4 ], # 0x67 g
[ 315, 8, 5, 4, 0, -5 ], # 0x68 h
[ 320, 8, 5, 2, 0, -5 ]... | |
#! /usr/bin/env python
##############################################################################
## DendroPy Phylogenetic Computing Library.
##
## Copyright 2010-2015 <NAME> and <NAME>.
## All rights reserved.
##
## See "LICENSE.rst" for terms and conditions of usage.
##
## If you use this work or any portion the... | |
To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_product_images_with_http_info(product_id, callback=callback_function)
:param callback function: The callback fun... | |
timestart))
# duration = datetime.time(0, 0, int(time.time() - timestart)).strftime("%H:%M:%S")
self.logger.info("Run completed. Duration: %s" % str(duration))
# Clear logging handlers.
self.logger.removeHandler(fh)
if ch is not None:
self.logger.removeHandler(ch)
@abstractmethod
def _run(self, progress_bar: ... | |
<reponame>binqsoft/CxPy
# coding=utf-8
# Python Dependencies
import base64
import re
import time
import logging
import os
from common import Common
from CxType.cli_scan_args import CliScanArgs
dir_path = os.path.dirname(os.path.realpath(__file__))
logging.basicConfig(filename=dir_path + '/checkmarx_soap_api.log',
f... | |
<reponame>hanwenzhu/ck
#
# Collective Knowledge (program)
#
# See CK LICENSE.txt for licensing details
# See CK COPYRIGHT.txt for copyright details
#
# Developer: <NAME>, <EMAIL>, http://fursin.net
#
cfg={} # Will be updated by CK (meta description of this module)
work={} # Will be updated by CK (temporal data)
ck=Non... | |
<filename>rl/util.py
import argparse
import collections
import inspect
import json
import logging
import multiprocessing as mp
import numpy as np
import re
import sys
import zipfile
from datetime import datetime, timedelta
from os import path, listdir, environ, getpid
from textwrap import wrap
PARALLEL_PROCESS_NUM = m... | |
import torch
import torch._prims as prims
import torch._prims.utils as utils
from torch._prims.utils import (
DimsType,
TensorLike,
TensorLikeType,
DimsSequenceType,
TensorSequenceType,
Number,
NumberType,
ELEMENTWISE_TYPE_PROMOTION_KIND,
elementwise_dtypes,
)
from torch._prims.wrappers import (
elementwise_... | |
<reponame>biergaiqiao/Oriole-Thwarting-Privacy-against-Trustworthy-Deep-Learning-Models
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 5 11:11:19 2020
@author: 一叶之秋
"""
import argparse
import glob
import logging
import os
import sys
import tensorflow as tf
logging.getLogger('tensorflow').disabled = Tru... | |
from __future__ import absolute_import, division, print_function
from builtins import range
import atexit
import glob
import hashlib
import math
import os
import re
import shutil
import sys
import time
import traceback
import warnings
from libtbx.queuing_system_utils import pbs_utils, sge_utils
from libtbx.math_util... | |
#!/usr/bin/env python
# coding: utf-8
# ***
# ### **I hope you find this kernel useful and your <font color="red"><b>UPVOTES</b></font> would be highly appreciated**
# ***
# # Decision Tree & Random Forest
#
# # 1. Decision Tree
#
# 
#
# Decision Trees are an important type of ... | |
tree produced by CSharp4Parser#struct_interfaces.
def exitStruct_interfaces(self, ctx):
pass
# Enter a parse tree produced by CSharp4Parser#struct_body.
def enterStruct_body(self, ctx):
pass
# Exit a parse tree produced by CSharp4Parser#struct_body.
def exitStruct_body(self, ctx):
pass
# Enter a parse tre... | |
<filename>swagger_client/apis/apps_api.py
# coding: utf-8
"""
fn
The open source serverless platform.
OpenAPI spec version: 0.2.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import sys
import os
import re
# python 2 and python 3 compatibility ... | |
<reponame>inmanta/inmanta-core
"""
Copyright 2017 Inmanta
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 agre... | |
are such a DOJI, STRAHD flew up...")
sleep(2)
print("Now, you have a huge disavantage")
sleep(2)
else:
print("...")
sleep(1)
print("......")
sleep(2)
print("...........")
sleep(2)
print("I told you to be careful!")
sleep(2)
print(f"...{player_name} you are such a KLUTZ, STRAHD flew...")
slee... | |
== 'normal':
std = math.sqrt(scale / fan)
self.weight.data.normal_(0, std)
elif distribution == 'uniform':
limit = math.sqrt(3 * scale / fan)
self.weight.data.uniform_(-limit, limit)
else:
raise ValueError('unknown distribution')
if self.bias is not None:
self.bias.data.fill_(0)
def set_parameters(self, wei... | |
import logging
from typing import List, Dict, Union, Tuple, Callable
from collections import defaultdict
from pathlib import Path
import torch
from torch import nn
from torch.utils.data import TensorDataset, DataLoader
import datasets
from datasets import ClassLabel
from sklearn.metrics import accuracy_score, precisio... | |
7: IiII - oO0o
if ( ooo0oo == oO00Oooo0o0o0 . registered_rlocs ) :
IIiiiIiii = ( oO00Oooo0o0o0 . group . is_null ( ) == False )
I1III = lisp_get_partial_rloc_set ( ooo0oo , I11oo , IIiiiIiii )
if ( I1III != ooo0oo ) :
oo0o = 15
ooo0oo = I1III
if 22 - 22: o0oOOo0O0Ooo * I1Ii111 * I1ii11iIi11i . OoOoOO00 . i1IIi %... | |
<filename>pyglet/gl/glxext_arb.py
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 <NAME>
# Copyright (c) 2008-2019 pyglet contributors
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permi... | |
"https://bitcointalk.org/index.php?topic=2175951.0",
"github": "https://github.com/SmartBillions/SmartBillions",
"gitter": "",
"instagram": "",
"linkedin": "",
"reddit": "https://www.reddit.com/r/SmartBillions",
"slack": "https://smartbillions.slack.com",
"telegram": "https://t.me/SmartBillionsGroup",
"twitter"... | |
len(netx)
if dead:
result[dead] = counts[1] / len(netx)
return result
def _cyclomatic(graph):
"""
Calculates the cyclomatic complexity of a graph.
"""
e = graph.number_of_edges()
v = graph.number_of_nodes()
return e - v + 1
def cyclomatic(graph, radius=5, name="cyclomatic", distance=None, verbose=True):
... | |
# Standard Library
import asyncio
import logging
import os
import pandas as pd
# Third Party
from elasticsearch import AsyncElasticsearch
from kubernetes import client, config
from PeakDetecion import PeakDetection
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(message)s")
config.load_in... | |
self.action_space.low[0]), self.action_space.high[0])])
def _cascaded_PI_controller(self, state, ref, k):
"""
cascaded controller with two PI controllers for inner current and outer speed control for DC motors
Args:
:param state: [omega, i_a, i_e] # use [omega, i, i] for series
:param ref: reference
:param k: c... | |
'**attrs'. If 'is_replace_attrs_values' then replace attributes values,
if not 'is_replace_attrs_values' then update (merge) attributes values
witch should be lists. If 'is_allow_none_values' then allow to set None
object's attributes values, and vice versa.
If 'is_replace_values_of_dicts' then update values of dic... | |
<filename>kato.py
import sys
import base64
import os
import json
from math import ceil
import random
from urllib import quote
from twisted.internet import reactor, defer, protocol
from twisted.internet.error import ConnectionDone
from twisted.internet.protocol import ReconnectingClientFactory
from twisted.python impor... | |
the file does not exist in the cache.
This cache affects strong consistency file existence check as file delete event does not reflect on the client till the cache expires.
This method bypasses SMB2 directory cache by making a call to the SAMBA server to check existence of a file.
:param path: file path
:param vTyp... | |
# 元データと低次元表現それぞれに対し精度を計算する
# X:特徴行列, L: ラベル
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.cluster import KMeans
from munkres import Munkres
import csv
from numpy import savetx... | |
the first dimension (samples).
"""
if mask is None:
mask = jnp.ones([logits.shape[0]])
mask = mask.reshape([logits.shape[0]])
error_rate = (((jnp.argmax(logits, -1) != jnp.argmax(one_hot_labels, -1))) *
mask).sum() / mask.sum()
# Set to zero if there is no non-masked samples.
return jnp.nan_to_num(error_rate)
... | |
<reponame>luca-riboldi/HES-OFF
## ------------------------------------------------------------------------------------------------------------------ ##
## ------------------------------------------------------------------------------------------------------------------ ##
## ___ ___ ________ ________ ______ ________ __... | |
startMatches = []
else:
hasStarted = False
if endMatches is None:
endMatches = []
for pair in self.getFramePairs(contentOnly):
token = pair[0]
if not hasStarted: # Before noise sequence
# Look for start of search space
if multiMatch(token, startMatches):
hasStarted = True
continue
else: # Part of noise se... | |
import custom_paths
import utils
import numpy as np
from typing import *
from pathlib import Path
import os
class ExperimentResults:
def __init__(self, results_dict: dict, exp_name: str):
# usually, results_dict[alg_name][task_name][split_idx] = something
self.results_dict = results_dict
self.exp_name = exp_name
... | |
'0004' '0D' '0004' '10' '16',
new_code = ('..' '....' '..' '..' '........' '..' '........'
+ NOP * 10 ),
),
Obj_Patch(
#offsets = [0x0001BAF8],
# Slightly different version of above.
ref_code = '0D' '0011' '02' '82' '........' '34' '........'
# Replace this chunk.
'01' '0D' '0012' '85' '........' '24'
'06' '1... | |
0, 11)
else:
assert False
def test_analyse_sig_not_strict_with_on_error_handler_fail_slow(self):
def f_a(name, index, value):
self._f_a(name, index, value)
print('f_a: name: {0}, index:{1}, value: {2}'.format(name, index, value))
raise _Error('a')
def f_c(name, index, value):
self._f_c(name, index, value)
p... | |
'''
GUI utilities.
'''
from __future__ import with_statement
from __future__ import division
import config
import functools
import wx, struct
from wx import GetTopLevelWindows, Point, Size
from logging import getLogger; log = getLogger('gui.util')
from traceback import print_exc
from PIL import Image, ImageDraw, ImageF... | |
<filename>sfeprapy/mcs1/mcs1_func_gen.py
# -*- coding: utf-8 -*-
import numpy as np
from pandas import DataFrame as df
from scipy import stats
from scipy.interpolate import interp1d
def lognorm_parameters_true_to_inv(miu, sigma):
"""
NAME: lognorm_parameters_true_to_inv
VERSION: 0.0.1
AUTHOR: <NAME>, <NAME>
DESC... | |
if (verbose):
print ("Test #{0} - DeleteName('Test Folder', verbose)".format(count + 1))
result = DeleteName("Test Folder", verbose)
if (result):
if (verbose):
print ("\tpass.")
count += 1
else:
if (verbose):
print ("\tfail.")
fails += 1
testResults = False
if (fails == 0 and count == total_tests):
print (... | |
'''
Contains a generic algorithm object which can do vanilla ICP
Then, create plugin functions which can do naive, simple, and fast PFH
'''
import time
import numpy as np
import matplotlib.pyplot as plt
import scipy.special as sp
from sklearn.metrics.pairwise import euclidean_distances
from . import utils
class PFH... | |
= [0,255,0] #AdG
#out_img[x-1, y+2] = [0,255,0] #AdG
return out_img
#################################################################
def plotMiddleLane(binary, middle_fitx, Minv, img_size, undistorted, ploty):
"""Plotte Mittellinie"""
# create new image to plot middle lane on
warped_middle_zero = np.ze... | |
_get_ctx(self, x):
match x:
case Ident():
obj_name = x.Name
case str():
obj_name = x
case Expr():
return x._type()
case _:
raise ValueError(x)
if obj := self._from_scope_or_outer(obj_name):
return obj._py_context
def _from_scope_or_outer(self, obj_name: str):
return self._from_scope(obj_name) or self._fro... | |
' '.join(args)
if 0 != os.system(cmd):
fail('Command failed: %s' % cmd)
return 0
# def homog(x):
# return np.concatenate([x, [1.]])
# def inhomog(x):
# y = x[:-1]
# y /= x[-1]
# return y
def homog(X):
# assumes X is either a vector or a matrix of n vectors of the shape (d by n)
X = np.asarray(X)
if X.ndim == 1... | |
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 6 12:43:49 2019
@author: bdobson
"""
import constants
import initialise
import options
from tqdm import tqdm
import pandas as pd
from copy import deepcopy
class model:
def __init__(self,addresses):
"""Initialise all state variables and parameters
These are set to es... | |
%s\nERROR: No such polynomial \"poly = %d\", allowed polynomials for n = %d are 0 to %d\n" % (lines[pc], instr, poly, param_n, int(8192/param_n)))
exit()
if bound >= 2**24:
print("\n[Line %4d] %s\nERROR: Parameter \"bound = %d\" too large, must be less than 2**24\n" % (lines[pc], instr, bound))
exit()
# Update reg... | |
import vtk, ctk, qt, slicer
from slicer.ScriptedLoadableModule import (ScriptedLoadableModule,
ScriptedLoadableModuleLogic,
ScriptedLoadableModuleWidget,
ScriptedLoadableModuleTest)
from collections import Counter
import csv
import logging
import os
from slicer.util import VTKObservationMixin
#
# DataImporter
#
cl... | |
Shanxi', 'zh': u('\u5c71\u897f\u7701\u6714\u5dde\u5e02')},
'86157357':{'en': 'Linfen, Shanxi', 'zh': u('\u5c71\u897f\u7701\u4e34\u6c7e\u5e02')},
'861573571':{'en': 'Shuozhou, Shanxi', 'zh': u('\u5c71\u897f\u7701\u6714\u5dde\u5e02')},
'861573572':{'en': 'Shuozhou, Shanxi', 'zh': u('\u5c71\u897f\u7701\u6714\u5dde\u5e0... | |
<reponame>akarakoc/SWE574<filename>mystream/streampage/forms.py
from django.contrib.auth import authenticate, get_user_model
from django import forms
from streampage.models import Primitives, communityUsers, Communities, Datatypes, DatatypeFields, Posts, CommunityTags, \
DatatTypeTags, PostTags, UserTags
from djan... | |
ws.dim_rowmax + 2
value = sum([counts[x] for x in counts if x[0] == 1])
total = sum(counts.values())
self.write_overall_value(ws, value, total, overall_column, overall_row, write_overall=True)
if gen_dataset:
tabulate_dataset("ws_47", ["Topic", "Answer", "Year", "Geography", "Count"], counts, ws_47_dataset)
def ... | |
<filename>nara_wpe/torch_wpe_real_imag.py<gh_stars>1-10
import numpy as np
import torch
import torch_complex.functional
from torch_complex.tensor import ComplexTensor
from nara_wpe.torch_wpe import build_y_tilde as _build_y_tilde
def build_y_tilde(Y, taps, delay):
"""
Note: The returned y_tilde consumes a similar ... | |
p-values - these are adjusted p-values
R('''dat2 <- dat2[, c("rna", "dna", "prna", "pdna")]''')
# take -log10(p-values)
R('''dat2$prna <- -log10(dat2$prna)''')
R('''dat2$pdna <- -log10(dat2$pdna)''')
R('''rownames(dat2) <- genes''')
R('''clust <- Mclust(dat2)''')
R('''classification <- data.frame(clust$classifi... | |
"""
Statistical tools for time series analysis
"""
import numpy as np
from scipy import stats, signal
from statsmodels.regression.linear_model import OLS, yule_walker
from statsmodels.tools.tools import add_constant
from tsatools import lagmat, lagmat2ds, add_trend
#from statsmodels.sandbox.tsa import var
from adfvalu... | |
import json
import os
import subprocess
import h5py
import uuid
from installed_clients.KBaseReportClient import KBaseReport
from installed_clients.DataFileUtilClient import DataFileUtil
from pprint import pprint
from shutil import copy
import subprocess
import matplotlib.pyplot as plt
import numpy as np
import pandas a... | |
setBoolProp
from .morphing import setActivated
final = finalProp(raw)
if raw not in self.drivers.keys():
self.drivers[raw] = []
self.visible[raw] = False
self.primary[raw] = False
if asset:
visible = (asset.visible or GS.useMakeHiddenSliders)
self.visible[raw] = visible
self.primary[raw] = True
if skey and n... | |
)
self.m_gauge_file_in.SetValue( 0 )
bSizer361.Add( self.m_gauge_file_in, 1, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 5 )
sbSizer201.Add( bSizer361, 0, wx.EXPAND, 5 )
bSizer371 = wx.BoxSizer( wx.HORIZONTAL )
self.m_button_folder_in = wx.Button( sbSizer201.GetStaticBox(), wx.ID_ANY, u"加载文件夹", wx.DefaultPosition, w... | |
but be careful when
calling compiled routines outside of wrf-python.
Args:
wrfin (iterable): An iterable type, which includes lists, tuples,
dictionaries, generators, and user-defined classes.
varname (:obj:`str`) : The variable name.
timeidx (:obj:`int` or :data:`wrf.ALL_TIMES`, optional): The
desi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.