id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
1685247
<reponame>ironss/micropython-lib<gh_stars>0 """ Watchdog monitor Various services must report in periodically. If all of them have reported in, the watchdog monitor feeds the hardware watchdog. Otherwise, the monitor does not feed the hardware watchdog and eventually the system restarts. """ import ulogging import ut...
StarcoderdataPython
1777096
<gh_stars>0 # Generated by Django 3.0.1 on 2020-12-20 15:35 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0005_auto_20201220_1616'), ] operations = [ migrations.AddField( model_name='prof', name='prof_...
StarcoderdataPython
98003
<gh_stars>0 # -*- coding: utf-8 -*- """ Created on Mon Feb 24 13:09:04 2020 @author: 766810 """ tab = [] loop = 'loop' # tab will hold all Kaprekar numbers found # loop is just for better wording def asc(n): # puts the number's digits in ascending... return int(''.join(sorted(str(n)))) def d...
StarcoderdataPython
1605051
<filename>cvchallenge1/predict.py from datetime import datetime import logging import os from urllib.request import urlopen from PIL import Image import tensorflow as tf import numpy as np from tensorflow.keras import backend as K from urllib.request import urlopen from tensorflow.keras import backend as K from tens...
StarcoderdataPython
47367
from conans.model import Generator """ PC FILE EXAMPLE: prefix=/usr exec_prefix=${prefix} libdir=${exec_prefix}/lib includedir=${prefix}/include Name: my-project Description: Some brief but informative description Version: 1.2.3 Libs: -L${libdir} -lmy-project-1 -linkerflag Cflags: -I${includedir}/my-project-1 Requi...
StarcoderdataPython
1603377
<reponame>DonaldKBrown/Keybase-SSH-Auth """ Keybase SSH Authentication Server Copyright 2019 - <NAME>, <EMAIL> Published under the MIT License This module is the main module in this project. It runs the Flask server responsible for requesting, checking, and reporting SSH authentication requests. """ from flask import...
StarcoderdataPython
1759694
<reponame>ecmwf/pyeccodes<filename>pyeccodes/defs/grib2/tables/4/4_2_3_1_table.py def load(h): return ({'abbr': 0, 'code': 0, 'title': 'Estimated precipitation', 'units': 'kg m-2'}, {'abbr': 1, 'code': 1, 'title': 'Instantaneous rain rate', 'units': 'kg m-2 s-1'}, ...
StarcoderdataPython
74079
from .cache import * # will also import some globals like `britive` def test_create(cached_security_policy): assert isinstance(cached_security_policy, dict) def test_list(cached_security_policy): policies = britive.security_policies.list() assert isinstance(policies, list) assert cached_security_po...
StarcoderdataPython
145139
import os from ocr import OCR class receiptParser: ocr = OCR() raw_tickets = None def __init__(self, image_folder_path): self.image_files = [f for f in os.listdir(image_folder_path) if bool(os.path.isfile(os.path.join(image_folder_path, f)) and '.jpg' in f)] print(self.image_files) def scrape_tickets(sel...
StarcoderdataPython
1725976
<filename>misc/trans_writer.py """ This script writes continuous transformation information to file """ import numpy import re SAVE_PATH = '/home/bioprober/gh/3d-converter/tests/data/' class TransWriter: def __init__(self, filename): self.filename = filename self.info = '' def config(self,...
StarcoderdataPython
147869
import pyxel import math pyxel.init(200, 200) pyxel.cls(7) for i in range(0, 360, 1): iRadian = math.radians(i) lineColor = int(i * 7 / 360) pyxel.line(100, 100, 100 + 100 * math.sin(iRadian * 2), 100 + 100 * math.cos(iRadian * 3), lineColor) pyxel.show()
StarcoderdataPython
3371204
import json from core_data_modules.data_models import Scheme def _open_scheme(filename): with open(f"code_schemes/{filename}", "r") as f: firebase_map = json.load(f) return Scheme.from_firebase_map(firebase_map) class CodeSchemes(object): INTERNET = _open_scheme("internet_working.json") ...
StarcoderdataPython
1632906
from djtools.socialnetworks.models import SocialNetwork from django.test import TestCase class SocialNetworkTestCase(TestCase): def setUp(self): self.twitter = SocialNetwork.objects.create( social_network='twitter', account_id='test' ) self.github = SocialNetwork.ob...
StarcoderdataPython
1753747
<filename>src/skmultiflow/trees/nodes/anytime_split_node.py import numpy as np from skmultiflow.trees.attribute_split_suggestion import AttributeSplitSuggestion from skmultiflow.trees.attribute_observer import NominalAttributeClassObserver from skmultiflow.trees.attribute_observer import NumericAttributeClassObserverGa...
StarcoderdataPython
136582
# # Copyright (c) 2018 CNRS INRIA # ## In this file, are reported some deprecated functions that are still maintained until the next important future releases ## from __future__ import print_function import warnings as _warnings from . import libpinocchio_pywrap as pin from .deprecation import deprecated, Deprecat...
StarcoderdataPython
3393142
''' Задача 10 Найти количество цифр 5 в числе ''' value=0 count=0 integer_number = 291341555 while integer_number > 0: value = integer_number % 10 if value == 5: count+=1 integer_number = integer_number//10 print(count)
StarcoderdataPython
3285594
<reponame>Kirpich1812/amino_service import random class DeviceGenerator: def __init__(self): device = self.generate_device_info() self.user_agent = device["user_agent"] self.device_id = device["device_id"] self.device_id_sig = device["device_id_sig"] @staticmethod def gene...
StarcoderdataPython
67859
<filename>sudokuless/load.py import os import sys from .exceptions import FormatError def from_text(txt): """Create a list structure from a special format of text. Args: txt: a string, 9 lines, 'x' represents blank cell that needs to fill. An example here: xx31x8xxx xx2xxx7xx...
StarcoderdataPython
1620942
<filename>slue_toolkit/text_ner/reformat_pipeline.py<gh_stars>0 import fire import os from slue_toolkit.generic_utils import read_lst, write_to_file def prep_data(model_type, asr_data_dir, asr_model_dir, out_data_dir, eval_set, lm="nolm"): """ Create tsv files for pipeline evaluation from the decoded ASR transcript...
StarcoderdataPython
1616001
#!/usr/bin/python3 import glob import os from pathlib import Path, PurePosixPath files = glob.glob('/home/bkk/Pictures' + '/**/*.*', recursive=True) filesToDelete = [] # detect files for deletion for f in files: if (PurePosixPath(f).suffix == '.jpg') and str(PurePosixPath(f).with_suffix('.HEIC')) in files: ...
StarcoderdataPython
3268973
<filename>src/proxy_data.py # Copyright 2017 NeuStar, 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 req...
StarcoderdataPython
3228617
inches = float(input()) centimeters = inches * 2.54 print(centimeters)
StarcoderdataPython
1654000
<gh_stars>1-10 import numpy as np def sigmoide(Z): # Calculo de la funcion sigmoide sigmoide = 1 / (1 + np.exp(-Z)) return sigmoide def one_hot(y, et): # Transforma y en one_hot con et numero de etiquetas m = len(y) y = (y - 1) y_onehot = np.zeros((m, et)) for i in range(m): ...
StarcoderdataPython
1694393
<gh_stars>10-100 # JN 2016-01-12 """ manage spikes for data viewer """ import os from .tools import debug class SpikeManager(object): """ Represent spikes for data viewer """ def __init__(self, sign, label): self.fnames = {} self.openfiles = {} self.times = {} self.spik...
StarcoderdataPython
3379191
<reponame>AbdulFMS/lanedet<gh_stars>100-1000 from .detector import Detector
StarcoderdataPython
3383660
""" Requirements. $ pip3 install bokeh """ from MotionDetector import data_frames from bokeh.plotting import figure, show, output_file from bokeh.models import HoverTool, ColumnDataSource # ColumnDataSource - standardized way of providing data to bokeh plot data_frames["Start_string"] = data_frames["Start"].dt...
StarcoderdataPython
4840337
<reponame>AKhodus/adcm<filename>python/api/component/serializers.py # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by ap...
StarcoderdataPython
123725
"""Read yaml configuration files.""" import yaml class Config: """Configuration file reader.""" def __init__(self, fh): """Initialize the configuration from a file handle.""" self._config = yaml.load(fh) fh.close() def get(self, *args): """Get a key from a path given as m...
StarcoderdataPython
1726215
<filename>bot.py from telegram.ext import Updater, MessageHandler, CommandHandler, Filters from watson_developer_cloud import ConversationV1 import json from dbhelper import DBHelper db=DBHelper() context = None # Define a few command handlers. These usually take the two arguments bot and # update. Error handlers al...
StarcoderdataPython
3345099
<reponame>c-bik/pretalx<gh_stars>1-10 from decimal import Decimal from functools import partial from django import forms from django.core.files.uploadedfile import UploadedFile from django.utils.translation import gettext_lazy as _ from pretalx.common.forms.utils import get_help_text, validate_field_length from preta...
StarcoderdataPython
145872
<reponame>pykulytsky/demando from typing import Type from fastapi import Depends from base.database import get_db from sqlalchemy.orm import Session from base.manager import BaseManager class ItemManager(BaseManager): def __init__( self, klass: Type, user_model: Type, db: Session...
StarcoderdataPython
3300019
import math import time from phalski_ledshim import app, client, chart def value(): t = time.time() return (math.sin(t) + 1) / 2 if __name__ == '__main__': a = app.App() a.configure_worker(0.1, chart.Factory.red_blue_bar_chart_source(a.pixels, value, lambda: 1 - value())) a.exec()
StarcoderdataPython
1637283
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ isoenum_webgui.routes ~~~~~~~~~~~~~~~~~~~~~ Isotopic enumerator web interface routes. """ import csv import io import json from flask import render_template from flask import request from flask import redirect from flask import url_for from flask import jsonify fro...
StarcoderdataPython
1759723
<filename>2020/cassava-leaf-disease-classification/util/metrics.py import numpy as np from sklearn.metrics import accuracy_score #from sklearn.metrics import f1_score def get_cate_acc(true: list, pred: list, logger=None): if len(true) != len(pred): return 0.0 labels = len(set(true)) acc_n = np.z...
StarcoderdataPython
3393861
import keras from keras.models import load_model, Sequential from keras.layers import Dense, Flatten, Conv2D, MaxPool2D from sklearn.model_selection import train_test_split import numpy as np from sklearn import preprocessing import cv2 np.random.seed(3) X = [] y = [] with open('actions.csv', 'r') as f: for line...
StarcoderdataPython
4806551
import itertools import os from contextlib import contextmanager from dataclasses import dataclass from typing import Literal from typing import Optional from typing import Union, List, Callable, Tuple, Dict, Any, NamedTuple import fitz import pdfminer import unicodedata from pdfminer.high_level import extract_pages f...
StarcoderdataPython
3329473
<reponame>torbjornvatn/powerline-shell from subprocess import Popen, PIPE from shlex import split def add_gcloud_segment(powerline): try: cmd = "gcloud config list| grep project | tr '=' ' ' | tr -s ' ' ' ' | cut -d' ' -f2 | cut -d'-' -f3 | tr -d '\n'" output = Popen('%s' % cmd, stdout=PIPE, shell=...
StarcoderdataPython
3339211
""" CoaT architecture. Paper: Co-Scale Conv-Attentional Image Transformers - https://arxiv.org/abs/2104.06399 Official CoaT code at: https://github.com/mlpc-ucsd/CoaT Modified from timm/models/vision_transformer.py """ from copy import deepcopy from functools import partial from typing import Tuple, List import mat...
StarcoderdataPython
3271944
<gh_stars>1-10 #!/usr/bin/env python # -*- coding: utf-8 -*- import threading import time import random tickets_disponibles = 1000 class VendeurTickets(threading.Thread): tickets_vendus = 0 def __init__(self, semaphore): super().__init__() self.sem = semaphore print('Le vendeur {} d...
StarcoderdataPython
154676
# Copyright © 2014 <NAME> # [This program is licensed under the "MIT License"] # Please see the file COPYING in the source # distribution of this software for license terms. # The += operator on lists appends the a copy of the # right-hand operand to the left-hand operand. This # makes z += y different from z = z + y....
StarcoderdataPython
1693547
<reponame>craftslab/gerritstats # -*- coding: utf-8 -*- import pprint import requests from gerritstats.querier.querier import Querier, QuerierException def test_exception(): exception = QuerierException("exception") assert str(exception) == "exception" def test_querier(): config = { "gerrit": ...
StarcoderdataPython
1760169
#!/usr/bin/env python ######################################################################### # Reinforcement Learning with PGPE on the ShipSteering Environment # # Requirements: pylab (for plotting only). If not available, comment the # last 3 lines out # Author: <NAME>, <EMAIL> #####################################...
StarcoderdataPython
80000
<reponame>SafetyGuardians/SafetyGuardiansApp # Generated by Django 2.0 on 2018-01-08 11:41 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('chat', '0003_auto_20180108_1123'), ] operations = [ migrations.RenameField( model_name='chats...
StarcoderdataPython
1785455
<reponame>keakon/Doodle # -*- coding: utf-8 -*- import logging import os doodle_env = os.getenv('DOODLE_ENV') try: if doodle_env == 'PRODUCTION': from .production import ProductionConfig as CONFIG logging.info('Production config loaded.') elif doodle_env == 'TEST': from .test import T...
StarcoderdataPython
3336689
#Change block #change the block the player is standing on #API setup from picraft import Vector from picraft import World, Block world = World() #-------Your Code-------# #get block below player position = world.player.tile_pos position -= Vector(y=1) #set the block world.blocks[position] = Block(1, 0)
StarcoderdataPython
124911
import json import errno config = { 'first_file_filesize' : '1024', 'second_file_filesize' : '128' } def write_config(): with open('config.json', 'w') as config_file: json.dump(config, config_file) def read_config(): try: config_file = open('config.json', 'r') config = json...
StarcoderdataPython
163303
from django.template import Template, Context from django.template.loader import render_to_string from django.conf import settings def parse(kwargs, template_name="shortcodes/vimeo.html"): video_id = kwargs.get('id') if video_id: width = int(kwargs.get( 'width', getattr(setting...
StarcoderdataPython
4824815
# Copyright 2019 The Forte Authors. 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 ...
StarcoderdataPython
3318993
<reponame>TMarquet/speech_recognition # -*- coding: utf-8 -*- """ Created on Fri Jan 22 11:02:28 2021 @author: kahg8 """ import webrtcvad import os # Helper libraries import numpy as np from scipy.io import wavfile import matplotlib.pyplot as plt labels = ["yes", "no", "up", "down", "left", "right", "on", "off", "st...
StarcoderdataPython
175061
from pathlib import Path from tempfile import TemporaryDirectory import numpy as np import torch from agent import DqnAgent from model import DqnModel from replay_buffer import ReplayBuffer from strategy import EpsilonGreedyStrategy from torch import nn import pytest BATCH_SIZE = 5 @pytest.fixture def agent(): ...
StarcoderdataPython
1789408
<gh_stars>1-10 #!/usr/bin/env python # -*- coding: utf-8 -*- """Compare all messages within a tree with those stored in a date tree (yyyy/mm)""" import KmdMbox import KmdCmd import KmdFiles import mailbox import time import os import logging class KmdMboxMergeDateTree(KmdCmd.KmdCommand): def extendParser(self):...
StarcoderdataPython
128261
from typing import List, Tuple import matplotlib.pyplot as plt import numpy as np import scipy.stats as scs from scipy.optimize import minimize class DistrManager: def __init__( self, left_border: int = -1.8, right_border: int = 2, step: int = 0.2 ) -> None: self._left_border = left_border ...
StarcoderdataPython
3350433
import numpy as np import bpy from mathutils import Matrix, Vector import bmesh import mathutils import copy def normalise_vector_batch(vector): ''' normalising vectors so that (a**2 + b**2 + c**2 == 1**2) ''' vector_s = vector ** 2 vector_s = np.sum(vector_s, axis=1) vector_s =...
StarcoderdataPython
3249687
# -*- coding: utf-8 -*- # This CORS implementation was ported from Jupyter # notebook.base.handlers.{IPythonHandler, APIHandler}. # # notebook's license is as follows: # # Copyright (c) Jupyter Development Team. # Distributed under the terms of the Modified BSD License. from __future__ import absolute_import, divisio...
StarcoderdataPython
4835809
a = exec(open("tmp.txt").read())
StarcoderdataPython
77889
<reponame>AviKalPython/self.py # exc. 7.1.4 def squared_numbers(start, stop): while start <= stop: print(start**2) start += 1 def main(): start = -3 stop = 3 squared_numbers(start, stop) if __name__ == "__main__": main()
StarcoderdataPython
1718658
class BaseStorage(object): """docstring for BaseStorage""" def __init__(self): super(BaseStorage, self).__init__() def filter(self, criteria): raise Exception("Not implemented Error") def getSummary(self, criteria): raise Exception("Not implemented Error") def insert(self,...
StarcoderdataPython
1658182
# Author: <NAME>, <NAME> # with some functions borrowed from https://github.com/SeanNaren/deepspeech.pytorch import json import librosa import numpy as np import os import os.path import scipy.signal import torch import torch.nn.functional import torchvision.transforms as transforms from PIL import Image from torch.uti...
StarcoderdataPython
1783040
from histogram import Histogram from metric import metric_decorated class Meter(Histogram): def __init__(self, name): Histogram.__init__(self, name) return def mark(self): self.update() return def __enter__(self): self.mark() return def __exit__(*unus...
StarcoderdataPython
178737
#!/usr/bin/env python3 import pytest import subprocess as sub from bin import get_dust def test_main(): sub.call(get_dust.__file__, shell=True) if __name__ == '__main__': pytest.main()
StarcoderdataPython
1707880
<reponame>ypix/TeTueTwitchBot from random import choice, randint from time import time from .. import db heist = None heist_lock = time() def coinflip(bot, user, side=None, *args): if side is None: bot.send_message("You need to guess which side the coin will land!") elif (side := side.lower()) not in (opt := ("h...
StarcoderdataPython
3288857
<filename>backend/api/serializers.py from rest_framework import serializers from api.models import * # So a user can be a user class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username') # Converts the flashcard data as needed in order to be passed class...
StarcoderdataPython
1799888
# coding=utf-8 from machine import Pin, Timer VALID_GP_PINS = [9, 10, 11, 24] PIN_PWM_TIMER = { 9: 2, 10: 3, 11: 3, 24: 0, } PIN_PWM_CHANNEL = { 9: Timer.B, 10: Timer.A, 11: Timer.B, 24: Timer.A, } PIN_PWM_ALT = { 9: 3, 10: 3, 11: 3, 24: 5, } PERC_100 = 10000 # in 1...
StarcoderdataPython
132009
import numpy as np import torch import ptan def unpack_batch_a2c(batch, net, last_val_gamma, device="cpu"): """ Convert batch into training tensors :param batch: :param net: :return: states variable, actions tensor, reference values variable """ states = [] actions = [] rewards = ...
StarcoderdataPython
3365363
<filename>main.py # encoding: utf-8 import re from sys import argv #在cmd中读入文件所用的库 from Exceptions import NoTextError from Exceptions import SameTextError from Algorithm import lcs from Algorithm import ld from zhon.hanzi import punctuation #这是去除中文标点所用的库 def readin(textpath): #处理读入文件 str = textpat...
StarcoderdataPython
128238
"""Tests for the serializers of the drf_auth app.""" from django.test import TestCase from mixer.backend.django import mixer from .. import serializers class LoginSerializerTestCase(TestCase): longMessage = True def test_serializer(self): user = mixer.blend('auth.User') user.set_password('<...
StarcoderdataPython
1714652
import os import pytest from ray.serve.storage.kv_store import (RayInternalKVStore, RayLocalKVStore, RayS3KVStore) def test_ray_internal_kv(serve_instance): # noqa: F811 with pytest.raises(TypeError): RayInternalKVStore(namespace=1) RayInternalKVStore(name...
StarcoderdataPython
3362873
"""Data and commands for REPL""" __all__ = ["CMDS", "MOVES", "ERRS", "META", "TITLE"] TITLE = r"""Welcome to... __/\\\\\\\\\\\\__________/\\\\\_________/\\\\\\\\\______/\\\________/\\\_ _\/\\\////////\\\______/\\\///\\\_____/\\\///////\\\___\/\\\_____/\\\//__ _\/\\\______\//\\\___/\\\/__\///\\\__\/\\\_____\/\\\...
StarcoderdataPython
171350
from __future__ import division from __future__ import print_function import json import pdb import math all_params = json.load(open('config.json')) dataset_name = all_params['dataset_name'] locals().update(all_params['experiment_setup']) locals().update(all_params[dataset_name]) tcn_params['model_params']['encod...
StarcoderdataPython
189879
<filename>Convolutional-Neural-Networks/cnn_classification.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Dec 02 13:40:22 2020 @author: ls616 """ import numpy as np import pandas as pd import matplotlib.pyplot as plt import cv2 import imutils import os from os import listdir from distutils.di...
StarcoderdataPython
89613
<filename>notion_extensions/base/props/block/link_to_page.py<gh_stars>1-10 import sys from typing import Dict, Union if sys.version_info >= (3, 8): # "from typing" in Python 3.9 and earlier from typing import Literal else: from typing_extensions import Literal from .block import Block from ...utils import pa...
StarcoderdataPython
66599
from django.utils.crypto import get_random_string from google.appengine.ext import ndb class AppConfig(ndb.Model): secret_key = ndb.StringProperty() @classmethod def get(cls): """Singleton configuration to store the Django secret key.""" chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^...
StarcoderdataPython
1634163
<reponame>campovski/hash20 class Reader: def __init__(self, filename): self.libraries = [] with open(filename, 'r') as f: first_line = f.readline().split() self.B = int(first_line[0]) self.L = int(first_line[1]) self.D = int(first_line[2]) ...
StarcoderdataPython
1731630
'''Trains a convolutional neural network on sample images from the environment using neuroevolution to maximize the ability to discriminate between input images. Reference: Koutnik, Jan, <NAME>, and <NAME>. "Evolving deep unsupervised convolutional networks for vision-based reinforcement learning." Proceedings of the ...
StarcoderdataPython
3374274
""" Read in a process Dee Bore data Author: jpolton Date: 26 Sept 2020 Conda environment: coast + requests, (E.g. workshop_env w/ requests) ### Build python environment: ## Create an environment with coast installed yes | conda env remove --name workshop_env yes | conda create --name workshop_...
StarcoderdataPython
1655527
<reponame>mrinaald/flower from typing import Tuple, Union, List import numpy as np from sklearn.linear_model import LogisticRegression import openml XY = Tuple[np.ndarray, np.ndarray] Dataset = Tuple[XY, XY] LogRegParams = Union[XY, Tuple[np.ndarray]] XYList = List[XY] def get_model_parameters(model: LogisticRegress...
StarcoderdataPython
103450
<gh_stars>100-1000 try: from overlays import builder builder.compile() builder.copy() except: pass import distribute_setup import io import sys import platform distribute_setup.use_setuptools() from setuptools import setup, Extension, find_packages open_as_utf8 = lambda x: io.open(x, encoding='utf-8')...
StarcoderdataPython
3379217
# -*- coding: utf-8 -*- """Test data integrity.""" import re import unittest import bioregistry import pandas as pd from compath_resources.resources import ( get_decopath_df, get_kegg_reactome_df, get_kegg_wikipathways_df, get_pathbank_kegg_df, get_pathbank_reactome_df, get_pathbank_wikipathways_df, get_rea...
StarcoderdataPython
1619136
<filename>kydavra/LassoSelector.py ''' Created with love by Sigmoid @Author - <NAME> - <EMAIL> ''' # Importing all needed libraries import numpy as np import matplotlib.pyplot as plt from sklearn.linear_model import lasso_path, LassoCV def warn(*args, **kwargs): pass import warnings warnings.warn = war...
StarcoderdataPython
1662038
"""Plot utilities for the DESI ETC. Requires that matplotlib is installed. """ import datetime import copy # for shallow copies of matplotlib colormaps try: import DOSlib.logger as logging except ImportError: # Fallback when we are not running as a DOS application. import logging import numpy as np impo...
StarcoderdataPython
3233453
# Generated by Django 2.0.13 on 2021-08-08 15:30 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("ddcz", "0101_remove_taverntablenoticeboard_id"), ] operations = [ migrations.AlterModelOptions( name="posta", optio...
StarcoderdataPython
160695
<filename>src/lib/imaplib.py<gh_stars>1-10 raise NotImplementedError("imaplib is not yet implemented in Skulpt")
StarcoderdataPython
1690805
<reponame>andrinelo/lego<gh_stars>0 # -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-09-08 16:51 from __future__ import unicode_literals import re import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tags', '0001_in...
StarcoderdataPython
3232369
from sqlalchemy import ( Column, Integer, SmallInteger, String, DateTime, Float, Boolean, Text, ARRAY, ) from sqlalchemy.ext.declarative import declarative_base from database_pg.utils import Mixin DeclarativeBase = declarative_base(cls=Mixin) def create_table(engine): Declarat...
StarcoderdataPython
116206
<filename>MFSDA/Resources/Libraries/stat_lpks_wob.py """ Local linear kernel smoothing for optimal bandwidth selection. Author: <NAME> (<EMAIL>) Last update: 2017-08-14 """ from __future__ import division import numpy as np from numpy.linalg import inv from stat_kernel import ep_kernel """ installed all the librarie...
StarcoderdataPython
1691986
<gh_stars>1-10 # -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import absolute_import # def get_package_data(): # """Get Package Data for utilipy.math""" # return {'utilipy.math': ['data/*']}
StarcoderdataPython
32055
<reponame>kthy/wren # -*- coding: utf-8 -*- """Gettext manipulation methods.""" from os import remove from os.path import exists from pathlib import Path from shutil import copyfile, copystat from typing import Sequence from filehash import FileHash from polib import MOFile, POFile, mofile from wren.change import Ch...
StarcoderdataPython
3384141
<reponame>PacktPublishing/GettingStartedwithPythonfortheInternetofThings- import cv2 import numpy as np # Load face cascade file frontalface_cascade= cv2.CascadeClassifier('haarcascade_frontalface_alt.xml') # Check if face cascade file has been loaded if frontalface_cascade.empty(): raise IOError('Unable to load the...
StarcoderdataPython
93241
<reponame>andrrizzi/tfep-revisited-2021 #!/usr/bin/env python # ============================================================================= # MODULE DOCSTRING # ============================================================================= """ Test objects and function in functions.transformer. """ # ============...
StarcoderdataPython
92778
<reponame>djgroen/flee-release import flee.flee as flee import datamanager.handle_refugee_data as handle_refugee_data import numpy as np import outputanalysis.analysis as a """ Generation 1 code. Incorporates only distance, travel always takes one day. """ if __name__ == "__main__": print("Testing basic data handli...
StarcoderdataPython
1613763
<gh_stars>0 import dynet as dy import numpy as np import numbers from typing import Any, List, Sequence, Union import xnmt.batchers as batchers import xnmt.event_trigger as event_trigger import xnmt.events as events import xnmt.input_readers as input_readers import xnmt.search_strategies as search_strategies import x...
StarcoderdataPython
31501
import re, requests, bs4, unicodedata from datetime import timedelta, date, datetime from time import time # Constants root = 'https://www.fanfiction.net' # REGEX MATCHES # STORY REGEX _STORYID_REGEX = r"var\s+storyid\s*=\s*(\d+);" _CHAPTER_REGEX = r"var\s+chapter\s*=\s*(\d+);" _CHAPTERS_REGEX = r"Chapters:\s*(\d+)\...
StarcoderdataPython
3206865
<gh_stars>1-10 from BaseScouting.views.base_views import BaseSingleMatchView from Scouting2013.model.reusable_models import Match from Scouting2013.model.models2013 import ScoreResult class SingleMatchView2013(BaseSingleMatchView): def __init__(self): BaseSingleMatchView.__init__(self, Match, 'Scouting20...
StarcoderdataPython
3302690
<filename>handler.py from dataclasses import dataclass import asyncio from . import types class Handler: def __init__(self): self.handlers = [] def register(self, handler, kwargs): record = Handler.HandlerObj(handler=handler, filters=kwargs) self.handlers.append(record) async def...
StarcoderdataPython
171294
#!/usr/bin/python # # Copyright 2022 DeepMind Technologies Limited # # 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 a...
StarcoderdataPython
1683941
<gh_stars>0 # define settings IMAGE_UPLOAD_SIZE = (1600, 1200) # image upload size IMAGE_QUALITY = 85 # image quality AMOUNT_ARTICLES_HOME_PAGE = 5 # amount of news on home page
StarcoderdataPython
3240151
#!/usr/bin/env python3 from os import walk from os.path import join, splitext from re import compile regex_bad_include = compile(r"^\s*#\s*include\s*<(ieompp/.*\.hpp)>\s*$") if __name__ == "__main__": for root, _, files in walk("include/ieompp"): for file in files: path = join(root, file) ...
StarcoderdataPython
1796910
<filename>segelectri/data_loader/utils/parse_img_op.py # coding=utf-8 import tensorflow as tf import tensorflow_io as tfio def decode_image(path: tf.Tensor): """decode fn for tiff, png, jpg, bmp, giff format Args: path (tf.Tensor): path for this image """ decode_fns = [tf.image.decode_image, ...
StarcoderdataPython
3357839
def patch(): if patch._initialized: return patch._initialized = True import gevent.monkey gevent.monkey.patch_all() import sys if sys.version_info.major < 3: _py2_patches() _export() patch._initialized = False def _export(): import lymph lymph.__version__ = '0....
StarcoderdataPython
55575
<gh_stars>0 class Solution: def maxNumEdgesToRemove(self, n: int, edges: List[List[int]]) -> int: answer=0 aliceVisited=[0]*(n+1) bobVisited=[0]*(n+1) aliceSet={} aliceSetNum=1 bobSet={} bobSetNum=1 # Return False if this edge can be deleted...
StarcoderdataPython