id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
86057 | <reponame>digitalmensch/silo
#!/usr/bin/env python3.6
import os
import datetime
import inspect
import json
import sys
import syslog
import time
import functools
import uuid
################################################################################
# Processors
###################################################... | StarcoderdataPython |
1783874 | from django.urls import path
from . import views
urlpatterns = [
path('',views.controllers, name='controllers'), # HomeView
] | StarcoderdataPython |
3305916 | <filename>settings.py
## application settings
##
## @author <NAME>
## @date 2015/09/26
import os.path
TEMPLATE_PATH = os.path.join(os.path.dirname(__file__), 'templates')
STATIC_PATH = os.path.join(os.path.dirname(__file__), 'assets')
settings = {
'autoreload': True,
'debug': True,
'compress_response': T... | StarcoderdataPython |
4814657 | <reponame>motion-workshop/shadow-fileio-python-example<filename>main.py<gh_stars>0
#
# Copyright (c) 2021, Motion Workshop
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of... | StarcoderdataPython |
3205994 | <filename>example_native_deps/handler.py
# must be called as we're using zipped requirements
try:
import unzip_requirements
except ImportError:
pass
import numpy
import scipy
import sklearn
def hello(event, context):
return {mod.__name__: mod.__version__ for mod in (numpy, scipy, sklearn)}
| StarcoderdataPython |
3311729 | <reponame>jmgiaever/home-assistant-snap
"""Support to check for available updates."""
from __future__ import annotations
import asyncio, logging, async_timeout, os, voluptuous as vol
from awesomeversion import AwesomeVersion
from datetime import timedelta
from homeassistant.const import __version__ as current_versio... | StarcoderdataPython |
47957 | <gh_stars>0
''' Esta função conta o número de ocorrências de cada palavra em uma frase '''
def count_words(sentence):
for s in ".:!&@$%^&": sentence=sentence.replace(s,'')
for s in "\n\r\t,_": sentence=sentence.replace(s,' ')
counts={}
for word in sentence.lower().split():
word = word.strip... | StarcoderdataPython |
1755218 | <reponame>nil1729/python__noob
"""
Black Jack Game Methods
take_bet => Player bets
"""
from game_objects import Chips, Hand
def setup_players(deck):
"""
Create a list of players and their names
"""
while True:
try:
name = input("Enter the name of the player: ")
... | StarcoderdataPython |
1614468 | <filename>account/middleware.py
from __future__ import unicode_literals
from django.utils import translation, timezone
from django.utils.cache import patch_vary_headers
from account.conf import settings
from account.models import Account
class LocaleMiddleware(object):
"""
This is a very simple middleware t... | StarcoderdataPython |
4809465 | from pprint import pprint
# Metaclass that will make all class attributes and methods be uppercase
class ToUpper(type):
def __new__(cls, name, bases, namespace):
new_namespace = {}
for attr, value in namespace.items():
if attr.startswith('__'):
new_namespace[attr] = valu... | StarcoderdataPython |
1700713 | <reponame>LI-Mingyu/GraphScope-MY
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2020 Alibaba Group Holding Limited. 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 Li... | StarcoderdataPython |
148717 | import os
import time
import cv2
import matplotlib.pyplot as plt
import numpy as np
import png
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
from colormap.colors import Color, hex2rgb
from sklearn.metrics import average_precision_score as ap_score
from torch.utils.data import DataLo... | StarcoderdataPython |
1642113 | <filename>BasicExperiments/ColorVigilanceTask.py
#!/usr/bin/env python2
"""Display a visual viglilance task where the dot at the center changes color periodically."""
# ColorVigilanceTask.py
# Created 1/3/16 by DJ based on VidLecTask_vigilance.py
from psychopy import core, gui, data, event, sound, logging#, visual # v... | StarcoderdataPython |
3398880 | <reponame>cirvine-MSFT/reinforcement_learning<filename>test_tools/reproduce_model.py
#!/usr/bin/env python3
"""
Utility script to replay DecisionService dsjson logs from a known initial model to obtain a given final target model.
"""
import os, hashlib, struct, argparse, subprocess
def check_result(result):
... | StarcoderdataPython |
101505 | example_schema_array = {"type": "array", "items": {"type": "string"}}
example_array = ["string"]
example_schema_integer = {"type": "integer", "minimum": 3, "maximum": 5}
example_integer = 3
example_schema_number = {"type": "number", "minimum": 3, "maximum": 5}
example_number = 3.2
example_schema_object = {"type": "obje... | StarcoderdataPython |
4815503 | #!/usr/bin/env python
#!/python -m spacy download en
# import lxml.html
import html2text
import spacy
import gensim
from gensim.summarization.summarizer import summarize
import textract
if __name__ == "__main__":
summaries = []
paths = [
'/Users/hobs/Downloads/The PwC Internal Audit.html',
'/U... | StarcoderdataPython |
3359010 | <reponame>CADDE-sip/connector
import connexion
from flask import send_file
import logging
from swagger_server.utilities.message_map import get_message
from swagger_server.services.service import fetch_data
from swagger_server.utilities.external_interface import ExternalInterface
from swagger_server.utilities.utilitie... | StarcoderdataPython |
124652 | import pandas as pd
def is_sum_of_series_big(series):
# Lets check if this dataframe has over a thousand rows
if series.sum() > 1000:
return True
else:
return False
if __name__ == "__main__":
s1 = pd.Series([1000, 1000])
print(s1)
print(is_sum_of_series_big(s1))
s2 = pd.Se... | StarcoderdataPython |
4804779 | <gh_stars>1-10
# 1. Look into Exercise 1 ( creating a variable) , and for the 10 varaibles we created earlier, state their data types
age = 20 # integer
name = "tuna" # string
speed_limit = "120km/h" # string
average = 2.34 # float
size = 23 # integer
number_of_babies = 2 # integer
number_of_scripts = 100 # ... | StarcoderdataPython |
166861 | <gh_stars>1-10
#!/usr/bin/python3
import logging
logging.basicConfig(filename='log.log', level=logging.DEBUG)
logging.info('This message should go to the log file')
| StarcoderdataPython |
1642780 | # -*- coding:utf8 -*-
from datetime import datetime
import time
def job_exec_per_sec(seconds):
"""
通过循环方式+sleep实现定时任务
:param seconds: 定时任务周期间隔描述
:return: 无返回
"""
while True:
print("while循环定时任务执行了,时间:%s" % datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
time.sleep(seconds)
if ... | StarcoderdataPython |
3217297 | <reponame>arcanemachine/menu-maker
from django.contrib.auth import get_user_model
from django.urls import reverse
from rest_framework import generics
from rest_framework.permissions import IsAuthenticated
from rest_framework.test import APITestCase
from menus_project import constants as c
from menus_project import fac... | StarcoderdataPython |
1710130 | ##############################################################################
# Copyright (c) 2021, Oak Ridge National Laboratory #
# All rights reserved. #
# #
# Th... | StarcoderdataPython |
84739 | #!/usr/bin/env python
import unittest
from pycoin.ecdsa import generator_secp256k1, sign, verify, public_pair_for_secret_exponent
class ECDSATestCase(unittest.TestCase):
def test_sign_verify(self):
def do_test(secret_exponent, val_list):
public_point = public_pair_for_secret_exponent(generat... | StarcoderdataPython |
1708255 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Cloud HR experiments
Created on Fri Dec 9 11:22:51 2016
@author: maxwell
"""
import numpy as np
import matplotlib.pyplot as plt
import time
import copy
import atmosphere as a
from parm import ChemParm, LWParm, SWParm
from solver import SolverFactory,HR
from misc... | StarcoderdataPython |
1746892 | <filename>PaddleCV/tracking/ltr/dataset/imagenetdet.py<gh_stars>1-10
import os
import numpy as np
from .base_dataset import BaseDataset
from ltr.data.image_loader import default_image_loader
import xml.etree.ElementTree as ET
import glob
import json
from collections import OrderedDict
import nltk
from nltk.corpus impor... | StarcoderdataPython |
159995 | <filename>Comprehensions/Exercises/05. diagonals.py
def read_matrix_lines():
return [int(x) for x in input().split(", ")]
def create_matrix(size):
result = [read_matrix_lines() for _ in range(size)]
return result
def get_first_diagonal(matrix, size):
return [matrix[i][i]for i in range(size)]
def get_... | StarcoderdataPython |
3280112 | <filename>python/EnsembleLearning/AdaBoost.py
# Boosting思想主要方法 - AdaBoost
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from sklearn.ensemble import AdaBoostClassifier # adaboost引入方法
from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import make_gaussian_quantiles # 造... | StarcoderdataPython |
97164 | # example_traceback.py
def loader(filename):
fin = open(filenam)
loader("data/result_ab.txt")
| StarcoderdataPython |
117057 | from aydin.util.misc.combinatorics import closest_product
def test_closest_product():
u = [1, 2, 5, 7, 9, 10]
N = 15
result = closest_product(u, N)
print(f"closest_product({u}, {N}) = {result}")
assert result == [1, 3]
N = 27
result = closest_product(u, N)
print(f"closest_product({u... | StarcoderdataPython |
1624443 | from functools import partial
from typing import List, Optional
import attr
import os
from multiprocessing.pool import ThreadPool
from urllib.parse import urlencode
from bs4 import BeautifulSoup
import requests
from stuff.core import Stuff
from stuff.constants import Area, Region, Category
@attr.s
class Proximinity... | StarcoderdataPython |
3337469 | <gh_stars>100-1000
"""
From https://github.com/vendasta/cloudpypi/blob/master/cloudpypi/package_api.py#L14
"""
import os
import re
ARCHIVE_SUFFIX = r"(\.zip|\.tar\.gz|\.tgz|\.tar\.bz3|-py[23]\.\d-.*|\.win-amd64-py[23]\.\d\..*|\.win32-py[23]\.\d\..*)$"
_archive_suffix_re = re.compile(ARCHIVE_SUFFIX, re.IGNORECASE)
wh... | StarcoderdataPython |
1766905 | import numpy as np
from iminuit import Minuit
from .energy_likelihood import *
from .spatial_likelihood import *
"""
Module to compute the IceCube point source likelihood
using publicly available information.
Based on the method described in:
<NAME> al., 2008. Methods for point source analysis
in high energy neutri... | StarcoderdataPython |
113881 | <reponame>googleinterns/vm-network-migration<filename>vm_network_migration/errors.py
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org... | StarcoderdataPython |
143092 | # Copyright (c) 2018-2019, NVIDIA CORPORATION
# Copyright (c) 2017- Facebook, Inc
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above ... | StarcoderdataPython |
1650846 | # test for generate seismic data
# Std import block
import time
import numpy as np
import matplotlib.pyplot as plt
from pysit import *
from pysit.gallery import horizontal_reflector
import os
import shutil
# Define Domain
pmlx = PML(0.1, 100)
pmlz = PML(0.1, 100)
os.environ["OMP_NUM_THREADS"] = "12"
x_config = (0.... | StarcoderdataPython |
8872 | """
Mock up a video feed pipeline
"""
import asyncio
import logging
import sys
import cv2
logging.basicConfig(format="[%(thread)-5d]%(asctime)s: %(message)s")
logger = logging.getLogger('async')
logger.setLevel(logging.INFO)
async def process_video(filename):
cap = cv2.VideoCapture(filename)
tasks = list()
... | StarcoderdataPython |
1721176 | # to tune see http://gunicorn-docs.readthedocs.org/en/latest/settings.html
import multiprocessing, os
# to serve directly via TCP:
bind = os.getenv('GUNICORN_BIND', '0.0.0.0:5000')
# for nginx or other proxy:
# bind = "unix:/deploy/run/gunicorn.sock"
#
workers = os.getenv('GUNICORN_WORKERS', (multiprocessing.cpu_count... | StarcoderdataPython |
1617425 | <reponame>ralfrost/probnum
"""
Interfaces for Bayesian filtering and smoothing.
"""
from abc import ABC, abstractmethod
class BayesFiltSmooth(ABC):
"""
Bayesian filtering and smoothing.
"""
def __init__(self, dynamod, measmod, initrv):
self.dynamod = dynamod
self.measmod = measmod
... | StarcoderdataPython |
1704749 | <filename>examples/pendulum_data_collect.py
import numpy as np
import gym
from rllab.baselines.linear_feature_baseline import LinearFeatureBaseline
from pytorchrl.algos.trpo import TRPO
from pytorchrl.envs.gym_env import GymEnv
from pytorchrl.policies.gaussian_mlp_policy import GaussianMLPPolicy
from pytorchrl.misc.l... | StarcoderdataPython |
1607016 | from turtle import *
pensize(20)
bgcolor("black")
colors = ["#db0f3c","#50ebe7","white"]
pos = [(0,0),(-5,13),(-5,5)]
for (x,y),col in zip(pos,colors):
up()
goto(x,y)
down()
color(col)
left(180)
circle(45,270)
forward(120)
left(180)
circle(50,90) | StarcoderdataPython |
3216400 | from keras.layers import Flatten, Convolution2D, Reshape, UpSampling2D, MaxPooling2D, Dense
from keras.models import Sequential, model_from_json
from keras.optimizers import *
from qlearning4k.Training import *
from qlearning4k.games.tictactoe import TicTacToe
from qlearning4k.nnAgent import Agent
from qlearning4k.ran... | StarcoderdataPython |
25055 | __author__ = 'przemyslaw.pioro'
| StarcoderdataPython |
192181 | """
Downloads practice statistics data from BigQuery into the
`settings.MATRIXSTORE_IMPORT_DIR` directory
"""
import csv
import gzip
import logging
import os
from django.conf import settings
from gcutils.bigquery import Client
from .common import get_practice_stats_filename, get_temp_filename
from .dates import gene... | StarcoderdataPython |
3331882 | <gh_stars>1-10
import gossip
from eva_intent import EvaIntent
INTENT = EvaIntent()
@gossip.register('eva.post_boot', provides=['intent'])
def post_boot():
gossip.trigger('eva.intent.ready_intent', intent=INTENT)
INTENT.build()
@gossip.register('eva.pre_interaction', provides=['intent'])
def pre_interaction(c... | StarcoderdataPython |
52850 | <reponame>hypergravity/starlight_wrapper
# -*- coding: utf-8 -*-
"""
Author
------
<NAME>
Email
-----
<EMAIL>
Created on
----------
- Sat Jul 16 22:30:00 2016
Modifications
-------------
- Sat Jul 16 22:30:00 2016 framework
- Sun Jul 17 23:00:00 2016 StarlightGrid
- Mon Jul 18 09:27:00 2016
Aims
----
- to g... | StarcoderdataPython |
1734230 | <filename>gui/demo/ptest - Copy (2).py<gh_stars>0
# coding=utf-8
import unittest
from mem_dixy.tag.alphabet import logical
from mem_dixy.Unicode.U0000 import *
from enum import Enum
class enum_comparison(Enum):
lt = 0,
le = 1,
eq = 2,
ne = 3,
ge = 4,
gt = 5,
sa = 6,
sn = 7
class o... | StarcoderdataPython |
1764448 | <reponame>stangelandcl/hardhat
import os
from .base import GnuRecipe
from ..util import patch
class LinuxPamRecipe(GnuRecipe):
def __init__(self, *args, **kwargs):
super(LinuxPamRecipe, self).__init__(*args, **kwargs)
self.sha256 = '241aed1ef522f66ed672719ecf2205ec' \
'513fd0... | StarcoderdataPython |
3391441 | <filename>speakeasy/winenv/api/usermode/ntdll.py<gh_stars>0
# Copyright (C) 2020 FireEye, Inc. All Rights Reserved.
from .. import api
class Ntdll(api.ApiHandler):
"""
Implements exported native functions from ntdll.dll. If a function is not supported
here, but is supported in the ntoskrnl handler (e.g.... | StarcoderdataPython |
3241749 | # Copyright 2019 Nokia
#
# 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, softwa... | StarcoderdataPython |
184193 | import json
from sort_strategy import *
class SortingServiceException(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
def create_book_by_dict(book_dict):
title = ('%(title)s' % book_dict)
author = ('%(author)s' % book_dict)
year ... | StarcoderdataPython |
3319154 | """
Contains the Image class.
"""
import math
import os
import time
import warnings
import azcam
import numpy
from astropy.io import fits as pyfits
from azcam.tools.header import Header
from azcam.tools.image_focalplane import FocalPlane
class Image(object):
"""
Class to create and manipulate the standard a... | StarcoderdataPython |
1632702 | <gh_stars>1-10
def longest_palindrome (s):
return 0 if not s else max([max([k - i if s[i:k][::-1] == s[i:k] else 0
for k in range(i + 1, len(s) + 1)])
for i, c in enumerate(s)])
| StarcoderdataPython |
1637706 | #!/usr/bin/env python
# coding: utf-8
import logging
from elasticsearch import Elasticsearch
class ConnectElasticsearch:
def __init__(self, host='localhost', port=9200):
'''
Reads the value of the host and the port.
'''
self.host = host
self.port = port
def connect... | StarcoderdataPython |
106949 | #!/usr/bin/env python3
# encoding: utf-8
from collections import defaultdict
from copy import deepcopy
from typing import Dict, List
import numpy as np
from mlagents_envs.environment import UnityEnvironment
from mlagents_envs.side_channel.engine_configuration_channel import \
EngineConfigurationChannel
... | StarcoderdataPython |
126134 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 21 10:30:25 2018
Try to predict in which lab an animal was trained based on its behavior
@author: guido
"""
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats
from os.path import join
import seaborn as s... | StarcoderdataPython |
53730 |
import Metodos.pf_multivariable
import Metodos.pf_desplazado
import Metodos.NewthonR_Mult
import Metodos.Newton_modificado
import math
def datos():
ecua = []
var = []
valor = []
Ecuaciones = int(input("Numero de ecuaciones:"))
print("Variables:")
for i in range(1, Ecuaciones+1):
vari... | StarcoderdataPython |
1635815 | <gh_stars>1-10
from django.apps import AppConfig
class OnesignalEmailConfig(AppConfig):
name = 'courier.emails.providers.onesignal'
label = 'onesignal-email'
def ready(self):
import courier.emails.providers.onesignal.signals
| StarcoderdataPython |
3245069 | import re,os
import xml.etree.ElementTree as ET
from .Webby import Webby
from .Common import *
class Harvester(object):
def __init__(self,verbosity):
self.webbies = set()
self.verbosity = verbosity
def harvest_nessus_dir(self,nessus_dir):
for dirpath,directories,files in os.walk(nessus... | StarcoderdataPython |
3232006 | # from __future__ import absolute_import
# from celery import Celery
# from django.conf import settings
#
# app = Celery(
# 'genobase',
# # broker='amqp://admin:mypass@{}:5672'.format(
# # 'rabbit' # if settings.IS_DOCKER else 'localhost'
# # ),
# broker='redis://redis:6379/0',
# backend='r... | StarcoderdataPython |
20298 | import os
import dgl
import time
import argparse
import numpy as np
import torch as th
import distutils.util
import torch.nn.functional as F
import utils
import models
import data_loader
os.environ["CUDA_VISIBLE_DEVICES"] = '0'
dev = th.device('cuda' if th.cuda.is_available() else 'cpu')
if __name__ == '__main__':
... | StarcoderdataPython |
124702 | import os
import sys
PACKAGE_PARENT = '..'
SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__))))
sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT)))
from src import main
class TestClass:
def test_one(self):
x = "this"
assert '... | StarcoderdataPython |
3387274 | <reponame>saturdayquant/arxiv-topic-graph
import arxiv
import time
def large_query(**kwargs):
"""Partitions large Arxiv query.
Parameters:
**kwargs: dict
Same parameters as arxiv.query() (https://github.com/lukasschwab/arxiv.py)
search_query: string
Ex: "ca... | StarcoderdataPython |
12264 | <filename>app/request/queue.py
import logging
from time import sleep
logger = logging.getLogger(__name__)
class StopRequestQueue:
cursor = 0
queue = None
service = None
current_request = None
request_delay = 0 # seconds
def __init__(self, service, request_delay=10):
self.queue = []
self.service ... | StarcoderdataPython |
1781055 | <filename>captain_hook/services/telegram/events/message.py
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from ...base.events import BaseEvent
import threading
import importlib
from utils import strings
import logging
log = logging.getLogger('hookbot')
class MessageEvent(BaseEvent):
def process(s... | StarcoderdataPython |
3266357 | from absl.testing import absltest
from data_structures import linked_list
class LLNodeTest(absltest.TestCase):
def test_holds_value(self):
node = linked_list.LLNode('str')
self.assertEqual('str', node.value)
node2 = linked_list.LLNode(3.14, next_node=node)
self.assertEqual(3.14, node2.value)
d... | StarcoderdataPython |
3205703 | def calculate_fuel(mass):
return (mass//3) - 2
with open('input.txt') as f:
lines = f.read().splitlines()
masses = map(int, lines)
total_cost = 0
for mass in masses:
while (calculate_fuel(mass) > 0):
mass = calculate_fuel(mass)
total_cost += mass
print(total_cost) | StarcoderdataPython |
3365115 | <reponame>OSPG/sv2
import inspect
def not_private(func):
if inspect.isfunction(func):
if func.__name__[0] != "_":
return True
return False
def is_public_class(obj):
if inspect.isclass(obj):
if obj.__name__[0].isupper():
return True
return False
def get_pub... | StarcoderdataPython |
3219492 | # Copyright (c) 2012-2016 Seafile Ltd.
"""
A set of request processors that return dictionaries to be merged into a
template context. Each function takes the request object as its only parameter
and returns a dictionary to add to the context.
These are referenced from the setting TEMPLATE_CONTEXT_PROCESSORS and used b... | StarcoderdataPython |
1790684 | import subprocess
import pathlib
import os
import shutil
# When you move on versions you can change the values here
MAJOR_VERSION = 0
MINOR_VERSION = 1
# What the name of your app should be
APP_NAME = "simple_folder"
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
def get_build_version():
'''
If there ... | StarcoderdataPython |
4820517 | <filename>MoinMoin/action/RenderAsDocbook.py<gh_stars>1-10
"""
MoinMoin - Render as DocBook action - redirects to the DocBook formatter
@copyright: 2005 MoinMoin:AlexanderSchremmer
@license: GNU GPL, see COPYING for details.
"""
from MoinMoin.Page import Page
def execute(pagename, request):
url = Pag... | StarcoderdataPython |
1669150 | version = "2019-01-03" | StarcoderdataPython |
1623662 | <filename>backend/secrets.py
jwtsecret = 'JWT_SECRET'
API_KEY = 'LASTFM_KEY'
API_SECRET = 'LASTFM_SECRET' | StarcoderdataPython |
175198 | <reponame>tsingdao-Tp/Indigo
import os
import sys
import errno
sys.path.append('../../common')
from env_indigo import *
if not os.path.exists(joinPathPy("out", __file__)):
try:
os.makedirs(joinPathPy("out", __file__))
except OSError as e:
if e.errno != errno.EEXIST:
raise
indigo =... | StarcoderdataPython |
1690744 | <filename>ejercicios/aeropuertos.py<gh_stars>1-10
"""AyudaEnPython: https://www.facebook.com/groups/ayudapython
Recopilamos los registros de los vuelos que ocurrieron durante un día
entre aeropuertos ubicados en Estados Unidos y los organizamos en un
diccionario de diccionarios. Ahora queremos que nos ayudes a
identif... | StarcoderdataPython |
1649315 | ## This file is used to annotate xml files to coco format
import json
import os
import cv2
from xml.dom.minidom import parse
import xml.dom.minidom
if __name__ == '__main__':
path = '../dataset_AgrilFruit_forCounting/exp1/'
# fruit classes
folders = ['lemon', 'custardapple', 'apple', 'pear', 'persim... | StarcoderdataPython |
1685015 | #!/usr/bin/env python3
import argparse
import mcb185
import matplotlib
# In prokaryotic genomes, genes are often predicted based on length
# Long ORFs are not expected to occur by chance
# Write a program that creates a histogram of ORF lengths in random DNA
# Your library should contain new functions for the followi... | StarcoderdataPython |
1680571 | <gh_stars>1-10
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more 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... | StarcoderdataPython |
52450 | <reponame>kindlehl/Py3NES
import argparse
from cpu import CPU
from graphics.graphics import Window
from nes_test import NesTestLog
from ram import RAM
from apu import APU
from ppu import PPU
from rom import ROM
class Nes:
def __init__(self, rom_bytes, testing):
self.rom = ROM(rom_bytes)
# create... | StarcoderdataPython |
1702516 | """DummyFactor API Views"""
from rest_framework.serializers import ModelSerializer
from rest_framework.viewsets import ModelViewSet
from passbook.factors.dummy.models import DummyFactor
class DummyFactorSerializer(ModelSerializer):
"""DummyFactor Serializer"""
class Meta:
model = DummyFactor
... | StarcoderdataPython |
162773 | <filename>backend/output/reports/AgentMatrixReport.py<gh_stars>0
import logging
from collections import Counter
from datetime import datetime
from openpyxl import Workbook
from output.ReportBase import ReportBase
from util.xcel_utils import addFilterAndFreeze, resizeColumnWidth, writeUncoloredRow
class AgentMatrixRe... | StarcoderdataPython |
3335542 | import numpy as np
import random
from collections import namedtuple, deque
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from utils.replay_buffer import ReplayBuffer
class DQNAgent():
"""Interacts with and learns from the environment."""
def __init__(self, st... | StarcoderdataPython |
3391229 | import time
from gromozeka import BrokerPoint, task
# first example function
from gromozeka import Gromozeka, ThreadWorker, ProcessWorker
@task(bind=True)
def test_func_one(self, sleep_time, word):
"""
Args:
self(gromozeka.primitives.Task):
sleep_time(int): Time to sleep
word(str): W... | StarcoderdataPython |
1742659 | <gh_stars>0
from sqlalchemy import Column, ForeignKey, Integer, String, UniqueConstraint
from sqlalchemy.orm import backref, relationship
from fonduer.parser.models.context import Context
class Table(Context):
"""A Table Context in a Document.
Used to represent tables found in a document.
"""
__tab... | StarcoderdataPython |
4823878 | <filename>hackerrank_algorithm_path/Warmup/time_conversion.py<gh_stars>1-10
#https://www.hackerrank.com/challenges/time-conversion
#!/bin/python3
import sys
time = input().strip()
tim=[]
if time[0]=='1' and time[1]=='2' and time[8]=='A' and time[9]=='M':
tim.append(0)
tim.append(0)
for i in range(2,8):
... | StarcoderdataPython |
169835 | """List Autoscale groups."""
# :license: MIT, see LICENSE for more details.
import click
from SoftLayer.CLI.command import SLCommand as SLCommand
from SoftLayer.CLI import environment
from SoftLayer.CLI import formatting
from SoftLayer.managers.autoscale import AutoScaleManager
from SoftLayer import utils
@click.co... | StarcoderdataPython |
1763054 | <reponame>hshrimp/Cail2018_wshong
#encoding='utf-8'
from keras.models import Model
from keras.optimizers import SGD,Adam
from keras.utils import plot_model
from keras.layers import Dense,Dropout,Input,Flatten,Lambda,Activation
from keras.layers import Conv1D,MaxPooling1D,Embedding,BatchNormalization
from keras.utils im... | StarcoderdataPython |
3248453 | """Script to remove background from pictures
This script removes the background from pictures
and set it to any predefined color.
"""
from os import listdir
from os.path import isfile, join
import cv2
import numpy as np
input_folder = "./img/input"
output_folder = "./img/output"
# Parameters
BLUR = 21
CANNY_THRESH... | StarcoderdataPython |
124060 | #!/usr/bin/env python3
# Extended from bwDB - CRUD library for sqlite 3 by <NAME> [http://bw.org/]
import sqlite3
import os
__version__ = '1.0.1'
class ArkDBSQLite:
kQUERY_PARAM_PLACE_HOLDER = '?'
def __init__(self, **kwargs):
"""
db = ArkDBSQLite ( [ table = ''] [, filename = ''] )
... | StarcoderdataPython |
1731154 | # Embeddia Project - Named Entity Recognition
# Copyright © 2020 <NAME> - La Rochelle Université
# Permission is hereby granted, free of charge, to any person obtaining a copy of this
# software and associated documentation files (the "Software"), to deal in the Software
# without restriction, including without limitat... | StarcoderdataPython |
1705993 | """ This module contains functions for computing fire weather metrics.
"""
import logging
import math
from typing import Optional
import rpy2.robjects as robjs
from rpy2.robjects import DataFrame
import rpy2.robjects.conversion as cv
from rpy2.rinterface import NULL
import app.utils.r_importer
from app.utils.singleton ... | StarcoderdataPython |
3226200 | PATH_NONE = "NONE"
PATH_UNION = "UNION"
PATH_INTER = "INTERSECT"
PATH_EXCEPT = "EXCEPT"
PATH_WHERE = "WHERE"
PATH_HAVING = "HAVING"
PATH_PAR = "PARALLEL" # To represent the multiple selection clauses in a single WHERE clause.
VEC_AGGREGATORS = [ 'none', 'max', 'min', 'count', 'sum', 'avg' ]
VEC_OPERATORS ... | StarcoderdataPython |
1727354 | <reponame>IBM/analyze_ecommerce_websites_and_recommend_optimal_price.
import sys
import requests
from bs4 import BeautifulSoup
def main(dict):
response = {}
if dict.get('type') == 1:
url = "http://XXXXXXX.eu-gb.mybluemix.net/"
response = price(url)
elif dict.get('type') == 2:
MRP =... | StarcoderdataPython |
3261306 | import os
import requests
from flask import Flask, render_template, redirect, request, url_for
app = Flask(__name__)
# config
CLIENT_ID = os.getenv("CLIENT_ID")
CLIENT_SECRET = os.getenv("CLIENT_SECRET")
CLIENT_URL = os.getenv("CLIENT_URL")
AS_URL = os.getenv("AS_URL", "https://sso.trade.gov.uk")
PORT = os.gete... | StarcoderdataPython |
3253631 | <filename>package_test/DebugKLDensityRatioEstimation.py
import matplotlib.pyplot as plt
from sklearn.model_selection import KFold
from pyanom.density_ratio_estimation import KLDensityRatioEstimation
import numpy as np
normal_data = np.loadtxt("../input/normal_data.csv", delimiter=",")
error_data = np.loadtxt("../input... | StarcoderdataPython |
3381493 | from werkzeug.security import generate_password_hash, check_password_hash
from flask import Flask, json, render_template, redirect, url_for, jsonify, request, abort
from flask_login import LoginManager, login_user, login_required, logout_user, current_user
import requests
from database import *
from form import *
from ... | StarcoderdataPython |
187859 | from flask import Flask, jsonify, render_template, request
from flask_cors import CORS
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route("/api/user/login", methods=["GET", "POST"])
def login(*args, **kwargs):
# print 'Got request for login'
# print args
... | StarcoderdataPython |
1651196 | from aloxidesdk.icon_network import IconNetwork
from aloxidesdk.eos_network import EosNetwork
ICON_NETWORK = 'ICON Network'
EOS_NETWORK = 'EOS Network'
class AloxideService:
def __init__(self, config):
self.config = config
if ICON_NETWORK == config['type']:
self.icon_network = IconNetwork(config['end... | StarcoderdataPython |
3275341 | <gh_stars>0
#!/usr/bin/env python3
"""A script for assigning PIDs for data files."""
import glob
import logging
import os
import sys
from tempfile import TemporaryDirectory
from typing import Optional
from uuid import UUID
import requests
from requests.exceptions import HTTPError
from data_processing import metadata_... | StarcoderdataPython |
18676 | <filename>django_cassiopeia/views.py
from django.shortcuts import render, HttpResponse
from django_cassiopeia import cassiopeia as cass
from time import sleep
import json
# Create your views here.
def test(request):
return render(request, "test/test.html")
def test_request(request, n):
context = {
"n... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.