id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
3334314
<gh_stars>0 # -*- coding:utf-8 -*- """ Example settings for local development Use this file as a base for your local development settings and copy it to umap/settings/local.py. It should not be checked into your code repository. """ from umap.settings.base import * # pylint: disable=W0614,W0401 PROJECT_DIR = os....
StarcoderdataPython
191047
<filename>eval_snippet.py import argparse import numpy as np KITTI_PATH = './kitti-odom-eval/dataset/kitti_odom/gt_poses/' class Pose_processor(object): def __init__(self): pass @staticmethod def abs2rel_poses(poses): """ poses: T{1_w}, T{2_w}, ..., T{n_w} ...
StarcoderdataPython
3356362
import time import datetime import os from django.conf import settings from django.core.management.base import NoArgsCommand from amazon.models import S3UploadQueue from amazon.utils import purge_queue class Command(NoArgsCommand): help = "Uploads video to s3 and deletes it from the server." def handle_noar...
StarcoderdataPython
3683
<reponame>hashnfv/hashnfv-moon<gh_stars>0 # Copyright 2014 IBM Corp. # # 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...
StarcoderdataPython
125935
<reponame>macaurther/DOCUSA from CvPythonExtensions import * from Consts import * import CvUtil gc = CyGlobalContext() class CvPediaImprovement: def __init__(self, main): self.iImprovement = -1 self.top = main self.X_INFO_PANE = self.top.X_PEDIA_PAGE self.Y_INFO_PANE = self.top.Y_PEDIA_PAGE self.W_INFO...
StarcoderdataPython
139732
#kullanıcıdan alınan bir sayının tek mi ya da çift mi olduğunu bulan kodu yazınız sayi = int(input("Bir Sayı Giriniz : ")) if sayi%2==0: print(" Sayısı Çift Sayıdır. ",sayi) else: print(" Sayısı Tek Sayıdır. ",sayi )
StarcoderdataPython
1669456
<gh_stars>0 ''' Discovery document generation. { "kind": "discovery#directoryList", "discoveryVersion": "v1", "items": [ { "kind": "discovery#directoryItem", "id": string, "name": string, "version": string, "title": string, "description": string, "discoveryRestUrl":...
StarcoderdataPython
3278560
import lldb import os import shlex import optparse def __lldb_init_module(debugger, internal_dict): debugger.HandleCommand('command script add -f vcl.handle_command vcl -h "Short documentation here"') def handle_command(debugger, command, exe_ctx, result, internal_dict): debugger.HandleCommand("pipe find_labe...
StarcoderdataPython
123938
#!/usr/bin/python import glob import argparse import os import sys from psnr_analyzer import PsnrAnalyzer from report_manager import ReportData, ReportManager from transcoder import Transcoder from configuration import prepare_config def prepare_output_dir(output_dir): if os.path.exists(output_dir): ...
StarcoderdataPython
158365
<reponame>Ziggareto/cs229 import matplotlib import matplotlib.pyplot as plt import numpy as np import os PLOT_COLORS = ['red', 'green', 'blue', 'orange'] # Colors for your plots K = 4 # Number of Gaussians in the mixture model NUM_TRIALS = 3 # Number of trials to run (can be adjusted for debugging) UNLABEL...
StarcoderdataPython
1697419
import torch.nn as nn import torch.nn.functional as F import math from .conversions import * from .grids import * from .icosahedron_functions import * from .spherical_projections import forward_gnomonic_projection, inverse_gnomonic_projection from .util import points_in_triangle_2d import _spherical_distortion_ext._m...
StarcoderdataPython
3228426
<reponame>sideroff/python-exercises<gh_stars>0 list_input = list(input("Choose a list of numbers separated by ', ': ").split(", ")) value_input = input("Choose a value to look for in the provided list: ") print("Value is %spresent in list." % ("" if value_input in list_input else "not "))
StarcoderdataPython
190577
<reponame>am0s/docker-register<filename>register.py #!/usr/bin/python import argparse import sys import os import etcd import json def load_config(): # We use a Python file as the config to make it easier with trailing commas import etcd_config return etcd_config def send_config(client, config, host=Non...
StarcoderdataPython
3276143
import json from django.utils.dateformat import DateFormat from seahub.share.models import UploadLinkShare from seahub.test_utils import BaseTestCase class SharedUploadLinksTest(BaseTestCase): def tearDown(self): self.remove_repo() def test_can_list(self): ls = UploadLinkShare.objects.create...
StarcoderdataPython
1670799
<reponame>matheusmatos/django-rest-models<filename>rest_models/tests/test_systemcheck.py # -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals import copy import logging import six from django.core.management import call_command from django.core.management.base import System...
StarcoderdataPython
1703794
<filename>data/plugins/radio.py from typing import TYPE_CHECKING from discord import Message, Guild, PermissionOverwrite, CategoryChannel from rpbot.data.roleplay import Roleplay from rpbot.plugin import Plugin, PluginCommandParam if TYPE_CHECKING: from rpbot.bot import RoleplayBot RADIO_CMD = 'radio' RADIO_SET...
StarcoderdataPython
3331312
from mycroft import MycroftSkill, intent_file_handler, intent_handler import requests from mycroft.skills.core import resting_screen_handler from adapt.intent import IntentBuilder from mtranslate import translate from datetime import datetime, timedelta class NatGeoPictureOfThedaySkill(MycroftSkill): def update_...
StarcoderdataPython
13065
import logging import threading from concurrent.futures import ThreadPoolExecutor from multiprocessing import Queue from foreverbull.worker.worker import WorkerHandler from foreverbull_core.models.finance import EndOfDay from foreverbull_core.models.socket import Request from foreverbull_core.models.worker import Inst...
StarcoderdataPython
4802393
import gpioRap as gpioRap import RPi.GPIO as GPIO print "An example of gpioRap, when the button is pressed it will light the led, and pressed again it will turn off the led" #Create GpioRap class using BCM pin numbers gpioRapper = gpioRap.GpioRap(GPIO.BCM) #Create an LED, which should be attached to pin 17 led = gpi...
StarcoderdataPython
3291441
from imageai.Prediction import ImagePrediction import os import cv2 import pytest from os.path import dirname import keras main_folder = os.getcwd() @pytest.mark.squeezenet @pytest.mark.recognition def test_recognition_model_squeezenet(): predictor = ImagePrediction() predictor.setModelTypeAsSqueezeNet()...
StarcoderdataPython
4816397
import defaultparams.params as params import defaultparams.uconv as uconv import scipy from mod_mass import * from mod_gasdensity import * ''' Temperature profile model ''' def intmodel(nemodel, c, rs, normsersic, r_arr, clustermeta): ''' Model of the form \rho_gas * M_tot * r^-2; intended to be integrated...
StarcoderdataPython
146269
def RC(value, tolerance=5.0, power=None, package="0603",pkgcode="07"): res = {"manufacturer": "Yageo"} suffix = ['R', 'K', 'M'] digits = 3 if tolerance < 5 else 2 while value >= 1000: value = value/1000. suffix.pop(0) suffix = suffix[0] whole = str(int(value)) decimal = str(...
StarcoderdataPython
3303109
import plotly.graph_objs as go from _plotly_utils.basevalidators import ColorscaleValidator from ._core import apply_default_cascade, init_figure, configure_animation_controls from .imshow_utils import rescale_intensity, _integer_ranges, _integer_types import pandas as pd import numpy as np import itertools from plotly...
StarcoderdataPython
4807070
import numpy as np import pandas as pd import matplotlib.pyplot as plt import GoogleTrend import RoadSection import bpnn import dynamic_bpnn import time # Load Data----------------------------------------------------- gt = GoogleTrend.GoogleTrend('multiTimeline.csv') gt.load() gt.normalize() rs = RoadSection.RoadSect...
StarcoderdataPython
3202128
<reponame>sotetsuk/paper2img # -*- coding: utf-8 -*- """Convert academic papers (pdf) to nice thumbnail (png) Usage: paper2tmb stack [--trim=<trim>] [--size=<size>] <input-file> <output-file> <num-col> <num-row> paper2tmb top [--density=<density>] [--trim=<trim>] [--size=<size>] [--reduce=<reduce>] <input-file> <...
StarcoderdataPython
3219253
"""added invoice line model Revision ID: <KEY> Revises: <PASSWORD> Create Date: 2016-06-22 13:53:08.301888 """ # revision identifiers, used by Alembic. revision = '<KEY>' down_revision = '<PASSWORD>' from alembic import op import sqlalchemy as sa def upgrade(): op.create_table('lines', sa.Column('id', sa....
StarcoderdataPython
124016
<reponame>kura-Lee/meiduo-mall from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData from django.conf import settings def generate_verify_email_url(user): """ 生成邮箱验证链接 :param user: 当前登录用户 :return: verify_url """ serializer = Serializer(settings.SECRET_KEY, expires_in=3...
StarcoderdataPython
1678915
""" When analysing data collected as part of a science experiment it may be desirable to remove the most extreme values before performing other calculations. Write a function that takes a list of values and an non-negative integer, n, as its parameters. The function should create a new copy of the list with the n large...
StarcoderdataPython
1785133
<reponame>evernym/indy-plenum from collections import OrderedDict from copy import deepcopy from random import randint, choice from plenum.common.util import randomString from state.db.persistent_db import PersistentDB from state.trie.pruning_trie import Trie, rlp_encode, rlp_decode from storage.kv_in_memory import Ke...
StarcoderdataPython
30057
<reponame>panda361/nonebot-hk-reporter from .bilibili import Bilibili from .rss import Rss from .weibo import Weibo from .utils import check_sub_target from .platform import PlatformNoTarget from .utils import platform_manager
StarcoderdataPython
1660071
<reponame>kofu145/voicetext-python<filename>voicetext.py import requests url = "https://api.voicetext.jp/v1/tts" # Errors: class textVoiceError(Exception): """Error with API request""" pass class fileFormatError(Exception): """Invalid file format""" pass class voice_text: def __init__(self, API_KEY, text, spe...
StarcoderdataPython
3354853
<reponame>bakerwm/goldclip #!/usr/bin/env python """ Trimming reads 1. cut 3-adapter 2. trim low quality bases 3. remove N reads 4. trim N-bases from either ends of reads 5. limit read length """ __author__ = "<NAME>" __email__ = "<EMAIL>" __date__ = "2018-03-21" __version__ = "0.1" from goldclip.goldcliplib.trim im...
StarcoderdataPython
4803459
#!/usr/bin/env python # -*- coding: UTF-8 -*- # pylint:disable=bad-whitespace # pylint:disable=line-too-long # pylint:disable=too-many-lines # pylint:disable=invalid-name # ######################################################### # # ************** !! WARNING !! *************** # ******* THIS FILE WAS A...
StarcoderdataPython
1708389
<reponame>mikoblog/splitio-requests # -*- coding: utf-8 -*- """Splits endpoint classes Requests and Response classes for Splits endpoint """ import logging from typing import Dict, Optional, Iterator, Union, NoReturn import jsonpatch from requests import Response, Session log = logging.getLogger('splitiorequests') ...
StarcoderdataPython
3244084
<reponame>peopledoc/ml-versioning-tools from os.path import join, exists from mlvtools.conf.conf import DEFAULT_CONF_FILENAME from mlvtools.ipynb_to_python import IPynbToPython from tests.helpers.utils import gen_notebook from tests.helpers.utils import write_conf def test_should_handle_notebook_with_invalid_python_...
StarcoderdataPython
1782563
#! /usr/bin/python3.5 import socket from rpc_core.codec.rpc_encoder import BaseEncoder from rpc_core.codec.rpc_decoder import BaseDecoder class Bio_Connector(object): def __init__(self, tcp_ip, tcp_port): self.tcp_ip = tcp_ip self.tcp_port = tcp_port self.sk = None def __enter__(self...
StarcoderdataPython
1619167
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import subprocess fr...
StarcoderdataPython
178162
import unittest import tensorflow as tf import fastestimator as fe import fastestimator.test.unittest_util as fet class TestReflectionPadding2D(unittest.TestCase): def setUp(self): self.x = tf.reshape(tf.convert_to_tensor(list(range(9))), (1, 3, 3, 1)) def test_reflection_padding_2d_double_side(sel...
StarcoderdataPython
3249707
<gh_stars>0 # -*- coding: utf-8 -*- # # Copyright (c) 2019~2999 - Cologler <<EMAIL>> # ---------- # # ---------- import sys import os import pytest from fsoopify import Path on_win = pytest.mark.skipif(os.name != 'nt', reason="only run on windows") on_unix = pytest.mark.skipif(os.name == 'nt', reason="only run on u...
StarcoderdataPython
131464
import os import itertools from ipykernel import kernelspec as ks import nbformat from nbformat.v4.nbbase import new_markdown_cell from generate_contents import NOTEBOOK_DIR, REG, iter_notebooks, get_notebook_title def prev_this_next(it): a, b, c = itertools.tee(it, 3) next(c) return zip(itertools.chain...
StarcoderdataPython
103125
# ------------------------------------------------------------------------------------ # Tutorial: Learn how to use Dictionaries in Python # ------------------------------------------------------------------------------------ # Dictionaries are a collection of key-value pairs. # Keys can only appear once in a dictiona...
StarcoderdataPython
192904
# Travel club # A group of people are member of a travel club. # The group shares expenses equally but it is not practical to share every expense as they happen, so all expenses are collated (such as taxis, train tickets etc) after the trip # The member cost is shared to within 1% between the group. # Create a prog...
StarcoderdataPython
3326466
from game_functions import random_move, move_down, move_left, move_right, move_up, add_new_tile POSSIBLE_MOVES = [move_left, move_up, move_down, move_right] def generation_algorithm (board, number_of_genoms, length_of_genom): genoms = [] for _ in range(number_of_genoms): genome = [] scoreTot...
StarcoderdataPython
193115
from regulations.generator.section_url import SectionUrl from regulations.generator.toc import fetch_toc def get_labels(current): return current.split('-') def _add_extra(el, version): """Add extra fields to a TOC element -- only added to elements we will use for prev/next""" if el.get('is_section')...
StarcoderdataPython
4815368
from django.conf import settings from django.conf.urls import url, include from django.conf.urls.static import static from django.contrib import admin from django.views.generic import RedirectView urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^about/', include('about_us.urls')), url(r'^book_a_tab...
StarcoderdataPython
1724038
""" Module For the ListParser """ import argparse from conjur.argument_parser.parser_utils import command_description, command_epilog, formatter, \ title_formatter from conjur.wrapper.argparse_wrapper import ArgparseWrapper # pylint: disable=too-few-public-methods class ListParser: """Partial class of the ArgP...
StarcoderdataPython
3394355
# encoding=utf-8 # author : <EMAIL> # date: 2014-06-20 # version: 0.1 # 写入: alllinkfile notsinglelinkfile alllinkstrfile : 作者发布的tweet @ 其他作者图 # 通过tweet之间的@关系,得到需要的信息 import numpy if __name__ == "__main__": # 输入: authornamefilename = "../Output/author.name" contentfilename = "../Output/content" pubd...
StarcoderdataPython
4831002
import os, pytest os.environ['APP_ENV'] = 'test' from api import create_app, db from sqlalchemy import create_engine @pytest.yield_fixture def app(): app = create_app('test') yield app @pytest.fixture def test_cli(loop, app, test_client): return loop.run_until_complete(test_client(app)) def reset_db()...
StarcoderdataPython
3339123
import yaml def load_yaml(yaml_file: str) -> dict: """Function to load the configuration from a YAML file into a python dictionary Parameters: yaml_file {str} -- The path for the YAML file. Returns: A dictionary containing the configuration information. """ file_stream = open(yaml_file,...
StarcoderdataPython
18850
<reponame>Kugeleis/TeslaInventoryChecker import http.client import json from types import SimpleNamespace def get_token(): conn = http.client.HTTPSConnection("www.tesla.com") payload = { "resource": "geocodesvc", "csrf_name": "", "csrf_value": "" } headers = { 'Content-T...
StarcoderdataPython
159769
<filename>reviewboard/accounts/tests/test_privacy_form.py """Unit tests for reviewboard.accounts.forms.pages.PrivacyForm.""" from __future__ import unicode_literals from django.contrib.auth.models import User from django.test.client import RequestFactory from reviewboard.accounts.forms.pages import PrivacyForm from ...
StarcoderdataPython
1703546
from TwitterAPI import TwitterAPI keys = dict( consumer_key="", consumer_secret="", access_token_key="", access_token_secret="", ) api = TwitterAPI(**keys)
StarcoderdataPython
3378281
""" Protorpc messages for video comment API """ from protorpc import messages from django_protorpc import DjangoProtoRPCMessage, nest_message from greenday_core.models import TimedVideoComment from ..comment.messages import CommentUserResponse, CommentResponseMessageSlim class VideoCommentResponseMessageSlim(Dj...
StarcoderdataPython
3305986
# import random # from exercises.data import get_data # users = get_data(5) # # # # print users type # print(type(users)) # # # get the first user # user = users[0] # # # print its type # print(type(user)) # # # view users # for user in users: # print(user) # # # view the second user # print(users[1]) # # names = [...
StarcoderdataPython
3317763
<gh_stars>1-10 whitelisted_name = ["name1", "name2","name3"] #enter the whitelisted items(names,items,codes etc...) name = input("Enter your name ") #takes user input as assigns it as variable "name" if name in whitelisted_name: #checks if the input you entere...
StarcoderdataPython
1609799
#!/usr/bin/env python import os from setuptools import find_packages, setup def read(filename): with open(os.path.join(os.path.dirname(__file__), filename)) as f: return f.read() setup( name="wagtail-link-block", version="0.1.4", description="Wagtail LinkBlock", long_description=read("R...
StarcoderdataPython
140018
<gh_stars>0 #AUTHOR: Kevin ## CHALLENGE - create 3 more classifiers... #1 Random Forest #2 Multi-layer Perceptron #3 Support Vector Machine #comparison #Try cross validation since we have a small dataset from sklearn.model_selection import cross_val_score #enable preprocessing (for MLP) under cross-validation from s...
StarcoderdataPython
82956
import os import gzip import time import copy import random import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import Dataset, DataLoader from torchvision import transforms fro...
StarcoderdataPython
145615
# -*- coding: utf-8 -*- # Copyright (c) 2012 by <NAME> <<EMAIL>> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version...
StarcoderdataPython
1709362
""" test_string_from_grant.py -- Given a URI of a grant, return a string describing the grant Version 0.1 MC 2013-12-27 -- Initial version. """ __author__ = "<NAME>" __copyright__ = "Copyright 2013, University of Florida" __license__ = "BSD 3-Clause license" __version__ = "0.1" impor...
StarcoderdataPython
98862
# Generated by Django 3.2.12 on 2022-03-18 19:43 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('regions', '0001_initial'), ('authors', '0001_initial'), ('articles', '0001_initial'), ...
StarcoderdataPython
142654
# -*- coding: utf-8 -*- """ RabbitMQ backend specific settings module. """ from __future__ import unicode_literals from django_event.backends.base.settings import * HOST = HOST or 5672 VIRTUAL_HOST = settings.BACKEND_OPTIONS.get('VIRTUAL_HOST', '') USERNAME = settings.BACKEND_OPTIONS.get('USERNAME', '') QUEUE_NAME...
StarcoderdataPython
3359981
import requests import lxml.html from collections import namedtuple # named tuples: # used for parsed data and themes Date = namedtuple('Date', ['year' # e.g. '2018' ,'season' # '01'-'03' which means 3rd season ,'season_name' # e.g. 'Bahar' or 'Spring' ...
StarcoderdataPython
1642523
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2016-11-28 08:17 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('exercises', '0003_auto_20161128_1753'), ] operatio...
StarcoderdataPython
1618587
from floodsystem.stationdata import build_station_list from floodsystem.station import inconsistent_typical_range_stations def run(): """Requirements for Task 1A""" # Build list of stations stations = build_station_list() itrs = inconsistent_typical_range_stations(stations) print(itrs) run()
StarcoderdataPython
3365554
#coding:utf-8 # # id: bugs.core_3965 # title: Creating a procedure containing "case when" expression leads to a server crash # decription: # tracker_id: CORE-3965 # min_versions: ['3.0'] # versions: 3.0 # qmid: None import pytest from firebird.qa import db_factory, isql_act, Action #...
StarcoderdataPython
103397
#New Solitaire for decisions import solitaireCipher import precipher class idk(solitaireCipher.Deckinator): def countCut2(self, number=0): try: self.countCut() except TypeError: return self.deck[-1] def getOut2(self): number = self.deck[0] ...
StarcoderdataPython
1732858
<reponame>IlyaBizyaev/ttools """Common image operators.""" import numpy as np import torch as th def crop_like(src, tgt): """Crop a source image to match the spatial dimensions of a target. Assumes sizes are even. Args: src (th.Tensor or np.ndarray): image to be cropped tgt (th.Tensor or...
StarcoderdataPython
1617643
<reponame>TugberkArkose/MLScheduler power = {'BUSES': {'Area': 1.33155, 'Bus/Area': 1.33155, 'Bus/Gate Leakage': 0.00662954, 'Bus/Peak Dynamic': 0.0, 'Bus/Runtime Dynamic': 0.0, 'Bus/Subthreshold Leakage': 0.0691322, 'Bus/Subthreshold Leakage with power ...
StarcoderdataPython
42390
salario = float(input('Qual o seu salario: ')) aumento = salario*1.15 print('O seu salário de R${:.2f} recebeu um aumento de 15% seu novo salário é R${:.2f}'.format(salario, aumento))
StarcoderdataPython
3324349
""" Create a new VGG19 class, without the redundant final layers. Also replace all max pooling with avg pooling""" # import os import tensorflow as tf # import numpy as np import time # import inspect import vgg19 VGG_MEAN = [103.939, 116.779, 123.68] class Vgg19(vgg19.Vgg19): def build(self, rgb, reset_dict ...
StarcoderdataPython
3207725
<filename>src/speeder/feature/feature_utils.py import os import pandas as pd import numpy as np from hydra import utils import itertools from sklearn import preprocessing class FeatureFactory: def __init__(self, configs: dict, cv=None): self.run_name = configs['exp_name'] self.data = configs.data ...
StarcoderdataPython
4824525
<gh_stars>0 import torch import math import os import time import json import logging from torchmeta.utils.data import BatchMetaDataLoader from maml.datasets import get_benchmark_by_name from maml.metalearners import ModelAgnosticMetaLearning import argparse
StarcoderdataPython
1777497
<filename>pdn.py # -*- coding:utf-8 -*- # Copyright (c) 2011 <NAME>, renato.ppontes at gmail dot com # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including witho...
StarcoderdataPython
3393196
# Smoothed-particle hydrodynamics (SPH) is a computational method used for simulating the mechanics of continuum media, such as solid mechanics and fluid flows. # Here we utilize SPH to simulate a fountain, who tries to hit a target given by the user. # The SPH simulator here implemented using Taichi is differentiabl...
StarcoderdataPython
1664261
from django.contrib import admin from .models import Quote admin.site.register(Quote)
StarcoderdataPython
128610
<reponame>andrewp-as-is/travis-env.py<filename>travis_env/clear.py<gh_stars>0 #!/usr/bin/env python """clear all environment variables""" import travis_env import click MODULE_NAME = "travis_env.clear" PROG_NAME = 'python -m %s' % MODULE_NAME USAGE = 'python -m %s repo' % MODULE_NAME @click.command() @click.argument...
StarcoderdataPython
50088
from core.config import app_config import json import datetime import logging import os from flask import Flask, render_template, Response, request, send_from_directory from core import compat, app, utils from core.ctrl import api, auth compat.check_version() webapp = Flask(__name__) app.mode = 'http' @webapp.route(...
StarcoderdataPython
91900
""" 1025. Divisor Game Easy Alice and Bob take turns playing a game, with Alice starting first. Initially, there is a number N on the chalkboard. On each player's turn, that player makes a move consisting of: Choosing any x with 0 < x < N and N % x == 0. Replacing the number N on the chalkboard with N - x. Also, if...
StarcoderdataPython
1609935
<gh_stars>0 from io import TextIOBase import os.path import operator from itertools import combinations, permutations from functools import reduce, partial from math import isfinite, prod from collections import Counter, defaultdict import re INPUT=os.path.join(os.path.dirname(__file__), "input.txt") with open(INPUT) ...
StarcoderdataPython
132408
''' Created on 2016年1月22日 @author: Darren ''' ''' Given N integers, count the number of pairs of integers whose difference is K. Input Format The first line contains N and K. The second line contains N numbers of the set. All the N numbers are unique. Output Format An integer that tells the number of pairs of int...
StarcoderdataPython
3230419
<filename>shell.py<gh_stars>0 import sys from download import download import argparse import os def valid_dir(path): if not os.path.isdir(path): raise argparse.ArgumentTypeError('{} is not an existing directory'.format(path)) if not path.endswith(os.sep): path += os.sep return path parser = argp...
StarcoderdataPython
4835054
""" Most of these tests are directly migrated from mozilla-central's reference implementation. """ import copy from nose.tools import eq_ from product_details.version_compare import ( Version, version_list, version_dict, version_int) # Versions to test listed in ascending order, none can be equal. # TODO Add su...
StarcoderdataPython
37459
from brownie import Lottery, accounts, config, network from web3 import Web3 def printStuff(): account = accounts[0] lottery = Lottery.deploy( config["networks"][network.show_active()]["eth_usd_price_feed"], config["networks"][network.show_active()]["gbp_usd_price_feed"], {"from": acco...
StarcoderdataPython
4804895
from django import forms from django.contrib.auth.models import AbstractUser, User from django.core.validators import FileExtensionValidator from django.db import models class Usuario(AbstractUser): imagen_perfil = models.ImageField( validators=[FileExtensionValidator(["jpg", "png"])], upload_to="imagenesP...
StarcoderdataPython
2916
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations from dataclasses import dataclass from enum import Enum from typing import Any, Iterable, cast from pants.core.util_rules.lockfile_metadata import ( ...
StarcoderdataPython
3289826
<filename>bdd/features/steps/activate_account.py from behave import * # Common to this feature @when('I visit my activation page "{url}"') def impl(context, url): context.browser.visit(context.config.server_url + '/accounts/activate/' + url ) # Unique to Scenario: Invited user visits page to activate account @t...
StarcoderdataPython
1673052
<reponame>flameshikari/ddrg from public import * # noqa def init(): array = [] base_url = "https://mirror.yandex.ru/ubuntu-cdimage/xubuntu/releases" html = bs(requests.get(base_url).text, "html.parser") for version in html.find_all("a", {"href": re.compile("^[a-z].*/$")}): pat...
StarcoderdataPython
11804
from tweepy import StreamListener, OAuthHandler, Stream from configs import Configs import sys class StdOutListener(StreamListener): def __init__(self, kafka_producer, topic): super().__init__() self.kafka_producer = kafka_producer self.topic = topic """ A listener handles tweets tha...
StarcoderdataPython
144332
<reponame>EmixMaxime/mx-home-security from enum import Enum class MqttServices(Enum): CAMERA_MANAGER = 'camera_manager' CAMERA = 'camera'
StarcoderdataPython
186117
<gh_stars>0 #!/usr/bin/env python3 # -*- coding: utf-8 -*- from collections import namedtuple import numpy from apppath import ensure_existence from sklearn.multiclass import OneVsRestClassifier from sklearn.preprocessing import LabelBinarizer from draugr.visualisation import confusion_matrix_plot, roc_plot from mu...
StarcoderdataPython
78131
<filename>utils/pipeline_compilers.py from functools import lru_cache import sass from django.conf import settings from django.contrib.staticfiles.finders import get_finders from pipeline.compilers import CompilerBase from .sass_functions.svg_to_data_uri import svg_to_data_uri def svg_to_data_uri_(file_): retur...
StarcoderdataPython
29740
<gh_stars>1-10 #!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import print_function from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from django.core.exceptions import ValidationError def between_zero_and_one_hundred(value): if value < 0 or...
StarcoderdataPython
3398168
<reponame>ColinDowney/MemN2N-babi-python<filename>demo-wins/form.py<gh_stars>0 import PySimpleGUI as sg import glob import numpy as np from demo.qa import MemN2N from util import parse_babi_task sg.theme('DarkAmber') # Add a touch of color # All the stuff inside your window. layout = [[sg.Text('babi数据集算法演示')], ...
StarcoderdataPython
1704390
#!/usr/bin/python """ utils.py - Utilities for reporting xm-test results Copyright (C) International Business Machines Corp., 2005 Author: <NAME> <<EMAIL>> This program 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...
StarcoderdataPython
3351566
<filename>flask_card/auth/forms.py """ Sign up and Login form """ from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField from wtforms.validators import DataRequired, Email, EqualTo, Length class SignupForm(FlaskForm): """ User Sign up """ name = StringField("Name", valida...
StarcoderdataPython
3289119
<filename>custom_featurizer.py import numpy as np from nltk.corpus import stopwords from similarity_scoring import SimilarityJaccard from nltk.tokenize import word_tokenize import seaborn as sns import matplotlib.pyplot as plt sns.set(color_codes=True) class CustomFeaturizer: def __init__(self): self.stop...
StarcoderdataPython
3308063
# -*- coding: utf-8 -*- import random MAX_BLUE_STONE = 9 COLOR = "RGYBW" CARD_VALUE = [1, 1, 1, 2, 2, 3, 3, 4, 4, 5] CARD_IN_HANDS = 5 MAX_BLUE_STONE = 8 MAX_RED_STONE = 3 NO_CARD = "NC" class InvalidActionError(Exception): """Error when an invalid move is done by a player""" def __init__(self, message): ...
StarcoderdataPython
3228706
from flask import render_template,url_for,request,abort,redirect from ..models import Blogpost,User,Comments from .import main from .forms import CommentForm,PostForm,UpdateProfile from flask_login import login_required,current_user from app import db @main.route('/') def index(): '''a function to take a user to th...
StarcoderdataPython
25341
<filename>ddganAE/utils.py """ General utilities for package """ import numpy as np import keras.backend as K from keras.losses import mse __author__ = "<NAME>" __credits__ = ["<NAME>"] __license__ = "MIT" __version__ = "1.0.0" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" __status__ = "Development" def calc_po...
StarcoderdataPython