id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
8165341 | <reponame>faical-yannick-congo/yappi
import time
import threading
import yappi
def foo():
time.sleep(0.1)
def profileme():
for i in range(5):
mythread = t()
mythread.start()
mythread.join()
foo()
class t(threading.Thread):
def run(self):
self.foo2()
... | StarcoderdataPython |
6567409 | """
Test basic functionality for loading datasets.
"""
import numpy as np
import numpy.testing as npt
import pytest
from pygmt.datasets import (
load_earth_relief,
load_japan_quakes,
load_ocean_ridge_points,
load_sample_bathymetry,
load_usgs_quakes,
)
from pygmt.exceptions import GMTInvalidInput
d... | StarcoderdataPython |
3266415 | # Copyright (c) 2022 <NAME>
# This software is published under MIT license. Full text of the license is available at https://opensource.org/licenses/MIT
from basal.ble import Ble
from basal.logging import Logging
from basal.planner import Planner
from compilations.chassis import Chassis, Speed, Manoeuver, Direction
... | StarcoderdataPython |
3287959 | <reponame>augustuswm/flagsmith-api<filename>src/sales_dashboard/views.py
import json
from app_analytics.influxdb_wrapper import (
get_event_list_for_organisation,
get_events_for_organisation,
)
from django.contrib.admin.views.decorators import staff_member_required
from django.core.paginator import Paginator
f... | StarcoderdataPython |
6420138 | """Configuration for neophile."""
from __future__ import annotations
from pathlib import Path
from typing import List, Optional
from pydantic import BaseModel, BaseSettings, Field, SecretStr
from ruamel.yaml import YAML
from xdg import XDG_CACHE_HOME
__all__ = ["Configuration"]
class GitHubRepository(BaseModel):
... | StarcoderdataPython |
3332937 | # -*- coding: utf-8 -*-
'''
Clon de Space Invaders
(Basado en un script original de <NAME>)
A partir de un ejercicio de <NAME>
'''
import pygame
from pygame.locals import *
from starwarslib import *
from random import randint
random.seed()
pygame.init()
visor = pygame.display.set_mode( (ANCHO, ALTO) )
pygame.displ... | StarcoderdataPython |
170505 | <filename>nookipedia/middlewares.py
from flask import abort
from nookipedia.errors import error_response
from nookipedia.db import query_db
# Check if client's UUID is valid:
def authorize(db, request):
if request.headers.get("X-API-KEY"):
request_uuid = request.headers.get("X-API-KEY")
elif request.a... | StarcoderdataPython |
186650 | from django.conf.urls import url, include
import views
from rest_framework.routers import DefaultRouter
user_router = DefaultRouter()
user_router.register(r'register', views.UserViewSet)
urlpatterns = [
url(r'^', include(user_router.urls)),
]
| StarcoderdataPython |
3456269 | from bunch import Bunch
def spawner_conf_ok():
spawner_conf = Bunch()
spawner_conf.cloud_user = 'user'
spawner_conf.cloud_userpassword = '<PASSWORD>'
spawner_conf.cloud_url = 'https://api.noo.cloud/keystone/v3/auth/tokens'
spawner_conf.cloud_region = 'region'
spawner_conf.cloud_project = 'cloudproject'
spawner_... | StarcoderdataPython |
206822 | <gh_stars>1-10
import unittest
import os
from os.path import expanduser
import torch
from torchvision.datasets import CIFAR10, MNIST
from torchvision.datasets.utils import download_url, extract_archive
from torchvision.transforms import ToTensor
from avalanche.benchmarks import dataset_benchmark, filelist_benchmark,... | StarcoderdataPython |
9736511 | import os.path
MAIN_VERSION = '0.0.6'
SUB_VERSION = 'beta'
VERSION = MAIN_VERSION + SUB_VERSION
DISCORD_MSG_CHAR_LIMIT = 2000
| StarcoderdataPython |
3372870 | from PyQt5.QtGui import QImage
import numpy as np
from skimage.color import gray2rgb
from skimage.transform import rescale
def converted_to_normalized_uint8(image):
if image.dtype != np.uint8 or image.max() != 255:
if image.max() != 0:
image = image / image.max() * 255
image = image.as... | StarcoderdataPython |
66216 | # -*- coding: utf-8 -*-
from jetfactory.controller import BaseController, Injector, route, input_load, output_dump
from jetfactory.schema import ParamsSchema
from jet_guestbook.service import VisitService, VisitorService
from jet_guestbook.schema import Visit, Visitor, VisitNew
class Controller(BaseController):
... | StarcoderdataPython |
8125964 | <filename>example/app.py
from fastapi import FastAPI
from django.apps import apps
from django.conf import settings
apps.populate(settings.INSTALLED_APPS)
app = FastAPI(title='Fast ORM Example')
from example.views import example_router # noqa: E402
app.include_router(prefix='/examples', router=example_router)
| StarcoderdataPython |
3556663 | import ROOT
import hftools.plotting
import sys
def main():
filename = sys.argv[1]
preplot = sys.argv[2]
postplot = sys.argv[3]
f = ROOT.TFile.Open(filename)
ws = f.Get('combined')
hftools.plotting.quickplot(
ws,
'channel1',
'x',
['background','signal'],
... | StarcoderdataPython |
292273 | #!/usr/bin/env python
""" Problem 50 daily-coding-problem.com """
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def __repr__(self):
return self.value
def evaluate(root: Node) -> int:
left, right = "", ... | StarcoderdataPython |
9751110 | <filename>lyapunov_reachability/speculation_ddpg/ddpg.py
import os
import pickle
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from lyapunov_reachability.speculation_ddpg.base import ContinuousBase
from lyapunov_reachability.common.utils import init_weights
from lyapunov_r... | StarcoderdataPython |
11288377 | from austin_heller_repo.socket import ServerSocketFactory, ServerSocket, ClientSocket, json, time, start_thread, os, get_machine_guid, get_module_from_file_path, try_mkdir
from austin_heller_repo.api_interface import ApiInterfaceFactory
import network
from src.austin_heller_repo.transmission_parser import ReceiveJsonTr... | StarcoderdataPython |
4910300 | __author__ = 'Liu'
import unittest
from Tarefa8.anagrama import Anagrama
class AnagramaTests(unittest.TestCase):
'''
'' e '' retorna verdadeiro
' ' e '' retorna verdadeiro
'a' e 'a' retorna verdadeiro
'a' e 'a ' retorna verdadeiro
'ab' e 'ab' retorna verdadeiro
'ba' e 'ab' retorna ve... | StarcoderdataPython |
3305311 | <reponame>oimokenp/LDA
# coding=utf8
import logging
import os
import gensim
from pyknp import Juman
from gensim import corpora, models
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
name = 'xxxx'
num = 0
#Jumanppオブジェクト
jumanpp = Juman()
if __name__ == '__main__':
#ト... | StarcoderdataPython |
5138381 | import datetime
from accounts.models import Managers, Tenants
from complaints.models import Complaints, UnitReport
from config.settings import DEFAULT_FROM_EMAIL
from django.contrib import messages
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required, user_passes_tes... | StarcoderdataPython |
12377 | <gh_stars>0
"""
Modifique as funções que foram criadas no desafio 107 para
que elas aceitem um parametro a mais, informando se o valor
retornado por elas vai ser ou não formatado pela função
moeda(), desenvolvida no desafio 108.
"""
from Aula22.ex109 import moeda
from Aula22.ex109.titulo import titulo
preco = float(... | StarcoderdataPython |
348090 | # model settings
weight_root = '/home/datasets/mix_data/iMIX/data/models/detectron.vmb_weights/'
model = dict(
type='M4C',
hidden_dim=768,
dropout_prob=0.1,
ocr_in_dim=3002,
encoder=[
dict(
type='TextBertBase', text_bert_init_from_bert_base=True, hidden_size=768, params=dict(num_... | StarcoderdataPython |
1730110 | <reponame>eedlez/deepracer-utils
import sys
import deepracer.boto3_enhancer
def main():
if "install-cli" in sys.argv:
force = True if "--force" in sys.argv else False
deepracer.boto3_enhancer.install_deepracer_cli(force)
elif "remove-cli" in sys.argv:
deepracer.boto3_enhancer.remove_d... | StarcoderdataPython |
5077606 | #!usr/bin/env python3
# -*- coding: utf-8 -*-
"""
pytest demo module by defining tests as functions.
The module name must start with "test_" or end with "_test".
"""
__author__ = '<NAME>'
import sys
import pytest
from pytest_for_python.src.codes import MyDict
# Use pytest.mark.skip decorator if you want to simpl... | StarcoderdataPython |
9738277 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv
import pdfkit
import requests
import os, errno
import logging
import urllib.parse
import urllib.request
from urllib.error import HTTPError
from bs4 import BeautifulSoup
# Constants
LIBI_URL = 'http://libi.local'
LIBI_URL_PREFIX = 'http://libi.local/'
OUTPUT_PATH... | StarcoderdataPython |
3327906 | <reponame>yhwang/kfp-tekton<filename>sdk/python/tests/compiler/testdata/condition_custom.py
# Copyright 2020 kubeflow.org
#
# 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.a... | StarcoderdataPython |
1791451 | <reponame>d-wizard/thermopi
import os
import argparse
import json
import time
from datetime import datetime
import ipc
ipcSocketPath = os.path.split(os.path.realpath(__file__))[0] + os.sep + 'ipcSocket'
################################################################################
# Logging
#######... | StarcoderdataPython |
3305077 | # ---
# jupyter:
# jupytext:
# formats: ipynb,py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.13.7
# kernelspec:
# display_name: Python [conda env:.conda-bandit_nhgf]
# language: python
# name: conda-... | StarcoderdataPython |
9756087 | <reponame>Jumpscale/ays9<filename>tests/test_services/test_delete_action_runsteps/actions.py
def init_actions_(service, args):
"""
this needs to returns an array of actions representing the depencies between actions.
Looks at ACTION_DEPS in this module for an example of what is expected
"""
# so... | StarcoderdataPython |
3268294 | import unittest
from honeygrove.core.FilesystemParser import FilesystemParser
from honeygrove.tests.testresources import __path__ as resources
from honeygrove.tests.testresources import testconfig as config
class FilesystemParserUnixTest(unittest.TestCase):
def setUp(self):
FilesystemParser.honeytoken_di... | StarcoderdataPython |
1716304 | <filename>test_case_prioritazation/utils/stats.py
import random
from matplotlib import pyplot as plt
import numpy as np
class Graph:
def __init__(self):
self.x = []
self.y = []
def add_data(self, x, y):
self.x.append(x)
self.y.append(y)
def draw_graph(self, title, x_label... | StarcoderdataPython |
11327469 | <reponame>dperilla/MS-Teams-Automation
import os
import pyautogui
import time
from time import sleep
from datetime import datetime
try:
# open MS Teams application
#os.startfile("/usr/bin/teams")
sleep(2)
# settings
settings = pyautogui.locateCenterOnScreen("Images/settings.PNG")
... | StarcoderdataPython |
9752658 | <reponame>martonmiklos/sigrokdecoders_to_logic2_analyzers
##
## This file is part of the libsigrokdecode project.
##
## Copyright (C) 2019 <NAME> <<EMAIL>>
##
## Permission is hereby granted, free of charge, to any person obtaining a copy
## of this software and associated documentation files (the "Software"), to deal
... | StarcoderdataPython |
1707442 | import pandas as pd
from gensim.models import Word2Vec
import os
import time
import datetime
def format_time(elapsed):
elapsed_rounded = int(round(elapsed))
return str(datetime.timedelta(seconds = elapsed_rounded))
train_data = pd.read_csv("../tianchi_datasets/track3_round1_newtrain3.tsv", sep="\t", header=N... | StarcoderdataPython |
1824396 | <reponame>OrderAndCh4oS/drone_squadron_api_prototype
from sqlalchemy.engine import ResultProxy
from drone_squadron.crud.steering_crud import SteeringCrud
from drone_squadron.schema import steering
class TestSteeringCrud:
crud = SteeringCrud
def test_insert(self, setup):
with self.crud() as crud:
... | StarcoderdataPython |
11351101 | import toml
from clin import __version__
def test_pyproject_version_matches_package_version():
pyproj = toml.load("pyproject.toml")
assert __version__ == pyproj["tool"]["poetry"]["version"]
| StarcoderdataPython |
9700905 | <gh_stars>1-10
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 20 14:08:42 2019
@author: smrak
"""
import numpy as np
from cartomap import geogmap as gm
from datetime import datetime
import matplotlib.pyplot as plt
import cartopy.crs as ccrs
import apexpy as ap
latlim = [-0,60]
lonlim= [-140,0]... | StarcoderdataPython |
6484795 | <reponame>Wwarrior1/DistributedServerCache<filename>algorithm/utils.py
import random
from utils.solution_checker import calculate_score
class AlgorithmUtils:
@staticmethod
def random_solution(data):
res = dict()
avg_video_size = sum(data.videos_sizes)/len(data.videos_sizes)
total_n_v... | StarcoderdataPython |
9753134 | # find the sum of contiguous subarray within a one-dimensional array of numbers which has the largest sum.
# example: [-1, -2, 4, 3, 1, -1, -5]
# ans: 2+4+3 = 9
def largest_sum_of_sub_array(arr):
max_so_far = 0
max_ending_here = 0
for num in arr:
max_ending_here = max_ending_here + num
... | StarcoderdataPython |
3285030 | from django.apps import AppConfig
class DatavizConfig(AppConfig):
name = 'dataVIZ'
| StarcoderdataPython |
6591740 | <gh_stars>1-10
from mpl_toolkits.mplot3d import Axes3D # pylint: disable=unused-import
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(projection="3d")
dt = [0, 1, 2, 3, 4, 5]
Ps = [3, 3.1, 3.2, 3.3, 3.4, 3.5]
Qc = [
[0, 0.1, 0.2, 0.3, 0.4, 0.5],
[0, 0.01, 0.02, 0.03, 0.04, 0.05],
... | StarcoderdataPython |
349636 | <gh_stars>0
class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
roman_dict1 = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
roman_dict2 = {'IV':4, 'IX':9, 'XL':40, 'XC':90, 'CD':400, 'CM':900}
sum_var = 0
i = ... | StarcoderdataPython |
135242 | import pytest
from homepage.models import Course
from django.core.exceptions import ValidationError
from decimal import Decimal
# -----------course tests----------- #
# creating a single new course with valid input
@pytest.mark.parametrize("valid_courses", [
(1, "Linear Algebra 1", True, 4),
# ... | StarcoderdataPython |
5024188 | from setuptools import setup
setup(name='skyblue-cloud',
version="MASTER",
description='Reusable Django app for prototyping',
long_description='django-fastapp is a reusable Django app which lets you prototype apps in the browser with client- and server-side elements.',
url="https://github.com/fatrix/django-fastapp... | StarcoderdataPython |
352955 | <reponame>SanjayRai/software_acceleration_framework_with_Xilinx_HLS<gh_stars>1-10
#! /usr/bin/python
import binascii
import os
import sys
if (len(sys.argv)) != 4 :
print "Wrong arguments\n\n\t ./rd_test.py 0xf7c00000 num_bytes srai_wr.bin"
else :
byte_count = 0
filename = sys.argv[3]
FP = open (filena... | StarcoderdataPython |
6669248 | origen.app.instantiate_dut("dut.falcon")
| StarcoderdataPython |
3472681 | <filename>setup.py<gh_stars>0
from setuptools import setup, find_packages
with open('README.md', encoding='utf-8') as f:
long_description = f.read()
setup(
name='kijiji-manager',
version='0.1.8',
author='jackm',
author_email='<EMAIL>',
description='App for viewing, posting, reposting, and dele... | StarcoderdataPython |
3251852 | import wifimgr
import dht
from machine import Pin, deepsleep, reset
import configmgr
import urequests
from time import localtime
import ntptime
import sys
wlan = wifimgr.get_connection()
if wlan is None:
print("Could not initialize the network connection.")
while True:
pass # you shall not pass :D
co... | StarcoderdataPython |
1618046 |
from zoopt.utils.zoo_global import gl
from zoopt.utils.tool_function import ToolFunction
"""
The class Dimension was implemented in this file.
This class describes dimension messages.
Author:
<NAME>
"""
class Dimension:
def __init__(self, size=0, regs=[], tys=[], include_upper_bound=False):
self._... | StarcoderdataPython |
3405434 | """
Python Interchangeable Virtual Instrument Driver
Copyright (c) 2017 <NAME>
derived from agilent436a.py driver by:
Copyright (c) 2012-2014 <NAME>
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 Soft... | StarcoderdataPython |
200278 | <reponame>andreamarini/yambopy<gh_stars>0
# Copyright (C) 2018 <NAME>
# All rights reserved.
#
# This file is part of yambopy
#
from __future__ import print_function
import unittest
import os
import numpy as np
from yambopy.io.outputfile import YamboOut
test_path = os.path.join(os.path.dirname(__file__),'..','..','dat... | StarcoderdataPython |
1744581 | <filename>features/audio_features/helpers/pyAudioLex/text_features/parts of speech/rbs_freq.py
'''
@package: pyAudioLex
@author: <NAME>
@module: rp_freq
rp = particle
'''
from nltk.tokenize import word_tokenize
from nltk.tag import pos_tag, map_tag
from collections import Counter
def rp_freq(importtext):
text=w... | StarcoderdataPython |
345060 | <filename>python/build_mats.py
##############################################################################
# This file is a part of PFFDTD.
#
# PFFTD is released under the MIT License.
# For details see the LICENSE file.
#
# Copyright 2021 <NAME>.
#
# File name: build_mats.py
#
# Description: Examples of setting/sav... | StarcoderdataPython |
6596465 | from flasgger import Swagger
from flask import Flask
from examples.meeting_room.view_models import MeetingSession, UserView
from examples.meeting_room.view_models.meeting_session import \
MeetingSessionMutation
from examples.meeting_room.views import meeting_session_ops
from onto.view import rest_api
app = Flask(... | StarcoderdataPython |
137100 | <reponame>mikkelos/expense-analyzer
"""
gcloud functions deploy update_transaction_categories --region europe-west1 --runtime python37 --trigger-http --entry-point update_transaction_categories
"""
import os
# Imports the Google Cloud client library
from google.cloud import datastore
from google.oauth2 import service... | StarcoderdataPython |
1872265 | <reponame>shyamalschandra/CNTK
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE.md file in the project root
# for full license information.
# ==============================================================================
"""
Extra utilities for CNTK, e.g. utilities that bri... | StarcoderdataPython |
3531604 | <gh_stars>0
from setuptools import setup, find_packages
with open("README.md", 'r') as readme:
long_description = readme.read()
setup(
name = 'elementally',
version = '0.4',
author = 'David "Dawn" <NAME>',
author_email = '<EMAIL>',
description = 'Utility module for elementwise operations on basic Python'
... | StarcoderdataPython |
8132776 | """blog URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based vi... | StarcoderdataPython |
5065443 | <reponame>oiwn/redis-tools
import importlib
class ItemSerializer(object):
"""Serialize/Deserialize python native data structure
using varisou set of libs"""
__slots__ = {"__serializer", "_loads", "_dumps"}
@property
def serializer(self) -> str:
return self.__serializer
def __init__(... | StarcoderdataPython |
4822217 | #!/usr/bin/env python
###############################################################################
# Copyright 2017 The Apollo 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 ... | StarcoderdataPython |
9783052 | <reponame>crazywiden/Leetcode_daily_submit<gh_stars>0
'''
Time complexity: O(n),52 ms, 98.04%
Space complexity: O(n)?,16.3 MB, 5.10%
'''
#method1: DFS
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class ... | StarcoderdataPython |
5192649 | from qualipy.backends.pandas_backend.pandas_types import (
FloatType,
IntType,
DateTimeType,
ObjectType,
BoolType,
)
PANDAS_TYPES = {
"FloatType": FloatType,
"IntType": IntType,
"DateTimeType": DateTimeType,
"ObjectType": ObjectType,
"BoolType": BoolType,
} | StarcoderdataPython |
3561812 | <reponame>richengguy/alias<filename>src/alias/links.py
import pathlib
import sqlite3
from typing import NamedTuple, Optional
import flask
class LinkEntry(NamedTuple):
alias: str
href: str
class LinksRegistry:
'''A key-value store that maps a short name to a URL.
The registry is used to find the UR... | StarcoderdataPython |
4838537 | import torch
import torch.nn as nn
import numpy as np
import scipy.misc
from ..attack import Attack
def save_images(images, size, image_path):
return imsave(inverse_transform(images), size, image_path)
def imsave(images, size, path):
image = np.squeeze(merge(images, size))
return scipy.misc.imsave(path,... | StarcoderdataPython |
4861230 | <gh_stars>1-10
# -*- coding: utf-8 -*-
import logging
from django.utils.translation import ugettext as _
import seaserv
from seaserv import seafile_api
from seahub.utils import EMPTY_SHA1
from seahub.base.accounts import User
logger = logging.getLogger(__name__)
def list_dir_by_path(cmmt, path):
if cmmt.root_id... | StarcoderdataPython |
1956507 | <reponame>Cataldir/koalixcrm<gh_stars>100-1000
# -*- coding: utf-8 -*-
import factory
from koalixcrm.crm.models import ResourceManager
from koalixcrm.djangoUserExtension.factories.factory_user_extension import StandardUserExtensionFactory
class StandardResourceManagerFactory(factory.django.DjangoModelFactory):
c... | StarcoderdataPython |
11266236 | <reponame>sciling/example-kubeflow-dcase
import typing
import kfp.components as comp
def generate_metrics(
mlpipelinemetrics_path: comp.InputPath(),
) -> typing.NamedTuple("Outputs", [("mlpipeline_metrics", "Metrics")]): # noqa: F821
import json
with open(mlpipelinemetrics_path, "r") as f:
metr... | StarcoderdataPython |
5004160 | from .exceptions import *
from .sns_message_type import SNSMessageType
from .sns_message_validator import SNSMessageValidator
| StarcoderdataPython |
15651 | # coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# 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 ... | StarcoderdataPython |
11343856 | import numpy as np
from numpy.testing import assert_, assert_almost_equal
from astroML.time_series import generate_power_law, generate_damped_RW
def check_generate_args(N, dt, beta, generate_complex):
x = generate_power_law(N, dt, beta, generate_complex)
assert_(bool(generate_complex) == np.iscomplexobj(x))
... | StarcoderdataPython |
288430 | <reponame>mtosity/CameraTrapHCMUS
import json
import os
from pathlib import Path
import requests
import yaml
from PIL import Image
from tqdm import tqdm
from utils import make_dirs
def convert(file, zip=True):
# Convert Labelbox JSON labels to YOLO labels
names = [] # class names
file = Path(file)
... | StarcoderdataPython |
4904646 | """
base classes for polynomial rings and rational function fields.
"""
import nzmath.ring as ring
import nzmath.poly.termorder as termorder
import nzmath.poly.univar as univar
import nzmath.poly.multivar as multivar
class PolynomialRing(ring.CommutativeRing):
"""
The class of uni-/multivariate polynomial r... | StarcoderdataPython |
1661447 | <filename>3rdparty/openmm/wrappers/python/tests/TestMetadynamics.py
import unittest
from simtk.openmm import *
from simtk.openmm.app import *
from simtk.unit import *
class TestMetadynamics(unittest.TestCase):
"""Test the Metadynamics class"""
def testHarmonicOscillator(self):
"""Test running metadyna... | StarcoderdataPython |
6448978 | # This module treats audio data, it can "hear", recognize, and speak. I did none of that, I should copy paste credits one day
import speech_recognition as sr
import os
from gtts import gTTS
def speak(audioString, lang):
save_audio(audioString, lang)
const = "mpg123 audio.mp3"
print(audioString)
os.sys... | StarcoderdataPython |
11281360 | <reponame>mrdrozdov/knnlm
import argparse
import collections
import os
import faiss
import numpy as np
from tqdm import tqdm
def main(args):
np.random.seed(args.seed)
os.system('mkdir -p {}'.format(args.output))
if args.test_only:
out = build_split(args.va_dstore, args.va_dstore_size, args.v... | StarcoderdataPython |
1750369 | '''
The initialization module for the performance measures package.
'''
from .jaccard_similarity import (jaccard_index_binary_masks,
jaccard_index_multipolygons)
__all__ = [
'jaccard_index_binary_masks',
'jaccard_index_multipolygons',
]
| StarcoderdataPython |
9742677 | <filename>publicdata/censusreporter/series.py
# Copyright (c) 2017 Civic Knowledge. This file is licensed under the terms of the
# MIT License, included in this distribution as LICENSE
"""
"""
from pandas import DataFrame, Series
import numpy as np
from six import string_types
import numpy as np
from six import strin... | StarcoderdataPython |
276236 | import collections
import re
import subprocess
import time
from typing import Any, Optional, Sequence
import pytest
from kopf.testing import KopfRunner
def test_all_examples_are_runnable(mocker, settings, with_crd, exampledir, caplog):
# If the example has its own opinion on the timing, try to respect it.
... | StarcoderdataPython |
178842 | """
Module to assist with the creation of python ascii art
"""
def goto(x_pos, y_pos):
"""
Move the cursor to a given position
"""
x_pos = int(x_pos)
y_pos = int(y_pos)
print(f"\033[{y_pos};{x_pos}H", end="")
def set_color(red, green, blue):
"""
Set the foreground color of the text
... | StarcoderdataPython |
8065853 | # -*- coding: utf-8 -*-
from django.db import models
from apps.registro.models.ExtensionAulica import ExtensionAulica
from apps.postitulos.models.CohortePostitulo import CohortePostitulo
from apps.postitulos.models.EstadoCohortePostituloExtensionAulica import EstadoCohortePostituloExtensionAulica
import datetime
"Cada... | StarcoderdataPython |
5001470 | import pandas as pd
order_df = pd.read_csv("https://storage.googleapis.com/dqlab-dataset/order.csv")
# Hitung harga maksimum pembelian customer
sort_harga = order_df.sort_values(by=["price"], ascending=False)
print(sort_harga) | StarcoderdataPython |
1681637 | __author__ = '<NAME>'
__version__ = '1.0'
from cab.global_constants import GlobalConstants
class GC(GlobalConstants):
def __init__(self):
super().__init__()
self.VERSION = '03-2017'
self.TITLE = 'Sugarscape'
self.GUI = "PyGame" # Options: "None", TK", "PyGame"
###########... | StarcoderdataPython |
4995171 | <reponame>HHS/ckan<filename>ckan/logic/auth/publisher/update.py<gh_stars>1-10
import ckan.logic as logic
from ckan.logic.auth import get_package_object, get_group_object, \
get_user_object, get_resource_object, get_related_object
from ckan.logic.auth.publisher import _groups_intersect
from ckan.logic.auth.publisher... | StarcoderdataPython |
1843144 | <reponame>chrislast/AoC21
# import our helpers
from utils import load, show, day, TRACE
from collections import Counter
####### GLOBALS #########
# load todays input data as a docstring
DATA = load(day(__file__)).splitlines()
# Parse input
TEMPLATE = DATA[0]
RULES = dict([tuple(_.split(" -> ")) for _ in DATA[2:] if ... | StarcoderdataPython |
395600 | # coding=utf-8
# Copyright 2019 The TensorFlow Datasets Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... | StarcoderdataPython |
5169832 | <gh_stars>1-10
#!/usr/bin/env python2
from __future__ import absolute_import, division, print_function
import argparse
import codecs
import datetime
import imp
import os
import os.path as path
import pkgutil
import re
import subprocess
import sys
import tempfile
from . import budoc
from .config import load_config
# ... | StarcoderdataPython |
3439875 | <reponame>OpenSourceDog/Bulbaspot-Cogs
# Ivysalt's sentry module. It keeps track of people who join and leave a chat.
# LICENSE: This single module is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
# @category Tools
# @copyright Copyright (c) 2018 dpc
# @version ... | StarcoderdataPython |
1777381 | <reponame>JLSchoolWork/12SDD-FinanceHelper<filename>Python/tax/TkHelper.py
from Tkinter import *
from GridLocation import *
import tkMessageBox
class TkHelper(object):
_wraplength = 350
def showAlert(self, message):
"""
Show a new window as an alert.
:param message: The message in th... | StarcoderdataPython |
146475 | from src.end_point import EndPoint
class Collection:
def __init__(self, collection_json):
self.end_points = [EndPoint(x) for x in collection_json["item"]]
def get_end_points(self):
return self.end_points
def remove_end_point(self, end_point):
self.end_points.remove(end_point)
| StarcoderdataPython |
4813157 | <filename>rpn/eval_pb.py
import init_path
import numpy as np
import argparse
import json
from rpn.utils.log_utils import StatsSummarizer
from rpn.env_utils import World
from rpn.bullet_envs import *
from rpn.problems_pb import factory
from rpn.env_utils import pb_session, load_world, set_rendering_pose
from rpn.plan_u... | StarcoderdataPython |
4832164 | <reponame>manojakm/sanskrit-ocr-1
import json
import os
import sys
initial_step = int(sys.argv[1])
final_step = int(sys.argv[2])
steps_per_checkpoint = int(sys.argv[3])
if os.path.exists("./model/CRNN/logs/val_preds.txt"):
os.remove("./model/CRNN/logs/val_preds.txt")
while initial_step<=final_step:
with ope... | StarcoderdataPython |
11378440 | <reponame>JordanSamhi/BricksBreaker
import random
'''
Cette classe definie les couleurs du jeu
Deux listes, une pour 10x10 et une pour 20x20
Deux methodes de recuperation aleatoire de couleurs dans ces tuples
'''
class ListeCouleurs():
def __init__(self):
self._listeCouleurs = ()
... | StarcoderdataPython |
6424778 | import unittest
import pandas as pd
from ccfd.data import get_data, train_val_test_split, scale_data, CLASS
AMOUNT = 'amount'
class TestData(unittest.TestCase):
DELTA = 0.001
def setUp(self):
self.data = get_data()
self.train_data, self.train_target, self.val_data, _, self.test_data, _ = t... | StarcoderdataPython |
8169724 | #!/usr/bin/env python
"""Discrete synthesis from a dummy abstraction with mixed switching.
This is an example to demonstrate how the output of a discretization algorithm
that abstracts a switched system might look like,
where the mode of the system depends on a combination of
environment and system controlled variable... | StarcoderdataPython |
4955343 | from sys import stdout
# issues: explicit locations. Should add parameters.
class Printer(object):
def __init__(self, verbose=True):
# self.row, self.col = 2, 1
self.verbose = verbose
if not verbose:
return
self.state_row, self.state_col = 2, 1
self.log_row, se... | StarcoderdataPython |
6520056 | """
(C) Copyright 2011, 10gen
This is a label on a mattress. Do not modify this file!
"""
# App
import settings as _settings
# Mongo
import pymongo, bson
# Python
import logging, threading, time, logging.handlers, urllib2, platform, socket, Queue
socket.setdefaulttimeout( _settings.socket_timeout )
class LogRelay... | StarcoderdataPython |
4928166 | <gh_stars>1-10
from django.apps import AppConfig
class HealthcheckAppConfig(AppConfig):
name = 'healthcheck'
| StarcoderdataPython |
5131489 | from citc.utils import get_cloud_nodes
import pytest
def test_get_cloud_nodes_error(fs):
fs.create_file("/etc/citc/startnode.yaml", contents="---\ncsp: blahblah")
with pytest.raises(Exception):
get_cloud_nodes()
| StarcoderdataPython |
1620249 | <filename>test/integration/ggrc/services/resources/test_converters.py
# -*- coding: utf-8 -*-
# Copyright (C) 2019 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Tests for import/export endpoints.
Endpoints:
- /api/people/person_id/imports
- /api/people/person_id/ex... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.