id
stringlengths
2
8
text
stringlengths
16
264k
dataset_id
stringclasses
1 value
1787866
from .shadowstack import ShadowStack from .cpuid import CpuId from .shiftstack import ShiftStack from .adversarial import Adversarial from .binary_optimization import BinaryOptimization from .simple_ptr_enc import SimplePointerEncryption
StarcoderdataPython
399425
#!/usr/bin/env python # Advanced Multi-Mission Operations System (AMMOS) Instrument Toolkit (AIT) # Bespoke Link to Instruments and Small Satellites (BLISS) # # Copyright 2017, by the California Institute of Technology. ALL RIGHTS # RESERVED. United States Government Sponsorship acknowledged. Any # commercial use must...
StarcoderdataPython
12823421
#!/usr/bin/env pybricks-micropython import math from pybricks.hubs import EV3Brick from pybricks.parameters import Color from pybricks.tools import wait from pybricks.media.ev3dev import Font, Image # Initialize the EV3 ev3 = EV3Brick() # SPLIT SCREEN ##############################################################...
StarcoderdataPython
6605754
# -*- coding: utf-8 -*- import math import logging logger = logging.getLogger(__name__) class NoPruning: @classmethod def filter(cls, Pe, Le, Te, *args): for i in range(1, len(Pe)+1): for j in range(i+1, len(Pe)+1): yield i, j class LazyCountPruning: @cla...
StarcoderdataPython
6529215
<filename>flowchem/components/stdlib/y_mixer.py from typing import Optional from flowchem.components.properties import PassiveMixer class YMixer(PassiveMixer): """ A Y mixer. This is an alias of `Component`. Arguments: - `name`: The name of the mixer. Attributes: - See arguments. "...
StarcoderdataPython
6494727
<gh_stars>0 from testdata import PROBLEMS from testdata import GOOGLE_PROBLEMS import unittest from clausefinder import ClauseFinder from clausefinder import googlenlp class GoogleTest(unittest.TestCase): """Test ClauseFinder using Google NLP""" def test0_JsonProblems(self): if GOOGLE_PROBLEMS is Non...
StarcoderdataPython
3412321
import base64 import random import string from rotkehlchen.fval import FVal from rotkehlchen.utils.misc import ts_now def make_random_bytes(size): return bytes(bytearray(random.getrandbits(8) for _ in range(size))) def make_random_b64bytes(size): return base64.b64encode(make_random_bytes(size)) def make_...
StarcoderdataPython
6620211
<gh_stars>1-10 from tool.runners.python import SubmissionPy class JonSubmission(SubmissionPy): def run(self, s): m = s.strip().splitlines() ny = len(m) nx = len(m[0]) def val(x, y): if x < 0 or x >= nx or y < 0 or y >= ny: return 10 return ...
StarcoderdataPython
3387939
<reponame>awesome-archive/Dragon<gh_stars>0 # ------------------------------------------------------------ # Copyright (c) 2017-present, SeetaTech, Co.,Ltd. # # Licensed under the BSD 2-Clause License. # You should have received a copy of the BSD 2-Clause License # along with the software. If not, See, # # <https:...
StarcoderdataPython
6614168
<reponame>vhn0912/python-snippets import numpy as np a_2d = np.arange(12).reshape(3, 4) print(a_2d) # [[ 0 1 2 3] # [ 4 5 6 7] # [ 8 9 10 11]] a_2d[0, 0] = 100 print(a_2d) # [[100 1 2 3] # [ 4 5 6 7] # [ 8 9 10 11]] a_2d[0] = 100 print(a_2d) # [[100 100 100 100] # [ 4 5 6 7] # [...
StarcoderdataPython
4900096
<reponame>jay-johnson/celery-loaders import celery from spylunking.log.setup_logging import build_colorized_logger log = build_colorized_logger( name='custom-task') class CustomTask(celery.Task): """CustomTask""" log_label = "custom_task" def on_success(self, retval, task_id, args, kwargs): ...
StarcoderdataPython
4831285
#!/usr/bin/env python """ Normalise count file by RPM """ __author__ = "<NAME>" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" import sys htseq = open(sys.argv[1], "r") htseq_readlines = htseq.readlines() htseq.close() total_reads = float(sys.argv[2]) scaling_factor = float(total_reads/1000000) raw_and_rpm_ou...
StarcoderdataPython
11266089
import pytest import scipy.optimize as sopt import scipy.sparse as sp import numpy as np from numpy.testing import assert_array_almost_equal from nnls import block_pivoting, lawson_hanson def test_block_pivoting(): # design matrix size (square) n = 100 # -------------------------------------------------...
StarcoderdataPython
11231569
<filename>tests/conftest.py<gh_stars>0 import hypothesis hypothesis.settings.register_profile('dev', max_examples=10) hypothesis.settings.register_profile('dist', max_examples=100)
StarcoderdataPython
9763827
from django.shortcuts import render from django.shortcuts import redirect from InvManage.models import EventCard, HistoryFilterState from InvManage.filters import EventCardFilter from django.http import JsonResponse, HttpResponse from django.template.response import TemplateResponse from InvManage.serializers import Hi...
StarcoderdataPython
3278256
<filename>docs/_mocked_modules/ctypes/__init__.py """Bare minimum mock version of ctypes. This shadows the real ctypes module when building the documentation, so that :mod:`rubicon.objc` can be imported by Sphinx autodoc even when no Objective-C runtime is available. This module only emulates enough of ctypes to make...
StarcoderdataPython
5027443
#! /usr/bin/env python import pathlib import re import shutil import os import git from ha import prepare_homeassistant from const import ( TMP_DIR, PACKAGE_DIR, REQUIREMENTS_FILE, CONST_FILE, REQUIREMENTS_FILE_DEV, LICENSE_FILE_HA, LICENSE_FILE_NEW, path, files, requirements_remove, HA_VERSION_FILE, ) if o...
StarcoderdataPython
6475912
def solution(S): p = "" N = 0 for s in S: p += s unique = set() for k in range(1, 1 + len(p)): c = p[-k] if c in unique: unique.remove(c) else: unique.add(c) N += 1 if len(unique) == k % 2 else 0 ret...
StarcoderdataPython
1735895
import pandas as pd from sklearn import preprocessing from sklearn.model_selection import train_test_split import numpy as np class Preprocessor: def __init__(self): pass def normalize(self, df, columns): min_max_scaler = preprocessing.MinMaxScaler() df[columns] = min_max_scaler.fit_t...
StarcoderdataPython
8002493
<gh_stars>0 #pip install lxml #pip install pyOpenSSL import requests import json from bs4 import BeautifulSoup as bs import ssl import time ''' The elsevier search is kind of a tree structure: "keyword --> a list of journals (a journal contain many articles) --> lists of articles ''' journals = [] art...
StarcoderdataPython
3495297
<filename>The-Sieve-of-Eratosthenes/SoE2.py # interater version # return generator derectly class myClass(): prime_numbers = [] index = 0 count = 0 def __init__(self, num): if num <= 0: raise RuntimeError("Not positive integer") elif num == 1: raise RuntimeErro...
StarcoderdataPython
6456118
<gh_stars>1-10 import tensorflow as tf from tensorflow.python.framework import graph_util with tf.Session() as sess: with open('./expert-graph.pb', 'rb') as graph: graph_def = tf.GraphDef() graph_def.ParseFromString(graph.read()) for i in graph_def.node: print(i.name) ou...
StarcoderdataPython
8102385
# coding: utf-8 import logging from typing import List, Optional from .api_area_block import ApiAreaBlock from ..web.block_obj import BlockObj from ..dataclass.ns import Ns from ..dataclass.area import Area from ..common.regx import pattern_http from ..common.constants import URL_SPLIT from ..common.log_load import Log...
StarcoderdataPython
11236883
<gh_stars>100-1000 import argparse import logging import uuid from urllib.parse import urljoin, urlparse import os import requests import requests.exceptions import tldextract from bs4 import BeautifulSoup from py_ms_cognitive import PyMsCognitiveWebSearch, PyMsCognitiveImageSearch parentdir = os.path.dirname(os.path...
StarcoderdataPython
3437009
<reponame>harry1911/CoolCompiler<gh_stars>0 from general import visitor, errors from general import ast_hierarchy as ast from .type import Type class TypeBuilderVisitor: def __init__(self, enviroment): self.enviroment = enviroment self.current_type = None # type(current_type) = Type ...
StarcoderdataPython
5195081
from Duelist_Algorithm import Duelist_Algorithm import math def f(x1,x2): x = [] x.append(x1) x.append(x2) obj = (math.sin(3*x[0]*math.pi))**2 + ((x[0] - 1)**2)*(1 + math.sin(3*x[1]*math.pi)**2) + ((x[1] - 1)**2)*(1 + math.sin(2*x[1]*math.pi)**2) return obj #İstenilen test fonksiyonu, f isimli fonksiyonda obj ol...
StarcoderdataPython
1707332
<reponame>acrenwelge/python-stuff<filename>simple-scripts/create-tar.py import tarfile import glob def create_tarfile(): tfile = tarfile.open("mytarfile.tar", "w") for file in glob.glob(pathname="./test/*.txt"): tfile.add(file) tfile.close() create_tarfile()
StarcoderdataPython
11271684
<gh_stars>1-10 # Copyright 2020 The TensorFlow Authors. 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 requ...
StarcoderdataPython
6499675
<gh_stars>0 # 生产者 -- 任务, 函数 # 1. 这个函数,必须要让 celery 的实例, task 装饰器 装饰 # 2. 需要 celery 自动检测指定包的任务 from libs.yuntongxun.sms import CCP from celery_tasks.main import app @app.task def celery_send_sms_code(mobile, code): CCP().send_template_sms(mobile, [code, 5], 1)
StarcoderdataPython
8017376
<reponame>dgarrett622/EXOSIMS # -*- coding: utf-8 -*- import numpy as np import astropy.units as u class ZodiacalLight(object): """Zodiacal Light class template This class contains all variables and methods necessary to perform Zodiacal Light Module calculations in exoplanet mission simulation...
StarcoderdataPython
1772594
import unittest import tornado.httputil from imbi import errors class DefaultFunctionalityTests(unittest.TestCase): def test_that_error_url_can_be_configured(self): saved_error_url = errors.ERROR_URL try: errors.set_canonical_server('server.example.com') err = errors.Appl...
StarcoderdataPython
3551116
import cocotb from cocotb.clock import Clock from cocotb.triggers import Timer, RisingEdge import logging from cocotb.wavedrom import trace import wavedrom from cocotb.binary import BinaryRepresentation, BinaryValue @cocotb.test() async def gcd_Test(dut): clk = Clock(dut.clk,10,"ns") cocotb.fork(clk.start()) ...
StarcoderdataPython
3295066
<reponame>loremipsumdolor/STEVE ''' S.T.E.V.E. Console Interactive command-line console A software component of S.T.E.V.E. (Super Traversing Enigmatic Voice-commanded Engine) Code and device by <NAME>; code released under the MIT license ''' import threading import cmdparser class console(threading.Thread): def _...
StarcoderdataPython
6649811
""" Defines the S3Model ontology in Python 3.7 Copyright, 2009 - 2022, <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 applica...
StarcoderdataPython
1642984
<filename>python/smap/ops/test/test_meter.py<gh_stars>10-100 """ Copyright (c) 2011, 2012, Regents of the University of California All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of ...
StarcoderdataPython
9654173
<reponame>jrderek/Data-science-master-resources import mysql.connector db = mysql.connector.connect( host="127.0.0.1", user="root", password="<PASSWORD>", database="employee_data", ) cursor = db.cursor() sql = "UPDATE customers SET name=%s, address=%s WHERE customer_id=%s" val = ("ShakibAL", "Dhaka", ...
StarcoderdataPython
9668368
from car.camera import Camera from car.car_status import CarStatus from car.motor import Motor class Car: """ This car represents the Raspberry Pi car """ def __init__(self, m1_forward, m1_backward, m2_forward, m2_backward, m3_forward, m3_backward, m4_forward, m4_backward, resolution_x, reso...
StarcoderdataPython
1632993
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2013 OpenStack 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
282154
from bill.views import InvoiceList, InvoiceDetail from rest_framework.urlpatterns import format_suffix_patterns from django.urls import path urlpatterns = [ path('invoices', InvoiceList.as_view(), name='invoice-list'), path('invoices/<int:pk>', InvoiceDetail.as_view(), name='invoice-detail'), ] urlpatterns =...
StarcoderdataPython
52998
<reponame>JSchwalb11/OpenCV_Practical import numpy as np import argparse import imutils import cv2 ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required = True, help = "Path to the image") args = vars(ap.parse_args()) image = cv2.imread(args["image"]) cv2.imshow("Original", image) (h,w) = image.sh...
StarcoderdataPython
89803
<gh_stars>100-1000 from __future__ import division import sys import time import re import threading from ..runtime import min_version, runtime_info, read_vm_size from ..utils import timestamp from ..metric import Metric from ..metric import Breakdown if min_version(3, 4): import tracemalloc class AllocationPr...
StarcoderdataPython
3448674
<gh_stars>10-100 from setuptools import find_packages, setup setup( name='homely', description=('Automate the installation of your personal config files and' ' favourite tools using Python. https://homely.readthedocs.io/'), url='https://homely.readthedocs.io/', author='<NAME>', lic...
StarcoderdataPython
9655725
<filename>example_snippets/multimenus_snippets/Snippets/SciPy/Optimization and root-finding routines/General-purpose optimization/Nelder-Mead Simplex algorithm.py<gh_stars>0 def rosen(x): """The Rosenbrock function""" return sum(100.0*(x[1:]-x[:-1]**2.0)**2.0 + (1-x[:-1])**2.0) x0 = np.array([1.3, 0.7, 0.8, 1.9...
StarcoderdataPython
5085524
<gh_stars>0 # import numpy as np # import networkx as nx # import matplotlib.pyplot as plt # import matplotlib as mpl # import matplotlib.colors as colors # from .paths import paths_prob_to_edges_flux
StarcoderdataPython
1692090
<reponame>nicholascar/comp7230-training<filename>lecture_resources/lecture_02_SQLite.py import csv import sqlite3 # create an SQLite DB conn = sqlite3.connect('test.db') print("Opened database successfully") # create a table conn.execute("DROP TABLE IF EXISTS dwellings;") conn.execute( """ CREATE TABLE dwelli...
StarcoderdataPython
1970025
"""Utilities for finding overlap or missing items in arrays.""" from .._ffi.function import _init_api from .. import backend as F class Filter(object): """Class used to either find the subset of IDs that are in this filter, or the subset of IDs that are not in this filter given a second set of IDs. ...
StarcoderdataPython
3552915
""" ################################################################################################## # Copyright Info : Copyright (c) Davar Lab @ Hikvision Research Institute. All rights reserved. # Filename : __init__.py # Abstract : # Current Version: 1.0.0 # Date : 2020-05-31 ###...
StarcoderdataPython
4827853
<reponame>hulecom/read-GRACE-harmonics #!/usr/bin/env python u""" calc_sensitivity_kernel.py Written by <NAME> (06/2021) Calculates spatial sensitivity kernels through a least-squares mascon procedure COMMAND LINE OPTIONS: --help: list the command line options -O X, --output-directory X: output directory for ...
StarcoderdataPython
6575805
<reponame>liziwenzzzz/cv_template<filename>network/AOD/Model.py import pdb import numpy as np import torch import os from .aod import AODnet from options import opt from optimizer import get_optimizer from scheduler import get_scheduler from network.base_model import BaseModel from mscv import ExponentialMovingAve...
StarcoderdataPython
4813562
<filename>ffmpeg_sample/test04_pydub_mp3_join.py<gh_stars>0 print ('pydubでmp3を連結する') # pydubを使うにはffmpegが必要- from pydub import AudioSegment # mp3ファイルの読み込み audio1 = AudioSegment.from_file("./test_data/test1.mp3", "mp3") audio2 = AudioSegment.from_file("./test_data/test2.mp3", "mp3") audio3 = AudioSegment.from_file("./t...
StarcoderdataPython
4961205
"""Stockanalysis.com/etf Model""" __docformat__ = "numpy" import argparse from typing import List import webbrowser import requests import pandas as pd from bs4 import BeautifulSoup as bs from tabulate import tabulate from gamestonk_terminal.helper_funcs import ( parse_known_args_and_warn, ) # Run this when calle...
StarcoderdataPython
4977557
# Generated by Django 2.2.8 on 2019-12-14 06:31 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('service', '0019_rent_is_paid'), ] operations = [ migrations.AddField( model_name='service', ...
StarcoderdataPython
3240830
<gh_stars>10-100 """ Utilities to implement Single Sign On for Discourse with a Python managed authentication DB https://meta.discourse.org/t/official-single-sign-on-for-discourse/13045 Thanks to <NAME> for the heavy lifting, detailed at https://meta.discourse.org/t/sso-example-for-django/14258 A SSO request handler...
StarcoderdataPython
8076537
# python -m pip install matplotlib import matplotlib.pyplot as plt # python -m pip install numpy import numpy as np # python -m pip install scipy from scipy.stats import norm from scipy import stats def variavel_aleatoria(nome: str, media: int, desvio_padrao: int, qtd: int): va = np.sort(np.random.normal(media, d...
StarcoderdataPython
6503315
<filename>Code/Scripts/plot_for_month.py from Code.Scripts.popularity_calculator import calculate_popularity,freq_of_popularity import xlrd import matplotlib.pyplot as plt file_name = 'D:\\Users\\yashk\\Campaign-Assistant\\Data\\Annotated\\graph_month_input.xls' workbook = xlrd.open_workbook(file_name) sheet = workboo...
StarcoderdataPython
11361306
# Base class for a CLI ThreadedConnection # # Copyright (c) 2018 Ensoft Ltd import re from entrance.connection.threaded import ThreadedConnection class ThreadedCLIConnection(ThreadedConnection): """ Base class for a ThreadedConnection whose worker thread maintains a CLI session """ async def sen...
StarcoderdataPython
1899095
import sys import subprocess from moban import constants, exceptions from moban.externals import reporter, file_system def git_clone(requires): from git import Repo if sys.platform != "win32": # Unfortunately for windows user, the following function # needs shell=True, which expose security ...
StarcoderdataPython
3313764
import pathlib from graphysio.dialogs import askOpenFilePath from .csv import CsvReader from .edf import EdfReader from .parquet import ParquetReader file_readers = {'csv': CsvReader, 'parquet': ParquetReader, 'edf': EdfReader} file_readers = {k: mod for k, mod in file_readers.items() if mod.is_available} class Fi...
StarcoderdataPython
1658756
<reponame>Blddwkb/awesome-DeepLearning #!/usr/bin/env python # coding: utf-8 # In[37]: # 查看当前挂载的数据集目录, 该目录下的变更重启环境后会自动还原 # View dataset directory. # This directory will be recovered automatically after resetting environment. get_ipython().system('ls /home/aistudio/data') # In[38]: # 查看工作区文件, 该目录下的变更将会持久保存. 请及时...
StarcoderdataPython
5171582
import unittest import collections from Core.Rate import Rate from Core.Structure import StructureAgent from Core.Atomic import AtomicAgent from Core.Complex import Complex from Core.Rule import Rule from Core.Side import Side from Core.Reaction import Reaction from Parsing.ParseBCSL import Parser class TestRule(uni...
StarcoderdataPython
63451
import yaml from util import AttrDict class SchemaOrField(object): def __init__(self, optional=False, default=None): self.optional = optional self.default = default def is_optional(self): return self.optional def keyify(self, parents, key=None): if key is not None: parents = parents + [key] return "...
StarcoderdataPython
11350677
<filename>ex010.py n = float(input('Quanto de dinheiro você tem? ')) d = n / 3.27 print('Com {:.2f} reais você pode comprar {:.2f} dolares'.format(n, d))
StarcoderdataPython
8105606
# https://www.codewars.com/kata/5648b12ce68d9daa6b000099/train/python # There is a bus moving in the city, and it takes and drop some people # in each bus stop. # You are provided with a list (or array) of integer arrays (or # tuples). Each integer array has two items which represent number # of people get into bu...
StarcoderdataPython
4996844
from setuptools import find_packages, setup with open("elasticdl/requirements.txt") as f: requirements = f.read().splitlines() setup( name="elasticdl", version="0.0.1", description="A Kubernetes-native Deep Learning Framework", author="<NAME>", url="https://github.com/sql-machine-learning/elas...
StarcoderdataPython
8080513
import copy from typing import * from cognite.client.data_classes._base import * # GenClass: relationshipResponse, relationship class Relationship(CogniteResource): """Representation of a relationship in CDF, consists of a source and a target and some additional parameters. Args: source (Dict[str, A...
StarcoderdataPython
3409600
<gh_stars>0 import unittest import yaml import os from bok_choy.web_app_test import WebAppTest from pages.ec2_configuration_subpage import Ec2ConfigurationSubPage class TestEc2ConfigurationSubPage(WebAppTest): def setUp(self): super(TestEc2ConfigurationSubPage, self).setUp() config_path = os.geten...
StarcoderdataPython
9627581
<reponame>gbd-consult/windrose """ Skript zum Erstellen von Windrose Plots aus CSV Dateien. python3 fromcsv.py windrose pfad/zur/datei.csv ordner/fuer/ausgabe """ import csv import sys import os.path from windrose import windrose, balken csv_file = sys.argv[2] out_path = sys.argv[3] stations = [] with open(c...
StarcoderdataPython
11249152
<reponame>JeronimoMendes/Tomatimer<gh_stars>0 # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'pref_win.ui' # # Created by: PyQt5 UI code generator 5.15.0 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what ...
StarcoderdataPython
4940032
<gh_stars>0 # # Copyright (c) 2018 TECHNICAL UNIVERSITY OF MUNICH, DEPARTMENT OF MECHANICAL ENGINEERING, CHAIR OF APPLIED MECHANICS, # BOLTZMANNSTRASSE 15, 85748 GARCHING/MUNICH, GERMANY, <EMAIL>. # # Distributed under 3-Clause BSD license. See LICENSE file for more information. # """ Assembly module. Module for asse...
StarcoderdataPython
11259826
<gh_stars>1-10 #!/usr/bin/env python from distutils.core import setup setup(name='qosy', version='1.0', description='Quantum Operators from SYmmetries', author='<NAME>', author_email='<EMAIL>', url='https://github.com/ClarkResearchGroup/qosy', packages=['qosy'] )
StarcoderdataPython
1636555
from model.contact import Contact import re import time class ContactHelper: def __init__(self, app): self.app = app def open_homepage(self): wd = self.app.wd if not (wd.current_url.endswith("/addressbook/") and len(wd.find_elements_by_name("searchstring")) > 0): wd.find_...
StarcoderdataPython
121746
from virtool.hmm.fake import create_fake_hmms async def test_fake_hmms(app, snapshot, tmp_path, dbi, example_path, pg): hmm_dir = tmp_path / "hmm" hmm_dir.mkdir() await create_fake_hmms(app) assert await dbi.hmm.find().to_list(None) == snapshot with open(hmm_dir / "profiles.hmm", "r") as f_resu...
StarcoderdataPython
11301292
# -*- coding: utf-8 -*- # Copyright 2020 <NAME>, Modified by Trinhlq (@l4zyf9x) # MIT License (https://opensource.org/licenses/MIT) """Train FastSpeech.""" import argparse import logging import os import sys import numpy as np import tensorflow as tf import yaml import tensorflow_tts from tqdm import tqdm from ...
StarcoderdataPython
6648117
#!/usr/bin/env python3.5 import json from json import JSONDecodeError import sys import argparse import gzip import re parser = argparse.ArgumentParser(description='Match multiple patterns against a JSON field') parser.add_argument('--field', help='Field to grep', default='url') parser.add_argument('file', help='File...
StarcoderdataPython
15101
# Copyright 2021 <NAME> <EMAIL> # # 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 writin...
StarcoderdataPython
79145
<gh_stars>0 #!/usr/bin/env python """utils.py: Utility methods for AnalogMethod""" __author__ = "<NAME>" __copyright__ = "Copyright 2019" __license__ = "MIT" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" __status__ = "Development" import xarray as xr import pandas as pd def calc_normalized_anomalies(ds_prep, wind...
StarcoderdataPython
3241085
<filename>src/fairtest/modules/metrics/metric.py """ Abstract Fairness Metric. """ import abc import numpy as np class Metric(object): """ An abstract fairness metric. """ __metaclass__ = abc.ABCMeta # Types of metrics DATATYPE_CT = 'ct' # Metrics over a contingency table DATATYPE...
StarcoderdataPython
11359460
<reponame>jrieke/feedback-nns import torch from torchvision import transforms, datasets from PIL import Image import random import numpy as np import matplotlib.pyplot as plt import utils def load_mnist(val_size=5000, seed=None): """Return the train (55k), val (5k, randomly drawn from the original test set) and t...
StarcoderdataPython
11275391
# Copyright 2022 The etils 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 applicable law or agreed to in wr...
StarcoderdataPython
3252013
import requests from bs4 import BeautifulSoup YOUTUBE_TRENDING_URL='https://www.youtube.com/feed/trending' # Doesn't execute the Javascript response=requests.get(YOUTUBE_TRENDING_URL) print('Status Code',response.status_code) # with open('trending.html','w') as f: # f.write(response.text) doc=BeautifulSoup(resp...
StarcoderdataPython
71441
import numpy as np km2 = np.array([44410., 5712., 37123., 0., 25757.]) anos2 = np.array([2003, 1991, 1990, 2019, 2006]) idade = 2019 - anos2 km_media = km2 / idade
StarcoderdataPython
3574807
############################################################################## # # Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOF...
StarcoderdataPython
5084868
from loguru import logger from sqlalchemy import Column, Integer, String, create_engine from sqlalchemy.orm import Session, declarative_base def test_database_with_sqlalchemy(): # Declare tables https://www.tutorialspoint.com/sqlalchemy/sqlalchemy_orm_declaring_mapping.htm Base = declarative_base() class...
StarcoderdataPython
309384
<filename>couchbase_utils/index_utls/index_ready_functions.py ''' Created on 07-May-2021 @author: riteshagarwal ''' from global_vars import logger import time from membase.api.rest_client import RestConnection class IndexUtils: def __init__(self, cluster, server_task, n1ql_node): self.cluster = cluster ...
StarcoderdataPython
5018111
<reponame>basepipe/developer_onboarding<filename>resources/dot_PyCharm/system/python_stubs/-762174762/PySide/QtGui/QIconEngine.py # encoding: utf-8 # module PySide.QtGui # from C:\Python27\lib\site-packages\PySide\QtGui.pyd # by generator 1.147 # no doc # imports import PySide.QtCore as __PySide_QtCore import Shiboken...
StarcoderdataPython
6704062
<reponame>m3at/chainer-mask-rcnn<gh_stars>10-100 import copy import chainer from chainer import reporter from chainercv.utils import apply_to_iterator import numpy as np import tqdm from .. import utils class InstanceSegmentationCOCOEvaluator(chainer.training.extensions.Evaluator): name = 'validation' def...
StarcoderdataPython
163610
<reponame>zhuzhenping/Wt4ElegantRL<filename>run_toy.py from runner import entry, Runner class SimpleRunner(Runner): def test(self): print('test1') if __name__ == '__main__': entry(obj=SimpleRunner())
StarcoderdataPython
9708916
<filename>util/contact_info.py def str_mj_arr(arr): return " ".join(["%0.3f" % arr[i] for i in range(arr.shape[0])]) def print_contact_info(sim): if sim.data.ncon == 0: print("No contacts/collisions") return # Print contact metadata for coni in range(sim.data.ncon): print(" C...
StarcoderdataPython
1989388
from django.db import models from django.utils import timezone import datetime class Vehicle(models.Model): def __str__(self): return self.manufacturer + " " + self.model + "(" + self.vehicle_number + ")" manufacturer = models.CharField(max_length=128) model = models.CharField(max_length=128) ...
StarcoderdataPython
5119960
from flask import Flask, render_template, jsonify, request import urllib import recipe_api from recipe_api import * import transformations.transformations from transformations.transformations import * import scraper from pprint import pprint app = Flask(__name__) @app.route("/") def index(): return render_template('...
StarcoderdataPython
11212557
import pytest from api_object_schema._compat import with_metaclass # pylint: disable=no-name-in-module from api_object_schema import Field, Fields, FieldsMeta from sentinels import NOTHING # pylint: disable=redefined-outer-name class MyObj(object): pass def test_field_string_types(): f = Field('name', typ...
StarcoderdataPython
1708452
<reponame>NathanKr/python-playground<gh_stars>0 a = 1 b = "hello" a = a +1 b = b + " world" print(a,b) a="hello !!!" print(a)
StarcoderdataPython
5096059
from arm.logicnode.arm_nodes import * class RpMSAANode(ArmLogicTreeNode): """Sets the MSAA quality.""" bl_idname = 'LNRpMSAANode' bl_label = 'Set MSAA Quality' arm_version = 1 property0: HaxeEnumProperty( 'property0', items = [('1', '1', '1'), ('2', '2', '2'), ...
StarcoderdataPython
6573571
<filename>notebooks/2022-02-15_01_downloading cordex data.py #%% # ============================================================================= # Dependencies # ============================================================================= # Get the dependencies from re import I import cdsapi import datetime as dt imp...
StarcoderdataPython
11346740
from typing import Any, Dict, List, Optional from typing_extensions import TypedDict from graphql.error import format_error as format_graphql_error from strawberry.types import ExecutionResult class GraphQLHTTPResponse(TypedDict, total=False): data: Optional[Dict[str, Any]] errors: Optional[List[Any]] de...
StarcoderdataPython
37886
<reponame>rudra012/django_rest from django.conf.urls import url from api.snippets import snippets_api urlpatterns = [ url(r'^$', snippets_api.snippet_list), url(r'^(?P<pk>[0-9]+)/$', snippets_api.snippet_detail), ]
StarcoderdataPython
1875488
import base64 from django.test import TestCase from django.test import Client from django.conf import settings class test_image_controller(TestCase): def test_create_image(self): data_path = settings.STORAGE_DIR+"/image/image_8.nii" data = open(data_path, "rb").read() encoded = base64.b6...
StarcoderdataPython
6432682
<reponame>MJochim/seahub from django.core import mail from django.conf import settings from shibboleth import backends from seahub.base.accounts import User from seahub.auth import authenticate from seahub.test_utils import BaseTestCase import importlib SAMPLE_HEADERS = { "REMOTE_USER": '<EMAIL>', "Shib-Appl...
StarcoderdataPython
171103
# Copyright (c) 2015 Cloudera, Inc. All rights reserved. import pytest from subprocess import check_call from tests.common.test_vector import * from tests.common.impala_test_suite import * from tests.util.filesystem_utils import WAREHOUSE, IS_S3 TEST_DB = 'hidden_files_db' TEST_TBL = 'hf' class TestHiddenFiles(Impal...
StarcoderdataPython
6634619
# <NAME> field_size = int(input()) mines = [] response = [] for i in range(0, field_size): aux = int(input()) mines.append(aux) for i in range(field_size): count = 0 if (i != 0): if (mines[i - 1] == 1): count += 1 if (mines[i] == 1): count += 1 if (i < field_s...
StarcoderdataPython