id
stringlengths
2
8
text
stringlengths
16
264k
dataset_id
stringclasses
1 value
1709006
<reponame>mounaiban/padsweb<filename>padsweb/forms.py # # # Public Archive of Days Since Timers # Form Classes # # from django import forms from django.utils import timezone from padsweb.settings import * from padsweb.strings import labels from padsweb.misc import get_timezones_all # Python Beginner's PROTIP: # # Du...
StarcoderdataPython
9665256
import numpy as np import matplotlib.pyplot as plt def sigmoid(val): return 1/(1 + np.exp(-val)) def stable_coeff(alpha_1, alpha_2): a_1 = 2*np.tanh(alpha_1) a_2 = np.abs(a_1) + (2 - np.abs(a_1))*sigmoid(alpha_2) - 1 return a_1, a_2 def roots_polynomial(a_1, a_2): delta = a_1**2 - 4 * a_2 d...
StarcoderdataPython
8055538
from .. import IrccGenerator, IrccType from motor_typing import TYPE_CHECKING _UNSIGNED_VERSIONS = {'i8': 'u8', 'i16': 'u16', 'i32': 'u32', 'i64': 'u64'} class IrccCTypes(IrccGenerator): _VECTOR_TYPES = {} # type: Dict[str, str] def __init__(self, file): # type: (TextIO) -> None IrccGene...
StarcoderdataPython
6584555
<reponame>Zhiyuan-w/DeepReg """Provide helper functions or classes for defining loss or metrics.""" from typing import List, Optional, Union import tensorflow as tf from deepreg.loss.kernel import cauchy_kernel1d from deepreg.loss.kernel import gaussian_kernel1d_sigma as gaussian_kernel1d class MultiScaleMixin(tf....
StarcoderdataPython
3243759
<gh_stars>1-10 from .. import DB_BASE as Base from sqlalchemy import Column, Integer, Sequence, Text class BlogInfoORM(Base): __tablename__ = 'tb_blog_info' __table_args__ = {'comment': '博客简介信息表'} id = Column(Integer, Sequence("tb_blog_info_id_seq"), primary_key=True) about_content = Column(Text, ...
StarcoderdataPython
11370888
# -*- coding: utf-8 -*- import os import numpy as np import statsmodels.api as sm # recommended import according to the docs import matplotlib.pyplot as plt import pandas as pd import scipy.stats.mstats as mstats from common import globals as glob import seaborn as sns sns.set(color_codes=True) from scipy import stats...
StarcoderdataPython
5139914
<reponame>vainotuisk/icecreamratings __version__ = '16.0'
StarcoderdataPython
363050
<filename>challenges/String_Info_Calculator/poller/for-release/machine.py #!/usr/bin/env python # # Copyright (C) 2014 <NAME>ustries <<EMAIL>> # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Softwar...
StarcoderdataPython
8182110
def even_numbers(maximum): return_string = "" for x in range(2, maximum+1, 2): return_string += str(x) + " " return return_string.strip() print(even_numbers(6)) # Should be 2 4 6 print(even_numbers(10)) # Should be 2 4 6 8 10 print(even_numbers(1)) # No numbers displayed print(even_numbers(3)) # Should be 2 pr...
StarcoderdataPython
123877
<reponame>gablin/python-verisure """ A python module for reading and changing status of verisure devices through verisure app API. """ __all__ = [ 'Error', 'LoginError', 'ResponseError', 'Session' ] from .session import ( # NOQA Error, LoginError, ResponseError, Session ) ALARM_ARMED...
StarcoderdataPython
3228726
<gh_stars>1-10 # Transform Bible verse lists into a format that Accordance accepts. import re from romnum import romNumVal from urllib import quote def escapePath(value): return quote(value.encode('utf_8')) def escapeQuery(value): value = value.replace(' ', '_') return quote(value.encode('utf_8'), ':;,._') ...
StarcoderdataPython
5084052
# encoding: utf-8 import numpy as np import tensorflow as tf import os import cv2 from tqdm import tqdm import re import sys sys.path.append('..') from config import cfg def convert(size, box): dw = 1./size[0] dh = 1./size[1] x = (box[0] + box[1])/2.0 y = (box[2] + box[3])/2.0 w = box[1] - box[0] ...
StarcoderdataPython
11332195
<reponame>AnonymusRaccoon/dotfiles<gh_stars>1-10 # Store interactive Python shell history in ~/.cache/python_history # instead of ~/.python_history. # # Create the following .config/pythonstartup.py file # and export its path using PYTHONSTARTUP environment variable: # # export PYTHONSTARTUP="${XDG_CONFIG_HOME:-$HOME/....
StarcoderdataPython
3401049
<gh_stars>1-10 from django.shortcuts import render, HttpResponse, redirect from courses.models import Course def home(request): return render(request, 'home.html', ) def aboutUs(request): return render(request,'about.html',{}) def Contactus(request): if request.method == 'POST': #work for it's backend !! ...
StarcoderdataPython
8080261
from .model_base import Baseline from .model_eval_op import TwoStreamSwitchBNOp
StarcoderdataPython
5181969
"""Modules that handle the events the bot recognizes and reacts to"""
StarcoderdataPython
1812199
#sample script to be executed by pipeViewer Console from model.node_element import NodeElement highest_access_count = 0 for element in context.GetElements(): if isinstance(element, NodeElement): split = element.GetProperty('data').split(':') if len(split) < 2: continue # either Start or ...
StarcoderdataPython
11313696
<reponame>miott/genielibs<filename>pkgs/ops-pkg/src/genie/libs/ops/stp/iosxr/stp.py ''' Stp Genie Ops Object for IOSXR - CLI. ''' # Genie from genie.libs.ops.stp.stp import Stp as SuperStp from genie.ops.base import Context # Parser from genie.libs.parser.iosxr.show_spanning_tree import ShowSpanningTreeMst, \ ...
StarcoderdataPython
4837467
<filename>src/SyntaxHighlight.py """ defines syntax_function which turns str into CSS/HTML formatted syntax highlighted TikZ code """ import re try: from pygments import highlight, lexers from pygments.styles import get_style_by_name from pygments.formatters import HtmlFormatter except ImportError: high...
StarcoderdataPython
1838556
from selenium import webdriver import time class JdSpider: def __init__(self): self.driver = webdriver.Chrome() self.driver.get(url='https://www.jd.com/') self.driver.find_element_by_xpath('//*[@id="key"]').send_keys("<PASSWORD>") self.driver.find_element_by_xpath('//*[@id="search"]...
StarcoderdataPython
22477
#!C:\Users\stpny\Downloads\grasp_public-master\grasp_public-master\Scripts\python.exe # EASY-INSTALL-ENTRY-SCRIPT: 'imageio==2.5.0','console_scripts','imageio_remove_bin' __requires__ = 'imageio==2.5.0' import re import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.argv[0] =...
StarcoderdataPython
8198582
<filename>src/run.py import tempfile from subprocess import check_output, run def run_script(cwd, script, return_output=False): output = "" print(f"Running script:\n{script}") with tempfile.NamedTemporaryFile() as f: f.write(script.encode("utf-8")) f.seek(0) if return_output: ...
StarcoderdataPython
146426
<reponame>applejenny66/snoopy<filename>utils.py # utils.py import numpy as np import cv2 import os def clearall(): import shutil shutil.rmtree('./test') os.mkdir('./test') def blankarray(shape): array = np.zeros(shape) for x in range(0, shape[0]): for y in range(0, shape[1]): ...
StarcoderdataPython
11302519
import fs.path from .utils import Docs class TestRegression(Docs): def setUp(self): super(TestRegression, self).setUp() self.base_folder = fs.path.join("tests", "regression_tests") def test_helper_and_partial(self): expected = ( "<h1>People</h1>" + "<ul><li>Bi...
StarcoderdataPython
11356631
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from builtins import range from builtins import super import mock import string import unittest from parameterized import parameterized import random import json from ppri...
StarcoderdataPython
3451101
# ============================================================================== # Copyright (c) 2018, Yamagishi Laboratory, National Institute of Informatics # Author: <NAME> (<EMAIL>) # All rights reserved. # ============================================================================== """ """ import tensorflow as...
StarcoderdataPython
8128161
# encoding: utf-8 from flask import Blueprint import ckan.plugins as p import ckan.plugins.toolkit as tk def fancy_route(package_type: str): return u'Hello, {}'.format(package_type) def fancy_new_route(package_type: str): return u'Hello, new {}'.format(package_type) def fancy_resource_route(package_type:...
StarcoderdataPython
12800276
import pandas as pd import numpy as np import matplotlib.pyplot as plt from scipy.io import wavfile from scipy import fftpack from scipy import signal import os # import soundfile as sf #import pyAudioAnalysis #module to output the sound from playsound import playsound #metadata is a python file which contains a di...
StarcoderdataPython
351334
x = int(input()) d = [0] * 1000001 for i in range(2,x+1): d[i] = d[i-1] + 1 if i%2 == 0: d[i] = min(d[i], d[i//2] + 1) if i%3 == 0: d[i] = min(d[i], d[i//3] + 1) print(d[x])
StarcoderdataPython
6554118
<filename>custom_functions.py<gh_stars>0 # This module contains custom functions functions for data wrangling import pandas as pd def remove_column_substr(df, substr): ''' remove substring from a column name in a pandas dataframe :param df: pandas dataframe :param substr: substring to remove :retu...
StarcoderdataPython
6591958
#!/usr/bin/env python from rftool.rf import get_args, main if __name__ == '__main__': args = get_args() main(args.file, args.cv)
StarcoderdataPython
11302325
from hashlib import sha256 # genesis block hash = (sha256(sha256( bytearray.fromhex( "0100000000000000000000000000000000000000000000000000000000000000000000003ba3edfd7a7b12b27ac72c3e67768f617fc81bc3888a51323a9fb8aa4b1e5e4a29ab5f49ffff001d1dac2b7c" )).digest()).digest().hex()) print(hash) # block from ...
StarcoderdataPython
1683176
<filename>sampling/potential_LAMMPS.py<gh_stars>1-10 ############################################################################## # Python-force-field-parameterization-workflow: # A Python Library for performing force-field optimization # # Authors: <NAME>, <NAME> # # Python-force-field-parameterization-workflow...
StarcoderdataPython
3467485
(dog+cat).cat.print(10) f"hi{dog}cat"
StarcoderdataPython
6609124
<gh_stars>100-1000 import sys import os import io from contextlib import contextmanager from unittest import TestCase from sqflint import parse_args, entry_point @contextmanager def captured_output(): new_out, new_err = io.StringIO(), io.StringIO() old_out, old_err = sys.stdout, sys.stderr try: s...
StarcoderdataPython
3214224
<reponame>zeou1/maggot_models<filename>notebooks/114.0-BDP-flow-revisited.py # %% [markdown] # ## from src.hierarchy import signal_flow from src.data import load_metagraph from src.visualization import matrixplot from src.visualization import CLASS_COLOR_DICT from src.io import savefig import os from src.graph import p...
StarcoderdataPython
1710803
<gh_stars>10-100 import smbus from time import sleep from skeleton import InputSkeleton class InputDevice(InputSkeleton): """A driver for Adafruit-developed Raspberry Pi character LCD&button shields based on MCP23017, either Adafruit-made or Chinese-made. Tested on hardware compatible with Adafruit schem...
StarcoderdataPython
3303416
<filename>src/im_task_webapp2/__init__.py from im_task import _launch_task, get_taskroute import webapp2 from google.appengine.ext import webapp def get_webapp_url(): return "%s/(.*)" % get_taskroute() class TaskHandler(webapp.RequestHandler): def post(self, name): _launch_task(self.request.body, name...
StarcoderdataPython
19045
<reponame>bbueno5000/BuildAnAIStartUpDemo import app import flask import flask_debugtoolbar app = flask.Flask(__name__) app.config.from_object('app.config') db = flask.ext.sqlalchemy.SQLAlchemy(app) mail = flask.ext.mail.Mail(app) app.config['DEBUG_TB_TEMPLATE_EDITOR_ENABLED'] = True app.config['DEBUG_TB_PROFILER_E...
StarcoderdataPython
8129396
<gh_stars>0 s = input('Enter string to get frequency of its words: ') words = s.split() d = {} for word in words : if word not in d : d[word] = 1 else : d[word] = d[word] + 1 print('Words and their frequencies are') for i in d : print(i, d[i])
StarcoderdataPython
3368078
<reponame>Tobias2023/dolosse """ file: test_data.py brief: File containing test data for the various Pixie16 test fixtures. author: <NAME> date: November 02, 2019 """ from struct import pack def pack_data(data, type): """ Packs an iterable into a bytes like object :param data: The data that we'll pack int...
StarcoderdataPython
309009
"""gecasmo is a package for estimating click models""" from .GCM import GCM from .clickdefinitionreader import ClickDefinition
StarcoderdataPython
3498174
<reponame>sarangbhagwat/Bioindustrial-Park # -*- coding: utf-8 -*- # BioSTEAM: The Biorefinery Simulation and Techno-Economic Analysis Modules # Copyright (C) 2020, <NAME> <<EMAIL>> # # This module is under the UIUC open-source license. See # github.com/BioSTEAMDevelopmentGroup/biosteam/blob/master/LICENSE.txt # for ...
StarcoderdataPython
3495438
<filename>src/staff/urls.py from django.urls import path from django.shortcuts import render from django.contrib.admin.views.decorators import staff_member_required from .views import ConsistencyTestView def home_view(request): return render(request, "staff/home.html", {}) urlpatterns = [ path("", home_vie...
StarcoderdataPython
178586
import networkx as nx import numpy as np def project3d(points, direction): """ 投影函数,将三维点集投影到二维 投影平面内的y方向为z轴投影(如果投影的法向量为z轴,则y方向为x轴投影) :param points: 三维点集 :param direction: 投影平面的法向量(u,v,w),投影平面通过原点(0,0,0) """ d = direction / np.linalg.norm(direction) y0 = np.array([1, 0, 0]) if np.array(...
StarcoderdataPython
3303285
from ...utils.json_schema import method_signature_to_json_schema, JsonParameter, JsonSchemaDocument from ..existing_table_handling import ExistingTableHandling from records_mover.records.delimited.hints import Hints from typing import Any, Dict, List, Callable from ...mover_types import JsonSchema HINT_PARAMETERS = [...
StarcoderdataPython
1744921
<filename>python/exercicios mundo 1/ex004/ex006.py #O mesmo professor do desafio 19 quer sortear a ordem de apresentação de trabalhos dos alunos. Faça um programa que leia o nome dos quatro alunos e mostre a ordem sorteada. import random n1 =str(input('primeiro aluno: ')) n2 =str(input('segundo aluno: ')) n3 =str(inpu...
StarcoderdataPython
6413054
from ..layers.HeteroLinear import HeteroMLPLayer from ..layers.GeneralGNNLayer import MultiLinearLayer def HGNNPreMP(args, node_types, num_pre_mp, in_dim, hidden_dim): """ HGNNPreMP, dimension is in_dim, hidden_dim, hidden_dim ... Note: Final layer has activation. Parameters ---------- ar...
StarcoderdataPython
1948674
<gh_stars>1-10 from abnormal import AB import proxies def get_proxies(): return proxies.get_proxies() def test_create_ab(): ab = AB(get_proxies()) assert ab def test_get_proxies(): working_proxies = get_proxies() assert len(working_proxies) > 100
StarcoderdataPython
1620904
import unittest import warnings import pytest from qiskit import QuantumCircuit from cirq import ParamResolver from qiskit.providers import JobStatus from azure.quantum.job.job import Job from azure.quantum.qiskit import AzureQuantumProvider from azure.quantum.cirq import AzureQuantumService from azure.quantum.cirq...
StarcoderdataPython
1685
import unittest from networks.QoS import QoS from networks.connections.mathematical_connections import FunctionalDegradation from networks.slicing import SliceConceptualGraph from utils.location import Location class TestBaseStationLinear(unittest.TestCase): def setUp(self): self.name = "network" ...
StarcoderdataPython
8050898
import pytest from godot import RID, Environment, Node def test_base(): v = RID() assert type(v) == RID def test_equal(): v1 = RID() v2 = RID() assert v1 == v2 # Environment is a Ressource which provides unique rid per instance res_a = Environment() v_a_1 = RID(res_a) assert v_a...
StarcoderdataPython
1891373
import numpy as np import cv2 from config import * from keras.utils.np_utils import to_categorical def pre_process_img(img,colorChannel='RGB'): #first remove the hood of car img = img[TOPCROP:BOTTOMCROP,...]; #normalize image return img/255.-0.5 def pre_process_label(label): #only use third index...
StarcoderdataPython
1687288
from features.numpy_sift import SIFTDescriptor import numpy as np import features.feature_utils from features.DetectorDescriptorTemplate import DetectorAndDescriptor class np_sift(DetectorAndDescriptor): def __init__(self, peak_thresh=10.0): super( np_sift, self).__init__( ...
StarcoderdataPython
1986993
<filename>Game/PlayerLogic/Actions/Double.py import IAction # BUG: Double hits and stands as well? class Double(IAction.IAction): def legal(self, player, admin): return player.cardCount() == 2 and player.isActive() def effect(self, player, admin): admin.dealCard(player) player.act...
StarcoderdataPython
5133202
<filename>main.py #!/usr/bin/env python3 import requests import json from dotenv import load_dotenv import os import mariadb import datetime import time import dateutil.relativedelta load_dotenv() PI_IP = os.getenv("PI_IP") API_KEY = os.getenv("API_KEY") DB_USER = os.getenv("DB_USER") DB_PASSWD = os.getenv("<PASSWOR...
StarcoderdataPython
8083321
#!/usr/bin/env python import subprocess, shlex, json def get_threat_list(): isi_threat_list_raw = "isi antivirus reports threats list --format json -a -z" isi_threat_list_split = shlex.split(isi_threat_list_raw) isi_threat_list_cmd = subprocess.Popen(isi_threat_list_split, stdout = subprocess.PIPE) is...
StarcoderdataPython
1642261
<filename>Python/136_SingleNumber.py class Solution(object): def singleNumber(self, nums): """ :type nums: List[int] :rtype: int """ #Using XOR to find the single number. #Because every number appears twice, while N^N=0, 0^N=N, #XOR is cummutative, so the ord...
StarcoderdataPython
42166
<gh_stars>0 # 저자: Charles # 공공 번호; Charles의 피카츄 # python 작은 게임 시리즈 만들기 - FlappyBird import Bird import Pipe import pygame from pygame.locals import * # 일부 상수 정의 WIDTH, HEIGHT = 640, 480 # 메인 함수 def main(): # 초기화 pygame.init() screen = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32) pygame.dis...
StarcoderdataPython
12833266
class NotInsideTransaction(Exception): def __init__(self): message = 'Trying to perform an operation that needs to be inside transaction' super(NotInsideTransaction, self).__init__(message) class MixedPositionalAndNamedArguments(Exception): def __init__(self): message = 'Cannot mix p...
StarcoderdataPython
3319739
from unittest import mock from django.db.utils import IntegrityError from django.test import Client, SimpleTestCase, TestCase from django.urls import resolve, reverse from users.api import CheckVerificationCodeView, EmailView from users.models import Emails from users.tasks import send_verification_code from users.ut...
StarcoderdataPython
389856
<filename>galois/factor.py<gh_stars>0 """ A module containing routines for integer factorization. """ import bisect import functools import math import random import numpy as np from .math_ import isqrt from .overrides import set_module from .prime import PRIMES, is_prime __all__ = ["prime_factors", "is_smooth"] d...
StarcoderdataPython
180966
<filename>p1_navigation/plots.py<gh_stars>0 import matplotlib.pyplot as plt def plot_loss(history): history['agent_avg_loss'].plot(label='avg_loss'); history['agent_avg_loss'].rolling(10).mean().plot(label='rolling(10) mean of avg_loss'); plt.title('Agent average loss') plt.xlabel('Episodes') plt.y...
StarcoderdataPython
1931642
<gh_stars>1-10 #!/usr/bin/env python3 # This script converts MeCab analysis result to Juman++ training data import sys import csv import random def escape(x): if '"' in x or ',' in x: replaced = x.replace('"', '""') return f'"{replaced}"' else: return x FIELD_NAMES = [ "pos1", ...
StarcoderdataPython
352601
""" Created on May 25, 2016 @author: xiul, t-zalipt """ import numpy as np ################################################################################ # Some helper functions ################################################################################ def unique_states(training_data): uniq...
StarcoderdataPython
8135739
<filename>2021-08-11/valid_lab_results.py """ Valid Lab Results | Cannabis Data Science Authors: UFO Software, LLC <NAME> <<EMAIL>> Created: Thursday, July 29, 2021 21:51 Updated: 8/10/2021 License GPLv3+: GNU GPL version 3 or later https://gnu.org/licenses/gpl.html This is free software: you are free to chang...
StarcoderdataPython
5179843
<gh_stars>1-10 import pathlib from setuptools import setup import versioneer # The directory containing this file HERE = pathlib.Path(__file__).parent # The text of the README file README = (HERE / "README.md").read_text() # This call to setup() does all the work setup( name="anonymizedf", version=versionee...
StarcoderdataPython
5063596
<filename>utils2.py import numpy as np import sklearn import gtg import os from math import log import random random.seed(314) def one_hot(labels, nr_classes): labells = labels[:, 0] labells = labells.astype(int) label_one_hot = np.zeros((labells.size, nr_classes)) label_one_hot[np.arange(labells.size...
StarcoderdataPython
11371801
import functools import operator import torch from sklearn.metrics import ( classification_report, f1_score, precision_recall_fscore_support, ) from torch import optim as optim, nn as nn from models import Model import time """ def fit( TEXT, train_dl, valid_dl, config, conv_depth, ...
StarcoderdataPython
12809214
<reponame>xuhang57/atmosphere """ Service Provider model for atmosphere. """ from django.db import models from django.utils import timezone from core.models.provider import Provider class NodeController(models.Model): """ NodeControllers are specific to a provider They have a dedicated, static IP addres...
StarcoderdataPython
5007430
<reponame>ArniDagur/auto-rental """ # Data file specification: ## Fundamentals: * Data files shall be given the extension .df * Data files be encoded in valid UTF-8 ## Revision ID: * The first line of a data file shall contain the file's revision ID. * The revision ID may be any positive number that has the following...
StarcoderdataPython
329080
<gh_stars>0 import sys import binascii init_byte = 0x0f def step(current_byte, in_bit): out_bit = in_bit ^ ((current_byte & 0x20) >> 5) next_byte = (current_byte & 0x01) << 7 next_byte |= (current_byte & 0x18) << 2 next_byte |= (current_byte & 0x80) >> 3 next_byte |= (current_byte & 0x06) << 1 ...
StarcoderdataPython
4884150
import logging from dataclasses import astuple, fields from pywps import LiteralInput from ravenpy.models import GR4JCN from raven import config from . import wpsio as wio from .wps_raven import RavenProcess LOGGER = logging.getLogger("PYWPS") """ Notes ----- The configuration files for RAVEN's GR4J-Cemaneige mod...
StarcoderdataPython
8137965
#!/usr/bin/env python2 import signal, socket, pickle, zlib, os signal.signal(signal.SIGCHLD, signal.SIG_IGN) s = socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(("0.0.0.0", 1024)) s.listen(5) entries = {} def rl(): l = "" while not l.endswith("\n"): c = s.recv(1) assert(c) l +...
StarcoderdataPython
325500
<gh_stars>1-10 from face.lbpcascade_animeface import LibCascadeAnimeFace class FaceModel: model = None def __init__(self, name): if name == "lbpcascade_animeface": self.model = LibCascadeAnimeFace() def show(self, img_path, args): self.model.show(img_path, args) if __name_...
StarcoderdataPython
11256980
<reponame>dolboBobo/python3_ios """ =================== Centered Ticklabels =================== sometimes it is nice to have ticklabels centered. Matplotlib currently associates a label with a tick, and the label can be aligned 'center', 'left', or 'right' using the horizontal alignment property:: ax.xaxis.set_t...
StarcoderdataPython
9686603
import numpy as np from neuralnet.utils import prep_batch from neuralnet.optimizers import GradientDescent class NeuralNet: def __init__(self,hidden,initializer,optimizer): self.hidden = hidden self.initializer = initializer self.training_error = [] self.validation_error = [] ...
StarcoderdataPython
6442121
<reponame>Arenhart/Portfolio # -*- coding: utf-8 -*- """ Created on Tue Feb 4 14:10:31 2020 @author: <NAME> """ from skimage import draw from skimage import filters from skimage import morphology import numpy as np import math import csv import matplotlib.pyplot as plt import io from scipy import ndimage from numba ...
StarcoderdataPython
3222130
<filename>stubs/micropython-v1_12-pyboard/stm.py<gh_stars>0 """ Module: 'stm' on micropython-v1.12-pyboard """ # MCU: {'ver': 'v1.12', 'port': 'pyboard', 'arch': 'armv7emsp', 'sysname': 'pyboard', 'release': '1.12.0', 'name': 'micropython', 'mpy': 7685, 'version': '1.12.0', 'machine': 'PYBv1.1 with STM32F405RG', 'build...
StarcoderdataPython
1995254
# Write the benchmarking functions here. # See "Writing benchmarks" in the asv docs for more information. import numpy as np import xarray as xr from scipy.stats import norm from xskillscore import ( brier_score, crps_ensemble, crps_gaussian, crps_quadrature, threshold_brier_score, ) from . impo...
StarcoderdataPython
9762342
<reponame>scolemann/mlfinlab """ Implements the Combinatorial Purged Cross-Validation class from Chapter 12 """ from itertools import combinations from typing import List import pandas as pd import numpy as np from sklearn.model_selection import KFold from .cross_validation import ml_get_train_times class Combinat...
StarcoderdataPython
11328220
import logging import unittest from vodem.api import save_sms class TestSaveSms(unittest.TestCase): @classmethod def setUpClass(cls): cls.valid_response = { } @unittest.skip('skip') def test_logs_defaults(self): params = {'SMSMessage': '0074006500730074'} with self....
StarcoderdataPython
9686363
<filename>DQM/L1TMonitor/python/L1TdeGEMTPG_cfi.py import FWCore.ParameterSet.Config as cms l1tdeGEMTPGCommon = cms.PSet( monitorDir = cms.string("L1TEMU/L1TdeGEMTPG"), verbose = cms.bool(False), ## when multiple chambers are enabled, order them by station number! chambers = cms.vstring("GE11"), da...
StarcoderdataPython
1792856
#!/usr/bin/env python3 import unittest from torch.testing._internal.common_distributed import MultiProcessTestCase from torch.testing._internal.common_utils import TEST_WITH_ASAN, run_tests from torch.testing._internal.distributed.rpc.rpc_test import RpcTest @unittest.skipIf( TEST_WITH_ASAN, "Skip ASAN as torch ...
StarcoderdataPython
9760190
from torch.testing._internal.jit_utils import JitTestCase import io import os import sys import torch import torch._C # Make the helper files in test/ importable pytorch_test_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) sys.path.append(pytorch_test_dir) if __name__ == '__main__': raise Runt...
StarcoderdataPython
1637631
<reponame>MeiK-h/JudgeLight import sys from distutils.core import Extension, setup sources = [ 'JudgeLight/JudgeLightRunner/judgelightrunner.c', 'JudgeLight/JudgeLightRunner/jl_runner.c', 'JudgeLight/JudgeLightRunner/jl_memory.c', 'JudgeLight/JudgeLightRunner/jl_limit.c', 'JudgeLight/JudgeLightRunn...
StarcoderdataPython
9737083
#!/usr/bin/env python3 def bytes_to_array(dat, sz): dat = dat.split() arr = [] for i in range(0, len(dat), sz): arr.append(int(''.join(reversed(dat[i:i+sz])), 16)) return arr key = "IdontKnowWhatsGoingOn" s = "08 00 00 00 06 00 00 00 2c 00 00 00 3a 00 00 00 32 00 00 00 30 00 00 00 1c 00 00 00 ...
StarcoderdataPython
5153235
#!/usr/bin/env python """ Converts an event price (tax-included) to a retail price (pre-tax) or vice versa. Event prices are calculated by applying a discount to the online price, adding sales tax, and rounding to the nearest dollar. Retail prices are calculated by removing sales tax, inverting the discount, roundin...
StarcoderdataPython
4802137
print(*map(lambda x: x.count(x[0]), [input()]))
StarcoderdataPython
6478164
<filename>apps/backend/subscription/constants.py # -*- coding: utf-8 -*- """ TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-节点管理(BlueKing-BK-NODEMAN) available. Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License")...
StarcoderdataPython
5094602
#!/usr/bin/env python # Copyright 2016 The LUCI Authors. All rights reserved. # Use of this source code is governed under the Apache License, Version 2.0 # that can be found in the LICENSE file. import contextlib import json import logging import os import socket import sys import tempfile import time import unittest ...
StarcoderdataPython
11312336
<gh_stars>0 import numpy as np from queue import deque class Memory(): """Sets up the memory element""" def __init__(self, max_size): """Initializes the memory element""" self.buffer = deque(maxlen = max_size) def add(self, experience): """Adds player experience to the memory elem...
StarcoderdataPython
6644463
import numpy as np class ExperienceReplay: def __init__(self, size): self.size = size class PrioritisedExperienceReplay: def __init__(self, size): self.size = size
StarcoderdataPython
8042298
load("@local_config_env//:env.bzl", "FELICIA_ROOT") load("@local_config_python//:py.bzl", "PYTHON_BIN") LastChangeInfo = provider("lastchange") def _lastchange_impl(ctx): outputs = [ctx.actions.declare_file("LASTCHANGE"), ctx.actions.declare_file("LASTCHANGE.committime")] tool_path = ctx.expand_location("$(lo...
StarcoderdataPython
3212855
<gh_stars>0 """ This file provides a wrapper around resnet and vote_fc and is useful for inference since it fuses both forward passes in one. """ import torch import torch.nn as nn from models import get_pose_net, SMPL # from models.resnet import resnet50 # from models.sc_layers_share_global6d import SCFC_Share from m...
StarcoderdataPython
12863384
""" This script creates users in a JAMF Pro Server instance from an LDAP query. """ # Copyright 2020 <NAME> # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including w...
StarcoderdataPython
9770450
import collections from copy import deepcopy import meshio import numpy from ._common import ( get_local_index, get_meshio_version, get_new_meshio_cells, get_old_meshio_cells, meshio_data, ) from ._properties import ( _connections, _face_areas, _face_normals, _faces, _materials...
StarcoderdataPython
9638171
import logging import re # STOP: Do not make changes to this file! This file contains defaults for the open group server and # is intended to be replaced on upgrade. If you want to override any changes you should instead set # the variable you care about in `config.py`, which overrides values specified here. # The ...
StarcoderdataPython
3380572
<gh_stars>0 import numpy as np import tensorflow as tf import h5py from sklearn.preprocessing import OneHotEncoder import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import time # Download data from .mat file into numpy array print('==> Experiment 5d') # Functions for initializing neu...
StarcoderdataPython
6406172
<reponame>AshuMaths1729/Sudoku-Vision<filename>data/gen_n10_data.py import numpy as np import cv2 as cv fileName = "n10.data" def gendata(): img = np.zeros((50, 50, 3), np.uint8)*255 img = cv.cvtColor(img, cv.COLOR_BGR2GRAY) roi = img[:,:] roi_1 = np.append([10], roi) roi_2 = np.append([10], cv.bitwise_not(roi)...
StarcoderdataPython