id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
1719815
<reponame>redhat-cip/dci-control-server<filename>dci/api/v1/tests.py # -*- coding: utf-8 -*- # # Copyright (C) 2015-2016 Red Hat, Inc # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http:...
StarcoderdataPython
1758425
<reponame>Kevinskwk/CV_and_DL_Python<filename>scripts/centroid.py<gh_stars>1-10 # you can tune with calibration.py import cv2 as cv import numpy as np cap = cv.VideoCapture(0) cv.namedWindow('Mask') cv.namedWindow('Image') UpperH = 158 #0-180 UpperS = 222 #0-255 UpperV = 189 #0-255 LowerH = 120 ...
StarcoderdataPython
1613709
import json import tempfile from fastapi import Depends, FastAPI import numpy as np import requests from requests.adapters import HTTPAdapter, Retry from ray._private.test_utils import wait_for_condition from ray.air.checkpoint import Checkpoint from ray.air.predictor import DataBatchType, Predictor from ray.serve.mo...
StarcoderdataPython
3210214
import numpy as np from model.error import Error from model.decision_tree.decision_tree import DecisionTree class RandomForest: def __init__(self, input_attr=0, output_attr=0, num=20, feature_sampling=np.log2): if input_attr != 0 and input_attr != 1: raise Error("Invalid input_attr!") i...
StarcoderdataPython
88225
# Feel free to modifiy this file. # It will only be used to verify the settings are correct import os import argparse import torch import torch.nn as nn import torch.nn.functional as F from torchvision import datasets, transforms, models from dataloader import CustomDataset from submission import get_model parser...
StarcoderdataPython
3367437
"""Misc zlib tests Made for Jython. """ import unittest import zlib from array import array from test import test_support class ArrayTestCase(unittest.TestCase): def test_array(self): self._test_array(zlib.compress, zlib.decompress) def test_array_compressobj(self): def compress(value): ...
StarcoderdataPython
4445
<reponame>jean1042/plugin-azure-cloud-services import logging from spaceone.inventory.libs.connector import AzureConnector from spaceone.inventory.error import * from spaceone.inventory.error.custom import * __all__ = ['SnapshotConnector'] _LOGGER = logging.getLogger(__name__) class SnapshotConnector(AzureConnector)...
StarcoderdataPython
3382764
<reponame>Atzingen/curso-IoT-2017<filename>aula-10-mqttbroker/mqtt_inicio/publish_mqtt.py<gh_stars>1-10 import paho.mqtt.client as mqtt client = mqtt.Client() client.connect('192.168.127.12') client.publish('teste','ligado')
StarcoderdataPython
3257014
# This file was automatically generated by SWIG (http://www.swig.org). # Version 1.3.31 # # Don't modify this file, modify the SWIG interface instead. # This file is compatible with both classic and new-style classes. import _efitlib import new new_instancemethod = new.instancemethod try: _swig_property = property...
StarcoderdataPython
3241300
#Escreva um programa que faça o computador "pensar" em um número inteiro #entre 0 e 5 e peça para o usuário tentar descobrir qual foi o número #escolhido pelo computador. #O programa deverá escrever na tela #se o usuário venceu ou perdeu. from random import randint from time import sleep print('_____<NAME>_____') prin...
StarcoderdataPython
58779
<filename>tests/riscv/vector/vector_indexed_load_store_force.py # # Copyright (C) [2020] Futurewei Technologies, Inc. # # FORCE-RISCV is 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 # # ht...
StarcoderdataPython
1723990
<reponame>mitodl/codejail """A proxy subprocess-making process for CodeJail.""" import ast import logging import os import os.path import subprocess import sys import time import six from six.moves import range from .subproc import run_subprocess log = logging.getLogger("codejail") # We use .readline to get data f...
StarcoderdataPython
3234667
<filename>svm.py import os from csv import reader import numpy as np from sklearn.model_selection import train_test_split from sklearn import svm from sklearn.svm import LinearSVC def norm(arr): x_max = max(arr) x_min = min(arr) for i in range(len(arr)): arr[i] = (arr[i] - x_min) / (x_max - x_min) ...
StarcoderdataPython
60453
import sys import typing from metal.serial import Engine from metal.serial.hooks import MacroHook from metal.serial.preprocessor import MacroExpansion class Argv(MacroHook): identifier = 'METAL_SERIAL_INIT_ARGV' def invoke(self, engine: Engine, macro_expansion: MacroExpansion): engine.write_int(len...
StarcoderdataPython
22997
<reponame>project-pantheon/pantheon_glob_planner # (C) British Crown Copyright 2011 - 2018, Met Office # # This file is part of cartopy. # # cartopy is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, eithe...
StarcoderdataPython
178274
<filename>api/urls.py from django.urls import include, path from rest_framework.routers import DefaultRouter from api.views import (BreedViewSet, CommentViewSet, GroupViewSet, PetViewSet, PostViewSet, SpeciesViewSet, UserCodeViewSet, UserTokenViewSet, UserViewSet) router ...
StarcoderdataPython
1647320
<gh_stars>1-10 #!/usr/bin/env python # pylint: disable=import-error,line-too-long """ Generate sample data for manual testing. """ import os from crowdsorter.settings import get_config from crowdsorter.factory import create_app from crowdsorter.models import Collection, Item, Redirect create_app(get_config(os.gete...
StarcoderdataPython
3283122
from __future__ import unicode_literals from rest_framework import generics from rest_framework import permissions from rest_framework.exceptions import NotFound from api.actions.serializers import PreprintRequestActionSerializer from api.base.views import JSONAPIBaseView from api.base import permissions as base_perm...
StarcoderdataPython
3276997
<reponame>effie-ms/eeflows from django.contrib import admin from stations.models import BioPeriod, Station admin.site.register(Station) admin.site.register(BioPeriod)
StarcoderdataPython
3354481
from http import HTTPStatus from pytest import mark from freddie.viewsets.dependencies import Paginator from .app import Item, test_item, test_items_seq from .utils import WithClient pytestmark = mark.asyncio api_prefixes = { 'argnames': 'prefix', 'argvalues': ['/unvalidated', '/validated', '/sync'], 'i...
StarcoderdataPython
3267329
<gh_stars>0 # Generated by Django 3.2.8 on 2021-10-14 16:16 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0004_auto_20211014_1611'), ] operations = [ migrations.AlterField( model_name=...
StarcoderdataPython
3379722
from flask_login import UserMixin, current_user from iot_lab_inventory import db, login_manager # from .cart import Cart, CartItem class Part(db.Model): __tablename__ = 'parts' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64)) description = db.Column(db.String) category ...
StarcoderdataPython
174195
<reponame>Mohammed785/University-System<filename>university_system/quizzes/urls.py from django.urls import path from .views import ( create_question_choice,create_quiz,create_quiz_question,CourseQuizzesView,update_question_choice, update_question,update_quiz,delete_choice,delete_question, delete_quiz,take_q...
StarcoderdataPython
3300685
import pandas as pd import numpy as np from annotations.CONSTANTS import * import pickle def save_as_csv(X, Y, feature_name, output_dir, output_filename='features_and_labels.csv'): # print(X[0], len(X[0]), len(feature_name)) # print('#x', len(X), '#y', len(Y)) data = np.array(X) pd_data = pd.DataFrame(...
StarcoderdataPython
3374702
<gh_stars>1-10 import asyncio import json import subprocess import time import traceback from io import StringIO from asgiref.sync import sync_to_async from django.core.exceptions import ValidationError from django.core.management import call_command from django.db import models from django.utils.translation import ge...
StarcoderdataPython
158362
<reponame>JasonFruit/hymnal-tools<filename>HtmlEmitter.py<gh_stars>1-10 class HtmlEmitter(object): def emit(self, s): self.file.write(s) def emit_line(self, s=""): self.emit(s) self.emit("\n") def initialize(self, filename, title, author, date): self.file = ...
StarcoderdataPython
1799714
#----------------------------------------------------------------------------- # Name: Formal Documentation i.e. docstrings (formalDocumentation_ex4.py) # Purpose: Provides an example of how to create docstrings in Python using # formal documentation standards. # # Author: <NAME> # Created: 22-...
StarcoderdataPython
191913
<gh_stars>0 from json import load, loads, dump from subprocess import run, PIPE, Popen def loadConfig(container): return load( open(f"/var/lib/docker/containers/{container}/config.v2.json", "r")) def writeConfig(container, obj): print("Write config") return dump( obj, open(f"/var/lib/doc...
StarcoderdataPython
3300829
from typing import Any, Dict, Optional, Type import pytest from importlinter.domain.fields import ( DirectImportField, Field, ListField, ModuleField, SetField, StringField, ValidationError, ) from importlinter.domain.imports import DirectImport, Module class BaseFieldTest: field_clas...
StarcoderdataPython
3375646
import nextcord from nextcord.ext import commands class say(commands.Cog): def __init__(self, client): self.client = client @commands.command() async def say(self, ctx, *,message=None): if message == None: await ctx.reply('Give me a word to say!') else: e=nextcor...
StarcoderdataPython
3352986
import argparse import csv import json import logging import os from datetime import datetime import torch from data_utils.log_wrapper import create_logger from data_utils.metrics import compute_acc, compute_cross_entropy from data_utils.utils import set_environment from mt_dnn.gobbli_batcher import GobbliBatchGen fro...
StarcoderdataPython
192706
# coding=utf-8 from __future__ import absolute_import from .user import * from .media import * from .book import * from .category import * from .configuration import * from .notify import *
StarcoderdataPython
3276092
# Generated by Django 2.1.2 on 2018-10-11 04:55 from django.db import migrations, models import users.models class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ] operations = [ migrations.AlterField( model_name='user', name='userna...
StarcoderdataPython
110443
<reponame>rupakc/Kaggle-Compendium import pandas as pd from sklearn.ensemble import RandomForestRegressor from sklearn.ensemble import BaggingRegressor from sklearn.ensemble import ExtraTreesRegressor from sklearn.ensemble import AdaBoostRegressor from sklearn.ensemble import GradientBoostingRegressor from sklearn.ense...
StarcoderdataPython
1676865
from tetris.game import GameObject def test_renderable(): pass def test_game_object(): obj = GameObject() def test_collision(): pass
StarcoderdataPython
4837068
from django.test import TestCase from mixer.backend.django import mixer from projects.models import Project from bugs.models import Bug class ProjectModelTests(TestCase): """Test the project model""" def setUp(self): self.project = Project.objects.create(title='Test') def test_project_status_en...
StarcoderdataPython
1655041
from conans import python_requires common = python_requires('llvm-common/0.0.0@Manu343726/testing') class ClangHeaders(common.LLVMModulePackage): version = common.LLVMModulePackage.version name = 'clang_headers' llvm_component = 'clang' header_only = True include_dirs = ['']
StarcoderdataPython
1635258
import unittest from generativepy.nparray import make_nparray, make_nparray_frame from generativepy.movie import save_frame from image_test_helper import run_image_test import numpy as np """ Test each function of the nparray module, with 1, 3 and 4 channel output """ def draw4(array, pixel_width, pixel_height, frame...
StarcoderdataPython
1677771
import demistomock as demisto import json import pytest from CommonServerPython import entryTypes entryTypes['warning'] = 11 bot_id: str = '9bi5353b-md6a-4458-8321-e924af433amb' tenant_id: str = 'pbae9ao6-01ql-249o-5me3-4738p3e1m941' team_id: str = '19:<EMAIL>' team_aad_id: str = '7d8efdf8-0c5a-42e3-a489-5ef5c3fc7...
StarcoderdataPython
1702446
<filename>thelma/tools/worklists/series.py<gh_stars>1-10 """ This file is part of the TheLMA (THe Laboratory Management Application) project. See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information. Class for worklist series support. AAB """ from StringIO import StringIO from thelma.tools.semicon...
StarcoderdataPython
142151
<reponame>ABM-Community-Ports/droidboot_device_planet-cosmocom<filename>scripts/dct/obj/GpioObj.py #! /usr/bin/python # -*- coding: utf-8 -*- import re import os import sys import string import ConfigParser import xml.dom.minidom from data.GpioData import GpioData from data.EintData import EintData from ModuleObj im...
StarcoderdataPython
16422
<gh_stars>1-10 #!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import annotations import unittest import numpy as np import numpy.testing as npt import pandas as pd from riip.material import RiiMaterial class KnownValues(unittest.TestCase): known_values = [ (1, [0.0 for _ in range(17)], 1...
StarcoderdataPython
189356
#!/usr/bin/env python3 """Zig Zag. Given an array A (distinct elements) of size N. Rearrange the elements of array in zig-zag fashion. The converted array should be in form a < b > c < d > e < f. The relative order of elements is same in the output i.e you have to iterate on the original array only. Source: https://p...
StarcoderdataPython
1721945
<filename>dags/daily_simple_stats.py """ # Simple Stats (Conversation Stats) This dag is to process agent's analytics data from agent's interaction with dashboard. ## Source * Database: Anayltics, * Tables: messages ## Return * Database: Stats, * Tables: conversations """ import os from airflow import DAG from airf...
StarcoderdataPython
3277208
<gh_stars>0 from boto3.s3.transfer import S3Transfer from datetime import datetime import boto3 import logging import os import frontmatter s3 = boto3.client('s3') s3r = boto3.resource('s3') transfesr = S3Transfer(s3) dynamodb = boto3.resource('dynamodb') table = dynamodb.Table(os.getenv('TABLE_NAME')) def insert...
StarcoderdataPython
3324637
<gh_stars>1-10 from .base import UIBase from .button import Button, ToggleButton from .ui_renderer import UIRenderer __all__ = [ "UIBase", "Button", "ToggleButton", "UIRenderer", ]
StarcoderdataPython
1779424
<reponame>squassina/seismic-deeplearning # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import torch from ignite.engine.engine import Engine, State, Events from ignite.utils import convert_tensor import torch.nn.functional as F from toolz import curry from torch.nn import functional as F imp...
StarcoderdataPython
4820373
from sqlalchemy.ext.declarative import declarative_base, declared_attr from sqlalchemy import Column, Integer import logging log = logging.getLogger("interactor.database.connection") class Base: # Metadata gets set by Sqlalchemy metadata = None # __repr_columns__ must be set by subclasses of Base __...
StarcoderdataPython
1646583
#!/usr/bin/python # # File: main.py # Date: 25-Oct-14 # Author: <NAME> <<EMAIL>> # # Analytics dashboard for courses running on edx-platform. # # Top-level module. import logging import os import re import json import webapp2 import datetime import gsdata import bqutil import auth import local_config import url...
StarcoderdataPython
73734
<filename>CoordenacaoFacil/models/Student.py from werkzeug.security import generate_password_hash, check_password_hash from CoordenacaoFacil import db class Student(): def __init__(self, code="", name="", email="", password="", course=None, university=None, createdAt=""): self.code = code self.nam...
StarcoderdataPython
3306878
<gh_stars>10-100 from django.core.exceptions import ValidationError class FieldFactory(): """ Factory """ fields = {} def get_class(id): return FieldFactory.fields[id] def get_all_classes(): return FieldFactory.fields.values() def register(id, type): if id not in...
StarcoderdataPython
1634593
#!/usr/bin/env python import xml.etree.ElementTree as ET import os import collections s = os.sep labelfile = '/data1/datasets/VOC/' testfile = os.path.join(labelfile, '2007_test.txt') trainfile = os.path.join(labelfile, '2007_train.txt') valfile = os.path.join(labelfile, '2007_val.txt') filelist = [testfile, trainfile...
StarcoderdataPython
13217
#!/usr/bin/python3 print("content-type: text/html") print() import subprocess as sp import cgi fs = cgi.FieldStorage() cmd = fs.getvalue("command") output = sp.getoutput("sudo "+cmd) print("<body style='padding: 40px;'>") print('<h1 style="color:#df405a;" >Output</h1>') print("<pre>{}</pre>".format(ou...
StarcoderdataPython
3396091
<gh_stars>0 from decimal import Decimal import mimetypes from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.views.generic.base import View from django.conf import settings from django.urls import reverse_lazy from django.contrib import messages fr...
StarcoderdataPython
3210305
import itertools as it with open("./input.txt", "r") as inputFile: readingsStr = inputFile.read().splitlines() readings = map(int, readingsStr) readingPairs = it.pairwise(readings) increasingPairs = map(lambda pair : pair[1] > pair[0], readingPairs) numOfIncreasingPairs = sum(increasingPairs) p...
StarcoderdataPython
196993
import functools import logging from datetime import datetime import django from django.contrib import admin from django.contrib import messages from django.db.models import F from django.http import HttpResponse from django.urls import reverse from django.utils.safestring import mark_safe from django.utils.translatio...
StarcoderdataPython
3201460
<gh_stars>1000+ import sys import ctypes from code import InteractiveConsole from collections import deque from threading import Thread, Lock, Event from queue import SimpleQueue from _godot import StdoutStderrCaptureToGodot, StdinCapture from godot import exposed, export, ResourceLoader, VBoxContainer from .plugin i...
StarcoderdataPython
88875
# -*- coding: utf-8 -*- """ Created on Mon Feb 22 15:42:46 2016 @author: ruben """ import os import datetime as dt import time as time_t import pandas as pd import numpy as np import pytz UNIDAD_ESTACIONES = 'Z:' PATH_ESTACION_GEONICA = UNIDAD_ESTACIONES + '/geonica/' PATH_ESTACION_HELIOS = UNIDAD_ESTACIONES + '/E...
StarcoderdataPython
1742799
from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout from rest_framework import permissions, status, response, views from rest_framework.authtoken.models import Token class LogoutViewSet(views.APIView): permission_classes = [permissions.IsAuthenticated,] def...
StarcoderdataPython
1651526
""" Copyright, the CVXPY 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 writing, software ...
StarcoderdataPython
1669198
<filename>2017/day20.py """ http://adventofcode.com/2017/day/20 """ import re from collections import Counter from typing import NamedTuple, Tuple, List class Particle(NamedTuple): pos: Tuple[int, int, int] vel: Tuple[int, int, int] acc: Tuple[int, int, int] id: int def step(p: Particle) -> Particle:...
StarcoderdataPython
4829688
<filename>async_signalr_client/models/futures/__init__.py from .completions import InvokeCompletionFuture __all__ = [ "InvokeCompletionFuture" ]
StarcoderdataPython
1784347
# Copyright 2021 UW-IT, University of Washington # SPDX-License-Identifier: Apache-2.0 """ This module interacts with hrpws restclient for employee appointments """ import logging import traceback from sis_provisioner.dao import ( DataFailureException, InvalidRegID, changed_since_str) from uw_hrp.worker import ge...
StarcoderdataPython
150072
from . import channels from . import paillier
StarcoderdataPython
1672565
# Copyright 2015 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 required by applica...
StarcoderdataPython
3361661
from django.apps import AppConfig class NSFaultManagementConfig(AppConfig): name = 'NSFaultManagement'
StarcoderdataPython
1656856
import pyblish.api import openpype.api import hou from openpype.hosts.houdini.api import lib class CollectRemotePublishSettings(pyblish.api.ContextPlugin): """Collect custom settings of the Remote Publish node.""" order = pyblish.api.CollectorOrder families = ["*"] hosts = ["houdini"] targets = ...
StarcoderdataPython
3313022
<reponame>christophe12/RaspberryPython #RGB of common colors: # Aqua -> (0, 255, 255) # Black -> (0, 0, 0) # Blue -> (0, 0, 255) # Fuchsia -> (255, 0, 255) # Gray -> (128, 128, 128) # Green -> (0, 128, 0) # Lime -> (0, 255, 0) # Maroon -> (128, 0, 0) # Navy Blue -> (0, 0, 128) # Olive -> (128, 128, 0) # Purple -> (128...
StarcoderdataPython
1660081
import requests import sys from os.path import basename, splitext #from platformio import util from datetime import date Import('env') try: import configparser except ImportError: import ConfigParser as configparser config = configparser.ConfigParser() config.read("platformio.ini") #value1 = config.get("my_...
StarcoderdataPython
4821980
""" numtoword.py Yet another number to words in Python Copyright 2021 Wardhana <<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 r...
StarcoderdataPython
3203100
<reponame>fadeevab/python-3-simple-server<gh_stars>0 #!/usr/bin/python3 from http import server PORT = 8080 class CookieHandler(server.BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) if 'Host' in self.headers and \ self.headers['Host'].startswith("localhost"):...
StarcoderdataPython
1767054
<gh_stars>1-10 # -*- coding: utf-8 -*- from setuptools import find_packages, setup setup( name="engineering_diplomats", version="1.0.0", description="engineeringdiplomats.org", packages=find_packages(), include_package_data=True, zip_safe=False, )
StarcoderdataPython
1652000
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SelectField, SubmitField class ShotForm(FlaskForm): asset_task = SelectField('Add Asset task:', id='asset-task') asset_users = SelectField('Add Assignee:', id='asset-task-user') submit = SubmitField('submit')
StarcoderdataPython
1698438
<reponame>Raalsky/neptune-client # # Copyright (c) 2021, Neptune Labs Sp. z o.o. # # 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 ...
StarcoderdataPython
3228531
""" __init__.py pytracer.geometry package Created by Jiayao on Aug 13, 2017 """ from __future__ import absolute_import from typing import overload from pytracer import * # Classes class Vector(np.ndarray): """ Vector Class A wrappper subclasses numpy.ndarray which models a 3D vector. """ @overload def __ne...
StarcoderdataPython
1698964
"""Write tax data to the console in Tax Exchange Format (TXF).""" import datetime from typing import Optional def _txf_write(*obj: str) -> None: # Write objects to the console with the recommended TXF line terminator. print(*obj, end='\r\n') return def _txf_normalize_amount(amount: str) -> str: # Rem...
StarcoderdataPython
3394273
import os import pytest import tempfile import shutil import sys from programs.utils import ship_files2spark if 'SPARK_HOME' not in os.environ: os.environ['SPARK_HOME'] = '/usr/lib/spark' @pytest.fixture(scope="module") def spark(): tempdir = tempfile.mkdtemp() # Add the directory with pyspark and py4...
StarcoderdataPython
4822307
import pytest from dlms_cosem import cosem, enumerations from dlms_cosem.protocol import xdlms class TestSetRequestNormal: def test_transform_bytes(self): data = b"\xc1\x01\xc1\x00\x08\x00\x00\x01\x00\x00\xff\x02\x00\t\x0c\x07\xe5\x01\x18\xff\x0e09P\xff\xc4\x00" request = xdlms.SetRequestNormal( ...
StarcoderdataPython
3298350
import discord from discord.ext import commands class Meh: """Tells a user that you said meh""" def __init__(self, bot): self.bot = bot @commands.command(pass_context=True) async def meh(self, ctx, user : discord.Member): """Tags a person and tells them meh""" #Your code will...
StarcoderdataPython
3203333
<gh_stars>0 # Generated by Django 3.1.4 on 2022-02-22 09:15 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ...
StarcoderdataPython
1770007
<filename>setup.py from setuptools import setup # Dependencies. with open('requirements.txt') as f: tests_require = f.readlines() install_requires = [t.strip() for t in tests_require] setup(name='contextily', version='0.99.0', description='Context geo-tiles in Python', url='https://github.com/da...
StarcoderdataPython
3289095
import argparse import os from uuid import uuid1 import optuna from dotenv import load_dotenv from optuna.integration.pytorch_lightning import PyTorchLightningPruningCallback from pytorch_lightning import Trainer from pytorch_lightning.callbacks import EarlyStopping, GPUStatsMonitor, ModelCheckpoint from pytorch_light...
StarcoderdataPython
3214174
#! /usr/bin/env python from setuptools import setup import re from os import path with open('tweetfinder/__init__.py', 'r') as fd: version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) this_directory = path.abspath(path.dirname(__file__)) with open(path.join(this_directo...
StarcoderdataPython
99390
<gh_stars>0 from django.contrib import admin from modeltranslation.admin import TranslationAdmin from .models import InCategory, OutCategory, Income, Expense class InCategoryAdmin(TranslationAdmin): '''Allowing translate InCategory in admin panel''' pass class OutCategoryAdmin(TranslationAdmin): '''Allowi...
StarcoderdataPython
3301466
import pandas as pd import numpy as np import re, os from pathlib import Path from tqdm import tqdm import pyarrow as pa import pyarrow.parquet as pq from pathlib import Path # In bash run ```$ cat *.txt>>combined.txt``` to concatenate all movie rating files into one rating_file = Path('../../data/training_set/combi...
StarcoderdataPython
4810362
<reponame>vadi2/codeql<gh_stars>1000+ import dataclasses import dis import logging from dis import Instruction from types import FrameType from typing import Any, List from cg_trace.settings import DEBUG, FAIL_ON_UNKNOWN_BYTECODE from cg_trace.utils import better_compare_for_dataclass LOGGER = logging.getLogger(__nam...
StarcoderdataPython
81946
# 07 Web Scraping # Not every website as an API to work wtih. # In situations like that the only way to get the data we want is to parse the html behind a webpage, get rid of all the html tags, and extract the avtual data. # This technic is called Web Scraping # In this example we are going to write a program that ext...
StarcoderdataPython
4801372
import uuid from django.db import models from django.conf import settings from specimens.models import Specimen class SpecimenLabel(models.Model): """標本ラベル""" class Meta: db_table = 'specimen_labels' ordering = ['-created_at'] id = models.UUIDField(default=uuid.uuid4, primary_key=True) ...
StarcoderdataPython
3328773
import tracemalloc def knapsack_space_optimized_dp(value_set, weight_set, total_weight): """Space optimized version of `knapsack_dp`. Here we conciously know that we only need two rows to compute the True/False""" # Creating only two rows. dp_table = [[0 for _ in range(total_weight + 1)] for _ in ran...
StarcoderdataPython
157502
<reponame>SamJakob/PythonTCPSocketsExample import sys from multiprocessing import Process from typing import Optional from socket import socket, MSG_PEEK, AF_INET, SOCK_STREAM # Import Queue from our utilities package. # This should probably only be necessary on macOS, but is probably worth keeping for # cross-compat...
StarcoderdataPython
3357536
<gh_stars>1000+ # Copyright 2021 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 req...
StarcoderdataPython
1727249
<reponame>luizschmall/tce_siconfi_inconsistencies import pandas import string import math import csv import os from unicodedata import normalize def remover_acentos(txt): return normalize('NFKD', txt).encode('ASCII', 'ignore').decode('ASCII') def containsNumber(line): res = False numero = ...
StarcoderdataPython
4834744
<gh_stars>0 from django.conf.urls import url from .views import pitList, detail, lock urlpatterns = [ url(r'^$', pitList, name='pit_list'), url(r'^detail$', detail, name='pit_detail'), url(r'^lock$', lock, name='pit_lock') ]
StarcoderdataPython
130725
#!/usr/bin/env python3 BASE_URL = 'https://enlighten.enphaseenergy.com' STARTING_URL = BASE_URL + '/login' LOGIN_URL = BASE_URL + '/login/login' LOGIN_SUCCESS_URL = BASE_URL + '/systems' STATE_DIR = '~/.enphase_scraper' import os import errno import http.cookiejar import urllib import urllib.request import urllib.err...
StarcoderdataPython
1725217
from pathlib import Path import json from .utils import write_jsonfile, check_accessmode class MetaData: """Dictionary-like access to disk based metadata. If there is no metadata, the metadata file does not exist, rather than being empty. This saves a block of disk space (potentially 4kb). """ ...
StarcoderdataPython
166699
<filename>model/relation_transformer.py<gh_stars>0 # copy from: https://github.com/yahoo/object_relation_transformer/blob/master/models/RelationTransformerModel.py ########################################################## # Copyright 2019 Oath Inc. # Licensed under the terms of the MIT license. # Please see LICENSE ...
StarcoderdataPython
119976
<gh_stars>1-10 from lale.sklearn_compat import clone_op from lale.operators import Operator, make_operator import logging import inspect import importlib logger = logging.getLogger(__name__) def wrap_imported_operators(): calling_frame = inspect.stack()[1][0] symtab = calling_frame.f_globals for name, im...
StarcoderdataPython
1757814
<reponame>amithapa/learn_py_asyncio import asyncio import random async def myCoroutine(id): process_time = random.randint(1, 5) await asyncio.sleep(process_time) print(f"Coroutine: {id}, has successfully completed after {process_time} seconds.") async def main(): tasks = [] for i in range(10): ...
StarcoderdataPython
65582
<filename>jiamtrader/app/algo_trading/algos/twap_algo.py from jiamtrader.trader.constant import Offset, Direction from jiamtrader.trader.object import TradeData from jiamtrader.trader.engine import BaseEngine from jiamtrader.app.algo_trading import AlgoTemplate class TwapAlgo(AlgoTemplate): """""" display_n...
StarcoderdataPython
118600
<filename>moar_dots/wipe.py<gh_stars>0 import logging import os import random import yaml from time import sleep from .config import easter from .constants import EASTER_FILE, ERROR_FILE class Wipe: """ An very strongly themed error handling class for moar-dots. Also has an easter egg. """ def ...
StarcoderdataPython