id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
4818183
<filename>common/utils/mathematical_conversation_utils.py def convert_price_to_us(price: str) -> float: us_number_convention = {",": ".", ".": ","} trans_table = price.maketrans(us_number_convention) price = price.translate(trans_table).replace(",", "") return float(price)
StarcoderdataPython
87880
#!/usr/bin/env python3 # prerequisite: xsel import subprocess import time class Selection: def __init__(self, intvl): self.content = "" self.intvl = intvl def get_str(self): while True: cur = subprocess.check_output(["xsel"]) if cur == self.content: ...
StarcoderdataPython
3321166
"""Test the json file with keys and values describing the data file.""" import os.path as op import json import sp_experiment init_dir = op.dirname(sp_experiment.__file__) fname = 'task-sp_events.json' fpath = op.join(init_dir, fname) def test_json(): """Test json file.""" with open(fpath, 'r') as f: ...
StarcoderdataPython
4818699
# Generated by Django 3.0.7 on 2020-06-30 17:30 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0007_auto_20200630_1728'), ] operations = [ migrations.AlterField( model_name='post', name='...
StarcoderdataPython
146682
# Copyright 2013-2017 Ent. Services Development Corporation LP # # Redistribution and use of this software in source and binary forms, # with or without modification, are permitted provided that the following # conditions are met: # # Redistributions of source code must retain the above copyright notice, # this list of...
StarcoderdataPython
1698040
""" Zipf's law This program fits data ranked along certain dimension (e.g. city population and word appearance) to Zipfian distribution. The probability mass function for zipf is: pmf(x, a) = 1/(zeta(a) * x**a), for x >= 1 and a > 1. https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.zipf.html It'...
StarcoderdataPython
19918
import const def corpora2idx(sents, ind2idx): return [[ind2idx[w] if w in ind2idx else const.UNK for w in s] for s in sents]
StarcoderdataPython
3343293
<gh_stars>0 import logging import requests from bs4 import BeautifulSoup from collections import Counter import azure.functions as func def main(req: func.HttpRequest) -> func.HttpResponse: logging.info('Python Website Parser function processed a request.') url = req.params.get('url') logging.info(f"R...
StarcoderdataPython
3246934
""" CCT 建模优化代码 束线 作者:赵润晓 日期:2021年5月1日 """ import multiprocessing # since v0.1.1 多线程计算 import time # since v0.1.1 统计计算时长 from typing import Callable, Dict, Generic, Iterable, List, NoReturn, Optional, Tuple, TypeVar, Union import matplotlib.pyplot as plt import math import random # since v0.1.1 随机数 import sys impor...
StarcoderdataPython
3200072
<filename>TranscriptCatcher/WallmineCatcher.py<gh_stars>0 from selenium import webdriver from selenium.webdriver.chrome.webdriver import WebDriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.s...
StarcoderdataPython
167168
from citrination_client.data import DatasetFile def test_can_crud_path(): """ Tests that full get/set/delete functionality is available for the path property """ path = "path" d = DatasetFile(path) assert d.path is path d.path = path assert d.path is path del(d.path) assert...
StarcoderdataPython
1659980
<filename>number_of_ships_rectangle.py """ https://leetcode.com/problems/number-of-ships-in-a-rectangle/ """ from __future__ import annotations class Sea(object): def hasShips(self, topRight: 'Point', bottomLeft: 'Point') -> bool: pass class Point(object): def __init__(self, x: int, y: int): self.x = x ...
StarcoderdataPython
149578
import pygame from core import animation from utils import vector from utils.settings import * class Actor(pygame.sprite.Sprite): """The Generic Actor Class""" def __init__(self): pygame.sprite.Sprite.__init__(self) self.actor_type = ACTOR_NONE self.can_collide = False self....
StarcoderdataPython
3356331
# -*- coding: utf-8 -*- """ Manifest Defaults """ from django.conf import settings from django.urls import reverse_lazy MANIFEST_ACTIVATED_LABEL = getattr( settings, "MANIFEST_ACTIVATED_LABEL", "ACCOUNT_ACTIVATED" ) MANIFEST_ACTIVATION_DAYS = getattr(settings, "MANIFEST_ACTIVATION_DAYS", 7) MANIFEST_ACTIVATION_...
StarcoderdataPython
1798
<reponame>mashaka/TravelHelper from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.contrib.auth.forms import AdminPasswordChangeForm, PasswordChangeForm, UserCreationForm from django.contrib.auth import update_session_auth_hash, login, authenticate from django.cont...
StarcoderdataPython
139833
<reponame>MissCatLady/AlarmEZ """passlib.ifc - abstract interfaces used by Passlib""" #============================================================================= # imports #============================================================================= # core import logging; log = logging.getLogger(__name__) import sy...
StarcoderdataPython
46974
<filename>Implementations/New folder/E2.py command = input() command = command.strip() tokens = [] numbers = ['0','1','2','3','4','5','6','7','9'] if (command[:4]=="cout" and command[-1]==';'): index = 4 while(True): if(command[index]=='<' and command[index+1]=='<'): index+=2 s="...
StarcoderdataPython
128596
<reponame>digolds/dp<gh_stars>0 import pandas as pd def _parse(args): return [] def _drop_empty_row(df): return df.dropna(how='all') name = 'drop-empty-row' def operator(df, args): return _drop_empty_row(df, *_parse(args)) if __name__ == "__main__": data = [['tom', 10], ['nick', 15], [None, None]]...
StarcoderdataPython
3295936
from brainstorming.email_verification import send_email_verification from brainstorming.models import BrainstormingWatcher from django.conf import settings from django.core.mail import send_mail, send_mass_mail from django.core.urlresolvers import reverse from django.template.defaultfilters import truncatechars from dj...
StarcoderdataPython
3239656
#!/usr/bin/env python3.4 # encoding: utf-8 import glob import os if __name__ == '__main__': print(''' Formatting example scripts into rst files for the docs ''') # input() for example_script in glob.glob('../example_scripts/*.py'): if os.path.exists(example_script) is False: co...
StarcoderdataPython
3222582
#!/usr/bin/python # -*- coding: utf-8 -*- #import stdin #import argparse import re """ Script para determinar las posibles tonalidades a partir de las notas insertadas Las notas se puede insertar del siguiente modo: C Cmaj7 Cmin7 Csus C# Por ahora, no se soporta poner "b". Cualquier bemol debe meterse como "#" """...
StarcoderdataPython
3304372
# -*- coding: utf-8 -*- # # Copyright 2017 dpa-infocom GmbH # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
StarcoderdataPython
197401
from imdbTask9 import* def directorName(movies): directorList=[] for index in movies: directorList.extend(index["director"]) return directorList directorList=directorName(movieDetailsWithCashing) def duplicateDirector(movies): duplicateDirector=[] for index1 in range(len(directorList)): ...
StarcoderdataPython
4801100
<filename>eventmanagement/events/views.py<gh_stars>1-10 from django.shortcuts import render from django.http import HttpResponse, Http404 from .models import Event, Organization, Organizer, Participant, Speaker # Create your views here. def index(request): return render(request, "events/index.html", { "eve...
StarcoderdataPython
146160
<filename>flexx/app/pair.py """ Base class for objects that live in both Python and JS. This basically implements the syncing of signals. """ import sys import json import weakref import hashlib from .. import react from ..react.hassignals import HasSignalsMeta, with_metaclass from ..react.pyscript import create_js_s...
StarcoderdataPython
3286125
from tir import Webapp from datetime import datetime DataSystem = datetime.today().strftime('%d/%m/%Y') import unittest class MATA410(unittest.TestCase): @classmethod def setUpClass(inst): inst.oHelper = Webapp() inst.oHelper.Setup("SIGAFAT",DataSystem,"99","01","05") inst.oHelper.Prog...
StarcoderdataPython
1644673
<reponame>antonlydell/Pandemy r"""Tests for the __init__ module of Pandemy.""" # ================================================= # Imports # ================================================= # Standard Library from datetime import date import re # Local import pandemy # ===========================================...
StarcoderdataPython
1790817
""" (c) 2020 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, an...
StarcoderdataPython
176448
<reponame>WeDias/RespCEV<filename>Exercicios-Mundo1/ex028.py import random user = int(input('Digite um Número de 0 a 5: ')) pc = random.randint(0, 5) if user == pc: print('O Computador esolheu o Número {}\nPARABENS! VOCÊ ACERTOU !'.format(pc)) else: print('O Computador escolheu o Número {}\nVOCÊ PERDEU !'...
StarcoderdataPython
74715
<filename>aiodogstatsd/contrib/aiohttp.py from http import HTTPStatus from typing import AsyncIterator, Callable, Optional, cast from aiohttp import web from aiohttp.web_app import _Middleware from aiohttp.web_routedef import _SimpleHandler from aiohttp.web_urldispatcher import DynamicResource, MatchInfoError from ai...
StarcoderdataPython
4807404
<gh_stars>1-10 from django.contrib.auth import get_user_model from django.test import TestCase from django.urls import reverse, reverse_lazy from ..models import Post from taggit.models import Tag class SetQueryTestCase(TestCase): def setUp(self): self.test_user = get_user_model().objects.create_user( ...
StarcoderdataPython
75592
<gh_stars>0 # Read the documentation here: # https://nose.readthedocs.org/en/latest/testing.html # Modify the import path to find our package import sys import os.path sys.path = [os.path.abspath("../scanr_publicationextractor")] + sys.path sys.path = [os.path.abspath("..")] + sys.path # Import our package from sca...
StarcoderdataPython
47480
Perfect Number Given a positive integer N as the input, the program must print yes if N is a perfect number. Else no must be printed. Input Format: The first line contains N. Output Format: The first line contains yes or no Boundary Conditions: 1 <= N <= 999999 Example Input/Output 1: Input: 6 Output: yes Example Inpu...
StarcoderdataPython
3303022
<reponame>maximskorik/RIAssigner from typing import List, Iterable from RIAssigner.data.Data import Data from .ComputationMethod import ComputationMethod class Kovats(ComputationMethod): """ Class to compute the Kovats retention index. """ def compute(self, query: Data, reference: Data) -> List[Data....
StarcoderdataPython
51204
<gh_stars>0 import discord from discord.ext import commands from evs import default from evs import permissions, default, http, dataIO import requests import os class Autoupdate_ko(commands.Cog): def __init__(self, bot): self.bot = bot self.config = default.get("config.json") # Commands @...
StarcoderdataPython
99126
import itertools # combine iterators it = itertools.chain([1, 2, 3], [4, 5, 6]) # repeat a value it = itertools.repeat("hello", 3) print(list(it)) # repeat an iterator's items it = itertools.cycle([1, 2]) result = [next(it) for _ in range(10)] print(result) # split an iterator it1, it2, it3 = itertools.tee(["fir...
StarcoderdataPython
35629
<gh_stars>1-10 from abc import ABC, abstractmethod class Command(ABC): @abstractmethod def execute(self): pass @abstractmethod def un_execute(self): pass class AddCommand(Command): def __init__(self, values, new_value): self.values = values self.new_value = new_v...
StarcoderdataPython
1705561
#!/usr/bin/env python import rospy import rosnode import roslaunch from geometry_msgs.msg import Twist from std_msgs.msg import String, Float64, UInt8 from std_srvs.srv import Empty from std_srvs.srv import EmptyResponse # @param timeout_ms Timeout for publishing in the topic (Warning: Precision of 10 miliseconds) c...
StarcoderdataPython
160874
from car import Car class UberBlack(Car): typeCarAccepted = [] seatsMaterials = [] def __init__(self, lincense, driver, typeCarAccepted, seatsMaterials): super().__init__(lincense, driver) self.typeCarAccepted = typeCarAccepted self.seatsMaterials = seatsMaterials
StarcoderdataPython
1732481
import numpy as np from neuron import SimpleNeuron from helpers.diagnostic_helpers import time_measure class NeuralNetwork(object): def __init__(self, layer_size=[2, 2, 1], activation_function=None, activation_fun_prime=None): """ Default activation function: np.tanh(x) Default learning fun...
StarcoderdataPython
3320712
<filename>tests/test_formal_agg.py from lake.top.lake_top import * import fault import pytest import tempfile @pytest.mark.skip def test_formal_agg(): lt_dut, n, u, t = get_formal_module("agg") magma_dut = kts.util.to_magma(lt_dut, flatten_array=True, ...
StarcoderdataPython
4831641
from django import template from django.template.loader import render_to_string from django.utils.html import format_html from django.utils.safestring import mark_safe from corehq.apps.domain.models import Domain import corehq.apps.style.utils as style_utils from corehq.apps.hqwebapp.models import MaintenanceAlert fro...
StarcoderdataPython
3240868
import re import ssl from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from smtplib import SMTP_SSL, SMTPAuthenticationError class Mail: def __init__(self, sender, receivers, smtp_server, password, port): self.sender = sender self.receivers = receivers se...
StarcoderdataPython
1612015
import pandas as pd from get_json_data import get_json_data def get_active_users(path_to_csv=None, token=None): """ Returns a dict of active users from The Spatial Community """ url = "https://slack.com/api/users.list" params = dict( token=token ) membe...
StarcoderdataPython
140479
"""An AccountScanner scans a set of accounts using an AccountScanPlan to define scan parameters""" from collections import defaultdict from concurrent.futures import Future, ThreadPoolExecutor, as_completed from dataclasses import dataclass import random import time import traceback from typing import Any, DefaultDict,...
StarcoderdataPython
166030
import SimpleHTTPServer import SocketServer import BaseHTTPServer import ssl import os import sys if len(sys.argv) > 1 and sys.argv[1] == 'https': exec_dir = os.path.abspath(os.path.dirname(os.path.abspath(__file__))) https = BaseHTTPServer.HTTPServer(('', 4443), SimpleHTTPServer.SimpleHTTPRequestHandler) ...
StarcoderdataPython
1663256
# coding: utf-8 import webbrowser from operator import itemgetter from .config import feedback, gconfig from .symbol_format import completion_to_suggest from .util import catch, Pretty class ProtocolHandler(object): """Mixin for common behavior of handling ENSIME protocol responses. Actual handler implemen...
StarcoderdataPython
1783129
<reponame>ckamtsikis/cmssw<gh_stars>100-1000 import FWCore.ParameterSet.Config as cms # # simple analyzer to make histos within a framework job off the super clusters in the event # Author: <NAME>, University of Rome & INFN # egammaSimpleAnalyzer = cms.EDAnalyzer("EgammaSimpleAnalyzer", xMaxHist = cms.double(60....
StarcoderdataPython
97045
""" Reversed from binary_search. Given a item, if the item in the list, return its index. If not in the list, return the index of the first item that is larger than the the given item If all items in the list are less then the given item, return -1 """ def binary_search_fuzzy(a...
StarcoderdataPython
1715185
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.select import Select from selenium.webdriver.chrome.options import Options import pandas as pd import os import datetime import time PATH = "chromedriver.exe" driver = webdriver.Chrome(PATH) df = pd.read_c...
StarcoderdataPython
1603820
""" Class for parsing and converting the discord flavor of Markdown. Part of the Gabby Gums Discord Logger. """ import logging from typing import TYPE_CHECKING, Optional, Dict, List, Union, Tuple, NamedTuple, Match import regex as re from jinja2 import escape log = logging.getLogger(__name__) class DiscordMarkdo...
StarcoderdataPython
3376056
if sm.getChr().getJob() == 2300: sm.jobAdvance(2310) sm.addSP(2) sm.completeQuest(parentID) sm.dispose()
StarcoderdataPython
100535
import numpy as np from sklearn import model_selection import typing as t from copy import copy from ..mltypes import RandomState from ..data.dataset import Dataset class DataSplit: def get_splits(self, dataset: Dataset) -> t.Generator[t.Tuple[Dataset, Dataset], None, None]: raise NotImplementedError c...
StarcoderdataPython
161758
<gh_stars>1-10 """ This file is create and managed by <NAME> ---------------------------------------------- It can be use only for education purpose """ # List Modification mix_list = [1, 'Programmer', 5.0, True] print(mix_list) # Mutable : Because re-assign value mix_list[0] = 2 print(mix_list) # Adding ...
StarcoderdataPython
180698
<filename>challenges/Azurad/poller/for-release/machine.py #!/usr/bin/env python from generator.actions import Actions import numpy as np import random import struct MAX_ITEMS = 1000 INSERT = 0x2064 RETR = 0xA097 ADD = 0x2C56 SUB = 0x973D MUL = 0xE925 SUM = 0x71B8 PROD = 0x1510 FLAG = 0x4141 RAND = 0xC4C5 QUIT = 0xA80...
StarcoderdataPython
3250800
from typing import Any, Union from bot.event import Event, EventType from pydantic.utils import deep_update def event( event_data: Union[str, dict[str, Any]], event_type: EventType = EventType.NEW_MESSAGE, ) -> Event: default = { "chat": {"chatId": "test"}, "from": "<EMAIL>", "msg...
StarcoderdataPython
1685919
<filename>improver_tests/nbhood/recursive_filter/test_RecursiveFilter.py # -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # (C) British Crown Copyright 2017-2021 Met Office. # All rights reserved. # # Redistribution and use in source and binary forms, with or witho...
StarcoderdataPython
3210322
# -*- coding: utf-8 -*- from mealy.constants import ErrorAnalyzerConstants from sklearn.metrics import accuracy_score, balanced_accuracy_score import numpy as np def compute_confidence_decision(primary_model_true_accuracy, primary_model_predicted_accuracy): difference_true_pred_accuracy = np.abs(primary_model_tru...
StarcoderdataPython
1659833
<filename>Login-Pass.py<gh_stars>0 def mail(): #function for Login Portal print("LOGIN PORTAL"); id1=raw_input("Email ID : "); pass1=raw_input("Password : "); login(id1,pass1); def login(id1,pass1): #ID PASSWORD checking function import time; f=open(id1+".txt","r"); c=f.readlines() if(id1=='e...
StarcoderdataPython
159297
<filename>feature_engine/encoding/decision_tree.py # Authors: <NAME> <<EMAIL>> # License: BSD 3 clause from sklearn.pipeline import Pipeline from feature_engine.encoding.base_encoder import BaseCategoricalTransformer from feature_engine.encoding.ordinal import OrdinalEncoder from feature_engine.discretisation import ...
StarcoderdataPython
79033
<gh_stars>1-10 import cv2 import math import os import numpy as np from scipy import ndimage import least_squares class SpectrumBuilder: def __init__(self, img, path, windows): self.image = img self.windows = windows self.max_window_size = windows[-1] self.height = img.shape[0] ...
StarcoderdataPython
3385235
""" https://data.cms.gov/provider-data/topics/doctors-clinicians These are the official datasets used on Medicare.gov provided by the Centers for Medicare & Medicaid Services. These datasets give you useful information about doctors, clinicians, and groups listed on Medicare Care Compare. General information about do...
StarcoderdataPython
174964
<filename>teams/api/views/teams_views.py from rest_framework import generics from rest_framework.permissions import IsAuthenticated from teams.api.serializers.teams_serializers import TeamSerializer from teams.models import Teams class TeamAPIList(generics.ListAPIView): permission_classes = [IsAuthenticate...
StarcoderdataPython
169490
# Class to store Trie(Patterns) # It handles all cases particularly the case where a pattern Pi is a subtext of a pattern Pj for i != j class Trie_Patterns: def __init__(self, patterns, start, end): self.build_trie(patterns, start, end) # The trie will be a dictionary of dictionaries where: # ... T...
StarcoderdataPython
1600458
<gh_stars>0 from datetime import date # ----------------------------------------------------------------------------- # 1.1. Raw strings with r" " print(r"C:\some\name") # good print("C:\some\name") # bad # ----------------------------------------------------------------------------- # 1.2. Formatting with repeate...
StarcoderdataPython
1712353
from .sk import ServerSocket from .packet import Packet import random class Client : def __createSocketId(self, length=7, step=3) : random_hash = 0 for _ in range(step) : random_hash += random.random() return str(random_hash).split(".")[1][:length] def __init__(self, cli...
StarcoderdataPython
8257
import json from btse_futures.constants import OrderType, Side, TimeInForce class Order: """ Class to represent a BTSE Order ... Attributes ---------- size : int order quantity or size. e.g. 1 price : float price. e.g. 7000.0 side: str order side. B...
StarcoderdataPython
22540
<filename>convert.py<gh_stars>0 from gensim.scripts.glove2word2vec import glove2word2vec (count, dimensions) = glove2word2vec("dataset/glove.42B.300d.txt", "dataset/cropus/42B_w2v.txt")
StarcoderdataPython
161214
<reponame>deniskolosov/django-doctor-appointment from django.shortcuts import render from django.views.generic import CreateView from django.contrib import messages from datetimewidget.widgets import DateTimeWidget from .models import Appointment class AppointmentCreateMixin(object): fields = ('patient_name', ...
StarcoderdataPython
61426
<filename>paymeuz/migrations/0002_auto_20200826_1127.py # Generated by Django 3.1 on 2020-08-26 06:27 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('paymeuz', '0001_initial'), ] operations = [ migrations.RenameField( model_...
StarcoderdataPython
37397
<filename>FaceTemplateMatching.py<gh_stars>1-10 import cv2 from threading import Thread import datetime import time import sys class FPSCounter: def __init__(self): self._start = None self._end = None self._noFrames = 0 def start(self): self._start = datetime.datetime.now() ...
StarcoderdataPython
59260
# Copyright 2021 Google LLC # # 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 agreed to in writing, ...
StarcoderdataPython
42579
# -*- coding: utf-8 -*- """ Created on Wed Sep 25 15:06:45 2019 @author: garci """ import matplotlib.pyplot as plt import numpy as np import csv import xlwings as xw import pandas import os '''MAKE X-Y PLOTS WITH 2-COLUMN FILES <NAME>, 2019 ''' '''lastRow credit: answered Sep 14 '16 at 11:39 - Stefan https://st...
StarcoderdataPython
1626327
<reponame>cmancone/clearskies-aws<gh_stars>0 #!/usr/bin/env python3 import unittest import sys, os sys.path.append(os.path.dirname(os.path.realpath(__file__))) glob = '?*test.py' if len(sys.argv) > 1: path = sys.argv[1] # generally expecting a directory. If it is a file then find the parent directory if ...
StarcoderdataPython
109953
import pytest # type: ignore from hopeit.app.config import AppConfig, AppDescriptor, \ EventDescriptor, EventType, EventPlugMode from hopeit.server.config import ServerConfig, LoggingConfig @pytest.fixture def mock_plugin_config(): return AppConfig( app=AppDescriptor(name='mock_plugin', version='tes...
StarcoderdataPython
108647
<filename>test/1d_text.py #!/usr/bin/env python # the earlier script for ploting the result in ASCII format # for ploting the HDF5 file, see the scripts in th 'pfm' directory import sys import numpy as np import matplotlib.pyplot as plt def get_color(): for item in ['r','g','b','c','m','y','k', 'r','g','b',...
StarcoderdataPython
88887
<reponame>gneumann333/jumpscaleX_core from Jumpscale import j class UserSessionBase(j.baseclasses.object): pass class UserSessionAdmin(UserSessionBase): def _init(self): self.admin = True self.threebot_id = None self.threebot_name = None self.threebot_circles = [] sel...
StarcoderdataPython
3205231
import main import state import utils import os from flask import Flask, render_template, request, redirect, cli from werkzeug.utils import secure_filename from nfc_reader import start_nfc_thread from utils import printt DEVENV = False try: # pylint: disable=import-error import RPi.GPIO as GPIO except: DEV...
StarcoderdataPython
1777058
<filename>scripts/remove_reads.py #!/usr/bin/env python from Bio.SeqIO.QualityIO import FastqGeneralIterator import sys if len(sys.argv) != 3: sys.exit('\nusage: python remove_reads.py fastqFile idFile \n\ \nThis is a prgram to remove records from id list output is a fastq file \ \n ...
StarcoderdataPython
4839601
"""Resources that represent both individual and collections of design workflow executions.""" import sys from typing import Optional, Union, Iterator from uuid import UUID from citrine._rest.collection import Collection from citrine._utils.functions import shadow_classes_in_module from citrine._session import Session ...
StarcoderdataPython
4827083
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import os import math import torch import unittest import gpytorch import numpy as np from torch.autograd import Variable from gpytorch.utils import approx_equal from gpy...
StarcoderdataPython
3239311
<reponame>cammelworks/CammelBot # coding: utf-8 from slackbot.bot import respond_to from slackbot.bot import listen_to from slackbot.bot import default_reply import re from datetime import datetime import locale locale.setlocale(locale.LC_CTYPE, '') @respond_to('time') def now(message): strftime = datetime.now()...
StarcoderdataPython
1627674
<gh_stars>1-10 from distutils.version import StrictVersion as SV import unittest import minecraft class VersionTest(unittest.TestCase): def test_module_version_is_a_valid_pep_386_strict_version(self): SV(minecraft.__version__) def test_minecraft_version_is_a_valid_pep_386_strict_version(self): ...
StarcoderdataPython
3201221
<gh_stars>1-10 # import webtest # import logging # import unittest # from google.appengine.ext import testbed # from protorpc.remote import protojson # import endpoints # # from conference import ConferenceApi # from models import ConferenceForm # from models import ConferenceForms # from models import ConferenceQueryF...
StarcoderdataPython
152064
import cv2 import numpy as np import matplotlib.pyplot as plt from glob import glob # K-means step1 def k_means_step1(img, Class=5): # get shape H, W, C = img.shape # initiate random seed np.random.seed(0) # reshape img = np.reshape(img, (H * W, -1)) # select one index randomly i = np.random.choice(np.ara...
StarcoderdataPython
1711320
#!/usr/local/bin/python3 """This program asks a user to guess a number up to 5 attempts.""" numguesses = 0 secret = 12 guess = 0 while numguesses < 5 and guess != secret: guess = (int(input("Guess a number:"))) if guess < secret: print("Guess higher") elif guess > secret: print("Guess lowe...
StarcoderdataPython
118651
<reponame>callat-qcd/lattedb """Admin view for correlation functions """ from espressodb.base.admin import register_admins register_admins("lattedb.correlator")
StarcoderdataPython
4817982
<reponame>lycantropos/reprit from typing import (Any as _Any, Callable as _Callable) from .core.hints import Domain as _Domain ArgumentSerializer = _Callable[[_Any], str] FieldSeeker = _Callable[[_Domain, str], _Any]
StarcoderdataPython
105151
<filename>collatorx/common/ledger.py from datetime import datetime from uuid import uuid4 class Ledger(): LEDGER_TYPE = "default" def __init__(self): self._id = uuid4() self._dob = datetime.datetime.today() @property def ledger_id(self): return str(self._id) @propert...
StarcoderdataPython
4810095
import platform import re import threading from time import sleep from urllib3 import make_headers, ProxyManager from common import DATA_DIR import subprocess, os class ProxyPool: def __init__(self, proxy_list_file): self.credit_record = {} self.waiting_round = {} self.proxy_list = self....
StarcoderdataPython
3363013
from __future__ import division from logging import getLogger logger = getLogger('game_object') from math import sqrt import collections import game from Box2D import b2 from vector import Vector class GameObject(object): def __init__(self, name="", world=None, shape='box', size=(0.5, 0.5), location=Non...
StarcoderdataPython
1768637
""" Client wrapper for Google App Engine memcache API https://cloud.google.com/appengine/docs/standard/python/memcache/ """ from vishnu.backend.client import Base from vishnu.backend.client import PickleableSession from google.appengine.api import memcache import pickle NAMESPACE = "vishnu" class Client(Base): ...
StarcoderdataPython
4815893
# -*- coding: utf-8 -*- # Generated by Django 1.11.10 on 2018-02-17 21:41 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0010_auto_20180216_0946'), ] operations = [ migrations.AlterField(...
StarcoderdataPython
3321385
import numpy as np from dgpy.domain import BoundaryCondition class AnalyticSolution: def __init__(self, boundary_condition_type, solution): assert boundary_condition_type in [ BoundaryCondition.DIRICHLET, BoundaryCondition.NEUMANN ] self.boundary_condition_type = boundary_condi...
StarcoderdataPython
4808879
<reponame>paulsbrookes/subcipher import numpy as np from key import Key import itertools default_alpha = ' etaoinshrdlcumwfgypbvkjxqz' def remove_duplicates(values): list_form = [x.tolist() for x in values] list_form.sort() filtered_list = list(list_form for list_form,_ in itertools.groupby(list_form)) ...
StarcoderdataPython
1688240
# lesson 44 Threading # multiple tasks at one time import threading from queue import Queue import time ## a lock per shared variable or shared function print_lock = threading.Lock() def exampleJob(worker): time.sleep(1.0) with print_lock: print(threading.current_thread().name, worker) ## assignin...
StarcoderdataPython
37721
#---- Python VM startup for LISTENERLISTENER_3_from_1 --- import SSL_listener incomingIP="localhost" incomingPort=10031 incomingPrivateKeyFile="server.key" incomingPublicKeyFile="server.crt" outgoingIP="localhost" outgoingPort=00000 outgoingPublicKeyFile="server.crt" def startLISTENER_3_from_1(): incoming_ssl_Encryp...
StarcoderdataPython
1674660
<gh_stars>0 from typing import Tuple from pandas import DataFrame from pyspark.sql import DataFrame as SparkDF from pyspark.sql.types import ArrayType, DoubleType, LongType, StringType, StructField, StructType from dagster import Out, Output, op HN_ACTION_SCHEMA = StructType( [ StructField("id", LongType...
StarcoderdataPython
4812789
<filename>testing/ros_debug/workspace/dev_ws/src/ros_debug_nodes/ros_debug_nodes/broadcast_node_details.py import rclpy import socket import random from rclpy.node import Node from std_msgs.msg import String class NodeNetworkingPublisher(Node): def __init__(self): super().__init__('node_network_publisher...
StarcoderdataPython
8115
from collections import deque def solution(N, bus_stop): answer = [[1300 for _ in range(N)] for _ in range(N)] bus_stop = [(x-1, y-1) for x,y in bus_stop] q = deque(bus_stop) for x,y in bus_stop: answer[x][y] = 0 while q: x, y = q.popleft() for nx, ny in ((x-1, y), (x+1, y)...
StarcoderdataPython