id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
121597
<reponame>aiiaaiiaaiia/Project<gh_stars>0 import os from flask import Flask, flash, request, redirect, url_for, render_template, jsonify, Response from werkzeug.utils import secure_filename from flask import send_from_directory from rt_atrt_lib import RT_ATRT import time import dw_vdo_url import threading UPLOAD_FOLDE...
StarcoderdataPython
1706099
<reponame>kmarcini/Project-Euler-Python ########################### # # #693 Finite Sequence Generator - Project Euler # https://projecteuler.net/problem=693 # # Code by <NAME> # ###########################
StarcoderdataPython
4839175
def get_min_max(ints): """ Return a tuple(min, max) out of list of unsorted integers. Args: ints(list): list of integers containing one or more integers """ # Handle non-list input if not isinstance(ints, list): return None, None # Define variables for min and max value and...
StarcoderdataPython
113318
#!/usr/bin/env python3 # imports go here import pandas as pd import plotly.plotly as py from plotly.graph_objs import * # # Free Coding session for 2015-05-24 # Written by <NAME> # years = list(range(2015, 2045)) YEARS_TO_SIMULATE = 30 INFLATION_RATE = 0.02 KWH_PRICE = 0.10 # 2015 dollars INSTALL_COST_PER_WATT =...
StarcoderdataPython
3293611
<reponame>twguest/FELPy #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ FELPY @author: twguest Created on Tue Mar 15 21:46:07 2022 __version__ = "1.0.1" __email__ = "<EMAIL>" """ def get_fwhm(): return if __name__ == '__main__': pass
StarcoderdataPython
1640413
# Copyright 2020 Microsoft Corporation # # 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...
StarcoderdataPython
3202134
<filename>editorcontainer/editor/editor.py """ editor ====== Contains the :py:class:`.Editor`, that is, the graphical part of the application to write/edit files. """ import os from pygments import highlight from pygments import lexers from pygments.lexers import get_lexer_for_mimetype from pygments import styles fr...
StarcoderdataPython
1657054
# -*- coding: utf-8 -*- from flask import current_app from lxml import etree namespaces = {'m': 'http://www.loc.gov/MARC21/slim', 'o': 'http://www.openarchives.org/OAI/2.0/'} def get_control_field(xml, field_tag): return xml.xpath('./o:controlfield[@tag="%s"]/text()' % field_tag, namespaces=namesp...
StarcoderdataPython
1716250
from typing import List, NoReturn from discord.ext import commands from zenbot.models import PermissionLevel, Mute from zenbot.helpers import has_cache, check_perms from .command import ZenCommand, ZenCommandParameter class MuteCommand(commands.Cog, ZenCommand): def __init__(self, bot: commands.Bot): se...
StarcoderdataPython
4821155
<gh_stars>0 """ BSD 3-Clause License Copyright (c) 2021, Netskope OSS All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this l...
StarcoderdataPython
4817956
<reponame>jonathanrocher/pybleau<filename>pybleau/app/plotting/plot_style.py from traits.api import Any, Bool, Button, Dict, Enum, Float, HasStrictTraits, \ Int, List, Property, Range, Trait, Tuple from traitsui.api import EnumEditor, HGroup, Item, OKCancelButtons, \ RangeEditor, VGroup, View from enable.api i...
StarcoderdataPython
136764
<gh_stars>0 #!/usr/bin/env python import numpy as np from scipy.stats import pearsonr import pylab as pl import matplotlib from matplotlib.backends.backend_pdf import PdfPages matplotlib.rcParams['ps.useafm'] = True matplotlib.rcParams['pdf.use14corefonts'] = True matplotlib.rcParams['text.usetex'] = True FONTSIZE = 2...
StarcoderdataPython
3280211
from django.core.exceptions import ImproperlyConfigured # Want to get everything from the 'normal' models package. from django.db.models import * # NOQA from django.utils.version import get_docs_version from django.contrib.gis.geos import HAS_GEOS if not HAS_GEOS: raise ImproperlyConfigured( "GEOS is re...
StarcoderdataPython
1605699
<gh_stars>0 from __future__ import absolute_import, unicode_literals import warnings from modeltranslation import settings as mt_settings from modeltranslation.utils import build_localized_fieldname def get_lang_obj(lang_code, cls, field_name, *args, **kwargs): """ Instantiates any `cls` with localized fiel...
StarcoderdataPython
55638
#!/usr/bin/env python # Copyright (C) 2016 Apple Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met:n # # 1. Redistributions of source code must retain the above copyright # notice, this li...
StarcoderdataPython
77864
<filename>shenjieting/Study/Study_request.py<gh_stars>1-10 import urllib.request import urllib.parse ''' urllib中包括了四个模块,包括:urllib.request,urllib.error,urllib.parse,urllib.robotparser urllib.request可以用来发送request和获取request的结果 urllib.error包含了urllib.request产生的异常 urllib.parse用来解析和处理URL urllib.robotparse用来解析页面的robots.txt文...
StarcoderdataPython
39369
<filename>project-euler/solutions/015.py #!/usr/bin/env python ''' 015.py: https://projecteuler.net/problem=15 Lattice paths Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner. How many such routes are there through...
StarcoderdataPython
76359
<reponame>davesanjay/reproducible-computational-workflows<filename>2-conda/hello.py print "Hello Basel!"
StarcoderdataPython
1621021
# HELPFUL CONSTANTS aToB = sin(PI/5) / sin(2*PI/5) # DRAWING def drawEdge(lxy): for i in range(0,len(lxy)-1): x1,y1 = lxy[i] x2,y2 = lxy[i+1] line(x1,y1,x2,y2) def drawEditPoints(lxy,r): noStroke() for x,y in lxy[1:-1]: ellipse(x,y,r,r) def drawEditPointsPlus(...
StarcoderdataPython
28214
import setuptools import os with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="supportr", version="0.1", author="<NAME> and <NAME>", author_email="<EMAIL>", description="Supportr", long_description=long_description, long_description_content_type="te...
StarcoderdataPython
3234023
from __future__ import print_function from orphics import maps,io,cosmology,stats from pixell import enmap,curvedsky as cs import numpy as np import os,sys from tilec import utils as tutils import healpy as hp #Port of healpix module coord_v_convert.f90 to python by JLS #Feb 28, 2017 from numpy import sin,cos from nu...
StarcoderdataPython
3276111
import jieba import simjb import torbjorn as tbn def get_data(name): train_data_path = f"./icwb2-data/training/{name}_training.utf8" with open(train_data_path, "r") as f_data: datas = f_data.readlines() return datas @tbn.run_time def calc(datas, data_name, tool_name, tool): all_num = 0 t...
StarcoderdataPython
3210139
<gh_stars>1-10 # (c) 2018-2021, <NAME> @ ETH Zurich # Computer-assisted Applications in Medicine (CAiM) Group, Prof. <NAME> import os, itertools from data_read.imarisfiles import ImarisFiles from config import system import argparse import numpy as np import urllib import zipfile import logging import pandas as pd...
StarcoderdataPython
3262127
<reponame>vincent-l-j/micropython-stubber import pytest # from libcst.codemod import CodemodTest from stubber.codemod.commands.noop import NOOPCommand ################################################################################ # Define a few codeblock for testing of the libcst parser ############################...
StarcoderdataPython
1716812
import re import unittest from django import forms from django.apps import AppConfig from django.utils.functional import curry class PyDataConfig(AppConfig): name = 'pydata' label = 'PyData' verbose_name = 'AMY for PyData conferences' def ready(self): from . import checks from works...
StarcoderdataPython
1607596
# 唐诗生成 import collections import os import sys import time import numpy as np import tensorflow as tf # 这里引入可能出错 from models.model import rnn_model # 句子预处理 产生batch函数 from dataset.fiction import process_poems, generate_batch import heapq # 后面那个是说明 tf.flags.DEFINE_integer('batch_size', 64, 'batch size.') tf.flags.DEFINE...
StarcoderdataPython
128245
import cv2 # reading the image image = cv2.imread(filename=r'.\img\Resized.jpg') cv2.putText(image,"Bhanu",org=(100,300),fontFace=cv2.FONT_ITALIC,fontScale=4,color=(3,5,23),thickness=2,lineType=3) cv2.putText(image,"Deepak",org=(00,100),fontFace=cv2.FONT_ITALIC,fontScale=4,color=(3,5,23),thickness=2,lineType=3) # disp...
StarcoderdataPython
117147
'''Copyright 2017, Deepak Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions i...
StarcoderdataPython
3267937
<filename>backend/src/baserow/config/settings/test.py from .base import * # noqa: F403, F401 USER_FILES_DIRECTORY = 'user_files' USER_THUMBNAILS_DIRECTORY = 'thumbnails' USER_THUMBNAILS = {'tiny': [21, 21]}
StarcoderdataPython
1768045
<gh_stars>0 from django import forms from django.utils.translation import gettext as _ class ProfileForm(forms.Form): email = forms.EmailField(label=_("Email address"), max_length=150) first_name = forms.CharField(label=_("First name"), max_length=150, required=False) last_name = forms.CharField(label=_("...
StarcoderdataPython
48662
# Copyright 2012 <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
1744918
<reponame>MonwarAdeeb/HackerRank-Solutions<gh_stars>0 # Enter your code here. Read input from STDIN. Print output to STDOUT import math def bi_dist(x, n, p): b = (math.factorial(n)/(math.factorial(x)*math.factorial(n-x)))*(p**x)*((1-p)**(n-x)) return(b) b, p, n = 0, 1.09/2.09, 6 for i in range(3,7): b += ...
StarcoderdataPython
117227
<reponame>c1c4/five-best_restaurants<filename>setup.py from setuptools import setup, find_packages NAME = 'best-matched-restaurants' VERSION = '1.0.0' REQUIRES = ['flask'] setup( name=NAME, version=VERSION, description=NAME, author_email='<EMAIL>', url='', keywords=['Swagger', NAME], inst...
StarcoderdataPython
1723677
import pandas as pd import numpy as np def cr_uplift(control, variant, round=None): """ Compute uplift Parameters ---------- control : float Proportion in control group variant : float Proportion in variant group round If int rounds the results to this number of de...
StarcoderdataPython
46720
from .example_model import get_chain_model,get_trailer_model from .trailer_printer import trailer_print,draw_rectangular_obstacle,draw_rectangular_obstacle_around_center
StarcoderdataPython
1781829
import time from torch.utils.data import DataLoader from dxtorchutils.utils.metrics import accuracy import numpy as np from dxtorchutils.utils.utils import state_logger from dxtorchutils.utils.info_logger import Logger import random import torch class TrainVessel: def __init__( self, datal...
StarcoderdataPython
66851
<reponame>cmu-catalyst/FlexFlow<gh_stars>0 from flexflow.core import * from flexflow.keras.datasets import cifar10 from flexflow.torch.model import PyTorchModel import os import numpy as np #from accuracy import ModelAccuracy from PIL import Image def top_level_task(): ffconfig = FFConfig() alexnetconfig = NetCon...
StarcoderdataPython
3200589
PATH_ROOT='C:/Users/<NAME>/Desktop/ICoDSA 2020/SENN/' print('==================== Importing Packages ====================') import warnings warnings.filterwarnings("ignore", category=FutureWarning) import pandas as pd import re import json import math import string import numpy as np from bs4 import BeautifulSoup i...
StarcoderdataPython
128902
<reponame>chengweilun/api_client # Copyright 2015 Fortinet, Inc. # # All Rights Reserved # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unl...
StarcoderdataPython
1776732
# Copyright 2020 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
StarcoderdataPython
3228076
<gh_stars>0 # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("foirequest", "0003_foirequest_reference"), ] operations = [ migrations.AddField( model_name="foirequ...
StarcoderdataPython
115673
# Flask configurations import os import sys sys.path.append(os.path.dirname(__file__)+'/AI') os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
StarcoderdataPython
1613959
<reponame>upstart-swiss/demisto-sdk<filename>demisto_sdk/commands/common/tests/update_id_set_test.py import json import logging import os import sys import tempfile import unittest from pathlib import Path import pytest import demisto_sdk.commands.common.update_id_set as uis from demisto_sdk.commands.common.constants...
StarcoderdataPython
4813652
import inspect from collections import UserList class Operator: def __init__(self, name, fn, num=None): self.name = name self.fn = fn self.num = num or len(inspect.signature(self.fn).parameters) # inspect arg number of operator def __repr__(self): return f"{self.name}" clas...
StarcoderdataPython
1775776
import unittest from swamp.parsers.mtzparser import MtzParser class MockGemmiMtz(object): """A class to mock :py:obj:gemmi.Mtz for testing purposes :param list columns: a list containing instances of :py:obj:`~swmap.parsers.tests.test_mtz_parser.MockGemmiMtzColumn` """ def __init__(self, columns): ...
StarcoderdataPython
3292853
import logging import hikaru from typing import Dict, Any, Optional from pydantic import BaseModel, PrivateAttr from .autogenerated.events import KIND_TO_EVENT_CLASS from .autogenerated.models import get_api_version from .model_not_found_exception import ModelNotFoundException from ..helper import prefix_match, exact_...
StarcoderdataPython
1779202
from typing import List class Solution: def calPoints(self, ops: List[str]) -> int: record = [] for i in ops: if(i == "C"): record.pop() elif(i == "D"): record.append(record[-1]*2) elif(i == "+"): record.append(rec...
StarcoderdataPython
87025
from selenium import webdriver from time import sleep from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC class Github: def __init__(self): self.brower = webdriver.Firefox(executable_pat...
StarcoderdataPython
1602447
somaidade=0 mediaidade=0 maioridadehomen=0 nomevelho='' totmulher20=0 for p in range(1,5): print('-------{} pessoa-------'.format(p)) nome=str(input('nome:')).strip() idade=int(input('idade')) sexo=str(input('sexo: [m/f]: ')).strip() somaidade+=idade if p ==1 and sexo in 'Mm': maioridade...
StarcoderdataPython
1666600
#!/usr/bin/env python import rospy from geometry_msgs.msg import Twist from sensor_msgs.msg import LaserScan from nav_msgs.msg import Odometry from tf.transformations import euler_from_quaternion import math pi = 3.14159265359 pose = [0 , 0 ,0 ] def Waypoints(): x2 = list() y2 = list() i=0 while i<=3...
StarcoderdataPython
1687215
# python3 ResultsVisualisation.py # -*- coding: utf-8 -*- # =========================================================================================== # Created by: <NAME> # Description: Plots the sales prediction results of the different machine learning models # ======================================================...
StarcoderdataPython
3285949
<reponame>y-srini/opentitan<filename>hw/ip/otbn/dv/rig/rig/gens/bad_bnmovr.py # Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 import random from typing import Optional from shared.operand import RegOperandType, OptionOp...
StarcoderdataPython
1718715
#!/usr/bin/env python # # Paramiko Expect Demo Helper # # Written by <NAME> # http://github.com/fgimian # # This interactive script is used to help demonstrate the paramiko_expect-demo.py # script from __future__ import print_function import sys if sys.version_info.major == 3: raw_input = input def main(): ...
StarcoderdataPython
1631032
## sql definition to import and export data import psycopg2 as pgsql import pandas as pd import sqlalchemy, os from ctdays import raw_ctd_to_df def export_sql(database_name, edit, location): # export table from sql # cruise name (in list, case insensitive) for AWI server, # table name for local if lo...
StarcoderdataPython
3238002
"""Implement extraction of 3D voxel-based morphological features.""" from typing import List, Optional import numpy.typing as npt from ..gpu import get_image_method def regionprops(image_bin: npt.ArrayLike, image: npt.ArrayLike, features: Optional[List] = None): """Extract region-based morphological features.""...
StarcoderdataPython
1615015
<gh_stars>0 import os import shutil from .base import GnuRecipe class Extra: def __init__(self, name): self.name = name self.sha256 = None class SwiPrologRecipe(GnuRecipe): def __init__(self, *args, **kwargs): super(SwiPrologRecipe, self).__init__(*args, **kwargs) self.sha256...
StarcoderdataPython
3248425
<reponame>happyseayou/tello_the_force """ 如何调用: mapcom=Mapcom() while:#视频帧循环里 if userc[4]==2 or userc[4]==3:进入map mapcom.readflightdata(data)#第一步更新飞行数据data由飞机类给出 comd=mapcom.com(userc)#需要传入用户控制指令,不然万一出错就放生了 flightdata=mapcom.send_flightdata()#将所有飞行数据传出用于显示和其他端口调用 if mapcom.checkal...
StarcoderdataPython
3311656
<gh_stars>1-10 from rest_framework import status from rest_framework.authtoken.models import Token from .basetests import BaseTest from questions.models import Question class QuestionModelTest(BaseTest): """ Tests for questions creation model """ def test_delete_question(self): """ Te...
StarcoderdataPython
3289370
<gh_stars>0 from honeybee import HoneyBee hb = HoneyBee('localhost', 8080, 'talbor49', '1234') print(hb.use('x')) print(hb.set('tal', 'bae')) print(hb.get('tal'))
StarcoderdataPython
3246043
<filename>ex.8(2).py list1=['d', 'cccc', 'bb', 'aaa'] def mysort(mylist = [],numflag = False): if numflag == False: mylist.sort(key = lambda x: x[0]) else: mylist.sort(key = len) return print(mylist) mysort(list1) mysort(list1, True) print('DONE')
StarcoderdataPython
197686
<reponame>andrewcharlesjones/cplvm<filename>experiments/simulation_experiments/hypothesis_testing/global_ebfs_cplvm_splatter.py import matplotlib from cplvm import CPLVM from cplvm import CPLVMLogNormalApprox from os.path import join as pjoin import functools import warnings import matplotlib.pyplot as plt import num...
StarcoderdataPython
1769248
from GradientDescent import *
StarcoderdataPython
25668
<filename>chapter03/python/situation.py from sklearn.metrics.pairwise import cosine_similarity import numpy as np import pandas as pd # 1. Load Data and Item Profile ratings = pd.read_csv('chapter03/data/movie_rating.csv') movie_ratings = pd.pivot_table( ratings, values='rating', index='title', column...
StarcoderdataPython
3210240
#!/usr/bin/env python3 '''Simple script to verify SHA256 hashes and rename downloaded versions with their version number''' import json import requests import hashlib from pathlib import Path class DownloadException(Exception): pass def sha256(path): with open(filename,"rb") as f: return hashlib.sha...
StarcoderdataPython
1683290
<filename>config/__init__.py __author__ = 'tuanvu' __create_time__ = '29/05/2015 2:17 PM'
StarcoderdataPython
3228872
# Generated by Django 2.2.6 on 2020-04-15 14:34 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("customers", "0009_rename_company_to_organization"), ] operations = [ migrations.AddField( model_name="organization", ...
StarcoderdataPython
3383351
<filename>misc_codes/seshat_misc.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Apr 12 12:55:40 2019 @author: hajime """ ''' Asymmetric regresion and MHG graphing. ''' #%% ''' Asymmetry regression ''' from sklearn.linear_model import LinearRegression CC_scaled_df = pd.DataFrame(CC_scaled,col...
StarcoderdataPython
1685654
<gh_stars>100-1000 """ Copyright (c) 2015-2020 <NAME>(<EMAIL>), StopStalk 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 without limitation the righ...
StarcoderdataPython
29958
#!/usr/bin/env python ''' Calculating the emissions from deposits in Platypus stable accounts ''' import numpy as np import matplotlib.pyplot as plt from matplotlib import cm from matplotlib.ticker import LinearLocator, EngFormatter, PercentFormatter from strategy_const import * from const import * def boosted_pool_...
StarcoderdataPython
3263203
# Copyright (C) 2017-2019 <NAME> # SPDX-License-Identifier: Apache-2.0 import dolfin from ocellaris.utils import shift_fields def before_simulation(simulation, force_steady=False): """ Handle timestepping issues before starting the simulation. There are basically two options, either we have full velocity...
StarcoderdataPython
1770450
import unittest import tempfile import os from .ParsedArgs import ParsedArgs from meraki_cli.__main__ import _args_from_file class TestArgsFromFile(unittest.TestCase): def setUp(self): self.parsed_args = ParsedArgs() def testArgsFromFileExplicitPathNoExist(self): self.parsed_args.configFile ...
StarcoderdataPython
3371650
<filename>hi-ml/testhiml/testhiml/test_attentionlayers.py import pytest from typing import Type, Union from torch import nn, rand, sum, allclose, ones_like from health_ml.networks.layers.attention_layers import (AttentionLayer, GatedAttentionLayer, MeanPoolingLa...
StarcoderdataPython
3285661
import numpy from .dtypes import index_type,value_type,label_type class FactorSubset(object): """ Holds a subset of factor indices of a graphical model. This class is used to compute queries for a a subset of a gm. This queries are very efficient since allmost all members are implemented ...
StarcoderdataPython
132682
<reponame>HugoS99/DagTest<filename>dag.py from airflow import DAG from datetime import datetime, timedelta from airflow.contrib.operators.kubernetes_pod_operator import KubernetesPodOperator from airflow.operators.dummy_operator import DummyOperator default_args = { 'owner': 'airflow', 'depends_on_past': Fals...
StarcoderdataPython
113811
n = input() def gcd(m, n): while True: m %= n if m == 0: return n n %= m if n == 0: return m def lcm(m, n): g = gcd(m ,n) return m * n / g def omin(n): r = n for i in range(2, n): if r % i != 0: r = lcm(r,...
StarcoderdataPython
4834542
# Copyright 2021 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "license...
StarcoderdataPython
1752153
#!/usr/bin/env python """ _New_ MySQL implementation of Jobs.New """ __all__ = [] import time import logging from WMCore.Database.DBFormatter import DBFormatter class New(DBFormatter): sql = """INSERT INTO wmbs_job (jobgroup, name, state, state_time, couch_record, cache_dir...
StarcoderdataPython
51460
# This file is Public Domain and may be used without restrictions. import _jpype import jpype from jpype.types import * from jpype import java import jpype.dbapi2 as dbapi2 import common import time try: import zlib except ImportError: zlib = None class SQLModuleTestCase(common.JPypeTestCase): def setUp(...
StarcoderdataPython
141863
<reponame>PatDaoust/MiscellaneousExercises<filename>Khan Academy Algorithms.py # -*- coding: utf-8 -*- """ Created on Mon Mar 22 16:30:42 2021 @author: catal """ import pdb import unittest # 1Let min = 0 and max = n-1. # 2If max < min, then stop: target is not present in array. Return -1. # 3Compute guess as the ave...
StarcoderdataPython
163390
""" Tests dataset views methods """ from __future__ import unicode_literals from __future__ import absolute_import import copy import datetime import json import django from django.utils.timezone import now from rest_framework import status from rest_framework.test import APITestCase from data.data.json.data_v6 impo...
StarcoderdataPython
1608151
<reponame>michael-christen/toolbox #!/usr/bin/env python3 import csv import json import sys import re RECIPE_RE = re.compile( r'[Rr]ecipe( here)?: (?P<url>http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\), ]|(?:%0-9a-fA-F][0-9a-fA-F]))+)') def main(): rows = get_rows() write_rows(rows) def write_rows(rows)...
StarcoderdataPython
116219
#!coding:utf-8 from sys import path as sys_path from os import path as os_path import subprocess import pytest sys_path.append(os_path.abspath(os_path.join(os_path.dirname(__file__), "../"))) import autoargparse @pytest.mark.example @pytest.mark.parametrize( "input,expected", [ ("python ./example/c...
StarcoderdataPython
1698957
from torch.nn import functional as F from torch import nn import torch class _Scorer(nn.Module): def __init__(self, n_classes, soft=False, apply_softmax=True, skip_first_class=True, smooth=1e-7): super(_Scorer, self).__init__() self.register_buffer('eye', torch.eye(n_classes)) self.soft = ...
StarcoderdataPython
18975
import collections import functools import json import logging import multiprocessing import os import time from collections import OrderedDict from queue import PriorityQueue, Empty from typing import List, Tuple, Any from itertools import cycle, islice import minerl.herobraine.env_spec from minerl.herobraine.hero imp...
StarcoderdataPython
108133
""" Module containing flask init and several """ from flask import request, render_template, redirect, url_for import hashlib import os from application.factories import make_flask_app # from celery_app import celery_app environment = os.environ.get('ENVIRONMENT') app = make_flask_app("log-parser", environment) def ...
StarcoderdataPython
89623
<reponame>basicpail/core """Test different accessory types: Triggers (Programmable Switches).""" from unittest.mock import MagicMock from homeassistant.components.homekit.type_triggers import DeviceTriggerAccessory from homeassistant.const import STATE_OFF, STATE_ON from homeassistant.setup import async_setup_compone...
StarcoderdataPython
3254946
<gh_stars>0 from .boids import Flock, Boid from matplotlib import pyplot as plt from matplotlib import animation from argparse import ArgumentParser import yaml import os def parse_args(): parser = ArgumentParser(description = "Runs the program.") parser.add_argument('--file', type=str, help='YAML ...
StarcoderdataPython
3270916
<reponame>djokester/autokeras # Copyright 2020 The AutoKeras Authors. # # 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...
StarcoderdataPython
1742231
<reponame>DavidsDvm/Dev_Exercises """ Programa que busque el area y el perimetro de un circulo """ print ("~=======================================~") radio = int(input("Ingrese el radio del circulo")) print ("~=======================================~") area = 3.1416 * (radio ** 2) perimetro = (radio * 2) * 3.1416 pr...
StarcoderdataPython
3277509
<reponame>emily-gordy/Decadal-SST-prediction<gh_stars>0 #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Oct 28 11:40:40 2021 @author: emgordy """ # Train NNs # this script was run on a cluster and takes days. Proceed with caution import xarray as xr import glob import numpy as np import math impor...
StarcoderdataPython
107878
# PROBABILISTIC ROBOT ACTION CORES # # (C) 2014 by <NAME> (<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 Software without restriction, including # without limitation the rights to use, c...
StarcoderdataPython
4836686
<gh_stars>1-10 # Copyright (c) 2016, Manito Networks, LLC # All rights reserved. import time, datetime, socket, struct, sys, json, socket, logging, logging.handlers from struct import * from socket import inet_ntoa from IPy import IP import dns_base import site_category from netflow_options import * def dns_add_addr...
StarcoderdataPython
3281549
""" Implements custom ufunc dispatch mechanism for non-CPU devices. """ from __future__ import print_function, absolute_import import operator import warnings from functools import reduce import numpy as np from numba.utils import longint, OrderedDict from numba.utils import IS_PY3 from numba.npyufunc.ufuncbuilder i...
StarcoderdataPython
112159
"""Tests for privacy.schema.embed""" from privacy.schema import embeds def test_embed_request(): embed_request_obj = embeds.EmbedRequest(token="<PASSWORD>", css="https://www.not_a.url") assert embed_request_obj.token == "<PASSWORD>" assert embed_request_obj.css == "https://www.not_a.url" assert embed_...
StarcoderdataPython
3395302
# !/usr/bin/python3 # -*- coding: utf-8 -*- # import subfolders here from utilsJ.Slack.hooks import msger, whisp # should remove above import, bad practise # from utilsJ.Behavior import glm2afc, plotting, models, ComPipe # import sys # import os # import numpy as np # import pandas as pd # #import swifter # import m...
StarcoderdataPython
47826
<filename>pip_update.py<gh_stars>10-100 import re import os import sys import shutil import subprocess def pip_update(): # Check for Ubuntu and get the wxPython extras release version. UBUNTU_RELEASE = '' os_release_file = '/etc/os-release' if os.path.exists( os_release_file ): with open( os_release_file ) as f:...
StarcoderdataPython
3291136
from torch.nn import functional as F import torch import sys import numpy as np from matplotlib import pyplot as plt from matplotlib import colors import gflags FLAGS = gflags.FLAGS gflags.DEFINE_string('filename', None, '') palette = ['83E76B', 'CDE584', 'DEDB6A', 'F39D58', 'C44028'] #palette = ['EA1B20', '12111...
StarcoderdataPython
1713206
from exchange_cash.exchange import Exchange class Cash: def __init__(self, cents: int, exchange: Exchange): self._exchange = exchange self._cents = cents @property def cents(self): return self._cents def in_(self, currency: str): return Cash( self._cents ...
StarcoderdataPython
3218849
import sqlite3 from Terminal import Terminal from LoginScreen import LoginScreen from RegisterScreen import RegisterScreen from WelcomeScreen import WelcomeScreen from MainMenuScreen import MainMenuScreen from PostScreen import PostScreen from SearchForPostsScreen import SearchForPostsScreen from PostQuery import Quest...
StarcoderdataPython
35270
import glob,os,sys class Path(): ''' >>> paths = Path(source,"*.txt") >>> for path in paths: lines = Stream(path) for line in lines: print(line) ''' def __init__(self, source, pattern): self.source = source self.pattern = pattern ...
StarcoderdataPython