id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
1752576
<gh_stars>0 from .perceptron import * from .ilayer import *
StarcoderdataPython
1718199
import os import cv2 from tqdm import tqdm import argparse def parsePaths(path): name_parts=path.split('_') mask_path = path.replace('composite_images','masks') mask_path = mask_path.replace(('_'+name_parts[-1]),'.png') target_path = path.replace('composite_images','real_images') target_p...
StarcoderdataPython
1714954
<gh_stars>0 import random import sys class Node: def __init__(self, value): self.value = value self.left = None self.right = None def __init__(self, value, left, right): self.parent = -1 self.data = value self.left_node = left self.right_node = right ...
StarcoderdataPython
3242486
<reponame>linusbrogan/edurange-flask<filename>tests/test_functional.py # -*- coding: utf-8 -*- """Functional tests using WebTest. See: http://webtest.readthedocs.org/ """ from flask import url_for from edurange_refactored.user.models import StudentGroups, User, GroupUsers from .factories import GroupFactory, UserFac...
StarcoderdataPython
1625926
import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' from ..model_builder import ModelBuilder def mobilenet(args): # Mobile Net like module filt_list = [32, 16, 24, 24, 32, 32, 32, 64, 64, 64, 64, 96, 96, 96, 160, 160, 160, 320, 1280] strides_list = [1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, ...
StarcoderdataPython
3376768
#!/usr/bin/env python from peyotl import read_as_json import codecs import json import sys try: subproblem_ids_file, in_annotations_file, out_annotations_file = sys.argv[1:] except: sys.exit('Expecting 3 arguments:\n subproblem_ids_file, in_annotations_file, out_annotations_file') import os bin_dir = os.path....
StarcoderdataPython
195628
import collectd from CinderMetrics import CinderMetrics from NeutronMetrics import NeutronMetrics from NovaMetrics import NovaMetrics def config_callback(conf): """Receive configuration block""" project_name = "demo" project_domainid = "default" user_domainid = "default" region_name = None int...
StarcoderdataPython
4811904
<filename>custom_components/nicehash_excavator/excavator.py """Nicehash Excavator API""" from __future__ import annotations import logging import aiohttp from aiohttp.client_reqrep import ClientResponse from .data_containers import Algorithm, GraphicsCard, RigInfo, Worker _LOGGER = logging.getLogger(__name__) cla...
StarcoderdataPython
191628
<reponame>ajharry69/django-xently class AppNotFoundError(Exception): pass class ClassNotFoundError(Exception): pass
StarcoderdataPython
1745804
<filename>data_utils/augmentor/spec_augment.py import random import numpy as np from PIL import Image from PIL.Image import BICUBIC from ppasr.data_utils.augmentor.base import AugmentorBase class SpecAugmentor(AugmentorBase): """Augmentation model for Time warping, Frequency masking, Time masking. SpecAugm...
StarcoderdataPython
1791642
from Bio import SeqIO import sys #Create genome file for bedtools print("Extracting chromosome lengths from %s ..." % str(sys.argv[1])) ids = [] lengths = [] for rec in SeqIO.parse(str(sys.argv[1]), "fasta"): ids.append(rec.id) lengths.append(len(rec)) print("Writing lengths to %s ..." % sys.argv[2]) with open(sys....
StarcoderdataPython
32132
# Copyright 2020 <NAME> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, softw...
StarcoderdataPython
3237859
<gh_stars>10-100 from pages.browser import Browser from selenium import webdriver from locators import * import time class LoginPage(Browser): def __init__(self): self.LOGIN = '/' def log_in_as(self, username, password): """ Locates username & password elements and sends cred...
StarcoderdataPython
77222
import os.path as osp import random import numpy as np import pytest from numpy.testing import assert_array_almost_equal, assert_array_equal from mmaction.core import (ActivityNetLocalization, average_recall_at_avg_proposals, confusion_matrix, get_weighted_score, ...
StarcoderdataPython
28425
import argparse import subprocess import sys import logging logger = logging.getLogger("helper") def azcli(command): process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out,err = process.communicate() logger.debug(str(out,"utf-8")) exit_code = process.returncode if ...
StarcoderdataPython
121973
import cv2 import time # Remove Later import numpy as np video = cv2.VideoCapture("./img/vert2.mp4") target_low = (0, 0, 0) target_high = (50, 50, 50) while True: ret, frame = video.read() if not ret: video = cv2.VideoCapture("./img/vert2.mp4") continue image = frame image = cv2.resiz...
StarcoderdataPython
1715626
<gh_stars>0 import csv import unittest from unittest import result from rdflib import URIRef from RQSSFramework.Availability.DereferencePossibility import \ DerefrenceExplorer class TestDereferency(unittest.TestCase): def setUp(self): self.test_data = [URIRef("https://www.wikidata.org/wiki/Q1"), ...
StarcoderdataPython
1653801
""" Copyright (c) 2022 Huawei Technologies Co.,Ltd. openGauss is licensed under Mulan PSL v2. You can use this software according to the terms and conditions of the Mulan PSL v2. You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, W...
StarcoderdataPython
142987
<filename>jobs/44-streaming-activity-data-file.py #read activity data, example from spark definitive guide. files are in json format. #create spark session from pyspark.sql import SparkSession from pyspark.sql.types import * from pyspark.sql.functions import * spark = SparkSession\ .Builder().appName("stream...
StarcoderdataPython
1750457
<gh_stars>0 from ._chart_forecast import create_forecast_chart from ._options import ForecastOptions (create_forecast_chart, ForecastOptions)
StarcoderdataPython
137849
<filename>ava/auditors/text.py from copy import copy from ava.common.auditor import _Auditor from ava.common.constant import HTTP from ava.handlers.value import _ValueHandler # metadata name = __name__ description = "audits text data" class _TextValueHandler(_ValueHandler): def _get_targets(self, vector): ...
StarcoderdataPython
1683706
import xml.dom.minidom from xml.dom.minidom import Node fileName = 'strings' projectName = 'my-module' filename = "path/to/project/" + projectName + "/src/main/res/values/" + fileName + ".xml" oputputfilename = "path/to/output/output-" + projectName + "-" + fileName + ".csv" fileout = open(oputputfilename, "w") def...
StarcoderdataPython
1788625
<reponame>arcticlimer/botinho<gh_stars>0 from abc import ABC, abstractmethod class IRepository(ABC): """ """ @abstractmethod async def create(self): pass @abstractmethod async def find(self): pass @abstractmethod async def update(self): pass @abstractmethod async def delete(s...
StarcoderdataPython
3362499
<reponame>tpdn/python-winscard<filename>winscard/scard.py from ctypes import * from ctypes.wintypes import * from winscard import * class SCard: context = SCARDCONTEXT() card = SCARDHANDLE() dwAutoAllocate = DWORD(-1) def __init__(self, dwScope=SCARD_SCOPE_USER, pvReserved1=None, pvReserved2=None): ...
StarcoderdataPython
146378
""" @ Author : <NAME>, <NAME>, <NAME> @ Date : 04/29/2018, 11/01/2018, 04/29/2019 @ Description : Youless Sensor - Monitor power consumption. """ VERSION = '2.0.1' import json import logging from datetime import timedelta from urllib.request import urlopen import voluptuous as vol import homeassistant.he...
StarcoderdataPython
1781826
<gh_stars>0 import os from flask import Flask, flash, make_response, request, redirect, url_for, render_template, send_from_directory from werkzeug.utils import secure_filename import numpy as np import cv2 from mainDetector import glass_detector UPLOAD_FOLDER = r'C:/Users/rianl/Desktop/tensorflow-yolov4-tflite/upload...
StarcoderdataPython
196049
""" Helper functions for testing. """ import inspect import os import string from matplotlib.testing.compare import compare_images from pygmt.exceptions import GMTImageComparisonFailure from pygmt.src import which def check_figures_equal(*, extensions=("png",), tol=0.0, result_dir="result_images"): """ Decor...
StarcoderdataPython
3263033
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Create seperate, binarised nii files for each tissue type in fs segm.""" import os import numpy as np from nibabel import load, save, Nifti1Image # set parent path parent_path = os.path.join(str(os.environ['parent_path']), 'data', 'segmenta...
StarcoderdataPython
69092
<filename>bea/api.py """ This module contains specifics based on the current documentation, to make calls and consume the data released by the BEA. Although the BEA (at the time of this writing) supports both XML and JSON responses; this module does not have XML response support at this time, only JSON and Python type...
StarcoderdataPython
1691471
import json from workflow import PasswordNotFound class AuthKeys(dict): keychain_account = '2fa_keys' def __init__(self, workflow, **kwargs): super(AuthKeys, self).__init__(**kwargs) self._wf = workflow self._load() def _load(self): try: json_data = self._wf...
StarcoderdataPython
4805156
# ! Desafio 29 # ! Crie um programa que leia a velocidade de um carro, se ele ultrapassar 80Kmh mostre uma mensagem dizendo que ele foi multado. A multa vai custar R$7,00 por cada km acima do limite. v = float(input('Qual a velocidade atual do seu carro? ')) if v <=80: print('Muito bem, pode seguir viagem!') else...
StarcoderdataPython
1762613
import sys import time from scipy.special import binom as binom from timer import Timer from util import * import numpy as np class SATCounter: def __init__(self, sat_problem, verbose=True, use_regular=False): """ Each SATCounter solves a specific sat problem that must be specified at creation """ ...
StarcoderdataPython
3358417
import math from itertools import combinations l=list(input().split(',')) p=int(math.sqrt(len(l))) b=[] max=sum(list(map(int,l))) for i in range(2,len(l)+1): a=list(combinations(l,i)) for j in a: c=sum(list(map(int,j))) if c==max and len(j)==4: b.append(j) b=set(b) print...
StarcoderdataPython
1785610
#!/usr/bin/python # -*- coding: UTF-8 -*- # pylint: disable=C0111 import unittest import platform from pyxmpp2.etree import ElementTree import pyxmpp2.version from pyxmpp2.iq import Iq from pyxmpp2.jid import JID from pyxmpp2.stanzaprocessor import StanzaProcessor from pyxmpp2.settings import XMPPSettings from pyxmp...
StarcoderdataPython
152798
# Generated by Django 3.1.8 on 2021-04-23 08:35 import django.contrib.postgres.fields from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import model_utils.fields import uuid class Migration(migrations.Migration): replaces = [('flags', '0001_initial'), ('flags...
StarcoderdataPython
1605647
import math class coord: def __init__(self, Satlatitude, Satlongitude, Glatitude, Glongtitude, Sataltitude, Galtitude, gx, gy, gz): self.lat1 = math.radians(float(Satlatitude)) self.lat2 = math.radians(float(Glatitude)) self.lon1 = math.radians(float(Satlongitude)) self.l...
StarcoderdataPython
28969
<reponame>pabarros/asgard-api<gh_stars>1-10 import json import unittest from copy import deepcopy from http import HTTPStatus from unittest.mock import call, patch from flask import Response as FlaskResponse from marathon import MarathonApp from marathon.models.group import MarathonGroup from marathon.models.task impo...
StarcoderdataPython
1635354
<reponame>JoeBuzh/Pm_Composition_Quallity_Control # -*- encoding: utf-8 -*- ''' @Filename : Extractor.py @Datetime : 2020/04/28 16:15:34 @Author : Joe-Bu @Version : 1.0 @Descrption : 根据指定气象站点信息提取指定气象观测、污染观测数据; 配置项在config.ini中配置,可配置气象、污染观测站点信息,指定提取时间段。 ''' import os import sys import tra...
StarcoderdataPython
3207326
<reponame>JaufreLallement/Wepwawet from functools import reduce def seconds_to_str(t): return "%d:%02d:%02d.%03d" % reduce(lambda ll, b: divmod(ll[0], b) + ll[1:], [(t * 1000,), 1000, 60, 60])
StarcoderdataPython
170023
<gh_stars>0 import numpy as np from typing import Callable from lanro.tasks.core import Task from lanro.simulation import PyBulletSimulation from lanro.tasks.scene import basic_scene from lanro.utils import RGBCOLORS class Reach(Task): def __init__(self, sim: PyBulletSimulation, ...
StarcoderdataPython
1646710
''' Speed Test for Internet - v1.2 Apache Lisance 2.0 Created by <NAME> ''' import time #for the next update import colorama #for the next update import requests as requests import speedtest colorama.init() def d...
StarcoderdataPython
3281638
from bs4 import BeautifulSoup import requests import csv page = requests.get("https://www.myhome.ie/residential/mayo/property-for-sale?page=1") soup = BeautifulSoup(page.content,'html.parser') home_file = open('week03MyHome.csv', mode='w') home_writer = csv.writer(home_file, delimiter='\t', quotechar='"', quoting=csv...
StarcoderdataPython
1608440
import boto3 import sure # noqa # pylint: disable=unused-import import time from moto import mock_glacier from moto.core import ACCOUNT_ID @mock_glacier def test_initiate_job(): client = boto3.client("glacier", region_name="us-west-2") client.create_vault(vaultName="myname") archive = client.upload_arc...
StarcoderdataPython
1608564
#pythran export run(int, int, int) #runas run(10,10,10) #from https://raw.githubusercontent.com/cphhpc/numpy/victim_cache/benchmark/Python/shallow_water.py import numpy as np def model(height, width, dtype): m = np.ones((height, width),dtype=dtype) m[height/4,width/4] = 6.0 return m def step(H, U, V, d...
StarcoderdataPython
1698574
import os from dotenv import load_dotenv from os.path import join, dirname dotenv_path = join(dirname(__file__), '.env') load_dotenv(dotenv_path) DELAY = 0.01 NUM_PARTITIONS = 3 OUTLIERS_GENERATION_PROBABILITY = 0.2 KAFKA_BROKER = "localhost:9092" TRANSACTIONS_TOPIC = "transactions" TRANSACTIONS_CONSUMER_GROUP = "tra...
StarcoderdataPython
3301274
# -*- coding: utf-8 -*- # Define here the models for your spider middleware # # See documentation in: # http://doc.scrapy.org/en/latest/topics/spider-middleware.html from scrapy.exceptions import NotConfigured from tools.proxies import get_proxy, del_proxy class HttpProxyMiddleware(object): """ 代理中间件 "...
StarcoderdataPython
3398570
<gh_stars>1-10 """ Copyright BOOSTRY Co., Ltd. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing,...
StarcoderdataPython
3273508
<reponame>dataspot/dgp-app<gh_stars>1-10 from slugify import slugify from .models import Models class Controllers(): def __init__(self, connection_string): self.models = Models(connection_string=connection_string) def _key(self, kind, id): return '{}::{}'.format(kind, id)[:128] def cre...
StarcoderdataPython
1688918
<reponame>chrisjdavie/ws_cross_project<gh_stars>0 ''' This generates the legendre polynomials, using the recursive definition found in wikipedia (and checked using other sources) Created on 30 Jan 2013 @author: chris ''' import numpy as np import scipy.misc as sc def Legendre_polys(l,m,x): # the maths and ...
StarcoderdataPython
138081
# Copyright 2021- imbus AG # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writi...
StarcoderdataPython
1728057
from datetime import date from datetime import timedelta from uuid import uuid1 import pytest from fastapi.testclient import TestClient from todo.backend import schema from todo.backend.endpoints import router from todo.backend.schema import ToDo from todo.backend.schema import Uuid @pytest.fixture(scope="module", ...
StarcoderdataPython
3351899
<reponame>captholley/ootp-pt-analysis from output_utils.progress.progress_bar import ProgressBar from util.number_utils import add_ip, ip_to_num import statsmodels.api as sm def get_woba_factors(ovr_data, vl_data, vr_data): ovr_factors = _calc_woba_factors(ovr_data) vl_factors = _calc_woba_factors(vl_data) ...
StarcoderdataPython
1661030
#!/usr/bin/python __author__ = 'ejk' ''' The bootstrap-salt.sh script here is a direct copy of github.bom/saltstack/salt-bootstrap you can find the authors of that script here https://github.com/saltstack/salt-bootstrap/blob/develop/AUTHORS.rst all credit to them for that fine piece of work''' import subpro...
StarcoderdataPython
3201126
<filename>stylization/stylization.py """This module contains various stylization functions of text appearance.""" import sys _style_dict = { "reset": "\033[0m", "bold": "\033[01m", "disable": '\033[02m', "underline": '\033[04m', "reverse": '\033[07m', "strikethrough": '\033[09m', "invisible...
StarcoderdataPython
3374078
<gh_stars>0 from __future__ import unicode_literals from django.utils.safestring import mark_safe from django.utils.translation import ugettext_lazy as _ from django.template.defaultfilters import truncatechars from mezzanine.weibopub import get_auth_settings FORMFIELD_HTML = """ <div class='send_weibo_container'> ...
StarcoderdataPython
3339683
from cms.extensions.toolbar import ExtensionToolbar from cms.toolbar_pool import toolbar_pool from django.utils.translation import ugettext_lazy as _ from cms.api import get_page_draft from cms.toolbar_pool import toolbar_pool from cms.toolbar_base import CMSToolbar from cms.utils.page_permissions import user_can_chan...
StarcoderdataPython
113871
import logging from qbot.core import registry from qbot.db import plugin_storage from qbot.message import Image, OutgoingMessage, Text, send_message from qbot.plugins.cmc import comic PLUGIN_NAME = "xkcd" LATEST_COMIC_KEY = "latest_comic" logger = logging.getLogger(__name__) @comic async def xkcd(): last_seen_...
StarcoderdataPython
3241732
# Copyright 2018 Propel http://propel.site/. All rights reserved. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
StarcoderdataPython
3336552
import time class progressbar(object): progressTime = 0 def __init__(self, stepNum, frontStr='', backStr=''): self.stepNum = stepNum self.fullRate = 100 self.lastOutputLen = 0 self.frontStr = frontStr self.backStr = backStr self.lastTime = time.perf_counter() def clear(self): spaceStr = ' ' *...
StarcoderdataPython
126997
import re import requests import xbmc from ..scraper import Scraper from ..common import random_agent, clean_title, googletag, filter_host, clean_search class Gostream(Scraper): domains = ['gostream.is'] name = "gostream" sources = [] def __init__(self): self.base_link = 'https://gostream.is' ...
StarcoderdataPython
1738325
<gh_stars>1-10 #!/usr/bin/env python3 import sys commands = {} commands['seq'] = { # non-arg commands 0xff: ['end'], 0xfe: ['delay1'], 0xfd: ['delay', 'var'], 0xfc: ['call', 'addr'], 0xfb: ['jump', 'addr'], 0xfa: ['beqz', 'addr'], 0xf9: ['bltz', 'addr'], 0xf8: ['loop', 'u8'], 0x...
StarcoderdataPython
3386008
# Generated by Django 2.0.3 on 2018-04-02 14:31 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('proxies', '0001_initial'), ] operations = [ migrations.AddField( model_name='proxy', name='letsencrypt', ...
StarcoderdataPython
1760675
<gh_stars>0 #!/usr/bin/python import sys import csv def reducer(): reader = csv.reader(sys.stdin, delimiter='\t') writer = csv.writer(sys.stdout, delimiter='\t') tagFrequency = {} for line in reader: tag = line[0] tagOccurance = int(line[1]) if tag not in tagFrequency: ...
StarcoderdataPython
3206579
import click from src.analyse import ParseTranslationData # SPECs are downloaded from https://src.fedoraproject.org/lookaside/ # https://src.fedoraproject.org/lookaside/rpm-specs-latest.tar.xz @click.command() @click.argument('keyword') @click.option( '--type', help="Parse format, example, SPEC" ) @click.option...
StarcoderdataPython
3393135
<gh_stars>0 from setuptools import setup, find_packages setup( name="Keywordtool Scraper", version="0.0.4", packages=find_packages(), )
StarcoderdataPython
3231381
from backend.database import db class AgentTypeVersion(db.Model): __tablename__ = "AgentTypeVersion" Id = db.Column(db.Integer, primary_key=True) Name = db.Column(db.String) AgentTypeId = db.Column(db.Integer, db.ForeignKey('AgentType.Id'), nullable=False) Payloads = db.relationship('Payload', bac...
StarcoderdataPython
84279
# -*- coding: utf-8 -*- { 'name': 'Slides', 'version': '1.0', 'sequence': 145, 'summary': 'Share and Publish Videos, Presentations and Documents', 'category': 'Website', 'description': """ Share and Publish Videos, Presentations and Documents' ====================================================...
StarcoderdataPython
105038
<filename>relimg.py from PIL import Image #this function saves initial relative image to be searched using CV2. def relimg (imgobj,relx1,rely1,relx2,rely2,canvwidth,canvheight, keynum, tempdir): iniwidth = imgobj.size[0] iniheight = imgobj.size[1] relimg = imgobj.crop((relx1*iniwidth/canvwidth,...
StarcoderdataPython
3395748
<filename>governor/utils.py<gh_stars>1-10 # -*- coding: utf-8 -*- # Copyright 2019 ICON Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-...
StarcoderdataPython
3378835
from orders.models import Orders import factory from faker import Faker import faker.providers.address Faker.seed(0) faker = Faker(['pt_BR']) class OrdersFactory (factory.django.DjangoModelFactory): cpf = faker.cpf() name = faker.name() email = faker.email() postal_code = faker.postcod...
StarcoderdataPython
3221160
<gh_stars>0 ''' To use this extension, follow these instrucitons: https://www.sphinx-doc.org/en/master/development/tutorials/todo.html#using-the-extension ''' from docutils import nodes from docutils.parsers.rst import Directive, directives from sphinx.locale import _ from sphinx.util.docutils import SphinxDirective ...
StarcoderdataPython
1697245
<reponame>mitodl/ocw-studio<filename>videos/signals_test.py """videos.signals tests""" import pytest from videos.constants import DESTINATION_YOUTUBE from videos.factories import VideoFileFactory @pytest.mark.django_db def test_delete_video_file_signal(mocker): """Deleting a youtube VideoFile should trigger the ...
StarcoderdataPython
1675238
<gh_stars>1-10 """Fixture module to skip the unsupervised_learning.rst doctest for versions of SciPy earlier than 0.12.0. """ from sklearn.utils.testing import SkipTest from sklearn.utils.fixes import sp_version def setup_module(module): if sp_version < (0, 12): raise SkipTest("Skipping because SciPy ver...
StarcoderdataPython
158185
from .classifier import USBaggingClassifier __version__ = '0.1.1'
StarcoderdataPython
1732362
import subprocess import logging import jinja2 from random import randint from pathlib import Path from .errors import ProcessingError DEBUG = True def run_subprocess(args): process = subprocess.Popen( args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) stdout, stderr ...
StarcoderdataPython
163326
#! /usr/bin/env python # Copyright 2021 <NAME> # # This file is part of WarpX. # # License: BSD-3-Clause-LBNL import os import sys import yt sys.path.insert(1, '../../../../warpx/Regression/Checksum/') import checksumAPI import numpy as np import scipy.constants as scc ## This script performs various checks for the...
StarcoderdataPython
1663492
<gh_stars>0 import os CURRENT_DIR = os.path.abspath(os.path.dirname(__file__)) DATA_DIR = os.path.join(CURRENT_DIR, 'data') MODELS_DIR = os.path.join(CURRENT_DIR, 'models') environments = { 8: dict( mat_file=os.path.join(DATA_DIR, 'gridworld_8.mat'), train_data_file=os.path.join(DATA_DIR, 'gridwo...
StarcoderdataPython
1742567
#------------------------------------------------------------------------------ # Copyright (c) 2013-2020, Nucleic Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file LICENSE, distributed with this software. #------------------------------------------------...
StarcoderdataPython
3245373
import numpy as np from sklearn import metrics def auc(t, p, **kwargs): # y_pred.shape = (N,) if p.ndim == 2 and t.ndim == 2: p = p[:,0] t = t[:,0] return {'auc': metrics.roc_auc_score(t, p)} def multi_auc(t, p, **kwargs): # y_pred.shape = (N,C) metrics_dict = {} for i in ra...
StarcoderdataPython
3351949
import argparse import glob import logging import os import shutil logging.basicConfig(format='[%(asctime)s] %(levelname)-8s | %(message)s', datefmt='%d-%b-%Y %H:%M:%S', level=logging.INFO) log = logging.getLogger() args_parser = argparse.ArgumentParser(description='Converts strings in files.') ar...
StarcoderdataPython
34863
<reponame>jackytu/newbrandx<filename>sites/newbrandx/rankx/admin.py from django.contrib import admin # Register your models here. from .models import Milk from .models import Brand from .models import Company admin.site.register(Milk) admin.site.register(Brand) admin.site.register(Company)
StarcoderdataPython
3340977
#!/usr/bin/env python3 import numpy as np from math import cos # define x limimts, y limits and step size yl,yh,xl,dx,dy=0,2,0,0.001,0.001 # define lower y limit as function of x def xh(y): return 2*pow(y,0.5) # integrand def func(x,y): return 5*x**3*cos(y**3) #double nested loop to go over each x,y pair a...
StarcoderdataPython
3398505
""" kullanıcıdan aldıgımız boy ve kg değerlerine göre beden kitle hesabı kilo/boy*boy """ boy:float=float(input("boy= ")) kilo:float=float(input("kilo= ")) print("sonuc= ") bdi=float((kilo/(boy*boy))) print(bdi) if bdi >25: print("şişman reyis")
StarcoderdataPython
159076
import im3components as cmp class BuildDocs: TargetFile = 'components.rst' def __init__(self): self.heading = """ ================== Component Registry ================== """ self.body_element = """ {header_bar} {name} {header_bar} **Parent**: {parent} **Child**: {child} ...
StarcoderdataPython
3386039
<reponame>uktrade/great-cms import pytest import requests from contact.helpers import ( extract_other_offices_details, extract_regional_office_details, format_office_details, retrieve_regional_office, retrieve_regional_office_email, ) from directory_api_client.exporting import url_lookup_by_postcod...
StarcoderdataPython
25519
# -*- coding: utf-8 -*- from amplify.agent.common.util.math import median from unittest import TestCase from hamcrest import * __author__ = "<NAME>" __copyright__ = "Copyright (C) Nginx, Inc. All rights reserved." __license__ = "" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" class MathTestCase(TestCase): de...
StarcoderdataPython
3208409
<reponame>zju-vipa/KamalEngine<filename>kamal/vision/models/classification/__init__.py<gh_stars>10-100 from .darknet import * from .mobilenetv2 import * from .resnet import * from .vgg import * from . import cifar from .alexnet import alexnet
StarcoderdataPython
1689155
<filename>tests/test-criticisms/test_metrics.py from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf from edward.criticisms.evaluate import * all_classification_metrics = [ binary_accuracy, sparse_categorical_a...
StarcoderdataPython
1696086
from flask import Blueprint, request from concepts.fields import fields_dict from concepts.schemas import MessageSchema from core.filters_view import shared_filter_view from core.schemas import FiltersWrapperSchema from core.shared_view import shared_view from core.utils import is_cached from extensions import cache f...
StarcoderdataPython
1786488
names = ['Jones', '<NAME>', '<NAME>'] message = f"My first bicycle was a {names[0]}." print(message) message = f"My first bicycle was a {names[1]}." print(message) message = f"My first bicycle was a {names[2]}." print(message)
StarcoderdataPython
3337478
import PIL from PIL import Image import src.pos as pos class ImageMaker: """ This is a class for making Binary PFPs. Attributes: color (str): The color of the PFP. """ def __init__(self): """ Initializes the ImageMaker class. Parameters: None ...
StarcoderdataPython
135993
from ignite.metrics import Metric, Precision, Recall from typing import Sequence, Callable, Optional, Union import torch from ignite.metrics.metric import reinit__is_reduced __all__ = ["FbetaScore"] class FbetaScore(Metric): def __init__( self, beta: int = 1, output_transform: Callable...
StarcoderdataPython
1627354
from optuna.distributions import BaseDistribution from optuna import type_checking if type_checking.TYPE_CHECKING: from typing import Dict # NOQA class UnsupportedDistribution(BaseDistribution): def single(self): # type: () -> bool return False def _contains(self, param_value_in_inter...
StarcoderdataPython
3373964
from __future__ import annotations from abc import ABC, abstractmethod from typing import Callable, Dict, Type, Union from ..backend import graph as G from ..layers import ( ConvolutionLayer, FlattenLayer, FullyConnectedLayer, InputLayer, Layer, MaxPoolLayer, ) ArgsType = Union[int, G.Tensor]...
StarcoderdataPython
1673503
<filename>nbfix.py #!/usr/bin/env python # https://gist.github.com/fbattello/c617e4928c37f3f934d14b90f9cc22fb # Fix IPython notebook files generated by vscode # Failed validating 'additionalProperties' in markdown_cell : https://github.com/microsoft/vscode-python/issues/8772 """ usage: python nbfix.py index.ipynb pyt...
StarcoderdataPython
1666515
from firstclasspostcodes.client import Client
StarcoderdataPython
1633297
<reponame>Khamaldeeen/Property-Scraper import requests import pandas as pd from bs4 import BeautifulSoup import time url = "https://nigeriapropertycentre.com/for-rent/flats-apartments/lagos?bedrooms=3&minprice=300000&maxprice=40000000&q=for-rent+flats-apartments+lagos+3+bedrooms+minprice+300000+maxprice+40000000" ur...
StarcoderdataPython
1647988
<filename>tests/test_spar_benchmark_api.py import unittest from fds.analyticsapi.engines.api.benchmarks_api import BenchmarksApi from fds.analyticsapi.engines.model.spar_benchmark_root import SPARBenchmarkRoot import common_parameters from common_functions import CommonFunctions class TestSparBenchmarkApi(unittest....
StarcoderdataPython
3375205
# -*- coding: utf-8 -*- """ Exceptions and Warnings used in the AltamISA library. """ __author__ = "<NAME> <<EMAIL>>" class IsaException(Exception): """Base class for exceptions raised by Altamisa.""" class ParseIsatabException(IsaException): """Exception raised on problems parsing ISA-TAB.""" class Writ...
StarcoderdataPython
115103
import os import pdb import pandas as pd import pickle as pkl import torch from torch.utils.data import Dataset, DataLoader class DetectionDataset(Dataset): def __init__(self, dslice): """Load the datasets Args: dslice: data slice (train, test, or val) """ dir...
StarcoderdataPython