id
stringlengths
2
8
text
stringlengths
16
264k
dataset_id
stringclasses
1 value
3588290
<filename>src/psiopic2/app/baseApp.py import sys from datetime import datetime from docopt import docopt from psiopic2.app.ui.prompt import ask, prompt import logging import textwrap from psiopic2.app.tasks import TaskException import traceback BASE_OPTIONS = """Options: --no-widgets Turn off all widgets, u...
StarcoderdataPython
1639003
<gh_stars>1-10 #!/usr/bin/env python # -*- coding: utf-8 -*- from django.contrib import admin from jamendo.models import Artist, Album, Track, License, Language,\ Country, State, City, Playlist, Radio, JamendoUser, Genre, Review admin.site.register(Artist) admin.site.register(Album) admin.site.register(Track) ad...
StarcoderdataPython
3388119
from twittertail.get_twitter_values import GetTwitterValues from twittertail.exceptions import ( FailedToGetTwitterValueException, FailedToGetTweetsException ) from html import unescape import requests import re class GetTweetsAPI: ''' GetTweetsAPI mimmicks the process a browser uses when accessing a ...
StarcoderdataPython
4914791
import pytask from src.config import BLD from src.config import SRC import numpy as np import json from itertools import product import pandas as pd from statsmodels.nonparametric.kernel_regression import KernelReg from sklearn.ensemble import RandomForestRegressor from sklearn.model_selection import train_test_split...
StarcoderdataPython
1867357
<reponame>sonata-nfv/son-monitor ## 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 appl...
StarcoderdataPython
4994792
input = """ 1 2 2 1 3 4 1 3 2 1 2 4 1 4 0 0 1 5 2 1 6 7 1 6 2 1 5 7 1 7 0 0 1 8 2 1 9 10 1 9 2 1 8 10 1 10 0 0 1 11 2 1 12 13 1 12 2 1 11 13 1 13 0 0 1 14 2 1 15 16 1 15 2 1 14 16 1 16 0 0 1 17 2 1 18 19 1 18 2 1 17 19 1 19 0 0 1 20 2 1 21 22 1 21 2 1 20 22 1 22 0 0 1 23 2 1 24 25 1 24 2 1 23 25 1 25 0 0 1 26 1 0 2 1 2...
StarcoderdataPython
11211195
<filename>many_classes/__init__.py<gh_stars>0 """ This package contains an example on how to run a Tango Device Server with 2 or more Device Classes. It includes the said 2 example Device Classes and a module to run them in one Device Server. """ __author__ = "<NAME>" __all__ = ["device_one", "device_two", "run_server"...
StarcoderdataPython
4993574
# -*- coding: utf-8 -*- """Top-level package for lidar.""" __author__ = """<NAME>""" __email__ = '<EMAIL>' __version__ = '0.5.0' from .filling import ExtractSinks from .slicing import DelineateDepressions from .filtering import MeanFilter, MedianFilter, GaussianFilter from .gui import gui, GUI # from .mounts import ...
StarcoderdataPython
6442462
import unittest from unittest.mock import patch from tmc import points from tmc.utils import load, load_module, reload_module, get_stdout, check_source from functools import reduce import os import textwrap from random import choice, randint exercise = 'src.factorials' function = 'factorials' def get_correct(test_ca...
StarcoderdataPython
1929622
<gh_stars>1000+ from typing import Any from packaging import version import optuna from optuna._deprecated import deprecated from optuna._imports import try_import with try_import() as _imports: import fastai if version.parse(fastai.__version__) >= version.parse("2.0.0"): raise ImportError( ...
StarcoderdataPython
1643741
<gh_stars>0 from uuid import uuid4 def generateUUID(): return str(uuid4())
StarcoderdataPython
8096511
<reponame>ethereum/asyncio-cancel-token import asyncio from typing import ( # noqa: F401 Any, Awaitable, List, Sequence, TypeVar, cast, ) from .exceptions import ( EventLoopMismatch, OperationCancelled, ) _R = TypeVar('_R') class CancelToken: def __init__(self, name: str, loop: ...
StarcoderdataPython
12805764
New Algorithms for Simulating Dynamical Friction <NAME>, <NAME>, <NAME> — RadiaSoft, LLC This notebook describes—and documents in code—algorithms for simulating the dynamical friction experienced by ions in the presence of magnetized electrons. The $\LaTeX$ preamble is here. $$ %% math text \newcommand{\hmhsp}{\mspa...
StarcoderdataPython
3556834
from .. import eval as ev from .. import nodes as no def test_eval(): q = no.Select( [ no.AllSelectItem(), ], [ no.Table( no.QualifiedNameNode.of(['t0'])), ], no.BinaryExpr( no.QualifiedNameNode.of(['id']), no....
StarcoderdataPython
1644207
# -*- coding: utf-8 -*- # # Copyright 2020 Google LLC. 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 requir...
StarcoderdataPython
6439497
<filename>Dynamic Programming/27_correct_word.py # We are given a function dict(word) that always works in O(1) time, which returns if a word is # a correct word of the language. We are given as an input a string without a space. Find an algorithm # that will find out if it is possible to insert spaces in the input str...
StarcoderdataPython
1723258
"""Functions to fit MRI SPGR signal to obtain T1. Created 28 September 2020 @authors: <NAME> @email: <EMAIL> @institution: University of Edinburgh, UK Functions: fit_vfa_2_point: obtain T1 using analytical formula based on two images fit_vfa_linear: obtain T1 using linear regression fit_vfa_nonlinear: obt...
StarcoderdataPython
9646089
# -*- coding: utf-8 -*- import os from setuptools import setup from numericalunits import __version__ # Utility function to read the README file. def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() descrip = ("A package that lets you define quantities with units, which can " ...
StarcoderdataPython
301498
<filename>p1_basic/day32_35thread/day33/11_线程池.py from concurrent.futures import ThreadPoolExecutor import time def task(a1, a2): time.sleep(2) print(a1, a2) # 创建了一个线程池(最多5个线程) pool = ThreadPoolExecutor(5) for i in range(40): # 去线程池中申请一个线程,让线程执行task函数。 pool.submit(task, i, 8)
StarcoderdataPython
3583026
<filename>testslider.py import numpy as np import matplotlib.pyplot as plt from matplotlib.widgets import Slider fig, ax = plt.subplots() plt.subplots_adjust(bottom=0.25) fig.canvas.set_window_title('Reaktionsfortschritt') t0 = 0 t = np.arange(0, t0, .5) k0 = 0.17 a = np.exp(- k0 * t) min_t = 5 l, = ax.plot(t, a, lw...
StarcoderdataPython
3379421
import pytest import torch from espnet2.enh.loss.criterions.tf_domain import FrequencyDomainL1 from espnet2.enh.loss.wrappers.fixed_order import FixedOrderSolver @pytest.mark.parametrize("num_spk", [1, 2, 3]) def test_PITSolver_forward(num_spk): batch = 2 inf = [torch.rand(batch, 10, 100) for spk in range(n...
StarcoderdataPython
6622156
<reponame>CurryEleison/workdocs-disaster-recovery from argparse import ArgumentParser, ArgumentTypeError from os.path import isdir from pathlib import Path import logging from workdocs_dr.cli_arguments import clients_from_input, bucket_url_from_input, logging_setup, organization_id_from_input, wdfilter_from_input from...
StarcoderdataPython
185856
<filename>power_perceiver/pytorch_modules/satellite_processor.py from dataclasses import dataclass import einops import torch from torch import nn from power_perceiver.consts import BatchKey from power_perceiver.pytorch_modules.query_generator import reshape_time_as_batch from power_perceiver.utils import assert_num_...
StarcoderdataPython
376515
# Objective 1: Read table from multiple pdf files contained in a directory to a list # Obkective 2: clean the pdf text data and find unique words then save them to a dictionary # To read tables contained within the pdf files, I'm using the tabula.py library # To install tabula.py on Python3 in windows OS, ensure Java ...
StarcoderdataPython
1691187
<reponame>cloudtools/awacs<gh_stars>100-1000 #!/usr/bin/env python3 import asyncio import importlib import sys import urllib.parse from pathlib import Path from typing import DefaultDict, Dict, Iterable, List, Set, Tuple import aiofiles import httpx from bs4 import BeautifulSoup BASE_URL = "https://docs.aws.amazon.co...
StarcoderdataPython
3448649
<reponame>t18cs020/discordpy-startup from discord.ext import commands import os import traceback bot = commands.Bot(command_prefix='/') token = os.environ['DISCORD_BOT_TOKEN'] #!/usr/bin/env python # coding: utf-8 # In[1]: # インストールした discord.py を読み込む import discord import random import csv import asyncio import da...
StarcoderdataPython
3448043
import importlib.metadata __version__ = importlib.metadata.version("cuda_checker")
StarcoderdataPython
226433
<filename>skm_tea/utils/env.py import os from iopath.common.file_io import PathManager, PathManagerFactory from meddlr.utils.cluster import Cluster from meddlr.utils.env import is_repro, supports_cupy # noqa: F401 def get_path_manager(key="skm_tea") -> PathManager: return PathManagerFactory.get(key) def cache...
StarcoderdataPython
9701789
from biobb_common.tools import test_fixtures as fx from biobb_io.api.memprotmd_sim_list import memprotmd_sim_list class TestMemProtMDSimList(): def setUp(self): fx.test_setup(self,'memprotmd_sim_list') def tearDown(self): fx.test_teardown(self) pass def test_memprotmd_sim_list(sel...
StarcoderdataPython
86924
# Copyright 2017 The Chromium 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 datetime import json import mock import unittest from mock import patch from google.protobuf import duration_pb2 from google.protobuf import empty_pb...
StarcoderdataPython
5076901
# # Testcase for DataHub # import pytest from macaca import DataHub def test_datahub(): print(DataHub) datahub = DataHub(hostname='127.0.0.1', port='9200') datahub.switch_scene(hub='sample', pathname='test1', data={ 'currentScene': 'scene1' }) datahub.switch_all_scenes(hub='sample', data={ 'currentSc...
StarcoderdataPython
5002622
from typing import Union from uuid import UUID from .base import BaseFunction from ..request import ( Request, SSEContextManager, ) class BackgroundTask(BaseFunction): """ Provides server-sent events streaming functions. """ task_id: UUID def __init__(self, task_id: Union[UUID, str]) ->...
StarcoderdataPython
3515295
""" Entropy calculations """ import math import zlib from collections import Counter from pathlib import Path from typing import Mapping from .analyzer import IPathPropertyAnalysis from . import register_analysis class EntropyCalculator(IPathPropertyAnalysis): @classmethod def ticks(cls) -> Mapping[float, ...
StarcoderdataPython
8184466
import torch a = torch.ones([10, 10]) b = torch.rand([10, 10]) print(a[:, None, :].size())
StarcoderdataPython
52843
from fabric.api import * def live(): """ Set the target to production. """ env.hosts = ['kurosaki@ichigo'] env.remote_app_dir = '/home/kurosaki/htdocs/setr.co.uk/' env.build_dir = '_site/' def push(): """ Pushes the code to nominated server. restart included. doesn't touch ...
StarcoderdataPython
211538
# The ExchangeAgent expects a numeric agent id, printable name, agent type, timestamp to open and close trading, # a list of equity symbols for which it should create order books, a frequency at which to archive snapshots # of its order books, a pipeline delay (in ns) for order activity, the exchange computation delay ...
StarcoderdataPython
5197128
<gh_stars>0 # Add the following code to your script to create a new Custom Vision service project. # Insert your subscription keys in the appropriate definitions. # Also, get your Endpoint URL from the Settings page of the Custom Vision website. from azure.cognitiveservices.vision.customvision.training import Custom...
StarcoderdataPython
6706097
''' Applications of computer vision ''' # pylint: disable=W0401 from .capture import * from .ipcam import *
StarcoderdataPython
5097000
# -*- coding: utf-8 -*- # MinIO Python Library for Amazon S3 Compatible Cloud Storage, (C) # 2020 MinIO, 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/lic...
StarcoderdataPython
6455195
#!/usr/bin/env pytest import logging import os from pathlib import Path from pytest_httpserver import HTTPServer from ornithology import ( config, standup, action, JobStatus, ClusterState, ) logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # Unset HTTP_PROXY for correct oper...
StarcoderdataPython
1746644
<filename>training-data/src/classification_data_tools.py from src.classification_print_tools import print_data_statistics def limit_negative_samples(features, targets, negative_count): limited_features = [] limited_targets = [] for i in range(0, len(targets)): if targets[i] == 1 or negative...
StarcoderdataPython
6441603
<gh_stars>0 from __future__ import absolute_import from __future__ import print_function import os import sys sys.path.insert(0, os.getcwd()) from twisted.internet import reactor from twisted.internet import defer from txjsonrpc.netstring.jsonrpc import Proxy def printValue(value): print("Result: %s" % str(valu...
StarcoderdataPython
11322354
<gh_stars>0 from __future__ import unicode_literals import frappe from frappe.core.doctype.user.user import create_contact import re def execute(): """ Create Contact for each User if not present """ frappe.reload_doc('integrations', 'doctype', 'google_contacts') frappe.reload_doc('contacts', 'doctype', 'contact') ...
StarcoderdataPython
176572
#!/usr/bin/env python3 from setuptools import setup, find_packages setup( name="Markdown-Video", version="0.1", url="http://github.com/Holzhaus/Python-Markdown-Video", license="GPL", author="<NAME>", author_email="<EMAIL>", description="Video Extension for Markdown", classifiers=[ ...
StarcoderdataPython
1837439
<gh_stars>0 # Censys exceptions class CensysTenableException(Exception): """Base Exception raised for errors in Censys Tenable integration.""" def __init__(self, message=None): self.message = message or "Error: Censys ASM assets not exported into Tenable" super().__init__(self.message) class ...
StarcoderdataPython
6582346
"""The Alarmo Integration.""" import logging import bcrypt import base64 from homeassistant.core import ( callback, ) from homeassistant.components.alarm_control_panel import DOMAIN as PLATFORM from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( ATTR_CODE, ATT...
StarcoderdataPython
138535
<filename>usuarios/views.py from django.shortcuts import render from django.shortcuts import redirect from django.contrib.auth import authenticate from django.contrib.auth import login from django.contrib.auth import logout from django.contrib.auth.models import User from products.models import Product from cart.models...
StarcoderdataPython
1682952
<reponame>xuanqing94/NeuralSDE import torch import torch.nn as nn from .diffusion_fn import MultiplicativeNoise, AdditiveNoise from .integrated_flow import IntegratedFlow from .flow_fn import RandFlowFn, RandFlowFn_v2 from .flow_net import MultiScaleFlow from .layers.conv2d import RandConv2d from .layers.linear impor...
StarcoderdataPython
4804075
""" Tests for fileio module """ # author: <NAME> (arm61) import unittest from datetime import datetime import os.path import pytest import yaml from orsopy.fileio.orso import Orso, OrsoDataset from orsopy.fileio.data_source import (DataSource, Experiment, Sample, Measurement, I...
StarcoderdataPython
1971753
<filename>python/sklearn/linear-regression/workload-analysis/bench-gpu/post-process/roofline/roofline.py #!/usr/bin/env python3 from collections import OrderedDict import matplotlib import matplotlib.pyplot as plt import seaborn as sns; def extract_model_data(data_file_path, debug=True): data_file_reader = open(...
StarcoderdataPython
11263904
""" intercepts.registration ~~~~~~~~~~~~~~~~~~~~~~~ This module implements the intercepts registration api. """ import atexit import sys import types from functools import partial # , update_wrapper from typing import Callable, Dict, List, Union import intercepts.builtinhandler as builtinhandler f...
StarcoderdataPython
241042
import math def function(x1): while True: try: value = int(input(x1)) except : print("HUEVON") continue else: break return float(value) while True: n2=function("Ceros: ") a2=function("Primer valor A: ") b2=func...
StarcoderdataPython
5047584
from . import Population from .genotype import Genome import math import logging class Experiment(object): """Peforms experiment using NEAT. Executes NEAT on a given set of data and a fitness method. Fitness method must be a python method named evaluate wrapped in a string. It will have one paramet...
StarcoderdataPython
6569780
<filename>LSTM/ModelProcessing.py<gh_stars>0 def Run(): import os.path import json results={} # if model doesn't exist,then train model if not os.path.exists('./LSTM/model_info.txt'): import numpy from pandas import read_csv import math from keras.models import Sequential from keras.layers import Dens...
StarcoderdataPython
3255961
<reponame>coherentsolutionsinc/issoft-insights-2019-sdc-carla-ros from math import atan2, sin class Stanley(object): def __init__(self, max_angle, k): self.max_angle = max_angle self.k = k self.int_val = self.last_error = 0. def reset(self): self.int_val = 0.0 def step(sel...
StarcoderdataPython
297491
<reponame>Austinstevesk/leetcode-solutions """ Given an array of strings strs, group the anagrams together. You can return the answer in any order. An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. Example 1: Inp...
StarcoderdataPython
123416
<reponame>PawanRamaMali/Family_Tree-Meet_The_Family<gh_stars>0 from src.family.processFileHandler import ProcessFileHandler from src.family.clan import Clan import pathlib import os import sys def main(): clan = Clan() file_name = 'input/initInput.txt' dir = pathlib.Path().absolute() fileProcessor = Proces...
StarcoderdataPython
8151711
<reponame>interhui/ovs-api # coding=utf-8 import os import logging from subprocess import Popen, PIPE enable_log_command = True enable_log_result = False enable_log_error = True enable_raise = False fmt = '%(asctime)s - %(name)s [%(process)d] : %(message)s' handler = logging.StreamHandler() handler.setFormatter(lo...
StarcoderdataPython
12854036
<filename>autohandshake/src/Pages/LoginPage.py from autohandshake.src.Pages.Page import Page from autohandshake.src.HandshakeBrowser import HandshakeBrowser from autohandshake.src.exceptions import InvalidURLError, NoSuchElementError, \ InvalidEmailError, InvalidPasswordError import re class LoginPage(Page): ...
StarcoderdataPython
1820465
from django.db import models from django.contrib.auth.models import User class UserProfile(models.Model): """ Extension of User model """ user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) # if vacation mode is set ...
StarcoderdataPython
79849
<gh_stars>1-10 #batch!/usr/bin/env python3 from __future__ import absolute_import, division, print_function, unicode_literals #DISTRIBUTED STRATEGY IN KERAS import tensorflow as tf # This file creates the trained models for a given neural network configuration from keras.models import Sequential from keras.layers i...
StarcoderdataPython
9786425
<gh_stars>0 from __future__ import annotations import copy import inspect import pathlib import typing from collections import Counter from io import StringIO from operator import eq import matplotlib.pyplot as plt import networkx as nx import networkx.algorithms.isomorphism as iso import numpy as np from chemicaldi...
StarcoderdataPython
191822
import parl from parl import layers class Model(parl.Model): def __init__(self, act_dim): self.conv1 = layers.conv2d(num_filters=32, filter_size=3, stride=2, padding=1, act='relu') self.conv2 = layers.conv2d(num_filters=32, filter_size=3, stride=2, padding=1, act='relu') self.conv3 = layer...
StarcoderdataPython
3526576
<gh_stars>0 import sys from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QHBoxLayout, QVBoxLayout, QMessageBox, QWidget, QGroupBox, QAction, QFileDialog, qApp from PyQt5.QtWidgets import QLabel from PyQt5.QtGui import QPixmap, QImage, QIcon from PyQt5.QtCore import Qt, QFile import numpy as np import cv2 c...
StarcoderdataPython
4839784
#!/usr/bin/env python import os import glob as gl import lxml.etree as etree import argparse as ap def Main(): path = ParseArguments().path FormatXmlsInPath(path) def ParseArguments(): parser = ap.ArgumentParser(description = 'Indents the xml in given path') parser.add_argument('path', help = 'path t...
StarcoderdataPython
83776
<reponame>Dreem-Organization/bender-api """bender URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r...
StarcoderdataPython
11272133
# -*- coding: utf-8 -*- u"""Run all experiments defined on a json file, storing results on database. Usage: run_experiments.py <configs.json> <dbname> [--dbserver=<dbserver>] Options: -h --help Show this screen. --version Show Version. --dbserver=<dbserver> URI of the mongodb server ...
StarcoderdataPython
6662549
<filename>metagraph/plugins/numpy/types.py from typing import Set, Dict, Any import numpy as np from metagraph import dtypes, Wrapper, ConcreteType from ..core.types import Vector, Matrix, NodeSet, NodeMap from ..core.wrappers import NodeSetWrapper, NodeMapWrapper class NumpyVectorType(ConcreteType, abstract=Vector):...
StarcoderdataPython
82102
import numpy as np def B_to_b(B): x_indices = [0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5] y_indices = [0, 0, 3, 1, 3, 1, 3, 2, 3, 2, 3] return np.array(B[x_indices, y_indices]) def b_to_B(b): B = np.zeros((6, 4)) x_indices = [0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5] y_indices = [0, 0, -1, 1, -1, 1, -1, 2, -1, ...
StarcoderdataPython
3385030
<reponame>philip-shen/note_python<gh_stars>0 from concurrent import futures import sys import tkinter import tkinter.scrolledtext import os, os.path import datetime import glob from PIL import Image, ImageTk from matplotlib.backends.backend_tkagg import ( FigureCanvasTkAgg, NavigationToolbar2Tk) from matplotlib.figur...
StarcoderdataPython
1630401
<gh_stars>1-10 from os import listdir, getcwd from os.path import isfile, join from math import sin, cos from setting_utils import timeLimit, heightLimit, input_stream files = [f for f in listdir(join(getcwd(), 'uploads')) if isfile(join(getcwd(), 'uploads', f))] files = [f for f in files if f.endswith(".txt")] rgb...
StarcoderdataPython
11398894
<filename>Algo-DS/10_Sorting/bubble.py<gh_stars>1-10 ''' Bubble Sort ''' def bubble_sort(arr): for n in range(len(arr)-1, 0, -1): print('loops: ', n) for k in range(n): print('bubble: ', k) if arr[k] < arr[k+1]: arr[k], arr[k+1] = arr[k+1], arr[k] pr...
StarcoderdataPython
1677375
import os import stat import shutil import filecmp from dvc.main import main from dvc.command.repro import CmdRepro from dvc.project import ReproductionError from dvc.utils import file_md5 from tests.basic_env import TestDvc class TestRepro(TestDvc): def setUp(self): super(TestRepro, self).setUp() ...
StarcoderdataPython
9700706
from PIL import Image from pywebio.input import * from pywebio.output import * from pywebio.session import * from pywebio import start_server import io from datetime import datetime import time now = datetime.now() # loading spin def loading(): with put_loading(shape='border', color='primary').style('width:4rem;...
StarcoderdataPython
1663755
import cv2 as cv img = cv.imread("Lenna.png") cv.namedWindow("BRISK", cv.WINDOW_NORMAL) def f(x): return # Initiate BRISK detector cv.createTrackbar("Threshold", "BRISK", 30, 128, f) cv.createTrackbar("Octaves", "BRISK", 3, 9, f) cv.createTrackbar("Pattern Scale", "BRISK", 3, 9, f) while True: current_th...
StarcoderdataPython
3525545
<reponame>wcsodw1/Computer-Vision-with-Artificial-intelligence # python David_1_1_detect_face.py -i "../../../CV_PyImageSearch/Dataset/data/basketball.jpg" # Summary : # 1.Detect image # 2.save(imwrite) bondingbox_image to File # API : 1.cv2.waitKey(0) # Visualize the image until 設定手動關閉Visualize Image ...
StarcoderdataPython
6486675
from sklearn import mixture import sklearn.datasets import matplotlib.pyplot as plt import numpy as np import generator as g; from sklearn import preprocessing def em(input_array,no_of_clusters): model = sklearn.mixture.GaussianMixture(n_components=no_of_clusters,covariance_type='diag') a = mode...
StarcoderdataPython
1612110
from django.shortcuts import redirect from django.views.generic.base import TemplateView from django.http import Http404, HttpResponse from django.urls import reverse from scorecard.profiles import get_profile from scorecard.models import Geography, LocationNotFound from infrastructure.models import Project from house...
StarcoderdataPython
4918812
<filename>ecommercejockey/main/serializers.py from rest_framework.serializers import Serializer class ProductOrderCreateSerializer(Serializer): def update(self, instance, validated_data): print(validated_data) x = { 'id': 820982911946154508, 'email': '<EMAIL>', ...
StarcoderdataPython
1959816
from rpi_inky_layout import Layout, Rotation from PIL import Image, ImageDraw # Uncomment if you want to test on your Pi/Inky combo. # from inky.auto import auto topLayout = Layout((400, 100), packingMode='h', border=(1, 2)) # Uncomment if you want to test on your Pi/Inky combo. # board = auto() # topLayout = Layout(...
StarcoderdataPython
1944359
import mock import numpy as np from emukit.core import ContinuousParameter, ParameterSpace from emukit.core.acquisition import Acquisition from emukit.core.interfaces import IModel from emukit.core.loop import (FixedIntervalUpdater, FixedIterationsStoppingCondition, LoopState, SequentialPointCalculator, ...
StarcoderdataPython
6473629
# coding:utf-8 # @Time : 2019/5/15 # @Author : xuyouze # @File Name : __init__.py import importlib from config.base_config import BaseConfig from models.base_model import BaseModel from models.build import build_model __all__ = ["create_model"] # # def find_model_using_name(model_name: str): # ...
StarcoderdataPython
6489267
<filename>sender.py import smtplib from config import SMTP_USER, SMTP_PWD def notify(recipients, subject, body): # build smtp message message = """From: %s\nTo: %s\nSubject: %s\n\n%s""" % \ (SMTP_USER, ", ".join(recipients), subject, body) # send email try: server = smtplib.SMTP(...
StarcoderdataPython
5053733
# -*- coding: utf-8 -*- """ Created on Mon Nov 12 08:59:32 2018 @author: ymamo """ import NetAgent as N import ResourceScape as R def form_connection(model): for agent in model.ml.agents_by_type[N.NetAgent].values(): meta = [] meta.append(agent) meta.append(model.ml.ag...
StarcoderdataPython
3385412
import setuptools def long_description(): with open('README.md', 'r') as file: return file.read() setuptools.setup( name='stream-unzip', version='0.0.69', author='Department for International Trade', author_email='<EMAIL>', description='Python function to stream unzip all the files i...
StarcoderdataPython
8032148
#-*- coding:utf-8 -*- from core_backend import context from core_backend import conf from core_backend.rpc.amqp import AMQPRpc from functools import wraps from contextlib import contextmanager from core_backend.libs.exception import Error import sys import traceback import logging import plugin import settings import p...
StarcoderdataPython
54750
from CreatureRogue.data_layer.species import Species class Encounter: def __init__(self, species: Species, min_level: int, max_level: int, rarity): self.species = species self.min_level = min_level self.max_level = max_level self.rarity = rarity def __str__(self): retu...
StarcoderdataPython
11225023
<gh_stars>0 from google.appengine.api import urlfetch from django.shortcuts import render from mock_data import EGFR_GBM_LGG as FAKE_PLOT_DATA from maf_api_mock_data import EGFR_BLCA_BRCA as FAKE_MAF_DATA from django.conf import settings ############################################# # this is file is an abstraction fo...
StarcoderdataPython
5194356
import sys puctuation_removal = [".", ",", "'", "!", "%", "$", "@", "#", "^", "&", "*", "(", ")", "-", "_", "+", "=", "{", "}", "[", "]", "|", ";", ":", "<", ">", "?"] def remove_punction(text_list): """ This Function removes any puctuation from provided text Punctuations, listed in puctuation_removal, will be r...
StarcoderdataPython
5091495
<filename>tensorflow_datasets/core/registered.py # coding=utf-8 # Copyright 2020 The TensorFlow Datasets Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org...
StarcoderdataPython
5085983
# pyOCD debugger # Copyright (c) 2006-2021 Arm Limited # Copyright (c) 2020 <NAME> # Copyright (c) 2021 mentha # Copyright (c) <NAME> # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obt...
StarcoderdataPython
6518741
#!/usr/bin/python #coding=utf-8 def plot(): import numpy as np import matplotlib.pyplot as plt plt.figure(1) # 创建图表1 plt.figure(2) # 创建图表2 ax1 = plt.subplot(211) # 在图表2中创建子图1 ax2 = plt.subplot(212) # 在图表2中创建子图2 x = np.linspace(0, 3, 100) for i in xrange(5): plt.figure(1) # ...
StarcoderdataPython
4978487
from . import schema, verify, apply import os, platform import pytest import jsonschema root = { 'username':'root', 'uid': 0, 'gid': 0, } non_existant_user = { 'username':'nonexistantuser333' } def test_schema(): jsonschema.validate(root, schema()) jsonschema.validate(non_existant_user, schem...
StarcoderdataPython
3389359
<filename>controller/controller.py<gh_stars>10-100 #!/usr/bin/env python2 import json import sys import threading import time from app.ipsec import IPsecS2SApplication from cli import start_cli import switch_controller # Load configuration with open('config/topology.json', 'r') as f: config = json.load(f) # Set...
StarcoderdataPython
264303
from datetime import datetime from fms_core.template_importer.row_handlers._generic import GenericRowHandler from fms_core.services.container import get_container, move_container class ContainerRowHandler(GenericRowHandler): def __init__(self): super().__init__() def process_row_inner(self, containe...
StarcoderdataPython
11388305
import json import re import glob from pathlib import Path from typing import List, Optional from rate import ClipRater from scripts.helper import render DEVICE = "auto" INIT_SCRIPT = """ epochs: 20 optimizer: rmsprob learnrate: 2 init: mean: 0.33 std: 0.03 resolution: 10 targets: - name: full scale ba...
StarcoderdataPython
248439
<gh_stars>0 # (c) 2021 <NAME> <<EMAIL>> import os,sys import numpy as np import imageio from ccvtools import rawio import random import string import mutagen import json def fill(full_times_file,ccv_file,ccv_times_file): ccv_out_file = ccv_file[0:-4]+'_filled'+ccv_file[-4:] ccv_times = np.loadtxt(ccv_times_f...
StarcoderdataPython
1758521
import typing as T class BaseView: def __init__(self, screen: T.Any) -> None: self.screen = screen def start(self) -> None: pass def stop(self) -> None: pass def idle(self) -> None: pass def keypress(self, key: int) -> None: pass
StarcoderdataPython
9688774
<reponame>corinneherzog/tea-lang import pandas as pd import tea import os from tea.logging import TeaLoggerConfiguration, TeaLogger import logging configuration = TeaLoggerConfiguration() configuration.logging_level = logging.DEBUG TeaLogger.initialize_logger(configuration) # This example is adapted from http://www....
StarcoderdataPython
2279
<gh_stars>100-1000 import numpy as np import unittest from pydlm.modeler.trends import trend from pydlm.modeler.seasonality import seasonality from pydlm.modeler.builder import builder from pydlm.base.kalmanFilter import kalmanFilter class testKalmanFilter(unittest.TestCase): def setUp(self): self.kf1 ...
StarcoderdataPython