content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def load_all_dicts(gs_files: list = None,
GLMDIR: str = None,
norm: typing.Union[str, bool] = 'bySessVoxZ',
roi: str = 'lang_LH_netw'):
"""Return df of rows = sentence, cols = gs single response for ROI of interest"""
# Load, extract the ROI of interest
lst_responses = []
lst_sents = []
lst_... | 67,900 |
def compute_range_table( stepsize = 0.001, maxextent = 10 ):
"""Compute integrals of the unit normal distribution and return these tabulated. Returns:
- range: NumPy array giving integration range (x) where integration range runs -x to +x
- integral: NumPy arrange giving integrals over specified integration range.... | 67,901 |
def phred(q):
"""Convert 0...1 to 0...30
No ":".
No "@".
No "+".
"""
n = int(q * 30 + 33)
if n == 43:
n += 1
if n == 58:
n += 1
return chr(n) | 67,902 |
def lemmatize(word):
"""
Out of all the related word forms of ``word``, return the smallest form that appears first in the dictionary
"""
forms = [word for pos_form in get_word_forms(word).values() for word in pos_form]
forms.sort()
forms.sort(key=len)
try:
return forms[0]
except... | 67,903 |
def test_browse_package_from_registry():
""" Verify loading manifest locally and from s3 """
with patch('t4.Package._from_path') as pkgmock:
registry = BASE_PATH.as_uri()
pkg = Package()
pkgmock.return_value = pkg
pkghash = pkg.top_hash()
# default registry load
... | 67,904 |
def write_k(version, internal, boundaries, location=None, file=None):
""" Write a turbulent kinetic energy (TKE) field file.
See :func:`~dafi.random_field.foam_utilities.write` for more
information.
"""
return write(version, 'k', internal, boundaries, location, file) | 67,905 |
def HLRBRep_BCurveTool_IsRational(*args):
"""
:param C:
:type C: BRepAdaptor_Curve &
:rtype: bool
"""
return _HLRBRep.HLRBRep_BCurveTool_IsRational(*args) | 67,906 |
def has_footer_comments(content):
"""Determine if the FOOTER_COMMENTS are already present.
"""
for comment in FOOTER_COMMENTS:
if content.find(comment) == -1:
return False
return True | 67,907 |
def get_directory_content_ajax(request, region_slug=None):
"""
View provides the frontend with the content of a directory via AJAX.
:param request: The current request
:type request: ~django.http.HttpRequest
:param region_slug: The slug of the current region
:type region_slug: str
:return... | 67,908 |
def int(val: 'Optional[b_int]' = None) -> PythonValue:
"""Returns an Int wrapped into a PythonValue"""
return PythonValue(Int(val)) | 67,909 |
def compare_files_pr(file1, file2):
""" Calculate simple P/R .
Compare lists of cells, left to right , top to bottom.
"""
cells = [[], []]
for i, fname in enumerate([file1, file2]):
with file(fname) as csvfile:
rd = csv.reader(csvfile, delimiter=',', quotechar='"')
... | 67,910 |
def read(filename, flags=0):
"""Read an image to a numpy array of shape (height, width) for
greyscale images, or shape (height, width, nchannels) for RGB or
RGBA images.
The `flags` parameter should be one or more values from the IoFlags
class defined in this module, or-ed together with | as appropr... | 67,911 |
def main():
"""Start point"""
app = QApplication(sys.argv)
window = FileMoverGUI(FileMover())
window.show()
sys.exit(app.exec_()) | 67,912 |
def _call_with_frames_removed(func, *args, **kwds):
"""
remove_importlib_frames in import.c will always remove sequences
of importlib frames that end with a call to this function
Use it instead of a normal call in places where including the importlib
frames introduces unwanted noise into the traceba... | 67,913 |
def generate_pose():
""" generate pose from hemisphere-distributed viewpoints
"""
# y axis(yr): -pi - pi
# x axis(xr): 0 - 0.5pi
# view_direction(ar): -0.1pi - 0.1pi
yr = (random.random()*2.0*np.pi)-np.pi
xr = (random.random()*0.5*np.pi)
ar = (random.random()*0.2*np.pi)-(0.1*np.pi)... | 67,914 |
def test_provide_start_str():
"""Test str provider."""
s = provide_start_str(True, 'active', 'en')
assert 'TEST for task A' in s
s = provide_start_str(False, 'passive', 'de')
assert 'der Aufgabe B' in s | 67,915 |
def _flop_count(idx_contraction, inner, num_terms, size_dictionary):
"""Copied from _flop_count in numpy/core/einsumfunc.py
Computes the number of FLOPS in the contraction.
Parameters
----------
idx_contraction : iterable
The indices involved in the contraction
inner : bool
Doe... | 67,916 |
def workspace(q=1,act=1,bw="string",cr="string",dir="string",en="string",fr="[string, string]",fre="string",frl=1,f=1,fn=1,l=1,lfw=1,lw=1,n=1,ot="[string, string]",ote="string",otl=1,o=1,pp="string",rfr="string",rve="string",rt="[string, string]",rte="string",rtl=1,rd=1,s=1,sn=1,u=1,ua=1,v="[string, string]",ve="string... | 67,917 |
def process_track_data(dataframe_name, concatenated_filepath, concatenated_filename, input_filepath, input_filename, device_id, output_create_files_filepath, output_create_files_filename,
invalid_position_filepath, output_flagging_filepath, output_flagging_filename):
"""Process track data fro... | 67,918 |
def ValidateLineItem(line_item, web_services):
"""Validate LineItem object.
Args:
line_item: dict LineItem object.
web_services: module Web services.
"""
SanityCheck.ValidateTypes(((line_item, dict),))
for key in line_item:
if line_item[key] == 'None': continue
if key in ('creativeSizes',):
... | 67,919 |
def margin_mortality(t):
"""Mortality margin
Mortality margin is defined :func:`coi` net of :func:`claims_over_av`.
The sum of the expense margin and mortality margin add
up to the net cashflow.
.. seealso::
* :func:`coi`
* :func:`claims_over_av`
"""
return coi(t) - clai... | 67,920 |
def test_correct_else_in_for_loop(
assert_errors, parse_ast_tree, code, default_options,
):
"""Violations are not raised when else without break statement."""
tree = parse_ast_tree(code)
visitor = WrongForElseVisitor(default_options, tree=tree)
visitor.run()
assert_errors(visitor, []) | 67,921 |
def getPrintLengthError(printHours: float) -> Optional[str]:
"""Returns a warning message if the print is too long.
:param printHours: Total hours the print will take.
:return: The message to display if the print is too long.
"""
currentLimit, limitEnds = getCurrentTimeLimit()
if currentLimit... | 67,922 |
def errorExit(error):
"""Show error message in messagebox and then exit after user presses OK"""
tkMessageBox.showerror("Error", error)
os._exit(1) | 67,923 |
def insert_combos(lst, vertical_sudoku, blockified_sudoku, row_index):
"""
Tries all combinations of missing elements and inserts to a list and returns it
args:
-lst - list containing missing elements
-vertical_sudoku - List containing lists of columns of the sudoku
(Will be ... | 67,924 |
def main():
"""main function"""
config = {
**dotenv_values('.env'),
**os.environ
}
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=int(config.get('LOG_LEVEL')))
logging.info('Loaded .env variables:\n%s', json.dumps(conf... | 67,925 |
def test_list_non_positive_integer_length_1_nistxml_sv_iv_list_non_positive_integer_length_2_3(mode, save_output, output_format):
"""
Type list/nonPositiveInteger is restricted by facet length with value
6.
"""
assert_bindings(
schema="nistData/list/nonPositiveInteger/Schema+Instance/NISTSch... | 67,926 |
async def test_event_start_trigger(hass, calls, fake_schedule):
"""Test the a calendar trigger based on start time."""
event_data = fake_schedule.create_event(
start=datetime.datetime.fromisoformat("2022-04-19 11:00:00+00:00"),
end=datetime.datetime.fromisoformat("2022-04-19 11:30:00+00:00"),
... | 67,927 |
def test_show_env_internet_free():
"""
test the show-env ggd call can run an internet free context
(show-env)
"""
## Install hg19-gaps
try:
pytest_enable_socket()
install_hg19_gaps_ucsc_v1()
except:
pass
## Check show-env in an internet free context
pyte... | 67,928 |
def options_from(**kwargs):
"""Generate a Values instances with our kwargs."""
kwargs.setdefault('hang_closing', True)
kwargs.setdefault('max_line_length', 79)
kwargs.setdefault('verbose', False)
kwargs.setdefault('stdin_display_name', 'stdin')
return optparse.Values(kwargs) | 67,929 |
def connect(server, username, password):
"""
Connect to Seafile server
:param server: address of the seafile server
:param username: username
:param password: password
:return: :class:`SeafileApiClient`.
"""
seafile_client = SeafileApiClient(server, username, password)
return seafile... | 67,930 |
def evaluate_powered_prefix(tokens):
"""
Evaluates prefix operations only before power values.
Parameters
----------
tokens : `list` of ``Token``
Tokens to evaluate.
"""
for index in reversed(range(1, len(tokens)-2)):
if tokens[index].id != OPERATION_POWER_ID:
... | 67,931 |
def lsolve(A, b):
"""Gaussian elimination with partial pivoting.
This is implemented here to avoid a dependency on numpy. This could be
replaced by :code:`(x, _, _, _) = lstsq(A, b)`, but we prefer the pure
Python implementation here.
"""
N = len(b)
for p in range(N):
# f... | 67,932 |
def setup_routes(server_instance: bottle.Bottle) -> None:
"""Setup all the routes for the server.
Usually routing is done using:
@app.route('/index')
def index():
...
But we're using lots of global objects, so we would face problems with
cyclic imports here. Also, dependin... | 67,933 |
def show_user():
"""
function to show existing users
:return: existing users
"""
return User.display_all_users() | 67,934 |
def sum(l):
"""
Returns the sum of the items in the container class.
This is more general than the build-in 'sum' function, because it is not specific for numbers.
This function uses the '+' operator repeatedly on the items in the contrainer class.
For example, if each item is a list... | 67,935 |
def main(args):
"""Process Glicko2 ratings."""
scrape = args.scrape
tournaments = args.tournaments
output_format = args.output_format
game = args.game
top_amount = int(args.top_amount)
sort = args.sort
if scrape:
scrape_all_tournaments()
if tournaments:
tournaments ... | 67,936 |
def extract_z_dec(model, sample_layer_name, vis=False, wt_chk=False):
"""
extract the z_decoder [z = p(x)] and return it as a keras model
Example Layer name:
sample_layer_name = 'img-img-dense-vae_ae_dense_sample'
"""
# need to make new model to avoid mu, sigma outputs
tmp_model = keras.mo... | 67,937 |
def acquire_new_oauth2_credentials(secrets_file):
"""
Args:
secrets_file. The file path to a JSON file of client secrets, containing:
client_id; client_secret; redirect_uris; auth_uri; token_uri.
Returns:
credentials for use with Google APIs
"""
flow = flow_from_clientsec... | 67,938 |
def hold_file_root(path, make_dir = True, delete_after = False, delete_before=False):
"""
:param path:
:return:
"""
old_path = FILE_ROOT
if delete_before and os.path.exists(path):
rmtree(path)
set_file_root(path, make_dir=make_dir)
yield
set_file_root(old_path)
if delete_... | 67,939 |
def debugInitializeWeights(fan_in, fan_out):
"""
Initializes the weights of a layer with fan_in incoming connections and
fan_out outgoing connections using a fixed set of values.
"""
# Set W to zero matrix
W = np.zeros((fan_out, fan_in + 1))
# Initialize W using "sin". This ensures that W ... | 67,940 |
def checkValues_coordinate0(coordinate0, reference_point):
"""Function that check the range of the input coordinates to be rigth"""
# AP
if 90 > coordinate0[0] > -90:
pass # Entry in correct range
else:
raise Exception(
"Coordinate AP ({}) out of range for lambda, should be... | 67,941 |
def correct_task_suggestions_in_loop_body(pet: PETGraphX, suggestions: List[PatternInfo]) -> List[PatternInfo]:
"""Separate treatment of task suggestions at loop increment CUs.
If regular loop: move taskwait suggested at loop increment line to end of loop body.
If do-all loop: move taskwait suggested at loo... | 67,942 |
def validate(data_loader, actor, save_dir, **kwargs):
"""Used to monitor progress on a validation set & optionally plot solution."""
actor.eval()
if kwargs['render_fn'] is not None:
if not os.path.exists(save_dir):
os.makedirs(save_dir)
rewards = []
for batch_idx, batch in enu... | 67,943 |
def gettags(conf, dlcs, *tags, **opts):
"""Print info about tag.
"""
if opts['ignore_case']:
tags = [t.lower() for t in tags]
for tag in cached_tags(conf, dlcs, opts['keep_cache'])['tags']:
if tag['tag'] in findtags or \
(opts['ignore_case'] and tag['tag'].lower() in f... | 67,944 |
def compare(isamAppliance1, isamAppliance2):
"""
Compare user name mapping
"""
ret_obj1 = get_all(isamAppliance1)
ret_obj2 = get_all(isamAppliance2)
for obj in ret_obj1['data']:
ret_obj = get(isamAppliance1, obj['id'])['data']
del obj['version']
obj['contents'] = ret_ob... | 67,945 |
def get_keyword(title):
"""
:param title: policy title (str)
:return: keyword (str)
"""
matchObj = re.match('(.*)关于(.*)的(.*)', title)
if matchObj:
title = matchObj.group(2)
matchObj2 = re.match(r'(.*)“(.*)”(.*)', title)
if matchObj2:
title = matchObj2.group(2)
matchO... | 67,946 |
def Rotation_calcNForBodyXYZInBodyFrame(*args):
"""
calcNForBodyXYZInBodyFrame(Vec3 q) -> Mat33
Parameters
----------
q: SimTK::Vec3 const &
Rotation_calcNForBodyXYZInBodyFrame(Vec3 cq, Vec3 sq) -> Mat33
Parameters
----------
cq: SimTK::Vec3 const &
sq: SimTK::Vec3 const &
... | 67,947 |
def remove_integer_identifier_types(*args):
"""
Sets all ``id`` fields to allow only strings, not integers.
"""
def schema_action(schema, pointer):
if 'properties' in schema:
if 'id' in schema['properties']:
schema['properties']['id']['type'] = 'string'
elif ... | 67,948 |
def get_version(versionfile):
"""Extract the __version__ from a given Python module."""
match = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', open(versionfile).read(), re.M)
if match:
return match.group(1)
else:
raise RuntimeError("Unable to find version string in {file}.".format(file... | 67,949 |
def create_push_down(target_path, arena_name, time=1000, is_train=True):
""" The reward is on top of a box. agent must push box in the right position to be able to acces the reward platform."""
coin = random.choice([0,1])
if coin == 1:
box_pos = (random.randint(25, 140) / 10., 1., random.randint(... | 67,950 |
def read_ap_custom_resource(custom_objects: CustomObjectsApi, namespace, plural, name) -> object:
"""
Get AppProtect CRD information (kubectl describe output)
:param custom_objects: CustomObjectsApi
:param namespace: The custom resource's namespace
:param plural: the custom resource's plural name
... | 67,951 |
async def natsClientClosedConn() :
"""natsClientClosedConn is called whenever the NATS client closes its
connection to the NATS message system."""
print("")
print("connection to NATS server is now closed.") | 67,952 |
def validate_with_reasoner(tree_path, phyloref_path):
""" Run the reasoner over the treePath and the phylorefPath, and
then check to see if every class named 'X_expected' has the same
set of individuals as 'X'.
- treePath: The path to the tree, as OWL
- phylorefPath: The path to the phyloref... | 67,953 |
def get_encoded_logs(job: Job, use_cache: bool = True) -> (DataFrame, DataFrame):
"""returns the encoded logs
returns the training and test DataFrames encoded using the given job configuration, loading from cache if possible
:param job: job configuration
:param use_cache: load or not saved datasets fro... | 67,954 |
def readelf_header(bin_file):
"""Read elf header and return dictionary"""
p = subprocess.Popen("readelf -h %s" % bin_file, shell=True, close_fds=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.wait()
attr_map = {}
for l in p.stdout.readlines():
line = l.decod... | 67,955 |
def test_multiple_bgp_config_lines_with_same_first_word():
""" Very similar lines starting with same word are different """
baseline = [
"router bgp {{BGP_AS}}",
" network {{LAN_NET}} mask 255.255.248.0",
" network {{LOOPBACK_IP}} mask 255.255.255.255",
" neighbour {{PE_IP}} remo... | 67,956 |
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the MPD platform."""
host = config.get(CONF_HOST)
port = config.get(CONF_PORT)
name = config.get(CONF_NAME)
password = config.get(CONF_PASSWORD)
device = MpdDevice(host, port, password, name)
add_entities([device... | 67,957 |
def _filter_messages(msgs: List[Message]) -> List[Message]:
"""Filter messages removing those that start with INTENT_MESSAGE_PREFIX"""
filtered_messages = []
for msg in msgs:
if not msg.text.startswith(INTENT_MESSAGE_PREFIX):
filtered_messages.append(msg)
return filtered_messages | 67,958 |
def TestFilterOpCode():
"""Tests that filtering with the "opcode" predicate works"""
# Check that delay jobs work fine.
AssertCommand(["gnt-debug", "delay", "0.01"])
# Add a filter that rejects all new delay jobs.
uuid = stdout_of([
"gnt-filter", "add",
'--predicates=[["opcode", ["=", "OP_ID", "OP_T... | 67,959 |
def hostname_resolves(hostname):
"""Checks to see if hostname is DNS resolvable"""
try:
socket.gethostbyname(hostname)
return 1
except socket.error:
return 0 | 67,960 |
def descale_fields(clip: vs.VideoNode, tff: bool = True,
width: int | None = None, height: int = 720,
kernel: Kernel = Catrom(), src_top: float = 0.0) -> vs.VideoNode:
"""
Simple descaling wrapper for interwoven upscaled fields.
This function also sets a frameprop with ... | 67,961 |
def migrate():
""" create test tables """
User().create()
FoodItem().create()
FoodOrder().create() | 67,962 |
def _gain2db(gain):
"""
Convert linear gain in range [0.0, 1.0] to 100ths of dB.
Power gain = P1/P2
dB = 10 log(P1/P2)
dB * 100 = 1000 * log(power gain)
"""
if gain <= 0:
return -10000
return max(-10000, min(int(1000 * math.log10(min(gain, 1))), 0)) | 67,963 |
def build_aggregation_layer(aggregation_input_layer, model_config,
calibrated_lattice_models, layer_output_range,
submodel_index, dtype):
"""Creates an aggregation layer using the given calibrated lattice models.
Args:
aggregation_input_layer: A list or a... | 67,964 |
def generate_int(data_format):
"""
Generate an integer based on the given data width and sign.
"""
is_signed = data_format['is_signed']
width = data_format['width']
if is_signed:
result = random.randrange(-2 ** (width - 1) + 1, 2 ** (width - 1) - 1)
else:
result = random.ran... | 67,965 |
def load(filep):
"""
Read an V_sim .ascii file and returns a pychemia
Structure object
Args:
filep: (string) Path to a .ascii file or an
actual file-like object
Returns:
struct: (object) A pychemia Structure object
"""
if isinstance(filep, str):
f = open... | 67,966 |
def mock_run_applescript(script):
"""Don't actually run any applescript in the unit tests, ya dingbat.
This function should return whatever type of object
dialogs._run_applescript returns.
Returns:
tuple
"""
return (1, "", "") | 67,967 |
def blur_spec(wl,spec,dv,truncsize = 20.0):
"""This function takes a spectrum, and blurs it using either a
Gaussian kernel or a box kernel, which have a FWHM width of dv km/s everywhere.
Meaning that the width changes dynamically on a constant d-lambda grid.
Because the kernel needs to be recomputed on ... | 67,968 |
def channel_last_to_first(img: torch.Tensor) -> torch.Tensor:
"""
Converts an image of shape batch_size, height, width, channels into an image of shape batch_size, channels, height,
width.
Parameters
----------
img: Image with shape batch_size, height, width, channels.
Returns
-------
... | 67,969 |
def _projector_on_tvl1_dual(grad, l1_ratio):
"""Function to compute TV-l1 duality gap.
Modifies IN PLACE the gradient + id to project it
on the l21 unit ball in the gradient direction and the L1 ball in the
identity direction.
"""
# The l21 ball for the gradient direction
if l1_ratio < 1.:... | 67,970 |
def export_type1(cursor, table_name, id_parameter_name):
"""
Type1 Mapping: SpineDB has an object with parameters. {'Table Name': 'Object Column Name'}
:param cursor: PYODBC Cursor
:param table_name: Table Name
:param id_parameter_name: Object ID Column Name
:return:
"""
for (_, id_para... | 67,971 |
def get_id(psco):
"""
Retrieve the persistent object identifier.
:param psco: Persistent object
:return: <String> Id
"""
return psco.getID() | 67,972 |
def rotate_image(img, angle):
"""
Rotate image by given angle. Adapted from https://stackoverflow.com/a/23316542.
"""
row, col, _ = img.shape
center = tuple(np.array([row, col]) / 2)
rot_mat = cv2.getRotationMatrix2D(center, angle, 1.0)
new_img = cv2.warpAffine(img, rot_mat, (col, row))
... | 67,973 |
def _defaults_to_code(val):
"""
Make sure that any defaults that are surrounded by << >> are in code quotes so that they render properly.
e.g.: <<display_name>> converts to '<<display_name>>'
"""
return re.sub(r"(<{2}.*>{2})", r"`\1`", val) | 67,974 |
def create_file(path):
"""Creates a file at a path and overwrites file if exists."""
open(path, "w").close() | 67,975 |
def test_parse_log_line(log_line):
"""
Test generic log line parser
"""
log_entry = parse_log_line(NGINX, log_line)
assert log_entry.host_ip == "77.179.66.156" | 67,976 |
def do_label_encoding(
source_train_df,
source_test_df,
target_train_df,
target_test_df,
categorical_features,
feature_name_suffix=None,
):
"""
Label encode the categorical features.
After encdoing, it appends a new set of features with name
<original_feature_name>_label to the t... | 67,977 |
def sprintf(fmt, *args):
"""C-style String Formatting
Args:
fmt: The formats
*args: The values
Returns:
A scalar string if all fmt, *args are scalar strings, otherwise
an array of formatted strings
"""
if is_scalar(fmt) and all(is_scalar(x) for x in args):
i... | 67,978 |
def morphological_process(image, kernel_size=5, func_type=cv2.MORPH_CLOSE):
"""
morphological process to fill the hole in the binary segmentation result
:param image:
:param kernel_size:
:return:
"""
if len(image.shape) == 3:
raise ValueError('Binary segmentation result image should ... | 67,979 |
def warm_restart(scheduler, T_mult=2):
"""warm restart policy
Parameters:
----------
T_mult: int
default is 2, Stochastic Gradient Descent with Warm Restarts(SGDR): https://arxiv.org/abs/1608.03983.
Examples:
--------
>>> # some other operations(note the order of operations)
>>... | 67,980 |
def good_cli():
"""Good CLI group."""
pass | 67,981 |
def build_ramps():
"""Make our color ramps."""
# WV
RAMPS["wv"] = np.loadtxt("wvramp.txt")
RAMPS["ir"] = np.loadtxt("irramp.txt")
# This is matplotlib's ramp
RAMPS["greys"] = np.loadtxt("greysramp.txt") | 67,982 |
def main() -> None:
"""Start the bot"""
bot_token = get_bot_token()
load_stats()
# Get the updater
updater = Updater(bot_token, use_context=True)
# Get the dispatcher to register handlers
dispatcher = updater.dispatcher
# Command Handlers
dispatcher.add_handler(CommandHandler("star... | 67,983 |
def checkNull(df):
"""
checkNull is a simple function that returns the sum of the number of nulls
you have in each column of your dataframe.
"""
assert isinstance(df, pd.DataFrame), "Please submit a dataframe when using this function."
return df.isnull().sum() | 67,984 |
def send_action(action=ChatAction.TYPING):
"""Sends `action` while processing func command."""
def decorator(func):
@wraps(func)
def command_func(update, context, *args, **kwargs):
context.bot.send_chat_action(chat_id=update.effective_message.chat_id, action=action)
retur... | 67,985 |
def split_dates(dataframe, date_column):
"""Converts date features into pandas datetime objects.
Args:
dataframe (pandas dataframe)
date_column (dataframe column)
"""
copy_of_df = dataframe.copy()
copy_of_df["Year"] = pd.DatetimeIndex(copy_of_df[date_column]).year
copy_of_df["M... | 67,986 |
def total_schedule(schedule):
"""Return the total number of 15 minute windows in which the schedule
is set to replicate in a week. If the schedule is None it is
assumed that the replication will happen in every 15 minute
window.
This is essentially a bit population count.
"""
if schedule i... | 67,987 |
def video_capture(video_path, frame_step, save_dir):
"""주어진 frame step 마다 영상을 이미지로 캡쳐하는 함수"""
vidcap = cv2.VideoCapture(video_path)
total_frames = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
print("Total Frames: ", total_frames)
frame_num = int(total_frames / frame_step)
print("Num of Frames: ", frame_num)
... | 67,988 |
def auth( # pylint: disable=too-many-arguments
obj: ContextInfo,
arg1: str,
arg2: str,
get: bool,
status: bool,
unset: bool,
is_all: bool,
) -> None:
"""Authenticate the accessKey of gas.\f
Arguments:
obj: A :class:`.utility.ContextInfo` instance containing the command cont... | 67,989 |
def verbose(message):
""" Say a verbose-level log message. """
message = "[Bloombox]: %s" % message
if not QUIET and VERBOSE:
if COLORS:
colors.gray(message)
else:
print message | 67,990 |
def test_p2p_device_concurrent_scan(dev, apdev):
"""Concurrent P2P and station mode scans with driver using cfg80211 P2P Device"""
with HWSimRadio(use_p2p_device=True) as (radio, iface):
wpas = WpaSupplicant(global_iface='/tmp/wpas-wlan5')
wpas.interface_add(iface)
wpas.p2p_find()
... | 67,991 |
def diff_mark(m, t):
"""
Subtract from a marking the postset of t and adds the preset
Parameters
------------
m
Marking
t
Transition
Returns
------------
diff_mark
Difference marking
"""
for a in t.out_arcs:
p = a.target
w = a.weight
... | 67,992 |
def vatm(model, x, logits, eps, num_iterations=1, xi=1e-6,
clip_min=None, clip_max=None, scope=None):
"""
Tensorflow implementation of the perturbation method used for virtual
adversarial training: https://arxiv.org/abs/1507.00677
:param model: the model which returns the network unnormalized l... | 67,993 |
def _initialize_file_path(path):
"""
:param path:
:return:
"""
if os.path.exists(path):
return
_mkdirs(os.path.dirname(path))
# touch the file to make sure it exists
open(path, 'ab').close() | 67,994 |
def put_byte(*args):
"""
put_byte(ea, x) -> bool
Set value of one byte of the program. This function modifies the
database. If the debugger is active then the debugged process memory
is patched too.The original value of the byte is completely lost and
can't be recovered by the 'get_original_byte()' functi... | 67,995 |
def get_session():
""" 获取数据库回话对象
如果当前存在事务,则使用最后一个事务的回话对象
否则,新建一个
"""
if hasattr(threadLocal, "sessions") and len(threadLocal.sessions) > 0:
return threadLocal.sessions[-1].session
return _create_session(True) | 67,996 |
def easy_writeSTAR_relion(fname, EAs=None, shifts=None, imgs_path=None, block_name=None):
"""
keywords for Euler angles and shifts
AngleRot, AngleTilt, AnglePsi, OriginX, OriginY
"""
if EAs is None and shifts is None:
raise ValueError('please specify input data: Euler angles or shifts')
... | 67,997 |
def recherche_motif_naive(texte, motif):
"""Retourne la position où le motif a été trouvé par fenetre glissante
ou -1 si le motif ne se trouve pas dans le texte
Si n = len(texte) et m = len(motif), la complexité est en O((n-m)*m)"""
for i in range(len(texte) - len(motif) + 1):
if correspondance_... | 67,998 |
def main(exchange_path, ob_path, title=None, outfile='liquidity_telemetry.png', verbose=False):
""" Processes orderbook from files, creates the liquidity telemetry plot and (optionally) prints statistics. """
processed_orderbook, transacted_orders, cleaned_orderbook = create_orderbooks(exchange_path, ob_path)
... | 67,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.