id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
3211910 | import torch
from registry import registry
from models.model_base import Model, StandardTransform, StandardNormalization
from mldb.utils import load_model_state_dict
model_params = {
'resnet18_ssl': { 'arch': 'resnet18',
'eval_batch_size': 256,
'img_crop_size': 224,
... | StarcoderdataPython |
214013 | <reponame>matu3ba/cports
pkgname = "libffi8"
pkgver = "3.4.2"
pkgrel = 0
build_style = "gnu_configure"
configure_args = [
"--includedir=/usr/include", "--disable-multi-os-directory", "--with-pic"
]
hostmakedepends = ["pkgconf"]
# actually only on x86 and arm (tramp.c code) but it does not hurt
makedepends = ["linux... | StarcoderdataPython |
12827057 | import math
import torch
from torch.nn.modules.loss import _Loss
__all__ = ['DiagLoss', 'ADD_loss', 'WingLoss', 'LossManager']
class DiagLoss(_Loss):
__constants__ = ['reduction']
def __init__(self, size_average=None, reduce=None, reduction: str = 'mean') -> None:
super().__init__(size_average, redu... | StarcoderdataPython |
12805822 | import json
import sys
import matplotlib.pyplot as plt
def main(path):
vals = {}
with open(path) as f:
vals = json.load(f)
plt.plot(vals['gp_x'], vals['gp_y'])
plt.title('Uncertainty curve')
plt.xlabel('Training points')
plt.ylabel('Average uncertainty')
plt.show()
if __name__ ... | StarcoderdataPython |
1976492 | <filename>day4-5.py
# Twowaits
Twowaits Problem
from collections import Counter
votes =['aman','ammy','amaan','amann','aaman','amu',
'ammu','amy','ammmyy','ammyy','aman','parna','naman']
#Count the votes for persons and stores in the dictionary
vote_count=Counter(votes)
#Find the maximum numbe... | StarcoderdataPython |
239171 | import unittest
import sequeval
class IndexListTestSuite(unittest.TestCase):
def test_setitem(self):
indexlist = sequeval.IndexList()
indexlist.append(None)
indexlist[0] = 'Zero'
self.assertEqual(indexlist[0], 'Zero')
self.assertEqual(indexlist.index('Zero'), 0)
def ... | StarcoderdataPython |
6575370 | <filename>setup.py
from setuptools import setup, find_packages
# allows to get version via python setup.py --version
__version__ = "0.1.0"
setup(
name="torchfid",
version=__version__,
description="Installable FID score calculation",
url="https://github.com/rromb/torchfid",
author="<NAME>",
a... | StarcoderdataPython |
249868 | # Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE... | StarcoderdataPython |
3475253 | <gh_stars>1-10
"""Three-dimensional mobjects."""
from __future__ import annotations
__all__ = [
"ThreeDVMobject",
"Surface",
"ParametricSurface",
"Sphere",
"Dot3D",
"Cube",
"Prism",
"Cone",
"Arrow3D",
"Cylinder",
"Line3D",
"Torus",
]
from typing import *
import numpy... | StarcoderdataPython |
4905201 | <filename>ssm/factorial_hmm/base.py
import warnings
import jax.numpy as np
import jax.random as jr
from ssm.factorial_hmm.posterior import FactorialHMMPosterior
from ssm.factorial_hmm.initial import FactorialInitialCondition
from ssm.factorial_hmm.transitions import FactorialTransitions
from ssm.factorial_hmm.emissio... | StarcoderdataPython |
1845484 | # Generated by Django 2.1 on 2018-08-25 07:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('task', '0007_auto_20180821_1416'),
]
operations = [
migrations.AddField(
model_name='task',
name='deadline',
... | StarcoderdataPython |
1946593 | <reponame>tidalmigrations/machine_stats
"""
Script to prepare JSON output for tidal sync servers from the list of hosts
"""
import argparse
import json
import os
import shutil
from functools import partial
from ansible.utils.path import unfrackpath
# Loading config file must be prior to importing most of the ansible... | StarcoderdataPython |
172135 | <filename>tests/test_entropy_encoders/test_arithmetic_coding.py
from typing import List, Sequence
import hypothesis.strategies as st
from entropy_encoders import arithmetic_coding
from hypothesis import given
EOF = "\n"
text_strategy = st.text(st.characters(blacklist_characters=EOF),
max_size=... | StarcoderdataPython |
3584452 | <reponame>elisabethzinck/Fairness-oriented-interpretability-of-predictive-algorithms
import torch
import os
import platform
import numpy as np
import pandas as pd
import re
import time
import pytorch_lightning as pl
from torchmetrics.functional import accuracy, auroc
from src.models.data_modules import CheXpertDataMod... | StarcoderdataPython |
77345 | import argparse
import logging
import os
import json
import pickle
import random
import time
import numpy as np
import torch
from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler, Dataset
from transformers import AdamW, get_linear_schedule_with_warmup, set_seed
from utils import set_l... | StarcoderdataPython |
9623195 | # -*- coding: utf-8 -*-
import glob
import os
import pandas as pd
from glassimaging.dataloading.niftidataset import NiftiDataset
import logging
import json
from torch.utils.data import Dataset
class Brats18(NiftiDataset):
available_sequences = ['flair', 't1', 't1Gd', 't2']
"""The image paths for each subje... | StarcoderdataPython |
4815661 | from graphics import drawRectangle, fillRectangle
def mapreader(world):
'''
this reads the map file and creates a dict of cords=key terrain type=val.
'''
world.mapdict = {} #key = cords , value = blocktype
worlddoc = open('map.txt', 'r')
lineCount = 0
world.tileWidth = 0
for line ... | StarcoderdataPython |
8189323 | <reponame>trueMiskin/tree-structures<gh_stars>0
#!/usr/bin/env python3
from array import array
import random
import time
import sys
CASES = [
# test number, number of operations, operation chances
[1, 100, [0.4, 0.3, 0.3, 0, 0]],
[2, 1_000, [0.3, 0.3, 0.3, 0.05, 0.05]],
[3, 10_000, [0.... | StarcoderdataPython |
94485 | import xlrd
import numpy as np
import xlwt
from tempfile import TemporaryFile
book = xlwt.Workbook()
sheet1 = book.add_sheet('sheet1')
data=xlrd.open_workbook(r'C:\Users\Desktop\teamE\D1_route.xlsx')
table=data.sheets()[0]
all_data=[]
row_num=table.nrows
col_num=table.ncols
all_loc=[]
for i in ran... | StarcoderdataPython |
6555835 | <filename>src/scripts/training_stats.py
import argparse
import glob
import json
import os
import time
from datetime import timedelta
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Training stats')
parser.add_argument('--path', default='outputs/librispeech', help='path')
parser.add... | StarcoderdataPython |
3546239 | <gh_stars>0
def greeting():
print("how 're u doing!!")
answer = input()
if answer.lower() == "cool n u":
print("me too great")
else:
print("Hmm all is going to be fine")
greeting()
| StarcoderdataPython |
3323757 | <filename>strategy/script/methods/attack.py
#!/usr/bin/env python
from __future__ import print_function
import rospy
import math
class Attack(object):
def ClassicAttacking(self, goal_dis, goal_ang):
v_x = goal_dis * math.cos(math.radians(goal_ang))
v_y = goal_dis * math.sin(math.radians(goal_ang))
v... | StarcoderdataPython |
6558664 | <filename>main.py
from __future__ import annotations
from copy import copy
from dataclasses import dataclass
from operator import add, floordiv, mul, sub
from tkinter import Button, Entry, StringVar, Tk
from typing import Any, Callable, Union
class App:
def __init__(self):
self.root = Tk()
self.root.title("Calcul... | StarcoderdataPython |
4847012 | # Generated by Django 2.0.3 on 2019-01-02 12:05
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('product', '0026_auto_20190102_2053'),
]
operations = [
migrations.AlterField(
model_name='produ... | StarcoderdataPython |
1870504 | <filename>minicash/utils/parsers.py<gh_stars>1-10
import re
import sys
import os
import hashlib
def isValidProof(fprint, proof, difficulty):
keyhash = hashlib.sha256()
fingerproof = fprint + '_' + str(proof)
keyhash.update(fingerproof.encode('utf-8'))
hashResult = keyhash.hexdigest()
if not hashRes... | StarcoderdataPython |
9694895 | from __future__ import division
import copy
from operator import itemgetter
import numpy as np
from flatland.core.env_observation_builder import ObservationBuilder
from flatland.envs.distance_map import DistanceMap
#from flatland.envs.rail_env_shortest_paths import get_shortest_paths
from shortestpath import get_shor... | StarcoderdataPython |
4952737 | <reponame>admariner/jurigged<filename>tests/snippets/dandelion:main.py
class Flower:
def __init__(self, name):
self.name = name
def sing(self):
return f"O {self.name}, how beautiful are thee!"
def test(self):
print("test 1 2 3")
def pluck(n):
return n - 1
def plack():
re... | StarcoderdataPython |
5114606 | <reponame>Matheus-Rangel/dash-carbon-components<gh_stars>1-10
# AUTO GENERATED FILE - DO NOT EDIT
from dash.development.base_component import Component, _explicitize_args
class NumberInput(Component):
"""A NumberInput component.
NumberInput component
Keyword arguments:
- allowEmpty (boolean; default False): `tr... | StarcoderdataPython |
8001744 | <filename>lucy/verbosity.py
import os
from contextlib import redirect_stdout
VERBOSE = False
def set_verbosity(verbose):
"""Turn on/off verbose output."""
global VERBOSE
VERBOSE = verbose
def verbose(func):
"""Redirect output to /dev/null if VERBOSE is False."""
def decorator(*args, **kwargs):
... | StarcoderdataPython |
12852193 | from datetime import datetime
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, no_translations
from note.models import NoteIndexPage
from note.models import NotePage
class Command(BaseCommand):
help = 'Create note page'
def add_arguments(self, parser):
... | StarcoderdataPython |
11255316 | from noise.backends.experimental.backend import ExperimentalNoiseBackend
noise_backend = ExperimentalNoiseBackend()
| StarcoderdataPython |
1960909 | <filename>5/evens_calculator.py<gh_stars>0
range_length = int(input("Type range length: "))
even_sum = 0
for i in range(0, range_length, 2):
even_sum += i
print(f"Sum of evens in range from 0 to {range_length} is equal {even_sum}") | StarcoderdataPython |
6488036 | ########################################################################
# LeetCode Problem Number : 102
# Difficulty Level : Medium
# URL : https://leetcode.com/problems/binary-tree-level-order-traversal/
########################################################################
from binary_search_tree.tree_node import ... | StarcoderdataPython |
96510 | '''Compute the SLR parsing table for a grammar read from stdin in extended
sytax, printing the original grammar, augmented grammar, first sets, follow
sets, and table to stdout in HTML.'''
import sys
from cfg.cfg_reader import *
from cfg.slr import *
try:
G = parse_cfg(sys.stdin.read())
except ValueError, e:
... | StarcoderdataPython |
6574956 | <reponame>OptimalDesignLab/pyStatReduce
# run_hadamard_eigen_accuracy
import os
import sys
import errno
import numpy as np
import chaospy as cp
from pystatreduce.stochastic_collocation import StochasticCollocation
from pystatreduce.quantity_of_interest import QuantityOfInterest
from pystatreduce.dimension_reduction i... | StarcoderdataPython |
3245288 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import argparse
# from functools import lru_cache
# from itertools import combinations
from copy import deepcopy
import time
# import regex
from collections import defaultdict
def arguments():
# Handle command line arguments
parser = argparse.ArgumentParser(descriptio... | StarcoderdataPython |
1705756 | <filename>kivygallery.py
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.label import Label
from kivy.uix.behaviors import ButtonBehavior
from kivy.properties import StringProperty, ListProperty
from kivy.clock import Clock
Builder.load_string("""
#:imp... | StarcoderdataPython |
3522956 | <gh_stars>100-1000
# Copyright 2017 Battelle Energy Alliance, 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 applica... | StarcoderdataPython |
1719173 | import os
import time
import urllib.parse
import requests
from bs4 import BeautifulSoup
import argparse
base_url = ""
directory = ""
is_directory_specified = False
def crawl_all_files(url):
global base_url
global directory
global is_directory_specified
r = requests.get(url)
soup = BeautifulSoup... | StarcoderdataPython |
6563953 | """
Controls the scene graph viewer.
@author <NAME>
"""
import json
from tools.envedit.edenv_component import EComponent
from tools.envedit.graph_node import GraphNode
from tools.envedit.gui.gui_component import GUIComponent
from tools.envedit.gui.gui_dock_layout import GUIDockLayout
from tools.envedit.gui.gui_frame ... | StarcoderdataPython |
1904982 | from django.shortcuts import render
# Create your views here.
from lib.http import render_json
from vip.models import Vip
def show_vip_permissions(request):
data={}
for vip in Vip.objects.all():
per_list=[]
for per in vip.permissions:
per_list.append(per.description)
data... | StarcoderdataPython |
81337 | from .pyomexmeta import PersonalInformation
from .pyomexmeta import EnergyDiff
from .pyomexmeta import PhysicalProcess
from .pyomexmeta import RDF, Editor, PhysicalEntity
from .pyomexmeta import SingularAnnotation
from .pyomexmeta import OmexMetaException
from .pyomexmeta_api import PyOmexMetaAPI, get_version, eUriType... | StarcoderdataPython |
9787965 | import asyncio
from asyncio import Event
from typing import Awaitable
class TestBind:
def __init__(self):
return
async def keyEVT(self):
def bind(self, event:Event, handler: Awaitable):
async def print_msg(text: str = None):
if text is not None:
print(text)
print('sleepi... | StarcoderdataPython |
1911120 | <gh_stars>1-10
import capybara
from capybara.tests.suite import DriverSuite
@capybara.register_driver("webtest")
def init_webtest_driver(app):
from capybara_webtest.driver import Driver
return Driver(app)
WebTestDriverSuite = DriverSuite(
"webtest",
skip=["css", "frames", "hover", "js", "modals", "... | StarcoderdataPython |
11242081 | import numpy
import pylab
from cmepy import model, solver, recorder
def main():
initial_copies = 20
m = model.create(
propensities = [lambda x: initial_copies - x],
transitions = [(1, )],
shape = (initial_copies + 1, ),
initial_state = (0, )
)
s = solver.create... | StarcoderdataPython |
3400801 | # -*- coding: utf-8 -*-
"""Add the Reveal.js specific short codes"""
import yaml
from nikola.plugin_categories import ShortcodePlugin
from nikola.utils import LOGGER
revealCodes = {
"start" : "<div class=\"reveal\" style=\"width:100%;height:75vh\"><div class=\"slides\"><section>",
"startSub" : "<section>",... | StarcoderdataPython |
153279 | '''
<NAME> 10/2/2017
<EMAIL>
Switches the MMGIS environment to release or development
Switching to release sets up the default test mission
and can limit access to tools
Usage Examples:
prepare.py d # switch to Dev env
prepare.py r # switch to Release env ... | StarcoderdataPython |
6503167 | <gh_stars>10-100
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# __Author__ = angel
# _PlugName_ = gedior upload
import re
def curl3(
url, post=None, raw=None, proxy=None, method=None,
referer=None, cookie=None,
user_agent='Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)',
header=No... | StarcoderdataPython |
8182454 | import os
import re
import sys
import copy
import logging
import warnings
import subprocess
import shutil
import uuid
import tempfile
import asyncio
from collections import OrderedDict
from pprint import pformat
from yggdrasil import platform, tools, languages, multitasking, constants
from yggdrasil.components import i... | StarcoderdataPython |
66437 | import numpy as np
import pandas as pd
from sklearn.base import TransformerMixin, ClassifierMixin
from suricate.preutils import concatixnames, createmultiindex, addsuffix
# THIS SHOULD BE OBSOLETE
class PipeDfClf(ClassifierMixin):
def __init__(self,
transformer,
classifier,
... | StarcoderdataPython |
297071 | from django.apps import AppConfig
class LikesConfig(AppConfig):
name = 'likes'
def ready(self):
super(LikesConfig,self).ready()
from .import signals | StarcoderdataPython |
1636327 | """Top-level package for EWAH Bool Utils."""
__version__ = '0.1.0'
from .ewah_bool_wrap import *
| StarcoderdataPython |
12803381 | <gh_stars>0
from flask_restful import Resource, reqparse, abort
from flask import request
from toko.models.servico_model import ServicoModel
from toko.schemas.servico_schema import ServicoSchema
class ServicoResource(Resource):
parser = reqparse.RequestParser()
parser.add_argument("id_proposta",
... | StarcoderdataPython |
3522895 | import unittest
from double_index_max_subsequence import double_index_max_subsequence
class Test_Case_Double_Index_Max_Subsequence(unittest.TestCase):
def test_double_index_max_subsequence(self):
self.assertEqual("[(56, 90), (60, 95), (65, 100), (68, 110), (70, 150), (75, 190)]", str(double_index_max_subse... | StarcoderdataPython |
5090292 | # -*- coding: utf-8 -*-
import logging
from typing import NoReturn, Text
import coloredlogs
from settings.handlers import (BaseFileHandler, BaseStreamHandler,
ContextHandler)
from tools.os import OS
# ===========================================================================... | StarcoderdataPython |
9781127 | """ Loading Raw data """
import logging
from dataclasses import dataclass
from numbers import Number
from pathlib import Path
from typing import List, Tuple, Union
import numpy as np
import pandas as pd
import xarray as xr
import nowcasting_dataset.filesystem.utils as nd_fs_utils
from nowcasting_dataset.data_sources.... | StarcoderdataPython |
1819358 | from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
import os
import tensorflow as tf
import tensorflow_probability as tfp
import numpy as np
from tqdm import trange
from scipy.io import savemat, loadmat
from scipy.stats import norm
import matplotlib.pyplot as ... | StarcoderdataPython |
4842219 | import shutil
import tempfile
from django.test import Client, TestCase, override_settings
from django.urls import reverse
from django.contrib.auth import get_user_model
from django.core.files.uploadedfile import SimpleUploadedFile
from django.conf import settings
from ..forms import PostForm
from ..models import Post, ... | StarcoderdataPython |
8104975 | """
This is test file for node_holder.py
"""
import unittest
import node_holder
class TestNodeHolder(unittest.TestCase):
"""Unit test for functions in node_holder.py"""
def test_fetch_change_id_postive_test(self):
"""positive unit test for fetch_change_id func"""
url = ('https://review.rdopr... | StarcoderdataPython |
11266256 | """ Client classes for individual A/V Receivers to be used by the PolyGlot node classes """
from .av_device import AvDevice
from .pioneer_vsx1021_device import PioneerVSX1021Device
from .sony_bravia_xbr_65x810c_device import SonyBraviaXBR65X810CDevice
| StarcoderdataPython |
9673288 | <filename>Testing/Python/AnalogOffsetRemoverTest.py
import btk
import unittest
import _TDDConfigure
import numpy
class AnalogOffsetRemoverTest(unittest.TestCase):
def test_Test0(self):
acq = btk.btkAcquisition()
acq.Init(0,25,1,1)
data = numpy.empty([25,1]);
data.fill(5.0)
acq.GetAnalog(0).SetVal... | StarcoderdataPython |
9656957 | # Copyright 2021 Foundries.io
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | StarcoderdataPython |
5143178 | import torch
import tqdm.auto as tqdm
import fairseq
from config import arch_args, config, task
from utils.env import enable_log, get_device
from utils.model import (build_model, inference_step, load_data_iterator,
try_load_checkpoint)
def main():
logger = enable_log()
device = get_d... | StarcoderdataPython |
4892529 | <gh_stars>1-10
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
import blocks.urls
import prices.urls
websocket_urlpatterns = (
blocks.urls.websocket_urlpatterns + prices.urls.websocket_urlpatterns
)
application = ProtocolTypeRouter(
{"websocket": Auth... | StarcoderdataPython |
12806643 | import torch
def weight_init(m):
# print(m)
if isinstance(m, torch.nn.Linear):
torch.nn.init.xavier_normal_(m.weight)
if m.bias is not None:
torch.nn.init.constant_(m.bias, 0)
elif isinstance(m, torch.nn.Conv2d):
torch.nn.init.xavier_normal_(m.weight)
if m.bias ... | StarcoderdataPython |
11245728 | <reponame>lkljlh1001/HelloPython<filename>Python3Lab/Lab03.py
# ((**lab01 ~ lab02의 예제를 함수로 작성**))
#<이름 짓기>
# 파스칼 표기법 : 첫단어를 대문자로 시작하며 이름을 지음
# ex) Employees, Departments
# RegisterEmployee,JoinMember
# 카멜 표기법 : 첫단어를 소문자로 시작하며 이름을 지음
# ex) registerEmployee
# 스네이크 표기법 : 소문자와 _기호를 이용해서 ... | StarcoderdataPython |
6493970 | #!/usr/bin/python
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import *
from User import *
db=create_engine("sqlite:///tutorial.db")
metadata = MetaData(db)
users_table = Table('users',metadata,
Column('id',Integer,primary_key=True),
Column('name',String(20)),
Column('fu... | StarcoderdataPython |
4893782 | <filename>tests/agents_tests/test_pgt.py
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases() # NOQA
import basetest_pgt... | StarcoderdataPython |
12815399 | <filename>autojs.py
#coding:utf-8
import types
import sublime
import sublime_plugin
import socket
import json
import threading
import traceback
from io import StringIO
from contextlib import closing
hostname = ''
port = 1209
class AutoJsServer:
def __init__(self, hostname, port):
self.hostname = hostna... | StarcoderdataPython |
3415481 | <reponame>Exterminus/myftp
# -*- coding: utf-8 -*-
#!/usr/bin/env python3
"""
Cliente
<NAME>
UFSJ
"""
import sys
import socket
import getpass
#utilizado para serialização de dados..
import pickle
#conexao segura.. todas as conexoes serao segura
import ssl
class Cliente(object):
"""Classe cliente conecta
ao ser... | StarcoderdataPython |
122972 | <filename>Hamming Distance.py
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
count = 0
for i in range(30, -1, -1):
mask = 1 << i
digitX = x & mask
digitY = y & mask
if digitX != digitY:
count += 1
ret... | StarcoderdataPython |
12806210 | # Copyright 2016, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the f... | StarcoderdataPython |
4976917 | from .core.cloud_logger import CloudLogger as __CloudLogger
__version__ = "0.2.3"
__all__ = ["cloud_logger"]
cloud_logger = __CloudLogger() | StarcoderdataPython |
9682854 | <filename>tests/slack_sdk_async/audit_logs/test_async_client.py
import unittest
from slack_sdk.audit_logs.async_client import AsyncAuditLogsClient
from slack_sdk.audit_logs import AuditLogsResponse
from tests.helpers import async_test
from tests.slack_sdk.audit_logs.mock_web_api_server import (
cleanup_mock_web_ap... | StarcoderdataPython |
5001359 | <gh_stars>1-10
import boto3
import rasterio
from rasterio.io import MemoryFile
s3 = boto3.client('s3')
class Outputs(object):
def __init__(self, arr, profile):
self.arr = arr
self.profile = profile
def to_array(self):
return self.arr
def to_gtiff(self, outfile):
with r... | StarcoderdataPython |
4832783 | import io
import os
import typer
from .core import DrCov
app = typer.Typer()
@app.command()
def extract_specific_cov_info(
in_file_path: str, out_file_path: str, module_name: str
) -> None:
dr_cov = DrCov()
dr_cov.import_from_file(in_file_path)
dr_cov.export_specific_module_to_file(module_name, out... | StarcoderdataPython |
3324812 | import os
from os import path
from collections import namedtuple
from hashlib import sha1
import cPickle as pickle
from itertools import imap, ifilterfalse
from contextlib import contextmanager
import re
import json
FileItem = namedtuple('FileItem', 'path checksum size time')
CHUNK_SIZE = 64 * 1024 # 64 KB
def repo_... | StarcoderdataPython |
1865474 | <filename>serie primos (1).py
#!/usr/bin/env python
# coding: utf-8
# In[3]:
def SeriePrimos(limite1):
n = 0
d = 3
divisor = 1
suma = 0
primo = 0
estado = False
for k in range(1, limite1 + 1):
n = n + 1
while not estado:
for i in range(1, primo + 1):
... | StarcoderdataPython |
5055332 | # E M O J I E S
SLOTH_EMOJI = "\U0001F9A5"
GLOBE_EMOJI = "\U0001F310"
AUTO_EMOJI = "\U0001F30E"
STAR_EMOJI = "\U00002B50"
CLOCK_EMOJI = "\U0001F552"
SAD_EMOJI = "\U00002639"
SLEEP_EMOJI = "\U0001F634"
REMOVE_EMOJI = "\U0001F5D1\U0000FE0F"
ADD_EMOJI = "\U00002795"
VIEW_EMOJI = "\U0001F4C4"
NEUTRAL_FACE_EMOJI... | StarcoderdataPython |
3494913 | <gh_stars>0
from setuptools import setup, find_packages
setup(
name='nixmyshell',
version='0.0.1',
description='A script to create shell.nix files',
author="<NAME>",
license="MIT",
packages=find_packages(),
entry_points={
'console_scripts': [
'nixmyshell=nixmyshell.nixmy... | StarcoderdataPython |
271921 | import tensorflow as tf
tf.set_random_seed(777) # for reproducibility
x_data = [1, 2, 3]
y_data = [1, 2, 3]
# W의 initial value 지정
W = tf.Variable(tf.random_normal([1]), name='weight')
# training 변수 지정(placeholder)
X = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)
# 기울기 없는 regression model 가정
hypothesi... | StarcoderdataPython |
11271415 | from compressario.compress import Compress
from compressario.diagnostics import (
compress_report,
savings,
savings_report,
storage_size,
)
#from compressario.formatter import StorageSize
from compressario.type_compressor import BaseTypeCompressor, DefaultCompressor
from compressario.typing import pdT
f... | StarcoderdataPython |
8046704 | <reponame>Michael-F-Bryan/cheesecake_kwalitee_index<filename>cheesecake_kwalitee_index/utils.py
"""
Miscellaneous utility functions, classes, constants and decorators.
"""
import logging
import sys
def get_logger(name, log_file, log_level=None):
"""
Get a logger object which is set up properly with the corr... | StarcoderdataPython |
222101 | <filename>gwsc_ingest/cli.py
import argparse
from .era5.cli import add_era5_parsers
def create_gwsc_command_parser():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(title='Commands', dest='sub-command')
subparsers.required = True
add_era5_parsers(subparsers)
return parser... | StarcoderdataPython |
5152050 | # -*- coding: utf-8 -*-
from collections import defaultdict
from functools import wraps
from time import time
from notetool.tool.log import logger
class Cache(object):
"""
具有大小限制和命中计数器的简单词典。
"""
def __init__(self, max_size=10 ** 5, increase=False, do_not_increase_after=10 ** 6):
"""
... | StarcoderdataPython |
6630824 | <reponame>listuser/jc<filename>tests/test_df.py
import os
import json
import unittest
import jc.parsers.df
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
class MyTests(unittest.TestCase):
def setUp(self):
# input
with open(os.path.join(THIS_DIR, os.pardir, 'tests/fixtures/centos-7.7/df.ou... | StarcoderdataPython |
8070119 | """Testing parser.py module."""
from pyclip2org import parser
from pyclip2org.parser import Book
from pyclip2org.parser import Clipping
def test_book_add_none_clipping() -> None:
"""Add none as clipping."""
book = Book("Test", "Author")
book.add_clipping(None)
assert len(book.clippings) == 0
asse... | StarcoderdataPython |
12864244 | <reponame>ritwik12/lightwood
import time
import copy
import random
import logging
from functools import partial
import numpy as np
import torch
from torch.utils.data import DataLoader
from transformers import DistilBertModel, DistilBertForSequenceClassification, DistilBertTokenizer, AlbertModel, AlbertForSequenceClass... | StarcoderdataPython |
6426559 | <filename>main.py
from QQ_tracer import QQTracer
if __name__ == '__main__':
QQTracer().run()
| StarcoderdataPython |
3472830 | from setuptools import find_packages, setup
import shutil
import os
from os import path
from typing import List
import glob
def get_model_zoo_configs() -> List[str]:
"""
Return a list of configs to include in package for model zoo. Copy over these configs inside
centermask/model_zoo.
"""
# Use abs... | StarcoderdataPython |
6577707 | <gh_stars>1-10
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__all__ = ['MODEL_DIR_NAME', 'PATH_TO_MODEL_DIR']
__version__ = '0.0.1'
__author__ = '<NAME>'
__author_email__ = '<EMAIL>'
def get_version():
return __version__
from .config import MODEL_DIR_NAME, PATH_TO_MODEL_DIR
| StarcoderdataPython |
165462 | <filename>rdflib/tools/__init__.py
"""
Various commandline tools for working with RDFLib
"""
| StarcoderdataPython |
3584143 | <reponame>stivenramireza/spotify-sync-app
from src.data_access import (
get_user_saved_tracks,
save_tracks_for_user,
get_user_recently_played_tracks,
get_album_tracks,
start_user_playback,
get_user_playlists
)
from src.logger import logger
import pandas as pd
import time
def filter_user_save... | StarcoderdataPython |
1895756 | import os
import sys
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
def setup(url):
global driver, orig_url
... | StarcoderdataPython |
105614 | <filename>tests/basic_deployment.py<gh_stars>0
# Copyright 2016 Canonical 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 requir... | StarcoderdataPython |
8030891 | <filename>IEEEXtreme 11/Aeneas' cryptographic disc (4th c. B.C.).py<gh_stars>0
import re, math
l=int(input())
alphabet={}
length=0
for i in range(1,27):
a=input().split(' ')
alphabet[a[0]]=float(a[1])
phrase=input().upper()
regex = re.compile('[^a-zA-Z]')
phrase=regex.sub('', phrase)
for i in range(1,len(... | StarcoderdataPython |
6524785 | <filename>Assignment2/RL/deep_q_network.py
#!/usr/bin/env python
from __future__ import print_function
import tensorflow as tf
import cv2
import sys
sys.path.append("game/")
import wrapped_flappy_bird as game
import random
import numpy as np
from collections import deque
# reference: https://github.com/yenchenlin/Dee... | StarcoderdataPython |
6686544 | <gh_stars>10-100
#!/usr/bin/python
# write out the data in a form useful to pass to the sba (demo) program
# it appears camera poses are basically given as [ R | t ] where R is
# the same R we use throughout and t is the 'tvec'
# todo, run sba and automatically parse output ...
import sys
sys.path.insert(0, "/usr/l... | StarcoderdataPython |
9633351 | from functools import wraps
from closures import chain_closures
import logging
logger = logging.getLogger()
def x(a):
def request_logger(f):
@wraps(f)
def rlog(*args, **kwargs):
logger.info("%s x entry", a)
ret = f(*args, **kwargs)
logger.info("%s x exit", a)
... | StarcoderdataPython |
8091843 | import sys
sys.path.insert(0, "../")
from PINN_Survey.problems.burgers.v1 import Burgers, Burgers_Siren, Burgers_Random_Fourier
from PINN_Survey.problems.burgers.data.load import load_burgers_bounds
from PINN_Survey.problems.helmholtz.data.load import load_helmholtz_bounds
from PINN_Survey.problems.helmholtz.v1 import... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.