id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
6477177 | from datetime import datetime
import json
from sty import fg, rs
from time import time as ctime
from .utils import printheader
class Logger(object):
def __init__(self, quiet: bool = False, time: bool = True):
self.quiet = quiet
self.time = time
self.start = ctime()
def header(self, ti... | StarcoderdataPython |
331632 | # ------------------------------------------------------------------------------
# <auto-generated>
# This code was generated by a tool.
# Changes to this file may cause incorrect behavior and will be lost if
# the code is regenerated.
# </auto-generated>
#
# Copyright (c) Microsoft Corporation. All rights ... | StarcoderdataPython |
6489965 | <filename>Interview Preparation Kit - Python/02. Arrays/003. New Year Chaos.py
# Problem: https://www.hackerrank.com/challenges/new-year-chaos/problem
# Score: 40
| StarcoderdataPython |
9687945 | <reponame>Xewus/Calculator<gh_stars>0
import sys
import unittest
from pathlib import Path
import deck
BASE_DIR = Path(__file__).resolve().parent.parent
sys.path.append(BASE_DIR / "deck")
class TestDeck(unittest.TestCase):
"""Тестирование последовательности `deck.Deck`.
"""
@classmethod
def setUpClas... | StarcoderdataPython |
1628785 | <reponame>lovewsy/patrace
##########################################################################
#
# Copyright 2011 <NAME>
# All Rights Reserved.
#
# 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 ... | StarcoderdataPython |
9645245 | #!/usr/bin/env python
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "blue.settings")
import sys
from rq import Queue, Connection, Worker
# Preload libraries
from utils import redis_conn
import jieba.analyse # import this to load dict
# Provide queue names to listen to as arguments to this script,
# simil... | StarcoderdataPython |
11373226 | <filename>data/gym_onpolicy_dataset.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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by a... | StarcoderdataPython |
4910632 | import logging
import re
# Metadata
NAME = 'sports'
ENABLE = True
TYPE = 'command'
PATTERN = '^!(?P<sport>nba|nfl|mlb|wnba|nhl|cfb) ?(?P<team>.*)?$'
USAGE = '''Usage: ![nhl|nba|wnba|mlb|nfl|cfb] <team_name>
Given a search query, this returns the scores from ESPN for the given sport or team
Example:
> !nb... | StarcoderdataPython |
1771126 | <reponame>ouyang-w-19/decogo
# MINLP written by GAMS Convert at 04/21/18 13:52:23
#
# Equation counts
# Total E G L N X C B
# 33 33 0 0 0 0 0 0
#
# Variable counts
# x b i... | StarcoderdataPython |
1993790 | # Copyright 2019
# Author: <NAME> <https://github.com/fabio-gut>
def idx_to_array_index(idx: int, idxpos0: int):
"""
Converts a nucleotide index to an 0-included array index
:param idx: The index to convert
:param idxpos0: The start index
:return: The index of the element in the array
>>> idx_... | StarcoderdataPython |
11237472 | <reponame>exalearn/oded
# Generated with SMOP 0.41
from libsmop import *
# RyxTheta.m
@function
def RyxTheta(r1=None,c1=None,theta=None,bluringT=None,*args,**kwargs):
varargin = RyxTheta.varargin
nargin = RyxTheta.nargin
# [c, r] = meshgrid(c1, r1);
# if (size(r)~=size(c))
# error('t... | StarcoderdataPython |
3583823 | import glob
import os
import librosa
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import load_file
from matplotlib.pyplot import specgram
batch_size = 290
training_epochs = 59
n_dim = 80
n_hidden_units_one = 280
n_hidden_units_two = 350
sd = 1 / np.sqrt(n_dim)
n_classes = 3
def test():... | StarcoderdataPython |
8157892 | # Lista para cardápio [código_do_produto, nome_do_produto, preço]:
produtos = [[100, "cachorro-quente", 4.50], [101, "Hamburger", 5.00], [102, "Misto", 2.75], [103, "Refrigerante", 3.50]]
#lista produtos comprados
preço_produtos_comprados = []
nome_produtos_comprados = []
# Função de verificar se o código digitado co... | StarcoderdataPython |
8137482 | __ALL__ = ('TFT240x135',)
import digitalio
import board
from PIL.Image import Image
from adafruit_rgb_display import st7789
# Setup SPI bus using hardware SPI:
from raspberry_pi.bases import BaseDisplay
spi = board.SPI()
class GPIOPins:
CE0 = digitalio.DigitalInOut(board.CE0)
D25 = digitalio.DigitalInOut(b... | StarcoderdataPython |
351868 | import unittest
from unittest.mock import Mock, patch
from .common import header, body, params, responses, R
from union.token import Token
from union.enquiry import Enquiry
from union.user import User
@patch('requests.post')
def test_access_token_generator(mock_post):
data = responses['AccessTokenGenerator']
... | StarcoderdataPython |
8023978 | #!/usr/bin/env python
import unittest
from bst import *
class BSTTest(unittest.TestCase):
def setUp(self):
self.tree1 = BST()
self.tree1.insert(23)
self.tree1.insert(8)
self.tree1.insert(4)
self.tree1.insert(16)
self.tree1.insert(15)
self.tree1.insert(42)
... | StarcoderdataPython |
1722810 | <gh_stars>1-10
import os
import numpy as np
import pandas as pd
import tarfile
import shutil
from PIL import Image, ImageDraw
def CUB_loader(path=''):
"""unpacked CUB dataset loader
source for dataset http://www.vision.caltech.edu/visipedia/CUB-200-2011.html
Parameters
----------
path_folde... | StarcoderdataPython |
5043747 | from typing import Any
from settings.router import router
from openpype.lib.postgres import Postgres
from openpype.types import Field, OPModel
class AttributeModel(OPModel):
name: str
title: str
example: str
description: str
attribType: str
scope: list[str] = Field(default_factory=list)
... | StarcoderdataPython |
9675944 | """
This script isn't a part of the CLI tool, but a helper script for image downloading from ajapaik.ee API.
"""
import json
import urllib.request
from pathlib import Path
def get_ajapaik_image_locations(
location='https://ajapaik.ee/api/v1/album/state/?id=22197&limit=100',
dimension='320') -> di... | StarcoderdataPython |
109482 | <gh_stars>0
def valid_palindrome(str):
left, right = 0, len(str) - 1
while left < right:
if not str[left].isalnum():
left += 1
elif not str[right].isalnum():
right -= 1
else:
if str[left].lower() != str[right].lower():
print('False'... | StarcoderdataPython |
1783045 | # https://dl.acm.org/citation.cfm?doid=965400.111112
import sys
import os.path
import time
import res
from bs4 import BeautifulSoup
import urllib
import urllib.parse
import urllib.request
import requests
import random
# comment this code ;)
def getRandomUserAgent():
return res.USER_AGENT_ST... | StarcoderdataPython |
5197253 | <gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2017/2/20 下午1:38
# @Author : sws
# @Site : 使用 ForkingMixin
# @File : forking_mixin_socket_server.py
# @Software: PyCharm
import os
import socket
import threading
import SocketServer
SERVER_HOST = 'localhost'
SERVER_PORT = 0 # 动态是设置端口
BUF_S... | StarcoderdataPython |
4886738 | #!/usr/bin/env python3
# Multiples of 3 and 5
def main():
print(sum([i if (i % 3 == 0 or i % 5 == 0) else 0 for i in range(0, 1000)]))
if __name__ == '__main__':
main()
| StarcoderdataPython |
5049077 | <reponame>andela/ah-infinity-stones
import math
from authors.apps.articles.models import (Article, Comment, LikeDislike,
ArticleRating, FavoriteArticle,
ArticleReporting)
from rest_framework import generics
from .serializers import (Ar... | StarcoderdataPython |
4939048 | ##
#
# This file contains custom optimization functions for use with
# scipy.minimize.
#
# As noted in the documentation, each routine takes a function (func(x))
# and an initial guess x0, and returns an OptimizeResult object.
#
# See https://docs.scipy.org/doc/scipy/reference/tutorial/optimize.html#custom-minimizers
... | StarcoderdataPython |
4865918 | import pymongo
client = pymongo.MongoClient('URL')
db = client['database_name']
collecction = db['collection_name']
# Print all collection names
print(db.list_collection_names())
# Insert one record
x = collection.insert_one(dict_obj)
# Insert multiple
x = collection.insert_many(list_of_dicts)
# Find one
x = coll... | StarcoderdataPython |
3263531 | #
# Copyright (c) 2013-2021 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
# -*- encoding: utf-8 -*-
#
from cgtsclient.common import base
from cgtsclient import exc
CREATION_ATTRIBUTES = ['confirmed', 'name', 'services', 'capabilities',
'tier_uuid', 'cinder_pool_gib', 'glan... | StarcoderdataPython |
9796444 | <filename>integration/images.py<gh_stars>0
# from cri_api import AuthConfig
from cri_api.channel import Channel
from cri_api.images import Images
channel = Channel.from_env()
images = Images(channel)
print(images.list_images())
images.pull_image("busybox")
print(images.get_image("busybox"))
print("*" * 70)
[print(f"{i... | StarcoderdataPython |
6558365 | from nonebot import on_command, CommandSession
import nonebot, random
bot = nonebot.get_bot()
@on_command('mute_me', aliases=('晚安', 'sleep', '禅定', '馋腚'))
async def mute_me(session: CommandSession):
sendFlag = True
my_id = await bot.get_login_info()
message_id = session.event['message_id']
user_id = se... | StarcoderdataPython |
6400583 | from common import *
def apply_mask(number: int, mask: str) -> int:
# There has to be a better way to do this... but oh well
# it works, after all
value = number_to_base(number, 2).zfill(len(mask))
combi = ""
for (v, m) in zip(value, mask.lower()):
if m == "x":
combi += v
... | StarcoderdataPython |
3337358 | <reponame>Splendens/atlas_biodiv_pdl<gh_stars>1-10
# coding: utf-8
from sqlalchemy import Boolean, Column, Date, DateTime, Integer, MetaData, String, Table, Text
from geoalchemy2.types import Geometry
from sqlalchemy.sql.sqltypes import NullType
from sqlalchemy.orm import mapper
from sqlalchemy.ext.declarative imp... | StarcoderdataPython |
3599616 | import numpy as np
import matplotlib.pyplot as plt
from load_data import responses_strong, stimulus_strong
from math import floor
| StarcoderdataPython |
11291497 | # /usr/bin/python3.9
import os
import pathlib
import json as json
path = pathlib.Path(__file__).parent.absolute()
resultFolders = list(filter(lambda x: "Results_" in x, os.listdir(path)))
results = {}
for folder in resultFolders:
results[folder] = {}
for file in os.listdir(folder):
if "result_" not... | StarcoderdataPython |
5062685 | <filename>pydotlib.py
# A Python based Liberty (dotlib) file lexer
import ply.lex as lex
reserved = {
'library' : 'LIBRARY',
'define' : 'DEFINE',
'define_group' : 'DEFINE_GROUP',
'cell' : 'CELL',
'pin' : 'PIN',
'bus' : 'BUS',
'direction' : 'DIRECTION',
'input' : 'IO_DIR',
'output' ... | StarcoderdataPython |
6658555 | """Defines a class for holding a vocabulary set."""
import string
from typing import List, Tuple, Type, Dict
import torch
from pycrf.nn.utils import sort_and_pad
SourceType = Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]
TargetType = Type[torch.Tensor]
class Vocab:
"""
Class... | StarcoderdataPython |
3476161 | <reponame>gcfc/introtodeeplearning
import cv2
import os
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import time
import h5py
import sys
import glob
IM_SHAPE = (64, 64, 3)
def plot_image_prediction(i, predictions_array, true_label, img):
predictions_array, true_label, img = predictions_... | StarcoderdataPython |
1993035 | import numpy as np
import tensorflow as tf
from tensorflow.python import keras
from tensorflow.python.ops import array_ops
from odin.bay.random_variable import RandomVariable as RV
from odin.bay.vi.autoencoder.beta_vae import BetaVAE
class MultitaskVAE(BetaVAE):
r""" Multi-tasks VAE for semi-supervised learning
... | StarcoderdataPython |
9614565 | ##############################################################################
#
# <NAME>
# <EMAIL>
#
# References:
# SuperDataScience,
# Official Documentation
#
# RANDOM FOREST REGRESSION
##############################################################################
# Importing the librari... | StarcoderdataPython |
6701148 | from typing import List
from fractions import Fraction
from abc import ABC, abstractmethod
import spacy
import string
import random
import requests
import pandas as pd
import diskcache
from somajo import SoMaJo
def has_space(text: str) -> bool:
return any(x.isspace() for x in text)
class Tokenizer(ABC):
def... | StarcoderdataPython |
9637008 | <gh_stars>1-10
__all__ = ["HTMLGene", "Train", "Validate", "Optimizer", "Others", "Dataset"]
from .Train import train
from .Validate import validate
from .HTMLGene import RenderParas, ImageParas, ModelParas
| StarcoderdataPython |
4855357 | <reponame>kaydoh/scale
from __future__ import unicode_literals
import datetime
import django
from django.test import TransactionTestCase
from django.utils.timezone import utc
from mock import patch
import batch.test.utils as batch_test_utils
import job.test.utils as job_test_utils
import recipe.test.utils as recipe_... | StarcoderdataPython |
11292957 | <reponame>rypaik/PYTHON<filename>py_projects_boilerplates/py_app_log_pytest_boiler/app/modules/hello_world/tools/tools.py
#from config import console, log
from config import console
def say_hello(message):
print(message)
console.print(message, style="bold blue")
# log.info(message)
return message
| StarcoderdataPython |
4902166 | <reponame>xzhan96/chromium.src
# Copyright (C) 2010 Research in Motion Ltd. 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 copyright
... | StarcoderdataPython |
6486969 | <reponame>neelabhro/CLEAVE<filename>cleave/core/client/statebase.py
# Copyright (c) 2020 KTH Royal Institute of Technology
#
# 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... | StarcoderdataPython |
3593378 | <reponame>m4ta1l/doit
from doit.tools import run_once
def task_get_pylogo():
url = "http://python.org/images/python-logo.gif"
return {'actions': ["wget %s" % url],
'targets': ["python-logo.gif"],
'uptodate': [run_once],
}
| StarcoderdataPython |
3447887 | <reponame>sjplautz/Education-Projects
import csv
import itertools
import sys
PROBS = {
# Unconditional probabilities for having gene
"gene": {
2: 0.01,
1: 0.03,
0: 0.96
},
"trait": {
# Probability of trait given two copies of gene
2: {
True: 0.65,
... | StarcoderdataPython |
228834 | <filename>plottify/__init__.py
from . import plot, poly, rle, utils | StarcoderdataPython |
11308184 | <reponame>pyrustic/codegame
from codegame.core import github_client
def show_repo_description(kurl, owner, repo):
cache = github_client.repo_description(kurl, owner, repo)
status_code, status_text, data = cache
if status_code not in (200, 304):
print("Failed to get the repo description")
i... | StarcoderdataPython |
3213206 | """Tests related to format_helper() function."""
import pandas as pd
import pytest
from diglett.output import format_helper
@pytest.fixture
def input_df() -> pd.DataFrame:
"""Create a DataFrame to use as input for tests."""
return pd.DataFrame({'num_': [1, 2, 3, 4], 'pct_': [0.9, 0.9, 0.8, 0.1]})
def test... | StarcoderdataPython |
145994 | <reponame>strean/push2-python<gh_stars>0
import weakref
class AbstractPush2Section(object):
"""Abstract class to be inherited when implementing the interfacing with specific sections
of Push2. It implements an init method which gets a reference to the main Push2 object and adds
a property method to get it... | StarcoderdataPython |
3318453 | from __future__ import annotations
import re
from bisect import bisect
from functools import reduce
from re import sub
from string import ascii_lowercase
from typing import Callable
from typing import Iterable
from typing import cast
from hypothesis.strategies import SearchStrategy
from hypothesis.strategies import c... | StarcoderdataPython |
3472387 | from core.viewsets import ModelViewSet
from core.models import Participant
from core.participants.serializers import ParticipantSerializer
from core.permissions import FRONT_DESK, CASE_MANAGER, ADMIN
class ParticipantViewSet(ModelViewSet):
"""
API endpoint that allows Participants to be viewed or edited
""... | StarcoderdataPython |
3456116 | import pytesseract
from PIL import Image
image = Image.open('1357042419_3300.jpg')
vcode = pytesseract.image_to_string(image)
print (vcode) | StarcoderdataPython |
9763936 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 24 01:17:10 2021
@author: KristinaSig
"""
import unittest
import pandas as pd
import numpy as np
from code.feature_extraction.avg_len_flag import AvgLenFeature
class AvgLenTest(unittest.TestCase):
def setUp(self):
self.INPUT_COLUM... | StarcoderdataPython |
344186 | <reponame>LionelMassoulard/aikit<filename>tests/test_model_definition.py<gh_stars>0
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 14 11:40:18 2018
@author: <NAME>
"""
import copy
from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier
from sklearn.linear_model import LogisticRegression
from aiki... | StarcoderdataPython |
151656 | <reponame>urumtsev/ok-esputnik
__all__ = (
'ESputnikException',
'InvalidAuthDataError',
'IncorrectDataError'
)
class ESputnikException(AttributeError):
pass
class InvalidAuthDataError(ESputnikException):
def __init__(self, code, message):
self.code = code
self.message = message
... | StarcoderdataPython |
3529973 | <reponame>llcoolmxdx5/series<filename>wordpress/run.py
import csv
import sys
from datetime import datetime, timedelta
from main import main as maintestlink
date = str(datetime.today().date() - timedelta(days=1))
def main():
with open(sys.path[0]+r'\config.csv', 'r', encoding='utf-8') as csvfile:
reader =... | StarcoderdataPython |
6575396 | from .connection import Connection
from .file_sync import rsync
from . import process
from . import connection
__version__ = '0.0.29'
| StarcoderdataPython |
3401940 | <reponame>yx222/BikeSim
# Examples showing how users should use the code. For deisgn guidance
# NOT WORKING EXAMPLES!
# Create a bike object
sc_5010 = BikeKinematics.from_json('some_json_file')
# Sweep through travel, get bike properties
# Questions:
# 1) which properties are just rear travel related?
# 2) which prop... | StarcoderdataPython |
3392729 | <filename>core/file_analyzer.py
import asyncio
import os
import subprocess
import json
from threading import Thread, Timer
from typing import Any, Dict, List, Union
from .phantoms import run_target_phantom
from .window_manager import get_window_manager, is_window_ignored
import sublime
import sublime_plugin
class _T... | StarcoderdataPython |
4802725 | import fault
import magma
from hwtypes import BitVector, Bit
from fault.value import AnyValue, UnknownValue, HiZ
from fault.real_type import RealType, RealKind
from fault.array import Array
from fault.select_path import SelectPath
from hwtypes.adt import Enum
def make_value(type_, value):
if issubclass(type_, Rea... | StarcoderdataPython |
157244 | <reponame>grayvalley/sanbox
from decimal import *
import time, random
from enum import Enum
class OrderType(Enum):
Limit = 1
Market = 2
def order_type_to_str(order_type):
if order_type == OrderType.Limit:
return 'LMT'
elif order_type == OrderType.Market:
return 'MKT'
else:
... | StarcoderdataPython |
6703789 | <gh_stars>0
from .errors.error import Error
from .views.view import View
from .tools.helper import Helper
from .tools.build import Build
from .emitters.emitter import Emitter
from .tools.assembler import get_root_path, get_mode
from .models.mappers.mapper import Mapper
from .models.services.service import Service
from ... | StarcoderdataPython |
4991174 | #!/usr/bin/env python3
from setuptools import setup
setup(
name='dinspect',
install_requires=[
'matplotlib',
'numpy'
],
packages=['dinspect'],
python_requires='>=3.6',
entry_points={
'console_scripts': [
'dinspect = dinspect.__main__:main',
]
}
... | StarcoderdataPython |
9780187 | <filename>venv/Lib/site-packages/pandas/tests/series/methods/test_between.py<gh_stars>1000+
import numpy as np
import pytest
from pandas import (
Series,
bdate_range,
date_range,
period_range,
)
import pandas._testing as tm
class TestBetween:
# TODO: redundant with test_between_datetime_values?
... | StarcoderdataPython |
6553991 | <reponame>horizon-blue/beanmachine-1
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""Error reporting for internal compiler errors"""
import os
from ast import AST
from tempfile import ... | StarcoderdataPython |
6665262 | <filename>src/conversation.py
# -*- coding: utf-8-*-
from src.brain import Brain
import logging, time
from src.components import logger
class Conversation:
"""
交谈
"""
def __init__(self, mic, profile, iot_client):
"""
初始化
:param mic:
:param persona:
:param profi... | StarcoderdataPython |
145063 |
import os
import sys
TRASH = [
'bottle',
'cup',
'fork',
'knife',
'spoon'
'banana',
'apple',
'sandwich',
'orange',
'broccoli',
'carrot',
'hot dog',
'pizza',
'donut',
'cake'
]
YOLO_PATH = os.path.join(sys.path[0], 'yc')
IMAGE_PATH = os.path.join(sys.path[0]... | StarcoderdataPython |
6469873 | <gh_stars>0
def getMinuteEffect(leaveMM,entranceMM):
minuteDiff = leaveMM - entranceMM
if(minuteDiff > 0):
return 1
else :
return -1
def getCost(entranceHH, leaveHH,minuteEffect):
cost = 2
hourDiff = leaveHH - entranceHH
if(minuteEffect >0):
hourDiff += 1
if (hourD... | StarcoderdataPython |
11246528 | <reponame>cku328/submarine<filename>submarine-sdk/pysubmarine/tests/ml/pytorch/test_metric_pytorch.py
# 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 AS... | StarcoderdataPython |
9775640 | from django import forms
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.db import transaction
from django.db.models import F
from django.shortcuts import get_object_or_404, redirect, render
from Organizations.common import get_managed_user, confirm_management_... | StarcoderdataPython |
202595 | <gh_stars>0
import cv2
import numpy as np
import os
from random import shuffle
from tqdm import tqdm
TEST_DIR = os.getcwd() + '/test'
IMG_SIZE = 50
LR = 1e-3
MODEL_NAME = 'healthyvsunhealthy-{}-{}.model'.format(LR, '2conv-basic')
def process_test_data():
testing_data = []
for img in tqdm(os.listdir(TEST_DIR... | StarcoderdataPython |
245178 | <filename>pycharles/session.py
import request
import json
def _assign_indexes(charles_requests):
current_index = 0
for _ in charles_requests:
_.index = current_index
current_index += 1
class CharlesSession(object):
"""Charles session object, initialized with a path to the file.
At ... | StarcoderdataPython |
151652 | <reponame>thiagofigcosta/pontomais-cli<filename>setup.py
from pontomais import __version__
from setuptools import setup, find_packages
from os import path
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'requirements.txt'), encoding='utf-8') as f:
requirements = f.read().s... | StarcoderdataPython |
9655963 |
"""Perform analysis on detections on a dataset."""
# from __future__ import absolute_import
# from __future__ import division
# from __future__ import print_function
# from __future__ import unicode_literals
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import argparse
# import cv2 # NOQA (... | StarcoderdataPython |
9724015 | <filename>src/app.py
import os
from flask import Flask
from flask_login import LoginManager
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager
from flask_jwt_extended import JWTManager
from src.models import db, init_db
from src.models.user import User
from src.models.todo import Todo ... | StarcoderdataPython |
3550704 | from rest_framework import serializers
from .models import ImgModel
class ImageSerializer(serializers.ModelSerializer):
class Meta:
model = ImgModel
fields = ('img',)
| StarcoderdataPython |
1894100 | import hypothesis
import hypothesis.nn
import hypothesis.nn.resnet
import numpy as np
import torch
from .default import batchnorm as default_batchnorm
from .default import channels as default_channels
from .default import convolution_bias as default_convolution_bias
from .default import depth as default_depth
from .de... | StarcoderdataPython |
5011686 | <gh_stars>0
# -*- coding: utf-8 -*-
import sqlite3
import time
sql = u"INSERT INTO textlogs (filename, text, created_at) values (?, ?, ?)"
db_file = './textlog.sqlite3'
def add_log(filename, text):
conn = sqlite3.connect(db_file)
cur = conn.cursor()
cur.execute(sql, (filename, text, long(time.time())))
... | StarcoderdataPython |
6420481 | # -*- coding: utf-8 -*-
# Copyright (c) 2012-2015, <NAME> <<EMAIL>>
# License: BSD New, see LICENSE for details.
from monad.types import Identity
from monad.types import Maybe
from monad.types import Either
testee = [
Identity,
Maybe,
Either,
]
test_range = range(-100, 100)
ids = [t.__name__ for t in teste... | StarcoderdataPython |
9621937 | from ...parsers.academia import Sem4_My_Attendance
from ... import helpers
def get(self, name):
if not self.methods:
return helpers.err('no handlers bind.')
if name not in self.methods.keys():
return helpers.err('no such handler bind.')
url = 'https://academia.srmuniv.ac.in/liveViewHeader.do';
payload = {
... | StarcoderdataPython |
9769282 | #!/usr/bin/env python
from operator import itemgetter
import sys
current_word = None
current_count = 0
word = None
wordcount = {}
count_list = []
def addToDictionary(current_word, current_count):
wordkey = current_word.split("_")[0]
if wordcount.get(wordkey) == None:
count_list = []
count_li... | StarcoderdataPython |
3233738 | <filename>DataHandler/echart_handler.py<gh_stars>0
#!/usr/local/bin/python2.7
# -*- coding: utf-8 -*-
#
# PyeCharts服务程序集
# ===================
# 2018.5.10 @Chengdu
#
#
from __future__ import unicode_literals
import logging
from pyecharts import Sankey,\
Page,Style,\
Boxplot,\
HeatMap,\
Geo,\
... | StarcoderdataPython |
8006290 | from transbank.common.model import CardDetail
class TransactionCreateResponse(object):
def __init__(self, token: str, url: str):
self.token = token
self.url = url
def __repr__(self):
return "token: {}, url: {}".format(self.token, self.url)
| StarcoderdataPython |
1600462 | <filename>www/tests/packed_arguments.py
# unpacking function parameters
args = [3,16,2]
log(range(*args))
log(range(3,16,2))
def parrot(voltage, state='a stiff', action='voom'):
log("-- This parrot wouldn't", action, end=' ')
log("if you put", voltage, "volts through it.", end=' ')
log("E's", state, "!")
d... | StarcoderdataPython |
3255155 | import os
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
pod_ip = os.getenv('POD_IP')
if pod_ip is None:
pod_ip = '<unknown>'
node_ip = os.getenv('NODE_IP')
if node_ip is None:
node_ip = '<unknown>'
return 'Howdy folks! 👍\nPOD IP: %s\nNODE IP: %... | StarcoderdataPython |
387227 | <filename>src/probnum/filtsmooth/gaussfiltsmooth/unscentedtransform.py
"""See BFaS; p.
84f.
"""
import numpy as np
__all__ = ["UnscentedTransform"]
class UnscentedTransform:
"""Used for unscented Kalman filter.
See also p. 7 ("Unscented transform:") of [1]_.
Parameters
----------
dimension : ... | StarcoderdataPython |
3278462 | <filename>nara_wpe/torch_wpe_real_imag.py<gh_stars>1-10
import numpy as np
import torch
import torch_complex.functional
from torch_complex.tensor import ComplexTensor
from nara_wpe.torch_wpe import build_y_tilde as _build_y_tilde
def build_y_tilde(Y, taps, delay):
"""
Note: The returned y_tilde consumes a si... | StarcoderdataPython |
4873937 | """Audit Logs API is a set of APIs for monitoring what’s happening in your Enterprise Grid organization.
Refer to https://slack.dev/python-slack-sdk/audit-logs/ for details.
"""
| StarcoderdataPython |
6617113 | <gh_stars>0
from tkinter import *
import pyperclip
root = Tk()
root.geometry("900x900")
pass_details = StringVar()
myList = []
def wifi_pass():
import subprocess
global myList
data = subprocess.check_output(['netsh', 'wlan', 'show', 'profiles']).decode('utf-8').split('\n')
profiles = [i.spli... | StarcoderdataPython |
63613 | import os
import math
import gzip
import csv
import time
import torch
import torch.optim as optim
import torch.utils.data as data_utils
from sklearn.model_selection import train_test_split
from tqdm import tqdm
# import matplotlib.pyplot as plt
import numpy as np
from crf import CRF
# import Data Loa... | StarcoderdataPython |
5066803 | <reponame>AmeyaHarmalkar/DeepAb
import h5py
import torch
import torch.utils.data as data
import torch.nn.functional as F
from deepab.util.tensor import pad_data_to_same_shape
class H5PairedSeqDataset(data.Dataset):
def __init__(self, filename, onehot_prim=True):
"""
:param filename: The h5 file f... | StarcoderdataPython |
3312225 | from direct.distributed.MsgTypes import * | StarcoderdataPython |
351741 | <filename>GPS/rtkGPS_anlyse.py<gh_stars>0
#!/usr/bin/env python
# license removed for brevity
import rospy
from beginner_tutorials.msg import rtkGPSmessage
import pylab
import math
import matplotlib
north = []
east = []
yaw =[]
count_yaw=[]
north_sparse = []
east_sparse = []
def callback1(data):
if data.vaild_fl... | StarcoderdataPython |
3279050 | <reponame>kprzybyla/testplates<gh_stars>0
import random
from typing import (
Any,
TypeVar,
List,
Final,
)
from resultful import unwrap_success
from hypothesis import (
assume,
given,
strategies as st,
)
from testplates import is_one_of
from tests.strategies import (
st_anything_comp... | StarcoderdataPython |
3298319 | # Copyright (c) 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Entry point for interacting with depot_tools from recipes."""
from recipe_engine import recipe_api
class DepotToolsApi(recipe_api.RecipeApi):
@pro... | StarcoderdataPython |
1665066 | # Init
result = Window(350, 350, "All Supported Widgets")
tabView = TabView(result)
fooTab = tabView.addTab("foo")
barTab = tabView.addTab("bar")
bazTab = tabView.addTab("baz")
label = Label(fooTab.view, text="Label")
label.font = Font("Verdana", 12, [FontTrait.Bold, FontTrait.Italic])
label.textColor = Color(0.42, 0.4... | StarcoderdataPython |
317063 | num = []
par = []
impar = []
for i in range(20):
num.append(float(input()))
print(num)
for i in num:
if i % 2 == 0:
par.append(i)
else:
impar.append(i)
print(par)
print(impar)
| StarcoderdataPython |
3453761 | import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QMainWindow, QSpinBox
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("My App")
widget = QSpinBox() # main widget
widget.setMinimum(-10)
widget.se... | StarcoderdataPython |
6411106 | <filename>ai/models/detectron2/labels/torchvisionClassifier/resnet.py
'''
2021 <NAME>
'''
from ai.models.detectron2.genericDetectronModel import GenericDetectron2Model
from ai.models.detectron2.labels.torchvisionClassifier import GeneralizedTorchvisionClassifier, DEFAULT_OPTIONS
class ResNet18(GeneralizedTorchvi... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.