id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
3353441 | import casadi as cas
from typing import Union, List
import numpy as np
import pytest
class Opti(cas.Opti):
def __init__(self,
variable_categories_to_freeze=[],
):
super().__init__()
p_opts = {}
s_opts = {}
s_opts["max_iter"] = 3000
s_opts["... | StarcoderdataPython |
6211 | # Copyright 2021 The NetKet 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 of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | StarcoderdataPython |
3278271 | """Remove None from nodes' logs lists."""
import sys
import logging
from website.app import init_app
from website.models import Node
from scripts import utils as script_utils
from modularodm import Q
logger = logging.getLogger(__name__)
def do_migration(records, dry=False):
count = 0
for node in records:
... | StarcoderdataPython |
1730795 | <reponame>tuanavu/python-gitbook
print("I'm spam")
def hello(name):
print('Hello %s' % name)
| StarcoderdataPython |
109727 | from saleor.celeryconf import app as celery_app
__all__ = ['celery_app']
__version__ = 'dev'
| StarcoderdataPython |
3312020 | <reponame>state-of-the-art/BlendNet
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
'''BlendNet TaskExecutorBase
Description: Common for all task executors (agent/manager)
'''
import os
import signal
import time # We need to sleep the watching thread
import threading # Sync between threads needed
import json # Used in the... | StarcoderdataPython |
185279 | """
This file contains different status codes for NetConnection, NetStream and SharedObject.
The source code was taken from the rtmpy project (https://github.com/hydralabs/rtmpy)
https://github.com/hydralabs/rtmpy/blob/master/rtmpy/status/codes.py
"""
# === NetConnection status codes and what they mean. ===
... | StarcoderdataPython |
33383 | # Programmer friendly subprocess wrapper.
#
# Author: <NAME> <<EMAIL>>
# Last Change: March 2, 2020
# URL: https://executor.readthedocs.io
"""
Portable process control functionality for the `executor` package.
The :mod:`executor.process` module defines the :class:`ControllableProcess`
abstract base class which enable... | StarcoderdataPython |
3357880 | <reponame>ProSeCo-Planning/proseco_planning<gh_stars>0
"""To be used in conjunction with stateAnalysis.cpp. This file generates plots of the respective action classes given a specific vehicular state."""
import plotly.express as px
import pandas as pd
import json
import tool as tl
from typing import Tuple, Dict
def ... | StarcoderdataPython |
67314 | <reponame>balmasea/genieparser<filename>src/genie/libs/parser/iosxe/tests/ShowRunInterface/cli/equal/golden_output12_expected.py
expected_output={
"interfaces": {
"Tunnel100": {
"autoroute_announce": "enabled",
"src_ip": "Loopback0",
"tunnel_bandwidth": 500,
"tunnel_dst": "2.2.2.2"... | StarcoderdataPython |
35835 | <filename>web/datasets/tasks.py
from datetime import datetime
from logging import info
from pathlib import Path
from typing import List
import requests
from celery import shared_task
from django.conf import settings
from django.contrib.admin.options import get_content_type_for_model
from requests import HTTPError
from... | StarcoderdataPython |
3314976 | i=0
while i<1000:
i+=1
print(i) | StarcoderdataPython |
1619907 | <reponame>TopBoxBox/ENERGY_MANAGEMENT
"""Network of power devices."""
import cvxpy as cvx
import numpy as np
import tqdm
def _get_all_terminals(device):
"""Gets all terminals, including those nested within child devices."""
terms = device.terminals
if hasattr(device, 'internal_terminal'):
terms +... | StarcoderdataPython |
1775453 | #!/usr/bin/env python3
import sys
import argparse
def make_range(s):
r = (start, end, step) = [int(x) for x in s.split(',')]
return r
def make_log_range(s):
r = (base, start, end, step) = [int(x) for x in s.split(',')]
return r
def log_range(base, start, end, step):
for p in range(start, end, st... | StarcoderdataPython |
133029 | <filename>depiction/models/uri/rest_api/__init__.py
"""Initialize rest_api module."""
from .rest_api_model import RESTAPIModel # noqa
from .max_model import MAXModel # noqa | StarcoderdataPython |
3265227 | import configparser
import os
import pandas as pd
import pydash
from config import project_config
coin_paprika_host = 'https://api.coinpaprika.com'
price_columns = [
'address',
'price',
'minute',
]
def read_tokens():
cfg = configparser.ConfigParser()
cfg.read('./prices.ini')
return cfg
d... | StarcoderdataPython |
1753530 | <filename>ships/gametest/channel_management.py
#!/usr/bin/env python3
# Copyright (C) 2019-2021 The Xaya developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from shipstest import ShipsTest
"""
Tests basic management of cha... | StarcoderdataPython |
1615515 | <gh_stars>0
RTL_LANGUAGES = {
'he', 'ar', 'arc', 'dv', 'fa', 'ha',
'khw', 'ks', 'ku', 'ps', 'ur', 'yi',
}
| StarcoderdataPython |
90686 | <reponame>FixturFab/pcb-tools
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2013-2014 <NAME> <<EMAIL>>
# 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... | StarcoderdataPython |
3353670 | from pyteal import *
def approval_program():
seller_key = Bytes("seller")
nft_id_key = Bytes("nft_id")
start_time_key = Bytes("start")
end_time_key = Bytes("end")
reserve_amount_key = Bytes("reserve_amount")
min_bid_increment_key = Bytes("min_bid_inc")
num_bids_key = Bytes("num_bids")
... | StarcoderdataPython |
1631857 | <filename>infogain/__main__.py
import argparse
import sys
parser = argparse.ArgumentParser(
prog="InfoGain",
description="Information Gain - Extract information\n"
)
parser.add_argument(
"command",
help="Select a command to run:\n\tDocument"
)
args = parser.parse_args(sys.argv[1:2])
if args.command ... | StarcoderdataPython |
100112 | import sys
# Given L, adds a column based on the <where>
# parameter, either at the begginning or end
def add_col(cubes,where):
for cube in cubes:
for grid in cube:
for row in grid:
if where == "end":
row.append(".")
elif where == "begin":
row.insert(0,".")
return cubes
def add_row(cubes,wher... | StarcoderdataPython |
1779415 | <reponame>e-koch/VLA_Lband<filename>14B-088/HI/imaging/jasper/HI_mask_channel_split.py
'''
Split the HI Arecibo mask for 14B-088 into individual
channels.
'''
from casa_tools import image_split_by_channel
start_chan = 0
nchan = 1231
mask = "/home/ekoch/m33/14B-088/M33_14B-088_HI_mask.image"
output_dir = "/home/ekoc... | StarcoderdataPython |
1716362 | <gh_stars>0
from typing import (
Dict,
Iterable,
)
import orjson as json
from aiobaseclient import BaseClient
from aiolibgen.exceptions import (
ClientError,
ExceededConnectionsError,
ExternalServiceError,
NotFoundError,
)
class LibgenClient(BaseClient):
default_fields = [
'title'... | StarcoderdataPython |
1799690 | import requests
from bs4 import Beautifulsoup
# Scrapes transcript data from scrapsfromtheloft.com
def url_to_transcript(url):
'''Returns transcript data specifically from scrapsfromtheloft.com.'''
page = requests.get(url).text
soup = BeautifulSoup(page, "html5lib")
text = [p.text for p in soup.f... | StarcoderdataPython |
4814381 | import sys
from functools import partial
import argparse
from cmd import Cmd
from .cpu import INSTRUCTION_SET
from .printer.instr import InstrJsonPrinter
from .printer.instr import InstrPrettyPrinter
class ArgumentError(Exception):
pass
class ArgumentParser(argparse.ArgumentParser):
def exit(self, status=0,... | StarcoderdataPython |
1716296 | <reponame>DerPhysikeR/bookcut
from bookcut.repositories import open_access_button
from bookcut.downloader import filename_refubrished
from bookcut.search import search_downloader
from click import confirm
"""
Article.py is using from article command and searches repositories for
published articles.
"""
def article_s... | StarcoderdataPython |
3200840 | <filename>tibanna/exceptions.py
# custom exceptions
class StillRunningException(Exception):
"""EC2 AWSEM instance is still running (job not complete)"""
pass
class EC2StartingException(Exception):
"""EC2 AWSEM instance is still starting (job not complete)"""
pass
class AWSEMJobErrorException(Excepti... | StarcoderdataPython |
3245481 | <filename>fabfile.py
from fabric.api import local, run
def info():
run("uname -a")
run("lsb_release -a")
# def freeze():
# local("pip freeze > requirements.txt")
# local("git add requirements.txt")
# local("git commit -v")
def pip_upgrade():
import pip
for dist in pip.get_installed_distrib... | StarcoderdataPython |
25408 | <reponame>lindsey98/dml_cross_entropy
from collections import OrderedDict
import torch
import torch.nn as nn
import torch.nn.functional as F
def state_dict_to_cpu(state_dict: OrderedDict):
"""Moves a state_dict to cpu and removes the module. added by DataParallel.
Parameters
----------
state_dict : O... | StarcoderdataPython |
115189 | from django.urls import include, path
from django.conf.urls import url
from rest_framework import routers
from . import views
# router = routers.DefaultRouter()
# router.register('jobpostings', views.JobPostingList)
# router.register('jobpostings/<int:id>', views.JobPostingDetail)
urlpatterns = [
# url(r'^jobpost... | StarcoderdataPython |
3246854 | <gh_stars>10-100
from typing import List
from alteia.apis.provider import AssetManagementAPI
from alteia.core.resources.resource import Resource
from alteia.core.utils.typing import ResourceId, SomeResourceIds, SomeResources
class CarrierModelsImpl:
def __init__(self, asset_management_api: AssetManagementAPI, **... | StarcoderdataPython |
3282054 | import pandas as pd
import numpy as np
import unidecode
comunas = pd.read_csv('./data/comuna.csv')
comunas_name = np.array([unidecode.unidecode(x).lower() for x in comunas['name'].to_numpy()],dtype=str)
comunas_id = np.array(comunas['id'].to_numpy(), dtype=int)
comuna_code = dict(zip(comunas_name, comunas_id))
comun... | StarcoderdataPython |
3391899 | <gh_stars>0
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you ... | StarcoderdataPython |
3256724 | <gh_stars>0
""" Common functionality for exasyncio """
from enum import IntEnum
from types import TracebackType
from typing import (
Optional,
Type,
)
class ExaConnStatus(IntEnum):
""" Indicates the status of a connection """
CLOSED = 0
WS_CONNECTED = 1
CONNECTED = 2
DISCONNECTING = 3
... | StarcoderdataPython |
4810325 | <reponame>ducnx1997/int3411<filename>Filter.py<gh_stars>0
from struct import unpack
from scipy import interpolate
import numpy
class Filter:
def __init__(self, acv_file_path, name):
self.name = name
with open(acv_file_path, 'rb') as acv_file:
self.curves = self._read_curves(acv_file)
... | StarcoderdataPython |
1644259 | import ssl
import websocket
import random, string, json, threading, time
import login
def on_message(ws, message):
global first
print(message)
def on_error(ws, error):
print(error)
def on_close(ws):
print("socket closed")
def on_open(ws):
print("socket opened ok")
chat = None
def ke... | StarcoderdataPython |
4843015 | from mock import Mock
from dataclasses import dataclass
from origin.bus.dispatcher import MessageDispatcher
from origin.bus import Message
@dataclass
class Message1(Message):
"""TODO."""
something: str
@dataclass
class Message2(Message):
"""TODO."""
something: str
class TestMessageSerializer:
... | StarcoderdataPython |
1736526 | <reponame>logyball/raspberry-pi-vacation-planner
from time import sleep, time
def cntdown_timer(window):
while True:
if int(time()) >= window.time_to_move:
window.move_right.emit()
sleep(1) | StarcoderdataPython |
100642 | <gh_stars>10-100
# The MIT License (MIT)
#
# Copyright (c) 2016 <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 Software without restriction, including without limitation the rights
# to use,... | StarcoderdataPython |
3261859 | <reponame>Project-BE-Comp-Face-Recognition/facerecognition<filename>helpers/facecrop.py
import cv2
import dlib
import os
import sys
#cam = cv2.VideoCapture(1)
detector = dlib.get_frontal_face_detector()
def faceDetector(teacherId):
detector = dlib.get_frontal_face_detector()
detectedFaces=0
facenumbe... | StarcoderdataPython |
3359795 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | StarcoderdataPython |
1622768 | <reponame>ptrourke/concordia
"""
See the module-level docstring for implementation details
"""
import os
import re
from functools import wraps
from logging import getLogger
from tempfile import NamedTemporaryFile
from urllib.parse import parse_qsl, urlencode, urljoin, urlparse, urlsplit, urlunsplit
import requests
fr... | StarcoderdataPython |
1682924 | from OpenGLCffi.GLES2 import params
@params(api='gles2', prms=['pname', 'value'])
def glBlendParameteriNV(pname, value):
pass
@params(api='gles2', prms=[])
def glBlendBarrierNV():
pass
| StarcoderdataPython |
3251190 | from setuptools import setup
if __name__ == "__main__":
console_scripts = ["iseq = iseq:cli"]
setup(entry_points={"console_scripts": console_scripts},)
| StarcoderdataPython |
3370740 | <gh_stars>1-10
# This file is part of QuTiP: Quantum Toolbox in Python.
#
# Copyright (c) 2011 and later, <NAME> and <NAME>.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# ... | StarcoderdataPython |
1675627 | __docformat__ = "numpy"
# pylint: disable=R1710
import argparse
from typing import List, Union, Set
import difflib
from prompt_toolkit.completion import NestedCompleter
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.helper_funcs import get_flair, system_clear
from gamestonk_terminal.me... | StarcoderdataPython |
4800978 | <gh_stars>1-10
class Solution {
public:
int longestMountain(vector<int>& A) {
int dp_ins[10010], dp_des[10010];
memset(dp_ins, 0, sizeof(dp_ins));
memset(dp_des, 0, sizeof(dp_des));
for(int i = 1; i < A.size(); i++){
if(A[i] > A[i-1]) dp_ins[i] = dp_ins[i-1] + 1;
... | StarcoderdataPython |
3289405 | <reponame>ruanyangry/Spark-ML-study
# _*_ coding:utf-8 _*_
'''
GaussianMixture
'''
from pyspark.sql import SparkSession
from pyspark.ml.clustering import GaussianMixture
spark = SparkSession.builder.appName("GaussianMixture").getOrCreate()
paths="/export/home/ry/spark-2.2.1-bin-hadoop2.7/data/mllib/"
... | StarcoderdataPython |
1750268 | # Code by Camden
import os, re, sys, time, platform, subprocess as sp
class g:
directory_application = None
directory_carts = None
IP = "localhost"
pause = None
scale = None
on = False
p8 = None
write = ""
read = ""
def sub():
g.scale = str(g.scale * 128)
... | StarcoderdataPython |
1611426 |
""" Register allocation scheme.
"""
from rpython.jit.backend.llsupport import symbolic
from rpython.jit.backend.llsupport.descr import CallDescr, unpack_arraydescr
from rpython.jit.backend.llsupport.gcmap import allocate_gcmap
from rpython.jit.backend.llsupport.regalloc import (FrameManager, BaseRegalloc,
Regist... | StarcoderdataPython |
3335092 | <filename>web/migrations/versions/dae74ff90530_add_task_info_to_analysis.py<gh_stars>0
"""Add task info to Analysis
Revision ID: dae74ff90530
Revises: 547fa0a6608b
Create Date: 2018-08-01 22:32:41.531901
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'dae74ff<... | StarcoderdataPython |
3280108 | from functools import partial, wraps
from mimetypes import guess_type
from os import path
from re import sub
from time import gmtime, strftime
from urllib.parse import unquote
from sanic.compat import stat_async
from sanic.exceptions import (
ContentRangeError,
FileNotFound,
HeaderNotFound,
InvalidUsag... | StarcoderdataPython |
164140 | import pandas as pd
import numpy as np
import umap
import sklearn.cluster as cluster
from sklearn.cluster import KMeans
from sklearn.cluster import DBSCAN
import spacy
import unicodedata
import matplotlib.pyplot as plt
import logging
logging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO)
logging.getL... | StarcoderdataPython |
1671712 |
# date: 2019.04.09
# https://stackoverflow.com/questions/55592626/how-would-i-make-this-button-so-that-it-only-registers-one-click
import pygame
# --- constants ---
WIDTH = 640
HEIGHT = 480
FPS = 5
# --- functions ---
def action_button_click(x, y, w, h, action=None):
mouse = pygame.mouse.get_pos()
click ... | StarcoderdataPython |
3292941 | <filename>hms_tz/nhif/api/sales_invoice.py
# -*- coding: utf-8 -*-
# Copyright (c) 2020, Aakvatech and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from hms_tz.nhif.api.healthcare_utils import update_dimensions, create_individ... | StarcoderdataPython |
169170 | import math
from typing import Optional, Union, Tuple, List
import numpy as np
import torch
import torch.nn.functional as F
from torch import Tensor
from torch_geometric.utils.num_nodes import maybe_num_nodes
from torch_scatter import scatter, segment_csr, gather_csr
from torch_scatter.utils import broadcast
import ... | StarcoderdataPython |
1604660 | #!/usr/bin/python
"""
(C) Copyright 2018-2020 Intel Corporation.
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 appli... | StarcoderdataPython |
3315123 | <reponame>Rafeen/Inventory-Management-and-POS
from rest_framework_json_api import serializers
from sales.models.client_sales_model import ClientSales
class ClientSalesSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = ClientSales
fields = ('sku', 'quantity', 'client', 'warehou... | StarcoderdataPython |
138939 | import copy
import itertools
from collections import deque
from typing import TextIO, Tuple
from aoc2019.intcode import Computer, read_program
def query_position(x: int, y: int, computer: Computer) -> bool:
computer = copy.deepcopy(computer)
computer.send_input(x)
computer.send_input(y)
computer.run... | StarcoderdataPython |
4837139 | <reponame>Express50/CHARTextract
import numpy as np
def create_train_and_valid(ids, data, labels, train_percent=.6, randomizer=None):
"""Splits data in train and valid
Keyword Arguments:
train_percent {float} -- Ratio of train/total (default: {.6})
randomizer {np.random.RandomState} -- Random... | StarcoderdataPython |
3340902 | import logging
import os
import shutil
import signal
from subprocess import Popen, PIPE, CalledProcessError
import sys
import tempfile
import time
from testify import *
from tron import cmd
# Used for getting the locations of the executables
_test_folder, _ = os.path.split(__file__)
_repo_root, _ = os.path.split(_t... | StarcoderdataPython |
103042 | #!/usr/bin/env python3
# Copyright 2020 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
import unittest
from cros.factory.gooftool import gbb
_TEST_DATA_PATH = os.path.join(os.path.dirname(__file__), 'testda... | StarcoderdataPython |
1678822 | <gh_stars>10-100
import re
from unittest.mock import patch
from ..twitter.generate_tweets_feed import (
format_tweet,
generate_twitter_feed,
generate_xml,
)
from .data import (
empty_feed,
formatted_tweet_1,
formatted_tweet_2,
invalid_param as param,
tweet_1,
tweet_1_feed,
tweet... | StarcoderdataPython |
3246230 | <gh_stars>10-100
from richkit.retrieve import dns
import unittest
class DNSTestCase(unittest.TestCase):
# Since A record change every time, just checking whether we are retrieving a record or not
def setUp(self):
self.test_urls = ["www.google.co.uk", "www.cloudflare.com", "www.intranet.es.aau.dk"]
... | StarcoderdataPython |
1665017 | from googleapiclient import discovery
import json
class Perspective:
"""
Intialize the class with your API_KEY, Required Languages and Required Attributes and their respective thresholds in **kwargs
You can also setup the Developer Name.
** Accepted attributes **
attributes = ["TOXICITY... | StarcoderdataPython |
4838698 | <filename>tests/ops/text/clean/test_change_case.py
import pytest
from jange.ops.text.clean import CaseChangeOperation, lowercase, uppercase
from jange.stream import DataStream
@pytest.mark.parametrize(
"fn,expected_mode", [(uppercase, "upper"), (lowercase, "lower")]
)
def test_helper_fns_returns_correct_operatio... | StarcoderdataPython |
1756003 | import argparse
import os
import torch
class AbsPoseConfig:
def __init__(self):
description = 'Absolute Pose Regression'
parser = argparse.ArgumentParser(description=description)
self.parser = parser
# Add different groups for arguments
prog_group = parser.add_ar... | StarcoderdataPython |
1705705 | #!/usr/bin/env python3
# @Author: <NAME> <archer>
# @Date: 2019-07-15
# @Email: george raven community at pm dot me
# @Filename: mongo_handler.py
# @Last modified by: archer
# @Last modified time: 2019-08-16
# @License: Please see LICENSE in project root
from __future__ import print_function, absolute_import #... | StarcoderdataPython |
79580 | """Factory classes for easily generating test objects."""
from .activation import Activation
from .annotation import Annotation
from .annotation_moderation import AnnotationModeration
from .auth_client import AuthClient, ConfidentialAuthClient
from .auth_ticket import AuthTicket
from .authz_code import AuthzCode
from .... | StarcoderdataPython |
1623146 | <gh_stars>0
#master implementation for UDP Hole Punching
#run this on a reachable machine (like an AWS Instance or something)
import socket
import sys
server_listening_port = 3540
sockfd = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
sockfd.bind(("", server_listening_port))
print(f"listening on port {se... | StarcoderdataPython |
3371160 | import os
import argparse
import joblib
import numpy as np
from PIL import Image
from torchvision import transforms, datasets
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV
from sklearn import metrics
from face_recognition import preprocessing, FaceFeaturesExtractor... | StarcoderdataPython |
3200973 | #!/usr/bin/env python
from __future__ import division
"""@package etddf
ROS interface script for delta tiering filter
Filter operates in ENU
steps: get this to at least launch by itself
verify it works in sim for static sonar (fast scan) & dynamic agent -> plot the error (associator, no sonar control)
check the con... | StarcoderdataPython |
3298403 | <gh_stars>10-100
"""Tests for the strategy"""
from django.http import HttpRequest
from rest_framework.request import Request
from authentication.utils import load_drf_strategy
def test_strategy_init(mocker):
"""Test that the constructor works as expected"""
drf_request = mocker.Mock()
strategy = load_drf... | StarcoderdataPython |
57621 | #import conf.bootstrap as config
#import conf.datakey as datakey
from .hashicorp_base import ConnBase
import consul
import os
import json
from ..utils.io import convert_yaml
from ..utils.logger import Logger
class ConsulCon(ConnBase):
"""Class to construct the dict properties for the app from Consul and Vault
... | StarcoderdataPython |
76702 | import tensorflow as tf
import numpy as np
def batches(l, n):
"""Yield successive n-sized batches from l, the last batch is the left indexes."""
for i in range(0, l, n):
yield range(i,min(l,i+n))
class Deep_Autoencoder(object):
def __init__(self, sess, input_dim_list=[7,64,64,7],transfer_function... | StarcoderdataPython |
116413 | from collections import namedtuple
class Config(namedtuple('Config', ['origin', 'api_key', 'maybe_logger'])):
"""Configuration for interacting with SLS API."""
__slots__ = ()
def __new__(cls, origin, api_key, maybe_logger=None):
return super(Config, cls).__new__(cls, origin, api_key,
... | StarcoderdataPython |
144763 | <gh_stars>1-10
from typing import Optional
from athenian.api.models.web.base_model_ import Model
from athenian.api.models.web.work_type import WorkType
class WorkTypePutRequest(Model):
"""Request body of `PUT /settings/work_type`."""
openapi_types = {"account": int, "work_type": WorkType}
attribute_map... | StarcoderdataPython |
1742622 | import os
from pathlib import Path
import pytest
from commitizen import config, defaults, git
PYPROJECT = """
[tool.commitizen]
name = "cz_jira"
version = "1.0.0"
version_files = [
"commitizen/__version__.py",
"pyproject.toml"
]
style = [
["pointer", "reverse"],
["question", "underline"]
]
[tool.bla... | StarcoderdataPython |
3231432 | from jnius import autoclass
import os
import numpy as np
import storage
File = autoclass('java.io.File')
Interpreter = autoclass('org.tensorflow.lite.Interpreter')
InterpreterOptions = autoclass('org.tensorflow.lite.Interpreter$Options')
Tensor = autoclass('org.tensorflow.lite.Tensor')
DataType = autoclass('o... | StarcoderdataPython |
108293 | import argparse
import ast
import collections
import configparser
import logging
import os
import sys
import typing
from abc import ABCMeta
from argparse import Action, ArgumentParser
from enum import Enum
from pathlib import Path
from types import MappingProxyType
from typing import (
Any, Callable, Dict, Iterable... | StarcoderdataPython |
1793343 | import itertools # set iterator for next word in the file
import pandas as pd
from sklearn.preprocessing import LabelEncoder # convert categorical variables into numerical variables
from sklearn.tree import DecisionTreeClassifier # Import Decision Tree Classifier
from sklearn import metrics # Import scikit-learn me... | StarcoderdataPython |
4809333 | """This module contains Module implementations for Kalman filtering.
"""
import numpy as np
import scipy.linalg as spl
from modprop.core.modules_core import ModuleBase, InputPort, OutputPort, iterative_invalidate
from modprop.core.backprop import sum_accumulators
def transpose_matrix(m, n):
'''Generate the vecto... | StarcoderdataPython |
177528 | <reponame>lwpamihiranga/python_fb_post_commentor
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from time import sleep
import time
username = "<put your fb account username here>"
password = "<put your account password here>"
# examp... | StarcoderdataPython |
197618 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2016 - 2020 -- <NAME>
# All rights reserved.
#
# License: BSD License
#
"""\
Test against issue #4.
<https://github.com/heuer/segno/issues/4>
"""
from __future__ import unicode_literals, absolute_import
from segno import consts, encoder
def test_issue_4():
qr = encoder.en... | StarcoderdataPython |
185895 | import os
import struct
import sys
import pytest
from bonsai.active_directory.acl import ACL
from bonsai.active_directory.sid import SID
from conftest import get_config
from bonsai import LDAPClient
from bonsai.active_directory import SecurityDescriptor
@pytest.fixture
def client():
""" Create a client with aut... | StarcoderdataPython |
1708464 | # Generated by Django 2.0 on 2017-12-25 05:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0004_auto_20171221_0621'),
]
operations = [
migrations.AddField(
model_name='game',
name='num_players',
... | StarcoderdataPython |
1672244 | # coding=utf-8
from django.db import models
from extended_choices import Choices
class Sponsor(models.Model):
LEVELS = Choices(
('platinum', 1, 'Platinum'),
('gold', 2, 'Gold'),
('silver', 3, 'Silver'),
('bronze', 4, 'Bronze'),
('diversity', 5, 'Diversity'),
('med... | StarcoderdataPython |
3335590 | #!/usr/bin/python
"""
Allow a web page to access local files.
This makes it easier to preview title screens and video files.
FF stores profiles in ~/.mozilla/firefox/profiles.ini
FF settings are set by creating a .js file that sets things on startup
1. count number of FF profiles.
If more than 1, give up.
2. ge... | StarcoderdataPython |
1787781 | <filename>bubbleimg/tabtools.py
import io
import os
import numpy as np
import astropy.table as at
from astropy.io import ascii
def write_row(fn, row, condi, overwrite=False, append=False):
"""
write row (append) to file. If the row already exists, according to the condi conditions, then this row is overwritten (or n... | StarcoderdataPython |
114320 | <gh_stars>1-10
import os
import unittest
import tempfile
import csv
import warnings
from requests import exceptions
from kbcstorage.tables import Tables
from kbcstorage.buckets import Buckets
class TestTables(unittest.TestCase):
def setUp(self):
self.tables = Tables(os.getenv('KBC_TEST_API_URL'),
... | StarcoderdataPython |
3244734 | <filename>pyouroboros/__init__.py
VERSION = "1.4.1"
BRANCH = "master"
| StarcoderdataPython |
1668742 | import csv
import json
import logging
import os
import re
from collections import OrderedDict
from io import BytesIO, StringIO
from zipfile import ZipFile
from urllib.parse import urljoin
import json_merge_patch
import requests
from ocdsextensionregistry import ExtensionRegistry
from ocdsdocumentationsupport.models i... | StarcoderdataPython |
4800957 | <gh_stars>1-10
"""Declare the models related to Ashley ."""
import uuid
from django.db import models
from machina.apps.forum.abstract_models import AbstractForum as MachinaAbstractForum
from machina.core.db.models import get_model, model_factory
LTIContext = get_model("ashley", "LTIContext") # pylint: disable=C0103
... | StarcoderdataPython |
3355192 | <filename>blueapps/utils/sites/open/__init__.py
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2020 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "L... | StarcoderdataPython |
1793327 | <reponame>evinism/littlebaker
from tinybaker import Transform, InputTag, OutputTag
from pickle import load, dumps
from base64 import b64encode
def test_data_uri_text():
class T(Transform):
foo = InputTag("foo")
bar = OutputTag("bar")
def script(self):
with self.foo.open() as f... | StarcoderdataPython |
1633465 | <reponame>peterbe/
import json
import getpass
import urllib.parse
import click
import requests
from gg.utils import error_out, success_out, info_out
from gg.state import read, update, remove
from gg.main import cli, pass_config
BUGZILLA_URL = "https://bugzilla.mozilla.org"
@cli.group()
@click.option(
"-u",
... | StarcoderdataPython |
1625125 | # ==============================================================================
# Copyright (C) 2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
# ==============================================================================
"""Openvino Tensorflow installation test
"""
from __future__ import print_funct... | StarcoderdataPython |
3354305 | <gh_stars>0
import json
from unittest.mock import Mock, patch
from freezegun import freeze_time
from satellite.aliases import AliasGeneratorType, AliasStoreType
from satellite.aliases.manager import redact
from satellite.aliases.store import AliasStore
from .base import BaseHandlerTestCase
@freeze_time('2020-11-0... | StarcoderdataPython |
3280841 | <reponame>toastisme/dials
from math import pi
import wx
from annlib_ext import AnnAdaptorSelfInclude
from wx.lib.agw import floatspin
import gltbx
import gltbx.gl as gl
import libtbx.phil
import wxtbx.utils
from libtbx import Auto
from scitbx.array_family import flex
from scitbx.math import minimum_covering_sphere
fr... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.