input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
in runs_where_y_has_same_sign_as_yaxis]
elif self.xaxis_mode == 'log':
for curve_name in self.curves.keys():
if self.curves[curve_name].yaxis == yaxis:
where_xy_have_same_sign_as_axes = np.where(np.logical_and(self.curves[curve_name].data_x * self.xaxis_sign > 0., self.curves[curve_name].data_y * self.yaxes[yaxis].... | |
properties for the resource.
:type tags: dict[str, str]
:param kind: Required. The kind of the environment.Constant filled by server. Possible values
include: "Gen1", "Gen2".
:type kind: str or ~azure.mgmt.timeseriesinsights.models.EnvironmentKind
:param sku: Required. The sku determines the type of environment, e... | |
"""
<Program Name>
repository_lib.py
<Author>
<NAME> <<EMAIL>>
<Started>
June 1, 2014
<Copyright>
See LICENSE for licensing information.
<Purpose>
Provide a library for the repository tool that can create a TUF repository.
The repository tool can be used with the Python interpreter in interactive
mode, or ... | |
codes, indices = ret
else:
codes, indices, values = ret
self.update_self_loop_bonus(values)
codes = self.unpack_x(codes, enc_len)
indices = self.unpack_x(indices, enc_len)
self._log_code_usage(indices, criterion)
if self.needs_global_info:
codes = (codes * fc) + bias
if needs_transpose:
codes = codes.transp... | |
Residues Colored Table for NON bonded################################
NH_templist4graph=[]
NH_graphdic1={}
if bool(Adenin_graphdicNH):
for k,v in Adenin_graphdicNH.iteritems():
#print k
for value in v:
NH_templist4graph.append(value)
samp=sorted(list(set(NH_templist4graph)))
NH_graphdic1.setdefault('%s'%k,[]).ap... | |
"north pole" or the
# "south pole" (after the central lon/lat have been taken into
# account).
if n_parallels == 1:
plat = 90 if standard_parallels[0] > 0 else -90
else:
# Which pole are the parallels closest to? That is the direction
# that the cone converges.
if abs(standard_parallels[0]) > abs(standard_paral... | |
REMOTE
)
cmdComplete = runAndCheckCommandComplete(cmd)
""" Check for files with extensions (i.e. .1, .2, ...) """
""" First, get a list of all files in the base directory """
fixupFileExtsList = []
baseDir = seg.primary_data_directory + "/base"
primaryTempFile = seg.primaryTempDir + '/tempfilesindir' + str(seg.... | |
<filename>persia/ctx.py<gh_stars>1-10
import os
import io
import socket
from enum import Enum
from queue import Queue
from typing import List, Tuple, Optional, Union
import torch
import persia.env as env
from persia.logger import get_default_logger
from persia.embedding.optim import Optimizer
from persia.embedding ... | |
is available immediately, then this function blocks until
a message is ready.
If the remote endpoint closes the connection, then the caller can still
get messages sent prior to closing. Once all pending messages have been
retrieved, additional calls to this method will raise
``ConnectionClosed``. If the local end... | |
'fast_component_update',
callbacks=[config.INSTALLATION_CONFIG.IsAlternateReleaseChannel])
class _SectionTest(_Section):
"""Contains the properties for the 'test' section."""
def __init__(self):
super(_SectionTest, self).__init__('test')
class _SectionDevshell(_Section):
"""Contains the properties for the 'de... | |
<filename>kubelet/datadog_checks/kubelet/kubelet.py
# (C) Datadog, Inc. 2016-2017
# All rights reserved
# Licensed under Simplified BSD License (see LICENSE)
# stdlib
import logging
import re
from urlparse import urljoin
# 3p
import requests
# project
from datadog_checks.checks import AgentCheck
from datadog_checks.... | |
<gh_stars>0
#!/usr/bin/env python
# Copyright (c) 2014 Johns Hopkins University
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# - Redistributions of source code must retain the above copyri... | |
obj._deserialize(item)
self.SelectedTables.append(obj)
memeber_set = set(params.keys())
for name, value in vars(self).items():
if name in memeber_set:
memeber_set.remove(name)
if len(memeber_set) > 0:
warnings.warn("%s fileds are useless." % ",".join(memeber_set))
class DeleteSnapshotsResponse(AbstractModel)... | |
nbar.x_index {sort}, nbar.y_index {sort}
""".format(sort=sort.value)
params = {"tile_type": [TILE_TYPE.value],
"tile_class": [tile_class.value for tile_class in TILE_CLASSES],
"satellite": [satellite.value for satellite in satellites],
"geom": bytearray(wkb),
"acq_min": acq_min, "acq_max": acq_max,
"level_nbar"... | |
them
Nlon=dict()
N_tot= Nlon['N_total'] =float(D.longitude.size)
all_CD_rep=dict()
all_CD_bud=dict()
for kk in seg_dict.keys():
CD_storage_rep=dict()
CD_storage_bud=dict()
lon_seg=seg_dict[kk]
print(kk)
Dsurface_segment = Dsurface.sel(longitude=lon_seg)
#ps_zm_seg = ps.sel(longitude=lon_seg).mean('longitude')... | |
is fixed.
if not aggressive:
return self._export_capsule(repository, includes_dependencies=includes_dependencies)
else:
try:
return self._export_capsule(repository, includes_dependencies=includes_dependencies)
except Exception:
# Empirically this fails occasionally, we don't know
# why however.
time.sleep(1)
... | |
list_extensions(self, **_params):
"""Fetch a list of all extensions on server side."""
return self.get(self.extensions_path, params=_params)
def show_extension(self, ext_alias, **_params):
"""Fetches information of a certain extension."""
return self.get(self.extension_path % ext_alias, params=_params)
def list... | |
18, 11),
r.period_end)
elif (r.groupby == {'resource_metadata.instance_type': '83'} and
r.period_start == datetime.datetime(2013, 8, 1, 10, 11)):
self.assertEqual(1, r.count)
self.assertEqual('s', r.unit)
self.assertEqual(4, r.min)
self.assertEqual(4, r.max)
self.assertEqual(4, r.sum)
self.assertEqual(4, r.avg... | |
# Copyright (c) 2020 The Foundry Visionmongers Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced... | |
<reponame>yohanesnuwara/seismic-deeplearning
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# commitHash: c76bf579a0d5090ebd32426907d051d499f3e847
# url: https://github.com/olivesgatech/facies_classification_benchmark
"""Script to generate train and validation sets for Net... | |
False == false_res.json()['enable']
req['build_index_resources'] = -3.222
requests.put(base_url + 'config/gpu_resources', data=json.dumps(req))
res = requests.get(base_url + 'config/gpu_resources')
assert false_res.json() == res.json()
def test_put_gpu_resources_build_index_resources_16(self, args):
if self.... | |
from pollination_dsl.alias import OutputAlias
from queenbee.io.common import IOAliasHandler
"""Alias for daylight factor recipe output."""
daylight_factor_results = [
OutputAlias.any(
name='results',
description='Daylight factor values. These can be plugged into the "LB '
'Spatial Heatmap" component along with me... | |
158, 157.949316, False),
'Lu-159': Iso('Lu-159', 'lutetium-159', 71, 159, 158.946636, False),
'Lu-160': Iso('Lu-160', 'lutetium-160', 71, 160, 159.946033, False),
'Lu-161': Iso('Lu-161', 'lutetium-161', 71, 161, 160.943572, False),
'Lu-162': Iso('Lu-162', 'lutetium-162', 71, 162, 161.943283, False),
'Lu-163': Iso(... | |
self.splitter_5_pop.setOrientation(QtCore.Qt.Vertical)
self.splitter_5_pop.setObjectName("splitter_5_pop")
self.layoutWidget_6 = QtWidgets.QWidget(self.splitter_5_pop)
self.layoutWidget_6.setObjectName("layoutWidget_6")
self.horizontalLayout_ExampleImgs_pop = QtWidgets.QHBoxLayout(self.layoutWidget_6)
self.ho... | |
<gh_stars>10-100
""" A container for all information about the field: geometry and labels, as well as convenient API. """
import os
import re
from glob import glob
from difflib import get_close_matches
from concurrent.futures import ThreadPoolExecutor
import numpy as np
from ...batchflow.notifier import Notifier
fro... | |
# C2SMART Lab, NYU
# NCHRP 03-137
# @file TTCD_Calculation_Online.py
# @author <NAME>
# @author <NAME>
# @date 2020-10-18
import pandas as pd
import numpy as np
from shapely.geometry import Polygon
import math
import time
import multiprocessing as mp
from itertools import repeat
from scipy import spatial
import sys
d... | |
#Adventure Game
#<NAME>, <NAME>, <NAME> (C)2010
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#This program is dis... | |
A.B")
temp_buck_distr_B_virt_err_self = temp_buck_distr_B_self + self.virtual_error
temp_buck_distr_B_virt_err_pb = temp_buck_distr_B_pb + pb.virtual_error
temp_virtual_error = self.convolve_same(temp_buck_distr_B_virt_err_self, temp_buck_distr_B_virt_err_pb) - temp_buck_distr_B_convolved
self.logger.info(" Comput... | |
'pressure'
var_list[5].name = 'conductivity'
var_list[0].data = np.array([])
var_list[1].data = np.array([])
var_list[2].data = np.array([])
var_list[3].data = np.array([])
var_list[4].data = np.array([])
var_list[5].data = np.array([])
var_list[0].units = 'seconds since 1900-01-01'
var_list[1].units ... | |
<gh_stars>1-10
#! /usr/bin/python3
r'''###############################################################################
###################################################################################
#
#
# Tegridy MIDI X Module (TMIDI X / tee-midi eks)
# Version 1.0
#
# NOTE: TMIDI X Module starts after the partia... | |
<gh_stars>1-10
# Program to program a Science of Cambridge MK14 with a 7Bot
# An MK14 is a very old micro-computer from what became Sinclair Research
# A 7Bot is a 7 degrees of freedom robot arm which orignated here:
# More information on this project is here: http://robdobson.com/2016/10/mk14-meets-7bot/
from __futur... | |
<reponame>CrankySupertoon01/Toontown-2
# File: D (Python 2.4)
from direct.distributed.DistributedNodeAI import DistributedNodeAI
from direct.distributed.ClockDelta import *
from direct.fsm import ClassicFSM, State
from direct.fsm import State
from direct.fsm import StateData
from direct.distributed.ClockDelta import *... | |
<reponame>MosHumanoid/bitbots_thmos_meta<gh_stars>0
#!/usr/bin/env python3
import cv2
import rospy
import tf2_ros
import numpy as np
import sensor_msgs.point_cloud2 as pc2
from cv_bridge import CvBridge
from sensor_msgs.msg import Image, CameraInfo, PointCloud2
from geometry_msgs.msg import Point, PolygonStamped
from t... | |
<filename>lightautoml/transformers/text.py
"""Text features transformers."""
import gc
import os
import pickle
from copy import deepcopy, copy
from typing import Optional, Union, List, Dict, Any
import gensim
import numpy as np
import pandas as pd
import torch
from log_calls import record_history
from sklearn.feature... | |
"people")
def test_no_empty_strings(self):
input_chunks = ["soylent", "green", "is", "people"]
si = utils.Spliterator(input_chunks)
outputs = (list(si.take(7)) # starts and ends on chunk boundary
+ list(si.take(2)) # spans two chunks
+ list(si.take(3)) # begins but does not end chunk
+ list(si.take(2)) # ends ... | |
<reponame>pagabuc/FirmAE<gh_stars>1-10
#!/usr/bin/env python3
import sys
import getopt
import re
import struct
import socket
import stat
import os
import time
import subprocess
debug = 0
SCRATCHDIR = ''
SCRIPTDIR = ''
QEMUCMDTEMPLATE = """#!/bin/bash
set -e
set -u
ARCHEND=%(ARCHEND)s
IID=%(IID)i
if [ -e ./firmae.... | |
<gh_stars>0
#
# Copyright (C) 2012 - 2018 <NAME> <<EMAIL>>
# License: MIT
#
# pylint: disable=unused-import,import-error,invalid-name
r"""Public APIs of anyconfig module.
.. versionadded:: 0.9.8
- Added new API load_plugins to [re-]load plugins
.. versionadded:: 0.9.5
- Added pathlib support. Now all of load and ... | |
f_result = directions.ParaclinicResult(issledovaniye=i, field=gi, value="")
else:
f_result = directions.ParaclinicResult.objects.filter(issledovaniye=i, field=gi)[0]
if f_result.value != content:
f_result.value = content
f_result.save()
if i.doc_save != doc or i.time_save != date or i.doc_confirmation != doc or i... | |
not found!
return None
def get_color(self, type_category, type_name):
color = self.get_representation(type_category, type_name, 'color')
if color != None:
return ' #%s' % color
else:
return ''
def get_label(self, type_category, node_name, type_name):
icon = self.get_representation(type_category, type_name, '... | |
-2, -3, -3, -2, -3, -3]
victimization -2.3 0.78102 [-1, -3, -3, -2, -3, -1, -3, -2, -3, -2]
victimizations -1.5 1.85742 [-2, -3, -3, -1, -2, 2, 2, -2, -3, -3]
victimize -2.5 0.67082 [-3, -2, -4, -2, -2, -2, -2, -3, -3, -2]
victimized -1.8 1.53623 [-2, -1, -3, -3, -3, 1, 1, -2, -3, -3]
victimizer -1.8 1.72047 [-3, -2, -... | |
data_newref_mask,
table_trans['X_POS'], table_trans['Y_POS'], psffit=psffit,
moffat=moffat, gauss=gauss, psfex_bintable_ref=fits_ref_psf,
header_new=header_new, header_ref=header_ref,
Scorr_peak=table_trans['SCORR_PEAK'], log=log)
return results
# determine optimal flux in D, directly added as columns to table... | |
<filename>src/ecs_tasks_ops_qt5/qt5_ecs.py
"""Qt5 Tree Model for ecs."""
from PyQt5 import QtCore
from PyQt5 import QtWidgets
from ecs_tasks_ops import ecs_conf
from ecs_tasks_ops import ecs_data
from ecs_tasks_ops import ecs_facade
from ecs_tasks_ops import ecs_ssh
from ecs_tasks_ops import pretty_json
class ECSTre... | |
from tkinter import *
import time, mysql.connector,csv,os,subprocess
from PIL import Image
from ast import literal_eval
from mysql.connector import errorcode
from tkinter import messagebox
from tkinter.filedialog import asksaveasfilename
class window(Tk):
def __init__(self):
super().__init__()
# create sql connectio... | |
<filename>AnalyzeControl.py
#!/usr/bin/env python
"""
Tencent is pleased to support the open source community by making HaboMalHunter available.
Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in
compliance wit... | |
df.shape[0])
assert r.chunks[0].inputs[0].shape[0] == df_raw.shape[0]
assert r.chunks[0].inputs[0].op._op_type_ == opcodes.CONCATENATE
# test transform scenarios on data frames
r = tile(df.transform(lambda x: list(range(len(x)))))
assert all(v == np.dtype('int64') for v in r.dtypes) is True
assert r.shape == df.... | |
OperationalError:
# something error occured
break
ln = _bytes_to_bint(self._read(4)) - 4
data = self._read(ln)
if code == 90:
self._trans_status = data
DEBUG_OUTPUT("-> ReadyForQuery('Z'):{}".format(data))
break
elif code == 82:
auth_method = _bytes_to_bint(data[:4])
DEBUG_OUTPUT("-> Authentication('R'):{}".... | |
"""Android Calculator App Test: Addition"""
# Created by <NAME>.
# GitHub: https://github.com/ikostan
# LinkedIn: https://www.linkedin.com/in/egor-kostan/
import allure
from tests.android_native.calculator_tests.calculator_base_testcase import AndroidCalculatorBaseTestCase
@allure.epic('Android Native App')
@allure... | |
actual call within the gRPC stub, and fake the request.
with mock.patch.object(
type(client.transport.move_book),
'__call__') as call:
# Designate an appropriate return value for the call.
call.return_value =grpc_helpers_async.FakeUnaryUnaryCall(library.Book(
name='name_value',
author='author_value',
title='tit... | |
"""
Module containing all necessary calculations, functions and classes, for ionization calculations from
Budapest-Florida code output.
It uses the interface given in tcdata.py module.
Most important feature is:
Ionization.IonizationForRawprofile static method calculates ionization for given rawProfile object.
"""
... | |
<reponame>matthewpipie/vectra_api_tools
import json
import requests
import warnings
import html
import re
warnings.filterwarnings('always', '.*', PendingDeprecationWarning)
class HTTPException(Exception):
def __init__(self, response):
"""
Custom exception class to report possible API errors
The body is contructe... | |
= [slice(None), slice(tl_y, br_y), slice(tl_x, br_x)]
>>> # Note: I'm not 100% sure this work right with non-intergral slices
>>> outputs = kwimage.subpixel_slice(inputs, index)
Example:
>>> inputs = np.arange(5 * 5 * 3).reshape(5, 5, 3)
>>> index = [slice(0, 3), slice(0, 3)]
>>> outputs = subpixel_slice(inputs,... | |
<filename>pandaharvester/harvestermonitor/htcondor_monitor.py
import re
import time
import datetime
import threading
import random
import xml.etree.ElementTree as ET
try:
import subprocess32 as subprocess
except Exception:
import subprocess
try:
from threading import get_ident
except ImportError:
from thread impo... | |
0x00, 0x00, #
0x00, 0x00, #
0x00, 0x00, #
0x00, 0x00, #
# @1024 'Z' (7 pixels wide)
0x00, #
0xFE, # OOOOOOO
0x02, # O
0x04, # O
0x08, # O
0x08, # O
0x10, # O
0x20, # O
0x20, # O
0x40, # O
0x80, # O
0xFE, # OOOOOOO
0x00, #
0x00, #
0x00, #
0x00, #
# @1040 '[' (2 pixels wide)
0x00,... | |
"CSF", "GM", "WM"],
"title": "MRBrainS Confusion Matrix"}},
every=1), Event.ON_TEST_EPOCH_END) \
.with_event_handler(PlotCustomVariables(visdom_logger, "ABIDE Confusion Matrix", PlotType.HEATMAP_PLOT,
params={
"opts": {"columnnames": ["VM", "GM", "CSF", "Background"],
"rownames": ["Background", "CSF", "GM", "WM"]... | |
<reponame>lrivallain/pyvcloud
# VMware vCloud Director Python SDK
# Copyright (c) 2014-2018 VMware, Inc. 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.ap... | |
from https://github.com/google/jax/issues/1907
key = jax.random.PRNGKey(0)
key, split = jax.random.split(key)
n = 5
def func(D0):
def shift(R, dR, **unused_kwargs):
return R + dR
def apply_fn(R):
return D0 * R
Rinit = jax.random.uniform(split, (n,3), minval=0.0, maxval=5.0,
dtype=jnp.float32)
def move(R... | |
import json
import logging
from cryptojwt.exception import BadSignature
from cryptojwt.jws.exception import JWSException
from cryptojwt.key_jar import KeyJar
from fedoidcmsg import ClientMetadataStatement
from fedoidcmsg import DoNotCompare
from fedoidcmsg import IgnoreKeys
from fedoidcmsg import MetadataStatementErr... | |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from __future__ import division, print_function
from .image import Image
import os
import pygame
import numpy as np
PYGAME_INITIALIZED = False
__all__ = [
'Display'
]
class Display(object):
"""
WindowsStream opens a window (Pygam... | |
optional
A constant that specify the scaling factor for the features of this
namespace.
Examples
--------
>>> from vowpalwabbit.DFtoVW import Namespace, Feature
>>> ns_one_feature = Namespace(Feature("a"))
>>> ns_multi_features = Namespace([Feature("a"), Feature("b")])
>>> ns_one_feature_with_name = Namespace(... | |
import pytest
import os, thread
from hippy.debugger import Connection, Message
from hippy.objspace import ObjSpace
from testing.test_interpreter import MockInterpreter, preparse
class TestDebugger(object):
def setup_method(self, meth):
self.read_fd1, self.write_fd1 = os.pipe()
self.read_fd2, self.write_fd2 = os.pi... | |
= Vertex(name = 'V_311',
particles = [ P.G0, P.G__plus__, P.sl3__minus__, P.sv3__tilde__ ],
color = [ '1' ],
lorentz = [ L.SSSS1 ],
couplings = {(0,0):C.GC_1134})
V_312 = Vertex(name = 'V_312',
particles = [ P.A0, P.H__plus__, P.sl3__minus__, P.sv3__tilde__ ],
color = [ '1' ],
lorentz = [ L.SSSS1 ],
couplings ... | |
<filename>targeter/targeter.py
import argparse
import functools
import re
from datetime import datetime, timezone
import aiohttp
import discord
from dateutil.parser import parse
from redbot.core import checks, commands
from redbot.core.commands import BadArgument, Converter, RoleConverter
from redbot.core.ut... | |
1 or hroots[0] != root_join_order[nridx]:
break
if nridx == 0: return partitions
# Now merge all other partitions from 0 to nridx-1 into nridx
bigone = []
tozero=[]
for idx,part in (enumerate(partitions)):
if idx > nridx: break
if part:
bigone = list(bigone) + list(part)
tozero.append(idx)
break
if not big... | |
version_dict['version']['disks'][disk_name]['type_of_disk'] = \
m.groupdict()['type_of_disk']
continue
# BIOS Flash Firmware Hub @ 0x0, 0KB
m = p10.match(line)
if m:
bios_flash = m.groupdict()['bios_flash']
version_dict['version']['bios_flash'] = bios_flash
# 0: Ext: Management0/0 : address is 5001.0003.0000,... | |
an exponential fit to the intensity histogram.
Intensity threshold will be set at where the exponential function will have dropped
to exp_intensity_filter (Default = 0.01).
min_peaks: int
Minimum number of peaks to keep, unless less are present from the start.
Default = 10.
max_peaks: int
Maximum number of peaks... | |
<filename>tests/modules/test_blazeMeterUploader.py
import json
import logging
import math
import os
import shutil
import time
from io import BytesIO
from bzt import TaurusException
from bzt.bza import Master, Session
from bzt.modules.aggregator import DataPoint, KPISet
from bzt.modules.blazemeter import BlazeMeterUplo... | |
<reponame>alsyz/genieparser<filename>src/genie/libs/parser/iosxe/tests/test_show_bgp.py
# Python
import unittest
from unittest.mock import Mock
# ATS
from pyats.topology import Device
from pyats.topology import loader
# Metaparser
from genie.metaparser.util.exceptions import SchemaEmptyParserError, \
SchemaMissingK... | |
<reponame>Wouter-Bekker-AI/yolov5-dataset-builder<filename>scripts/Helper.py
import cv2 as cv
import shutil
import numpy as np
import os
import pandas as pd
from tqdm import tqdm
import random
import time
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import skewnorm
from PIL import I... | |
def forward(self, input_token, target_token, timestep, *inputs):
"""
Decoder step inputs correspond one-to-one to encoder outputs.
"""
log_probs_per_model = []
state_outputs = []
next_state_input = len(self.models)
# underlying assumption is each model has same vocab_reduction_module
vocab_reduction_module = ... | |
the attr
while not a == '':
a = a.split(":")
a, new = ':'.join(a[:-1]), a[-1]
attr = new
if k in form:
# If the form has the split key get its value
tainted_split_key = k
if should_be_tainted(k):
tainted_split_key = taint_string(k)
item = form[k]
if isinstance(item, record):
# if the value is mapped to a re... | |
gapxy)
# set y coordinate to y_centerline_fit[iz] for elements 1 and 2 of the cross
for i in range(1,3):
landmark_curved[index][i][1] = y_centerline_fit[iz_curved[index]]
# set coordinates for landmarks +y and -y. Here, x coordinate is 0 (already initialized).
landmark_curved[index][3][2], landmark_curved[index][3... | |
queryset=RackReservation.objects.all(),
widget=forms.MultipleHiddenInput()
)
user = forms.ModelChoiceField(
queryset=User.objects.order_by(
'username'
),
required=False
)
tenant = forms.ModelChoiceField(
queryset=Tenant.objects.all(),
required=False
)
description = forms.CharField(
max_length=100,
requir... | |
not data.positive:
msg = "Can't use negative index %s" % value
if msg:
global error_occurred
error_occurred = True
print("ERROR - %s near line %i" % (msg, t.lineno(1)))
def p_type_def_1(t):
'''type_def : TYPEDEF declaration SEMI'''
# declarations is a type_info
d = t[2]
lineno = t.lineno(1)
sortno = t.lineno... | |
<filename>AnDe/AnDe.py
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 26 11:36:48 2021
@author: ChandrimaBiswas
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import time
import os
from sklearn.preprocessing import OneHotEncoder
from sklearn.compose import ColumnTransformer
... | |
<reponame>Vladimir-Ivanov-Git/raw_packet
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# region Description
"""
dhcp_fuzz.py: DHCPv4 fuzzing script
Author: <NAME>
License: MIT
Copyright 2020, Raw-packet Project
"""
# endregion
# region Import
from sys import path
from os.path import dirname, abspath
from argparse im... | |
* cenrace', 'detailed'),
},
},
CC.ROUNDER_QUERY_ORDERING: {
0: {
0: ('total', 'hhgq', 'hhgq * hispanic', 'hhgq * hispanic * cenrace', 'hhgq * votingage * hispanic * cenrace',
'detailed'),
},
},
}
cty_tr_bg_ordering = {
CC.L2_QUERY_ORDERING: {
0: {
0: ('total',),
1: ('cenrace', 'hispanic', 'votingage', 'hh... | |
tree
header_all_in_i, unheader_all_in_i = check_header(item)
# Logic for applying and removing headers
if any([header_all_in_p, header_all_in_s, header_all_in_i]):
if item['content'][0] != '*':
item.update(content='* ' + item['content'])
for ci in child_items:
if not ci['content'].startswith('*'):
ci.update(co... | |
silent_option))
else: os.system("chown -R {} {}".format(owner+":"+group, path))
else:
if sudo: os.system("sudo chown {} {} {}".format(owner+":"+group, path, silent_option))
else: os.system("chown {} {} {}".format(owner+":"+group, path, silent_option))
def check(self, owner=None, group=None, sudo=F... | |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2018 Fetch.AI Limited
#
# 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
#... | |
in parms:
hstrainRef = wx.CheckBox(DData,wx.ID_ANY,label=Pa)
hstrainRef.thisown = False
hstrainRef.SetValue(ref)
Indx[hstrainRef.GetId()] = [G2frame.hist,Id]
hstrainRef.Bind(wx.EVT_CHECKBOX, OnHstrainRef)
hstrainSizer.Add(hstrainRef,0,WACV|wx.LEFT,5)
# azmthOff = G2G.ValidatedTxtCtrl(G2frame.dataDisplay,data,'azm... | |
<reponame>florianjehn/IPCC-Reports-Focus-Overview<gh_stars>0
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 17 10:12:26 2021
@author: <NAME>
"""
import os
import pandas as pd
import numpy as np
import re
import random
def read_ipcc_counts_temp():
"""reads all counts of temperatures for all reports and... | |
import pickle, glob, sys, csv, warnings
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.metrics import accuracy_score, confusion_matrix, auc, roc_curve
from feature_extraction_utils import _load_file, _save_file, _get_node_info
from scipy.stats import multivariate_normal
from scipy.n... | |
"Kernel", lineno),
"Complex",
[self._parse_numeric_string(s)],
None,
lineno
)
def _parse_int(self, s):
if "X" in s:
base = 16
elif "O" in s:
base = 8
elif "B" in s:
base = 2
else:
base = 10
if base != 10:
# Strip off the leading 0[xob]
s = s[2:]
val = rbigint()
i = 0
while i < len(s):
c = ord(s[i... | |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""Process wind data for adjacent years and save processed data to a NetCDF file per subset. Settings, such as target file name,
are imported from config.py.
Example::
$ python process_data.py : process all latitudes (all subsets)
$ python process_data.py -s subsetID :... | |
# pubsub completion notification
def test_cron_abort_expired_task_to_run_retry(self):
pub_sub_calls = self.mock_pub_sub()
run_result = self._quick_reap(
1,
0,
pubsub_topic='projects/abc/topics/def',
task_slices=[
task_request.TaskSlice(
expiration_secs=600,
properties=_gen_properties(idempotent=True),
wait_... | |
<filename>Empirical_Roofline_Tool-1.1.0/Python/ert_core.py
import sys,operator,subprocess,os,glob,filecmp,math
import socket,platform,time,json,optparse,ast
from ert_utils import *
def text_list_2_string(text_list):
return reduce(operator.add,[t+" " for t in text_list])
class ert_core:
def __init__(self):
self.e... | |
<reponame>bentley/tools<filename>se/spelling.py
#!/usr/bin/env python3
"""
Defines various spelling-related helper functions.
"""
from pathlib import Path
from pkg_resources import resource_filename
import regex
import se
DICTIONARY = [] # Store our hyphenation dictionary so we don't re-read the file on every pass
... | |
#
# Copyright (c) 2014 NORDUnet A/S
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and th... | |
self.colors.keys():
cr = Color(c, v, p.get_shades())
cr.default = p.get_core_shade()
self._colors[c] = cr
self.log.info(
f"Color '{c}' extracted from '{p.get_palette_name()}'")
self.log.info(f"Total of {len(self.colors) - previous} new colors "
f"added to the current color list")
def _extract(self, name: str)... | |
without extension
# NOTE: not compatible with use of the -i option
xtitle_filename = os.path.split(xfile)[1]
xtitle_filename = os.path.splitext(xtitle_filename)[0]
logging.info('Title:[%s]', NP.strunicodeout(xtitle_filename))
# For each pic found on Flickr 1st check title and then Sets
pic_index = 0
for pic in ... | |
bool = False,
modules_query: Optional[Tuple[str, str]] = None,
extensions_ver: Optional[str] = None,
architectures_ver: Optional[str] = None,
archives_query: Optional[List[str]] = None,
tool_name: Optional[str] = None,
is_long_listing: bool = False,
):
"""
Construct MetadataFactory.
:param spec: When set, th... | |
<reponame>ChameleonCloud/portal<filename>tas/forms.py
import re
from django import forms
import logging
from pytas.http import TASClient
logger = logging.getLogger(__name__)
ELIGIBLE = "Eligible"
INELIGIBLE = "Ineligible"
REQUESTED = "Requested"
PI_ELIGIBILITY = (
("", "Choose One"),
(ELIGIBLE, ELIGIBLE),
(INELI... | |
return resp["router"]
@atomic.action_timer("neutron.show_router")
def get_router(self, router_id, fields=_NONE):
"""Get router details
:param router_id: Router ID
:param fields: The fields that you want the server to return. If no
fields list is specified, the networking API returns all
attributes allowed by t... | |
<filename>frmod/analysis.py
"""
Frequency ratio model analysis.
Perform a landslide susceptibility analysis with the frequency ratio method.
@author: <NAME>
"""
import os
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import frmod.utils as utils
def get_freq_ratios_classic(vr,
mask,
bin... | |
import pytest
from helpers.cluster import ClickHouseCluster
from helpers.test_tools import TSV
import re
cluster = ClickHouseCluster(__file__)
instance = cluster.add_instance('instance')
@pytest.fixture(scope="module", autouse=True)
def start_cluster():
try:
cluster.start()
instance.query("CREATE DATABASE test"... | |
effective_at: str
:param as_at: The asAt datetime at which to retrieve the person's relations. Defaults to return the latest LUSID AsAt time if not specified.
:type as_at: datetime
:param filter: Expression to filter the relations. Users should provide null or empty string for this field until further notice.
:type... | |
<gh_stars>0
#!/usr/bin/env python
# coding=utf-8
import base64
import os
import re
import time
import datetime
import hashlib
import string
import random
import pickle
import zlib
import math
from google.appengine.ext import webapp
from google.appengine.api import memcache
from google.appengine.api import urlfetch
fr... | |
len(seqs) == 1, seqs
assert seqs[0].startswith('GGTTGACGGGGCTCAGGGGG')
def test_screed_streaming_ufq():
# uncompressed fq
o = execute_streaming_diginorm(utils.get_test_data('test-fastq-reads.fq'))
seqs = [r.sequence for r in screed.open(o)]
assert seqs[0].startswith('CAGGCGCCCACCACCGTGCCCTCCAACCTGATGGT')
def ... | |
True
dirLen = len(dir)
# this skips all of /var/lib/conarydb/
for (dirName, dirNameList, pathNameList) in os.walk(dir):
for path in pathNameList:
if path[0] == ".": continue
fullPath = dirName[dirLen:] + "/" + path
if fullPath == "/var/log/conary": continue
if fullPath.startswith("/var/lib/conarydb/"): contin... | |
<reponame>emailweixu/XWorld
"""
Copyright (c) 2017 Baidu Inc. 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 b... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.