id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
9764686 | # https://www.reddit.com/r/dailyprogrammer/comments/3jn6te/20150903_challenge_230_hard_logo/
import os
import sys
fullwords = {}
X = None
Y = None
grid = None
res = None
def deletechar(ori, x, y):
if ori == 0:
if ((y > 0 and grid[y-1][x] != ' ') or
(y < Y-1 and grid[y+1][x] != ' ')):
... | StarcoderdataPython |
9799409 | <gh_stars>0
# Add this project to the path
import os; import sys; currDir = os.path.dirname(os.path.realpath("__file__"))
rootDir = os.path.abspath(os.path.join(currDir, '..')); sys.path.insert(1, rootDir)
# Warnings
import warnings
warnings.filterwarnings("ignore")
# My modules
from features.build_features import *
... | StarcoderdataPython |
9670642 | <filename>py_eye/script/group_script.py
#######################################################
# Copyright (c) 2013 <NAME>
#
# See the file license.txt for copying permission.
########################################################
from io import *
from polish import *
from preprocessing import *
from analys... | StarcoderdataPython |
3351230 | <reponame>vierofernando/username601<filename>framework/xmltodict.py
"""
WHO TF NEEDS XMLTODICT WHEN YOU HAVE THE FILE ITSELF
(file from the official repo of xml2dict python pypi package)
removed some functions to make it more "lightweight" i guess?
"""
from xml.parsers import expat
from xml.sax.saxutils import XMLGene... | StarcoderdataPython |
11267451 | <reponame>Chaytali/Python
def add_emp():
id=0
details=[]
n=input("Please enter the number of records you wish to add")
while(n):
id=id+1
print("Please enter the following details to add the employee")
name=input("Enter the name of employee")
dob=input("Enter the DOB of th... | StarcoderdataPython |
332438 | # -*- coding: utf-8 -*-
'''
Created on Jun 10, 2011
@author: evan
'''
from lxml import etree
from kayako.core.object import KayakoObject
__all__ = [
'TicketCountTicketStatus',
'TicketCountTicketType',
'TicketCountOwnerStaff',
'TicketCountUnassignedDepartment',
'TicketCountDepartment',
'Ticke... | StarcoderdataPython |
6690509 | <filename>predict.py
import os
import sys
import tensorflow as tf
import numpy as np
from model import input_fn, model_fn, IMAGES_WITH_SIGNS_PATH, IMAGES_WITHOUT_SIGNS_PATH, CROPPED_IMAGE_SIZE, IMAGES_WITHOUT_SIGNS_CROPPED_PATH
from data.config import DIR_CROPPED_NO_SIGNS, DIR_CROPPED_SIGNS, DIR_FRAMES_SIGNS, CROPPED_... | StarcoderdataPython |
100571 | from django.urls import path
from . import views
urlpatterns = [
path('signup/viewer', views.SignUPViewer.as_view(), name='signup_viewer'),
path('signup/contentcreator', views.SignUPContentCreator.as_view(), name='signup_cc'),
] | StarcoderdataPython |
5046314 | <reponame>ahuraplus/hawkpost
from django.utils import timezone
from datetime import datetime
from functools import wraps
from shutil import rmtree
import gnupg
import tempfile
def with_gpg_obj(func):
@wraps(func)
def inner(key):
# create temp gpg keyring
temp_dir = tempfile.mkdtemp()
g... | StarcoderdataPython |
3467162 | <gh_stars>0
import re
from typing import Optional
import requests
import utils
def solution(initial_nothing: int) -> str:
text = ""
next_nothing = str(initial_nothing)
while next_nothing:
r = requests.get(f"http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing={next_nothing}")
pr... | StarcoderdataPython |
1852023 | <filename>clipper/src/CLIP_analysis.py
"""
Analizes CLIP data given a bed file and a bam file
<NAME> and <NAME>
"""
from collections import Counter, OrderedDict, defaultdict
import os
import subprocess
from bx.bbi.bigwig_file import BigWigFile
import HTSeq
import numpy as np
import pandas as pd
import pybedtools
... | StarcoderdataPython |
3445142 | <reponame>AGeekInside/myhacks
#!/usr/bin/env python
import configparser
import click
from tabulate import tabulate
import myhacks as myh
@click.command()
@click.option("--outputformat", type=click.Choice(myh.OUTPUTS), default="simple")
def run_lspkg(outputformat):
"""Utility to list packages installed in a giv... | StarcoderdataPython |
8195063 | <reponame>PDFGridder/PDFGridder<gh_stars>1-10
from django import forms
class StripeTokenForm(forms.Form):
stripe_token = forms.CharField()
| StarcoderdataPython |
11270801 | <filename>tests/apollo/util/bft_network_partitioning.py
# Concord
#
# Copyright (c) 2019 VMware, Inc. All Rights Reserved.
#
# This product is licensed to you under the Apache 2.0 license (the "License").
# You may not use this product except in compliance with the Apache 2.0 License.
#
# This product may include a num... | StarcoderdataPython |
8104541 | from imutils.face_utils import rect_to_bb
import argparse
import imutils
import dlib
import cv2
import matplotlib.pyplot as plt
import warnings
import os
import tensorflow as tf
import time
from imutils.face_utils.helpers import FACIAL_LANDMARKS_68_IDXS
from imutils.face_utils.helpers import FACIAL_LANDMARKS_5_IDXS
fro... | StarcoderdataPython |
188455 | <gh_stars>1-10
import torch
from torch.utils import data
import os
import numpy as np
import soundfile as sf
from .wsj0_mix import Wsj0mixDataset
def make_dataloaders(train_dir, valid_dir, n_src=2, sample_rate=16000,
segment=4.0, batch_size=4, num_workers=None,
**kwargs):
... | StarcoderdataPython |
3246370 | def problem338():
pass
| StarcoderdataPython |
11328689 | <filename>ktrain/graph/node_generator.py
from .stellargraph.mapper import node_mappers
class NodeSequenceWrapper(node_mappers.NodeSequence):
def __init__(self, node_seq):
if not isinstance(node_seq, node_mappers.NodeSequence):
raise ValueError('node_seq must by a stellargraph NodeSequene object... | StarcoderdataPython |
3257071 | <gh_stars>0
def _precedence_graph_to_graphviz_inner(pg):
dot = f'"{str(pg)}" [label="{str(pg)}"];\n'
for child in pg.children:
dot += f'"{str(pg)}" -> "{str(child)}"; \n'
dot += _precedence_graph_to_graphviz_inner(child)
return dot
def precedence_graph_to_graphviz(pg):
dot = 'digraph ... | StarcoderdataPython |
249145 | <gh_stars>0
def createCalendar(month):
ac = ''
days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
for i in days:
ac = ac + i + ' '
print(f'\n {month}\n')
print(ac)
createCalendar('March') | StarcoderdataPython |
1875006 | # PART ONE #######################################
# import Tkinter as tk
# root = tk.Tk()
# w = tk.Label(root, text="Hello, world!")
# w.pack()
# frame=tk.Frame(root)
# frame.pack()
# b1=tk.Button(frame,text='Close',command=frame.quit)
# def say_hi():
# print 'hello'
# b2=tk.Button(frame,text='Hi',command... | StarcoderdataPython |
1992446 | """
Practice: Factorials with While Loops
Find the factorial of a number using a while loop.
A factorial of a whole number is that number multiplied by every whole number between itself and 1. For example, 6 factorial (written "6!") equals 6 x 5 x 4 x 3 x 2 x 1 = 720. So 6! = 720.
We can write a while loop to take an... | StarcoderdataPython |
1829105 | <gh_stars>1-10
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2019 <NAME> <<EMAIL>>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICEN... | StarcoderdataPython |
6684489 | from distutils.core import setup
import py2exe
setup(console=['{program_py}'])
| StarcoderdataPython |
1935401 | <gh_stars>100-1000
#!/usr/bin/env python
"""Get all images of a wikipedia commons category."""
import json
import logging
import os
import sys
import urllib # images
import urllib2 # text
import xmltodict
logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s',
level=logging.DEBUG,
... | StarcoderdataPython |
3540569 | <reponame>eladkarako/yt-dlp_kit<gh_stars>1-10
# -*- coding: utf-8 -*-
#
# SelfTest/PublicKey/test_DSA.py: Self-test for the DSA primitive
#
# Written in 2008 by <NAME> <<EMAIL>>
#
# ===================================================================
# The contents of this file are dedicated to the public domain... | StarcoderdataPython |
11398479 | <reponame>fooliscool/saleor
from email.headerregistry import Address
from email.utils import parseaddr
from typing import Optional
from django.conf import settings
from django.contrib.sites.models import Site
from django.core.exceptions import ImproperlyConfigured
from django.core.validators import MaxLengthValidator,... | StarcoderdataPython |
98002 | #!/usr/bin/env python
#
# Copyright (c) 2016 Juniper Networks, Inc. All rights reserved.
#
import os
import sys
import json
# License: Apache-2.0
# https://github.com/openstack/cliff/blob/master/cliff/complete.py
class CompleteDictionary:
"""dictionary for bash completion
"""
def __init__(self):
... | StarcoderdataPython |
3340628 | <reponame>lleonart1984/rendezvous
from rendering.manager import *
from rendering.scenes import *
import os
__PT_SHADERS__ = os.path.dirname(__file__)+"/shaders/PT"
compile_shader_sources(__PT_SHADERS__)
class Pathtracer(Technique):
def __init__(self, scene: RaytracingScene, image):
super().__init__()
... | StarcoderdataPython |
6431718 | <filename>tests/test_bridge.py<gh_stars>1-10
# -*- coding: utf-8 -*-
#
# Copyright 2016, 2017 dpa-infocom GmbH
#
# 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/lic... | StarcoderdataPython |
5161615 | # copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | StarcoderdataPython |
5086174 | <filename>partition-labels.py
from typing import Dict, List
def getInd(s: str) -> int:
return ord(s) - ord('a')
class Solution:
def partitionLabels(self, s: str) -> List[int]:
# char_to_laps: Dict[str, List[int]] = {}
# for ind, c in enumerate(s):
# if c in char_to_laps:
... | StarcoderdataPython |
8188676 | #!/bin/env python
# linxzh 2015-12-10
import sys
# home: 1/1, 0/0, hete: 0/1
type_dict = {"1/1":1, "0/0":0, "0/1":-1}
def CalRate(inlist):
miss = inlist.count(0)
home = inlist.count(1)
hete = inlist.count(-1)
all = float(len(inlist))
return "%s\t%s\t%.2f%%\t%s\t%.2f%%\t%s\t%.2f%%\n" % (home ... | StarcoderdataPython |
225543 | <filename>Deep Learning/Bayesian Network/BNN_dev.py
# Probabilistic Bayesian Neural Networks
"""
Title: Probabilistic Bayesian Neural Networks
Author: [<NAME>](https://www.linkedin.com/in/khalid-salama-24403144/)
Date created: 2021/01/15
Last modified: 2021/01/15
Description: Building probabilistic Bayesian neural netw... | StarcoderdataPython |
5137909 | <gh_stars>10-100
import gym
from gym import spaces
import numpy as np
import pickle
import matplotlib.pyplot as plt
import networkx as nx
import pyglet
import os
import time
import rmsd
import pymol
pymol.finish_launching(['pymol', '-qc'])
cmd = pymol.cmd
class RNAWorld2D(gym.Env):
metadata = {
... | StarcoderdataPython |
1981720 | <reponame>foroozandehgroup/NMR-EsPy
from nmrespy import freqfilter, sig
import matplotlib as mpl
mpl.use("pgf")
import matplotlib.pyplot as plt
plt.style.use("./lato.mplstyle")
from matplotlib import patches
import numpy as np
fig = plt.figure(figsize=(4,6))
bottom = 0
top = 1
left = 0.05
right = 0.95
total_height ... | StarcoderdataPython |
1748605 | #!/usr/bin/env python
#
# base.py - The Action and ToggleAction classes.
#
# Author: <NAME> <<EMAIL>>
#
"""This module provides the :class:`Action`, :class:`NeedOverlayAction`, and
:class:`ToggleAction` classes. See the :mod:`.actions` package documentation
for more details.
"""
import logging
import fsl.data.image... | StarcoderdataPython |
12858766 | <filename>rlpy/Domains/__init__.py
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
#from Domain import Domain
from future import standard_library
standard_library.install_aliases()
from .HelicopterHover import Helicopte... | StarcoderdataPython |
3464180 | import asyncio
from multiprocessing import Process
from threading import Thread, current_thread
class AppServerThread(Thread):
def __init__(self, app, port=None, **kwargs):
Thread.__init__(self, **kwargs)
self._app = app
self._port = port
self._loop = None
self._thread_id =... | StarcoderdataPython |
6402066 | """The tests for the homekit component."""
| StarcoderdataPython |
3422703 | # ----------------------------------------------------------------------
# Distributed Lock
# ----------------------------------------------------------------------
# Copyright (C) 2007-2021 The NOC Project
# See LICENSE for details
# ----------------------------------------------------------------------
# Python m... | StarcoderdataPython |
3592498 | import numpy as np
class Image:
def __init__(self, image):
# Initialize the image
self.data = image
self.keypoints = None
self.camera = None
def add_keypoints(self, kpts):
# Set the keypoints
self.keypoints = kpts
def get_descriptors(self):
return n... | StarcoderdataPython |
221110 | # Example 1: sets up service wrapper, sends initial message, and
# receives response.
import watson_developer_cloud
# Set up Conversation service.
conversation = watson_developer_cloud.ConversationV1(
username = '531b64f4-1023-4a46-b81a-f289c6e334b4', # replace with username from service key
password = '<... | StarcoderdataPython |
5097693 | <reponame>kevinw/pyflakes<filename>setup.py<gh_stars>10-100
#!/usr/bin/env python
# (c) 2005-2009 Divmod, Inc. See LICENSE file for details
from distutils.core import setup
setup(
name="pyflakes",
license="MIT",
version="0.4.0",
description="passive checker of Python programs",
author="<NAME>",
... | StarcoderdataPython |
8016631 | from selenium.webdriver.support.select import Select
from ui_tests.caseworker.pages.BasePage import BasePage
from tests_common import functions
class FlaggingRulePages(BasePage):
RADIO_BTN_FLAGGING_RULE_TYPE_ID = "level"
GOOD_OPTION_ID = RADIO_BTN_FLAGGING_RULE_TYPE_ID + "-Good"
DESTINATION_OPTION_ID = R... | StarcoderdataPython |
4970432 | <reponame>eduardagoulart/crawler
import csv
import re
import string
import numpy as np
import clean_datas
import nltk
def stop_words():
return nltk.corpus.stopwords.words('portuguese')
def table_declaration():
_table = {
"á": "a", "à": "a", "â": "a", "ä": "a", "ã": "a", "å": "a",
"é": "e", "... | StarcoderdataPython |
6453520 | <filename>aphla/gui/TinkerUtils/ui_configDescriptionEditor.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui_configDescriptionEditor.ui'
#
# Created: Sat Mar 22 16:56:19 2014
# by: PyQt4 UI code generator 4.9.3
#
# WARNING! All changes made in this file will be lost!
from PyQt4 ... | StarcoderdataPython |
11232107 | <gh_stars>10-100
import io
from unittest.mock import patch, PropertyMock
from os.path import abspath, dirname, join
import OpenSSL
from django.core.management import call_command
from django.test.testcases import TestCase
from gspread.exceptions import SpreadsheetNotFound
from oauth2client.client import AccessTokenRef... | StarcoderdataPython |
12848473 | <filename>nick_derobertis_site/software_page/config/page.py
from nick_derobertis_site.software_page.config.banner import SOFTWARE_BANNER_MODEL
from nick_derobertis_site.software_page.config.card import SOFTWARE_CARD_MODELS
from nick_derobertis_site.software_page.software_page_model import SoftwarePageModel
SOFTWARE_PA... | StarcoderdataPython |
251684 | <reponame>prerak23/Room_Param_Estimation<filename>cal_features/cal_stds.py<gh_stars>1-10
import numpy as np
import h5py
#This script calculates std and variance of the rt60 values/freq band in the training set.
abc=np.load("train_random_ar.npy")
#Annoted labels of rt60,abs,vol,surface area.
dc=h5py.File("rt60_anno_... | StarcoderdataPython |
3505085 | <reponame>PiecePaperCode/Network_ping_Mining
#This is the Main Part of this Programm if ur just interested to ping some Stuff urself!
#Ping Funktion Checking for WIN OS Externe Ping Defenition
import sys, subprocess, os
def ping(host):
process = subprocess.Popen(["ping", cmd1, cmd2,host], stdout=subprocess.PIPE, ... | StarcoderdataPython |
9690274 | <gh_stars>0
import os
import argparse
import inspect
import imageio
import pickle
import torch
from torch import nn
import torch.nn.functional as F
from torch.utils.data import TensorDataset, DataLoader
import torchsso
from sklearn.datasets import make_blobs
import numpy as np
import matplotlib.pyplot as plt
from to... | StarcoderdataPython |
12804431 | import click
from .main import main, lprint
from ..sera import run, remote
@main.command(
context_settings=dict(
ignore_unknown_options=True))
@click.pass_context
@click.argument('args', nargs=-1, type=click.UNPROCESSED)
def echo(ctx, args):
"""Test connection with watcher"""
if ctx.obj['local']:... | StarcoderdataPython |
3349386 | import numpy as np
from common.constant.df_from_csv import WORD_LIST_FOR_CMP
from core.nlp.response_generator.product.base.base_response_generator import BaseResponseGenerator
class CMPResponseGenerator(BaseResponseGenerator):
"""
This class creates cmp responses
"""
def __call__(self):
retur... | StarcoderdataPython |
3483341 | from apistar.test import TestClient
from app import app, welcome
def test_welcome():
"""
Testing a view directly.
"""
data = welcome()
assert data == {'message': 'Welcome to API Star!'}
def test_http_request():
"""
Testing a view, using the test client.
"""
client = TestClient(ap... | StarcoderdataPython |
4933473 | import numpy as np
nat_freq_true = np.array([176.07332578, 476.4634351, 932.28540465, 1534.78951957,
2286.31989538, 3162.15866336, 4181.71710178])
complex_modes_true = np.array([[ 8.78858427e+00-4.62576800e+01j, 1.47828731e+02-3.77006628e+02j,
2.88980008e+01-1.75736863e+02j, 5.02619914e-01+3.... | StarcoderdataPython |
3344476 | #!/usr/bin/env python
from __future__ import print_function
"""
This script will use PyPI to identify a release of a package, and then search
through github to get a count of all of the issues and PRs closed/merged since
that release.
Usage:
python gh_issuereport.py astropy/astropy astropy/0.3
Note that it will prom... | StarcoderdataPython |
6430775 | <filename>0-Simulation/kinematics.py
import math
import time
from numpy.lib.twodim_base import tri
from constants import *
from scipy.optimize import minimize
import numpy as np
# Given the sizes (a, b, c) of the 3 sides of a triangle, returns the angle between a and b using the alKashi theorem.
def alKashi(a, b, c, s... | StarcoderdataPython |
3322737 | <reponame>GeneKao/compas_viewers
from compas.datastructures import Mesh
from compas_viewers.meshviewer import MeshViewer
viewer = MeshViewer()
viewer.mesh = Mesh.from_polyhedron(6)
viewer.show()
| StarcoderdataPython |
12821324 | <gh_stars>1-10
import torch
import torch.nn as nn
class BottleNeck(nn.Module):
def __init__(self, in_channels, out_channels, stride=1):
super().__init__()
self.residual_function = nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size = 1, bias = False),
nn.BatchNo... | StarcoderdataPython |
8100316 | <filename>space_agency/travels/views.py<gh_stars>1-10
from django.http import HttpResponse
def home(request):
dummy_html = "<h1> Hi! You are visiting the space travel agency</h1>"
return HttpResponse(dummy_html) | StarcoderdataPython |
5128357 | __author__ = 'guest148'
import matplotlib.pyplot as plt
from math import pi, sin
from numpy import arange
def calculateTopX(a, b, c):
return -b/(2*a)
def calculateTopY(a, b, c):
x = calculateTopX(a, b, c)
return calcY(a, b, c, x)
def calcY(a, b, c, x):
return a * x**2 + b * x + c
def genParabola(... | StarcoderdataPython |
6574960 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | StarcoderdataPython |
6479829 | <gh_stars>1-10
import numpy as np
class ParseYOLOOutput:
def __init__(self, conf):
# store the configuration file
self.conf = conf
def parse(self, layerOutputs, LABELS, H, W):
# initialize our lists of detected bounding boxes,
# confidences, and class IDs, respectively
... | StarcoderdataPython |
4998732 | # import_gshhg.py
import os.path
import psycopg2
import osgeo.ogr
connection = psycopg2.connect(database="distal",
user="distal_user",
password="...")
cursor = connection.cursor()
cursor.execute("DELETE FROM shorelines")
for level in [1, 2, 3, 4]:
num_... | StarcoderdataPython |
4818020 | <filename>ml_progress/display.py<gh_stars>0
class Display():
def update(self, metric: str, width: int):
raise NotImplementedError | StarcoderdataPython |
1860150 | # Copyright (c) 2012-2021, <NAME> <<EMAIL>>
# All rights reserved.
#
# See LICENSE file for full license.
from .aws import Action as BaseAction
from .aws import BaseARN
service_name = "AWS Certificate Manager"
prefix = "acm"
class Action(BaseAction):
def __init__(self, action: str = None) -> None:
super... | StarcoderdataPython |
1878534 | import matplotlib.pyplot as plt
import tensorflow as tf
def normalize(image_path = 'data/raw/gonzalez.tif', mask_path = 'data/ground_truth/gonzalez/gonzalez_mask.tif'):
input_image = plt.imread(fname=image_path, format="tif")
input_image = tf.cast(input_image, tf.float32) / 255.0
input_mask = plt.imread(f... | StarcoderdataPython |
1942443 | <reponame>almmessias/CursoPython
tupla = ('zero', 'um', 'dois', 'tres', 'quatro', 'cinco',
'seis', 'sete', 'oito', 'nove', 'dez', 'onze', 'doze',
'treze', 'catorze', 'quinze', 'dezesseis', 'dezessete',
'dezoito', 'dezenove', 'vinte')
while True:
num = int (input ('Digite um número entre 0... | StarcoderdataPython |
1603006 | <filename>ufora/FORA/test/test.py
# Copyright 2015 Ufora 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 require... | StarcoderdataPython |
4879040 | <filename>scrapy/contrib/dupefilter.py
"""
Dupe Filter classes implement a mechanism for filtering duplicate requests.
They must implement the following methods:
* open_spider(spider)
open a spider for tracking duplicates (typically used to reserve resources)
* close_spider(spider)
close a spider (typically used ... | StarcoderdataPython |
1738652 | <filename>official/vision/beta/modeling/backbones/revnet.py
# Lint as: python3
# Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
... | StarcoderdataPython |
5199349 | <filename>app/connect.py
import os
import psycopg2
from psycopg2.extras import RealDictCursor
from flask import current_app
from app import schema
from werkzeug.security import generate_password_hash, check_password_hash
class QuestionerDB():
"""Class with database connection"""
@classmethod
def init_db(... | StarcoderdataPython |
1895405 | <reponame>Voidxtoxic/kita
import telegram.ext as tg
from pyrate_limiter import (
BucketFullException,
Duration,
RequestRate,
Limiter,
MemoryListBucket,
)
from telegram import Update
import YorForger.modules.sql.blacklistusers_sql as sql
from YorForger import LOGGER, DEV_USERS, SUPPORT_USERS, WHITE... | StarcoderdataPython |
228756 | <gh_stars>1-10
from enum import Enum
REQUEST_POLL = b'\x01'
FRAME_START = b'\x02'
FRAME_END = b'\n'
class CommandChar(Enum):
POLL = b'P'
ACK = b'A'
NACK = b'N'
MSG = b'M'
class ReportType(Enum):
THERMO_CALIB = b'C'
SENSORS = b'D'
WETNESS_CALIB = b'K'
THRESHOLD = b'T'
WETNESS = ... | StarcoderdataPython |
3423454 | <gh_stars>1-10
def BFS_undirected(G, s):
#Breadths first search for finding all the nodes connected to s undirected graph, also compute the distance to the s.
#G: the undirected graph, nodes form 1 to N
#s: the starting node
Q = [s]
nodes_explored = {s: 0}
while len(Q) > 0:
v = Q.pop(0)
... | StarcoderdataPython |
4836652 | import requests
import os
import time
def down_book(uri,pos,PAGENUM,root):
"""
:param uri: the base uri
:param pos: the posix
:param PAGENUM: total page number
:param root: the saved root directory name
:return: none
"""
for id in range(1,PAGENUM):
file_path = '%s/%3d%s'%(root,... | StarcoderdataPython |
1704555 | <reponame>ismailbennani/ReGraph
"""ReGraph hierarchy tutorial ex 1."""
import networkx as nx
from regraph import Hierarchy, plot_graph, primitives
# create an empty hierarchy
hierarchy = Hierarchy()
# initialize graphs `t` & `g`
t = nx.DiGraph()
primitives.add_nodes_from(
t, ["agent", "action", "state"])
primiti... | StarcoderdataPython |
8134594 | <filename>output/models/nist_data/union/any_uri_float/schema_instance/nistschema_sv_iv_union_any_uri_float_enumeration_3_xsd/__init__.py
from output.models.nist_data.union.any_uri_float.schema_instance.nistschema_sv_iv_union_any_uri_float_enumeration_3_xsd.nistschema_sv_iv_union_any_uri_float_enumeration_3 import (
... | StarcoderdataPython |
1817954 | from requests import Response
from py365.data import BaseData
from ._base_resource import BaseResource
class ChildResource:
"""
Represent a child resource on the OG
Every OG API class that represent a child API should inherit from this class
"""
def __init__(self, baseAPI: BaseResource, edgeMid: ... | StarcoderdataPython |
11332131 | import json
from typing import List
from voluptuous import In, Schema, Required, IsDir
from pyesg.configuration.json_serialisable_class import JSONSerialisableClass, _has_parameters
from pyesg.constants.validation_analyses import ALL_VALIDATION_ANALYSES
class Parameters(JSONSerialisableClass):
"""
Represent... | StarcoderdataPython |
137716 | <reponame>zzzeek/calchipan
from sqlalchemy.testing.fixtures import TestBase
import pandas as pd
from sqlalchemy import create_engine, MetaData, Table, Column, \
String, Integer, ForeignKey, select, exc, func
from . import eq_, assert_raises_message
class DialectTest(TestBase):
def _emp_d_fixture(self, id_col... | StarcoderdataPython |
6696403 | <reponame>jadedgamer/alifewellplayed.com
from __future__ import absolute_import
#from urlparse import urlparse
from urllib.parse import urlparse
import hashlib
from django.shortcuts import render_to_response, render, get_object_or_404, redirect
from django import template
from ..models import Account
register = templ... | StarcoderdataPython |
368867 | <gh_stars>0
import os
from PIL import Image
def get_file_paths(folder, also_filenames=False):
image_file_paths = []
my_filenames = []
for root, dirs, filenames in os.walk(folder):
filenames = sorted(filenames)
my_filenames = filenames.copy()
for filename in filenames:
... | StarcoderdataPython |
348909 | <reponame>margudo/marvin
# !usr/bin/env python2
# -*- coding: utf-8 -*-
#
# Licensed under a 3-clause BSD license.
#
# @Author: <NAME>
# @Date: 2017-06-12 19:13:30
# @Last modified by: <NAME>
# @Last Modified time: 2017-06-12 19:23:07
from __future__ import print_function, division, absolute_import
from marvin.cor... | StarcoderdataPython |
9741925 | <filename>services/proto_aggregator/api.py
#coding:utf-8
#
# PROGRAM/MODULE: Saturnin microservices
# FILE: prot_aggregator/api.py
# DESCRIPTION: API for protobuf aggregator microservice
# CREATED: 20.1.2020
#
# The contents of this file are subject to the MIT License
#
# Permission is hereby grante... | StarcoderdataPython |
6658627 | from multiprocessing import Queue
import logging
class QueueWrapper():
def __init__(self, queue):
self.logger = logging.getLogger(__name__)
self.queue = queue
def put_blocking(self, element):
self.queue.put(element, block=True)
def put_none_blocking(self, element):
if sel... | StarcoderdataPython |
3545237 | <filename>imylu/neighbors/knn_regressor.py
# -*- coding: utf-8 -*-
"""
@Author: tushushu
@Date: 2018-08-14 15:34:28
@Last Modified by: tushushu
@Last Modified time: 2018-08-14 15:34:28
"""
from .knn_base import KNeighborsBase
class KNeighborsRegressor(KNeighborsBase):
def __init__(self):
KNeighborsBase.... | StarcoderdataPython |
4920617 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class UserInfoDetail(object):
def __init__(self):
self._ip_id = None
self._ip_role_id = None
self._out_member_id = None
self._user_info_id = None
self._user_info... | StarcoderdataPython |
3493221 | import re
def my_hash(_o):
val = 0
for c in bytes(_o, encoding="ascii"):
val *= 7
val += int(c)
return val
def str_list_hash(o):
var = 0
for _ in o:
var *= 7
var += my_hash(_)
return var
def unordered_list_hash(o):
var = 0
for _ in o:
var += ... | StarcoderdataPython |
3515005 | <reponame>spearlineltd/sqlalchemy-cockroachdb
from sqlalchemy import __version__ as sa_version
from sqlalchemy.testing import combinations
from sqlalchemy.testing import skip
from sqlalchemy.testing.suite import * # noqa
from sqlalchemy.testing.suite import ComponentReflectionTest as _ComponentReflectionTest
from sqla... | StarcoderdataPython |
5009398 | from __future__ import absolute_import
import os
"""A Julia set computing workflow: https://en.wikipedia.org/wiki/Julia_set.
This example has in the juliaset/ folder all the code needed to execute the
workflow. It is organized in this way so that it can be packaged as a Python
package and later installed in the VM wor... | StarcoderdataPython |
1903648 | <reponame>jannero/setuptools_autover
import setuptools
import setuptools_autover
with open('README.rst', 'rt') as readme_file:
long_desc = readme_file.read() # pylint: disable=invalid-name
setuptools.setup(
name='setuptools_autover',
version=setuptools_autover.get_version(),
description='Automatic ... | StarcoderdataPython |
235469 | <filename>meld/utils/app_data.py
from appdirs import user_data_dir
from pathlib import Path
from meld.__about__ import __title__, __author__
app_data_dir = Path(user_data_dir(__title__, __author__))
# Initialize data directory and required datafiles
Path(app_data_dir).mkdir(exist_ok=True, parents=True) | StarcoderdataPython |
9674841 | # Copyright (c) 2021 AccelByte Inc. All Rights Reserved.
# This is licensed software from AccelByte Inc, for limitations
# and restrictions contact your company contract manager.
#
# Code generated. DO NOT EDIT!
# template file: justice_py_sdk_codegen/__main__.py
# justice-lobby-server (staging)
# pylint: disable=d... | StarcoderdataPython |
82855 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2014-2016 bromix (plugin.video.youtube)
Copyright (C) 2016-2018 plugin.video.youtube
SPDX-License-Identifier: GPL-2.0-only
See LICENSES/GPL-2.0-only for more information.
"""
from six.moves import range
import copy
import json
import time
from ...youtube.you... | StarcoderdataPython |
204046 | import argparse
import configparser
import json
import os
import sys
import time
import cv2
import numpy as np
import torch
from retinanet.model import PostProcessor
from tools import Preprocessor
from trttools import common
from trttools.engine_utils import gpu_warmup, get_engine
from utils.label_utils import load_c... | StarcoderdataPython |
6607336 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# ==================================================
# @Time : 2019-06-05 10:15
# @Author : ryuchen
# @File : unittest_vmware.py
# @Desc :
# ==================================================
"""
Using this unittest to test vmware guest operate function
The function below w... | StarcoderdataPython |
8083716 | <reponame>Pearl-Ayem/ATSC_Notebook_Data
import numpy as np
#
# get Stull's c_1 and c_2 from fundamental constants
#
# c=2.99792458e+08 #m/s -- speed of light in vacuum
# h=6.62606876e-34 #J s -- Planck's constant
# k=1.3806503e-23 # J/K -- Boltzman's constant
c, h, k = 299792458.0, 6.62607004e-34, 1.38064... | StarcoderdataPython |
11233664 |
def serialize_post(post, postswriter, commentswriter, reactionswriter, subcommentswriter, creactionswriter, subreactionswriter, attachmentswriter):
post_id=posts["id"]
from_id=posts["from"]["id"]
post_fieldnames=["from","message","attachments","id","created_time"]
post_dict = {key: post[key] for key ... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.