text stringlengths 232 16.3k | domain stringclasses 1
value | difficulty stringclasses 3
values | meta dict |
|---|---|---|---|
<|fim_suffix|> idx2=np.zeros((1,np.shape(idx1)[1]))
idx2[0,0:np.shape(idx1)[1]-1] = idx1[0,1:np.shape(idx1)[1]]
TFmat = np.zeros((7,7))
for i in range(0,np.shape(idx1)[1]):
TFmat[int(idx1[0,i])-1,int(idx2[0,i])-1] = TFmat[int(idx1[0,i])-1,int(idx2[0,i])-1]+1
TPmat=TFmat/np.sha... | code_fim | hard | {
"lang": "python",
"repo": "neil-n-zhang/ABRS",
"path": "/ABRS_behavior_analysis.py",
"mode": "spm",
"license": "BSD-2-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: iskandr/parakeet path: /test/algorithms/test_matmult_loops.py
import numpy as np
from parakeet import jit
from parakeet.testing_helpers import run_local_tests, expect
<|fim_suffix|> m,d = X.shape
n = Y.shape[1]
for i in range(m):
for j in range(n):
total = 0
... | code_fim | medium | {
"lang": "python",
"repo": "iskandr/parakeet",
"path": "/test/algorithms/test_matmult_loops.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> for X in matrices:
for Y in matrices:
res = np.dot(X, Y.T)
Z = np.zeros(res.shape, dtype = res.dtype)
expect(mm_loops, [X,Y.T,Z], res)
if __name__ == "__main__":
run_local_tests()<|fim_prefix|># repo: iskandr/parakeet path: /test/algorithms/test_matmult_loops.py
import nu... | code_fim | hard | {
"lang": "python",
"repo": "iskandr/parakeet",
"path": "/test/algorithms/test_matmult_loops.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> for i in range(m):
for j in range(n):
total = 0
for k in range(d):
total += X[i,k] * Y[k,j]
Z[i,j] = total
return Z
def test_matmult_loops():
for X in matrices:
for Y in matrices:
res = np.dot(X, Y.T)
Z = np.zeros(res.shape, dtype =... | code_fim | medium | {
"lang": "python",
"repo": "iskandr/parakeet",
"path": "/test/algorithms/test_matmult_loops.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> Parameters
----------
username : str
The username
password : str
The password
"""
# server = "cfcsql17.gs.umt.edu"
server = "fcfc-sql.cfc.umt.edu"
database = 'MCOMesonet'
params = urllib.parse.quote_plus('DRIVER={ODBC Driver 17 for SQL Server};SERVER='... | code_fim | medium | {
"lang": "python",
"repo": "mt-climate-office/mesonet-db-python",
"path": "/build/lib/mesonet/connect.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: mt-climate-office/mesonet-db-python path: /build/lib/mesonet/connect.py
"""Connect to the Montana Mesonet database
This module uses sqlalchemy to connect to the MT Mesonet database via
a username and password, and to create an optimized engine for the connection.
This script requires that `sqla... | code_fim | medium | {
"lang": "python",
"repo": "mt-climate-office/mesonet-db-python",
"path": "/build/lib/mesonet/connect.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> params = urllib.parse.quote_plus('DRIVER={ODBC Driver 17 for SQL Server};SERVER=' + server +
';DATABASE=' + database +
';UID=' + username +
';PWD=' + password)
return sqlalchemy.create_e... | code_fim | hard | {
"lang": "python",
"repo": "mt-climate-office/mesonet-db-python",
"path": "/build/lib/mesonet/connect.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>def desaturated_randcol(saturation,brightness=100):
"""Returns a random color that is guaranteed to have low-ish saturation.
Brightness of output is ceiling-ed at 253 to contrast with pure white,
and floor-ed at 40 to contrast with pure black (outlines of sprites etc.)
The 'satura... | code_fim | hard | {
"lang": "python",
"repo": "pcred566/Dragon-Breeder",
"path": "/colutils.py",
"mode": "spm",
"license": "Zlib",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: pcred566/Dragon-Breeder path: /colutils.py
from sge import gfx
from sge.gfx import Sprite,Color
from random import randint,choice
FPS = 64
w = 360 # convenience, width of window
h = 240 # convenience, height of window
def clamp(num,start,end):
"""Returns 'num' if num >= start and num <= end... | code_fim | hard | {
"lang": "python",
"repo": "pcred566/Dragon-Breeder",
"path": "/colutils.py",
"mode": "psm",
"license": "Zlib",
"source": "the-stack-v2"
} |
<|fim_suffix|> return gfx.Color(tuple(col))
def pastel_randcol():
"""Returns a random color that is guaranteed to have low saturation
and high brightness like a pastel color."""
# begin with saturated then desaturate
col = saturated_randcol()
offset = 175
for i in range(3):
i... | code_fim | medium | {
"lang": "python",
"repo": "pcred566/Dragon-Breeder",
"path": "/colutils.py",
"mode": "spm",
"license": "Zlib",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: basement-tech/Monitoring-zimKnives path: /code/RaspPi/MonitoringParameters.py
# MonitoringParameters.py
#
# Organize the data for the Monitoring_zimKnives project.
#
# ACKNOWLEDGEMENT:
# I have benefitted greatly from many more experienced python developers
# than I can keep track of. So, ... | code_fim | hard | {
"lang": "python",
"repo": "basement-tech/Monitoring-zimKnives",
"path": "/code/RaspPi/MonitoringParameters.py",
"mode": "psm",
"license": "LicenseRef-scancode-warranty-disclaimer",
"source": "the-stack-v2"
} |
<|fim_suffix|> # local control of the light (usually automatic)
self.light = Parm("light", False, False, "t/f", "00:00:00", Parm.PUB, "zk-env/light", False, False, self.write_pin, conf["SSR_PIN"], GPIO.OUT)
# automatic override indicator
self.ovrled = Parm("ovrled", False,... | code_fim | hard | {
"lang": "python",
"repo": "basement-tech/Monitoring-zimKnives",
"path": "/code/RaspPi/MonitoringParameters.py",
"mode": "spm",
"license": "LicenseRef-scancode-warranty-disclaimer",
"source": "the-stack-v2"
} |
<|fim_suffix|> def display_parameters(self):
""" for debugging, display all parameter values """
self.logging.debug("============")
for attr in self.parm_list:
self.logging.debug(attr.label + " (" + attr.when + ")" + " = " + str(attr.value))
self.logging.debug("==========... | code_fim | hard | {
"lang": "python",
"repo": "basement-tech/Monitoring-zimKnives",
"path": "/code/RaspPi/MonitoringParameters.py",
"mode": "spm",
"license": "LicenseRef-scancode-warranty-disclaimer",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: drewsp7/blog path: /2014-01-30-founder-experience/API_scripts/get_all_people.py
def get_all_people():
conn = sqlite3.connect('crunchbase.db')
cursor = conn.cursor()
<|fim_suffix|> people = []
for p in ppl:
people.append(p[0])
return people<|fim_middle|> cur... | code_fim | medium | {
"lang": "python",
"repo": "drewsp7/blog",
"path": "/2014-01-30-founder-experience/API_scripts/get_all_people.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> conn.close()
people = []
for p in ppl:
people.append(p[0])
return people<|fim_prefix|># repo: drewsp7/blog path: /2014-01-30-founder-experience/API_scripts/get_all_people.py
def get_all_people():
conn = sqlite3.connect('crunchbase.db')
cursor = conn.cursor()
... | code_fim | medium | {
"lang": "python",
"repo": "drewsp7/blog",
"path": "/2014-01-30-founder-experience/API_scripts/get_all_people.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def __str__(self):
return "{0} (${1})".format(self.Nombre, self.Precio)
class Reservacion(models.Model):
cliente = models.ForeignKey(Cliente, null = False, blank = False, on_delete = models.CASCADE)
habitacion = models.ForeignKey(Habitacion, null = False, blank = False, on_delete = mo... | code_fim | hard | {
"lang": "python",
"repo": "Jonathan-aguilar/DAS_Sistemas",
"path": "/Ago-Dic-2017/Cuauhtémoc Martínez/Ordinario/ResHotel/apps/hotel/models.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Jonathan-aguilar/DAS_Sistemas path: /Ago-Dic-2017/Cuauhtémoc Martínez/Ordinario/ResHotel/apps/hotel/models.py
from django.db import models
# Create your models here.
class Cliente(models.Model):
Nombre = models.CharField(max_length = 35)
ApellidoPaterno = models.CharField(max_length = 3... | code_fim | hard | {
"lang": "python",
"repo": "Jonathan-aguilar/DAS_Sistemas",
"path": "/Ago-Dic-2017/Cuauhtémoc Martínez/Ordinario/ResHotel/apps/hotel/models.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: hmeine/qimage2ndarray path: /test/test_qimage_views.py
import qimage2ndarray
from qimage2ndarray.dynqt import QtGui, QImage_Format
from compat import setColorCount, sizeInBytes
# Format_Indexed8 = 3
def test_raw_indexed8():
qimg = QtGui.QImage(320, 240, QImage_Format.Format_Indexed8)
s... | code_fim | hard | {
"lang": "python",
"repo": "hmeine/qimage2ndarray",
"path": "/test/test_qimage_views.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|>
def test_byte_view_indexed():
qimg = QtGui.QImage(320, 240, QImage_Format.Format_Indexed8)
setColorCount(qimg, 256)
v = qimage2ndarray.byte_view(qimg)
qimg.fill(23)
qimg.setPixel(12, 10, 42)
assert v.shape == (240, 320, 1)
assert list(v[10, 10]) == [23]
assert list(v[10, 1... | code_fim | hard | {
"lang": "python",
"repo": "hmeine/qimage2ndarray",
"path": "/test/test_qimage_views.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Haibarayu/Wu-Qing-couplet path: /show_rule/char_to_char.py
import numpy as np
import pickle
import json
class CharToChar:
# ——————字的词性一致—————— #
json_dict = open('show_rule/data/dict.json', encoding='utf-8').read()
dict = json.loads(json_dict)
word2id = {}
for k in dict:
... | code_fim | hard | {
"lang": "python",
"repo": "Haibarayu/Wu-Qing-couplet",
"path": "/show_rule/char_to_char.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> sim = []
for idx, ch in enumerate(first):
vector_f = self.char_embedding[self.char_dict.get(first[idx])]
vector_s = self.char_embedding[self.char_dict.get(second[idx])]
sim.append(self.cos(vector_f, vector_s))
# print(sim)
return sim
... | code_fim | hard | {
"lang": "python",
"repo": "Haibarayu/Wu-Qing-couplet",
"path": "/show_rule/char_to_char.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> '''字字相对'''
def char_to_char(self, first, second):
pos = self.part_of_speech(first, second)
sim = self.char_cos(first, second)
word_ctc = []
for idx, ch in enumerate(first):
word_ctc.append(pos[idx] * 0.4 + sim[idx] * 0.6)
# print(word_ctc)
... | code_fim | hard | {
"lang": "python",
"repo": "Haibarayu/Wu-Qing-couplet",
"path": "/show_rule/char_to_char.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: deergoose/BasicSR path: /codes/data/dstl_dataset/dataset.py
import cv2
from glob import glob
import numpy as np
import os
#import pandas as pd
import torch
import torch.utils.data as data
from data.dstl_dataset.image_data import ImageData
from data.dstl_dataset.preprocess_utils import adjust_siz... | code_fim | hard | {
"lang": "python",
"repo": "deergoose/BasicSR",
"path": "/codes/data/dstl_dataset/dataset.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> return {
'LR': torch.from_numpy(np.ascontiguousarray(
np.transpose(image_lr, (2, 0, 1)))).float(),
'HR': torch.from_numpy(np.ascontiguousarray(
np.transpose(image, (2, 0, 1)))).float()
}
def __len__(self):
return self.to... | code_fim | hard | {
"lang": "python",
"repo": "deergoose/BasicSR",
"path": "/codes/data/dstl_dataset/dataset.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> def __len__(self):
return self.total_imgs * 679 # number of patches
def _transform_labels(label):
# Reduce the dimension of label classes.
label[:, :, 0] = label[:, :, 0] + label[:, :, 1]
label[:, :, 1] = label[:, :, 2] + label[:, :, 3]
label[:, :, 2] = label[:, :, 4]
lab... | code_fim | hard | {
"lang": "python",
"repo": "deergoose/BasicSR",
"path": "/codes/data/dstl_dataset/dataset.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: esc/bloscpack path: /test/test_file_io.py
# -*- coding: utf-8 -*-
# vim :set ft=py:
from __future__ import print_function
import blosc
import pytest
from unittest.mock import patch
import numpy as np
from bloscpack.args import (BloscArgs,
BloscpackArgs,
... | code_fim | hard | {
"lang": "python",
"repo": "esc/bloscpack",
"path": "/test/test_file_io.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> test_metadata = {'dtype': 'float64',
'shape': [1024],
'others': [],
}
received_metadata = pack_unpack_fp(1, metadata=test_metadata)
assert test_metadata == received_metadata
def test_metadata_opportunisitic_compression():
# m... | code_fim | hard | {
"lang": "python",
"repo": "esc/bloscpack",
"path": "/test/test_file_io.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> def does_move_win(self, x, y):
"""
Checks whether a newly dropped chip at position param x, param y
wins the game.
:param x: column index
:param y: row index
:returns: (boolean) True if the previous move has won the game
"""
me = self.boa... | code_fim | hard | {
"lang": "python",
"repo": "ColdFrenzy/gym-connect4",
"path": "/gym_connect4/envs/connect4_env.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def is_on_board(self, x, y):
return x >= 0 and x < self.width and y >= 0 and y < self.height
def get_result(self, player):
"""
:param player: (int) player which we want to see if he / she is a winner
:returns: winner from the perspective of the param player
... | code_fim | hard | {
"lang": "python",
"repo": "ColdFrenzy/gym-connect4",
"path": "/gym_connect4/envs/connect4_env.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: ColdFrenzy/gym-connect4 path: /gym_connect4/envs/connect4_env.py
from typing import List
from copy import deepcopy
import numpy as np
import gym
from gym.spaces import Box, Discrete, Tuple
from colorama import Fore
class Connect4Env(gym.Env):
"""
GameState for the Connect 4 game.
... | code_fim | hard | {
"lang": "python",
"repo": "ColdFrenzy/gym-connect4",
"path": "/gym_connect4/envs/connect4_env.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: ruscur/FFPR_Speedhack path: /ffpr_speedhack.py
#!/usr/bin/env python3
from capstone import *
from capstone.x86 import *
import pefile
import sys
AUTOBATTLE_FLAG_MARKER = b"\x0f\xb6\x40\x19\xc3"
SPEED_TO_HEX = {"1.5x": b"\x00\x00\xc0\x3f",
"2x": b"\x00\x00\x00\40",
... | code_fim | hard | {
"lang": "python",
"repo": "ruscur/FFPR_Speedhack",
"path": "/ffpr_speedhack.py",
"mode": "psm",
"license": "Unlicense",
"source": "the-stack-v2"
} |
<|fim_suffix|>print()
if autobattle_response == "y" and always_fast == False:
print("Replacing test al,al with cmp al,0xff...")
pe.set_bytes_at_rva(test.address, b"\x3c\xff")
always_fast = True
elif autobattle_response == "n" and always_fast == True:
print("Replacing cmp al,0xff with test al,al...")
... | code_fim | hard | {
"lang": "python",
"repo": "ruscur/FFPR_Speedhack",
"path": "/ffpr_speedhack.py",
"mode": "spm",
"license": "Unlicense",
"source": "the-stack-v2"
} |
<|fim_suffix|>print()
autobattle_response = None
while autobattle_response not in ["y", "n"]:
autobattle_response = input("Do you want your battles to always have autobattle speed? [y/n]: ")
print("\nYour game currently has autobattle speed %s." % autobattle_speed)
print()
speed_response = None
while speed_respons... | code_fim | hard | {
"lang": "python",
"repo": "ruscur/FFPR_Speedhack",
"path": "/ffpr_speedhack.py",
"mode": "spm",
"license": "Unlicense",
"source": "the-stack-v2"
} |
<|fim_suffix|>class M(Model[List[int], int]):
def _predict(self, item):
return sum(item)<|fim_prefix|># repo: pquentin/modelkit path: /tests/testdata/typing/predict_list.py
from typing import List
<|fim_middle|>from modelkit.core.model import Model
| code_fim | easy | {
"lang": "python",
"repo": "pquentin/modelkit",
"path": "/tests/testdata/typing/predict_list.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: pquentin/modelkit path: /tests/testdata/typing/predict_list.py
from typing import List
<|fim_suffix|> return sum(item)<|fim_middle|>from modelkit.core.model import Model
class M(Model[List[int], int]):
def _predict(self, item):
| code_fim | medium | {
"lang": "python",
"repo": "pquentin/modelkit",
"path": "/tests/testdata/typing/predict_list.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> return sum(item)<|fim_prefix|># repo: pquentin/modelkit path: /tests/testdata/typing/predict_list.py
from typing import List
from modelkit.core.model import Model
<|fim_middle|>
class M(Model[List[int], int]):
def _predict(self, item):
| code_fim | medium | {
"lang": "python",
"repo": "pquentin/modelkit",
"path": "/tests/testdata/typing/predict_list.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: CybernetiX-S3C/Dshell path: /dshell/plugins/flows/longflows.py
"""
Displays netflows that have a duration of at least 5 minutes.
Minute threshold can be updated by the user.
"""
import dshell.core
from dshell.output.netflowout import NetflowOutput
class DshellPlugin(dshell.core.ConnectionPlugin... | code_fim | hard | {
"lang": "python",
"repo": "CybernetiX-S3C/Dshell",
"path": "/dshell/plugins/flows/longflows.py",
"mode": "psm",
"license": "LicenseRef-scancode-warranty-disclaimer",
"source": "the-stack-v2"
} |
<|fim_suffix|> tdelta = (conn.endtime - conn.starttime).total_seconds()
if tdelta >= self.secs:
self.write(**conn.info())
return conn<|fim_prefix|># repo: CybernetiX-S3C/Dshell path: /dshell/plugins/flows/longflows.py
"""
Displays netflows that have a duration of at least 5 minut... | code_fim | hard | {
"lang": "python",
"repo": "CybernetiX-S3C/Dshell",
"path": "/dshell/plugins/flows/longflows.py",
"mode": "spm",
"license": "LicenseRef-scancode-warranty-disclaimer",
"source": "the-stack-v2"
} |
<|fim_suffix|> _DISPENSER.__init__(self)
self.name = "DISPENSERS"
self.specie = 'nouns'
self.basic = "dispenser"
self.jsondata = {}<|fim_prefix|># repo: cash2one/xai path: /xai/brain/wordbase/nouns/_dispensers.py
from xai.brain.wordbase.nouns._dispenser import _DISPENSER
#calss header
class _DISPENSERS(_DI... | code_fim | easy | {
"lang": "python",
"repo": "cash2one/xai",
"path": "/xai/brain/wordbase/nouns/_dispensers.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: cash2one/xai path: /xai/brain/wordbase/nouns/_dispensers.py
from xai.brain.wordbase.nouns._dispenser import _DISPENSER
<|fim_suffix|> def __init__(self,):
_DISPENSER.__init__(self)
self.name = "DISPENSERS"
self.specie = 'nouns'
self.basic = "dispenser"
self.jsondata = {}<|fim_middle... | code_fim | easy | {
"lang": "python",
"repo": "cash2one/xai",
"path": "/xai/brain/wordbase/nouns/_dispensers.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> if isinstance(rv, ApiResponse):
return rv.to_response()
return Flask.make_response(self, rv)
def create_app() -> ApiFlask:
app = ApiFlask(__name__)
return app<|fim_prefix|># repo: Sketchy502/flask-api-template path: /application/app.py
from flask import Flask, Respo... | code_fim | easy | {
"lang": "python",
"repo": "Sketchy502/flask-api-template",
"path": "/application/app.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: Sketchy502/flask-api-template path: /application/app.py
from flask import Flask, Response
from application.responses import ApiResponse
class ApiFlask(Flask):
<|fim_suffix|>def create_app() -> ApiFlask:
app = ApiFlask(__name__)
return app<|fim_middle|> def make_response(self, rv) -... | code_fim | medium | {
"lang": "python",
"repo": "Sketchy502/flask-api-template",
"path": "/application/app.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>def create_app() -> ApiFlask:
app = ApiFlask(__name__)
return app<|fim_prefix|># repo: Sketchy502/flask-api-template path: /application/app.py
from flask import Flask, Response
from application.responses import ApiResponse
<|fim_middle|>
class ApiFlask(Flask):
def make_response(self, rv) -... | code_fim | medium | {
"lang": "python",
"repo": "Sketchy502/flask-api-template",
"path": "/application/app.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: dwavesystems/dimod path: /tests/test_trackingcomposite.py
# Copyright 2019 D-Wave Systems Inc.
#
# 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:... | code_fim | hard | {
"lang": "python",
"repo": "dwavesystems/dimod",
"path": "/tests/test_trackingcomposite.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> def test_sample_ising(self):
sampler = dimod.TrackingComposite(dimod.ExactSolver())
h0 = {'a': -1}
J0 = {('a', 'b'): -1}
ss0 = sampler.sample_ising(h0, J0)
h1 = {'b': -1}
J1 = {('b', 'c'): 2}
ss1 = sampler.sample_ising(h1, J1)
self.ass... | code_fim | hard | {
"lang": "python",
"repo": "dwavesystems/dimod",
"path": "/tests/test_trackingcomposite.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> self.assertEqual(sampler.input, dict(h=h1, J=J1))
self.assertEqual(sampler.output, ss1)
self.assertEqual(sampler.inputs, [dict(h=h0, J=J0), dict(h=h1, J=J1)])
self.assertEqual(sampler.outputs, [ss0, ss1])
def test_sample_ising_copy_true(self):
sampler = dimod.... | code_fim | hard | {
"lang": "python",
"repo": "dwavesystems/dimod",
"path": "/tests/test_trackingcomposite.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: smh87/Bachelor_p6 path: /P6-HAR-DataSeg-main/PreProcessIMSHA.py
import os
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler, LabelEncoder
from dotenv import load_dotenv
def preprocess2():
load_dotenv()
filepath = os... | code_fim | hard | {
"lang": "python",
"repo": "smh87/Bachelor_p6",
"path": "/P6-HAR-DataSeg-main/PreProcessIMSHA.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> #Standardize data
scaler = StandardScaler()
temp_X = pd.DataFrame()
temp_X = read_dataframes[f"subject_{j}"][['feature0','feature1','feature2','feature3','feature4','feature5','feature6','feature7','feature8',
'feature9','feature10','feature11',
'feature12','feature... | code_fim | hard | {
"lang": "python",
"repo": "smh87/Bachelor_p6",
"path": "/P6-HAR-DataSeg-main/PreProcessIMSHA.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> self.assertFalse(lr_node(1, 1) in self.test_graph)
self.test_graph.add_node(lr_node(1, 1))
self.assertTrue(lr_node(1, 1) in self.test_graph)
def test_add_edge(self):
self.assertFalse(lr_node(1, 1) in self.test_graph)
self.assertFalse(lr_node(1, 2) in self.test_... | code_fim | medium | {
"lang": "python",
"repo": "alexander-bzikadze/graph_diff",
"path": "/tests/graph/test_graph_with_repetitive_nodes_with_root.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: alexander-bzikadze/graph_diff path: /tests/graph/test_graph_with_repetitive_nodes_with_root.py
import unittest
from graph_diff.graph import rnr_graph, lr_node
from graph_diff.graph.graph_with_repetitive_nodes_exceptions import GraphWithRepetitiveNodesKeyError
class GraphWithRepetitiveNodesWith... | code_fim | hard | {
"lang": "python",
"repo": "alexander-bzikadze/graph_diff",
"path": "/tests/graph/test_graph_with_repetitive_nodes_with_root.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> self.assertFalse(lr_node(1, 1) in self.test_graph)
self.assertFalse(lr_node(1, 2) in self.test_graph)
self.assertRaises(GraphWithRepetitiveNodesKeyError,
self.test_graph.add_edge_exp,
lr_node(1, 1),
lr_no... | code_fim | hard | {
"lang": "python",
"repo": "alexander-bzikadze/graph_diff",
"path": "/tests/graph/test_graph_with_repetitive_nodes_with_root.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> def predict(self, temp_type='separated'):
"""
Transpile the predict method.
Parameters
----------
:param temp_type : string
The kind of export type (embedded, separated, exported).
Returns
-------
:return : string
... | code_fim | hard | {
"lang": "python",
"repo": "jonaphin/sklearn-porter",
"path": "/sklearn_porter/estimator/classifier/DecisionTreeClassifier/__init__.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: jonaphin/sklearn-porter path: /sklearn_porter/estimator/classifier/DecisionTreeClassifier/__init__.py
# -*- coding: utf-8 -*-
import os
from json import encoder
from json import dumps
from sklearn_porter.estimator.classifier.Classifier import Classifier
class DecisionTreeClassifier(Classifie... | code_fim | hard | {
"lang": "python",
"repo": "jonaphin/sklearn-porter",
"path": "/sklearn_porter/estimator/classifier/DecisionTreeClassifier/__init__.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> """
Save model data in a JSON file.
Parameters
----------
:param directory : string
The directory.
:param filename : string
The filename.
:param with_md5_hash : bool, default: False
Whether to append the checksum ... | code_fim | hard | {
"lang": "python",
"repo": "jonaphin/sklearn-porter",
"path": "/sklearn_porter/estimator/classifier/DecisionTreeClassifier/__init__.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> # Check for last letter
if len(current_occurrence) == 2 and two_count == False:
two_occurrence += 1
current_occurrence = []
elif len(current_occurrence) == 3 and three_count == False:
three_occurrence += 1
current_occurrence = []
prin... | code_fim | hard | {
"lang": "python",
"repo": "julianschmuckli/adventofcode_2018",
"path": "/Day 2/task1.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: julianschmuckli/adventofcode_2018 path: /Day 2/task1.py
input = open("input.txt", "r").read()
boxes = input.split("\n")
two_occurrence = 0
three_occurrence = 0
for box in boxes:
letters = list(box)
if len(letters) != 0:
letters.sort()
previous_letter = ''
curren... | code_fim | hard | {
"lang": "python",
"repo": "julianschmuckli/adventofcode_2018",
"path": "/Day 2/task1.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>sfile: The actual classes that perform the transformations
"""<|fim_prefix|># repo: sdilts/cl-bindgen path: /cl_bindgen/__init__.py
""" A Library for generating common lisp bindings from C header files
Provides the following modules:
+ manglers: A set of c<|fim_middle|>lasses for transforming C names i... | code_fim | medium | {
"lang": "python",
"repo": "sdilts/cl-bindgen",
"path": "/cl_bindgen/__init__.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: sdilts/cl-bindgen path: /cl_bindgen/__init__.py
""" A Library for generating common lisp bindings from C header files
Provides the following modules:
+ manglers: A set of c<|fim_suffix|>sfile: The actual classes that perform the transformations
"""<|fim_middle|>lasses for transforming C names i... | code_fim | medium | {
"lang": "python",
"repo": "sdilts/cl-bindgen",
"path": "/cl_bindgen/__init__.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: joodo/loser-fan path: /contrib/fanfouapi/management/commands/posturl.py
from django.core.management.base import BaseCommand
from django.conf import settings
import sys, urllib, re
from fanfouapi import oauth, auth, api
from urllib2 import Request, urlopen
from urlparse import urljoin
import getp... | code_fim | medium | {
"lang": "python",
"repo": "joodo/loser-fan",
"path": "/contrib/fanfouapi/management/commands/posturl.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> print 'getting url', url, '...'
req = Request(url, None, headers={'User-Agent': USER_AGENT})
resp = urlopen(req, None, 30)
info = resp.info()
charset = info.getparam('charset')
if charset is None:
charset = 'utf-8'
charset = charset.lower... | code_fim | medium | {
"lang": "python",
"repo": "joodo/loser-fan",
"path": "/contrib/fanfouapi/management/commands/posturl.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: featness/featness path: /featness/models/team.py
from mongoengine import Document, StringField, ListField, ReferenceField
from featness.models.user import User
class Team(Document):
<|fim_suffix|> return "Team %s" % self.name<|fim_middle|> name = StringField(required=True)
slug = ... | code_fim | medium | {
"lang": "python",
"repo": "featness/featness",
"path": "/featness/models/team.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> return "Team %s" % self.name<|fim_prefix|># repo: featness/featness path: /featness/models/team.py
from mongoengine import Document, StringField, ListField, ReferenceField
from featness.models.user import User
<|fim_middle|>class Team(Document):
name = StringField(required=True)
slug = ... | code_fim | hard | {
"lang": "python",
"repo": "featness/featness",
"path": "/featness/models/team.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: stjordanis/gnes path: /gnes/indexer/base.py
# Tencent is pleased to support the open source community by making GNES available.
#
# Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use t... | code_fim | hard | {
"lang": "python",
"repo": "stjordanis/gnes",
"path": "/gnes/indexer/base.py",
"mode": "psm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|>
class BaseDocIndexer(BaseIndexer):
"""Storing documents and contents """
def add(self, keys: List[int], docs: List['gnes_pb2.Document'], *args, **kwargs):
"""
adding new docs and their protobuf representation
:param keys: list of doc_id
:param docs: list of proto... | code_fim | hard | {
"lang": "python",
"repo": "stjordanis/gnes",
"path": "/gnes/indexer/base.py",
"mode": "spm",
"license": "BSD-3-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|> def setUp(self):
pass
def tearDown(self):
pass
def _get_random_file(self, path):
'''
Gets a random file from the directory defined in the path variable.
'''
return random.choice(os.listdir(path=path))
if __name__ == "__main__":
#i... | code_fim | medium | {
"lang": "python",
"repo": "derigible/project-builder",
"path": "/tests/base_test.py",
"mode": "spm",
"license": "BSD-2-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: derigible/project-builder path: /tests/base_test.py
__doc__ = '''
Created on Feb 8, 2015
@author: derigible
This class is for common test case inheritance. This class will be built over time.
'''
import unittest, os, random
class BaseTest(unittest.TestCase):
# Used to point the TestCase ... | code_fim | hard | {
"lang": "python",
"repo": "derigible/project-builder",
"path": "/tests/base_test.py",
"mode": "psm",
"license": "BSD-2-Clause",
"source": "the-stack-v2"
} |
<|fim_suffix|>if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.main()<|fim_prefix|># repo: derigible/project-builder path: /tests/base_test.py
__doc__ = '''
Created on Feb 8, 2015
@author: derigible
This class is for common test case inheritance. This class will be built over ... | code_fim | medium | {
"lang": "python",
"repo": "derigible/project-builder",
"path": "/tests/base_test.py",
"mode": "spm",
"license": "BSD-2-Clause",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: nishanthpp93/curation path: /tests/unit_tests/data_steward/admin/admin_api_test.py
import os
import mock
import unittest
from mock import patch
from slack.errors import SlackClientError
from admin import admin_api
class AdminApiTest(unittest.TestCase):
@classmethod
def setUpClass(cls... | code_fim | hard | {
"lang": "python",
"repo": "nishanthpp93/curation",
"path": "/tests/unit_tests/data_steward/admin/admin_api_test.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> """
mock_delete_expired_keys.side_effect = [
self.expired_keys, self.expired_keys, []
]
mock_get_expiring_keys.side_effect = [
self.expiring_keys, [], self.expiring_keys
]
full_body = admin_api.text_body(self.expired_keys, self.expiri... | code_fim | hard | {
"lang": "python",
"repo": "nishanthpp93/curation",
"path": "/tests/unit_tests/data_steward/admin/admin_api_test.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> @mock.patch('admin.admin_api.post_message')
@mock.patch('admin.key_rotation.get_expiring_keys')
@mock.patch('admin.key_rotation.delete_expired_keys')
@mock.patch('api_util.check_cron')
def test_client_errors_raised(self, mock_check_cron,
mock_delete_ex... | code_fim | hard | {
"lang": "python",
"repo": "nishanthpp93/curation",
"path": "/tests/unit_tests/data_steward/admin/admin_api_test.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: zxyf/django-qcloud-cos path: /qcloudcos/cos_object.py
import requests
from qcloudcos.cos_auth import Auth
from django.conf import settings
from utils import get_logger
LOGGER = get_logger('Tencent Cos')
class CosObject(object):
def __init__(self, option=None):
if not option:
... | code_fim | hard | {
"lang": "python",
"repo": "zxyf/django-qcloud-cos",
"path": "/qcloudcos/cos_object.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> r = s.put(url, data=content)
if r.status_code == 200:
return r
else:
LOGGER.info(r.content)
def head_object(self, name, is_private=False):
method = 'head'
appid = self.option['Appid']
SecretID = self.option['SecretID']
Se... | code_fim | hard | {
"lang": "python",
"repo": "zxyf/django-qcloud-cos",
"path": "/qcloudcos/cos_object.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> def delete_object(self, name):
method = 'delete'
appid = self.option['Appid']
SecretID = self.option['SecretID']
SecretKey = self.option['SecretKey']
region = self.option['region']
bucket = self.option['bucket']
if name[0] != '/':
nam... | code_fim | hard | {
"lang": "python",
"repo": "zxyf/django-qcloud-cos",
"path": "/qcloudcos/cos_object.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: PyreWatch/pyrefinder path: /tests/publisher.py
import json
import io
from PIL import Image
import paho.mqtt.publish as publish
if __name__ == "__main__":
## SETUP ##
# creating an image for image sending
image = Image.open("87205_1.jpg")
imgByteArr = io.BytesIO()
image.save... | code_fim | medium | {
"lang": "python",
"repo": "PyreWatch/pyrefinder",
"path": "/tests/publisher.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> # test for status updates where fighter was not in db
publish.single("dt/fighter/bob", status, client_id="bob")
publish.single("dt/fighter/tom", status, client_id="tom")
# test image where file was not detected being sent
publish.single("dt/fighter/bob/nofire_image",
... | code_fim | medium | {
"lang": "python",
"repo": "PyreWatch/pyrefinder",
"path": "/tests/publisher.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> if not os.path.exists('./results/'):
os.mkdir('results')
buff = []
# 先统计有多少图像
total = 0
gif = cv2.VideoCapture('Pani_poni_dash.gif')
while True:
ret, frame = gif.read()
if not ret:
break
total += 1
gif.release()
gif = cv2.VideoCap... | code_fim | hard | {
"lang": "python",
"repo": "chiro2001/pani-poni-dash",
"path": "/process.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> # 最后反色
mask = 255 - mask
img = Image.fromarray(mask, "RGBA")
mask = np.array(img)
mask = cv2.cvtColor(mask, cv2.COLOR_RGBA2GRAY)
_, mask = cv2.threshold(mask, 0, 255, cv2.THRESH_OTSU + cv2.THRESH_BINARY)
return mask
def process(frame: np.ndarray, filename: str) -> np.ndarray:... | code_fim | hard | {
"lang": "python",
"repo": "chiro2001/pani-poni-dash",
"path": "/process.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: chiro2001/pani-poni-dash path: /process.py
import cv2
import os
import numpy as np
from PIL import Image
import imageio
from tqdm import trange
from myCVHelper.my_cv_helper import logger
from myCVHelper import my_cv_helper as helper
# 获取图像外围的空白区域遮罩
def get_block(im: np.ndarray) -> np.ndarray:
... | code_fim | hard | {
"lang": "python",
"repo": "chiro2001/pani-poni-dash",
"path": "/process.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> """Funcion para comprobar si un numero es primo o no"""
primo = True
for i in range(2, num):
if num%i == 0:
primo = False
return primo
n = -1
while n <= 0:
n = input("Introduzca numero mayor que 0: ")
if n <= 0:
print "Error: numero incorrecto. Vuelva a... | code_fim | medium | {
"lang": "python",
"repo": "DarkShadow4/Python",
"path": "/preparación para la olimpiada/numeros defectuosos y que son divisores primo/numeros defectuosos y que son divisores primo.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: DarkShadow4/Python path: /preparación para la olimpiada/numeros defectuosos y que son divisores primo/numeros defectuosos y que son divisores primo.py
def get_divisores(num):
"""Funcion para obtener los divisores del numero dado"""
divisores = [] #uso una lista para guardar los divisores
... | code_fim | hard | {
"lang": "python",
"repo": "DarkShadow4/Python",
"path": "/preparación para la olimpiada/numeros defectuosos y que son divisores primo/numeros defectuosos y que son divisores primo.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|># Test inputformatter class
print("------InputFormatter------")
print(format_1d_int_list("{1, 2, 3}"))
print(format_1d_char_list("{'1', '2', '3'}"))
print(format_2d_int_list("{{1, 2, 3}, {4, 5, 6}}", 2, 3))
print(format_2d_char_list("{{'1', '2', '3'}, {'4', '5', '6'}}", 2, 3))
pretty_print_llist(for... | code_fim | medium | {
"lang": "python",
"repo": "rishi772001/QuickDS",
"path": "/python/QuickDS/test.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|># Test BinarySearchTree class
print("------BST------")
r1 = convert_sorted_list_to_bst([1, 2, 3, 4, 5])
st = serialize(r1)
print(st)
r2 = deserialize(st)
r3 = create_random_binary_search_tree()
pretty_print_bst(r1)
pretty_print_bst(r3)
print_bst(r2)<|fim_prefix|># repo: rishi772001/QuickDS path:... | code_fim | hard | {
"lang": "python",
"repo": "rishi772001/QuickDS",
"path": "/python/QuickDS/test.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: rishi772001/QuickDS path: /python/QuickDS/test.py
"""
@Author: rishi
"""
from QuickDS import *
# Test Linked list class
print("------LinkedList------")
array = [1, 2, 3, 4, 5]
pretty_print_llist(create_linked_list(array))
pretty_print_llist(create_random_linked_list(20))
# Test Lis... | code_fim | hard | {
"lang": "python",
"repo": "rishi772001/QuickDS",
"path": "/python/QuickDS/test.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>Solution:
Hashtable
We can use a hashmap to record the length of LAS which ends at A as dict[A]
If the key 'A - difference' in the dict, it means there is a element in the previous array which can form a LAS with cur element.
So we increment the length, d[A] = d[A-difference] + 1. In the mean while, updat... | code_fim | medium | {
"lang": "python",
"repo": "yanshengjia/algorithm",
"path": "/leetcode/Hash Table/1218. Longest Arithmetic Subsequence of Given Difference.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>Input: arr = [1,5,7,8,5,3,4,2,1], difference = -2
Output: 4
Explanation: The longest arithmetic subsequence is [7,5,3,1].
Solution:
Hashtable
We can use a hashmap to record the length of LAS which ends at A as dict[A]
If the key 'A - difference' in the dict, it means there is a element in the previous a... | code_fim | medium | {
"lang": "python",
"repo": "yanshengjia/algorithm",
"path": "/leetcode/Hash Table/1218. Longest Arithmetic Subsequence of Given Difference.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: yanshengjia/algorithm path: /leetcode/Hash Table/1218. Longest Arithmetic Subsequence of Given Difference.py
"""
Given an integer array arr and an integer difference, return the length of the longest subsequence in arr which is an arithmetic sequence such that the difference between adjacent elem... | code_fim | medium | {
"lang": "python",
"repo": "yanshengjia/algorithm",
"path": "/leetcode/Hash Table/1218. Longest Arithmetic Subsequence of Given Difference.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: samithaj/serving path: /tensorflow_serving/rnn_client/path_formatter.py
import os.path
def format_test_file_string(folder, zone, instance_type, delta):
"""
:param folder: The base folder of the test files
:param zone: The zone of the test file
:param instance_type: The instance ... | code_fim | medium | {
"lang": "python",
"repo": "samithaj/serving",
"path": "/tensorflow_serving/rnn_client/path_formatter.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|>
def format_serving_export_path_string(folder, model_name, zone='', instance_type=''):
"""
:param folder: The base folder of the model exports
:param model_name: The name of the model
:param zone: The zone of the training files
:param instance_type: The instance type of the training fi... | code_fim | hard | {
"lang": "python",
"repo": "samithaj/serving",
"path": "/tensorflow_serving/rnn_client/path_formatter.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: jennifernolan/FYP-Development-Navigation-Assistant path: /Final_Dissertation_Code/Unit_Tests/TestSensorDistance.py
'''
Developer Name: Jennifer Nolan (C16517636)
Program Description: These set of test cases test the detected object distance retrieved by the RangeSensor program.
This program test... | code_fim | hard | {
"lang": "python",
"repo": "jennifernolan/FYP-Development-Navigation-Assistant",
"path": "/Final_Dissertation_Code/Unit_Tests/TestSensorDistance.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def test_short_distance_sensor(self):
distance = get_distance()
print(distance)
if distance < 20:
self.assertTrue(distance < 20)
else:
self.assertFalse(distance < 20)
if __name__ == '__main__':
unittest.main()<|fim_prefix|># rep... | code_fim | hard | {
"lang": "python",
"repo": "jennifernolan/FYP-Development-Navigation-Assistant",
"path": "/Final_Dissertation_Code/Unit_Tests/TestSensorDistance.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def setUp(self):
pass
def tearDown(self):
pass
def test_long_distance_sensor(self):
distance = get_distance()
print(distance)
if distance >= 60:
self.assertTrue(distance >= 60)
else:
self.assertFalse(distance >= ... | code_fim | medium | {
"lang": "python",
"repo": "jennifernolan/FYP-Development-Navigation-Assistant",
"path": "/Final_Dissertation_Code/Unit_Tests/TestSensorDistance.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def add_run(self, run, molecule, hamiltonian, ansatz):
"""Add VQE run to the Results
Parameters
----------
run:
object returned by tq.minimize
molecule : tequila.quantumchemistry.psi4_interface.QuantumChemistryPsi4
molecule used in the r... | code_fim | hard | {
"lang": "python",
"repo": "QuantMarkFramework/LibMark",
"path": "/libmark/result.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: QuantMarkFramework/LibMark path: /libmark/result.py
from abc import ABC, abstractmethod
from tequila.circuit.compiler import Compiler
from datetime import datetime
import tequila as tq
import requests
import json
# Use this (or wherever your local WebMark2 is running) while developing
# url = '... | code_fim | hard | {
"lang": "python",
"repo": "QuantMarkFramework/LibMark",
"path": "/libmark/result.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|>
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('net_name', type=str, help='Name for Sumo network.')
parser.add_argument('num_simulations', type=int,
help='Number of simulations to run.')
parser.add_argument('--trip_end_time', '-te... | code_fim | hard | {
"lang": "python",
"repo": "arsenious/trafficgraphnn",
"path": "/simulation_script.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: arsenious/trafficgraphnn path: /simulation_script.py
import argparse
import os
import numpy as np
from trafficgraphnn.sumo_network import SumoNetwork
from trafficgraphnn.genconfig import ConfigGenerator
from trafficgraphnn.preprocessing.preprocess import run_preprocessing
def main(
net_name... | code_fim | hard | {
"lang": "python",
"repo": "arsenious/trafficgraphnn",
"path": "/simulation_script.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def getUsers(self, name):
try:
existUser = Users.objects.get(name=name)
return existUser
except Exception, e:
return None<|fim_prefix|># repo: QDPeng/PushNotify path: /apps/notification/UserUtil.py
from models import Users
"""the singleton func"""
def singleton(cls, *args, **kw):
in... | code_fim | hard | {
"lang": "python",
"repo": "QDPeng/PushNotify",
"path": "/apps/notification/UserUtil.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: QDPeng/PushNotify path: /apps/notification/UserUtil.py
from models import Users
"""the singleton func"""
def singleton(cls, *args, **kw):
instances = {}
def _singleton():
if cls not in instances:
instances[cls] = cls(*args, **kw)
return instance... | code_fim | hard | {
"lang": "python",
"repo": "QDPeng/PushNotify",
"path": "/apps/notification/UserUtil.py",
"mode": "psm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_suffix|> existUser = self.getUsers(name)
changeDic = dict(changeDic)
print changeDic
if existUser:
for attribute, value in changeDic.iteritems():
setattr(existUser, attribute, value)
existUser.save()
def isInUsers(self, name):
try:
existUser = Users.objects.get(name=name)
return True
... | code_fim | hard | {
"lang": "python",
"repo": "QDPeng/PushNotify",
"path": "/apps/notification/UserUtil.py",
"mode": "spm",
"license": "Apache-2.0",
"source": "the-stack-v2"
} |
<|fim_prefix|># repo: joshuahellier/PhDStuff path: /codes/kmc/steadyStateFlow/ProcessStatistics.py
""" Module for the process statistics analysis plugin """
"""Note that I've had to change this at top level; for some reason things wouldn't hook up properly, I'll work out why later. =S"""
# Copyright (c) 2014 Mikae... | code_fim | hard | {
"lang": "python",
"repo": "joshuahellier/PhDStuff",
"path": "/codes/kmc/steadyStateFlow/ProcessStatistics.py",
"mode": "psm",
"license": "MIT",
"source": "the-stack-v2"
} |
<|fim_suffix|> def setup(self, step, time, configuration):
"""
Recieves the setup call.
"""
# Set the initial time.
self.__last_time = time
self.__initialTime = time
# Allocate space for the spatially resolved information.
typeList = configuration.type... | code_fim | hard | {
"lang": "python",
"repo": "joshuahellier/PhDStuff",
"path": "/codes/kmc/steadyStateFlow/ProcessStatistics.py",
"mode": "spm",
"license": "MIT",
"source": "the-stack-v2"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.