id
stringlengths
2
8
text
stringlengths
16
264k
dataset_id
stringclasses
1 value
6675662
<reponame>amoskowitz14/causalML<filename>projects/reinforcement learning/causal_reinforcement_learning/src/envs/pomdp.py import types from gym_pyro import PyroPOMDP from . import renders def make_pomdp(path, *args, **kwargs): """make_pomdp Creates a PyroPOMDP instance based on the given POMDP file, injecti...
StarcoderdataPython
6448159
import datetime import dateutil import urllib import functools import time import requests import simplejson from datapackage_pipelines_measure.config import settings import logging log = logging.getLogger(__name__) DEFAULT_REPORT_START_DATE = '2014-01-01' def request_data_from_discourse(domain, endpoint, **kwarg...
StarcoderdataPython
5000100
from IGParameter import * from PIL import Image import copy class IGParameterImage(IGParameter): def __init__(self): super().__init__("Image") self._value["image"] = None @property def image(self): return self._value["image"] @image.setter def image(self, image): ...
StarcoderdataPython
9739743
<gh_stars>0 # Copyright 2020 The FedLearner 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 require...
StarcoderdataPython
295105
<reponame>kolyasalubov/Lv-677.PythonCore def count_positives_sum_negatives(arr): if not arr: return [] positive_array_count = 0 negative_array_count = 0 neither_array = 0 for i in arr: if i > 0: positive_array_count = positive_array_count + 1 elif i == 0: ...
StarcoderdataPython
8168192
import logging from icrawl_plugin import IHostCrawler from utils.config_utils import crawl_config_files logger = logging.getLogger('crawlutils') class ConfigHostCrawler(IHostCrawler): def get_feature(self): return 'config' def crawl( self, root_dir='/', exclude_...
StarcoderdataPython
1982777
import os import sys import h5py import numpy as np import shutil job_repeat_attempts = 5 def check_file(filename): if not os.path.exists(filename): return False # verify the file has the expected data import h5py f = h5py.File(filename, 'r') fkeys = f.keys() f.close() if set(fkeys...
StarcoderdataPython
3582283
<gh_stars>1-10 """ Copyright (C) 2020 ETH Zurich. All rights reserved. Author: <NAME>, ETH Zurich 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/licens...
StarcoderdataPython
3234044
<filename>CorbanDallas1982/Home_work_6/HW_6_3.py<gh_stars>0 word = input("Enter your word:") def f(): global word return {x: list(word).count(x) for x in list(word)} print(f())
StarcoderdataPython
3543111
from rest_framework import serializers from django.contrib.auth import get_user_model from django.contrib.auth.password_validation import validate_password from .models import Supply, Standard, Connector, SupplyConnectorRelation class ConnectorField(serializers.ModelField): def __init__(self, *args, **kwargs): ...
StarcoderdataPython
9692682
import numpy as np import math import itertools def _p_val_1d(A, B, metric=np.mean, numResamples=10000): """Return p value of observed difference between 1-dimensional A and B""" observedDiff = abs(metric(A) - metric(B)) combined = np.concatenate([A, B]) numA = len(A) resampleDiffs = np.zeros(...
StarcoderdataPython
5178261
<reponame>rkwong43/Toh<filename>utils/ids/weapon_id.py from enum import Enum, auto """Represents the IDs of different weapon types. """ class WeaponID(Enum): # Weapon types GUN = auto() SHOTGUN = auto() MACHINE_GUN = auto() FLAK_GUN = auto() MISSILE_LAUNCHER = auto() FLAK_CANNON = auto() ...
StarcoderdataPython
9703565
<reponame>L-Net-1992/Paddle # Copyright (c) 2022 PaddlePaddle 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....
StarcoderdataPython
6603018
from rest_framework import serializers from app.models import CountTrue class UserSerializer(serializers.Serializer): """ A serializer class for serializing the SlackUsers """ id = serializers.IntegerField() firstname = serializers.CharField() lastname = serializers.CharField() photo = ser...
StarcoderdataPython
9741123
from unittest import TestCase from strStr_dfa import Solution class TestSolution(TestCase): so = Solution() def test_get_dfa(self): dp = self.so.get_dfa('ababdababa') # X取值依次为[0,0,1,2,0,1,2,3,4] for i, e in enumerate(dp): for j, number in enumerate(e): if nu...
StarcoderdataPython
4871247
<filename>ddc_packages/hddump/hddump/hddumpMain.py """ Demonstration handle dump for CMIP/ESGF files .. USAGE ===== -h: print this message; -v: print version; -t: run a test -f <file name>: examine file, print path to replacement if this file is obsolete, print path to sibling files (or replacements). -id <track...
StarcoderdataPython
361425
foobar = 'blah %d' % 1 c = 'a' specialChars = 'what\'ll\r\nhappen\r\nhere\\?' def fn(val): return val + '!!' baz = < foo: "bar bar" baz: blah bar: 1 bob: foo: bar blah: blah: blahber someList: - a - b - c otherList: [1, 2, 3] boolList: [true, false, !~ True] nullVal...
StarcoderdataPython
8100215
# # Copyright 2018 Analytics Zoo 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...
StarcoderdataPython
3209627
from __future__ import unicode_literals from django.conf.urls import patterns, include, url from django.conf.urls.i18n import i18n_patterns from django.contrib import admin from mezzanine.conf import settings import mezzanine_pagedown.urls from tastypie.api import Api from amp import views as amp_views from blogapi....
StarcoderdataPython
52619
<reponame>emaballarin/DSSC_DL_2021 #!/usr/bin/env python3 # -*- coding: utf-8 -*- # # ============================================================================== # # :: IMProved :: # # Improved tools for Iterative Magnitude Pruning and PyTorch model masking # with minimal-memory impact, device invariance, O(1) amort...
StarcoderdataPython
378715
<gh_stars>100-1000 #!/usr/bin/env python import os from brutal.core.management import exec_overlord if __name__ == "__main__": os.environ.setdefault("BRUTAL_CONFIG_MODULE", "{{ spawn_name }}.config") exec_overlord("{{ spawn_name }}.config")
StarcoderdataPython
11298784
import numpy as np from matplotlib import pyplot as plt from add_noise import salt_and_pepper, white_noise def _gaussian_weight(im, p1, p2, n_size, filtering): r = int(n_size / 2) x1, y1 = p1 x2, y2 = p2 area1 = im[(x1 - r):(x1 + r + 1), (y1 - r):(y1 + r + 1), :] area2 = im[(x2 - r):(x2 + r + 1...
StarcoderdataPython
1872033
from utils.args import is_existing_file, is_valid_folder from utils.timer import timer import pandas as pd from spacy.matcher import PhraseMatcher import spacy from nltk.tokenize import RegexpTokenizer from pdfminer.high_level import extract_text, extract_text_to_fp from pdfminer.converter import TextConverter from pdf...
StarcoderdataPython
4933396
<reponame>JFF-Bohdan/yabtool<filename>yabtool/shared/jinja2_helpers.py import os from jinja2 import BaseLoader, Environment, StrictUndefined def jinja2_custom_filter_extract_year_four_digits(value): return value.strftime("%Y") def jinja2_custom_filter_extract_month_two_digits(value): return value.strftime(...
StarcoderdataPython
5157342
import copy from typing import Union import gym import numpy as np import pytest import torch as T from pearll.models import Actor, ActorCritic, Critic, Dummy from pearll.models.actor_critics import Model from pearll.models.encoders import IdentityEncoder, MLPEncoder from pearll.models.heads import BoxHead, DiagGauss...
StarcoderdataPython
6549771
from unittest import skip from django.contrib.auth import get_user_model from django.urls import reverse from django.test import TestCase from rest_framework import status from rest_framework.test import APIClient from core.models import Tag, Recipe from recipe.serializers import TagSerializer TAGS_URL = reverse('...
StarcoderdataPython
12509
# Copyright 2018 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
11310764
<filename>rotkehlchen/inquirer.py from __future__ import unicode_literals # isort:skip import logging import operator from enum import auto from pathlib import Path from typing import TYPE_CHECKING, Any, Dict, Iterable, List, NamedTuple, Optional, Tuple, Union from rotkehlchen.assets.asset import Asset, EthereumToke...
StarcoderdataPython
3330133
<reponame>trivenews/central import factory from factory import fuzzy from django.utils import timezone from .models import User from ..wallet.factories import WalletFactory class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User username = factory.Sequence(lambda n: 'user%s' %...
StarcoderdataPython
5042024
<filename>urllib_request_basicauth.py #!/usr/bin/env python3 import urllib.request import getpass import os import json import pandas as pd jq = pd.read_csv('jenkins_queries.csv') url = jq.loc[3,'URL'] auth_user = "ericnelson" auth_token = os.environ['JENKINS_TOKEN'] #HTTPBasicAuthHandler setup passman = urllib.re...
StarcoderdataPython
5127760
import numpy as np import matplotlib.pyplot as plt __all__ = ['tracer', 'np'] def tracer_plan_cartesien(): plt.arrow(-1, 0, 2, 0, width=0.005, head_width=0.05, color='k') plt.arrow(0, -1, 0, 2, width=0.005, head_width=0.05, color='k') plt.grid('on') def tracer(x, y, **kwargs): tracer_plan_cartesien()...
StarcoderdataPython
5002981
import pygame import constants as c import math class Powerup: def __init__(self, game, surface, pos=(0, 0)): self.radius = 24 self.age = 0 self.game = game self.x, self.y = pos self.y_offset = -self.y self.surface = surface self.shadow = pygame.Surface((sel...
StarcoderdataPython
3220743
<reponame>Guilehm/investir-nao-da-xp from django.contrib import admin from communications.models import Communication @admin.register(Communication) class CommunicationAdmin(admin.ModelAdmin): list_display = ('id', 'method', 'error', 'date_added') list_filter = ('date_added', 'method') search_fields = ('...
StarcoderdataPython
3222872
# Input: A pickle file with multiple things pickled in it: # Output: A text file of python pickles in a single file # Convert some pickles to Python import cPickle from pprint import pprint import sys import string if len(sys.argv) != 3 : print "Usage: pickles2pythondicts.py pickleddata.pickle pythontable.py"...
StarcoderdataPython
8052385
# SPDX-License-Identifier: BSD-3-Clause from ..util import * __all__ = ( 'sim_case', 'run_sims', ) def _collect_sims(*, pkg): from pkgutil import walk_packages from importlib import import_module from inspect import getmembers from os import path from amaranth.sim import Simulator def...
StarcoderdataPython
1981990
<reponame>ccebrecos/btc-scripting import sys from btc_framework.bitcoin import OP_AND, OP_OR, OP_XOR, OP_1, OP_0 from btc_framework.bitcoin import SignableTx, TxInput, TxOutput, script, \ address if __name__ == "__main__": # read params keys_base58 = sys.argv[1:] keys =...
StarcoderdataPython
5050869
# Author: <NAME> # Problem 004 # Find the largest palindrome made from the product of two 3-digit numbers\ def isPalindrone(number): '''Check each digit of the number to check for a palimdrone''' str_number = str(number) digits = list(str_number) length = len(digits) for i in range(0, length): ...
StarcoderdataPython
1786062
<reponame>sebnil/internet-uptime import time import urllib.request from datetime import date def internet_on(): try: urllib.request.urlopen('http://google.se', timeout=5) return 1 except urllib.request.URLError: print('URLError') except: print('could not do urlopen') ret...
StarcoderdataPython
8081734
<reponame>LpLegend/zenml<gh_stars>1-10 import inspect from abc import abstractmethod from tfx.orchestration import metadata from tfx.orchestration import pipeline as tfx_pipeline from tfx.orchestration.local.local_dag_runner import LocalDagRunner from playground.datasources.base_datasource import BaseDatasource from ...
StarcoderdataPython
3301005
import struct from typing import Tuple, Optional, Union from bxcommon.utils.blockchain_utils.ont.ont_object_hash import OntObjectHash from bxgateway import ont_constants from bxgateway.messages.ont.ont_message import OntMessage from bxgateway.messages.ont.ont_message_type import OntMessageType class GetDataOntMessag...
StarcoderdataPython
6470049
import uuid from django.db import models from cities.models import City from users.models import User class OfferCategory(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(verbose_name='Наименование', max_length=50) class Meta: ve...
StarcoderdataPython
11319089
import json, requests, urllib3 from flask import Flask, request, jsonify from datetime import datetime import time import traceback import os import redis import cPickle as pickle from multiprocessing import Process def avi_request(avi_api,tenant,api_version='17.2.1'): cookies=dict() if 'avi-sessionid' in l...
StarcoderdataPython
356874
<reponame>metataro/DirectFeedbackAlignment<gh_stars>1-10 from distutils.core import setup from Cython.Build import cythonize import numpy as np setup( name='im2col', ext_modules=cythonize("network/utils/im2col_cython.pyx"), include_dirs=[np.get_include()] )
StarcoderdataPython
1864015
from rest_framework import serializers from ..models import CartItem, Order from ..serializers.carts import CartItemSerializer class OrderSerializer(serializers.ModelSerializer): order_items = CartItemSerializer(many=True) class Meta: model = Order fields = ( 'pk', 'o...
StarcoderdataPython
1602919
#!/usr/bin/env python import sys import os import json from huvr_client import Client from huvr_client.helpers import make_base_directory, save_profile_to_file, save_checklist_to_file, save_project_type_to_file if __name__ == '__main__': # .-------------------------------. # | Setup main variables ...
StarcoderdataPython
9704479
#!/usr/bin/env python from __future__ import (absolute_import, division, print_function) from ansible.plugins.callback import CallbackBase from jinja2 import Template from ansible.errors import AnsibleError, AnsibleParserError from ansible.module_utils._text import to_native from tempfile import SpooledTemporaryFile ...
StarcoderdataPython
3300932
<gh_stars>1-10 import argparse import sys from pathlib import Path from ruamel.yaml import YAML from termcolor import cprint def parse_cli_overides(): """Parse the command-line arguments. Parse args from CLI and override config dictionary entries This function implements the command-line interface of t...
StarcoderdataPython
4879196
import logging import os from pathlib import Path from dotenv import load_dotenv env_path = Path(__file__).resolve().parent.parent / "envs/etl.env" load_dotenv(dotenv_path=env_path) logging.basicConfig(filename="logs/etl.log", level="INFO") logger = logging.getLogger() logger.setLevel(level="INFO") dsl = { "dbn...
StarcoderdataPython
4933353
<reponame>LordFitoi/feline<filename>feline/jobposts/migrations/0013_auto_20211108_1026.py # Generated by Django 3.1.13 on 2021-11-08 14:26 import ckeditor.fields from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('jobposts', '0012_auto_20211103_0559'), ] o...
StarcoderdataPython
1694076
<reponame>abcdabcd987/acm-compiler-judge #!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function, division, unicode_literals import os import csv import sys import time import json import shutil import codecs import hashlib import StringIO from datetime import datetime from collections impor...
StarcoderdataPython
11331606
<filename>test/tests/multiprocessing_test.py import multiprocessing # from https://docs.python.org/2/library/multiprocessing.html def f(x): return x*x if __name__ == '__main__': p = multiprocessing.Pool(5) print(p.map(f, [1, 2, 3])) def f(name): print 'hello', name if __name__ == '__main__': p...
StarcoderdataPython
6554682
# DEPRECATED!! import torch.nn as nn import torch import torch.optim as optimizer import torch.nn.functional as F ''' input : (15x15) numpy array output : realno število ?? ''' class NNFullyConnected(nn.Module): """ Returns a fully connected neural network of given dimensions. The input is of dimensions ...
StarcoderdataPython
1682119
<reponame>bmacphee/sqlalchemy from typing import List from typing import TYPE_CHECKING from sqlalchemy import Column from sqlalchemy import ForeignKey from sqlalchemy import Integer from sqlalchemy import String from sqlalchemy.orm import Mapped from sqlalchemy.orm import relationship from sqlalchemy.orm.decl_api impo...
StarcoderdataPython
11239101
# coding: utf-8 from __future__ import absolute_import import unittest from flask import json from six import BytesIO from openapi_server.models.coupled_model import CoupledModel # noqa: E501 from openapi_server.test import BaseTestCase class TestCoupledModelController(BaseTestCase): """CoupledModelController...
StarcoderdataPython
6452167
#More guests: names = ['tony','steve','thor'] message = ", You are invited!" attendeemessage = " is not coming." print(names[0]+message) print(names[1]+message) print(names[2]+message) print(names[1]+attendeemessage) del names[1] names.insert(1,'peter') print(names[0]+message) print(names[1]+message) print(names[2]...
StarcoderdataPython
4995709
import open3d as o3d import numpy as np import matplotlib.pyplot as plt # Grab intensity of items = how much it reflects off object intensity = [] with open('object3dF1.pcd') as f: coordinates = f.readlines() for line in coordinates: try: values = list(map(float,line.split())) intensity.app...
StarcoderdataPython
9650556
from construct import * from construct.lib import * def enum_int_range_u__constants(subcon): return Enum(subcon, zero=0, int_max=4294967295, ) enum_int_range_u = Struct( 'f1' / enum_int_range_u__constants(Int32ub), 'f2' / enum_int_range_u__constants(Int32ub), ) _schema = enum_int_range_u
StarcoderdataPython
1791572
#!/usr/bin/env python import requests HTTP POST message to cloud platform #Most times gateway communicate with cloud via MQTT(hbmqtt framework), #in some special time, it need to use HTTP(requests framework) to POST message to cloud.
StarcoderdataPython
1746538
#Import accel module from rstem import accel from time import sleep #Initialze accelerometer on i2c bus 1, on early Pi's this may be 0 instead accel.init(1) #Loop to display values while True: force = accel.read() #Returns a tuple of the form (x, y, z) acceleration angles = accel.angles() #Returns a...
StarcoderdataPython
1954949
class URLValidator: def validate_url(self, url: str) -> bool: pass
StarcoderdataPython
9753068
<reponame>kids-first/kf-api-release-coordinator import json import pytest from coordinator.api.models import Release, Event from coordinator.api.models.release import next_version def test_version_bumping(db): r = Release() r.save() assert str(r.version) == '0.0.0' assert str(next_version()) == '0.0.1...
StarcoderdataPython
226078
<reponame>klassen-software-solutions/BuildSystem #!/usr/bin/env python3 """Program to run a static analysis on a directory. Note that at present this simply runs pylint. """ import os import subprocess import sys def _main(directory): if not os.path.isdir(directory): print("'%s' does not exist or is ...
StarcoderdataPython
4904471
<reponame>TianXie1999/selective-inference import numpy as np import sys from scipy.stats import norm import regreg.api as rr from .credible_intervals import projected_langevin from .lasso_reduced import nonnegative_softmax_scaled, neg_log_cube_probability class selection_probability_objective_ms_lasso(rr.smooth_atom...
StarcoderdataPython
153611
<gh_stars>0 """ Stores a Boolean indicating if the app should run in debug mode or not. This option can be set with -d or --debug on start. """ debug = False """ Variable storing a reference to the container backend implementation the API should use. This option can be set with --container-backend CONTAINER_BACKEND...
StarcoderdataPython
1750226
import struct import GLWindow import ModernGL wnd = GLWindow.create_window() ctx = ModernGL.create_context() prog = ctx.program( ctx.vertex_shader(''' #version 330 in vec2 vert; in vec2 pos; in float scale; in vec3 color; out vec3 v_color; void main() { ...
StarcoderdataPython
3398294
<gh_stars>0 # this Python snippet is stored as src/py/api.py def calculate(body): niter = body['niter'] from calculatepipy import PiCalculate pifinder = PiCalculate(niter) pi = pifinder.calculate() return {'pi': pi}
StarcoderdataPython
12855683
import requests def ok(event, context): url = "http://ok:8080/" response = requests.request("GET", url) return response.text
StarcoderdataPython
5008574
import asyncio from typing import List from .api import ApiProvider, ApiError from .structs import ( Pair, OrderSide, OrderStatus, OrderType, Period, Candle, Trade, OrderInBook, OrderBook ) class Exchange: """Interface to base exchange methods.""" def __init__(self, api: ApiProvider = None): ...
StarcoderdataPython
5115216
<filename>Ch02_Pattern_SlidingWindow/P1_MaximumSumSubarrayOfSizeK/Python/solution.py # Copyright (c) 2021 <NAME> # # This software is released under the MIT License. # https://opensource.org/licenses/MIT class Solution: def max_sub_array_of_size_k(self, k, arr): max_sum , window_sum = 0, 0 window_start = 0 ...
StarcoderdataPython
4963629
import binascii import sys import Adafruit_PN532 as PN532 # Hack to make code compatible with both Python 2 and 3 (since 3 moved # raw_input from a builtin to a different function, ugh). try: input = raw_input except NameError: pass # PN532 configuration for a Raspberry Pi: CS = 18 MOSI = 23 MISO = 24 SC...
StarcoderdataPython
1910283
""" Application Config """ FUND_STORE = ( "https://funding-service-design-fund-store-dev.london.cloudapps.digital" ) APPLICATION_STORE = "https://funding-service-design-application-store-dev.london.cloudapps.digital" # noqa
StarcoderdataPython
8144102
from django.core.urlresolvers import resolve from django.http import HttpRequest from django.http import QueryDict from django.test import TestCase from django.test import Client from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators i...
StarcoderdataPython
9737374
import logging # We don't catch this one internallyclass OptFail(Exception): class OptError(Exception): def __init__(self, mesg='None given', err_type='Not specified'): optimize_log = logging.getLogger(__name__) optimize_log.critical('OptError: Optimization has failed.') self.mesg = mesg ...
StarcoderdataPython
5190724
from DB2Gams_l2 import * import ShockFunction class gams_model: """ Databases: Dictionary with databases. Keys = name of database, value∈{path to gdx file, GamsDatabase, or a DataBase.py_db}. work_folder: Point to folder where the model should be run from. opt_file: Add options file. If None, a default options fi...
StarcoderdataPython
1603389
# -*- coding: utf-8 -*- """ Created on 201906 Author : GJ Python version:3.7 """ import pandas as pd from WindPy import * import numpy as np import xlsxwriter as xls import datetime import calendar import copy import os from decimal import Decimal import time import seaborn as sns import openpyxl ...
StarcoderdataPython
4985098
<filename>0642 Number of K-Divisible Sublists.py class Solution: def solve(self, nums, k): nums.insert(0,0) counts = defaultdict(int, {0:1}) ans = 0 for i in range(1,len(nums)): nums[i] += nums[i-1] m = nums[i]%k ans += counts[m] ...
StarcoderdataPython
1715709
<reponame>py-graphit/py-graphit # -*- coding: utf-8 -*- """ file: graph_arraystorage_driver.py Classes that store nodes, edges and their attributes as numpy arrays using the Pandas package """ import weakref import logging from collections import MutableMapping from numpy import nan as Nan from pandas import DataFr...
StarcoderdataPython
4926290
<filename>uploadserver/__main__.py<gh_stars>10-100 import uploadserver if __name__ == '__main__': uploadserver.main()
StarcoderdataPython
266202
from gym import GoalEnv, spaces from inspect import getargspec from mujoco_py import MjViewer import numpy as np from .environment import Environment class GymWrapper(GoalEnv): """Wraps HAC environment in gym environment. Assumes hac_env is an instance of Environment as defined in the original Hier...
StarcoderdataPython
6478230
#!/usr/bin/python ################################################################################# # EC2 server backup daily retenttion job # removes backups older than day specified in local cache # # ec2_local_backup_retention.py --days 10 --dir /var/backup --prefix db_bk.tgz ####################################...
StarcoderdataPython
1723085
#!/usr/bin/python3 ''' FILE NAME relay_demo_gpiod.py 1. WHAT IT DOES This is a very simple script that shows how to turn on and off a single relay on the Keyestudio 4 Channel relay HAT, or any other relay HAT that can be controled directly through the Raspberry Pi GPIOs. In this example, the GPIO is controlled using ...
StarcoderdataPython
5070653
<reponame>RajivBiswal/myprofile-rest-api from django.urls import path, include from profile_api import views from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register('hello-viewset', views.HelloVeiwset, base_name='hello-viewset') router.register('profile', views.UserProfileViewset) ro...
StarcoderdataPython
3532627
<gh_stars>1-10 from typing import List, Optional, Tuple from mikan.combine import NumberCombine, StandardCombine, TsuCombine from mikan.compound import Compound from mikan.number import Number from mikan.word import Word from mikan.writing import Writing __all__ = [ 'Counter', 'DayHourCounter', 'MonthDayCo...
StarcoderdataPython
9754398
from Task import Task from Interfaces import Management from Helper import Level from time import sleep from datetime import datetime class SingleSliceCreationTime(Task): def __init__(self, logMethod, parent, params): super().__init__("Single Slice Creation Time Measurement", parent, params, logMethod, No...
StarcoderdataPython
249897
#!/usr/bin/env python3 from django.core.management.base import BaseCommand, CommandError from django.contrib.auth.models import User class Command(BaseCommand): help = 'Add teammate' def add_arguments(self, parser): parser.add_argument('username', nargs='+', type=str) def handle(self, *args, **o...
StarcoderdataPython
1719579
<gh_stars>0 from django.shortcuts import render from django.views.generic import ListView from.models import LegoSet # Create your views here. def LegoHome(request): return render(request, "lego/lego_home.html") class LegoListView(ListView): model = LegoSet template_name = "lego/lego_list.html"
StarcoderdataPython
5079253
<reponame>linqyd/etk import re """ Keywords: all the street types we want to match on. """ keywords = ["avenue", "blvd", "boulevard", "pkwy", "parkway", "way", "st", "street", "rd", "road", "drive", "lane", "alley", "ave"] keyword_patterns = dict() for each_keyword in keywords: p = re.compile(r'\...
StarcoderdataPython
8053843
<filename>coffeecart/cart/admin.py from django.contrib import admin from .models import Snacks from .models import Drinks admin.site.register(Snacks) admin.site.register(Drinks)
StarcoderdataPython
5138715
<filename>misc/logic_func.py def equalElements_check(my_list): """ Checks if elements in the list are the same """ return len(set(my_list)) <= 1
StarcoderdataPython
3250208
class RussianSpeedLimits: def getCurrentLimit(self, signs): c, s = True, 60 for sign in signs: if sign == 'default': s = 60 if c else 90 elif sign == 'city': s = 90 if c else 60 c = not c else: s = in...
StarcoderdataPython
8142145
from flask_bootstrap import Bootstrap from flask_login import LoginManager from flask_migrate import Migrate from flask_rq2 import RQ from flask_sqlalchemy import SQLAlchemy bootstrap = Bootstrap() db = SQLAlchemy() migrate = Migrate() rq = RQ() login_manager = LoginManager() login_manager.login_view = "web.login"
StarcoderdataPython
5184044
from django_elasticsearch_dsl import ( Document, fields, Index, ) from django_elasticsearch_dsl_drf.compat import KeywordField, StringField from django.conf import settings from hyper.models import HyperManager INDEX = Index(settings.ELASTICSEARCH_INDEX_NAMES[__name__]) @INDEX.doc_type class HyperManage...
StarcoderdataPython
6416370
# -*- coding: utf-8 -*- """ Created on Mar 18th 10:58:37 2016 run models, including training and validating @author: hongyuan """ import pickle import time import numpy import theano from theano import sandbox import theano.tensor as tensor import os import scipy.io from collections import defaultdict from theano.te...
StarcoderdataPython
260790
from __future__ import print_function import os import sys import time import argparse import datetime import math import pickle import numpy as np import torchvision import torchvision.transforms as transforms import torch import torch.utils.data as data import torch.nn as nn import torch.optim as optim import tor...
StarcoderdataPython
6639373
<filename>tools/perf-scale-workload/devops_query_driver.py ################################################## ## A multi-process and multi-threaded driver ##### ## that executes the specified query workload #### ## simulating concurrent user sessions querying ## ## recent and historical data ingested into ###### ## the...
StarcoderdataPython
9678181
from flask import Blueprint user = Blueprint('user', __name__, template_folder='templates',static_folder='static') from ytegg.user import views
StarcoderdataPython
1863991
<reponame>tanaydw/CenterNet from __future__ import absolute_import from __future__ import division from __future__ import print_function import _init_paths import os import cv2 import numpy as np from opts import opts from detectors.detector_factory import detector_factory image_ext = ['jpg', 'jpeg', 'png', 'webp']...
StarcoderdataPython
6459527
<filename>joybusutils/tinymodule.py # This is an example module to help me get started with nmigen # It should be a module that sets a signal high after 5 clock cycles. from nmigen import Elaboratable, Signal, Module from nmigen.sim.pysim import Simulator, Tick from tabulate import tabulate class TinyModule(Elaborat...
StarcoderdataPython
9734343
<reponame>brihijoshi/swaad<filename>app/flask_test.py from flask import Flask, request, Response import os import json from werkzeug import utils from aws_detect import detect_labels_local_file from food2fork import get_recipes app = Flask(__name__) label_list = [] @app.route('/handshake', methods=['POST']) def han...
StarcoderdataPython
9796510
<filename>my intereseted short codes/Omniaz/test_HOG.py #%% #importing required libraries from skimage.io import imread from skimage.transform import resize from skimage.feature import hog from skimage import exposure import matplotlib.pyplot as plt # reading the image img = imread('1.jpg') plt.axis("off") plt.imshow...
StarcoderdataPython