id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
4832939 | <filename>Inverted_Pendulum/fuzzy/Rule.py
# -*- coding: utf-8 -*-
#
# Copyright (C) 2009 <NAME>
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 3 of the License, or (at... | StarcoderdataPython |
1680456 | <gh_stars>1-10
import tensorflow as tf
import numpy as np
def weightVariable(shape, trainable=True):
# initial = tf.truncated_normal(shape, stddev=0.1, name='weights')
# return tf.Variable(initial)
return tf.get_variable('weights', shape=shape, initializer=tf.contrib.layers.xavier_initializer(), trainable=trainab... | StarcoderdataPython |
4828654 | <filename>core/urls.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from rest_framework_simplejwt import views as jwt_views
from Todo.views import TodoViewSet
from . import views
# set up router and register the viewsets; does URL binding automatically
router = Defa... | StarcoderdataPython |
3329858 | <filename>py1.py
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 23 12:41:13 2021
@author: Windows
"""
F = [[1,1],[1,0]]
T = [[1,2],[3,4]]
def copy(A, B): #copies matrix B into matrix A. Matrixes must be 2 by 2.
A[0][0] = B[0][0]
A[0][1] = B[0][1]
A[1][0] = B[1][0]
A[1][1] = B[1... | StarcoderdataPython |
183807 | from GoProCamera import GoProCamera
import time, datetime
import configparser
import logging
from subprocess import call
# Logging
#logging.basicConfig(filename="GoProTimelapse.log", level=logging.DEBUG, format='%(asctime)s %(message)s')
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(message)s')
# Get... | StarcoderdataPython |
147359 | <gh_stars>0
#!/usr/bin/env python
#
# This library is free software, distributed under the terms of
# the GNU Lesser General Public License Version 3, or any later version.
# See the COPYING file included in this archive
import hashlib
import unittest
import struct
import lbrynet.dht.node
import lbrynet.dht.constants... | StarcoderdataPython |
43020 | <reponame>lvayssac/bioptim<gh_stars>0
"""
The first part of this example of a single shooting simulation from initial guesses.
It is NOT an optimal control program. It is merely the simulation of values, that is applying the dynamics.
The main goal of this kind of simulation is to get a sens of the initial guesses pass... | StarcoderdataPython |
91182 | <gh_stars>0
from .ImageEnhancer import ImageEnhancer
import io
import base64
class EnhanceEncoder:
def __init__(self, image_path: str):
self.enhancer = ImageEnhancer(image_path)
def Encode(self, param):
image = self.enhancer.enhance(param)
output = io.BytesIO()
image.save(out... | StarcoderdataPython |
4842350 | <gh_stars>0
from qiwi_handler.types.transaction.sum import Sum
from qiwi_handler.types.transaction.commission import Commission
from qiwi_handler.types.transaction.total import Total
from qiwi_handler.types.transaction.provider import Provider
from qiwi_handler.types.transaction.source import Source
from qiwi_handler.t... | StarcoderdataPython |
155460 | import tensorflow as tf
def minibatch_std(input_tensor, epsilon=1e-8):
n, h, w, c = tf.shape(input_tensor)
group_size = tf.minimum(4, n)
x = tf.reshape(input_tensor, [group_size, -1, h, w, c])
group_mean, group_var = tf.nn.moments(x, axes=(0), keepdims=False)
group_std = tf.sqrt(group_var + epsilon... | StarcoderdataPython |
3378064 | <reponame>rojithakamal/functions<filename>scripts/tutorial_shift_calendar.py
import json
import logging
from sqlalchemy import Column, Integer, String, Float, DateTime, Boolean, func
from iotfunctions import bif
from iotfunctions.metadata import EntityType
from iotfunctions.db import Database
from iotfunctions.enginelo... | StarcoderdataPython |
4802631 | """
Django settings for scaffold project.
Generated by 'django-admin startproject' using Django 2.2.1.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
i... | StarcoderdataPython |
4810467 | import pytest
from prisma import Client, errors
@pytest.mark.asyncio
async def test_catches_not_connected() -> None:
"""Trying to make a query before connecting raises an error"""
client = Client()
with pytest.raises(errors.ClientNotConnectedError) as exc:
await client.post.delete_many()
asse... | StarcoderdataPython |
161106 | <reponame>kolonialno/django-migrations-checker
"""
A super simple API client for the Github API.
"""
import json
from dataclasses import dataclass
from http.client import HTTPResponse
from typing import Any
from urllib.parse import urljoin
from urllib.request import Request, urlopen
@dataclass
class Comment:
id: ... | StarcoderdataPython |
65471 | <reponame>LandRegistry/maintain-frontend
from maintain_frontend import main
from flask import url_for
from flask_testing import TestCase
from unit_tests.utilities import Utilities
from unittest.mock import patch, call
from maintain_frontend.dependencies.session_api.session import Session
from maintain_frontend.constant... | StarcoderdataPython |
1671683 | <reponame>christopherthompson81/fastapi_demo<gh_stars>1-10
'''
FastAPI Demo
/token router
'''
# Standard Imports
from datetime import timedelta
# PyPi Imports
from fastapi import APIRouter, Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
import jwt
from sqlalchemy.o... | StarcoderdataPython |
3374845 | <filename>users/urls.py<gh_stars>1-10
from django.urls import path # path is a relative path to create a route
from django.conf import settings
from django.conf.urls.static import static # static provides a file static to me
from django.conf.urls import url
from users import views
app_name = "users"
urlpatterns = [
... | StarcoderdataPython |
8882 | <gh_stars>10-100
#!/usr/bin/env python
# encoding: utf-8
"""
script to install all the necessary things
for working on a linux machine with nothing
Installing minimum dependencies
"""
import sys
import os
import logging
import subprocess
import xml.etree.ElementTree as ElementTree
import xml.dom.minidom as minidom
imp... | StarcoderdataPython |
7115 | <gh_stars>0
name = "cluster"
num_cores = 1000
GENERAL_PARTITIONS = ["regular"]
GPU_PARTITIONS = ["gpu"]
PARTITIONS = GENERAL_PARTITIONS + GPU_PARTITIONS
ACTIVE_JOB_STATES = ["RUNNING", "COMPLETING"]
FINISHED_JOB_STATES = ["COMPLETED", "NODE_FAIL", "TIMEOUT", "FAILED", "CANCELLED"]
JOB_STATES = ACTIVE_JOB_STATES + F... | StarcoderdataPython |
1788663 | <filename>views/forms.py
from wtforms import StringField, SubmitField, PasswordField, BooleanField
from wtforms.validators import DataRequired, EqualTo
from flask_wtf import FlaskForm
### REGISTRATION/LOGIN HANDLING ###
class SignupForm(FlaskForm):
password = PasswordField("Password", validators=[DataRequired(), ... | StarcoderdataPython |
85318 | <reponame>isaacizey/Questioner-endpoints<filename>app/api/v2/models/questions_models.py
import datetime
from datetime import datetime as dt
import app.db_connect as connection
import psycopg2 as psycopg
from flask import jsonify
db_conn = connection.get_connection()
db_cursor = db_conn.cursor()
class QuestionsModel()... | StarcoderdataPython |
1799158 | import logging
import random
from django.conf import settings
from django.shortcuts import render
from spid_cie_oidc.entity.models import TrustChain
logger = logging.getLogger(__name__)
def oidc_rp_landing(request):
trust_chains = TrustChain.objects.filter(
metadata__openid_provider__isnull=False,
... | StarcoderdataPython |
4837154 | <gh_stars>0
frase = str(input('Digite uma frase: ')).strip().upper()
palavrasSeparadas = frase.split()
junto = ''.join(palavrasSeparadas)
inverso = junto[::-1]
print(junto, inverso)
if junto == inverso:
print('Sim, é um palíndromo')
else:
print('Não é um palíndromo')
| StarcoderdataPython |
175712 | """
Core views
"""
from celery.app import shared_task
from drf_spectacular.utils import extend_schema
from rest_framework import mixins, generics, status
from rest_framework.response import Response
from .serializers import (
JobSerializer,
KeywordSearchSerializer,
URLSearchSerializer,
TagSearchSeriali... | StarcoderdataPython |
1750160 | <reponame>statropy/pigweed<filename>pw_env_setup/py/pw_env_setup/cargo_setup/__init__.py<gh_stars>10-100
# Copyright 2020 The Pigweed 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
#... | StarcoderdataPython |
3303084 | <gh_stars>1-10
import unittest, scarf
class TestScarfMethods(unittest.TestCase):
def test_replaceRepStr(self):
self.assertEqual(scarf.replaceRepStr("K the pattern, rep from *", 5), "K the pattern, rep from * (5) times")
def test_getLargest(self):
self.assertEqual(scarf.getLargest([1,2,3]), 3)... | StarcoderdataPython |
185848 | import pytest # noqa
from za_id_number.za_id_number import SouthAfricanIdentityValidate
import datetime
from za_id_number.constants import LIB_DATE_FORMAT
from dateutil.relativedelta import relativedelta
from dataclasses import dataclass
@dataclass
class DateTimeTest:
"""Class for keeping track of an item in in... | StarcoderdataPython |
1739637 | <reponame>xuhangc/shadow
import os
import random
import time
import numpy as np
import cv2
import torch
import torch.optim as optim
from torch.utils.data import DataLoader
from tqdm import tqdm
from warmup_scheduler import GradualWarmupScheduler
import utils
from config import Config
from data import get_training_dat... | StarcoderdataPython |
3208656 | from flask import Blueprint
efrain = Blueprint('efrain',__name__, template_folder='templates')
from . import routes | StarcoderdataPython |
73247 | <reponame>fredstro/sage
r"""
Set of homomorphisms
"""
#*****************************************************************************
# Copyright (C) 2014 <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
#
# Distributed under the terms of the GNU General Public License (GPL)
# as published by the Free Software Fo... | StarcoderdataPython |
1768603 | from setuptools import setup
setup(
name="ssoconnector",
install_requires=[
"PyJWT >= 2.3.0",
"requests >= 2.27.1"
],
)
| StarcoderdataPython |
3294772 | <filename>dotnet/providers.bzl<gh_stars>0
DotnetPublishInfo = provider(
fields = {
"launcher": "The generated launcher file that invokes dotnet via PATH or via DOTNET_CLI_HOME",
"launcher_windows": "The generated launcher.exe file for windows that invokes dotnet via PATH or via DOTNET_CLI_HOME",
... | StarcoderdataPython |
4821335 | <reponame>jordanemedlock/psychtruths<filename>temboo/core/Library/Facebook/Actions/Video/WantsToWatch/UpdateWantsToWatch.py
# -*- coding: utf-8 -*-
###############################################################################
#
# UpdateWantsToWatch
# Updates an existing wants_to_watch action.
#
# Python versions 2.6... | StarcoderdataPython |
3324547 | from typing import Union
from scipy.spatial.distance import pdist
from UQpy.utilities import NumpyFloatArray
from UQpy.utilities.distances.baseclass.EuclideanDistance import EuclideanDistance
class L2Distance(EuclideanDistance):
def compute_distance(self, xi: NumpyFloatArray, xj: NumpyFloatArray) -> float:
... | StarcoderdataPython |
3361948 | <reponame>nikon-petr/tcp-zip-server
if __name__ == '__main__':
from client.client_ui import start_ui
start_ui()
| StarcoderdataPython |
57473 | import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import collections
import os
def Clear_Empty_Lines(text):
# Read lines as a list
fh = open(text, "r")
lines = fh.readlines()
fh.close()
# Clear empty lines
lines = filter(lambda x: not x... | StarcoderdataPython |
14529 | # -*- coding: utf-8 -*-
"""
Authors: <NAME>
UNESCO-IHE 2017
Contact: <EMAIL>
Repository: https://github.com/wateraccounting/wa
Module: Generator/Sheet3
"""
import os
def Create(Dir_Basin, Basin, Simulation, Dir_Basin_CSV_a, Dir_Basin_CSV_b):
"""
This functions create the monthly and yearly sheet 3 in ... | StarcoderdataPython |
154919 | <reponame>risklayer/corona-landkreis-crawler<filename>nrw/siegen.py<gh_stars>10-100
#!/usr/bin/python3
from botbase import *
_siegen_c = re.compile(r"insgesamt ([0-9.]+) Personen aus Siegen-Wittgenstein mit dem Coronavirus")
_siegen_cc = re.compile(r"([0-9.]+|\w+) neue Coronafälle")
_siegen_d = re.compile(r", ([0-9.]+... | StarcoderdataPython |
165785 | # Generated by Django 2.2.6 on 2019-10-24 15:23
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('data_core', '0006_file_m... | StarcoderdataPython |
122808 | <reponame>drewheathens/The-Moringa-Tribune
"""test import from a builtin module"""
from __future__ import absolute_import
from math import log10
__revision__ = None
def log10_2():
"""bla bla bla"""
return log10(2)
| StarcoderdataPython |
3265188 | <reponame>yurigalindo/FourierHeatmap
import logging
from typing import Dict, List, Tuple
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from .fourier.heatmap import eval_fourier_heatmap # noqa
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
def calc_errors(... | StarcoderdataPython |
1611491 | from dateutil.parser import parse
from dateutil.relativedelta import *
from datetime import *
def parse_date(date_string):
return parse(date_string)
def __check_date__(date_string):
try:
parse_date(date_string)
return True
except ValueError:
return False
def get_date_delta(date... | StarcoderdataPython |
187837 | <reponame>IsakJones/space_invaders
"""
DOCSTRING
Contains main initializing variables as constants.
Changing initializing variables for testing should be done here.
While verbose, the python enum syntax supports the project's
overarching object-oriented approach and keeps all variables
in one single module.
Enum bu... | StarcoderdataPython |
169958 | <reponame>sirdodger/acstat
#!/usr/bin/env python3
"""Tiles that comprise a ship.
"""
import utils
from .tile import Tile
from .tile_cannon import CannonTile
from .tile_cargo import CargoTile
from .tile_cloak import CloakingTile
from .tile_engine import EngineTile
from .tile_helm import HelmTile
from .tile_hyperdriv... | StarcoderdataPython |
153820 | <reponame>NeQuissimus/nix-home<gh_stars>1-10
import json
import sys
import os
f = open(sys.argv[1])
out = sys.argv[2]
data = json.load(f)
for key in data["files"]:
val = data["files"][key]
try:
os.makedirs(out + "/" + os.path.dirname(key))
except:
print "ignoring error"
if type(val) =... | StarcoderdataPython |
56876 | <filename>linux/bin/hex2bin.py<gh_stars>1-10
#!/usr/bin/env python3
import binascii
import sys
hex_bytes = sys.stdin.buffer.read()
hex_bytes_clean = ''.join(str(hex_bytes, encoding='UTF8').split())
raw_bytes = binascii.a2b_hex(hex_bytes_clean)
sys.stdout.buffer.write(raw_bytes)
| StarcoderdataPython |
72167 | import json
import sqlite3
from scrapekit.logs import log_path
conn = sqlite3.connect(':memory:')
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
def log_parse(scraper):
path = log_path(scraper)
with open(path, 'r') as... | StarcoderdataPython |
19096 | <filename>funing/_ui/about.py
import gettext
import os
import re
import subprocess
import sys
import time
import tkinter as tk
import tkinter.filedialog as tkf
import uuid
import webbrowser
from datetime import date, datetime
from enum import Enum
from tkinter import *
from tkinter import messagebox
from tkinter.ttk i... | StarcoderdataPython |
1662711 | <reponame>Mjusick/rest-api-introduction-app
import random
from string import ascii_letters
from string import punctuation
def __generate_random_secret(k: int = 10):
"""
:param k: integer depicting number of character in string
:return: string of length k with ascii letters, punctuation and numbers
""... | StarcoderdataPython |
1783557 | <reponame>zjpjack/azure-cli
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# ----------------------------------------... | StarcoderdataPython |
3266957 | import matplotlib.pyplot as plt
import numpy as np
# parameterized layer architecture
layer_func = lambda x, A,w: (A*np.cos(w*np.linspace(0,np.pi/2,x))).astype(int)
if __name__ == "__main__":
cm = plt.cm.get_cmap('jet')
f,ax = plt.subplots(1)
for i in range(50):
sizes = layer_func(
np.... | StarcoderdataPython |
1698576 | # Copyright 2016 Ifwe 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 agreed to in writing, so... | StarcoderdataPython |
142838 | from __future__ import absolute_import, unicode_literals
import sys
import django
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from debug_toolbar.compat import import_string
from debug_toolbar.panels import Panel
class VersionsPanel(Panel):
"""
Shows versions of ... | StarcoderdataPython |
97079 | from sklearn.base import BaseEstimator, TransformerMixin
import pandas as pd
import numpy as np
class Interactions(BaseEstimator, TransformerMixin):
"""Feature creation based on existing categorical variables, interactions between them
Args:
scheme_management_payment (bool): if True creates featu... | StarcoderdataPython |
3246104 | <filename>navigation.py
"""
The main class for the yoshi vector. The elementary logic is implemented here,
while most utility functions are located in support.py
"""
import anki_vector
from support import *
import support
from anki_vector.util import degrees, distance_mm, speed_mmps
from anki_vector.connection impo... | StarcoderdataPython |
101398 | """Common testing word list."""
# word list Breakdown
# 1: a (1)
# 2: go. no, be, by (4)
# 3: cry, fun, run, for (4)
# 4: demo, foul, wait, sell (4)
# 5: yeast, wrong, water, skill (4)
# 6: accept, admire, bicorn, biceps, planks (5)
# 7: bizonal, biofuel, bigfoot, scalene (4)
# 8: mobility, notebook, superior, taxpaye... | StarcoderdataPython |
1734161 | <filename>lofi/optimizers/OPLES.py
from .optimizer import Optimizer, Options, cluster, np
class OPLES_options(Options):
def __init__(self):
super().__init__()
self.n = 40 # population size
self.max_sigma = 1e-1 # max sampling deviation
self.min_sigma = 1e-8 ... | StarcoderdataPython |
3078 | #!/usr/bin/python
import random
count = 20
test_set = []
while count:
a = random.randrange(3,20)
b = random.randrange(3,20)
if a > b and a - b > 1:
if (b, a-b) not in test_set:
test_set.append((b, a-b))
count -= 1
elif b > a and b - a > 1:
if (a, b-a) not in te... | StarcoderdataPython |
1786307 | """
Faster R-CNN with Normalized Wasserstein Assigner
Average Precision (AP) @[ IoU=0.50:0.95 | area= all | maxDets=1500 ] = 0.134
Average Precision (AP) @[ IoU=0.25 | area= all | maxDets=1500 ] = -1.000
Average Precision (AP) @[ IoU=0.50 | area= all | maxDets=1500 ] = 0.356
Average Precision (AP) @... | StarcoderdataPython |
4803728 | from ggmodel_dev.projection import *
from ggmodel_dev.models.landuse.BE2 import model_dictionnary
MODEL = model_dictionnary['BE2_model']
PROJECTION_DICT = {
'FDi': lambda x: apply_itemized_ffill_projection(x, min_year=2018),
'SSRi': lambda x: apply_itemized_ffill_projection(x, min_year=2018),
'SVi': lamb... | StarcoderdataPython |
3248252 | <gh_stars>0
import re
import nltk
import requests
import validators
from bs4 import BeautifulSoup
from nltk.stem.wordnet import WordNetLemmatizer
from nltk.tokenize import RegexpTokenizer
from pymystem3 import Mystem
from telegram.ext import Updater, Filters, MessageHandler
from common import config, logger
# lang n... | StarcoderdataPython |
3397484 | #! /usr/bin/env python
from enum import Enum
class RobotState(Enum):
PENDING = 1
RECEIVED = 2
ACTIVE = 3
PREEMPTED = 4
SUCCEEDED = 5
FAILED = 6
ABORTED = 7
| StarcoderdataPython |
4835142 | <gh_stars>10-100
# -*- coding: utf-8 -*-
"""
Ensures that the netstring example Protocol and Connector class implementations
work as expected.
"""
from drogulus.net.netstring import (NetstringProtocol, NetstringConnector,
LENGTH)
from drogulus.dht.messages import OK, to_dict, from_di... | StarcoderdataPython |
3213533 | """
Demo Flask application to test the operation of Flask with socket.io
Aim is to create a webpage that is constantly updated with random numbers from a background python process.
30th May 2014
===================
Updated 13th April 2018
+ Upgraded code to Python 3
+ Used Python3 SocketIO implementation
+ Updated... | StarcoderdataPython |
1759032 | <reponame>modwizcode/luna
#
# This file is part of LUNA.
#
# Copyright (c) 2020 Great Scott Gadgets <<EMAIL>>
# SPDX-License-Identifier: BSD-3-Clause
""" fomu Platform definitions.
This is a non-core platform. To use it, you'll need to set your LUNA_PLATFORM variable:
> export LUNA_PLATFORM="luna.gateware.platfo... | StarcoderdataPython |
3313939 | <gh_stars>1-10
print('O dolar custa 3.75')
dinheiro = float(input('Quanto voçê tem em dinheiro? R$'))
converssão = dinheiro/3.75
print('A quantidade de US$ que voce pode comprar com R${} é esta {:.2f}'.format(dinheiro, converssão))
| StarcoderdataPython |
3279055 | <gh_stars>10-100
# edit-mode: -*- python -*-
import paddle.v2 as paddle
#from config.test_conf import cfg
from config.pascal_voc_conf import cfg
def net_conf(mode, scale=1.0):
"""Network configuration. Total three modes included 'train' 'eval'
and 'infer'. Loss and mAP evaluation layer will return if using 't... | StarcoderdataPython |
154396 | """
parseando arquivo html
retornando texto
parser padrão
"""
# importando modulo BeautifulSoup do pacote bs4
from bs4 import BeautifulSoup
# abrir arquivo para leitura
with open('arquivo01.html','r') as f:
soup = BeautifulSoup(f, 'html5lib')
# transforma em uma string bem formatada
#print(soup.prettify())
# ret... | StarcoderdataPython |
142637 | from torch import nn
__all__ = ['Identity']
class Identity(nn.Module):
"""The most useful module. A pass-through module which does nothing."""
def __init__(self, *args, **kwargs):
super().__init__()
def forward(self, x):
return x
| StarcoderdataPython |
4818150 | '''
* Copyright 2018 Canaan 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 agreed to... | StarcoderdataPython |
3252312 | """
Functions to construct Transformer based models.
"""
import tensorflow as tf
# pylint: disable=no-name-in-module
from tensorflow.keras.layers import Dense, MultiHeadAttention, TimeDistributed
from vlne.consts import DEF_MASK
from .funcs import (
get_inputs, get_outputs, modify_series_layer, add_hidden_layers... | StarcoderdataPython |
1616467 | #!/usr/bin/env python
######################################################################
# @author : <NAME> (linusfernandes at gmail dot com)
# @file : primes
# @created : Sunday Sep 19, 2021 19:07:50 IST
# @description :
# -*- coding: utf-8 -*-'
###################################################... | StarcoderdataPython |
131908 | <reponame>jgabriel1607/Python<filename>ex060.py
print('Vamos realizar o fatorial: ')
n = int(input('Digite um número inteiro: '))
c = n
f = 1
print('{}! = '.format(n), end=' ')
while c > 0:
print(c, end=' ')
print(' x ' if c > 1 else ' = ', end=' ')
f *= c
c -= 1
print(f)
print('FIM!')
| StarcoderdataPython |
3311764 | <reponame>homdx/sadpandareader
from kivy.app import App
from kivymd.navigationdrawer import MDNavigationDrawer
from kivymd.navigationdrawer import NavigationLayout
from kivymd.navigationdrawer import NavigationDrawerIconButton
from kivy.lang import Builder
from kivy.clock import Clock
Builder.load_file("kv/navdrawer.k... | StarcoderdataPython |
1725647 | from requests.auth import AuthBase
import os
class BearerAuth(AuthBase):
"""
This class is responsible for authenticating
request using bearer token
"""
def __init__(self, path_to_token_file):
self.path_to_token_file = path_to_token_file
self._assert_token_file_valid()
def __c... | StarcoderdataPython |
1714178 | print('-='*10)
print('MEDIDOR DE VELOCIDADE')
print('-='*10)
sua_velocidade = float(input('Digite a velocidade que você estava: '))
multa = (sua_velocidade - 80) * 7
velocidade_acima = sua_velocidade - 80
if sua_velocidade > 80:
print(f'Limite de velocidade é de 80km\n'
f'Você passou há {velocidade_acima}... | StarcoderdataPython |
136630 | <filename>TrendOfPositiveCases.py
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from scipy.signal import savgol_filter
days_omitted = 8
trend_data = 50
df = pd.read_csv("CovidDataset.csv")
#all_cities = set(list(df["Reporting_PHU_C... | StarcoderdataPython |
3351028 | <filename>k_notify/__init__.py
from TwilioSMSCallback import TwilioSMSCallback
| StarcoderdataPython |
1746635 | import cairo
from src.elements.primitives.object import Object
from src.elements.properties.point import Point
class Line(Object):
__name__ = "Line"
def __init__(self):
Object.__init__(self)
self.handler.is_line = True
self.start_point = Point()
self.end_point = Point()
... | StarcoderdataPython |
1738327 | """ Multicast DNS Service Discovery for Python, v0.14-wmcbrine
Copyright 2003 <NAME>, 2014 <NAME>
This module provides a framework for the use of DNS Service Discovery
using IP multicast.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser Gene... | StarcoderdataPython |
1659727 | import logging
import json
import codecs
import sys
import os
import re
import itertools
import warnings
from instagram_private_api.compat import compat_urllib_request
class TerminalColors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
END... | StarcoderdataPython |
1739318 | <filename>bnb/track/utils.py
import inspect
from attr import asdict
from attr.exceptions import NotAnAttrsClassError
class States:
OK = 'OK'
UNK = 'UNK'
FAIL = 'FAIL'
DEAD = 'DEAD'
SIGINT = 'SIGINT'
RUNNING = 'RUNNING'
PRE_DISPATCH = 'P... | StarcoderdataPython |
1615700 | class Solution:
def numDistinct(self, s: str, t: str) -> int:
m = len(s)
n = len(t)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
dp[i][0] = 1
for i in range(1, m + 1):
for j in range(1, n + 1):
if s[i - 1] == t[j - 1]:
dp[i][j] = dp[i - 1][j - 1... | StarcoderdataPython |
3299478 | from unittest import TestCase
import zeeguu
class LanguageTest(TestCase):
def test_languages_exists(self):
zeeguu.log("tüst")
| StarcoderdataPython |
1754194 | # coding: utf-8
from redis import Redis
class RedisManager(object):
KEY_PREFIX = "GoodsGetter"
def __init__(self):
self.redis_instance = Redis(host="redismaster", port=6379)
def _generate_key(self, *args):
key_part = "-".join([str(item) for item in args])
return "-".join([self.KE... | StarcoderdataPython |
1760905 | <reponame>aaaimx/covid19-assistant-api
# First steps with Django
# https://docs.celeryproject.org/en/latest/django/first-steps-with-django.html
from __future__ import absolute_import
from django.conf import settings
import os
from celery import Celery
# set the default Django settings module for the 'celery' program.... | StarcoderdataPython |
98807 | #create function
import pandas as pd
from os.path import dirname,join
from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np
import re
from sklearn.metrics.pairwise import cosine_similarity
filename = join(dirname(__file__),"pre_darktour.csv")# csv 읽어오기
ai_process = pd.read_csv(filename)
pre... | StarcoderdataPython |
3251269 | <filename>op3/envs/blocks/mujoco/block_occlusions.py
import os
import pdb
import numpy as np
import shutil
import pickle
import cv2
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from argparse import ArgumentParser
import op3.envs.blocks.mujoco.utils.data_generation_utils as dgu
from op3.util.... | StarcoderdataPython |
3382191 | <reponame>gothedistance/python-book
if 3 > 1:
print('Hello,Python!')
| StarcoderdataPython |
50022 | #!/usr/bin/env python
from __future__ import division, unicode_literals
import argparse
import os
import time
import cv2
from net.wyun.blankanswer import image_utils
from net.wyun.blankanswer.loader import SimplePreprocessor
default_buckets = '[[240,100], [320,80], [400,80],[400,100], [480,80], [480,100], [560,80],... | StarcoderdataPython |
3221551 | #!/usr/bin/env python
#----------------------------------------------------------------------------
#
# TSDuck sample Python application running a chain of plugins:
# Filter tables using plugin events to get binary tables in a Python class.
#
# See sample-filter-tables-log.py for an equivalent example using log lines
#... | StarcoderdataPython |
78528 | """
Util files for TorchServe
"""
import inspect
import os
import json
import itertools
import logging
logger = logging.getLogger(__name__)
def list_classes_from_module(module, parent_class=None):
"""
Parse user defined module to get all model service classes in it.
:param module:
:param parent_class... | StarcoderdataPython |
86094 | """
Window [DiamondQuest]
Handles the game window and caches primary surfaces.
Author(s): <NAME>, <NAME>, <NAME>
"""
# LICENSE (BSD-3-Clause)
# Copyright (c) 2020 MousePaw Media.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that ... | StarcoderdataPython |
1761713 | <filename>src/plotter/settings.py
from pathlib import Path
AUTO_SCALE = True
OUTPUT_PATH = Path("../img")
BACKGROUND = 'black'
MIDDLEGROUND = 'gray'
FOREGROUND = 'white'
TITLE_SIZE = 16
LABEL_SIZE = TITLE_SIZE - 3
COLORS = [
'#e6194b',
'#3cb44b',
'#ffe119',
'#4363d8',
'#f58231',
'#911eb4',... | StarcoderdataPython |
136767 | <gh_stars>100-1000
from ctypes import *
import subprocess
from os.path import isfile
'''
This file contains the definitions used by HackRF one, e.g. library path or constants.
'''
HACKRFLIB_AVAILABLE = False
# Autofind the path of libhackrf.so
possiblePaths = [
"/usr/local/lib/libhackrf.so",
"/usr/lib/x86_64-linux-... | StarcoderdataPython |
1683008 | # -*- coding: utf-8 -*-
"""
utils.tool
~~~~~~~~~~
Some tool classes and functions.
:copyright: (c) 2019 by staugur.
:license: BSD 3-Clause, see LICENSE for more details.
"""
import re
import sys
import hmac
import hashlib
import requests
import smtplib
import semver
from uuid import uuid4
from ti... | StarcoderdataPython |
81849 | """
PyMap3D provides coordinate transforms and geodesy functions with a similar API
to the Matlab Mapping Toolbox, but was of course independently derived.
For all functions, the default units are:
distance : float
METERS
angles : float
DEGREES
time : datetime.datetime
UTC time of observation
These funct... | StarcoderdataPython |
8374 | <filename>cats/types.py
from pathlib import Path
from types import GeneratorType
from typing import AsyncIterable, Iterable, TypeAlias
import ujson
from cats.errors import MalformedHeadersError
try:
from django.db.models import QuerySet, Model
except ImportError:
QuerySet = type('QuerySet', (list,), {})
... | StarcoderdataPython |
3265535 | # Code to train a word2vec model with gensim
# For use with ml5.js word2vec examples
import re
import json
import sys
import argparse
import glob
import os
from collections import Counter
from gensim.models import Word2Vec
import nltk
#Parsing for the user arguments
parser = argparse.ArgumentParser(description="Text... | StarcoderdataPython |
143701 | # -*- coding: utf-8 -*-
"""Testing the assembly of information from ld.dicts"""
import unittest
import os
os.environ["TESTING_LDT"] = "TRUE"
import ldt
from ldt.helpers.ignore import ignore_warnings
class Tests(unittest.TestCase):
"""
The tests in this block inspect the loading of all the information from
... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.