id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
8114674
<reponame>shyamrav/gatk-sv #!/usr/bin/env python # -*- coding: utf-8 -*- # """ """ import argparse import pandas as pd def make_combinations(genic, genelists, noncoding, functional): # Assign all variants ANY effect and ANY genelist any_variants = genic.copy() any_variants['effect'] = 'Any' any_var...
StarcoderdataPython
16810
from django.urls import re_path from user_queries.views import UserQuerySaveView, UserQueryCollectView urlpatterns = [ re_path(r"^/save/?$", UserQuerySaveView.as_view(), name="user-save-query"), re_path( r"^/collect/?$", UserQueryCollectView.as_view(), name="user-collect-queries", )...
StarcoderdataPython
1663403
<reponame>Teinstein/PythonCore # Python Program to calculate area of different shapes # This is a menu driven program to input what shape's # area is required. def circleArea(radius): return 3.142*float(radius)*(radius); def rectangleArea(length,breadth): return float(length)*float(breadth); def squareArea(s...
StarcoderdataPython
1805252
<filename>testrail_client/api/__init__.py #!/usr/bin/env python # -*- coding: utf-8 -*- from .case import Case from .configurations import Config from .milestone import MileSt...
StarcoderdataPython
8025465
#!/usr/bin/env python # ___INFO__MARK_BEGIN__ ####################################################################################### # Copyright 2008-2021 Univa Corporation (acquired and owned by Altair Engineering Inc.) # Licensed under the Apache License, Version 2.0 (the "License"); you may not # use this file exc...
StarcoderdataPython
12856572
# @Copyright [2021] [<NAME>] import fileinput as fi # This module replaces the word <|SPACE|> with a new line (code line 18) def writer(): with open("c:/PycharmProjects/copy_data_from_1_file_to_another/input.txt", "w") as writer: data = input("Whatever you will write will be present in input.txt - ") ...
StarcoderdataPython
147705
""" Various utility methods for `taskweb` """ def parse_undo(data): """ Return a list of dictionaries representing the passed in `taskwarrior` undo data. """ undo_list = [] for segment in data.split('---'): parsed = {} undo = [line for line in segment.splitlines() if line.strip...
StarcoderdataPython
59450
<gh_stars>1-10 # ############################################################################### # (c) 2011, The Honeynet Project # Author: <NAME> <EMAIL> and <NAME> <EMAIL> # # This program is free software you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # t...
StarcoderdataPython
1734051
<filename>tocode/_literal_eval_par/_literal_eval.py<gh_stars>1-10 import sys import traceback from importlib import reload import pathlib from tocode.__inner_files__._built_in._built_in_file_manager import __reset_files from tocode._literal_eval_par._str_parser import __Str _current_abso_path = pathlib.Path(__file__)....
StarcoderdataPython
4928692
from multiprocessing import Pool, cpu_count from multiprocessing.pool import ThreadPoo #from tqdm import tqdm from ailabtools.utils import tqdm_ailab as tqdm def pool_worker(target, inputs, use_thread=False, num_worker=None, verbose=True): """Run target function in multi-process Parameters ---------- ...
StarcoderdataPython
3432037
# -*- coding: utf-8 -*- import pytest from chaoslib.exceptions import InvalidExperiment from chaoslib.extension import get_extension, has_extension, merge_extension, \ remove_extension, set_extension, validate_extensions from fixtures import experiments def test_extensions_must_have_name(): with pytest.rais...
StarcoderdataPython
9792482
<reponame>Aquaveo/gsshapyorm<gh_stars>0 """ ******************************************************************************** * Name: TimeSeriesModel * Author: <NAME> * Created On: Mar 18, 2013 * Copyright: (c) Brigham Young University 2013 * License: BSD 2-Clause ********************************************************...
StarcoderdataPython
3427458
<gh_stars>0 from setuptools import setup setup(name='django 1.7 on Red Hat Openshift', version='1.3', description='django on OpenShift', author='', author_email='', url='https://github.com/jfmatth/openshift-django17', )
StarcoderdataPython
4979917
<filename>Repository/_tools/generate_repo.py """ repository files and addons.xml generator """ """ Modified by Rodrigo@XMBCHUB to zip plugins/repositories to a "zip" folder """ """ Modified by BartOtten: create a repository addon, skip folders without addon.xml, user config file """ """ This file is "as is", without ...
StarcoderdataPython
1921348
from django.contrib import admin from contents.models import ContentBlock admin.site.register(ContentBlock)
StarcoderdataPython
6440603
<reponame>denzow/newser # coding: utf-8 from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): image_url = models.URLField('画像URL', blank=True)
StarcoderdataPython
3455569
import pygame from main.display import Display from main.pywitch_manager import PyWitchManager from main.click_manager import ClickManager from main.zombie import Zombie class Game(): def __init__(self): self.width = 1366 self.height = 768 self.tps = 60 self.clock = pygame.time...
StarcoderdataPython
4879309
<gh_stars>0 # -*- coding: utf-8 -*- # @Time : 2022/2/20 16:30 # @Author : <NAME> # @File : train.py # @Description: training wrapping launch.py import argparse from util import * import yaml, os parser = argparse.ArgumentParser() parser.add_argument( '-d', '--device', default="cpu", help="使用的运...
StarcoderdataPython
1839247
<filename>pyind/util.py def get_args(func, exclusion=()): args = list( func.__code__.co_varnames[:func.__code__.co_argcount] ) for e in exclusion: args.remove(e) return tuple(args) def cre_args(func, conf, exclusion=()): return tuple([ conf[e] for e in get_args(func, exclus...
StarcoderdataPython
8069047
import os from csdl.solvers.solver import Solver class LinearSolver(Solver): """ Base class for linear solvers. Attributes ---------- _rel_systems : set of str Names of systems relevant to the current solve. _assembled_jac : AssembledJacobian or None If not None, the Assemble...
StarcoderdataPython
6672053
<reponame>MohamedRaslan/screenpy """ Locators and URL for the Add & Remove Elements page. """ from screenpy import Target URL = "http://the-internet.herokuapp.com/add_remove_elements/" ADD_BUTTON = Target.the("add element button").located_by("button[onclick^=addElement]") ADDED_ELEMENTS = Target.the("added elements...
StarcoderdataPython
159228
# Copyright 2020 Silicon Compiler Authors. All Rights Reserved. import os import siliconcompiler import pytest @pytest.mark.eda @pytest.mark.quick def test_ghdl(datadir): design = "adder" design_src = os.path.join(datadir, f'{design}.vhdl') chip = siliconcompiler.Chip(loglevel="INFO") chip.load_target...
StarcoderdataPython
8147389
""" This sample shows to update an assignment Python 2.x/3.x ArcREST 3.5 """ from __future__ import print_function import arcrest from arcrest.common.general import Feature from arcresthelper import featureservicetools from arcresthelper import common from arcrest.packages import six import csv from datetime ...
StarcoderdataPython
3415193
from time import sleep class ResourcePool(object): def __init__(self, *resources, **kwargs): self.resources = list(resources) self.initializer = 'initializer' in kwargs and kwargs['initializer'] or None self.finalizer = 'finalizer' in kwargs and kwargs['finalizer'] or None def initiali...
StarcoderdataPython
6574432
<reponame>ivartb/itmo-assembler #!/usr/bin/python import sys from math import log from itertools import * total = {} bad = {} k = 2 eps = 1e-100 n2m = {'A' : 0, 'T' : 1, 'G' : 2, 'C' : 3} key_expr = sys.argv[1] bad = {} total = {} for l in sys.stdin: if not l: break l = l[:-1] x = l.split("\t...
StarcoderdataPython
11276053
from datetime import datetime, date from marqeta.response_models.application import Application from marqeta.response_models import datetime_object import json import re class ClientAccessTokenResponse(object): def __init__(self, json_response): self.json_response = json_response def __str__(self): ...
StarcoderdataPython
8021529
<reponame>bispojr/observatorio-ufj-covid19 from observatorio import settings from django.views.decorators.http import require_GET import datetime import requests @require_GET def obtem_ultimo_dia(request): # a API do brasil.io so exibe os dados do ultimo dia hoje = datetime.date.today() um_dia = datetime.timedel...
StarcoderdataPython
1679618
<reponame>aop4/PantherGoAPI from rest_framework import serializers from rest_api.models import * basic_info = ('uuid', 'latitude', 'longitude', 'name', 'id') class BasicAcademicBuildingSerializer(serializers.ModelSerializer): class Meta: model = AcademicBuilding fields = basic_info class BasicRes...
StarcoderdataPython
48312
<gh_stars>0 # -*- coding: utf-8 -*- import itertools import pathlib import numpy as np import numpy.linalg as LA from PIL import Image def tovector(image, k=None): # image -> vector data = np.asarray(image, dtype=np.float64) if k: return data[:,:, k].flatten() else: r...
StarcoderdataPython
8050774
from .iot import IoTData from .credential import CredentialProviderChain from .fc import Client
StarcoderdataPython
9628714
<reponame>JIHarrison/BundleTool # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'C:\Users\jharrison\Documents\GitHub\BundleTool\misc_Dialog.ui' # # Created by: PyQt5 UI code generator 5.10.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidget...
StarcoderdataPython
18886
from rest_framework.permissions import BasePermission, SAFE_METHODS from .models import User class IsAdminOrReadOnly(BasePermission): def has_permission(self, request, view): return bool( request.method in SAFE_METHODS or request.user and request.user.is_authenticated and ...
StarcoderdataPython
9611723
import os import glob from fastapi import FastAPI from fastapi_health import health from pydantic import BaseModel import datetime from db import ( model, action_model, form_model, response_model, question_model, answer_model, ) from db import action_meta_data from cassandra.cqlengine import c...
StarcoderdataPython
1609265
# MINLP written by GAMS Convert at 04/21/18 13:55:13 # # Equation counts # Total E G L N X C B # 384 180 64 140 0 0 0 0 # # Variable counts # x b i s1s s2s sc ...
StarcoderdataPython
1695973
# Copyright (c) 2015 SONATA-NFV, 2017 5GTANGO # 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 ...
StarcoderdataPython
130744
<filename>tools/perf/measurements/polymer_load.py # Copyright 2014 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. from telemetry.page import page from telemetry.page import page_test from telemetry.value import scalar c...
StarcoderdataPython
1874818
<filename>razemax/consumers.py import logging from typing import Union from razemax.drivers import SQSDriver from razemax.event_manager import EventManager class MessageConsumer: def __init__(self, mapper_factory: dict, event_manager: Union[EventManager, type(EventManager)], queue_driver: SQSDri...
StarcoderdataPython
11352681
<gh_stars>100-1000 import os # Plain text to morse code dictionary. MORSE_CODE_DICT = {'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', 'M': '--',...
StarcoderdataPython
6683663
# Roll number: # Registration number: # To verify the Goldbach conjecture and find the Goldbach composition of 1st n even numbers. from q11 import prime_list def goldbach_comp(n): lst = prime_list(1, n) for i in range(len(lst)): for j in range(i, len(lst)): if lst[i] + lst[j] == n: print(n, "=", lst[i], "+...
StarcoderdataPython
8145669
# -*- encoding: utf-8 -*- # PKGBUILDer v4.2.17 # An AUR helper (and library) in Python 3. # Copyright © 2011-2018, <NAME>. # See /LICENSE for licensing information. """ PKGBUILDer Data Storage. :Copyright: © 2011-2018, <NAME>. :License: BSD (see /LICENSE). """ from . import _, __version__ import pkgbuilder import pk...
StarcoderdataPython
3391594
<reponame>camall3n/actgen import math import gym import numpy as np from .. import utils class DiscreteBox(gym.Wrapper): """ Discretize a continuous "Box" action space into a discrete action space """ def __init__(self, env): """ :param env: an unwrapped gym environment that has a Box...
StarcoderdataPython
199017
"""The motionEye integration.""" from __future__ import annotations import asyncio import logging from typing import Any, Callable from motioneye_client.client import ( MotionEyeClient, MotionEyeClientError, MotionEyeClientInvalidAuthError, ) from motioneye_client.const import KEY_CAMERAS, KEY_ID, KEY_NAM...
StarcoderdataPython
348306
# Backtracking is a general algorithm for finding all (or some) solutions to some computational problems, notably # constraint satisfaction problems, that incrementally builds candidates to the solutions, and abandons a candidate # ("backtracks") as soon as it determines that the candidate cannot possibly be complete...
StarcoderdataPython
6562961
from django.contrib.localflavor.nl.forms import NLZipCodeField from django.forms.models import ModelForm from shop.models import Order class OrderForm(ModelForm): customer_zipcode = NLZipCodeField() class Meta: model = Order exclude = ('updated_at','created_at','is_payed','is_shipped')
StarcoderdataPython
11357619
<reponame>matan-h/futurecoder import inspect import linecache import os import sys from functools import lru_cache from importlib import import_module import friendly.runtime_errors import friendly.syntax_errors from main.workers.tracebacks import TracebackSerializer from main.workers.utils import import_submodules d...
StarcoderdataPython
5021404
# ---------------------------------------------------------------------------- # - Open3D: www.open3d.org - # ---------------------------------------------------------------------------- # The MIT License (MIT) # # Copyright (c) 2020 www.open3d.org # # Permission is her...
StarcoderdataPython
1811136
<filename>flask.py # -*- coding: utf-8 -*- """ flask ~~~~~ A microframework based on Werkzeug. It's extensively documented and follows best practice patterns. :copyright: (c) 2010 by <NAME>. :license: BSD, see LICENSE for more details. """ from __future__ import with_statement import os impor...
StarcoderdataPython
12822265
<gh_stars>1-10 import os import numpy as np def save(S,name): savedict ={} for at in S.__dict__: if type(S.__dict__[at]) == str: savedict[at] = S.__dict__[at] elif type(S.__dict__[at]) == list: savedict[at] = S.__dict__[at] elif type(S.__dict__[at]) == int: ...
StarcoderdataPython
11256788
import autograd.numpy as np import scipy.sparse as sparse # for testing import sys, time try: from . import csc, ltvsystem except: import csc, ltvsystem class LTVMPC: '''Interface that the provided "model" must provide: - getLinearDynamics(y, u) - dynamics(y, u) - if ITERATE_TRAJ is selected '...
StarcoderdataPython
3560411
<filename>ImbalanaceDataStudyLinearModel.py import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import SGDClassifier from sklearn.linear_model import LogisticRegression import pandas as pd import numpy as np from sklearn.preprocessing import StandardScaler, Normalizer import matplotlib.pyplot a...
StarcoderdataPython
3212491
<filename>aria/multivim-plugin/src/main/python/multivim-plugin/keystone_plugin/tests/test.py import mock import unittest from cloudify.context import NODE_INSTANCE from cloudify.mocks import ( MockContext, MockNodeInstanceContext, MockNodeContext ) from openstack_plugin_common import ( OPENSTACK_ID_PR...
StarcoderdataPython
1664673
<reponame>adujovic/JorG # -*- coding: utf-8 -*- import numpy as np from itertools import product import spglib from JorGpi.aux.Masks import maskFull from JorGpi.aux.PeriodicTable import periodicTableElement class Identity(dict): def __missing__(self, key): return key class FindFlips: wyckoffD...
StarcoderdataPython
12802280
import concurrent import math import threading from concurrent.futures import ThreadPoolExecutor from multiprocessing import Pool, cpu_count, Process import src.repository.global_params as global_params from src.library.logger import logger from src.library.shell import run_system_command_with_res class MultiProcess...
StarcoderdataPython
5104451
<gh_stars>1000+ # make importing these a bit less hassle from flexget.utils.parsers.movie import MovieParser # noqa pylint: disable=unused-import from flexget.utils.parsers.parser import TitleParser # noqa pylint: disable=unused-import from flexget.utils.parsers.series import ( # noqa pylint: disable=unused-import ...
StarcoderdataPython
8031025
# Copyright 2021 CR.Sparse Development Team # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed...
StarcoderdataPython
3516357
import os dir_path = os.path.dirname(os.path.realpath(__file__)) import numpy as np np.random.seed(10) import tensorflow as tf tf.random.set_seed(10) from tensorflow.keras import Model from flow_layers import scalar_real_nvp # Plotting import matplotlib.pyplot as plt #Build the model which does basic map of inputs t...
StarcoderdataPython
63007
#!/usr/bin/env python3 # # pico.workflow.executor - manages the execution of workflows # # Background # # The Workflow and Executor classes were factored out of BAP.py when its # execution logic became too unwieldy. They are simple implementations # of a generic workflow definition language and execution engine....
StarcoderdataPython
12860296
import sys import structlog from osrest import Tcpml import services_component def build_os(dataset_path, model_path, logger): logger.info(f"Loading OS dataset from \"{dataset_path}\".") dataset = Tcpml.load_dataset(dataset_path) logger.info(f"Building OS model.") model = Tcpml.build_model(dataset) ...
StarcoderdataPython
5011138
<filename>print_shippo_manifest.py<gh_stars>1-10 import shippo import datetime import time import requests import subprocess import os timestamp = datetime.datetime.now().isoformat()[:-3] + 'Z' # get carrier accounts carrier_account = {} carrier_account['tpr'] = os.getenv('CARRIER_ACCOUNT_TPR') carrier_account['thepr...
StarcoderdataPython
3539839
from map_base_abc import MapBase class UnsortedTableMap(MapBase): """Map implementation using an unordered list.""" def __init__(self): """Create an empty map.""" self._table = [] # list of _Item objects def __getitem__(self, k): """Return value associated with key k. Raise KeyErr...
StarcoderdataPython
5034419
"""Module for conveniently managing paths through the :class:`URI` class which is fully compatible with :class:`pathlib.Path`. """ from pathlib import Path, _PosixFlavour from typing import Callable import logging import abc import re import os import wrapt logger = logging.getLogger(__name__) class _URIFlavour(_Po...
StarcoderdataPython
3565644
#! /usr/bin/env python """ Usage: alex FILE_NAME Arguments: FILE input file """ from docopt import docopt from subprocess import Popen, PIPE, STDOUT, call import re def _collect_input(content): m = re.findall('"""I\n(.*?)"""', content, re.DOTALL) if len(m): return m return None def _collect_output(...
StarcoderdataPython
6445036
<filename>app/cards/admin.py from django.contrib import admin from cards import models @admin.register(models.Card) class CardAdmin(admin.ModelAdmin): model = models.Card
StarcoderdataPython
3479820
<filename>11.container-with-most-water.py # https://leetcode-cn.com/problems/container-with-most-water/ from typing import List class Solution1: ''' Date: 2022.04.11 Pass/Error/Bug: 1/2/0 执行用时: 184 ms, 在所有 Python3 提交中击败了 71.48% 的用户 内存消耗:24.2 MB, 在所有 Python3 提交中击败了 79.28% 的用户 ''' def maxAr...
StarcoderdataPython
316099
<filename>application/routes.py from application import app from flask import render_template, request, json, Response, current_app from .ceres.getpie import getPIE from pathlib import Path import pandas as pd from datetime import datetime from .ceres.sandbox import mkTaskData from flask import Flask, request, r...
StarcoderdataPython
5149658
<gh_stars>0 """ Module for Date type. """ from typing import Union, Optional, Any from PyQt5 import QtCore from pineboolib.application.utils.date_conversion import date_dma_to_amd class Date(object): """ Case que gestiona un objeto tipo Date. """ date_: QtCore.QDate time_: QtCore.QTime def _...
StarcoderdataPython
373888
#!/usr/bin/python3 """Configuration handling""" import configparser def get_config(location = "/etc/doors.ini"): config = configparser.ConfigParser() config.read(location) return config config = get_config()
StarcoderdataPython
6484278
# -*- coding: utf-8 -*- from flask.ext.assets import Bundle, Environment css = Bundle( "css/public/home.css", output="public/css/common.css" ) js = Bundle( "js/utils.js", filters='jsmin', output="public/js/common.js" ) assets = Environment() assets.register("js_all", js) assets.register("css_all", c...
StarcoderdataPython
5006812
from data_preprocessing import key_dts from stock_embedding import * PRINCIPAL = 1_000_000 PORTFOLIO_PATH = './output/portfolio' if not os.path.exists(PORTFOLIO_PATH): os.makedirs(PORTFOLIO_PATH) assert np.intersect1d(key_dts, historic_last_trx_day_in_each_month).shape == key_dts.shape daily_nav = pd.Series(dtype...
StarcoderdataPython
3295519
import numpy as np import geovista as gv M, N = 45, 90 lats = np.linspace(-90, 90, M + 1) lons = np.linspace(-180, 180, N + 1) mlons, mlats = np.meshgrid(lons, lats, indexing="xy") data = np.random.random((M + 1) * (N + 1)) mesh = gv.Transform.from_2d(mlons, mlats, data=data, name="synthetic") plotter = gv.GeoPlott...
StarcoderdataPython
3227374
""" Demo Flask application to test the operation of Flask with socket.io Aim is to create a webpage that is constantly updated with random numbers from a background python process. """ from flask_socketio import SocketIO from flask import Flask, render_template, request from random import random import threading from t...
StarcoderdataPython
6406570
#!/usr/bin/env python # Copyright Contributors to the OpenCue Project # # 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
1773505
from datetime import datetime from unittest import TestCase from eocdb.core.db.db_submission import DbSubmission from eocdb.core.models import DatasetValidationResult, Issue, QC_STATUS_SUBMITTED, QC_STATUS_VALIDATED from eocdb.core.models.submission_file import SubmissionFile class DbSubmissionTest(TestCase): d...
StarcoderdataPython
4839406
# Generated by Django 3.2.7 on 2021-09-14 21:03 from django.db import migrations, models import uuid class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Product', fields=[ ('id', model...
StarcoderdataPython
4879035
import sys import os sys.path.append(os.path.abspath(".")) sys.dont_write_bytecode = True __author__ = "COSAL" from utils.lib import O from utils import logger import properties from elasticsearch import Elasticsearch LOGGER = logger.get_logger(os.path.basename(__file__.split(".")[0])) def get_connection(): # ...
StarcoderdataPython
6432814
from dataclasses import dataclass from .utils import ResponseResourceBase @dataclass class ThumbnailKey: url: str = None width: int = None height: int = None @dataclass class ThumbnailResource: default: ThumbnailKey = None medium: ThumbnailKey = None high: ThumbnailKey = None standard: Thu...
StarcoderdataPython
6609733
from .logging import log
StarcoderdataPython
4872966
<gh_stars>1-10 from models.OutlierDetector import Detector from holders.Dataset import Dataset from configpkg.SettingsConfig import SettingsConfig from math import floor import numpy as np from utils.metrics import calculate_roc_auc def evaluate_detectors(dataset, detector_id): threshold_percentage = len(dataset....
StarcoderdataPython
5099896
from django.contrib import admin from django.utils.safestring import mark_safe from .models import Account, Note @admin.register(Account) class AccountAdmin(admin.ModelAdmin): list_display = ('name', 'icon_image', 'feed') exclude = ('private_key', 'public_key') def icon_image(self, row): return ma...
StarcoderdataPython
11233776
/usr/lib/python2.7/encodings/mac_roman.py
StarcoderdataPython
6616476
""" Maya stub of imports used in the UI library. The idea is to make this file as short as possible while leaving room for other packages to implement features. """ import functools, os, sys, platform from SkinningTools.Maya.tools import shared, joints from SkinningTools.Maya.tools import weightPaintUtils fro...
StarcoderdataPython
104376
<filename>src/ips.py """ 所有的定位算法 """ import numpy as np from scipy.stats import norm from funcs import * def kNNEstimation(samples, query, positions, k): """实现KNN方法 Args: samples (ndarray): 训练集样本 query (ndarray): 测试集样本 positions (ndarray): 训练集样本的位置 k (Number): 最近邻个数 Retu...
StarcoderdataPython
12815047
<gh_stars>0 import tkinter from tkinter import ttk import imageio from PIL import ImageTk, Image import time import threading import numpy as np from imageio.plugins.ffmpeg import FfmpegFormat class VideoPL(): def __init__(self, file_path, frame, preload=True, debug=False): format = FfmpegFormat( ...
StarcoderdataPython
6478816
from datetime import date from pydantic import BaseModel class DateRange(BaseModel): start: date end: date class Booking(BaseModel): id: int start: date end: date total: int listing_id: int owner_id: int status: str class CreateBookingIn(BaseModel): date_range: DateRange ...
StarcoderdataPython
6616582
<gh_stars>0 import cv2 import imutils def get_color_location(lower, upper, frame): # resize the frame, blur it, and convert it to the HSV # color space #frame = imutils.resize(frame, width=600) #blurred = cv2.GaussianBlur(frame, (11, 11), 0) blurred = frame hsv = cv2.cvtColor(blurred, cv2....
StarcoderdataPython
6578172
from p5 import * def draw(): background(204) line((0, 0), (width, height)) print(frame_count) run(frame_rate=30)
StarcoderdataPython
1817446
# Copyright 2020 The PGDL Competition organizers. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
StarcoderdataPython
50599
<reponame>obareau/python_travaux_pratiques text = """first row second row third row""" print(text)
StarcoderdataPython
49719
import os import cv2 import gc import random import time from tqdm import tqdm import numpy as np import matplotlib.pyplot as plt import argparse from glob import glob import torch import torch.nn as nn import torchvision.transforms as transforms from PIL import Image, ImageFilter from models.OEFT import OEFT parse...
StarcoderdataPython
6472147
<gh_stars>1000+ import numpy as np point = { 'rect': [22.0, 22.0], 'coords': [22.0, 22.0, 22.0, 22.0, 22.0], 'single': 22.0, 'missing': [22.0, 22.0, 22.0, 22.0]} rect = { 'rect': [[[ 1., 2.], [ 21., 21.]], [[ 12., 12.], [ 22., 22....
StarcoderdataPython
1728546
<reponame>cc13ny/all-in class Solution: # @param {string} s # @return {integer} def lengthOfLastWord(self, s): s = s.strip() ss = s.split() if len(ss) == 0: return 0 res = ss[len(ss) - 1] return len(res)
StarcoderdataPython
9611416
"""Actions for Runner Chaser Problem """ from typing import List from intmcp.model import DiscreteAction, JointAction from intmcp.envs.rc import grid as grid_lib class RCAction(DiscreteAction): """An action in the Runner Chaser Problem """ def __str__(self): return grid_lib.DIR_STRS[self.action_num...
StarcoderdataPython
3474941
"""CmdStanModel""" import os import platform import re import subprocess import shutil import logging from collections import OrderedDict from concurrent.futures import ThreadPoolExecutor, as_completed from multiprocessing import cpu_count from numbers import Real from pathlib import Path from typing import Any, Dict...
StarcoderdataPython
3315472
<reponame>romilly/roam-data from datetime import datetime from typing import List, Optional from roam_data.dates.dates import roam_format, dates_for_wc from roam_data.roam.graph import Entry, Block, Page def daily_entries_for_wc(entries: List, dt: datetime) -> List: dates = [roam_format(d) for d in dates_for_wc(...
StarcoderdataPython
40352
<gh_stars>1-10 # pylint: disable=global-statement,redefined-outer-name import argparse import csv import glob import json import os import yaml from flask import Flask, jsonify, redirect, render_template, send_from_directory from flask_frozen import Freezer from flaskext.markdown import Markdown # ------------- SERVE...
StarcoderdataPython
3481951
from rest_framework.views import exception_handler from rest_framework.exceptions import ValidationError from rest_framework import status from rest_framework.exceptions import JsonResponse from utils.response import ResponseBody def custom_exception_handler(exc, context): response = exception_handler(exc, conte...
StarcoderdataPython
249460
import numpy as np import matplotlib.pyplot as plt import seaborn as sns class Vizuals: def plot_manhattan(self, team=1): if team == 1: team = self.team1_df else: team = self.team2_df plt.style.use('ggplot') plt.figure(figsize=(15,9)) ass = team.groupby('Over')...
StarcoderdataPython
6490006
<reponame>microsoft/msgen # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. try: from setuptools import setup except ImportError: from distutils.core import setup # The version string is stored in only one place # so get it from msgen.py. from msgen_cli.msgen import VERSION as msgen_v...
StarcoderdataPython
332996
<gh_stars>10-100 #!/usr/bin/python3 def predict_image(model,test_image_name): from torchvision import transforms from PIL import Image import torch from imageio import imread image_transforms = { 'test':transforms.Compose([ transforms.ToPILImage(), transforms.Resize(size=256), ...
StarcoderdataPython
5158682
<filename>visualization/patient_visualization/paths_internal.py root = '/cluster/work/grlab/clinical/Inselspital/DataReleases/01-19-2017/InselSpital/'
StarcoderdataPython