id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
105982 | # -*- coding: UTF-8 -*-
import __future__
import os
import sys
import traceback
import site
import tempfile
import Quartz
import time
class StdOutput(object):
def __init__(self, output, isError=False):
self.data = output
self.isError = isError
def write(self, data):
if isinstance(data... | StarcoderdataPython |
1617759 | '''
Author : <NAME>
GitHub : https://github.com/royaleagle73
Email : <EMAIL>
'''
import os
class get_package_list:
'''
get_package_list CLASS COMBINE A SINGLE METHOD AND A CONSTRUCTOR, WHICH ARE AS FOLLOWS:
1) __init__
2) work()
__init__ DOCFILE:
__init__ SERVES THE PURPOSE TO INITIALISE VARIABLES ... | StarcoderdataPython |
3426538 | <gh_stars>0
from typing import Iterator, List, Optional
import astroid
from ._base import NAMES, Extractor, WarningInfo
BRANCHING = (
astroid.If,
astroid.With,
astroid.TryExcept,
astroid.TryFinally,
astroid.Return,
astroid.Raise,
)
class WarningsExtractor(Extractor):
"""Extractor for `... | StarcoderdataPython |
328157 | <filename>homeassistant/components/sabnzbd/sab.py
"""Support for the Sabnzbd service."""
from pysabnzbd import SabnzbdApi, SabnzbdApiException
from homeassistant.const import CONF_API_KEY, CONF_PATH, CONF_URL
from homeassistant.core import _LOGGER, HomeAssistant
from homeassistant.helpers.aiohttp_client import async_g... | StarcoderdataPython |
3320564 | <filename>andabb/PositionListener.py
import abc
from .PoseUpdater import Pose
class IPositionListener(object, metaclass=abc.ABCMeta):
"""
Interface for position listeners
"""
@abc.abstractmethod
def newPosition(self, pose: Pose):
raise NotImplementedError('users must define newPosition t... | StarcoderdataPython |
9613563 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2018-02-05 11:21
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('childf_app', '0002_auto_20180205_1421'),
]
operations = [
migrations.AlterF... | StarcoderdataPython |
3571696 |
"""Fill gaps in Python time API-s.
parse_iso_timestamp:
Parse reasonable subset of ISO_8601 timestamp formats.
[ http://en.wikipedia.org/wiki/ISO_8601 ]
datetime_to_timestamp:
Get POSIX timestamp from datetime() object.
"""
import re
import time
from datetime import datetime, timedelta, tzinfo
__all__... | StarcoderdataPython |
4983710 | """Testing GraphCircuits
"""
import pytest
import qcdenoise as qcd
@pytest.fixture()
def graph_state():
graph_db = qcd.GraphDB()
graph_state = qcd.GraphState(graph_db=graph_db, n_qubits=7)
return graph_state.sample()
@pytest.mark.dependency()
def test_CXGateCircuit(graph_state):
circ_builder = qcd.C... | StarcoderdataPython |
4812723 | <gh_stars>10-100
from typing import List, Dict, Optional, Iterable, Tuple
from itertools import chain, cycle
from functools import partial
from multiprocessing import Manager, Pool, Queue, cpu_count
import numpy as np
import simpy
from . import simulation as cs
from .cache import get_from_cache, save_to_cache
from .ea... | StarcoderdataPython |
294689 | <filename>github/joeynmt/vizseq/_view/data_filter.py
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from typing import List
# TODO: scale this part
class... | StarcoderdataPython |
222538 | from setuptools import find_packages
from setuptools import setup
setup(
name="src",
packages=find_packages(),
version="0.1.0",
description="Predicting BMI from facial images",
author="<NAME>",
license="MIT",
)
| StarcoderdataPython |
1714288 | <reponame>IMULMUL/etl-parser<filename>etl/parsers/etw/Microsoft_Pef_WFP_MessageProvider.py
# -*- coding: utf-8 -*-
"""
Microsoft-Pef-WFP-MessageProvider
GUID : c22d1b14-c242-49de-9f17-1d76b8b9c458
"""
from construct import Int8sl, Int8ul, Int16ul, Int16sl, Int32sl, Int32ul, Int64sl, Int64ul, Bytes, Double, Float32l, St... | StarcoderdataPython |
9703082 | import asyncio
import os
import dbsync
import pytest
import sqlalchemy
from dbsync import client
from dbsync.client.wsclient import SyncClient
from dbsync.client.tracking import track, start_tracking
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from .models_websockets import Base, PORT... | StarcoderdataPython |
1629310 | <filename>plotvars-masked.py
mapbox_access_token = ''
plotly_username=''
plotly_apikey=''
ipinfo_access_token = ''
| StarcoderdataPython |
8180363 | <reponame>megies/SHTOOLS
"""
This script builds the python documentation from the function signature and the
customized markdown files. The processed documentation is saved as ascii text
files which are loaded on runtime and replace the __doc__ string of the f2py
wrapped functions.
"""
import sys
import os
import re
im... | StarcoderdataPython |
9776937 | """Library with basic functions for data input and plotting."""
from plotting import PlotAnnotator
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import numpy as np
import csv
from contextlib import contextmanager
BASIC_EMOTIONS = [
'happiness', 'sadness', 'fear', 'surprise', 'anger', 'disgus... | StarcoderdataPython |
11279298 | #!/usr/bin/env python
# Script takes a Rosecheckers output file and extracts its diagnostic
# information
#
# The only argument indicates the file containing the input.
#
# The script should take the text data via standard input. The data
# should be produced from a build process using make and g++. A
# suitable comm... | StarcoderdataPython |
1926819 | """Test model for SMP-CAIL2020-Argmine.
Author: Tsinghuaboy <EMAIL>
Usage:
python main.py --model_config 'config/bert_config.json' \
--in_file 'data/SMP-CAIL2020-test1.csv' \
--out_file 'bert-submission-test-1.csv'
python main.py --model_config 'config/rnn_config.json' \
... | StarcoderdataPython |
320067 | <gh_stars>1-10
# coding: utf-8
import os
import logging
from functools import lru_cache
from typing import Optional
from pydantic import BaseSettings, PostgresDsn
class Setting(BaseSettings):
ENVIRONMENT: str = "developpment"
PG_DNS: PostgresDsn
# docs
OPENAPI_URL: Optional[str] = "/openapi.json"
... | StarcoderdataPython |
12858801 | import sys
import numpy as np
import cv2
from easydict import EasyDict as edict
from base_tracker import BaseTracker
import path_config
sys.path.append("external/SiamDW/lib")
from tracker.siamrpn import SiamRPN
import models.models as models
from utils.utils import load_pretrain
class SiamDW(BaseTracker):
def __... | StarcoderdataPython |
3509503 | import logging
import numpy as np
import xarray as xr
from xclim import run_length as rl
from xclim import utils
from xclim.utils import declare_units
from xclim.utils import units
# logging.basicConfig(level=logging.DEBUG)
# logging.captureWarnings(True)
xr.set_options(enable_cftimeindex=True) # Set xarray to use... | StarcoderdataPython |
5127227 | <gh_stars>10-100
from attrdict import AttrDict
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from torch.distributions.normal import Normal
from torch.distributions.categorical import Categorical
from torch.distributions.kl import kl_divergence
import numpy as np
from genesis.... | StarcoderdataPython |
355241 | class JobState(basestring):
"""
Jobs execute as self-contained state machines. They follow a
series of careful steps from creation to destruction. These
steps are dictated by the states that they find themselves in as
well as the allowable list of states they may transition into.
The state can... | StarcoderdataPython |
1900877 | <filename>xTool/algorithms/collections/attrdict.py
# -*- coding: utf-8 -*-
"""
可以使用第三方库:attrdict
"""
try:
from collections import UserDict
except ImportError:
pass
from typing import Any
try:
import typing # noqa
_ObjectDictBase = typing.Dict[str, typing.Any]
except ImportError:
_ObjectDictBase... | StarcoderdataPython |
11383112 | <gh_stars>0
# Adapted based on SOM benchmark.
# Copyright 2011 Google Inc.
#
# 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 re... | StarcoderdataPython |
5167005 | <gh_stars>1-10
"""
Methods for reading and writing FITS files.
"""
# -----------------------------------------------------------------------------
# IMPORTS
# -----------------------------------------------------------------------------
from pathlib import Path
from typing import Optional, Tuple, Union, overload
from... | StarcoderdataPython |
8149085 | import os
from decisionengine.framework.modules import Source
PRODUCES = ["available_cloud_budget"]
class CloudBudget(Source.Source):
def __init__(self, params_dict):
self.budget_file = params_dict["budget_file"]
def produces(self, schema_id_list):
return PRODUCES
# The DataBlock give... | StarcoderdataPython |
12863470 | <reponame>mahyar-osn/mapclientplugins.scaffoldfiniteelementmeshfitterstep<filename>mapclientplugins/scaffoldfiniteelementmeshfitterstep/model/imageplanemodel.py
from opencmiss.utils.maths.algorithms import calculate_line_plane_intersection
class ImagePlaneModel(object):
def __init__(self, master_model):
... | StarcoderdataPython |
4873661 | <gh_stars>0
# pylint: skip-file
"""データセットの読み込みなど。"""
from .ic import *
from .keras import *
from .sklearn import *
from .ss import *
from . import coco
from . import voc
| StarcoderdataPython |
11344666 | # -*- coding: utf-8 -*-
# file: lca_bert.py
# author: yangheng <<EMAIL>>
# Copyright (C) 2020. All Rights Reserved.
import torch
import torch.nn as nn
import numpy as np
import copy
from pytorch_transformers.modeling_bert import BertPooler, BertSelfAttention
class SelfAttention(nn.Module):
def __init__(self, co... | StarcoderdataPython |
9638871 | """Chase program: run the lights in sequence, one light on at a time.
"""
from collections import deque
from functools import partial
from itertools import cycle
import time
import sys
def chase(n_lights, until=sys.maxsize, forward=True):
direction = 1 if forward else -1
# start with the first light on and... | StarcoderdataPython |
194806 | <filename>platformio/package/pack.py
# Copyright (c) 2014-present PlatformIO <<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/licenses/LICENSE-2.0
#
# Un... | StarcoderdataPython |
5190495 | <gh_stars>0
from setuptools import setup
setup(name='whopy',
version='1.0.2',
description='Provides Whois data for domains.',
author='<NAME>',
author_email='<EMAIL>',
url='https://github.com/amshamah419/whopy',
packages=['whopy'],
package_dir={"whopy":"whopy"},
package_d... | StarcoderdataPython |
4985454 | #!/usr/bin/python3
# -*- coding:utf-8 -*-
# __author__ = '__Jack__'
from django.urls import path
from wenhu.users import views
app_name = "users"
urlpatterns = [
path("update/", views.UserUpdateView.as_view(), name="update"),
path("<str:username>/", views.UserDetailView.as_view(), name="detail"),
]
| StarcoderdataPython |
1758458 | from UdonPie import UnityEngine
from UdonPie.Undefined import *
class RigidbodyInterpolation:
def __new__(cls, arg1=None):
'''
:returns: RigidbodyInterpolation
:rtype: UnityEngine.RigidbodyInterpolation
'''
pass
| StarcoderdataPython |
3510845 | <gh_stars>10-100
# -*- coding: utf-8 -*-
## @package color_histogram.core.hist_1d
#
# Implementation of 1D color histograms.
# @author tody
# @date 2015/08/29
import numpy as np
from color_histogram.core.color_pixels import ColorPixels
from color_histogram.core.hist_common import colorCoordinates, col... | StarcoderdataPython |
1747832 | import pytest
import itertools
from signs import named_chars, build_index
@pytest.fixture
def first_5():
return [(' ', 'SPACE'),
('!', 'EXCLAMATION MARK'),
('"', 'QUOTATION MARK'),
('#', 'NUMBER SIGN'),
('$', 'DOLLAR SIGN')]
def test_first_5_named(... | StarcoderdataPython |
4950275 | <filename>examples/lambda.py
def apply(f, x):
return f(x)
apply(lambda x: x + 1, 5) | StarcoderdataPython |
3377308 | <filename>com/vmware/content/library_client.py
# -*- coding: utf-8 -*-
#---------------------------------------------------------------------------
# Copyright 2020 VMware, Inc. All rights reserved.
# AUTO GENERATED FILE -- DO NOT MODIFY!
#
# vAPI stub file for package com.vmware.content.library.
#-------------------... | StarcoderdataPython |
11244861 | <reponame>Nikandros1997/Sessions-2.0<gh_stars>0
from .Entity import Entity
import os
from ..Helpers import DEV_MODE, running_from, running_apps
class Software(Entity):
def __init__(self, session_name):
super().__init__(session_name)
self.ignoreFile = self.format_file_name('.ignore')
... | StarcoderdataPython |
9684123 | from camera_calibrator import CameraCalibrator
import numpy as np
import cv2
import pickle
import copy
from glob import glob
def pmat(mat):
'''Print matrix
'''
print(np.round(mat, 3))
if __name__ == "__main__":
calib = CameraCalibrator(board_shape=(6, 7), tile_side=0.10, apriltag_families="tag36h10")
... | StarcoderdataPython |
1895909 | #!/usr/bin/env python
__author__ = '<NAME>, <NAME>'
import unittest
from mock import Mock, patch
from pyon.util.int_test import IonIntegrationTestCase
from nose.plugins.attrib import attr
from pyon.core.exception import BadRequest, Conflict, Inconsistent, NotFound
from pyon.public import PRED, RT, IonObject, OT
fro... | StarcoderdataPython |
9773717 | <filename>Puzzles/checkio/Home/The-Most-Wanted-Letter/mySolution.py
def extractChars(text):
charsList = []
for char in text.lower():
if char not in charsList and unicode.isalpha(char):
charsList.append(char)
return charsList
def checkio(text):
text = text.lower()
chars =... | StarcoderdataPython |
4960512 | <reponame>khaosans/parse_anchorusd_cointracker
import maya
import csv
def toUTCtimestamp(timestamp):
dt = maya.parse(timestamp).datetime()
return (dt.strftime("%Y-%m-%d %H:%M:%S"))
transaction = ['Sell', 'Buy']
def translate(Datestamp, transaction, Token, Amount, TPXLM):
switcher: Dict[str, str] = {
... | StarcoderdataPython |
3393949 | <filename>terra_sdk/util/converter.py
from datetime import datetime
def to_isoformat(dt: datetime) -> str:
return (
dt.isoformat(timespec="milliseconds")
.replace("+00:00", "Z")
.replace("000Z", "Z")
)
| StarcoderdataPython |
4956969 | """
Indent the each enum item in the enum block.
== Violation ==
enum A {
A_A, <== Violation
A_B <== Violation
}
== Good ==
enum A {
A_A, <== Good
A_B
}
"""
from nsiqcppstyle_rulehelper import *
from nsiqcppstyle_reporter import *
from nsiqcppstyle_rulemanager impo... | StarcoderdataPython |
1653286 | import networkx as nx
from spira.gdsii.elemental.label import Label
from spira.param.field.typed_graph import PathList
from spira import param
from spira.core.initializer import ElementalInitializer
import spira
from spira import log as LOG
from spira.core.mixin.gdsii_output import OutputMixin
def _loops(g):
"""
... | StarcoderdataPython |
11259830 | <reponame>kkingstoun/post_mumax_v4
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
# from matplotlib import rcParams
from mpl_toolkits.axes_grid1 import make_axes_locatable
from hslcolormap import Hslcolormap
import cmocean
import random
import seaborn as sns
import matplotlib.style as style
from a... | StarcoderdataPython |
3596619 | """
Prepare data for running benchmark on sparse linear regression model
"""
from __future__ import print_function
import argparse
import keras_sparse_model
import mxnet as mx
from scipy import sparse
from keras import backend as K
from keras.utils.data_utils import prepare_sliced_sparse_data
def invoke_benchmark(... | StarcoderdataPython |
3315939 | """
This module defines a datastructure for creating
kmers.
"""
from dataclasses import dataclass
import pickle
from typing import Dict, List, Optional, Union
from tqdm import tqdm
import os
from os.path import exists
# in-house packages
from src.debruijnextend.utils import hamming_dist
@dataclass
class KmerCluster... | StarcoderdataPython |
12822866 | <filename>annotation_utils/rgb_to_gs_segmentation_mask.py
#!/usr/bin/env python
# coding: utf-8
import os
from glob import glob
from PIL import Image
import numpy as np
from tqdm import tqdm
import sys
# DATA_FOLDER =
# '/mnt/storage/data/object_detection/helmet_100/annotated/segmentation_masks/validation' # no... | StarcoderdataPython |
52164 | <gh_stars>1-10
# This file is not empty !
| StarcoderdataPython |
337983 | <reponame>wannabethere/Spark-delta-jupyter-experiments
import json
from pyspark.sql.functions import *
from pyspark.sql.types import *
from pyspark.sql import *
import json
import global_vals
infer_schema = update_kafka_schema
if not infer_schema:
try:
topic_schema_txt = dbutils.fs.head(schema_location)
... | StarcoderdataPython |
4965715 | <gh_stars>1-10
#!/usr/bin/env python
#
# Copyright (c) 2014, 2016 Apple 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:
# 1. Redistributions of source code must retain the above copyright
# ... | StarcoderdataPython |
8152523 | import discord
from discord.ext import commands
from discord.utils import get
class c90(commands.Cog, name="c90"):
def __init__(self, bot: commands.Bot):
self.bot = bot
@commands.command(name='A_Term_for_Peace', aliases=['c90'])
async def example_embed(self, ctx):
embed = discord.Embed(tit... | StarcoderdataPython |
123897 | <filename>shape.py<gh_stars>1-10
import turtle
import time
import random
squares = input("Enter the number of sides of the shape: ")
numshapes = input("Enter the number of shapes to draw: ")
angle = 180 - 180*(squares-2)/squares
turtle.up
x = 0
y = 0
turtle.setpos(x,y)
for x in range(numshapes):
turtle.color(r... | StarcoderdataPython |
9605635 | def functionCalculator(first_num,operator,second_num):
if operator =='+':
result =first_num+ second_num
elif operator =='-':
result =first_num- second_num
elif operator =='/':
result =first_num/second_num
elif operator =='*':
result =first_num*second_num
... | StarcoderdataPython |
8180101 | <reponame>caiyongji/py36-tf2.0rc<gh_stars>0
# This file is MACHINE GENERATED! Do not edit.
# Generated by: tensorflow/python/tools/api/generator/create_python_api.py script.
"""Public API for tf.random namespace.
"""
from __future__ import print_function as _print_function
import sys as _sys
from tensorflow._api.v2.... | StarcoderdataPython |
1859595 | <gh_stars>1-10
#!/usr/bin/env python3
# vim: set fileencoding=utf-8
from PIL import Image
from time import sleep
class Sprite:
'''
Collection of animation sprites, based on a single source image (spritesheet).
This class provides the #define-method to create animation cycle methods (with internal counte... | StarcoderdataPython |
6567405 | <filename>Dataset/Leetcode/train/70/81.py
class Solution:
def XXX(self, n: int) -> int:
f=lambda x:f(x-1)*x if x>=2 else 1
i=r=1
while n>i:
n-=1
r+=f(n)/(f(i)*f(n-i))
i+=1
return int(r)
| StarcoderdataPython |
6413974 | <reponame>iwoithe/Gimel-Studio
# THIS FILE IS A PART OF GIMEL STUDIO AND IS LICENSED UNDER THE SAME TERMS:
# ----------------------------------------------------------------------------
# Gimel Studio Copyright 2019-2021 by <NAME> and contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# yo... | StarcoderdataPython |
5152077 | #!/usr/bin/env python
# coding: utf-8
# author: <NAME> <EMAIL>
# platform: python 2.6-2.7, 3.5-3.8+
# demos are provided in test_json_compare.py
from __future__ import print_function
import json
import re
import traceback
import six
import codecs
_NUMBER_TYPES = list(six.integer_types) + [float]
class _Compare(objec... | StarcoderdataPython |
159824 | from flask import Flask
app = Flask(__name__)
import lachesis.views
from lachesis.models.database import init_db, clear_db
if __name__ == '__main__':
app.run(debug=True)
| StarcoderdataPython |
6557644 | # -*- coding: utf-8 -*-
"""Contains app-specific admin classes."""
# Django imports
from django.conf import settings
from django.contrib.admin import ModelAdmin, register
# app imports
from auth_enhanced.models import UserEnhancement
def register_only_debug(*models, **kwargs):
"""Register the given model(s) cla... | StarcoderdataPython |
6511816 | """
海龟交易策略
此示例策略适用于OKEX币本位合约,
可根据自己需求自行修改
Author: <NAME>
Date: 2020/09/17
email: <EMAIL>
"""
from purequant.trade import OKEXFUTURES
from purequant.indicators import INDICATORS
from purequant.market import MARKET
from purequant.position import POSITION
from purequant.logger import logger
from purequant.time import *... | StarcoderdataPython |
5077864 |
from django.apps import AppConfig
import logging
from nalkinscloud_django.settings import PROJECT_NAME
# Define logger
logger = logging.getLogger(PROJECT_NAME)
class NalkinsCloudAPIConfig(AppConfig):
name = 'nalkinscloud_api'
# def ready(self):
# logger.info("#################################\n"
... | StarcoderdataPython |
11398925 | from pyrad import dictionary, packet, server
import logging
from loguru import logger
import traceback
import platform
from util import *
from config import config
from users import *
logging.basicConfig(filename="pyrad.log", level="DEBUG",
format="%(asctime)s [%(levelname)-8s] %(message)s")
clas... | StarcoderdataPython |
9674974 | <filename>simple_ml/knn.py
# -*- coding:utf-8 -*-
from __future__ import division, absolute_import
from simple_ml.base.base_enum import *
from simple_ml.base.base_error import *
from simple_ml.evaluation import *
from simple_ml.base.base_model import *
import numpy as np
from collections import Counter
__all__ = ['... | StarcoderdataPython |
9731097 | def mean(mylist):
the_mean = sum(mylist) / len(mylist)
return the_mean
print(mean([1,4,5]))
def meanListDict(value):
if type(value) == dict:
the_mean = sum(value.values()) / len(value)
else:
the_mean = sum(value) / len(value)
return the_mean
monday_temperatures = [8.8, 9.1... | StarcoderdataPython |
8091863 | <filename>backend/src/gql/mutation/import_milestone.py
from containers import SDContainer
from models import Milestone, OnPathway
from .mutation_type import mutation
from datacreators import ImportMilestone
from authentication.authentication import needsAuthorization
from graphql.type import GraphQLResolveInfo
from dep... | StarcoderdataPython |
142833 | <reponame>cron-ooo/django-compressor
from django.core.exceptions import ImproperlyConfigured
from django.utils.encoding import smart_str
from django.utils.functional import cached_property
from compressor.exceptions import ParserError
from compressor.parser import ParserBase
class LxmlParser(ParserBase):
"""
... | StarcoderdataPython |
1666494 | #coding:utf-8
#
# id: bugs.core_1787
# title: Consistency check when subquery is ordered by aggregate function from other context
# decription:
# tracker_id: CORE-1787
# min_versions: []
# versions: 2.5.0
# qmid: None
import pytest
from firebird.qa import db_factory, isql_act, Action
... | StarcoderdataPython |
9711680 | import os
from museum_site.core.detail_identifiers import *
from museum_site.models.detail import Detail
class File_Extension_Info(object):
def __init__(self, extension, name="", associated_details=[], file_viewer_type="", file_viewer_func="", ambiguous=False):
self.extension = extension
self.name... | StarcoderdataPython |
385259 | from PIL import Image, ImageOps
import numpy as np
import matplotlib.pyplot as plt
import os
def colorize(path):
img = Image.open(path)
# img2 = ImageOps.colorize(img, black ="Blue", white ="white")
# img2.show()
img_arr = np.array(ImageOps.equalize(img).convert("L"), np.uint8)
arr = np.array(Ima... | StarcoderdataPython |
46534 | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... | StarcoderdataPython |
9790795 | <reponame>CodingGorit/Coding-with-Python<filename>Python Web/Flask/Flask WeChat Official Accounts/service/__init__.py
#!/usr/bin/python
# -*- coding: utf-8 --
#@File: __init__.py.py
#@author: Gorit
#@contact: <EMAIL>
#@time: 2020/3/4 0:13 | StarcoderdataPython |
1659918 | <reponame>aaronkurz/hitl-ab-bpm<gh_stars>1-10
""" Area for user to upload process versions and metadata, which will start a new experiment """
import streamlit as st
import requests
from resources import user_assistance
from config import BACKEND_URI
def upload_files():
""" Area for user to upload process version... | StarcoderdataPython |
1721282 | import torch
import torch.nn as nn
from utils import DynamicRNN
class HierarchicalRecurrentEncoder(nn.Module):
def add_cmdline_args(parser):
parser.add_argument_group('HRE specific arguments')
parser.add_argument('-img_feature_size', default=4096,
help='Channel siz... | StarcoderdataPython |
12860059 | <reponame>thusoy/grunt-pylint
""" This module is used for integration testing. """
# pylint: disable=locally-disabled,unused-import
import venv_exclusive
| StarcoderdataPython |
8021155 | #!/usr/bin/env python
import ecto
from ecto.tutorial import Increment, Add
from ecto import BlackBoxCellInfo as CellInfo, BlackBoxForward as Forward
class MyBlackBox(ecto.BlackBox):
"""
We encapsulate the plasm from the hello_tutorial by exposing the
start value of 'i2' as a parameter to the BlackBox and f... | StarcoderdataPython |
1792212 | import numpy as np
import matplotlib.pyplot as plt
def train(X, T):
# Standardize input data (X)
# Calculate mean and std.
means = X.mean(axis = 0)
std = X.std(axis = 0)
Xs = (X - means) / std
# Tack a column of 1s
Xs = np.insert(Xs, 0, 1, 1)
# Use Xs to generate mode... | StarcoderdataPython |
3303646 | """
Export Directory constants
"""
from setuptools import setup, find_packages
setup(
name='directory_constants',
version='21.1.0',
url='https://github.com/uktrade/directory-constants',
license='MIT',
author='Department for International Trade',
description='Constant values shared between Dire... | StarcoderdataPython |
284915 | import requests
from bs4 import BeautifulSoup
def parse_url(url):
list_of_tasks = []
r = requests.get(url)
r.encoding = 'utf-8'
soup = BeautifulSoup(r.text, 'html.parser')
div = soup.find_all("div", {"class": "item-title"})
for tag in div:
a = tag.find_all("a")
list_of_tasks.a... | StarcoderdataPython |
9660384 | from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
import os
import os.path
import time
from openpyxl import load_workbook
import csv
class Command(BaseCommand):
help = 'Converts an XLS spreadsheet into a CSV format.'
def add_arguments(self, parser):
par... | StarcoderdataPython |
278804 | #!/usr/bin/python
class TaggedAttribute(object):
"""Simple container object to tag values with attributes.
Feel free to initialize any node with a TA instead of its actual
value only and it will then have the desired metadata. For example:
from pylink import TaggedAttribute as TA
tx_power = TA(... | StarcoderdataPython |
3533865 | <reponame>Cheezegami/HKU-ECTTP
from Controls import Controls
from GenericObject import GenericObject
from ObjectRunner import ObjectRunner
class ScoreBoard():
def __init__(self,int_score) : # Constructor
self.int_score=int_score
self.bool_mayClickMouse = True
self.int_clickDelay = 20
... | StarcoderdataPython |
1647862 | <reponame>hodakamori/deepmd-starter-kit<filename>gen_cp2k_inputs.py
import MDAnalysis as mda
import os
import shutil
import subprocess as sub
def write_trj_as_cp2k_input(system_name, cell, types, type_map, positions):
types = [type_map[t] for t in types]
positions = positions.astype('str')
with open(syste... | StarcoderdataPython |
6551572 | import json
import urllib.parse
from typing import Callable, Dict, Tuple, List
import demistomock as demisto
from CommonServerPython import * # noqa # pylint: disable=unused-wildcard-import
from CommonServerUserPython import * # noqa
import requests
# Disable insecure warnings
requests.packages.urllib3.disable_war... | StarcoderdataPython |
3444058 | import subprocess
import sys
import unittest
import erwin.__main__
class TestMain(unittest.TestCase):
def test_help(self):
output = subprocess.check_output(
[sys.executable, "-m", "erwin", "--help"])
def test_list(self):
output = subprocess.check_output(
[sys.execu... | StarcoderdataPython |
11310644 | <filename>test/hlt/pytest/python/com/huawei/iotplatform/client/dto/QueryTaskDetailsInDTO.py
class QueryTaskDetailsInDTO(object):
def __init__(self):
self.appId = None
self.taskId = None
self.status = None
self.index = None
self.nodeId = None
self.deviceId = None
... | StarcoderdataPython |
8019363 | import tensorflow as tf
import numpy as np
"""
Implementation of Deep Deterministic Policy Gradients (A2C):
Deep Deterministic Policy Gradient (DDPG) is an algorithm which concurrently learns a Q-function and a policy. It
uses off-policy data and the Bellman equation to learn the Q-function, and uses the Q-f... | StarcoderdataPython |
3439835 | <reponame>Phenylalaninquelle/python-snippets<gh_stars>0
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Example usage of plot_radar_chart function
"""
import numpy as np
from pysnips.plotting import plot_radar_chart
def main():
# random sampled data
data = np.random.randint(1, 5, (4, 5))
# the vari... | StarcoderdataPython |
1618734 | """Platform for climate integration."""
import logging
from typing import List, Optional
from homeassistant.components.climate import (
ATTR_TEMPERATURE,
HVAC_MODE_HEAT,
SUPPORT_TARGET_TEMPERATURE,
TEMP_CELSIUS,
ClimateEntity,
)
from homeassistant.config_entries import ConfigEntry
from homeassistan... | StarcoderdataPython |
1634358 | <reponame>AllMyChanges/allmychanges.com<filename>allmychanges/tests/api2/user_tags.py
# coding: utf-8
from nose.tools import eq_
from operator import itemgetter
from django.test import Client
from ..utils import create_user, get_json, post_json
from allmychanges.models import Changelog, Tag
from unittest import TestCa... | StarcoderdataPython |
8039856 | import enum
from typing import Dict, List
import re
import pandas as pd
from pandas import DataFrame
class Sentiments(enum.Enum):
POS = 'POS'
NEG = 'NEG'
def read_sample() -> DataFrame:
df = pd.read_csv('data/raw/reviews.csv')
df['rating'] = df['rating'].astype(dtype='int64')
return df
def c... | StarcoderdataPython |
6672329 | <filename>Engine/Render/rpcore/gui/loading_screen.py
"""
RenderPipeline
Copyright (c) 2014-2016 tobspr <<EMAIL>>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including wi... | StarcoderdataPython |
1834875 | <reponame>spencerkent/pyPyrTools<gh_stars>10-100
import numpy
def sp3Filters():
''' Steerable pyramid filters. Transform described in:
@INPROCEEDINGS{Simoncelli95b,
TITLE = "The Steerable Pyramid: A Flexible Architecture for
Multi-Scale Derivative Computation",
... | StarcoderdataPython |
6691274 | import os
import bcrypt
import pymongo
from flask import flash, Flask, render_template, request, redirect
from flask.views import MethodView
from flask_admin import Admin, AdminIndexView
from flask_admin.contrib import rediscli
from flask_admin.contrib.fileadmin import FileAdmin
from flask_admin.consts import ICON_TYP... | StarcoderdataPython |
5078149 | import torch
import torch.nn as nn
import torch.nn.functional as F
from .coord_predict import RelativePolarCoordPredictor as CoordPredictor
class SCLModule(nn.Module):
def __init__(self, size, feature_dim, structure_dim):
super().__init__()
self.size = size
self.feature_dim = fea... | StarcoderdataPython |
366619 | <gh_stars>0
""" This holds all implementations of the SingleValueField parent class """
import numpy as np
from .containers import PLUMED_Group
from .specifications import SingleValueField
class PLUMED_Distance(SingleValueField):
""" Class to hold two AtomGroup objects, calculate geometric distances between them
... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.