id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
4887741 | #
# import pdb
# import numpy as np
#
#
# def tempdic(dictionary):
# latch_lowtohigh = np.nonzero(np.diff(dictionary['TriggerLatch']) == 1)
# dt = np.diff(dictionary['elapsed_time'][0:2])
# timestart = dt * latch_lowtohigh[-1] * (-1)
# timeend = (len(dictionary['elapsed_time']) - latch_lowtohig... | StarcoderdataPython |
35435 | <filename>Traditional/split_path.py
#!/usr/bin/env python3
import os
from posixpath import normpath
path = "///data/video/project1//"
normalized_path = os.path.normpath(path)
sep_path = normalized_path.split(os.sep)
path_tail = sep_path[-1] #last word in path - need to be volume name
currentPath = ''
for folder in sep_... | StarcoderdataPython |
6548121 | import json
from elasticsearch import Elasticsearch
from .definition import ElasticIndex
from .conf import settings
class BaseService:
def __init__(self, entity: ElasticIndex):
assert isinstance(entity, ElasticIndex), "Invalid entity provided, should be an object of ElasticIndex"
self.entity = e... | StarcoderdataPython |
3415824 | <reponame>CaseyK9/Scarecrow
import discord
import discord.ext.commands
def setup(bot):
bot.help_command = TreeHelpCommand()
def teardown(bot):
bot.help_command = discord.ext.commands.DefaultHelpCommand()
class TreeHelpCommand(discord.ext.commands.DefaultHelpCommand):
"""Deviation from the default help... | StarcoderdataPython |
11284423 | #########################################################
#
# Main file for parallel mesh testing.
#
# This is a modification of the run_parallel_advection.py
# file.
#
#
# Authors: <NAME>, <NAME> and <NAME>,
# June 2005
#
#
#
#########################################################
import time
import sys
import n... | StarcoderdataPython |
1965874 | <reponame>s-vigneshwaran/Sustainable-Development-Goals-Classifier
from flask import Flask, jsonify, request
from flask_cors import CORS, cross_origin
from ngram_matcher import NgramMatcher
import uuid
import PyPDF2
import os
import numpy as np
import json
# Loading dataset into memory
fos_ids = np.load('fos_ids.npy', ... | StarcoderdataPython |
4818350 | # Copyright 2014 Mirantis, 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://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | StarcoderdataPython |
5137220 | <filename>pyeccodes/defs/grib2/tables/5/5_7_table.py
def load(h):
return ({'abbr': 1, 'code': 1, 'title': 'IEEE 32-bit', 'units': 'I=4 in Section 7'},
{'abbr': 2, 'code': 2, 'title': 'IEEE 64-bit', 'units': 'I=8 in Section 7'},
{'abbr': 3, 'code': 3, 'title': 'IEEE 128-bit', 'units': 'I=16 i... | StarcoderdataPython |
9612489 | <gh_stars>0
'Helpers for using Django from threads'
from django.db import close_old_connections
from threading import Thread as BaseThread
from concurrent.futures import ThreadPoolExecutor as BaseThreadPoolExecutor
__VERSION__ = '0.0.1'
class Thread(BaseThread):
def start(self):
close_old_connections()
... | StarcoderdataPython |
3206306 | <reponame>gshuflin/pants
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import logging
import os
from dataclasses import dataclass
from typing import Mapping, Optional, Tuple
from pants.base.build_environment import get_buildroot
from... | StarcoderdataPython |
71671 | <gh_stars>0
"""Defines Hello message."""
# System imports
from enum import IntEnum
from pyof.foundation.base import GenericMessage, GenericStruct
from pyof.foundation.basic_types import BinaryData, FixedTypeList, UBInt16, UBInt32, TypeList
from pyof.foundation.exceptions import PackException
from pyof.v0x05.common.h... | StarcoderdataPython |
1728543 | import hangpy
import redis
server_configuration = hangpy.ServerConfigurationDto(cycle_interval_milliseconds=10000, slots=10)
redis_client = redis.StrictRedis(host='172.17.0.1', port=6379, password=None)
job_repository = hangpy.RedisJobRepository(redis_client)
server_repository = hangpy.RedisServerRepository(redis_cl... | StarcoderdataPython |
1615262 | <reponame>outrofelipe/Python-para-zumbis<gh_stars>1-10
import urllib.request
pagina = urllib.request.urlopen(
'http://beans.itcarlow.ie/prices-loyalty.html')
texto = pagina.read().decode('utf-8')
onde = texto.find('>$')
inicio = onde + 2
fim = onde + 4
preco = texto[inicio:fim]
print(preco)
| StarcoderdataPython |
1928022 | <reponame>JNKielmann/Master-Thesis
"""
Expert list create from online survey data.
List contains Microsoft Academic Graph Ids
"""
survey_expert_list = {
"humanoid robot": [
1047662447,
1305265972,
2570474579,
],
"natural language processing": [
2061074560,
207... | StarcoderdataPython |
6682820 | import torch
from torch import nn, optim
from torchvision import models
import numpy as np
from collections import OrderedDict
def create_model(arch, hidden_units , prob_dropout):
# Create model
model = eval("models." + arch + "(pretrained=True)")
model.epochs = 0
# To prevent backprop through p... | StarcoderdataPython |
3454309 | import pytest
import requests
import hashlib
import tarfile
import json
import os
import pyhf
import numpy as np
@pytest.fixture(scope='module')
def sbottom_likelihoods_download():
"""Download the sbottom likelihoods tarball from HEPData"""
sbottom_HEPData_URL = "https://doi.org/10.17182/hepdata.89408.v1/r2"
... | StarcoderdataPython |
11209889 | from bs4 import BeautifulSoup
from markdown import markdown
class Markdown():
def markdown_to_plaintext(markdown_text):
html = markdown(markdown_text)
text = ''.join(BeautifulSoup(html, 'html.parser').findAll(text=True))
return text
def tree_to_plaintext(marked_tree):
text_li... | StarcoderdataPython |
1753353 | #!/usr/bin/env python3
### MORTGAGE CALCULATOR ###
# The program calculates the monthly payments of a fixed term mortgage over given Nth terms at a given interest rate. Also figure out how long it will take the user to pay back the loan.
# Firstly, we define "months" , "interest rate" and "loan".
months = int(input... | StarcoderdataPython |
6630783 | <reponame>sireliah/polish-python<filename>Lib/lib2to3/fixes/fix_tuple_params.py
"""Fixer dla function definitions przy tuple parameters.
def func(((a, b), c), d):
...
->
def func(x, d):
((a, b), c) = x
...
It will also support lambdas:
lambda (x, y): x + y -> lambda t: t[0] + t[1]
# The pa... | StarcoderdataPython |
1715344 | # python3
from abc import ABC
from collections import namedtuple
from sys import setrecursionlimit, stdin
from threading import stack_size, Thread
from typing import AnyStr, IO, List
from unittest import TestCase
setrecursionlimit(10 ** 6)
stack_size(2 ** 27)
border = namedtuple('border', 'left right')
test = namedt... | StarcoderdataPython |
1985595 | <filename>daily_menu/crawler/management/commands/helpers/init_zomato_restaurants.py<gh_stars>0
from django.core.management import BaseCommand
from datetime import datetime
from crawler.models import RestaurantScraperConfig
from restaurants.models import Restaurant
class Command(BaseCommand):
help = 'Scrape recip... | StarcoderdataPython |
8172967 | import numpy as np
counter = 15
for i in range(1, counter):
if i == 10:
break
| StarcoderdataPython |
3250631 | <filename>subscribers/migrations/0004_subscriptionrequest_token.py
# Generated by Django 2.1.4 on 2018-12-17 23:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('subscribers', '0003_auto_20181216_2144'),
]
operations = [
migrations.Add... | StarcoderdataPython |
12861484 | import djclick as click
from django.contrib.auth.models import User, Group
from django.db import transaction
from django.core.management.base import CommandError
class DryRunFinished(Exception):
pass
def get_or_create_users(email_addresses):
users = []
for email in email_addresses:
if not email... | StarcoderdataPython |
3438005 | # (C) Copyright 2020 ECMWF.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of its status as an intergovernmenta... | StarcoderdataPython |
8108953 | """
Module defines REST API methods and their handles.
Implementation of handles is in corresponding modules, not here.
"""
from __future__ import print_function, division
import cherrypy
from WMCore.Configuration import Configuration
from WMCore.REST.Server import RESTApi
from WMCore.REST.Services import ProcessMat... | StarcoderdataPython |
11375916 | <gh_stars>0
class Converter:
def __init__(self, num):
self.num = num
self.lst = []
def binary(self):
"""Function to return a number decimal in binary"""
aux = self.num
while aux > 0:
self.lst.append(str(aux % 2))
aux //= 2
return ''.join(s... | StarcoderdataPython |
9746756 | import os
from xml.etree import ElementTree
import pytest
from . import Dictionary, YaTranslateException
class TestDictionary:
def setup_class(self):
self.api_key = os.environ.get("API_KEY_YA_DICT")
assert self.api_key
self.v_json = Dictionary(self.api_key)
assert self.v_json
... | StarcoderdataPython |
6651387 | from django.urls import path
from . import views
app_name = 'grading'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:test_id>/question/<int:pk>', views.QuestionView.as_view(), name='question'),
path('<int:test_id>/question/<int:question_id>/submit', views.submit, name='submit'),
... | StarcoderdataPython |
185665 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2017, JK
# Full license can be found in License.md
# -----------------------------------------------------------------------------
import os
import sys
from setuptools import setup
import subprocess
# get home directory
home_dir = os.path.expanduser('~')
#... | StarcoderdataPython |
11272995 | <filename>trafilatura/filters.py
"""
Functions related to content filtering, mostly duplicate detection and language
detection.
"""
import logging
import re
# language detection
try:
import cld3
LANGID_FLAG = True
except ImportError:
LANGID_FLAG = False
from .lru import LRUCache
from .settings import LRU... | StarcoderdataPython |
6547418 | <gh_stars>0
from pyserverpilot.models.basemodel import BaseModel
class Server(BaseModel):
id: str
name: str
plan: str
autoupdates: str
firewall: str
deny_unknown_domains: str
available_runtimes: list
lastaddress: str
lastconn: int
datecreated: int
| StarcoderdataPython |
9664075 | # Generated by Django 3.1.12 on 2021-07-12 19:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('survey', '0003_lastpage_description'),
]
operations = [
migrations.AddField(
model_name='lastpage',
name='whatsapp_... | StarcoderdataPython |
11280969 | <gh_stars>1-10
for i in range(10):
print(i, end="")
print()
print(i)
print(2 + 3 * 5.)
print(1//2*3)
x= 11
y = 4
x = x % y
x = x % y
y = y % x
print(y)
print(1/2+3//3+4**2)
x = 2
y = 4
x = x/y
print(y/x)
x=1
y=2
z=x
x=y
y=z
print(x,y)
#x = 2 // 4
#y = 4 // x | StarcoderdataPython |
4847313 | <gh_stars>1-10
from gym_flexlab.envs import flexlab_env
import os
from datetime import timedelta
import pandas as pd
import numpy as np
import pytz
import random
import time
from drllib import dqn_functions
from drllib import models, utils
import torch
import torch.optim as optim
import torch.nn as nn
import torch.n... | StarcoderdataPython |
3501127 | <filename>brax/envs/wrappers.py<gh_stars>0
# Copyright 2021 The Brax 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 req... | StarcoderdataPython |
4964711 | # -*- coding: utf-8 -*-
"""
The ANN classification method in TDEM
Methods:
MLP: the ANN classification method
"""
__all__ = ['MLP']
from sklearn.neural_network import MLPClassifier # 'tanh',lbfgs,(50,)
from sklearn.metrics import accuracy_score
import numpy as np
def MLP(train_set, test_set, solver='lbfgs', hi... | StarcoderdataPython |
6701161 | <reponame>apache/geode-native
#!/usr/local/bin/python3
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file exc... | StarcoderdataPython |
386326 | <gh_stars>1000+
# -*- coding: utf-8 -*-
"""
walle-web
:copyright: © 2015-2017 walle-web.io
:created time: 2017-06-14 15:53:46
:author: <EMAIL>
"""
import logging
from walle.service.extensions import login_manager
from walle.model.user import UserModel
from walle.model.user import RoleModel
from walle.... | StarcoderdataPython |
11280762 | <reponame>AlexNemmo/yt_py_downloader
from pytube import YouTube
link = input("Enter the link: ")
yt = YouTube(link)
print(f"Title: {yt.title}")
print(f"Author: {yt.author}")
print(f"Length: {yt.length}")
ys = yt.streams.get_highest_resolution()
print("Downloading....")
ys.download()
print('\x1b[6;30;42m' + 'Success... | StarcoderdataPython |
8104186 | <reponame>multitudes/Python_am_Freitag
# Capitalizes a copy of a string while checking for errors
import sys
from cs50 import get_string
# Get a string
s = get_string("s: ")
if not s:
sys.exit(1)
# Capitalize first letter in copy
t = s.capitalize()
# Print strings
print(f"s: {s}")
print(f"t: {t}")
sys.exit(0)
| StarcoderdataPython |
8050457 | import numpy as np
import pandas as pd
from tqdm import tqdm
import os
import ast
from IPython import embed
if __name__ == '__main__':
data_path = f'./data/drugs/'
df = pd.read_csv(f'{data_path}train_data_allcontext_sideeffect.csv', index_col=0)
embed()
df.groupby('user')['activity_count'].agg('cou... | StarcoderdataPython |
6414397 | import numpy as np
from .instances import construct_canonical, construct_feasible_bounded
def lhs_repair(random_state, lhs):
empty_columns = ((lhs != 0).sum(axis=0) == 0)
if empty_columns.any():
for column in np.where(empty_columns)[1]:
# Hacky, basically just adds a loose upper bound.
... | StarcoderdataPython |
22577 | """Test Predict API calls"""
import io
from PIL import Image
from dataclasses import dataclass
import tempfile
from pathlib import Path
import pytest
from mock import patch
from mldock.api.predict import send_image_jpeg, send_csv, send_json, handle_prediction
import responses
import requests
@pytest.fixture
def image... | StarcoderdataPython |
247269 | <gh_stars>0
"""Typing helpers to use throughout project.
All totally optional, of course.
"""
from typing import Union
import datetime
DTType = Union[datetime.datetime, datetime.date]
| StarcoderdataPython |
1656713 | #!/usr/bin/env python3
"""
Refactored version of Part 1a.
It turned out to be slow for Part 2.
"""
from collections import deque
from typing import Deque, List
class Rotator:
def __init__(self, digits: str) -> None:
self.d: Deque[int] = deque([int(x) for x in digits])
self.MIN = min(self.d)
... | StarcoderdataPython |
3275539 | <filename>wavespectra/construct/specconstruct.py
import os
import numpy as np
import xarray as xr
from wavespectra.core.attributes import attrs, set_spec_attributes
from wavespectra.specdataset import SpecDataset
def prepare_reconstruction(spec_info, base_dset=None):
""" Load parameters for spectral reconstruct... | StarcoderdataPython |
3540273 | <filename>code/4-ROC_PR_curve/calculate_roc.py
# Siamese Architecture for face recognition
import random
import numpy as np
import time
import tensorflow as tf
import math
import pdb
import sys
import os
import scipy.io as sio
from sklearn import *
import matplotlib.pyplot as plt
tf.app.flags.DEFINE_string(
'eval... | StarcoderdataPython |
3230527 | import os
import numpy as np
try:
import cv2
except ImportError:
cv2 = False
VIDEO_TYPES = ['.avi', '.mp4', ]
IMAGE_TYPES = ['.png', '.bmp', '.tiff', '.jpg', '.jpeg']
class FundusImageWithMetaData(object):
""" Class to hold the fundus image and any related metadata, and enable saving.
Attributes:
... | StarcoderdataPython |
3539028 | from django.http import HttpResponse
from django.shortcuts import render, redirect
from .forms import FormLinks
from .models import Links
from django.template import RequestContext
def home(request):
form = FormLinks()
status = request.GET.get('status')
return render(request, 'home.html', {'form': form, 's... | StarcoderdataPython |
60372 | import torch
import torch.nn as nn
class CNNLayer(nn.Module):
"""
This layer is callable for 1d convolution and pooling functions with fatten result
"""
def __init__(self,
input_dim,
kernel_size=(3, 4, 5),
kernel_num=200):
"""
:par... | StarcoderdataPython |
5014542 | # -*- coding: utf-8 -*-
import traceback
from .interface import uuid
class TopicUuid(uuid.CloudioUuid):
"""Topic based CloudioUuid (Universally Unique Identifier)
In the case of topic based MQTT communication the topic is used directly in order to identify objects
"""
def __init__(self, cloud_io_e... | StarcoderdataPython |
8087898 | <gh_stars>0
# Bienvenido a AiSaturdays Sevilla 2020!
# --------------------------------------
print("Hello world") | StarcoderdataPython |
5042300 | import discord
from discord.ext import commands
import json
import sys
import os
import time
from modules.log import log
import modules.activity as activity
from modules.misc import get_args
from modules.misc import is_owner
class Debug(commands.Cog):
def __init__(self, bot):
self.bot = bot
... | StarcoderdataPython |
4909349 | <filename>Tests/test_FramePcapAnalysis.py<gh_stars>0
class TestFramePcapAnalysis:
def test_show_frame(self):
assert False
| StarcoderdataPython |
5102768 | # coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen
https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.14.4
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
... | StarcoderdataPython |
22763 | """ Here all the blog's urls routes will be mapped """
from django.urls import path
from django.conf.urls import include, url
from . import views
app_name = 'core'
urlpatterns = [
# path('', views.home, name='home-page'),
url(r'^api/', include('apps.core.api.urls', namespace='api')),
]
| StarcoderdataPython |
37055 | <filename>YatzyPy/tests.py
# tests.py
from . main import Yatzy
def runTests():
c = Yatzy([5, 5, 6, 5, 6])
s = c.getScoreTable()
assert s['change'] == 27 and s['fullhouse'] == 27
assert s['double'] == 12 and s['six'] == 12
assert s['five'] == 15 and s['triple'] == 15
assert s['pair'] == 22
... | StarcoderdataPython |
5123879 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from swagger_spec_compatibility.spec_utils import load_spec_from_spec_dict
from swagger_spec_compatibility.walkers.response_paths import ResponsePathsWalker
def test_ResponsePa... | StarcoderdataPython |
1638564 | <reponame>filiparente/Predtweet<gh_stars>1-10
# 1) Reportar 6 métricas:
# MSE normal,
# RMSE normal,
# RMSE normalizado pela média das observações y,
# RMSE normalizado por ymax-ymin,
# RMSE normalizado pela std(y),
# RMSE normalizado pela diferença dos quantiles 0.75 e 0.25 de y,
# FFT
#
# ... | StarcoderdataPython |
5091873 | <filename>tests/cli/test_indirect.py<gh_stars>0
# -*- coding: utf-8 -*-
#
# Copyright 2019 - Swiss Data Science Center (SDSC)
# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and
# Eidgenössische Technische Hochschule Zürich (ETHZ).
#
# Licensed under the Apache License, Version 2.0 (the "License... | StarcoderdataPython |
4846810 | <reponame>kasohrab/robocup-software
import main
import robocup
import behavior
import constants
import enum
import math
import standard_play
import evaluation
from situations import Situation
import tactics.coordinated_pass
import skills.move
import skills.capture
import random
## Basic Offensive Pileup play
# Has on... | StarcoderdataPython |
8098335 | # -*- coding: utf-8 -*-
# pylint: disable=missing-docstring
import datetime as dti
import pytest # type: ignore
import nineties.parser as p
VALID_FUTURE_ISO = "3210-09-08T07:06:05.432"
VALID_FUTURE_ISO_CEST = VALID_FUTURE_ISO + "+0200"
VALID_FUTURE_ISO_CEST_COLON = VALID_FUTURE_ISO + "+02:00"
VALID_FUTURE_DT_UTC_FRO... | StarcoderdataPython |
5075988 | <filename>dbconn.py
from sqlalchemy import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import configparser
config = configparser.ConfigParser()
config.read("config.txt")
login_string = config.get("configuration", "password")
engine = create_engine(login_string, ech... | StarcoderdataPython |
1921167 | <gh_stars>0
L = int(input())
a, g = [int(x) for x in input().split()]
pa, pg = [float(x) for x in input().split()]
pa = L / (a / pa)
pg = L / (g / pg)
print(f'{pa:.2f}')
print(f'{pg:.2f}')
if pa < pg: print('Alcool')
elif pa > pg: print('Gasolina')
else: print('Indiferente')
| StarcoderdataPython |
9789254 | <reponame>tejas1995/nmtpytorch
import torch
class TFEmbedding(torch.nn.Embedding):
"""Position-aware embeddings for Transformer models.
Adapted from OpenNMT-py & original `Attention is all you need` paper.
"""
def __init__(self, num_embeddings, embedding_dim, max_len=1024, dropout=0.1):
self.... | StarcoderdataPython |
8310 | from logging import warning
from requests import get
from .info import Info
from .provider import Provider
from .providers import get_provider
class Parser:
def __init__(self, args: dict):
self.params = args
def init_provider(
self,
chapter_progress: callable = None,
... | StarcoderdataPython |
8140437 | <filename>Code/API/funibot_api/funiserial.py
from __future__ import annotations
from traceback import print_exc
from benedict import benedict
from json import JSONDecoder, JSONEncoder, JSONDecodeError
from enum import Enum
from typing import Union, Tuple, List, Optional
from funibot_api.funimock import IMockSerial
f... | StarcoderdataPython |
5063255 | import pyxel
import constants
from random import *
from enum import Enum
class GameStatus(Enum):
GAME = 0,
Main_UI =1
def define_sound():
pyxel.sound(0).set(
notes="c3e3g3c4c4", tones="s", volumes="4", effects=("n" * 4 + "f"), speed=7
)
pyxel.sound(1).set(
notes="f3 b... | StarcoderdataPython |
1699359 | from rest_framework import serializers
from apps.stt_tests.models import SttTest
class SttTestSerializer(serializers.ModelSerializer):
language = serializers.CharField(
source='language.code'
)
class Meta:
model = SttTest
fields = '__all__'
| StarcoderdataPython |
3245944 | import os
from pathlib import Path
import pytest
from s3fetch import __version__
from s3fetch.command import S3Fetch
from s3fetch.exceptions import DirectoryDoesNotExistError, NoObjectsFoundError
@pytest.fixture(scope="function")
def aws_credentials():
"""Mocked AWS Credentials for moto."""
os.environ["AWS_A... | StarcoderdataPython |
6517910 | from django.conf import settings
def global_settings(request):
return {
'OTP_PRIMARY_COLOR': settings.OTP_PRIMARY_COLOR,
'OTP_BACKGROUND_BTN': settings.OTP_BACKGROUND_BTN,
'OTP_BACKGROUND_BTN_HOVER': settings.OTP_BACKGROUND_BTN_HOVER,
'OTP_COLOR_TEXT_BTN': settings.OTP_COLOR_TEXT_B... | StarcoderdataPython |
5163061 | from math import ceil, floor
# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
BROWN = (95, 95, 0)
GRAY = (95, 95, 95)
WINDOW_WIDTH = 1024
WINDOW_HEIGHT = 768
# Time since last logic update
DELTATIME = 5 # In milliseconds; 5 ms = p... | StarcoderdataPython |
6657317 | #!/usr/bin/env python
import pdfminer.psparser as p
p.PSLiteral
p.PSLiteralTable.intern()
| StarcoderdataPython |
6511720 | __description__ = \
"""
Submodule with dialog boxes raised by main window.
"""
__author__ = "<NAME>"
__date__ = "2017-06-01"
from .aic_test import AICTest
from .documentation import Documentation
from .about import About
from .fit_options import FitOptions
from .add_experiment import AddExperiment
| StarcoderdataPython |
3469372 | <gh_stars>0
from flask import request
from flask_restful import Resource
# from app.components.process_ingestion_helper import process_ingestion_helper
from app.components.process_ingestion_voter import process_ingestion_voter
from app.components.process_compare_voter import process_compare_voter
from app.components.p... | StarcoderdataPython |
4994131 | import os
import zipfile
import rastervision as rv
from rastervision.utils.files import (download_if_needed, make_dir,
load_json_config, save_json_config)
from rastervision.protos.command_pb2 import CommandConfig as CommandConfigMsg
from rastervision.data.raster_source import Chan... | StarcoderdataPython |
8180240 | <filename>Data/ReplayScripts/rendering_attributes.py
import g
def init_scene():
g.set_duration(0)
g.set_dataset('Femur (Vis2021, Teaser)')
g.set_camera_checkpoint('TeaserA-2')
g.set_rendering_algorithm_settings({
'line_width': 0.005,
'band_width': 0.020,
'depth_cue_strength': 0.... | StarcoderdataPython |
66867 | <filename>cinder/tests/unit/volume/drivers/dell_emc/powermax/test_powermax_common.py<gh_stars>0
# Copyright (c) 2017-2019 Dell Inc. or its subsidiaries.
# 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... | StarcoderdataPython |
9705690 | from time import sleep
print('-=-=-=-= DESAFIO 99 -=-=-=-=')
print()
def maior(* num): # MINHA RESOLUÇÃO FOI COM TUPLA
print('-='*20)
print('Analisando os valores passados...')
maior = 0
for c, n in enumerate(num): # TUPLA
if c == 0 or n > maior:
maior = n
print(n, end=... | StarcoderdataPython |
6565576 | <reponame>crazbot/unet-gan-matting
import os
import cv2
import random
import numpy
import math
def image_fill(img, size, value):
border = [math.ceil((size[0] - img.shape[0])/2),
math.floor((size[0] - img.shape[0])/2),
math.ceil((size[1] - img.shape[1])/2),
math.floor((si... | StarcoderdataPython |
9772799 | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... | StarcoderdataPython |
1742166 | <reponame>grahamgower/demesdraw
"""
Add version string to the navbar and footer.
"""
import demesdraw
def inject_version(app, config):
v = demesdraw.__version__
if v != "undefined":
v_short = v.split("+")[0]
config.html_theme_options["extra_navbar"] = f"demesdraw {v_short}"
config.html... | StarcoderdataPython |
11219410 | <filename>server/app/services/tasks_scheduler/timer_tasks/app/api_count/sql_statements.py
api_hour_count_sql = """
INSERT INTO app_api_logs_hour("createAt", "countTime", "apiCount", "tenantID")
SELECT current_timestamp AS "createAt",
date_trunc('hour', current_timestamp - ... | StarcoderdataPython |
3216935 | print(ma<caret>) | StarcoderdataPython |
3286302 | <reponame>fuh/wechatpy
# -*- coding: utf-8 -*-
"""
wechatpy.exceptions
~~~~~~~~~~~~~~~~~~~~
Basic exceptions definition.
:copyright: (c) 2014 by messense.
:license: MIT, see LICENSE for more details.
"""
class WeChatException(Exception):
"""Base exception for wechatpy"""
def __init__(se... | StarcoderdataPython |
9671938 | <filename>experiments/ERA5/plot.py
try:
from mpl_toolkits.basemap import Basemap
except:
print('Install `basemap` library first!')
import glob
import pickle
import sys
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
def output_preprocessor(
mdl_list=['Rid... | StarcoderdataPython |
1813733 | # from app.models.db import db, migrate
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
db = SQLAlchemy()
migrate = Migrate()
from app.models.fact import Fact
from app.models.user import User | StarcoderdataPython |
105481 | #! /usr/bin/env python3
# coding: utf-8
# modified example from https://weatherstack.com/documentation
import requests, hvac, getpass
# sets up the vault client, prompts for creds, and gather's the data
client = hvac.Client(url='http://localhost:8200')
client.auth.userpass.login(input("username: "), getpass.getpass(pr... | StarcoderdataPython |
3287739 | from django import forms
from spark.articles.models import Article
class ArticleForm(forms.ModelForm):
status = forms.CharField(widget=forms.HiddenInput())
title = forms.CharField(
widget=forms.TextInput(attrs={'class': 'form-control'}),
max_length=255)
content = forms.CharField(
... | StarcoderdataPython |
11293500 | <gh_stars>1-10
from .stop_words import STOP_WORDS
from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
from .punctuation import TOKENIZER_PREFIXES, TOKENIZER_INFIXES
from ...language import Language
class ItalianDefaults(Language.Defaults):
tokenizer_exceptions = TOKENIZER_EXCEPTIONS
stop_words = STOP_WORDS... | StarcoderdataPython |
5111111 | <reponame>hixio-mh/plugin-python
a = 12
b = 14
a, b = b, a
a = b, c = 1, 2
a = b = 1, 2
new_file_name = file_name[:-6] + extension
| StarcoderdataPython |
6662209 | <reponame>christiansteinert/tibetan-dictionary
#!/usr/bin/env python3
import sys, re
def getAlternativeValue(value):
value = re.sub(r"\b1\b","one",value)
value = re.sub(r"\b2\b","two",value)
value = re.sub(r"\b3\b","three",value)
value = re.sub(r"\b4\b","four",value)
value = re.sub(r"\b5\b","five"... | StarcoderdataPython |
1828924 | #!/usr/bin/env python
'''Base class for layout tests.
'''
__docformat__ = 'restructuredtext'
__version__ = '$Id: $'
import unittest
import sys
from pyglet.gl import *
from layout import *
from pyglet.window import *
from pyglet.window.event import *
class LayoutTestBase(unittest.TestCase):
# Supply either XHTM... | StarcoderdataPython |
9652295 | # -*- coding: utf-8 -*-
from nose.tools import eq_
from anytree import Node
from anytree.util import commonancestors
from anytree.util import leftsibling
from anytree.util import rightsibling
def test_commonancestors():
"""commonancestors."""
udo = Node("Udo")
marc = Node("Marc", parent=udo)
lian = N... | StarcoderdataPython |
3458784 | from typing import Generator
from fastapi import Depends, HTTPException, Security, status
from fastapi.security import OAuth2PasswordBearer
from fastapi.security.api_key import APIKeyCookie, APIKeyHeader, APIKeyQuery
from jose import JWTError, jwt
from sqlalchemy.orm import Session
from starlette.status import HTTP_40... | StarcoderdataPython |
12802869 | """
The main entry point for the web server
"""
from aiohttp import web
import time
import base64
from cryptography import fernet
from aiohttp_session import setup, get_session
from aiohttp_session.cookie_storage import EncryptedCookieStorage
import quakes
import db
import auth
import game
import configparser
routes ... | StarcoderdataPython |
3307461 | <reponame>johnstcn/whatsnew
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login
from django.db.models.aggregates import Max
from django.http import HttpResponseRedirect
from django.shortcuts import redirect
from django.views i... | StarcoderdataPython |
11274216 | # Copyright (c) 2021 Qianyun, Inc. All rights reserved.
from cloudify import ctx
from . import constants
from abstract_plugin.platforms.common.base import CommonResource
class CommonEip(CommonResource):
@staticmethod
def get_related_vm():
relationships = ctx.instance.relationships
for relati... | StarcoderdataPython |
1685245 | """
Matplotlib draw methods for TGraph
The plot and errorbar methods are available.
When used through the decorators with mplbplot.plot (recommended),
the methods will be called rplot and rerrorbar,
and the full documentation is available through
TGraph.__plot__ and TGraph.__errorbar__.
"""
__all__ = ("plot", "errorba... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.