id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
1699428 | import pytest
from py_meta_utils import (McsArgs, MetaOption, AbstractMetaOption, MetaOptionsFactory,
EnsureProtectedMembers, Singleton, deep_getattr)
class TestMcsArgs:
def test_module_and_qualname_properties(self):
mcs_args = McsArgs(type, 'Test', (), {})
assert mcs_a... | StarcoderdataPython |
93859 | <filename>enthought/block_canvas/canvas/selectable_component_mixin.py
# proxy module
from __future__ import absolute_import
from blockcanvas.canvas.selectable_component_mixin import *
| StarcoderdataPython |
3372812 | <filename>gui/bind/footer.py
__author__ = 'ishan'
from gi.repository import Gtk, GtkSource
class Footer:
def __init__(self):
"""
creates the combobox to be used in footer
"""
self.liststore = Gtk.ListStore(str)
lang_ids = GtkSource.LanguageManager().get_language_ids()
... | StarcoderdataPython |
3268812 | <reponame>luis-armando-perez-rey/diffusion_vae_github<filename>modules/deltavae/deltavae_latent_spaces/deltavae_clifford_torus.py
'''
Created on Dec 6, 2018
'''
# System imports
import os
# Standard imports
import numpy as np
import tensorflow as tf
import keras.backend as K
import itertools
from scipy import stats
... | StarcoderdataPython |
1783479 | <reponame>igorsobreira/eizzek
from redis import Redis
from eizzek import config
class SessionPersistence(object):
def __init__(self):
self._redis_client = None
self.host = config.REDIS_HOST
self.port = config.REDIS_PORT
self.db = config.REDIS_DB
def begin(self, jid, plugin_nam... | StarcoderdataPython |
3268081 | #!/usr/bin/env python3
class Solution:
def splitArray(self, nums: List[int], m: int) -> int:
| StarcoderdataPython |
3277970 | <reponame>fslds/atomic-threat-coverage<filename>scripts/attack_navigator_export.py
from os import listdir
from os.path import isfile, join
import json
from atcutils import ATCutils
from yaml.scanner import ScannerError
try:
ATCconfig = ATCutils.read_yaml_file("config.yml")
dr_dir = ATCconfig.get('detection_ru... | StarcoderdataPython |
33889 | import numpy as np
from math import pi
import torch
from pykeops.torch import LazyTensor
from plyfile import PlyData, PlyElement
from helper import *
import torch.nn as nn
import torch.nn.functional as F
# from matplotlib import pyplot as plt
from pykeops.torch.cluster import grid_cluster, cluster_ranges_centroids, fr... | StarcoderdataPython |
1726338 | <gh_stars>0
#fname = raw_input("Enter file name: ")
fh = open('/home/anabrs1/Python_material/code/romeo.txt')
#I will read the fh2 as a string
fh2 = fh.read()
lst = fh2.split()
for x in lst:
if x in lst:
lst.remove(x)
lst.sort()
print lst
print 'This code gives a wrong output: required debugging' | StarcoderdataPython |
1634227 | <reponame>engeir/release-trader<gh_stars>0
"""Schedule run of strategy."""
import time
import schedule
import release_trader.strategy as s
def main() -> None:
"""Release Trader."""
schedule.every(5).seconds.do(s.buy_on_release)
while 1:
schedule.run_pending()
time.sleep(1)
if __name__... | StarcoderdataPython |
78431 | <filename>insights/parsers/dirsrv_sysconfig.py
"""
dirsrv_sysconfig - file ``/etc/sysconfig/dirsrv``
=================================================
This module provides the ``DirsrvSysconfig`` class parser, for reading the
options in the ``/etc/sysconfig/dirsrv`` file.
Sample input::
# how many seconds to wai... | StarcoderdataPython |
1771549 | """
MuJoCo 1.50 compatible MujocoEnv.
Adapted from https://github.com/openai/gym/pull/767.
"""
import os
from gym import error, spaces
from gym.utils import seeding
import numpy as np
from os import path
import gym
import six
import cythonized
from .mujoco.generated import const
class MujocoEnv(gym.Env):
"""
... | StarcoderdataPython |
3306644 | <filename>saas/backend/apps/application/migrations/0011_auto_20201221_1556.py
# -*- coding: utf-8 -*-
"""
TencentBlueKing is pleased to support the open source community by making 蓝鲸智云-权限中心(BlueKing-IAM) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT L... | StarcoderdataPython |
1736962 | <filename>fw_dir/scripts/wifi_setup.py
import os
import imp
import sys
import time
import threading
import subprocess
# usb or sd card
user_dir = os.getenv("USER_DIR", "/usbdrive")
fw_dir = os.getenv("FW_DIR")
# imports
current_dir = os.path.dirname(os.path.abspath(__file__))
og = imp.load_source('og', current_dir + ... | StarcoderdataPython |
1792934 | from sample_players import DataPlayer
import math, random
class CustomPlayer_AB(DataPlayer):
def minimax(self, state, depth):
'''
Min-max algorithm
:param state: Game state
:param depth: Depth of tree
:return: the state with highest score
'''
def min_value(... | StarcoderdataPython |
1794144 | <reponame>qai222/ATMOxide<filename>DataGeneration/1_ChemicalDiagramSearch/1_sniff_formula.py<gh_stars>0
import re
import pandas as pd
from ccdc.io import EntryReader, Entry
from tqdm import tqdm
from AnalysisModule.routines.util import MDefined, csdformula2pmg_composition, Composition
CSD_READER = EntryReader('CSD')... | StarcoderdataPython |
3338095 | <gh_stars>0
from os.path import basename
class Configuration(object):
def __init__(self, api):
self.api = api
def upload(self, configuration):
self.api.put('/', {
'configuration': configuration,
'sphinx_version': '2.0.4'
})
def upload_from_file(self, path):
file = open(path)
sel... | StarcoderdataPython |
53964 | <filename>purchase/migrations/0004_auto_20200928_0513.py
# Generated by Django 3.1.1 on 2020-09-28 05:13
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('organization', '0004_auto_20200914_0713'),
('products', '00... | StarcoderdataPython |
4826959 | import tweepy
import logging
import os
logger = logging.getLogger()
def create_api():
consumer_key = os.getenv("CONSUMER_KEY")
consumer_secret = os.getenv("CONSUMER_SECRET")
access_token = os.getenv("ACCESS_TOKEN")
access_token_secret = os.getenv("ACCESS_TOKEN_SECRET")
bearer_token= os.getenv('BE... | StarcoderdataPython |
1697032 | import unittest
import sys
import os
from robot_session_server import get_robot_version
from robot_session_server import create_libdoc
from robot_session_server import get_classes_from_module
from robot_session_server import get_module_path
from robot_session_server import get_variables
from robot_session_server impor... | StarcoderdataPython |
3354811 | <reponame>andreyzharkov/plc<gh_stars>0
import itertools
class Quariable(object):
def __init__(self, iterable):
self.iterable = iterable
def select(self, selector):
return Quariable(map(selector, self.iterable))
def flatten(self):
def gen(iterable):
flow = iterable
... | StarcoderdataPython |
59046 | """
Test utilities
"""
import os
import pytest
import factory
from django.test.html import HTMLParseError, parse_html
from cms.api import add_plugin
from cms.models import Placeholder
from cms.test_utils.testcases import CMSTestCase
from cmsplugin_blocks.utils.factories import create_image_file
def get_fake_words(... | StarcoderdataPython |
1691687 | # -*- coding: utf8 -*-
ENV = 'development'
HOST = '0.0.0.0'
PORT = 3000
SQLALCHEMY_TRACK_MODIFICATIONS = False
STRICT_SLASHES = False
ANNOTATIONS_PER_PAGE = 1000
CORS_RESOURCES = {
r"/*": {
"origins": "*",
"allow_headers": [
'Content-Type',
'Content-Length',
'Auth... | StarcoderdataPython |
3318468 | """=============================================================
~/fn_portal/fn_portal/tests/api/test_FN014.py
Created: 08 Jun 2021 17:00:43
DESCRIPTION:
This file contains a number of unit tests that verify that the api
endpoint for FN014 objects works as expected:
+ the fn014 list returns all of the gears ... | StarcoderdataPython |
170938 | #!/usr/bin/env python3
# Copyright (c) 2008-9 Qtrac Ltd. All rights reserved.
# This program or module is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as published
# by the Free Software Foundation, either version 2 of the License, or
# version 3 of the Lic... | StarcoderdataPython |
1670059 | <filename>benchmarks/trackmate/trackmate_test_fiji.py
# @String basedir
# @String detector
# @Float radius
# @Boolean median
"""Testing script for trackmate's FIJI API."""
import csv
import glob
import os
from ij import IJ
from fiji.plugin.trackmate import Model
from fiji.plugin.trackmate import Settings
from fiji.p... | StarcoderdataPython |
1729475 | import os
from .base import BaseTask
from django.core.mail import EmailMessage
from reports.models import ReportTaskStatus
class SendEmail(BaseTask):
def run(self, **kwargs):
subject = kwargs['subject']
sender = kwargs['sender']
recipients = kwargs['recipients']
file_location =... | StarcoderdataPython |
3296814 | <gh_stars>1-10
from django import template
from django import forms
from django.http import HttpResponseRedirect
from pirate_social.models import Subscription,RelationshipEvent
from pirate_core.views import HttpRedirectException, namespace_get
from customtags.decorators import block_decorator
register = template.Lib... | StarcoderdataPython |
3349854 | # http://picamera.readthedocs.io/en/release-1.10/recipes2.html#rapid-capture-and-streaming
import socket
import os
import time
import cv2
from scipy import ndimage
if __name__ == "__main__":
host = "0.0.0.0"
port = 2201
server = socket.socket()
server.setsockopt(socket.SOL_SOCKET, socket.S... | StarcoderdataPython |
1795841 | # ABC134d
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**6)
n = int(input())
a = [-1]
a.extend(list(map(int, input().split())))
ans = [0]*(n+1)
for i in range(n, 0, -1):
j = 1
su = 0
while (i * j <= n):
su += ans[i * j]
j += 1
# print(str(i)+"は"+str(su))
if (su % ... | StarcoderdataPython |
103173 | <reponame>brianchiang-tw/HackerRank<gh_stars>1-10
def get_median( arr ):
size = len(arr)
mid_pos = size // 2
if size % 2 == 0:
# size is even
median = ( arr[mid_pos-1] + arr[mid_pos] ) / 2
else:
# size is odd
median = arr[mid_pos]
return (median)
def collect... | StarcoderdataPython |
130694 | <gh_stars>1-10
"""
xst.py
Copyright 2007 <NAME>
This file is part of w3af, http://w3af.org/ .
w3af is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 2 of the License.
w3af is distributed in the hope that ... | StarcoderdataPython |
1681965 | from django.conf.urls import url, patterns
from . import views
urlpatterns = [
url(r'^$',views.index,name="index"),
url(r'^mydefects$',views.mydefects,name="mydefects"),
url(r'^moderate$',views.moderate,name="moderate"),
url(r'^list$',views.list,name="list"),
url(r'^help$',views.help,name="help"),
... | StarcoderdataPython |
54193 | from numpy import ndarray, array
from electripy.physics.charges import PointCharge
class _ChargesSet:
"""
A _ChargesSet instance is a group of charges. The electric
field at a given point can be calculated as the sum of each
electric field at that point for every charge in the charge
set.
"""
... | StarcoderdataPython |
1619346 | <reponame>jenna-jordan/beepocalypse_streamlit<filename>app.py
import streamlit as st
import pandas as pd
import numpy as np
import plotly.express as px
st.set_page_config(page_title="Beepocalpyse", layout="wide")
df = pd.read_csv(
"Data/bln-queries_6pubs_26Feb.csv",
parse_dates=["publication_date"],
dtype... | StarcoderdataPython |
3299636 | <reponame>dcurry09/Tensorflow-Project-OOP
#!/usr/bin/env python3
"""
Implements a data loader class by inheriting the DataLoader base class.
IMDB dataset is accessed through the Keras API
@author: <NAME>
@version: 1.0
"""
from base.data_loader_base import DataLoader
from keras.datasets import imdb
from sklearn.prepr... | StarcoderdataPython |
4805163 | from django.urls import path
from . import consumers
websocket_urlpatterns = [path("ws/game/<int:id>", consumers.GameConsumer)]
| StarcoderdataPython |
50078 | #!/usr/bin/python
# encoding: utf-8
import os
import json
import time
from time import sleep
import requests
import re
from werkzeug import secure_filename
from flask import (Flask, request, render_template,
session, redirect, url_for, escape,
send_from_directory, Blueprint, abort)
delete_okta = Blueprint('okta_de... | StarcoderdataPython |
29318 | <reponame>TaIos/code_generator
import pathlib
class ExporterConfig:
def __init__(self, github_token, gitlab_token):
self.github_token = github_token
self.gitlab_token = gitlab_token
class ConfigLoader:
@classmethod
def load(cls, cfg):
"""
Load and validate application c... | StarcoderdataPython |
172079 | <filename>src/ui_tests/tests/dimension_check_test.py
# Test DimensionChecker.
from test_util import test_helper
CELL1 = '''
### CELL1 ###
import croquis
import numpy as np
# Test coordinate broadcast logic (similar to numpy).
fig = croquis.plot()
X = np.linspace(-5, 5, 10) # shape = (10,)
Y = np.arange(30).reshape... | StarcoderdataPython |
4830776 |
from tkinter import Tk
from tkinter.filedialog import askopenfilename
from ibm_watson import TextToSpeechV1
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator
from ibm_watson import SpeechToTextV1
from ibm_watson.websocket import RecognizeCallback, AudioSource
from ibm_cloud_sdk_core.authenticat... | StarcoderdataPython |
3284921 | # -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.11.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %% [raw] raw_mimetype="tex... | StarcoderdataPython |
3343243 | <filename>python/quality/random_cluster/__init__.py<gh_stars>1-10
from .utils import read_inferred_clusters
| StarcoderdataPython |
1789876 | #!/usr/bin/env python
# author: d.koch
# coding: utf-8
# naming: pep-0008
# typing: pep-0484
# docstring: pep-0257
# indentation: tabulation
""" canp_test.py
Simple CAN interface tester
"""
# --- IMPORT ---
# Standard libraries (installed with python)
import asyncio
#import atexit
#import json
#import logging
imp... | StarcoderdataPython |
1798202 | <filename>papy/sol/coord.py
#!/usr/share/bin python
from datetime import timedelta
import warnings
from astropy.io import fits
from astropy.time import Time
import numpy as np
from numpy import sin, cos, tan, sqrt, arcsin, arctan
from papy.misc import cached_property
# Numerical tools ==============================... | StarcoderdataPython |
1789668 | <filename>noise/model.py
import numpy as np
from utils.unit_conversions import db_to_lin, lin_to_db
from utils import constants
import atm
def get_thermal_noise(bandwidth_hz, noise_figure_db=0, temp_ext_k=0):
"""
N = thermal_noise(bw,nf,t_ext)
Compute the total noise power, given the receiver's noise ban... | StarcoderdataPython |
29446 | <filename>edbdeploy/spec/__init__.py
class SpecValidator:
def __init__(self, type=None, default=None, choices=[], min=None,
max=None):
self.type = type
self.default = default
self.choices = choices
self.min = min
self.max = max
| StarcoderdataPython |
3278811 | <gh_stars>0
#! /usr/bin/env python3
# -*-coding:UTF-8 -*-
# @Time : 2018/12/25 11:37:57
# @Author : che
# @Email : <EMAIL>
import heapq
class PriorityQueue(object):
def __init__(self):
self._queue = []
self._index = 0
def push(self, item, priority):
# 注意构造item顺序, 以heapq的规则插入项目... | StarcoderdataPython |
1698093 | <filename>pyProj/z2.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def garm(*args):
if args:
summa = float(0)
for arg in args:
summa = summa + (1 // arg)
n = len(args)
return n // summa
else:
return None
if __name__ == "__main__":
print(garm(1, 4, 6,... | StarcoderdataPython |
1703646 | <filename>AppleMusicAnalyzer/Music.py<gh_stars>0
import pandas as pd
from collections import Counter
from tqdm import tqdm
import matplotlib.pyplot as plt
import calmap
class Song:
start_time = ''
song_name = ''
artist_name = ''
container_name = ''
device = ''
def __init__(self, start_time=''... | StarcoderdataPython |
4801219 | # -*- coding: utf-8 -*-
"""Script for making Lyman-alpha forest temperature-density plots using the phase_plot module"""
import matplotlib
matplotlib.use('PDF')
from mpl_toolkits.axes_grid1 import AxesGrid
import phase_plot
import matplotlib.pyplot as plt
outdir="/home/spb/scratch/ComparisonProject/"
bar_label="Mass ... | StarcoderdataPython |
3204808 | <filename>train_tabular.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
from contextlib import contextmanager
import gc
import math
import random
import os
import time
import warnings
import numpy
import torch
from tqdm import tqdm
import lib.datasets as datasets
import lib.utils as utils
import lib... | StarcoderdataPython |
1661216 | <gh_stars>1-10
import os
import logging
from flask import Flask, jsonify, make_response, request, abort
from flask_httpauth import HTTPBasicAuth
from linkedin import linkedin
logging.basicConfig(filename = 'tweetsched-linkedin-publisher.log', level = logging.INFO)
auth = HTTPBasicAuth()
app = Flask(__name__)
@auth.ge... | StarcoderdataPython |
3205491 | #this algo only looks at the stocks in the biopharmcatalyst.com table and makes a trading decision based on the data in it
import otherfxns as o
algo = o.os.path.basename(__file__).split('.')[0] #name of the algo based on the file name
def init(configFile):
global c
#set the multi config file
c = o.configpars... | StarcoderdataPython |
1677573 | <gh_stars>0
"""
CLI command for "pipeline init" command
"""
from typing import Any, Optional
import click
from samcli.cli.cli_config_file import configuration_option, TomlProvider
from samcli.cli.main import pass_context, common_options as cli_framework_options
from samcli.commands.pipeline.init.interactive_init_flow... | StarcoderdataPython |
119436 | from typing import Any, Iterable, Optional
import sqlalchemy as sa
from sqlalchemy import Table, orm
@orm.declarative_mixin
class DeclarativeMixin:
__table__: 'Table'
@orm.declarative_mixin
class InheritedDeclarativeMixin(DeclarativeMixin):
__bases__: Iterable[Any]
@orm.declarative_mixin
class Polymorphi... | StarcoderdataPython |
3362329 | <reponame>mytram/learning-python
# Largest prime factor
# Problem 3
# The prime factors of 13195 are 5, 7, 13 and 29.
#
# What is the largest prime factor of the number 600851475143 ?
#
#
from common import PrimeGenerator
def solve(problem = 600_851_475_143):
series = PrimeGenerator()
prime = next(series)
... | StarcoderdataPython |
1717476 | <gh_stars>1-10
__source__ = 'https://leetcode.com/problems/range-sum-of-bst/'
# Time: O(N)
# Space: O(H) height of the tree
#
# Description: Leetcode # 938. Range Sum of BST
#
# Given the root node of a binary search tree,
# return the sum of values of all nodes with value between L and R (inclusive).
#
# The binary s... | StarcoderdataPython |
3339233 | <reponame>davehadley/graci<filename>docs/examples/simple_nested.py
import operator
import fungraph
if __name__ == "__main__":
f = fungraph.fun(
operator.add,
fungraph.fun(operator.mul, 1, 2),
fungraph.fun(operator.mul, 3, 4),
)
print(f()) # prints 14
| StarcoderdataPython |
1701448 | <gh_stars>1-10
from const import WHITE, BLACK
def switch_color(color) -> Int:
"""
Assigns opposite color.
"""
if color == BLACK:
return WHITE
else:
return BLACK
class Player:
""" Human player """
def __init__(self, gui, color="black"):
self.color = color
s... | StarcoderdataPython |
11163 | import pytest
import cudf
import mock
from cuxfilter.charts.core.non_aggregate.core_non_aggregate import (
BaseNonAggregate,
)
from cuxfilter.dashboard import DashBoard
from cuxfilter import DataFrame
from cuxfilter.layouts import chart_view
class TestCoreNonAggregateChart:
def test_variables(self):
... | StarcoderdataPython |
4801487 | <filename>capitulo2_repeticoes/while_infinito.py
numero = int(input('Digite um numero: '))
while numero <= 100:
print('\t', numero)
numero += 1
print('LAÇO ENCERRADO...')
| StarcoderdataPython |
4823647 | g = float(input("Digite um angulo em graus: "))
r = ((g * 3.14)/180)
print("O angulo {} em radianos ficarah: {:.4f}".format(g,r))
| StarcoderdataPython |
3239536 | from chainercv.transforms.bbox.crop_bbox import crop_bbox # NOQA
from chainercv.transforms.bbox.flip_bbox import flip_bbox # NOQA
from chainercv.transforms.bbox.resize_bbox import resize_bbox # NOQA
from chainercv.transforms.bbox.translate_bbox import translate_bbox # NOQA
from chainercv.transforms.image.center_cro... | StarcoderdataPython |
1717899 | # coding: utf-8
import cmath
import numpy as np
from rcwa.common import matmul, redheffer_star_prod, get_input
from rcwa.structure import HomogeneousStructure
from rcwa.source import Source
from rcwa._constants import UNIT_MAT_2D
def save_outputs(R, T):
with open('output.toml', 'w') as fid:
fid.write('[R... | StarcoderdataPython |
1607723 | from copy import deepcopy
from typing import List
import numpy as np
import pandas as pd
import pytest
from xarray import DataArray, Dataset, Variable, concat
from xarray.core import dtypes, merge
from . import (
InaccessibleArray,
assert_array_equal,
assert_equal,
assert_identical,
requires_dask... | StarcoderdataPython |
44349 | <reponame>isabella232/cronus-agent<filename>agent/agent/lib/agent_thread/threadmgr.py<gh_stars>1-10
#pylint: disable=R0904,W0105
'''
Copyright 2014 eBay Software Foundation
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 ... | StarcoderdataPython |
73774 | class Rect(object):
def __init__(self, cx, cy, width, height, confidence):
self.cx = cx
self.cy = cy
self.width = width
self.height = height
self.confidence = confidence
self.true_confidence = confidence
def overlaps(self, other):
if abs(self.cx - other.c... | StarcoderdataPython |
3396097 | <gh_stars>1-10
# Generated by Django 1.11.28 on 2020-02-17 10:58
import collections
import jsonfield.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('site_configuration', '0002_auto_20160720_0231'),
]
operations = [
migrations.AlterFiel... | StarcoderdataPython |
3270069 | """Leetcode 5. Longest Palindromic Substring
Medium
URL: https://leetcode.com/problems/longest-palindromic-substring/
Given a string s, find the longest palindromic substring in s.
You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Examp... | StarcoderdataPython |
1642682 | import numpy as np
import pytest
from numpy.testing import assert_almost_equal as aae
from spectra import SticksSpectrum
def setup():
pass
def teardown():
pass
def test_init():
energies, intensities = np.arange(10), np.arange(10)
s1 = SticksSpectrum("Hello World", energies, intensities, units="ms... | StarcoderdataPython |
48570 | for i in range(plan_arguments['RUN_NUM']):
############################################# CC #############################################
add_test(name='cc_feature_rtest',
tags=['L10', 'cc'],
args=[' -rtlarg +uvm_set_config_int=uvm_test_top,layers,%d ' % plan_arguments['LAYER_NUM'], ge... | StarcoderdataPython |
118153 | <gh_stars>1-10
import json
import re
from statistics import mean
from timeit import repeat
import numpy as np
from scipy.optimize import curve_fit
from sklearn.metrics import r2_score
pattern = r"- (.*) bsz (\d+): total (\d+.\d+), propotion (\d+.\d+)"
with open("tests/profile/nsys_extract.log", "r") as fp:
tex... | StarcoderdataPython |
107622 | <filename>forecaster/forms.py<gh_stars>1-10
from django import forms
import datetime
import json, requests
class UserForm(forms.Form):
def hitAPI():
start = datetime.date.today()
tdelta = datetime.timedelta(days=1)
end = start + tdelta
if start.weekday() in [5, 6]:
... | StarcoderdataPython |
1662635 | <reponame>AmashiSenpai/holodex
from typing import Any
class AutoCompleteInfo:
def __init__(self, response: Any) -> None:
self._response = response
@property
def type(self) -> str:
return self._response["type"]
@property
def value(self) -> str:
return self._response["value... | StarcoderdataPython |
3276799 | <filename>slacktor/auth.py
import functools
from . import _GenericAPI
from .api_wrapper import RestAPI
_API = {
"test": {
"url": "/api/auth.test",
"method": "GET",
"params": {
"token": { "type": "string", "is_required": True },
},
"parse_data": ("url", "team", "... | StarcoderdataPython |
1635038 | <filename>RI/flask_server/tapi_server/models/tapi_oam_pm_bin_data.py<gh_stars>10-100
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from tapi_server.models.base_model_ import Model
from tapi_server.models.tapi_commo... | StarcoderdataPython |
4843010 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
# Third party
from django.template import Context
from django.template import loader
from django.core.mail import EmailMultiAlternatives
# Local
from .base import BaseBackend
class EmailBackend(BaseBackend):
plaintext_template = 'verification/email.... | StarcoderdataPython |
7573 | <reponame>Mandera/generalfile
import pathlib
import os
from generallibrary import VerInfo, TreeDiagram, Recycle, classproperty, deco_cache
from generalfile.errors import InvalidCharacterError
from generalfile.path_lock import Path_ContextManager
from generalfile.path_operations import Path_Operations
from generalfi... | StarcoderdataPython |
3280035 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2021 Huawei Device Co., Ltd.
# 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
#
#... | StarcoderdataPython |
3256634 | from collections import OrderedDict
import torch
from torch import nn
import torch.nn.functional as F
from torchvision.ops import misc as misc_nn_ops
from torchvision.ops import MultiScaleRoIAlign
from .generalized_rcnn import GeneralizedRCNN
from .rpn import AnchorGenerator, RegionProposalNetwork
from .roi_heads im... | StarcoderdataPython |
1771861 | import typing as tp
import astropy.io.fits as fits
import astropy.time as astro_time
import astropy.units as u
import h5py
import numpy as np
import scipy.interpolate as interpolate
from astropy.coordinates import get_body, get_moon, get_sun
from gbmgeometry.utils.gbm_time import GBMTime
class PositionInterpolator(... | StarcoderdataPython |
3237870 | <filename>dataprep/clean/components/cat_imputation/most_frequent_imputer.py
"""
Implement categorical most-frequent imputer.
"""
from typing import Any, List, Optional
import dask.dataframe as dd
class MostFrequentImputer:
"""Most frequent imputer for imputing categorical values
Attributes:
null_valu... | StarcoderdataPython |
3297679 | <gh_stars>0
# Creating the database and tables
import sqlite3
conn = sqlite3.connect('data_wrangling.sqlite')
conn.text_factory = str
cur = conn.cursor()
#Make some fresh tables using executescript()
cur.execute('''DROP TABLE IF EXISTS nodes''')
cur.execute('''DROP TABLE IF EXISTS nodes_tags''')
cur.execute... | StarcoderdataPython |
3217862 | # -*- coding: utf-8 -*-
# Copyright 2016 OpenMarket Ltd
#
# 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 la... | StarcoderdataPython |
3323793 | <reponame>Black-Black-Man/MsWaveNet
# coding:utf-8
"""
_author = <NAME>
"""
import librosa
import wave
import numpy as np
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.optim import lr_scheduler
from torchvision import models
from torch.autograd... | StarcoderdataPython |
3254718 | """Module to check the validity of DOIs."""
import re
def is_doi(identifier):
"""Determine whether the given identifier has a valid DOI format."""
if not isinstance(identifier, str):
return False
identifier = normalize(identifier)
identifier = identifier.split('/')
if len(identifier) < 2... | StarcoderdataPython |
4841157 | # Copyright 2018 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# or in th... | StarcoderdataPython |
1788034 | """
*
* Author: <NAME>(coderemite)
* Email: <EMAIL>
*
"""
X=[0,-1,0,1,0]
Y=[0,1,1,1,2]
n,*a=[*open(0)]
n=int(n)
a=[list(x) for x in a]
for r in range(n-2):
for c in range(1,n-1):
if all(a[r+y][c+x]=='.' for y,x in zip(Y,X)):
for y,x in zip(Y,X):
a[r+y][c+x]='#'
print('YNEOS'[any('.'in x for x ... | StarcoderdataPython |
3266334 | <reponame>limingmax/WFCode<filename>trend/src/zutils/zrpc/client/__init__.py
# @Time : 2018-11-06
# @Author : zxh
| StarcoderdataPython |
105658 | from machine import I2C, Pin
# Create an I2C object
i2c = I2C(0, sda = Pin(19), scl = Pin(18))
address = i2c.scan() # list
# Scan for devices
print('Address:', hex(address[0])) | StarcoderdataPython |
25557 | <reponame>GouaiedYosra/mask_rcnn<gh_stars>0
# example of extracting bounding boxes from an annotation file
from xml.etree import ElementTree
# function to extract bounding boxes from an annotation file
def extract_boxes(filename):
# load and parse the file
tree = ElementTree.parse(filename)
# get the root of the doc... | StarcoderdataPython |
1656419 | import os
import logging
logger = logging.getLogger(__name__)
import numpy as np
import astropy.io.fits as fits
import matplotlib.pyplot as plt
from ...echelle.imageproc import combine_images
from ...echelle.trace import find_apertures, load_aperture_set
from .common import (get_bias, get_mask, correct_overscan,
... | StarcoderdataPython |
4807666 | <reponame>sfermigier/bocadillo
import pytest
from bocadillo import App, provider, useprovider
@pytest.mark.parametrize("by_name", (False, True))
def test_useprovider(app: App, by_name):
called = False
@provider
async def set_called():
nonlocal called
called = True
@app.route("/")
... | StarcoderdataPython |
1618646 | <filename>examples/python/metar_get_keys.py
# (C) Copyright 2005- ECMWF.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
#
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it... | StarcoderdataPython |
1627430 | <gh_stars>0
import unittest
import numpy as np
import torch
from torch.autograd import Variable
import torch.nn
from pyoptmat import ode, models, flowrules, hardening, utility, damage
from pyoptmat.temperature import ConstantParameter as CP
torch.set_default_tensor_type(torch.DoubleTensor)
torch.autograd.set_detect... | StarcoderdataPython |
59487 | import os
def get_icons():
icons = {}
icons_walk = os.walk("src/icons")
_, authors, _ = next(icons_walk)
for root, _, files in icons_walk:
author = os.path.split(root)[-1]
icons[author] = files
return icons
def generate_js(icons):
lines = []
all_icons = []
for author,... | StarcoderdataPython |
3365642 | <reponame>krinj/k-package-template
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Bump the micro-version number of the package.
"""
import os
import re
if __name__ == "__main__":
with open("version", "r") as f:
current_version = f.readline()
versions = current_version.split(".")
versi... | StarcoderdataPython |
1685664 | <reponame>jumpscale7/jumpscale_portal
def main(j, args, params, tags, tasklet):
page = args.page
modifier = j.html.getPageModifierGridDataTables(page)
filters = dict()
for tag, val in args.tags.tags.iteritems():
if tag in ('gid', ) and val and not val.startswith("$$"):
filters['gid... | StarcoderdataPython |
3305417 | <filename>pangakupu/grid_export.py
import pygame
import numpy as np
from pathlib import Path
import config
import bitstring as bs
import grid_drawer as gd
import grid_number as gn
cf = config.ConfigFile()
grids_path = cf.configfile[cf.computername]["grids_file_path"]
SPLITTER1 = "-"
SPLITTER2 = "x"
def get_grid_nam... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.