id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
1700613 | <reponame>harrysame/ReinforcementLearning<gh_stars>1-10
import numpy as np
stateSpace = np.zeros([48,2], dtype=int)
stateSpace[:,0] = np.tile(range(12),4)
stateSpace[:,1] = np.tile(np.repeat(range(4),12),1)
stateSpace = stateSpace.tolist()
terminal_state = [11,0]
cliff_states = np.arange(1,11) #i.e. states [1,0],[2,0]... | StarcoderdataPython |
177134 | <reponame>nint8835/hyperion-test-bot
import os
from functools import lru_cache
from typing import Any, Dict, Optional
from dotenv import load_dotenv
from requests import Session
load_dotenv()
hyperion_base_url = f"{os.getenv('HYPERION_ENDPOINT')}/api/v1"
hyperion_session = Session()
hyperion_session.headers.update(... | StarcoderdataPython |
58542 | <gh_stars>1-10
# -*- coding: utf-8 -*-
# ====================================== #
# @Author : <NAME>
# @Email : <EMAIL>
# @File : __init__.py.py
# ALL RIGHTS ARE RESERVED UNLESS STATED.
# ====================================== #
import numpy as np
import pytorch_lightning as pl
import torch
from torch.nn import ... | StarcoderdataPython |
1651154 | from dataclasses import asdict, is_dataclass, make_dataclass
from functools import partial
import typing as t
def _g_ignore(prop: t.Tuple[str, t.Any]):
"""Global properties ignore for serialization."""
key, value = prop
return not (
value is None
or key in ('senha',)
or key.endswit... | StarcoderdataPython |
1786343 | import unittest
import solution
class TestQ(unittest.TestCase):
def test_case_0(self):
self.assertEqual(solution.cuttree(3, 1, [[2, 1], [2, 3]]), 6)
if __name__ == '__main__':
unittest.main()
| StarcoderdataPython |
1765644 | from __future__ import print_function
import flydra_analysis.a2.core_analysis as core_analysis
import numpy as np
import flydra_analysis.a2.utils as utils
class EquivalentObjectFinder:
def __init__(self, src_h5, dst_h5):
self.ca = core_analysis.get_global_CachingAnalyzer()
self.src_h5 = src_h5
... | StarcoderdataPython |
198998 | <reponame>fanzhikang/relaxrender<gh_stars>0
from numpy import *
'''blur_factor
Deal with the depth axis from dimg, output image with blur_factor axis
args:
dimg: numpy.ndarray type. Image with a depth axis.
return:
fimg: numpy.ndarray type. Image with a blur_factor axis(total 4 axis).
Blur_factor decide... | StarcoderdataPython |
3305602 | '''
Using .map() with a dictionary
The .map() method is used to transform values according to a Python dictionary look-up. In this exercise you'll practice this method while returning to working with the election DataFrame, which has been pre-loaded for you.
Your job is to use a dictionary to map the values 'Obama' a... | StarcoderdataPython |
1728502 | # -*- coding:utf-8 -*-
class singleton(type):
def __init__(cls, name, bases, dict):
super(singleton, cls).__init__(name, bases, dict)
cls._instance = None
def __call__(cls, *args, **kw):
if cls._instance is None:
cls._instance = super(singleton, cls).__call__(*arg... | StarcoderdataPython |
76791 | """Generate coil geometries.
This module provides functions to generate various coil geometries
that can be used in conjuction with the eppy module to calculate eddy
currents in flat plates.
"""
import numpy as np
import numpy.typing as npt
# ----------------------------------------------------------------------
#... | StarcoderdataPython |
1674765 | <filename>models-training/UDA_BERT/load_data.py
# Copyright 2019 SanghunYun, Korea University.
# (Strongly inspired by <NAME>, Kakao Brain)
#
# This file has been modified by SanghunYun, Korea Univeristy.
# Little modification at Tokenizing, AddSpecialTokensWithTruncation, TokenIndexing
# and CsvDataset, load_data has... | StarcoderdataPython |
1719906 | <reponame>MarcelaSamili/Desafios-do-curso-de-Python
teste = []
teste.append('Marcela')
teste.append(22)
print(f'{teste}')
| StarcoderdataPython |
185390 | <gh_stars>0
from flask_assets import Environment
from flask_cors import CORS
from flask_marshmallow import Marshmallow
assets = Environment()
cors = CORS()
ma = Marshmallow()
| StarcoderdataPython |
182542 | from z3c.relationfield.relation import (RelationValue,
TemporaryRelationValue,
create_relation)
from z3c.relationfield.index import RelationCatalog
from z3c.relationfield.schema import Relation, RelationChoice, RelationList
from z3c.relatio... | StarcoderdataPython |
3248444 | <reponame>Serge3006/ifc2rdf-webapp<filename>converter/tests/functional/test_modules.py
import io
"""
This file constains the functional tests for the app routes
These tests use GETs and POSTs to different URL's to check for the proper behavior
of the app routes
"""
def test_get_home_page(test_client):
"""
G... | StarcoderdataPython |
31596 | <filename>testapp2/admin.py<gh_stars>10-100
""" testapp2 admin configs """
from django.contrib import admin
from testapp2.models import Library
admin.site.register(Library)
| StarcoderdataPython |
73697 | <gh_stars>0
import os
import sqlite3
from query_function import query_and_print
"""
THIS is the output from your queries as docstring comments
FOR GRADING PURPOSES
$ python northwind.py
********************************************************************************
PART TWO
*****************************************... | StarcoderdataPython |
176016 | import threading
import etcd
from oslo_log import log
from networking_ovn.common import config
LOG = log.getLogger(__name__)
class OVSDBWatchLeaderThread(threading.Thread):
def __init__(self, hosts):
self.ovsDbNbOvnIdls = []
threading.Thread.__init__(self)
self.client = etcd.Client(hosts... | StarcoderdataPython |
13049 | <filename>src/user_auth_api/serializers.py
from rest_framework import serializers
from user_auth_api.models import User
# User Serializer
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = [
'user_name',
'email',
'current_jamb_score',
... | StarcoderdataPython |
4822496 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2019-02-19 18:39
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('travelling', '0031_auto_20190219_1843'),
]
operations = [
migrations.Alter... | StarcoderdataPython |
3347475 |
import requests, re
from typing import List, Optional, Tuple, Literal
#----- Some useful data -----#
regex_version = r'<div class=\"version\">[^<]+<br/>\s*<[^>]+>\s*([^<\n\r]+)\s*</a>'
timeout = 5
#----- Errors management -----#
class Error(Exception):
"""Base class for exceptions in this module."""
pass
c... | StarcoderdataPython |
1662324 | from django.db import models
from projectmanagent.models.general import ProjectManager
from jsonfield import JSONField
# Create your models here.
class InterfaceModule(models.Model):
"""
项目模块的模型
"""
name = models.CharField(max_length=20, verbose_name="name", help_text="模块名")
top = m... | StarcoderdataPython |
1612100 | <filename>CCKNN/predict.py<gh_stars>0
import numpy as np
from ICCStandard.ICCStandard import IPredict
from CCKNN.dataloader import DataLoader
from CCKNN.model import Model
class Predicter(IPredict):
def __init__(self, train_file_name, ignore_first_row=False):
self.model_init()
self.dataloader = Dat... | StarcoderdataPython |
3294257 | # Write a function that takes a string as input and reverse only the vowels of a string.
#
# Example 1:
#
# Input: "hello"
# Output: "holle"
# Example 2:
#
# Input: "leetcode"
# Output: "leotcede"
# Note:
# The vowels does not include the letter "y".
class Solution:
def reverseVowels(self, s):
if len(s) =... | StarcoderdataPython |
4830047 | """Kata: Disemvowel Trolls - return a string with the values of the given
string removed.
#1 Best Practices Solution by cvk77, zyrolasting, sneakybueno.
def disemvowel(s):
return s.translate(None, "aeiouAEIOU")
"""
def disemvowel(string):
return ''.join([x for x in string if x != 'O' and x != 'o' and x != '... | StarcoderdataPython |
3243938 | import sys
class AnomalyLevel(object):
def __init__(self, level):
self.level = level
def __str__(self):
return level
module = sys.modules[__name__]
for level in ['INFO', 'UNUSUAL', 'CORRUPTION']:
setattr(module, level, AnomalyLevel(level))
class Anomaly(object):
def __init__(self, c... | StarcoderdataPython |
30027 | from Custom-env.envs.Env1 import ENV1_NAME
from Custom-env.envs.Env2 import ENV2_NAME
| StarcoderdataPython |
3336992 | <filename>pyqchem/__init__.py
__author__ = '<NAME>'
__version__ = '0.8.8'
from pyqchem.structure import Structure
from pyqchem.qc_input import QchemInput
from pyqchem.qchem_core import get_output_from_qchem
| StarcoderdataPython |
1626302 | <reponame>jb-adams/simple-passports-admin<filename>ga4gh/passports/cli/broker.py
import click
import os
from ga4gh.passports.utils.dirutils import DirUtils
@click.group()
def broker():
pass
@click.command()
def ls():
brokers = DirUtils.list_subfiles(DirUtils.get_brokers_dir())
if len(brokers) == 0:
... | StarcoderdataPython |
3204100 | from behave import *
import requests
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token
use_step_matcher("re")
@given("that I am a unregistered participant of a event")
def step_impl(context):
context.username = "12thMan"
context.password = "<PASSWORD>"
context... | StarcoderdataPython |
149702 | <gh_stars>0
import functools
import pathlib
import typing
import click
import pygit2
from . import context
def is_clean(repo: pygit2.Repository) -> bool:
return not any(
code
for code in repo.status().values()
if (
code
^ (code & pygit2.GIT_STATUS_WT_NEW)
... | StarcoderdataPython |
1782307 | # Generated by Django 2.2.9 on 2020-03-08 03:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('device', '0027_auto_20200224_2035'),
]
operations = [
migrations.AddField(
model_name='device',
name='mysqladdress',... | StarcoderdataPython |
3251264 | <filename>python/authz/test_authorization.py
import requests
from fhir.resources.capabilitystatement import CapabilityStatement
from rich import print
def url(endpoint, path):
"""append the provided path to the endpoint to build an url"""
return f"{endpoint.rstrip('/')}/{path}"
endpoint = "https://terminology... | StarcoderdataPython |
3322233 | # -*- coding: utf-8 -*-
from datetime import timedelta, datetime
import pandas as pd
from fooltrader.bot.bot import NotifyEventBot
from fooltrader.contract.es_contract import get_es_kdata_index, get_es_statistic_index
from fooltrader.domain.data.es_quote import CommonKData, CommonStatistic
from fooltrader.settings im... | StarcoderdataPython |
1635312 | import os
import logging
import typer
from typing import Optional
from pathlib import Path
from nemreader import nmis_in_file
from nemreader import output_as_csv
from nemreader import output_as_daily_csv
from nemreader import output_as_sqlite
from nemreader import __version__
LOG_FORMAT = "%(asctime)s %(levelname)-8s ... | StarcoderdataPython |
86555 | <reponame>LuchaComics/comicscantina-django<gh_stars>0
import json
from datetime import datetime
from django.shortcuts import render
from django.core import serializers
from django.http import HttpResponse
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.contrib.auth... | StarcoderdataPython |
3374070 | __author__ = 'vietbq'
import struct
import threading
import io
class SocketReader(threading.Thread):
def __init__(self, connection):
super(SocketReader, self).__init__()
self.connection = connection
self.stream = io.BytesIO()
self.terminated = False
def run(self):
whil... | StarcoderdataPython |
3232658 | import glob
import os
import pathlib
import re
from collections import defaultdict
from typing import Dict, Union
REGEX_ENTITY = re.compile(r'^(T\d+)\t([^\s]+)([^\t]+)\t(.*)$')
REGEX_NOTE = re.compile(r'^(#\d+)\tAnnotatorNotes ([^\t]+)\t(.*)$')
REGEX_STATUS = re.compile(r'^(#\d+)\tStatus ([^\t]+)\t(.*)$')
REGEX_RELATI... | StarcoderdataPython |
173560 | # -*- coding: utf-8 -*-
import json
from collections import OrderedDict
from operator import itemgetter
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
from django.contrib.postgres.fields import ArrayField
from django.db import models
from django.utils.tra... | StarcoderdataPython |
3369727 | @app.route("/") # Root (default) page to display when landing on web site
@app.route("/page/<int:page>") # Specific site page
@login_required # Force authentication
def entries(page=1):
"""
Query the database entries of the blog.
:param page: The page number of the site.
:return: Template page with the... | StarcoderdataPython |
1738823 | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | StarcoderdataPython |
1797589 | """
Скрипт запуска последовательности обработки данных на разных наборах параметров
Основная цель - визуальная оценка качества обработки при различных наборах значений параметров
компенсация набега -> формирование и сохранение карт качества -> развертка и сохранения результата
Пример использования:
... | StarcoderdataPython |
1788108 | import re
from markdown import markdown
from django.db import models
from django.contrib.auth import models as user_models
class Page(models.Model):
"""
A single page.
"""
path = models.CharField(max_length=1024, blank=True)
content = models.TextField()
last_updated = models.DateTimeField(a... | StarcoderdataPython |
174066 | <reponame>ITXIAOKE/XKInterface-python
__author__ = "xiaoke"
class GlobalVar:
'''拿到execl中列的值,最后在程序的主入口中,遍历行的时候,根据行和列就能拿到cell单元格的值'''
# id值
ID = '0'
# 模块
NAME = '1'
# 请求的url
URL = '2'
# 是否运行
RUN = '3'
# 请求的方式
REQUEST_METHOD = '4'
# 是否携带header
HEADER = ... | StarcoderdataPython |
1787860 | <reponame>haraldujc/pyladder
# This is a sample client calling the graph rendering engine with a dictionary of nodes.
# This convention invokes pyladder to visually display the graph.
# The dictionary key is the descriptor of a node that will be displayed along the y axis
# The dictionary value is a list of nodes, wher... | StarcoderdataPython |
60038 | from .. import *
from ..utils.mini_batch_iter import MINI_BATCH_ITER
from .classifier import Classifier
from .nn_model import NN_Model
# def check_attributes(check_attributes):
# def func(*args,**kwargs):
# try check_attributes:
# if check_attributes:
# func()
# except Exception as e... | StarcoderdataPython |
1748109 | from typing import List
import numpy as np
import zmq
def send_array(socket, A: np.ndarray, t: List[int],
n_samples: int, std: List[float],
flags=0, copy=True, track=False):
"""send a numpy array with metadata
A can be:
xu: (n, n_x + n_u): 2D array containing the nominal ... | StarcoderdataPython |
3286959 | import re
import datetime
def LogSquad_Damage(data_str, server_id):
matchObj = re.search(r"[([0-9.:-]+]\[([ 0-9]*)]LogSquad: Player:(.*) ActualDamage=(\d+(\.\d+)?) from (.*) "
r"caused by (.*).*",
data_str, re.M | re.I)
date_time = datetime.datetime.strptime(m... | StarcoderdataPython |
3374772 | from precipy.main import render_data
import tests.analytics
def test_render_data():
config = {
# The report template
'template' : """a is {{ wavy_line_plot.args.a }}""",
# Sources for data prep & asset gen (plots, json data)
'analytics' : [
['wavy_line_plot', {'a' : 7, '... | StarcoderdataPython |
179402 | import unittest
from typing import List
import torch
from torch import nn
import Utility.Torch.Models.Supertransformer.EnsembleTools.SuperEnsemble
from Utility.Torch.Models.Supertransformer.Layers import EnsembleTools as Ensemble
class test_Submodel(unittest.TestCase):
"""
Tester for the submodel unit of t... | StarcoderdataPython |
1696039 | from zomato_api.requester import Requester
class Zomato():
def __init__(self, API_KEY):
self.r = Requester(API_KEY)
def get_categories(self):
categories = self.r.get('categories')
return categories['categories']
def get_cities(self, **kwargs):
params = {}
availabl... | StarcoderdataPython |
1751803 | # Regular Expressions
import re
with open('Day2/input.txt','r') as file:
data = file.readlines()
count = 0
for line in data:
arr = line.split(' ')
range = arr[0].split('-')
letter = arr[1].replace(':','')
value = arr[2].replace('\n','')
#ncount count of matches
ncount = 0
for n in val... | StarcoderdataPython |
105186 | # -*- coding: utf-8 -*-
import clr
import os.path
project_dir = os.path.dirname(os.path.abspath(__file__))
import sys
sys.path.append(os.path.join(project_dir, "TestStack.White.0.13.3\\lib\\net40\\"))
sys.path.append(os.path.join(project_dir, "Castle.Core.3.3.0\\lib\\net40-client\\"))
clr.AddReferenceByName("TestStack... | StarcoderdataPython |
160341 | <reponame>civascu/hue<filename>desktop/core/ext-py/Twisted/twisted/web/test/test_cgi.py
import sys, os
from twisted.trial import unittest
from twisted.internet import reactor, interfaces
from twisted.python import util
from twisted.web import static, twcgi, server, resource
from twisted.web import client
DUMMY_CGI = ... | StarcoderdataPython |
4830927 | from __future__ import absolute_import
import os
from typing import Optional # noqa: F401
from eth_keys.utils.module_loading import (
import_string,
)
from .base import BaseECCBackend # noqa: F401
from .coincurve import ( # noqa: F401
CoinCurveECCBackend,
is_coincurve_available,
)
from .native import ... | StarcoderdataPython |
1649791 | # converter = mdates.ConciseDateConverter()
# munits.registry[np.datetime64] = converter
# munits.registry[datetime.date] = converter
# munits.registry[datetime.datetime] = converter
# Convert to Numpy array
xvals = data['Date/Time'].values
yvals = data['Mean Temp (°C)'].values
fig = plt.figure(dpi=100, figsize=(14,... | StarcoderdataPython |
182169 | <filename>csvio/processors/processor_base.py
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Any, Dict, Type, Union
from ..utils.types import RS, R
class ProcessorBase(ABC):
"""
Processor Base Class
"""
processors: Dict[str, Any] = {}
def __init__(self... | StarcoderdataPython |
1697213 | #!/usr/bin/env python
import os
import argparse
import btrwin.lib as lib
import btrwin.units as units
#G=units.conf.load()
def create_prefix_config(PREFIX,TPL='',BIT='',EXES=''):
G=units.conf.load()
bin=['wine','wine64','wineboot','winecfg','wineconsole','msiexec','notepad','regedit','regsvr32','wineserver','wine... | StarcoderdataPython |
3236503 | <filename>eval_cd_nc_f1_ecd_ef1.py
import numpy as np
import os
import h5py
from multiprocessing import Process, Queue
import queue
import time
import trimesh
from sklearn.neighbors import KDTree
sample_num = 100000
pred_dir = "samples/"
gt_dir = "../../objs/"
f1_threshold = 0.003
ef1_radius = 0.004
ef1_dotproduct_th... | StarcoderdataPython |
3210667 | # -*- coding: utf-8 -*-
"""
Created on Fri Jan 3 11:08:35 2020
@author: martijn.krol
"""
import json
import pandas as pd
import logging
import gspread
from oauth2client.service_account import ServiceAccountCredentials
from localsecret import username, password
from spiceup_labels.config_lizard import patch_labeltype... | StarcoderdataPython |
3347059 | <reponame>G-H-Li/PathNavigation
import math
import time
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl
from data import obstacles
from data.Map import Map
from data.plotting import plot_map, plot_set_title, plot_clear, plot_path, plot_show
# 此方案无法找到合适参考,在本题目的应用场景中存在缺陷,短时间内我无法解决,暂时废弃
c... | StarcoderdataPython |
1612664 | <filename>settings.py
DEBUG = True
# Feature knobs are only intended for incomplete functionality.
FEATURES = {
'PARSE_MARKERS': True,
}
| StarcoderdataPython |
4807369 | import subprocess
import sys
import random
import os
def addLineToFile(oFile, line):
with open("oFile", "a+") as file_object:
# Move read cursor to the start of file.
file_object.seek(0)
# If file is not empty then append '\n'
data = file_object.read(100)
if len(data) > 0 :
... | StarcoderdataPython |
3390375 | from typing import Union
import abjad
from .extract_trivial_tuplets import (
extract_trivial_tuplets as extract_trivial_tuplets_function,
)
def prettify_rewrite_meter(selection: abjad.Selection,
meter: Union[abjad.Meter, abjad.TimeSignature],
*,
... | StarcoderdataPython |
3318611 | # Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html
import scrapy
class ScrapyZmkItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
index = scrapy.Field()
zh = scrapy.Field()
en = scra... | StarcoderdataPython |
65122 | <gh_stars>1-10
from cryptography.hazmat.primitives import serialization as crypto_serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import (
default_backend as crypto_default_backend)
def generate_ssh_keys():
key = rsa.generate_private_key(
backe... | StarcoderdataPython |
1781555 | #
# Copyright IBM Corporation 2021
#
# 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 wri... | StarcoderdataPython |
4832834 | import os
import re
import subprocess
import random
import shutil
import logging
import time
from anchore import anchore_utils
from anchore.util import scripting, contexts
class Navigator(object):
_logger = logging.getLogger(__name__)
def __init__(self, anchore_config, imagelist, allimages):
self.con... | StarcoderdataPython |
3209241 | <filename>challenges/003-sumofprimes.py
def generate_n_primes(n):
primes = []
i = 2
while len(primes) < n:
if not filter(lambda x: i % x == 0, primes):
primes.append(i)
i += 1
return primes
print sum(generate_n_primes(1000)) | StarcoderdataPython |
4838752 | # Copyright (c) 2022 Mira Geoscience Ltd.
#
# This file is part of geoapps.
#
# geoapps is distributed under the terms and conditions of the MIT License
# (see LICENSE file at the root of this source code package).
from uuid import UUID
from geoh5py.objects.surveys.electromagnetics.magnetotellurics import MTRecei... | StarcoderdataPython |
83043 | """penaltymodel provides functionality for accessing PenaltyModel factories.
Accessing Factories
-------------------
Any factories that have been identified through the :const:`FACTORY_ENTRYPOINT` entrypoint
and installed on the python path can be accessed through the :func:`get_penalty_model`
function.
Examples:
... | StarcoderdataPython |
3209536 | <filename>py/src/experimental/constantine/Halfar-SIA-MMS.py
#!/usr/bin/env python
# coding: utf-8
# In[19]:
#from bokeh.plotting import output_notebook, figure, show
#output_notebook()
# In[2]:
import numpy as np
# In[3]:
import sympy as sp
# Next, import some shortcuts:
# - `S` turns the argument into a S... | StarcoderdataPython |
69961 | import zeit.edit.testing
class EditorJavascript(zeit.edit.testing.SeleniumTestCase):
def test_initial_editor_load_loads_js_and_css(self):
self.open(
'/@@/zeit.edit.browser.tests.fixtures/initial-load/editor.html')
self.wait_for_condition('!zeit.edit.editor.busy')
self.wait_for... | StarcoderdataPython |
1779999 | <reponame>dnbaumann/acoustic-sight<gh_stars>0
import math
import numpy as np
_curves = dict()
def is_power_of_2(num):
return ((num & (num - 1)) == 0) and num != 0
def hilbert_curve(n):
"""
Generate Hilbert curve indexing for (n, n) array. 'n' must be a power of two.
Taken from http://znah.net/hil... | StarcoderdataPython |
1705175 | from flask import Flask, request
from http_client import place_order
from exceptions import CircuitBreakerOpen
app = Flask(__name__)
@app.route('/buy_course', methods=['POST'])
def buy_course():
post_data = request.get_json()
# TODO: Validate input data
try:
# place the order in the external s... | StarcoderdataPython |
1716119 | #!/usr/bin/env python3
from doxhooks.main import Doxhooks, add_output_roots
from doxhooks.preprocessor_contexts import PreprocessorContext
from doxhooks.resource_configs import ResourceConfiguration as _
from doxhooks.resources import PreprocessedResource
class ControlResource(PreprocessedResource):
class Context... | StarcoderdataPython |
3236942 | # Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
from mmcv.runner import HOOKS, Hook
from mmcv.utils import print_log
@HOOKS.register_module()
class ODCHook(Hook):
"""Hook for ODC.
This hook includes the online clustering process in ODC.
Args:
centroids_update_interval (int): F... | StarcoderdataPython |
1621532 | <gh_stars>1-10
# coding: utf-8
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for
# license information.
# ------------------------------------------------------... | StarcoderdataPython |
50669 | from gbe.forms import ParticipantForm
from django.forms import (
ChoiceField,
MultipleChoiceField,
)
from gbe_forms_text import (
how_heard_options,
participant_labels,
)
from gbetext import (
act_casting_label,
states_options,
)
from scheduler.idd import get_occurrences
from gbe.models import S... | StarcoderdataPython |
100064 | <filename>tests/better_sqrt_test.py
from src.bsqrt import *
def test_better_sqrt():
assert better_sqrt(-180) == (-6, 5)
assert better_sqrt(-100) == (-10, 1)
assert better_sqrt(-70) == (-1, 70)
assert better_sqrt(-16) == (-4, 1)
assert better_sqrt(-1) == (-1, 1)
assert better_sqrt(0) == (0, 0)
... | StarcoderdataPython |
3339288 | """
Example showing how to find all devices from Princeton Instruments.
"""
# this "if" statement is used so that Sphinx does not execute this script when the docs are being built
if __name__ == '__main__':
from msl.equipment.exceptions import PrincetonInstrumentsError
from msl.equipment.resources import Princ... | StarcoderdataPython |
155368 | from bratdb.reader import build_brat_dump
from bratdb.logger import initialize_logging
def main():
import argparse
parser = argparse.ArgumentParser(fromfile_prefix_chars='@!')
parser.add_argument('anndir',
help='Path to directory containing brat annotation files')
parser.add_a... | StarcoderdataPython |
3293791 | from user_sync.error import AssertionException
from Crypto.PublicKey import RSA
def make_auth_dict(name, config, org_id, tech_acct, logger):
auth_dict = {
'org_id': org_id,
'tech_acct_id': tech_acct,
'api_key': config.get_credential('api_key', org_id),
'client_secret': config.get_c... | StarcoderdataPython |
1791510 | <gh_stars>1-10
def leiaInt(msg):
"""LeiaInt
Returns:
[int]: O retorno é o número que o jogador colocou dentro do nosso input.
"""
while True:
num = str(input(msg))
if num.isnumeric():
num = int(num)
break
else:
print('\... | StarcoderdataPython |
1662442 | from django.apps import AppConfig
class ConservationConfig(AppConfig):
name = "conservation"
| StarcoderdataPython |
30594 | <filename>pyannote/audio/applications/pyannote_audio.py
#!/usr/bin/env python
# encoding: utf-8
# The MIT License (MIT)
# Copyright (c) 2019-2020 CNRS
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in th... | StarcoderdataPython |
3329576 | from setuptools import setup
def readme():
with open('README.md') as f:
README = f.read()
return README
setup(
name='python-pysh',
version='0.0.2',
description='A Python package that mimics the Oh-My-ZSH shell. This package creates a colorful ZSH prompt.',
long_description=readme(),
... | StarcoderdataPython |
46560 | <filename>gorden_crawler/spiders/item_lacoste.py
# -*- coding: utf-8 -*-
from scrapy.spiders import Spider
from scrapy.selector import Selector
from gorden_crawler.items import BaseItem, ImageItem, SkuItem, Color
from scrapy import Request
from scrapy_redis.spiders import RedisSpider
import re
import execjs
import js... | StarcoderdataPython |
1696692 | #-*- encoding:utf-8 -*-
import requests
import hashlib
import uuid
class Baidu(object):
"""
baidu translation
"""
def __init__(self, appid, key):
self.appid = appid
self.key = key
self.langList = {}
self.initLang()
def initLang(self):
self.langList['ch'... | StarcoderdataPython |
3247897 | <reponame>Munfred/seqdepth
import numpy as np
import sklearn
import pandas as pd
from glob import glob
from tqdm import tqdm
import anndata
import torch
from scvi.dataset import GeneExpressionDataset
from scvi.models import VAE
from scvi.inference import UnsupervisedTrainer
from scvi.inference.posterior import Posterio... | StarcoderdataPython |
1686938 | <filename>cnt2lms.py
#############################################################################
# Content to LMS converter for CyLMS
#############################################################################
# External imports
from distutils import dir_util
from distutils.errors import DistutilsFileError
import... | StarcoderdataPython |
130292 | <gh_stars>0
#!/usr/bin/env python
"""
Apply a "Security Group" to the members of an etcd cluster.
Usage: apply-firewall.py
"""
import os
import re
import string
import argparse
from threading import Thread
import uuid
import colorama
from colorama import Fore, Style
import paramiko
import requests
import sys
import y... | StarcoderdataPython |
1624378 | from tests import BaseTestCase
from redash.models import ApiKey, Dashboard, AccessPermission, db
from redash.permissions import ACCESS_TYPE_MODIFY
from redash.serializers import serialize_dashboard
from redash.utils import json_loads
class TestDashboardListResource(BaseTestCase):
def test_create_new_dashboard(se... | StarcoderdataPython |
96163 | <reponame>Batool-Salehi/beam_selection
#Script context use : This script uses Raymotime data (https://www.lasse.ufpa.br/raymobtime/) in the context of the UFPA - ITU Artificial Intelligence/Machine Learning in 5G Challenge (http://ai5gchallenge.ufpa.br/).
#Author : <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>... | StarcoderdataPython |
110407 | #Script: Read.py
#Author: <NAME> & <NAME>
#Date: 14 December 2015
""" What this script does:
1. opens the necessary CSV files from the Eclipse and Mozilla Defect Tracking Dataset
and stores into lists named respecitvely
2. create the dependent dummy variable indicating whether a bug was fixe... | StarcoderdataPython |
3268536 | <filename>probayes/functional.py<gh_stars>0
""" Provides Functional to contain multiple expressions """
import collections
import functools
from probayes.functional_utils import NX_UNDIRECTED_GRAPH, collate_vertices,\
parse_identifiers
from probayes.expression import Expression
#... | StarcoderdataPython |
3275169 | <reponame>frogmon-dev/ETCs<filename>src/frogmon/uLogger.py
# uLogger.py
#-*- coding:utf-8 -*-
import sys
import logging
import logging.handlers
import sdnotify
from frogmon.uCommon import COM
from unidecode import unidecode
from colorama import Fore, Back, Style
#logger instance create
logger = logging.... | StarcoderdataPython |
149369 | <gh_stars>10-100
#!/usr/bin/env python3
import os
import sys
import shlex
import subprocess
from attrdict import AttrDict
import re
from configparser import ConfigParser
class VCF2rGFAHelper:
def __init__(self, fasta, vcf, outDir):
try:
import pysam
self.usePysam = True
e... | StarcoderdataPython |
96647 | import cv2
import numpy as np
def build_transformation_matrix(transform):
"""Convert transform list to transformation matrix
:param transform: transform list as [dx, dy, da]
:return: transform matrix as 2d (2, 3) numpy array
"""
transform_matrix = np.zeros((2, 3))
transform_matrix[0, 0] = np... | StarcoderdataPython |
3300738 | import errno
import os
import shutil
__author__ = '<NAME>'
__all__ = ['mkdir_p', 'remove_childreen']
def mkdir_p(path):
'''
Recursively creates the directories in a given path
Equivalent to batch cmd mkdir -p.
Parameters
----------
path : str
Path to the final directory to create.
... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.