id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
1754916
<reponame>DasPrombelBread/laneBOT-Whatsapp #!/usr/bin/python3 # PLEASE READ EVERY LINE WHERE I COMMENTED "TODO"! YOU CAN SEARCH IT IN THE TEXT BY USING THE SEARCH TOOL OF YOUR TEXT EDITOR OR IDE! # INFO # This Script was made by "DasPrombelBread" (Lane)! # This program is standing under the MIT license, # you can cop...
StarcoderdataPython
1744719
<gh_stars>0 #!/usr/bin/env python import unittest from flattery import flatten, unflatten class FunctionTestCase(unittest.TestCase): def __init__(self, **keywords): unittest.TestCase.__init__(self) self.args = [] self.kwargs = {} for k, v in keywords.items(): setattr(self, k, v) def runT...
StarcoderdataPython
3352849
<gh_stars>1-10 from md_condition.extension import ConditionExtension def makeExtension(**kwargs): return ConditionExtension(**kwargs)
StarcoderdataPython
1727255
"""Hello world plugin.""" from phy import IPlugin, connect class ExampleHelloPlugin(IPlugin): def attach_to_controller(self, controller): @connect(sender=controller) def on_gui_ready(sender, gui): """This is called when the GUI and all objects are fully loaded. This is to ...
StarcoderdataPython
123800
<filename>pyvalidator/alpha.py alpha = { 'en-US': '^[A-Z]+$', 'az-AZ': '^[A-VXYZÇƏĞİıÖŞÜ]+$', 'bg-BG': '^[А-Я]+$', 'cs-CZ': '^[A-ZÁČĎÉĚÍŇÓŘŠŤÚŮÝŽ]+$', 'da-DK': '^[A-ZÆØÅ]+$', 'de-DE': '^[A-ZÄÖÜß]+$', 'el-GR': '^[Α-ώ]+$', 'es-ES': '^[A-ZÁÉÍÑÓÚÜ]+$', 'fa-IR': '^[ابپتثجچحخدذرزژسشصضطظعغف...
StarcoderdataPython
3344343
<reponame>bruxy70/garbage_collection """Define constants used in garbage_collection.""" # Constants for garbage_collection. # Base component constants DOMAIN = "garbage_collection" CALENDAR_NAME = "Garbage Collection" SENSOR_PLATFORM = "sensor" CALENDAR_PLATFORM = "calendar" ATTRIBUTION = "Data from this is provided ...
StarcoderdataPython
29945
class SendResult: def __init__(self, result={}): self.successful = result.get('code', None) == '200' self.message_id = result.get('message_id', None)
StarcoderdataPython
3366821
<filename>Demo/liaoxf/do_listcompr.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- import os # 列表生成式/列表推导 # 通常的原则是,只用列表推导来创建新的列表,并且尽量保持简短 list_comp1 = [x * x - 1 for x in range(1, 21)] print(list_comp1) # 笛卡尔积1 list_comp2 = [m + n for m in 'ABC' for n in 'XYZ'] print(list_comp2) # 笛卡尔积2(Python 会忽略代码里 []、 {} 和 (...
StarcoderdataPython
3330824
import logging import os import numpy as np import tensorflow as tf import tensorflow.keras as keras import tensorflow.keras.layers as kl from keras.models import Model from keras_radam import RAdam from tensorflow.keras.layers import Activation from tensorflow.keras.layers import BatchNormalization from tensorflow.ke...
StarcoderdataPython
83072
<reponame>hackthevalley/hack-the-back from django.core.exceptions import ValidationError from django.utils.translation import gettext as _ from hacktheback.messenger.utils import render_mjml def validate_mjml(value): rendered = render_mjml(value) if rendered is None: raise ValidationError(_("The valu...
StarcoderdataPython
66381
""" A :class:`~glue.core.subset_group.SubsetGroup` unites a group of :class:`~glue.core.subset.Subset` instances together with a consistent state, label, and style. While subsets are internally associated with particular datasets, it's confusing for the user to juggle multiple similar or identical subsets, applied to ...
StarcoderdataPython
1776826
# encoding: utf-8 # author: BrikerMan # contact: <EMAIL> # blog: https://eliyar.biz # file: test_processor.py # time: 2019-05-23 17:02 import os import time import logging import tempfile import unittest import numpy as np import random from kashgari import utils from kashgari.processors import ClassificationProcesso...
StarcoderdataPython
1701956
class StockItem : def __init__(self, date, open, high, low, close, volume, transation): self.date = date self.open = (int)(open*100) self.high = (int)(high*100) self.low = (int)(low*100) self.close = (int)(close*100) self.volume = (i...
StarcoderdataPython
1685057
<reponame>isc-projects/forge """Kea leases manipulation commands""" # pylint: disable=invalid-name,line-too-long import pytest import srv_msg import misc import srv_control @pytest.mark.v6 @pytest.mark.kea_only @pytest.mark.controlchannel @pytest.mark.hook @pytest.mark.lease_cmds def test_hook_v6_lease_cmds_list()...
StarcoderdataPython
3305247
<reponame>cardosofede/hummingbot<gh_stars>100-1000 from aiounittest import async_test from aiohttp import ClientSession import asyncio from contextlib import ExitStack from decimal import Decimal from os.path import join, realpath from typing import List, Dict, Any import unittest from unittest.mock import patch from ...
StarcoderdataPython
184403
<filename>glypy/io/linear_code.py ''' A module for operating on GlycoMinds Linear Code Assumes that the structure's root is the right-most residue, as shown in :title-reference:`A Novel Linear Code Nomenclature for Complex Carbohydrates, Banin et al.`. Currently does not handle the sigils indicating deviation from th...
StarcoderdataPython
194554
#!/usr/bin/env python3 # Copyright (c) 2018 Aiven, Helsinki, Finland. https://aiven.io/ import argparse import os import sys from consumer_example import consumer_example from producer_example import producer_example def main(): parser = argparse.ArgumentParser() parser.add_argument('--service-uri', help="S...
StarcoderdataPython
1610136
<reponame>AlexNilsson/python-remove-duplicate-files from .Files import Files def removeDuplicates(directory): Files(directory).removeDuplicates()
StarcoderdataPython
3377984
""" Example Train Annex 4 v1 ======================== A train with three routes each composed of two sections. Given this infrastructure: .. uml:: ../uml/tom-06-example-annex-4-infrastructure.puml The following routing specification describes the initial planned routes for the rain with `ID1`. As you can see, ther...
StarcoderdataPython
3370540
<filename>src/migrations/023_create_endpoint_history.py """Creates the endpoint history tables. Not storing the history of tables is a recipe for disaster, even with backups. Furthermore if we do not store a history we essentially can never grant access to people we only sort of trust. With these tables it's way eas...
StarcoderdataPython
92905
from . import wrapper @wrapper.parse def _encode(b,file_parsed): macs = [] for i in file_parsed: mac = '' mac_list = [i[o].to_bytes(1,'big') for o in range(0,len(i))] # adress groups (1byte), to_bytes --> convert int to bytes mac_list_len = len(mac_list) for j in range(mac_list_len): # groups len ...
StarcoderdataPython
1629477
import shutil import torch CHECKPOINT_SIZE_MB = 333 BATCH_SIZE_PER_GB = 2.5 LEARNING_RATE_PER_BATCH = 3.125e-5 def get_available_memory(): """ Get available GPU memory in GB. Returns ------- int Available GPU memory in GB """ gpu_memory = torch.cuda.get_device_properties(0).total...
StarcoderdataPython
3301028
<gh_stars>1-10 from pvector import PVector import pgzrun # from pgzero import Actor WIDTH = 400 HEIGHT = 400 class Ball(Actor): def __init__(self, x, y, v_x, v_y, radius, image): super().__init__(self, image) self.radius = radius self.position = PVector(x, y) self. velocity = ...
StarcoderdataPython
3288345
<gh_stars>1-10 import os import numpy as np import tensorflow as tf SEQUENCE_LENGTH = 1.0 # seconds STEP_TIME = 0.2 # seconds CHOOSE_STEP = int(SEQUENCE_LENGTH / STEP_TIME) def cosserat_rods_sim_pc(path, content_file, batch_size, load_train=True, load_val=True, load_test=True): df = np.load(os.path.join(path,...
StarcoderdataPython
196634
# encoding: utf-8 from __future__ import print_function import sys template = """ from distutils.core import setup, Extension import sys import pprint from Cython.Distutils import build_ext ext = Extension("%(name)s", sources = %(source_files)s, language="c++", include_dirs = %(include_dirs)r, e...
StarcoderdataPython
3202631
<gh_stars>1-10 import redis r = redis.Redis(host='10.10.14.245', port=6379) count = 0 with open(r'E:\Python_work\SpiderWork\SpiderPro\SC\city.txt', mode='r', encoding='utf-8') as fp: city_list = fp.readlines() with open(r'E:\Python_work\SpiderWork\SpiderPro\SC\pinpai.txt', mode='r', encoding='utf-8') as fp: ...
StarcoderdataPython
3288277
""" Module responsible for translating sequence annotation data into GA4GH native objects. """ from __future__ import division from __future__ import print_function from __future__ import unicode_literals import json import random import ga4gh.protocol as protocol import ga4gh.datamodel as datamodel import ga4gh.sqli...
StarcoderdataPython
3362610
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jul 27 14:07:01 2018 @author: gbaechle """ import numpy as np from scipy import misc import matplotlib.pyplot as plt from os import listdir from os.path import isfile, join, exists import warnings gdal_available = True try: from osgeo import gda...
StarcoderdataPython
1622433
<reponame>victorers1/anotacoes_curso_python<filename>excript/aulas/aula96_funcao_aninhada.py def func(): print("func") def func_interna(): print("func_interna") func_interna() func()
StarcoderdataPython
106734
# -*- coding: utf-8 -*- # @File : google_im2txt/get_uni_caption.py # @Info : @ TSMC-SIGGRAPH, 2018/7/9 # @Desc : # -.-.. - ... -- -.-. .-.. .- -... .---. -.-- ..- .-.. --- -. --. ..-. .- -. import re from utils.emb_json import load_json_file, store_json_file data = load_json_file("google_im2txt_cap.js...
StarcoderdataPython
8365
<reponame>Lifeistrange/WeiboSpider # coding:utf-8 import datetime import json import re import redis from config.conf import get_redis_args redis_args = get_redis_args() class Cookies(object): rd_con = redis.StrictRedis(host=redis_args.get('host'), port=redis_args.get('port'), pas...
StarcoderdataPython
3332691
<reponame>kollieartwolf/pc-rudn-course-2020-21 from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('lectures.urls', namespace='lectures')), ]
StarcoderdataPython
193732
from typing import List def insert_sort(lst: List[int]): for i in range(1, len(lst)): j = i - 1 key = lst[i] while lst[j] > key and j >= 0: lst[j + 1] = lst[j] j -= 1 lst[j + 1] = key return lst
StarcoderdataPython
1746193
<gh_stars>1-10 #!/usr/bin/env python3 # -*- coding: utf-8 -*- import copy import numpy as np import pandas as pd from scipy import signal from scipy.stats import linregress # from collections import namedtuple from raman_fitting.processing.spectrum_template import ( SpecTemplate, SpectrumWindowLimits, Sp...
StarcoderdataPython
1674396
<reponame>nikhiljha/kubernetes-typed # Code generated by `typeddictgen`. DO NOT EDIT. """V1AWSElasticBlockStoreVolumeSourceDict generated type.""" from typing import TypedDict V1AWSElasticBlockStoreVolumeSourceDict = TypedDict( "V1AWSElasticBlockStoreVolumeSourceDict", { "fsType": str, "partiti...
StarcoderdataPython
3331292
print("Hello") username = "Joe" print(username)
StarcoderdataPython
3274917
class BaseMeta(type): def __new__(cls,name,bases,body): if not 'bar' in body: raise TypeError("Bad user class") # print('BaseMeta.__new__',cls,name,bases,body) return super().__new__(cls,name,bases,body) class Base(metaclass=BaseMeta): def foo(self): return self....
StarcoderdataPython
1727386
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn.metrics import confusion_matrix, roc_curve, auc def multiple_histograms_plot(data, x, hue, density=False, bins=10, alpha=0.5, colors=None, hue_order=None, ...
StarcoderdataPython
83002
<filename>TF/logistic_regression.py # coding=utf-8 import tensorflow as tf import numpy as np import matplotlib.pyplot as plt def get_weight(shape, lamda): pass # 添加层,带有激活函数,但是没有考虑 def add_layer(inputs, in_size, out_size, activation_function=None): """添加层""" # add one more layer and return the output of...
StarcoderdataPython
1775882
<filename>setup.py import re from setuptools import setup, find_packages def get_long_description(): with open('README.md') as f: return f.read() def get_version(): with open('monobank_client/__init__.py') as f: version_match = re.search(r"^__version__\s+=\s+['\"]([^'\"]*)['\"]", f.read(), ...
StarcoderdataPython
3258238
from flask import Flask, jsonify, redirect, request from flask_caching import Cache import data_fetch app = Flask(__name__) cache = Cache(app, config={'CACHE_TYPE': 'simple'}) cache.init_app(app) cache_time = 120 # 2 Minutes @app.route('/') @cache.cached(timeout=cache_time) def index(): fetcher = data_fetch.V...
StarcoderdataPython
20865
from ..util import slice_ def csrot(N, CX, INCX, CY, INCY, C, S): """Applies a Givens rotation to a pair of vectors x and y Parameters ---------- N : int Number of elements in input vector CX : numpy.ndarray A single precision complex array, dimension (1 + (`N` - 1)*abs(`INCX`)) ...
StarcoderdataPython
3271108
<gh_stars>1-10 import os import numpy as np from astropy.table import Table from astropy.modeling.models import custom_model from scipy.ndimage.filters import gaussian_filter1d from astropy.modeling.core import Fittable1DModel from astropy.modeling.parameters import Parameter __all__ = ['IronTemplate'] pathList = os....
StarcoderdataPython
4833273
<reponame>MSD-99/telegram_statistics from abc import abstractmethod import json def read_json(file_path: str) -> dict: """Reads a json file and returns the dict """ with open(file_path) as f: return json.load(f) def read_file(file_path: str) -> str: """Reads a file and returns the conent ...
StarcoderdataPython
1795580
import numpy import struct import warnings from .compat import structured_cast # from .logger import logger from ..lib.arraybase import set_or_add_to_structured, to_structured from ..lib.iterable import split try: import xxhash _HAS_XXHASH = True except ImportError: _HAS_XXHASH = False import hashlib ...
StarcoderdataPython
5725
import numpy as np if __name__ == '__main__': h, w = map( int, input().split() ) row_list = [] for i in range(h): single_row = list( map(int, input().split() ) ) np_row = np.array( single_row ) row_list.append( np_row ) min_of_each_row = np.min( row_list, axis = 1) ...
StarcoderdataPython
130823
<reponame>Armorless-Visage/blacklistparser #!/usr/bin/env python3 # <NAME> (c) 2019 ISC # Full licence terms located in LICENCE file from os import path ''' some types for argparse type argument ''' def base_path_type(pathname): ''' custom type for checking that a file path is valid returns input if the...
StarcoderdataPython
3275860
__all__ = ('APIHooker', 'form', 'Config') import functools import json import os import re import textwrap import uuid from typing import Iterable from flask import render_template, request, redirect class APIHooker: def __init__(self, app, upload='data'): self._app = app self._upload = upload...
StarcoderdataPython
3338431
# Copyright (c) 2018 <NAME> # This code is available under the "Apache License 2.0" # Please see the file COPYING in this distribution for license terms. import tensorflow as tf import math from multiprocessing import cpu_count files = tf.gfile.Glob('/data/tf-records/batches/*.tfrecords') train_test_split = math.cei...
StarcoderdataPython
3318165
#!/usr/bin/python # vim: ts=4 sw=4 et """Class for handling argparse parsers. Methods are configured as subparsers.""" import argparse import os import subprocess import sys import textwrap import yaml from vctools import Logger # pylint: disable=too-many-instance-attributes class ArgParser(Logger): """Argparser c...
StarcoderdataPython
3326227
from typing import List, Optional import pytest from cdv.test import CoinWrapper from cdv.test import setup as setup_test from chia.consensus.default_constants import DEFAULT_CONSTANTS from chia.types.blockchain_format.coin import Coin from chia.types.blockchain_format.program import Program from chia.types.spend_bun...
StarcoderdataPython
1773357
import os import cv2 from sklearn.preprocessing import StandardScaler from sklearn.cluster import KMeans import numpy as np import pickle import matplotlib.pyplot as plt NUMBER_IMAGES = 50 DIR = 'images/' files = [] for root, directories, filenames in os.walk(DIR): for filename in filenames: files.append...
StarcoderdataPython
3279360
"""Support for Overkiz locks.""" from __future__ import annotations from typing import Any from pyoverkiz.enums import OverkizCommand, OverkizCommandParam, OverkizState from homeassistant.components.lock import LockEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import Platform f...
StarcoderdataPython
3252903
<reponame>Vaibhav9119/MBA749A-Assignments # Nothing is here
StarcoderdataPython
113676
<filename>scraper/core/classifiers/BaseClassifier.py import math import re from collections import Counter, OrderedDict class BaseClassifier: WORD = re.compile(r'\w+') def get_cosine(self, vec1, vec2): # print vec1, vec2 intersection = set(vec1.keys()) & set(vec2.keys()) numerator = ...
StarcoderdataPython
93737
<reponame>acstarr/clean_ipynb from setuptools import setup name = "clean_ipynb" setup( name=name, version="1.1.1", python_requires=">=3.6", install_requires=("autoflake", "black", "click", "isort"), packages=(name,), entry_points={"console_scripts": ("{0}={0}.{1}:{1}".format(name, "cli"),)}, )...
StarcoderdataPython
3271386
# Copyright 2014 Mirantis, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
StarcoderdataPython
3363279
<filename>src/oci/license_manager/models/bulk_upload_validation_error_info.py # coding: utf-8 # Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache...
StarcoderdataPython
1767582
<filename>aorn/methods/antest.py # -*- coding: utf-8 -*- '''Generic test method module ''' from __future__ import with_statement, division, absolute_import, print_function from abc import ABCMeta, abstractmethod import six @six.add_metaclass(ABCMeta) class ANTest(object): '''Generic test method class ''' ...
StarcoderdataPython
113902
#!/usr/bin/env python3 # ======================================================================== # # Imports # # ======================================================================== import os import shutil import argparse import subprocess as sp import numpy as np import time from datetime import timedelta # ===...
StarcoderdataPython
1725957
<reponame>MrFunBarn/ADRL from astropy.io import fits class dataSet(): def __init__():
StarcoderdataPython
3201149
# -*- coding: utf-8 -*- """OpenCTI CrowdStrike connector module.""" from crowdstrike.core import CrowdStrike __all__ = ["CrowdStrike"]
StarcoderdataPython
1635480
<filename>code/python/echomesh/sound/Sound.py from __future__ import absolute_import, division, print_function, unicode_literals from echomesh.base import Config from echomesh.util import ImportIf pyaudio = ImportIf.imp('pyaudio') _PYAUDIO = None _LIST_FORMAT = ('{name:24}: {maxInputChannels} in, ' + ...
StarcoderdataPython
151691
# MIT License # # Copyright (c) 2018 Image & Vision Computing Lab, Institute of Information Science, Academia Sinica # # 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, inc...
StarcoderdataPython
3227743
<gh_stars>1-10 import os class Config(): SECRET_KEY = 'ilovetofly' SQLALCHEMY_DATABASE_URI = 'sqlite:////var/tmp/bapa.db' SQLALCHEMY_TRACK_MODIFICATIONS = False MAIL_SERVER = 'smtp.dummy.com' MAIL_PORT = '123' MAIL_USERNAME = 'uname' MAIL_PASSWORD = '<PASSWORD>' MAIL_DEFAULT_SENDER = ...
StarcoderdataPython
4801004
<reponame>marc-haddad/web-scraping-challenge<filename>Missions_to_Mars/app.py<gh_stars>0 from flask import Flask, render_template, redirect import pymongo from flask_pymongo import PyMongo import scrape_mars # Configure app app = Flask(__name__) mongo = PyMongo(app, uri="mongodb://localhost:27017/scrape_mars_app") @...
StarcoderdataPython
16802
<filename>tools/modules/verify.py # ------------------------------------------------------------------------ # Copyright 2020, 2021 IBM Corp. 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 cop...
StarcoderdataPython
47024
import os import sys NAME = 'multipla' PACKAGE = __import__(NAME) AUTHOR, EMAIL = PACKAGE.__author__.rsplit(' ', 1) with open('docs/index.rst', 'r') as INDEX: DESCRIPTION = INDEX.readline() with open('README.rst', 'r') as README: LONG_DESCRIPTION = README.read() URL = 'https://github.com/monkeython/%s' % NA...
StarcoderdataPython
3220160
<gh_stars>1-10 import rospy import smach import mission_plan.srv class PopItemState(smach.State): """ This state should only be used when in PICKING mode, to remove items from the mission plan after the picking was UNSUCCESSFUL and should not be attempted again! If picking was SUCCESSFUL, use the...
StarcoderdataPython
4838998
""" Python 3.6+ Data import from Excel file and addition to CTVdb <NAME> 2020-2022 """ import argparse import os import sys import pandas as pd from Database_tools.db_functions import searchexact, session_maker from Database_tools.sqlalchemydeclarative import Serotype, SerotypeVariants, Group, Variants, ...
StarcoderdataPython
3383690
<gh_stars>0 import datetime import message_strings as loginfo import json class Logger: def __init__(self, logType='default'): self.logType = logType def log(self, message): """ Logs the a message into logfile.txt along with a timestamp & log type. """ timestamp = date...
StarcoderdataPython
1736541
<gh_stars>1-10 """ Left-Right Circle Shift @author Rafael """ #!/bin/python3 def getShiftedString(s, leftShifts, rightShifts): """ Generate the string after the following operations 1. Left Circle Shift 2. Right Circle Shift :type s: string :type leftShifts: int :type rightShifts:...
StarcoderdataPython
149181
# -*- coding: utf-8 -*- import numpy as np import pandas as pd def calculate_effect_of_credit_drop(model, X, credit_factors): probs = model.predict_proba(X)[:, 1] all_probs_changes = {} all_credit_amount_changes = {} all_expected_costs_in_credit = {} for factor in credit_factors: probs...
StarcoderdataPython
1615990
""" :Copyright: 2006-2021 <NAME> :License: Revised BSD (see `LICENSE` file for details) """ from byceps.database import db from byceps.services.authentication.password.dbmodels import ( Credential as DbCredential, ) from byceps.services.authentication.password import service as password_service from byceps.service...
StarcoderdataPython
1741256
append_file = open('output.txt', 'a') append_file.write('Hello Atom!\n') append_file.close()
StarcoderdataPython
58135
# coding=utf-8 # Copyright 2020 The Google Research 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 applicab...
StarcoderdataPython
101386
<gh_stars>10-100 import os from ats.easypy import run import argparse def main(): parser = argparse.ArgumentParser() parser.add_argument('--device', dest='device') parser.add_argument('--nbr-count', dest='expected_nbr_count') args, unknown = parser.parse_known_args() pwd = os.path.dirname(__file__...
StarcoderdataPython
3231310
def fatorial(n): return 1 if n == 1 else n * fatorial(n - 1) print(fatorial(int(input())))
StarcoderdataPython
3270573
# Importing header files import numpy as np import warnings warnings.filterwarnings('ignore') #New record new_record=[[50, 9, 4, 1, 0, 0, 40, 0]] #Reading file data = np.genfromtxt(path, delimiter=",", skip_header=1) #print(np.shape(data)) #Code starts here census=np.concatenate((data,new_record),axis=0...
StarcoderdataPython
4832978
<filename>elementary/python/ej11.py print("""\ A program that computes (ecuation on OneNote) Created By <NAME> <<EMAIL>> """) sumatoria = 0 for k in range(1, 10 ** 6): sumatoria += ((-1) ** (k + 1)) / ((2 * k) - 1) print('Resultado:', 4 * sumatoria) print('Es pi jajajaja... mientras mas alto el final de la sumat...
StarcoderdataPython
1708412
<filename>src/esamarathon/donation_parser/donation_parser.py from bs4 import BeautifulSoup import requests import sys import string import datetime import time def main(): print("Hekathon 2021 donations") donations = get_esamarathon_donations("hekathon", "hek21") for donation in donations: print(d...
StarcoderdataPython
76691
from pal.transform.abstract_transform import AbstractTransform from pal.logger import logger class SpecialToUnderscore(AbstractTransform): def __init__(self): self.special_chars = " !@#$%^&*()[]{};:,./<>?\|`~-=+" @property def description(self): d = "replacing special characters ({chars}) ...
StarcoderdataPython
3328077
#Developed by Momalekiii import moviepy.editor as mp import speech_recognition as sr def main(): clip = mp.VideoFileClip(r"video.mp4") # add video name here clip.audio.write_audiofile(r"converted.wav") recognizer = sr.Recognizer() audio = sr.AudioFile("converted.wav") with audio as so...
StarcoderdataPython
3313827
import pytest from mock import Mock, patch from AndroidRunner.BrowserFactory import BrowserFactory from AndroidRunner.Browsers import Browser, Chrome, Firefox, Opera class TestBrowsers(object): @pytest.fixture() def browser(self): return Browser.Browser(None) def test_get_browser_chrome(self): ...
StarcoderdataPython
78552
<filename>metaheuristica/source_TSP/python/TSP.py #!/usr/bin/python3 import pandas as pd import numpy as np from scipy.spatial.distance import pdist, squareform def get_dist_tsp(fname='ar9152.tsp'): """ Returns the list with the positions of the cities. Parameters ---------- fname -- filename with...
StarcoderdataPython
1775044
# Copyright 2019-2020 The Kale 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 applicable law or agreed to i...
StarcoderdataPython
3205349
<filename>Python/uif2MongoDB.py import sys from core.storage import Uif, MongoDB if __name__ == '__main__': argc = len(sys.argv) if 4 == argc or 5 == argc: storagePath = sys.argv[1] dataBaseName = sys.argv[2] tableName = sys.argv[3] hostAndPort = sys.argv[4] if 5 == argc else ...
StarcoderdataPython
68079
<filename>src/utils/epoch_logger.py from gensim.models.callbacks import CallbackAny2Vec from datetime import datetime class EpochLogger(CallbackAny2Vec): """ Callback to log information about training Reference: - https://colab.research.google.com/drive/1A4x2yNS3V1nDZFYoQavpoX7AEQ9Rqtve#scrollTo=m...
StarcoderdataPython
3242289
""" Use this module members to connect to RabbitMQ instance. """ import asyncio import logging from fnmatch import fnmatch from typing import AnyStr, Sequence, Optional from uuid import uuid4 import aioamqp from sunhead.events import exceptions from sunhead.events.abc import AbstractTransport, AbstractSubscriber fro...
StarcoderdataPython
3353029
<reponame>diCagri/content import demistomock as demisto from CommonServerPython import * # flake8: noqa: E501 class Client: def __init__(self, params: Dict): self.cs_client = CrowdStrikeClient(params) def add_role_request(self, domain_mssprolerequestv1_resources): data = assign_params(resourc...
StarcoderdataPython
3300510
<filename>make_eye_motion_dataset.py import os import glob import argparse import cv2 import pickle import numpy as np from tqdm import tqdm_gui from data_utils import VideoWrapper, SubtitleWrapper, ClipWrapper ''' # Eye motion dataset strucuture { 'vid': vid_name, 'clip_info': [ { 'sent...
StarcoderdataPython
1656590
<reponame>rakesh-lagare/Thesis_Work # -*- coding: utf-8 -*- from random import randrange import matplotlib.pyplot as plt import numpy as np import numpy.random as nprnd import pandas as pd import os os.remove("dataframe.csv") os.remove("dataList.csv") def pattern_gen(clas,noise,scale,offset): ts_data=[] ...
StarcoderdataPython
3229153
<reponame>TheSlimvReal/PSE---LA-meets-ML from modules.controller.commands.command import Command ## command to display the help message # # this command will be created when entering help in the terminal # @extends Command so it can be treated as the other commands class HelpCommand(Command): pass
StarcoderdataPython
190389
import pandas as pd import tushare as ts from StockAnalysisSystem.core.config import TS_TOKEN from StockAnalysisSystem.core.Utility.common import * from StockAnalysisSystem.core.Utility.time_utility import * from StockAnalysisSystem.core.Utility.CollectorUtility import * # -------------------------------------------...
StarcoderdataPython
1657618
# Mở file file = open("putTacGia.txt", "w") for num in range(1,50001): s2=str(num) s3="put 'TACGIA','TG" + s2 + "','TG:MSTG','MSTG" + s2 + "'\n" s4="put 'TACGIA','TG" + s2 + "','TG:TENTG','TENTG" + s2 + "'\n" s5="put 'TACGIA','TG" + s2 + "','TG:SDT','SDT" + s2 + "'\n" s6="put 'TACGIA','TG" + ...
StarcoderdataPython
3311033
<filename>Scripts/rcfilt.py import numpy as np from scipy.signal import lfilter def rcfilt(y=None,SampTime=None,TimeConstant=None,UpDown='up',*args,**kwargs): ''' Filters a spectrum using a RC low-pass filter as built into cw spectrometers to remove high-frequency noise. This script is freely insp...
StarcoderdataPython
109059
import datetime import json import os def get_utc_now(): return datetime.datetime.utcnow() def format_datetime(date_time): """Generate string from datetime object.""" return date_time.strftime("%Y-%m-%d %H:%M:%S") def get_vcap_service(): vcap_config = os.getenv('VCAP_SERVICES', None...
StarcoderdataPython
176283
import numpy as np import datetime from ..nets.lstm_network import ActorCritic import torch import torch.optim as optim from tqdm import trange from tensorboardX import SummaryWriter class Agent(object): def __init__(self, agent_name, input_channels, network_parameters, ppo_parameters=None, n_actions=3): ...
StarcoderdataPython
1644890
# Copyright 2019 D-Wave Systems Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wri...
StarcoderdataPython
15616
"""Coverage based QC calculations. """ import glob import os import subprocess from bcbio.bam import ref, readstats, utils from bcbio.distributed import transaction from bcbio.heterogeneity import chromhacks import bcbio.pipeline.datadict as dd from bcbio.provenance import do from bcbio.variation import coverage as co...
StarcoderdataPython