id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
283754
<gh_stars>0 from typing import Any, Set from sqlalchemy import or_ from sqlalchemy.orm import Query from rabbitai import security_manager from rabbitai.views.base import BaseFilter class DatabaseFilter(BaseFilter): # TODO(bogdan): consider caching. def schema_access_databases(self) -> Set[str]: # noqa pyli...
StarcoderdataPython
3308440
<filename>prestans/devel/__init__.py<gh_stars>0 # -*- coding: utf-8 -*- # # prestans, A WSGI compliant REST micro-framework # http://prestans.org # # Copyright (c) 2017, Anomaly Software Pty Ltd. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are perm...
StarcoderdataPython
12843644
import pytest @pytest.fixture def star_quality_metric(pipeline, analysis_step_run, bam_file): return { 'status': "finished", 'pipeline': pipeline['uuid'], 'step_run': analysis_step_run['uuid'], 'schema_version': '2', 'quality_metric_of': [bam_file['uuid']] } def test_...
StarcoderdataPython
1719964
<gh_stars>0 #!/usr/bin/env python # -*- coding:utf-8 -*- """================================================================= @Project : Algorithm_YuweiYin/LeetCode-All-Solution/Python3 @File : LC-0118-Pascals-Triangle.py @Author : [YuweiYin](https://github.com/YuweiYin) @Date : 2022-02-15 ======================...
StarcoderdataPython
3212273
<filename>12 - Esfera.py<gh_stars>0 R = float(input()) PI = 3.14159 VOLUME = (4/3.0) * PI * (R ** 3) print(f'VOLUME = {VOLUME:.3f}')
StarcoderdataPython
242954
<filename>lightcone_resample/find_galaxies.py #!/usr/bin/env python2.7 from __future__ import print_function, division import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as clr import dtk import h5py import sys import time from numpy.random import normal import pandas as pd def get_hfiles(f...
StarcoderdataPython
4952746
<gh_stars>1-10 """ Raw Python version of jupyter notebooks from fast.ai course """ __author__ = "<NAME>" from fastai import * from fastai.vision import * def create_own_dataset_from_google():
StarcoderdataPython
1998593
# encoding:utf-8 import sys sys.path.extend(["../../","../","./"]) import time import torch.optim.lr_scheduler import torch.nn as nn import random import argparse from driver.Config import * from driver.Model import * from driver.Labeler import * from data.Dataloader import * import pickle import os import re from dri...
StarcoderdataPython
1816347
<gh_stars>0 #!/usr/bin/python3 import sys import re import json import socket import os import subprocess from pathlib import Path executable = Path(sys.argv[0]).name if os.getuid() != 0: print(f"{executable} requires root access") exit(1) if "/etc/pve" not in Path("/proc/mounts").read_text(): print("ERRO...
StarcoderdataPython
3574078
#!/usr/bin/env python # encoding: utf-8 # <NAME>, 2006-2010 (ita) """ Support for translation tools such as msgfmt and intltool Usage:: def configure(conf): conf.load('gnu_dirs intltool') def build(bld): # process the .po files into .gmo files, and install them in LOCALEDIR bld(features='intltool_po', appna...
StarcoderdataPython
1725345
# -*- coding: utf-8 -*- """TcEx Runtime App Test Case""" import os from six import string_types from .test_case import TestCase class TestCaseJob(TestCase): """App TestCase Class""" _output_variables = None redis_client = None @staticmethod def create_shelf_dir(shelf_path): """Create a d...
StarcoderdataPython
4909072
<reponame>Socrats/Axelrod import random from axelrod.action import Action from axelrod.player import Player, obey_axelrod from axelrod.strategies import TitForTat from axelrod.strategy_transformers import NiceTransformer from numpy.random import choice from ._strategies import all_strategies from .hunter import (Alte...
StarcoderdataPython
1915851
from __future__ import annotations from abc import ABCMeta, abstractmethod from typing import Tuple, Type from io import BytesIO class MessageException(Exception): pass class Message(metaclass=ABCMeta): """ header: information required to e.g. route to correct subsystem It is limited to carry o...
StarcoderdataPython
1659593
"""Gives users direct access to class and functions.""" from shamirs.shamirs import share, shares, interpolate
StarcoderdataPython
1758015
<gh_stars>1-10 import datetime from sqlalchemy import or_ from lib.util_sqlalchemy import ResourceMixin from coder.extensions import db from coder.blueprints.billing.models.credit_card import CreditCard from coder.blueprints.billing.models.coupon import Coupon from coder.blueprints.billing.gateways.stripecom import (...
StarcoderdataPython
8167321
<gh_stars>1-10 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import logging import numpy as np from typing import Dict import torch from detectron2.layers import ShapeSpec, batched_nms_rotated from detectron2.structures import Instances, RotatedBoxes, pairwise_iou_rotated from detectron2.utils...
StarcoderdataPython
8040051
<gh_stars>0 #!/usr/bin/env python # -*- coding: utf-8 -*- import json from lighttree import TreeBasedObj from pandagg.tree.mappings import _mappings from pandagg.interactive._field_agg_factory import field_classes_per_name from pandagg.utils import DSLMixin class IMappings(DSLMixin, TreeBasedObj): """Interacti...
StarcoderdataPython
9667423
from myproductivitytool.common.services import * from myproductivitytool.project.models import * from myproductivitytool.project.serializers import * from django.db.models.functions import Concat from django.db.models import F, Value, CharField class BaseProjectEntityService(ModelService): entity = BaseProjectEnt...
StarcoderdataPython
8000784
import os import itertools import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as mpatches from helper import * #Visualize scanpath for all participants based on I-VT fixations: for h,j in itertools.product(sub_id,img_id): file='Sub_'+str(h)+'_Image_'+str(j)+'.csv' ...
StarcoderdataPython
8153109
<gh_stars>0 class PowerCellGrid: def __init__(self, width, height, serial_number): self.grid = list() for y in range(1, height+1): self.grid.append(list()) for x in range(1, width+1): self.grid[y-1].append(self.find_power_level(x, y, serial_number)) def f...
StarcoderdataPython
9745942
#!/bin/python3 import sys n = int(input().strip()) a = list(map(int, input().strip().split(' '))) swapCount = 0 # bubble sort for i in range(n): for j in range(n - 1): if a[j] > a[j + 1]: temp = a[j] a[j] = a[j + 1] a[j + 1] = temp swapCount += 1 print("Arr...
StarcoderdataPython
372809
<filename>flask_app/app.py from pprint import pprint as pp from pandas.core.indexes.datetimes import date_range import requests from flask import Flask, flash, redirect, url_for, Response, request import os import pandas as pd import numpy as np from query_from_models import predict_json, create_input_for_model from ac...
StarcoderdataPython
11256249
from .stopwatch import StopWatch from .dateutils import DateUtils from .counter import Counter __all__=['StopWatch','DateUtils','Counter']
StarcoderdataPython
179744
<reponame>Jmast/kombu-redis-priority<filename>tests/scheduler/test_roundrobin.py<gh_stars>1-10 import unittest from ddt import ddt, data from kombu_redis_priority.scheduling.round_robin import RoundRobinQueueScheduler @ddt class TestRoundRobinQueueScheduler(unittest.TestCase): def test_round_robin_scheduler_gets...
StarcoderdataPython
3512579
from . import __version__ as app_version app_name = "slnee" app_title = "Slnee" app_publisher = "Weslati Baha Eddine" app_description = "Custom apps developed by Slnee engineers" app_icon = "octicon octicon-file-directory" app_color = "grey" app_email = "<EMAIL>" app_license = "MIT" app_logo_url = "/assets/slnee/image...
StarcoderdataPython
3460788
<reponame>yotamitai/AuToPN<gh_stars>0 from itertools import combinations from tools import * def get_similar(sim, p0, p1): if p0 in sim.keys(): sim[p0].append(p1) else: flag = True for v in sim.values(): if p0 in v: flag = False break ...
StarcoderdataPython
6473117
<gh_stars>0 from django.db import models class Idol(models.Model): name = models.CharField(unique=True, max_length=255) google_calender = models.CharField(max_length=255, null=True) is_group = models.BooleanField(default=False)
StarcoderdataPython
11262454
# Databricks notebook source # MAGIC %md # CCU002_02-D07-covid19 # MAGIC # MAGIC **Description** This notebook determines the COVID19 infection and hospital outcomes. # MAGIC # MAGIC **Author(s)** <NAME> # COMMAND ---------- # MAGIC %md ## Define functions # COMMAND ---------- # Define create table function by <...
StarcoderdataPython
3358874
<filename>sd_estimator/estimator.py from .theoretical_estimates import * from math import inf, ceil, log2, comb from prettytable import PrettyTable from progress.bar import Bar from scipy.special import binom as binom_sp from scipy.optimize import fsolve from warnings import filterwarnings filterwarnings("ignore", cat...
StarcoderdataPython
1885188
# used - straight check, strings are cut def test_contact_fields_on_home_page(app): contact_from_home_page = app.contact.get_contact_list()[0] contact_from_edit_page = app.contact.get_contact_info_from_edit_page(0) assert contact_from_home_page.firstname == contact_from_edit_page.firstname assert cont...
StarcoderdataPython
4812560
<filename>Day45_46_BST/minimum_difference.py #code T = int(input()) for i in range(T): N = int(input()) arr = list(map(int, input().split())) arr.sort() # n diff = 10**20 # initialize difference as infinite for i in range(len(arr)-1): # nlogn if((arr[i+1] - arr[i]) < diff): dif...
StarcoderdataPython
5172608
<reponame>Tymec/Playground def count_boomers(lst): boomer_list = [] for i in range(2, len(lst)): if lst[i - 2] == lst[i] and lst[i - 1] != lst[i]: boomer_list.append(lst[i - 2:i + 1]) return boomer_list, len(boomer_list) print(count_boomers([1, 5, 1, 5, 5, 6, 5, 3, -1, -2, 3, 2, 3])) print(coun...
StarcoderdataPython
8192698
<filename>setup.py import setuptools with open("README.md", "r") as fh: long_description = fh.read() files = ["web/web.zip", "config/logging.json"] setuptools.setup( name="transposcope", version="2.0.0", author="<NAME>", author_email="<EMAIL>", description="A package for visualizing read cove...
StarcoderdataPython
9733900
import logging import torch as T from fairseq.data import encoders from selsum.utils.posterior_generator import PosteriorGenerator from selsum.utils.helpers.collators import collate_features from selsum.utils.helpers.subsampling import sample_from_q from fairseq.utils import apply_to_sample from selsum.utils.constants....
StarcoderdataPython
1819488
<filename>Med_Cabinet/data/Leafly_csv_Wrangle.py<gh_stars>0 # Leafly_csv_Wrangle.py # First wrangle to get unique effects for front end user survey and ML use # Second wrangle to strip "[]"" from list of Effects in Effects column values # and replace "," with " " in attempt for better neural networking fit. # Imp...
StarcoderdataPython
1873276
from distutils.core import setup setup( name='capiq-python', version='0.1', packages=['capiq'], url='https://github.com/guydmann/capiq-python', license='', author='guydmann', author_email='<EMAIL>', description='Thin Api Wrapper for Cap IQ' )
StarcoderdataPython
5126169
<reponame>williamlzw/MicroCls<gh_stars>0 import torch import torch.nn as nn from torch.nn.functional import adaptive_avg_pool2d class ConvBNACT(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, groups=1): super().__init__() self.conv = nn....
StarcoderdataPython
5126164
#!/usr/bin/env python import numpy as np from spatialmath import SE3, base import math def p_servo(wTe, wTep, gain=2, threshold=0.1): ''' Position-based servoing. Returns the end-effector velocity which will cause the robot to approach the desired pose. :param wTe: The current pose of the end-e...
StarcoderdataPython
5038474
<reponame>peter88213/PyWOffice """HmtlBookDescReader - Class for book summary. file operations and parsing. Part of the PyWriter project. Copyright (c) 2020 <NAME> For further information see https://github.com/peter88213/PyWOffice Published under the MIT License (https://opensource.org/licenses/mit-license.php) ...
StarcoderdataPython
6457657
""" :Author: <NAME> <<EMAIL>> """ import inspect from imagination.decorator.validator import restrict_type from tori.db.common import PseudoObjectId from tori.db.exception import LockedIdException from tori.db.metadata.helper import EntityMetadataHelper def get_collection_name(cls): raise RuntimeError('obsolete...
StarcoderdataPython
6650711
import requests from AlertManager.how_to_create_alert import create_alert from AlertManager.how_to_get_alert_by_id import get_alert from AlertManager.how_to_get_alert_type_by_id import get_alert_type from AlertManager.how_to_get_alert_types import get_alert_types from AlertManager.how_to_get_alerts import get_alerts f...
StarcoderdataPython
4950602
from docker_update.dockerUpdate import DockerUpdate
StarcoderdataPython
197679
<gh_stars>1-10 # # Copyright 2017 the original author or 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/licenses/LICENSE-2.0 # # Unless required by ap...
StarcoderdataPython
11325654
import models from django.db.models.base import ModelBase import serializer # imports Generic Views from django_template_project base app from base.views import ( SerializerListView, SerializerDetailView, SerializerCreateView, SerializerUpdateView ) for name, cls in models.__dict__.items(): if i...
StarcoderdataPython
1643560
<filename>day05/day05_puz1.py<gh_stars>1-10 #! /usr/bin/env python def run_opcode(code_list, programme_input=1): """Run the opcode as determined by the values in code_list Before you enter the next loop, check to see if the opcode (the first number in the sequence) is 99. If it is, then you can stop ...
StarcoderdataPython
6489281
''' The commands manager is an API to be used to create commands, bind commands to handlers and activate them. It's also possible to bind handlers to a given scope so that they're only active when a scope is active. # The basic usage is: commands_manager.register_command('copy', 'Copy') commands_manager.se...
StarcoderdataPython
75990
import shapefile from shapely.geometry import shape import csv import sys import matplotlib.pyplot as plt import numpy as np from random import randint from subprocess import call from array import array from shapely.geometry import Polygon from shapely.geometry.multipolygon import MultiPolygon import glob import math ...
StarcoderdataPython
1766823
# -*- coding: utf-8 -*- import grok from grokui.admin import representation class ApplicationInformation(grok.ViewletManager): grok.name('grokui_admin_appinfo') grok.context(representation.IApplicationRepresentation)
StarcoderdataPython
4824668
#!/usr/bin/env python3 # Generate and upload changelog from git import Repo, exc from github import Github import os import sys upload_changelog = True # Tracked repositories and their paths # First entry in each pair is how the repository will appear in the changelog # Second is the path relative to the script (or...
StarcoderdataPython
9605013
<filename>polybar/scripts/weather/parser.py import argparse USAGE_MESSAGE = """%(prog)s [-c [CITY_NAME]] [-u [UNIT]] [-a [API_KEY]] [-l [LANGUAGE]] [-v] Some examples: ~$ %(prog)s ::> 275 K ~$ %(prog)s -c london ::> 291 K ~$ %(prog)s -u imperial -v ::> 79ºF, Scattered Clouds ~$ %(prog)s -v -C -u metric ::> 26ºC, B...
StarcoderdataPython
3205752
<gh_stars>0 def amplitude(n): amplitude = '' for x in range(1,n): amplitude += f'(I Sin[x])^{x} Cos[x]^{n-x} + ' return amplitude[:-3] with open('cut2.nb', 'w') as f: for n in range(4,20,2): f.write(f'a{n}[x_] := {n}*Abs[{amplitude(n)}]/Sqrt[2^{n}];\n') for n in range(4,20,2): f.write(f'Print[{amplitude(n)...
StarcoderdataPython
8014756
class Node: def __init__(self): self.data = None self.next = None def setData(self, data): self.data = data def getData(self): return self.data def setNext(self, next): self.next = next def getNext(self): return self.next class SinglyLinkedList: ...
StarcoderdataPython
4923814
<gh_stars>100-1000 import argparse import re """ Currently, litex outputs XDC constraints in which the create_clock commands cannot be correctly parsed yet by the XDC yosys plugin. Example of failing XDC command: create_clock -name clk100 -period 10.0 [get_nets clk100] Example of working XDC command: create_c...
StarcoderdataPython
53795
<gh_stars>0 # -*- coding: utf-8 -*- import random import copy from local_searchs.heuristic import Heuristic class Neighbor(object): def __init__(self, state): self.state = state self.bagState = state[0] self.itemState = state[1] def generateState(self): #State = [[V_1, V_2, V_...
StarcoderdataPython
9708039
<gh_stars>1-10 from signals.logging import SignalsError, warn class Field(object): DATE = "date" DATETIME = "datetime" INTEGER = "int" DECIMAL = "decimal" FLOAT = "float" STRING = "string" TEXT = "text" BOOLEAN = "boolean" VIDEO = "video" IMAGE = "image" TYPES = [DATE, DATE...
StarcoderdataPython
4952575
from django.db import models from django.conf import settings from django.utils import timezone from budgetbuddy.paychecks.choices import deduction_type_choices class Paycheck(models.Model): company = models.CharField(max_length=200) annual_salary = models.DecimalField(max_digits=10, decimal_places=2) pay...
StarcoderdataPython
3335677
# -*- coding: utf-8 -*- ''' Created on 17/3/13. @author: love ''' import gevent import gevent.monkey gevent.monkey.patch_all() from pymqant.module.app import mqant from server.chat_module import ChatModule from server.test_module import TestModule if __name__ == "__main__": app=mqant() app.Run(True,ChatModule(...
StarcoderdataPython
9625854
<reponame>kubamahnert/panoramic-cli<filename>src/panoramic/cli/__init__.py from panoramic.cli.cli import cli from panoramic.cli.utils.logging import configure_logging configure_logging() __all__ = ['cli']
StarcoderdataPython
9776817
<gh_stars>0 # -*- coding: utf-8 -*- """Missing batteries for itertools. For more batteries for itertools, see also the ``unpythonic.fold`` module. ``flatten`` based on Danny Yoo's version: http://rightfootin.blogspot.fi/2006/09/more-on-python-flatten.html ``uniqify``, ``uniq``, ``take``, ``drop``, ``partition`` j...
StarcoderdataPython
5173052
<filename>backend/app/exceptions.py # -*- coding: future_fstrings -*- from flask import jsonify def template(message='An error has occurred', code=500): return {'message': message, 'status_code': code} USER_NOT_FOUND = template('User not found', code=404) USER_ALREADY_REGISTERED = template('User already registe...
StarcoderdataPython
3373888
<filename>tests/test_csv.py import os from kgx import PandasTransformer cwd = os.path.abspath(os.path.dirname(__file__)) resource_dir = os.path.join(cwd, 'resources') target_dir = os.path.join(cwd, 'target') def test_load(): """ Test for loading data into PandasTransformer """ t = PandasTransformer()...
StarcoderdataPython
6681556
<filename>ch04/practice_two_layer_net.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Feb 24 20:27:37 2019 @author: Emma """ import sys,os sys.path.append(os.pardir) from common.functions import * from common.gradient import numerical_gradient import numpy as np class twoLayerNet: def __init...
StarcoderdataPython
3452541
# -*- coding: utf-8 -*- # # removeolduploads.py -- remove old and uploaded packages from Debexpo # # This file is part of debexpo - https://alioth.debian.org/projects/debexpo/ # # Copyright © 2011 <NAME> <<EMAIL>> # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this softw...
StarcoderdataPython
162602
from opera.parser.tosca.v_1_3.node_filter_definition import ( NodeFilterDefinition, ) class TestParse: def test_full(self, yaml_ast): NodeFilterDefinition.parse(yaml_ast( """ properties: - num_cpus: { in_range: [ 3, 6 ] } capabilities: [] "...
StarcoderdataPython
9650822
<gh_stars>1-10 #!/usr/bin/env python # -*- coding: utf-8 -*- # # Generated from FHIR 3.6.0-bd605d07 on 2018-12-20. # 2018, SMART Health IT. import os import io import unittest import json from . import valueset from .fhirdate import FHIRDate class ValueSetTests(unittest.TestCase): def instantiate_from(self, f...
StarcoderdataPython
9752013
from __future__ import absolute_import from phovea_processing_queue.task_definition import task, getLogger _log = getLogger(__name__) @task def add(x, y): return float(x) + float(y) @task def mul(x, y): return float(x) * float(y) @task def xsum(numbers): return sum(numbers)
StarcoderdataPython
257991
<reponame>binyoucai/ProxyPool #!/usr/bin/python3 # -*- coding: utf-8 -*- """ @content : 全局变量配置模块 db.py, getter.py, tester.py, scheduler.py @Author : 北冥神君 @File : setting.py @Software: PyCharm """ # ———————————————————————————————————————————华丽分割线—————————————————————————————————————————————————————————————————— ...
StarcoderdataPython
11305787
<reponame>owencole12/LdsHack from advent import * game = Game() entry = game.new_location( "Start of Game", """ Something will eventually go here """ )
StarcoderdataPython
34517
<reponame>s-ai-kia/nasa_stf # -*- coding: utf-8 -*- """mopitt_data_analysis.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1bb_9kuO0Suo5761xgJioS84TrEdR5ojj """ import pandas as pd df = pd.read_csv('MOP02J-20200101-L2V18.0.3.csv') df.head() df ...
StarcoderdataPython
4982243
<reponame>ImanolGo/IngoLightAndBuilding from openframeworks import * from protopixel import Content from random import randint import math print "Blackout" #a global variable size = 170 currentTransparency = 0 targetTransparency = 0 content = Content("Blackout") content.FBO_SIZE = (170,170) #optional: define size o...
StarcoderdataPython
79344
import csv import os import random import numpy as np import sys from sklearn import svm from keras.models import Sequential, model_from_yaml from keras.layers import Dropout, Dense from keras.callbacks import EarlyStopping def open_csv(file_path): # Input read as f_wh, f_wmt, f_posh, f_posmt, f_len, y asser...
StarcoderdataPython
140769
#!/usr/bin/python #coding: utf-8 class Subject(object): def __init__(self): self._observers = [] def attach(self, observer): if not observer in self._observers: self._observers.append(observer) def detach(self, observer): try: self._observers.remove(observer) except ValueError: pass def notify(sel...
StarcoderdataPython
3220132
""" import traceback HTTP API for airfilter prometheus collector. """ import time from prometheus_client import CONTENT_TYPE_LATEST, Summary, Counter, generate_latest from werkzeug.routing import Map, Rule from werkzeug.serving import run_simple from werkzeug.wrappers import Request, Response from werkzeug.exceptions ...
StarcoderdataPython
3217104
<reponame>EgorBolt/studying<filename>tooi/lab7/lab7a.py import time print('Введите число: ') i = int(input()) while i > 0: time.sleep(i) print('Введите число: ') i = int(input())
StarcoderdataPython
385839
#!/usr/bin/python3 # # This contains the main pyFvwm class which handles creation # and management of the pyFvwm configuration database. In # addition it handles formatting fvwm2rc files and building # themes. # # Ensure that the home directory below is set to the location # of pyFvwm's data files. # import os impor...
StarcoderdataPython
6592601
from .saveStrategy import SaveStrategy import sqlite3 class DatabaseSave(SaveStrategy): def __init__(self): self.connection = sqlite3.connect("saves/saveDatabase.db") self.cursor = self.connection.cursor() self.createTable() def load(self): pass def save(self, player): ...
StarcoderdataPython
4835174
# number = None # while (not number) or not (number > 0): # try_number = input("Please enter a number > 0: ") # try: # number = float(try_number) # print("Got it!") # except ValueError as err: # print("Error: ", err) # try: # file_handle = open("my_file") # except IOError as err...
StarcoderdataPython
1750046
<gh_stars>0 import pytest from insertion_sort import insertion_sort # @pytest.fixture() # def unsorted_lst(): # lst = [5, 2, 8, 1, 15] def test_randomly_unsorted_list(): """An unsorted list returns sorted""" lst = [5, 2, 8, 1, 15] expected = [1, 2, 5, 8, 15] actual = insertion_sort(lst) ass...
StarcoderdataPython
187349
<reponame>happyandy2017/LeetCode<gh_stars>0 class Solution: def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if not strs: return '' zip_strs = zip(*strs) for i, letter_group in enumerate(zip_strs): ...
StarcoderdataPython
6428565
<filename>api/apis/ArpTable.py import os import pymongo from bson.objectid import ObjectId from pymongo.collection import ReturnDocument from flask_restplus import Namespace, Resource, fields myclient = pymongo.MongoClient(os.getenv("DB_CONN")) db = myclient[os.getenv("DB_NAME")] arp_table_col = db["arp_tables"] api =...
StarcoderdataPython
8065735
<filename>HRD_201706.py #coding=utf-8 from lib.device import Camera from lib.process_new import getHR import cv2 import numpy as np import datetime import serial import socket import sys class getHeartRate(object): def __init__(self): self.cameras = [] self.selected_cam = 0 for i in rang...
StarcoderdataPython
1797596
from talon import speech_system, Context from talon.engines.w2l import W2lEngine from talon.engines.webspeech import WebSpeechEngine # engine = W2lEngine(model="en_US", debug=True) # engine = W2lEngine(model="en_US-sconv-beta5", debug=True) engine = W2lEngine(model="en_US-sconv-large-b2", debug=True) # engine = W2lEng...
StarcoderdataPython
8181917
# Copyright 2018 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can # be found in the LICENSE file. # This file is automatically generated by mkgrokdump and should not # be modified manually. # List of known V8 instance types. INSTANCE_TYPES = { 0: "IN...
StarcoderdataPython
8045793
<filename>stage1/DataSet.py # #author: <NAME> #Project Description: This repository contains source code for semantically segmenting WSIs; however, it could be easily # adapted for other domains such as natural image segmentation # File Description: This file is used to create data tuples #===========...
StarcoderdataPython
351828
# Generated by Django 2.2.7 on 2019-11-27 15:22 # Modified by hand to ensure that initial dates of a salary grade change are the start date of the financial year from datetime import date from django.db import migrations, models import django.utils.timezone def set_initial_salarygradechange_date(apps, schema_editor):...
StarcoderdataPython
3515408
<reponame>jacob975/deep_learning<filename>std_code.py #!/usr/bin/python3 ''' Abstract: This is a program for matching the sources in ALLWISE catalogue and c2d+SWIRE catalogue. Usage: match_sp_wise.py [spitzer coord] [wise coord] Output: 1. coordinates of matched sources 2. coordinates of un-matched sou...
StarcoderdataPython
1925547
import eventlet eventlet.monkey_patch() import requests from .issue import Issue def post(url, headers, payload): with eventlet.Timeout(20, False): r = requests.post(url, headers=headers, json=payload) if r.status_code != 200: return None # debug print(r.json()) ...
StarcoderdataPython
5065075
<reponame>dgarlitt/release_notes_generator import sys import mock from nose.tools import eq_, ok_, assert_raises import nose.tools # from main import load_props, sanitize_path, parse_version_number # class TestMain: # @mock.patch('main.json') # @mock.patch('__builtin__.open', spec=open, read_data='some raw json') ...
StarcoderdataPython
1986944
<filename>mAP_COCO/get_gt_json.py # -*- coding: utf-8 -*- # @Time : 2021/9/20 下午3:30 # @Author : DaiPuWei # @Email : <EMAIL> # @File : get_gt_json.py # @Software: PyCharm """ 这是生成测试数据集每张图像中真实目标及其定位信息json文件的脚本 """ import os import cv2 import sys import json import argparse import numpy as np import xml.et...
StarcoderdataPython
3365821
"""Neural style transfer (https://arxiv.org/abs/1508.06576) in PyTorch.""" from pathlib import Path srgb_profile = (Path(__file__).resolve().parent / 'sRGB_Profile.icc').read_bytes() del Path from .style_transfer import STIterate, StyleTransfer from .web_interface import WebInterface from .cli import *
StarcoderdataPython
3502699
from collections import Counter from util import read_puzzle_input def num_questions_answered_by_group(group_input): questions_only = group_input.replace(" ", "").replace("\n", "") question_counts = Counter(questions_only) return len(question_counts) def sum_questions_answered_by_group(puzzle_input): ...
StarcoderdataPython
3245069
import re,os import xml.etree.ElementTree as ET from .Webby import Webby from .Common import * class Harvester(object): def __init__(self,verbosity): self.webbies = set() self.verbosity = verbosity def harvest_nessus_dir(self,nessus_dir): for dirpath,directories,files in os.walk(nessus...
StarcoderdataPython
4849776
<filename>EventDec/event_dec/test/test_model.py import unittest from unittest.mock import patch import numpy as np import event_dec from event_dec.model import Model class ModelTests(unittest.TestCase): @patch.object(event_dec.main.process_input, "input", create=True) def test_predict(self, input): "...
StarcoderdataPython
5036856
<reponame>AIJIJI/devtools #!/bin/python3 from setuptools import setup from setuptools import find_packages NAME = "devtools" PACKAGES = [NAME] + ["%s.%s" % (NAME, i) for i in find_packages(NAME)] LONG_DESC = '''Some useful helper-funcs for devpers. Sub-package is the extension of corresponding package with the same na...
StarcoderdataPython
372672
import argh import argparse from lithium.manage.commands.services import new from lithium.manage.commands.clients import generate from lithium.manage.commands.users import import_data parser = argh.ArghParser() parser.add_commands([new], namespace='service', title='Services related commands') parser.add_commands([gene...
StarcoderdataPython
6425374
<reponame>fomartin/GeneticAlgorithm<gh_stars>0 from Habitat import * from Organism import * class PowerLawHabitat(Habitat): def _calculate_for_organism(self, organism, set_of_parameters): if len(organism.genes()) - 1 != len(set_of_parameters): print("[ERROR] Power Law formula requires one mor...
StarcoderdataPython
3287239
<gh_stars>1-10 #!/usr/bin/env python3 # -*- coding: utf-8 -*- from subprocess import check_output from contextlib import contextmanager import re @contextmanager def rewrite(fname): """Work with lines in-place (read, yield, write).""" with open(fname, 'r') as f: lines = [line for line in f] yield lines ...
StarcoderdataPython
337482
"""Methods used for generating the symmetry group. All of these methods were adapted to python from their original fortran implementations which can be found at: https://github.com/msg-byu/symlib """ from copy import deepcopy import numpy import math def get_concs_for_size(size,nspecies,res_concs,nB,concs): """Ge...
StarcoderdataPython
6630500
<filename>examples/hello.py from concurrence import dispatch def hello(): print "Hello World!" if __name__ == '__main__': dispatch(hello)
StarcoderdataPython
4925120
<filename>ttt_tests/optimal_ai_move_test.py<gh_stars>0 import tictactoe as ttt import numpy as np board = np.array([ ['e', 'r', 't'], ['d', 'f', 'g'], ['c', 'v', 'b'] ]) available = ttt.find_available_moves(board) metric_dict = ttt.optimal_ai_move(board=board, x_or_o='x', available=available) print(metri...
StarcoderdataPython