id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
3298360
#-*- coding: utf-8 -*- """ Twilio account config """ from __future__ import absolute_import, division, print_function, unicode_literals from configurations import values class Twilio(object): #: Account SID TWILIO_ACCOUNT_SID = values.SecretValue(environ_prefix=None) #: Auth token TWILIO_AUTH_TOK...
StarcoderdataPython
3394981
import os import sys import warnings import importlib import inspect import os.path as osp import numpy as np import tensorflow as tf from tensorflow.keras.utils import Sequence from tensorflow.python.keras import callbacks as callbacks_module from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint from ...
StarcoderdataPython
1759769
# Generated by Django 3.2.7 on 2021-09-10 17:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('backend', '0003_auto_20210910_0956'), ] operations = [ migrations.AddField( model_name='pixelcount', name='black_or_...
StarcoderdataPython
182290
<gh_stars>0 import pulsar as psr def load_ref_system(): """ Returns d-xylulose as found in the IQMol fragment library. All credit to https://github.com/nutjunkie/IQmol """ return psr.make_system(""" C 2.5413 -0.0840 0.1586 C 1.0785 0.2582 -0.2141 C...
StarcoderdataPython
29751
<filename>models/tree.py from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() def configure(app): db.init_app(app) app.db = db class Tree(db.Model): __tablename__ = 'tree' id = db.Column(db.Integer, primary_key=True) code = db.Column(db.String(50), nullable=False) description...
StarcoderdataPython
1779604
""" Accounts views. """ # Django from django.urls import reverse_lazy from django.contrib import messages from django.shortcuts import redirect, render from django.contrib.auth import (authenticate, login, logout, update...
StarcoderdataPython
3295162
from .common import * # noqa ALLOWED_HOSTS = [ 'maestromusicpros.com', 'www.maestromusicpros.com', #'www.djangoproject.com', #'djangoproject.com', 'www.djangoproject.localhost', #'polar-inlet-43860.herokuapp.com', #'pacific-lowlands-80447.herokuapp.com', #'docs.djangoproject.com', ...
StarcoderdataPython
42973
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import csv import numpy as np import os import sys from observations.util import maybe_download_and_extract def swahili(path): """Swahili Attitudes towards the Swahili language a...
StarcoderdataPython
1783443
<reponame>daniele21/financial_anomaly_detection<filename>core/network/encoder.py # -*- coding: utf-8 -*- import torch import torch.nn as nn class LSTM_Encoder(nn.Module): def __init__(self, in_features, reduce_factor: int, layers: int, seed: int...
StarcoderdataPython
1615479
<reponame>CYTMWIA/MyGarage<filename>GuaDao/Steam/SteamRequestsSession.py import requests import time class SteamRequestsSession(requests.sessions.Session): def __init__(self): self.last_request_time = 0 self.request_interval = 10 super().__init__() self.headers.update({ ...
StarcoderdataPython
18739
<reponame>krzysztoffiok/twitter_sentiment_to_usnavy<gh_stars>1-10 import pandas as pd import numpy as np import datatable as dt import re """ Basic pre-processing of Twitter text from SemEval2017 data set. """ # replace repeating characters so that only 2 repeats remain def repoo(x): repeat_regexp = re.compile(r'...
StarcoderdataPython
1783308
<gh_stars>1-10 # Generated by Django 2.1.3 on 2018-12-18 16:22 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app_story', '0002_auto_20181218_1619'), ] operations = [ migrations.AddField( model_name='story', nam...
StarcoderdataPython
3258733
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('auth', '0006_require_contenttypes_0002'), ('jobs', '0011_auto_20150908_1225'), ] operations = [ migrations.CreateMod...
StarcoderdataPython
118852
<gh_stars>1-10 import cv2 grayImage = cv2.imread('pic2.png', cv2.CV_LOAD_IMAGE_GRAYSCALE) cv2.imwrite('pic2Gray.png', grayImage)
StarcoderdataPython
3327849
<reponame>cyrusimap/CalDAVTester ## # Copyright (c) 2006-2016 Apple 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 # ...
StarcoderdataPython
82759
from kivy.uix.screenmanager import ScreenManager class ScreenManagement(ScreenManager): pass
StarcoderdataPython
3342214
import tempfile import os from PIL import Image from django.contrib.auth import get_user_model from django.test import TestCase from django.urls import reverse from rest_framework import serializers, status from rest_framework.test import APIClient from api.models import Business, Tag, Task from business.serializer...
StarcoderdataPython
118444
<filename>Bot/extensions/fun/level.py import hikari import lightbulb import utils from imports import * from Bot.DataBase.levelsys import DBLevel from easy_pil import Editor, Font, load_image_async, Canvas buttons = { "ison": ["Activate Level System", "Deactivate Level System"], "doubleexp": ["Activate Double...
StarcoderdataPython
1626469
from jupyterhub.auth import Authenticator from tornado import gen from traitlets import ( Unicode, Int ) import pymysql from passlib.hash import phpass class WordPressAuthenticator(Authenticator): dbhost = Unicode("localhost", config=True, help="URL or IP address of the database server") dbport = Int...
StarcoderdataPython
3237457
<reponame>kushalmangtani/grouping-content ''' https://coderpad.io/MGMYMWXZ Problem defination: This function would traverse dirPath and return a mapping of (f -> a list of files that have the exact same content as f) Examples: / /a.txt /b.bin /c.jpg /dir1/j.whatever /dir2/subdir1/q.whatever ...
StarcoderdataPython
1666415
# -*- coding: utf-8 -*- import torch # Addition:syntax 1 x = torch.ones(5, 3) y = torch.rand(5, 3) print(x + y) # Addition: syntax 2 x = torch.ones(5, 3) y = torch.rand(5, 3) result = torch.empty(5, 3) torch.add(x, y, out=result) print(result) # Addition: syntax 3, in-place x = torch.ones(5, 3) y = torch.rand(5, 3) ...
StarcoderdataPython
1675942
<reponame>HelloHiGw/sim_v1.0 import point def real2grid(rpoint_list, ratio): """ 将实际坐标系坐标点转化为栅格坐标系坐标点 :param rpoint_list: 实际坐标系坐标点列表 :param ratio: 栅格对应的实际长度 :return gpoint_list: 栅格坐标系坐标点列表 """ gpoint_list = [] for rp in rpoint_list: gp_x = rp.x//ratio + 1 gp_y = rp.y/...
StarcoderdataPython
3309935
import sys import os from pathlib import Path from datetime import datetime import logging import time from . import command_line_interface as cli from . import maxquant as mq from . import simsi_output from . import thermo_raw as raw from . import maracluster as cluster from . import tmt_processing from . import tran...
StarcoderdataPython
145780
<gh_stars>10-100 import os import re import random import torch import torch.nn.functional as F import numpy as np import scipy.sparse as sp import pandas as pd def pad_tensor(adj_nodes_list, mask=False): """Function pads the neighbourhood nodes before passing through the aggregator. Args: adj...
StarcoderdataPython
1627128
# -*- coding: utf-8 -*- """ Mapping for Artifactory apis to python objects """ __copyright__ = "Copyright (C) 2016 Veritas Technologies LLC. All rights reserved."
StarcoderdataPython
1696766
from django.apps import AppConfig class BotAdminConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'bot_admin'
StarcoderdataPython
4813221
<filename>test_falsy.py """Test the falsy module.""" import pytest import falsy @pytest.mark.parametrize('value', [ False, 'false', 'f', 'no', 'n', 'none', 'null', 'nil', ]) def test_falsy(value): """Test is_ with falsy values.""" assert falsy.is_(value) @pytest.mark.parame...
StarcoderdataPython
3276714
import requests, pandas as pd from sklearn.preprocessing import MinMaxScaler from sklearn import tree from sklearn.model_selection import train_test_split import numpy as np from pandas import DataFrame #load csv data #fields = ['Name','Median Gross Rent(monthly)','Total Household Income(yearly)','Total po...
StarcoderdataPython
3241966
<reponame>qfoxic/grapher-aws PRICING_DATABASE = {'ap-northeast-1': {'linux': {'c1.medium': 0.158, 'c1.xlarge': 0.632, 'c3.2xlarge': 0.511, 'c3.4xlarge': 1.021, 'c3.8xlarge': 2.043, ...
StarcoderdataPython
3266463
#!/usr/bin/env python3 import sys import argparse from Bio import SeqIO from gffpal.gff import GFFRecord, Strand from gffpal.attributes import GFFAttributes def cli(prog, args): parser = argparse.ArgumentParser( prog=prog, description=""" Converts a tab-separated blast-like file to a GFF3. ...
StarcoderdataPython
1796968
<reponame>sbanwart/data-science import math, random from matplotlib import pyplot as plt from collections import Counter def uniform_pdf(x): return 1 if x >= 0 and x < 1 else 0 def uniform_cdf(x): "return the probability that a uniform random variable is <= x" if x < 0: return 0 # uniform random is n...
StarcoderdataPython
3200087
from typing import Iterable Trend = Iterable[float]
StarcoderdataPython
1630236
import logging from pyferm import pyferm logging.basicConfig( format="%(asctime)s %(levelname)-10s %(message)s", level=logging.DEBUG ) p = pyferm() p.start()
StarcoderdataPython
3277052
from submission_code.nlp_tools import tokenizer from onmt.translate.translator import build_translator from argparse import Namespace import math import os def tokenize_eng(text): return tokenizer.ner_tokenizer(text)[0] def predict(invocations, model_dir, model_file, result_cnt=5): """ Function called...
StarcoderdataPython
3275990
<filename>0108-Convert-Sorted-Array-to-Binary-Search-Tree.py class Solution: def sortedArrayToBST(self, nums: List[int]) -> TreeNode: def devide(nums): if len(nums) == 0: return None midPoint = len(nums) // 2 left_list = nums[:midPoint] right_l...
StarcoderdataPython
1638898
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/utils.ipynb (unless otherwise specified). __all__ = ['first_not_na'] # Internal Cell from math import sqrt from typing import Optional, Tuple import numpy as np from numba import njit # type: ignore # Internal Cell @njit def _validate_rolling_sizes(window_size: int, ...
StarcoderdataPython
1646457
<reponame>mosiac1/OpenMetadata<gh_stars>1-10 # Copyright 2021 Collate # 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 app...
StarcoderdataPython
3373333
<gh_stars>10-100 import unittest from disklist import DiskList class TestDiskList(unittest.TestCase): def test_add(self): """ Test the + operator """ dlist1 = DiskList() dlist2 = DiskList() dlist1.append('1') dlist1.append('2') dlist2.append('3'...
StarcoderdataPython
3256776
<filename>test/config/redfish1_0_config.py<gh_stars>100-1000 from settings import * from on_http_redfish_1_0 import Configuration, ApiClient config = Configuration() config.host = 'http://{0}:{1}'.format(HOST_IP,HOST_PORT) config.host_authed = 'https://{0}:{1}'.format(HOST_IP, HOST_PORT_AUTH) config.verify_ssl = Fal...
StarcoderdataPython
3226590
def proteins(strand): pass
StarcoderdataPython
3223407
version = "0.11.33"
StarcoderdataPython
69928
from flask import Flask, url_for, redirect, request, Markup, render_template, session, flash import json, datetime import config app = Flask(__name__) app.config.from_object('config') # DISABLE DEBUG FOR PRODUCTION! app.debug = False def clear_session(): session['last_action'] = None # using session.clear()...
StarcoderdataPython
3376218
#!/usr/bin/env python3 import unittest, os from util.securechannel import SecureChannel, SecureError from util import secp256k1 AID = "B00B5111CE01" APPLET = "toys.BlindOracleApplet" CLASSDIR = "BlindOracle" mode = os.environ.get('TEST_MODE', "simulator") if mode=="simulator": from util.simulator import Simulator...
StarcoderdataPython
4828019
#!/usr/bin/python ## # This module defines the ProMP class, which is the user-facing class for deploying Probabilistic Movement Primitives. # The code for conditioning the ProMP is taken from the code by <NAME> at https://github.com/sebasutp/promp # TODO: Implement the EM based learning with NIW prior # # @author...
StarcoderdataPython
1705936
<reponame>ssin122/test-h # -*- coding: utf-8 -*- from __future__ import unicode_literals import pytest from h.groups.util import WorldGroup from h.services.groupfinder import groupfinder_service_factory from h.services.groupfinder import GroupfinderService class TestGroupfinderService(object): def test_returns...
StarcoderdataPython
1711061
<filename>urllink2.py import urllib.request, urllib.parse, urllib.error from urllib.request import urlopen from bs4 import BeautifulSoup import ssl #Ignore ssl certificate errors ctx=ssl.create_default_context() ctx.check_hostname=False ctx.verify_mode=ssl.CERT_NONE url=input("Enter- ") html=urlopen(url,context=ctx)...
StarcoderdataPython
3342093
# Copyright 2021, 2022 IBM Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to ...
StarcoderdataPython
4835507
<reponame>suetAndTie/face-generator ''' train.py Modified from https://github.com/cs230-stanford/cs230-code-examples/blob/master/pytorch/vision/train.py ''' import argparse import logging import os import numpy as np import torch import torch.optim as optim from torch.autograd import Variable from tqdm import tqdm i...
StarcoderdataPython
1762657
from . import _musicplayer async def on_ready(): _musicplayer.clear_cache_root()
StarcoderdataPython
163146
<reponame>Nuullll/llvm-test-suite<filename>litsupport/modules/codesize.py """Test module to collect code size metrics of the benchmark executable.""" from litsupport import testplan import logging import os.path def _getCodeSize(context): # First get the filesize: This should always work. metrics = {} met...
StarcoderdataPython
3246492
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param root: The root of binary tree. @return: True if this Binary tree is Balanced, or false. """ def isBalanced(self, root): i...
StarcoderdataPython
3343272
<filename>monstro/views/tests/test_pagination.py from monstro.db import Model, String import monstro.testing from monstro.views.paginators import ( Paginator, PageNumberPaginator, LimitOffsetPaginator ) class User(Model): value = String() class Meta: collection = 'users' class PaginatorTest(mo...
StarcoderdataPython
1668697
from scipy.stats import randint as sp_randint from scipy.stats import uniform as sp_uniform import numpy as np import random from sklearn.ensemble import RandomForestRegressor from sklearn.neural_network import MLPRegressor from lightgbm import LGBMRegressor class LayerSizeGenerator: def __init__(self): s...
StarcoderdataPython
1669925
<filename>algotrader/utils/trade_data.py from algotrader.model.trade_data_pb2 import * def is_buy(new_order_req: NewOrderRequest): return new_order_req.action == Buy def is_sell(new_order_req: NewOrderRequest): return new_order_req.action == Sell
StarcoderdataPython
9856
import pytest from aiospamc.client import Client from aiospamc.exceptions import ( BadResponse, UsageException, DataErrorException, NoInputException, NoUserException, NoHostException, UnavailableException, InternalSoftwareException, OSErrorException, OSFileException, CantCre...
StarcoderdataPython
3258231
import sys import os import csv import numpy as np import utils from utils import error import describe import histogram import file import logreg_train housenames = ["Ravenclaw", "Slytherin", "Gryffindor", "Hufflepuff"] def usage(): error('%s [dataset] [theta dataset]' % sys.argv[0]) def logreg_predict(feature...
StarcoderdataPython
195441
from nornir import InitNornir from nornir_utils.plugins.functions import print_result from nornir_netmiko import netmiko_send_command def send_command(task): task.run(task=netmiko_send_command, command_string="set cli complete-on-space off") task.run(task=netmiko_send_command, command_string="show ip interfac...
StarcoderdataPython
1743311
from taurex.core import Singleton from taurex.log import Logger import inspect import pkg_resources class ClassFactory(Singleton): """ A factory the discovers new classes from plugins """ def init(self): self.log = Logger('ClassFactory') self.extension_paths = [] self.rel...
StarcoderdataPython
1630072
# vim: set ts=4 sw=4 expandtab: from libtimesheet.ApplicationConstants import Notification from pyjamas.ui.DockPanel import DockPanel from pyjamas.ui.RootPanel import RootPanelCls from pyjamas.ui.MenuBar import MenuBar from pyjamas.ui.MenuItem import MenuItem from pyjamas.ui.VerticalPanel import VerticalPanel from ...
StarcoderdataPython
123445
<reponame>imranq2/SparkAutoMapper.FHIR from __future__ import annotations from typing import Optional, TYPE_CHECKING, Union from spark_auto_mapper_fhir.fhir_types.date_time import FhirDateTime from spark_auto_mapper_fhir.fhir_types.list import FhirList from spark_auto_mapper_fhir.fhir_types.string import FhirString fr...
StarcoderdataPython
3204394
# -*- coding: utf-8 -*- """ORCID Blueprint Module Module that contains the full blueprint for ORCID OAuth """ from flask import flash, redirect, session, url_for, current_app, Markup from flask_user import current_user from flask_login import login_user from app.oauth.orcid_flask_dance import make_orcid_blueprint fro...
StarcoderdataPython
1672029
#!/usr/bin/env python # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.spread import pb from twisted.internet import reactor def one(port, user, pw, service, perspective, number): factory = pb.PBClientFactory() reactor.connectTCP("localhost", port, factory) def1 = fa...
StarcoderdataPython
170543
from flask_api import FlaskAPI from flask_sqlalchemy import SQLAlchemy from instance.config import app_config from flask import request, jsonify, abort db = SQLAlchemy() def create_app(config_name): app = FlaskAPI(__name__, instance_relative_config=True) app.config.from_object(app_config[config_name]) ap...
StarcoderdataPython
1727628
import os import io import glob import json import shutil import datetime import time import zipfile import requests from importlib import import_module from jinja2 import Template from django.conf import settings from celery.decorators import task from django.urls import reverse from django.contrib.auth import get_us...
StarcoderdataPython
1720805
<filename>notebook/python_sandbox/py_ufo/drops/test3.py def run_me(): print('this is test copied') if __name__ == '__main__': run_me() x = 2
StarcoderdataPython
1631385
<filename>sdk/python/pulumi_vault/azure/outputs.py # coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping,...
StarcoderdataPython
3287027
<filename>barbeque/cms/toolbar.py from django.utils.encoding import force_text from cms.cms_toolbars import ADMIN_MENU_IDENTIFIER, PAGE_MENU_IDENTIFIER from cms.extensions.toolbar import ExtensionToolbar from cms.toolbar_base import CMSToolbar from cms.toolbar_pool import toolbar_pool from cms.toolbar.items import Sid...
StarcoderdataPython
136341
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Console script for daskerator.""" from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor import datetime as dt from functools import partial from hashlib import md5 import inspect from operator import methodcaller import os from pathlib import Path from...
StarcoderdataPython
14543
<gh_stars>0 """ Load tests from :class:`unittest.TestCase` subclasses. This plugin implements :func:`loadTestsFromName` and :func:`loadTestsFromModule` to load tests from :class:`unittest.TestCase` subclasses found in modules or named on the command line. """ # Adapted from unittest2/loader.py from the unittest2 plu...
StarcoderdataPython
3219983
<reponame>SheikyHaz/tiny_python_projects # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html # For details: https://github.com/PyCQA/pylint/blob/main/LICENSE """A collection of typing utilities.""" import sys from typing import TYPE_CHECKING, Dict, List, NamedTuple, Union if TYPE_CHECKING...
StarcoderdataPython
3319490
import operator dic = {'a': 12, 'b': 15, 'c': 3} ascending = sorted(dic.items(), key=operator.itemgetter(1)) print(ascending) descending = sorted(dic.items(), key=operator.itemgetter(1), reverse=True) print(descending)
StarcoderdataPython
39160
<gh_stars>0 from __future__ import print_function import sys import json def convert(path): try: with open(path, 'r') as f: geojson = json.loads(f.read()) # Warning - Only looking at the exterior, hence skipping holes. coordinates = geojson['features'][0]['geometry']['c...
StarcoderdataPython
4834543
<reponame>kryptn/Authda<filename>Authda/tests/test_tests.py import unittest class TestTestCase(unittest.TestCase): def test_test(self): self.assertTrue(True)
StarcoderdataPython
1683017
from dotenv import load_dotenv from flask import make_response import jwt from models import User from helpers import is_login load_dotenv() def register_controller(session, request): try: data = request.form email = data['email'] name = data['name'] password = data['password'] ...
StarcoderdataPython
114231
<gh_stars>0 class ResponseKeys(object): POST = 'post' POSTS = 'posts' POST_SAVED = 'The post was saved successfully' POST_UPDATED = 'The post was updated successfully' POST_DELETED = 'The post was deleted successfully' POST_NOT_FOUND = 'The post could not be found'
StarcoderdataPython
125625
from anthill.platform.services import PlainService, ControllerRole from anthill.platform.api.internal import as_internal from psutil import virtual_memory, cpu_percent class Service(ControllerRole, PlainService): """Anthill default service.""" master = 'game_master' @staticmethod def setup_internal_a...
StarcoderdataPython
106658
<filename>ryu/app/load_tt_schedule_tb.py<gh_stars>1-10 # Copyright (C) 2016 Nippon Telegraph and Telephone Corporation. # # 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.apach...
StarcoderdataPython
3332252
<filename>coordpy/decorators.py<gh_stars>1-10 # -*- coding: utf-8 -*- import functools class CoordinateValueError(ValueError): """Custom ValueError class. Just to distinguish this exception and make tracebacks easier, we will use this exception when cleaning coordinate values. """ def __init__(...
StarcoderdataPython
4824893
import socket def gateway(): """Guest's gateway address.""" return slash24prefix() + '.1' def guestip(): """Not platform independent, but works on my setup with Windows.""" return socket.gethostbyname(socket.gethostname()) def vmnumber(): """VM number is denoted by the third octet.""" octets ...
StarcoderdataPython
3276018
import click with open('resources/cs-cl.sqs.yaml', 'r') as fh: config_contents = fh.read() def inject_config_file(filename='sqs.yaml'): def _decorator(f): def _injected(self, *args, **kwargs): assert hasattr(self, 'cli_runner') assert isinstance(self.cli_runner, click.testi...
StarcoderdataPython
1658767
<reponame>jpphooper/ds-art import librosa from librosa.display import waveshow, specshow import streamlit as st import matplotlib.pyplot as plt import matplotlib.colors as colors import numpy as np from voxelfuse.voxel_model import VoxelModel from voxelfuse.mesh import Mesh from voxelfuse.primitives import generateMate...
StarcoderdataPython
1678436
import sys def progressify( seq, message = "", offset: int = 0, length: int = 0, ): """ Display a progress bar in the terminal while iterating over a sequence. This function can be used whereever we iterate over a sequence (i.e. something iterable with a length) and we want to display p...
StarcoderdataPython
3217132
def gcd(a, b): while b: t = b b = a % b a = t return a def run_test(limit): print('computing GCD of all pairs of integers in [1, ' + repr(limit) + ']^2') x = limit while x > 0: y = limit while y > 0: r = gcd(x, y) print('gcd of ' + repr(x) + ' and ' + repr(y) + ' is ' + repr(...
StarcoderdataPython
4836310
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
StarcoderdataPython
173821
#!/usr/bin/env python3 import sqlite3 import pandas as pd import numpy as np import matplotlib.pyplot as plt from contextlib import closing as ctx_closing from argparse import ArgumentParser def read_daily_stats(sqc): df = pd.read_sql_query( "SELECT day, avg, (xx/n - avg*avg) AS var, min, max, n AS count FROM (" + ...
StarcoderdataPython
1622856
""" Verifies that embedding UAC information into the manifest works. """ import TestGyp from xml.dom.minidom import parseString test = TestGyp.TestGyp(formats=['msvs', 'ninja'], platforms=['win32'], disable='Need to solve win32api.LoadLibrary problems') import pywintypes import win32api import winerror RT_MANIFEST...
StarcoderdataPython
3222982
import torch import dgl.function as fn import torch.nn as nn import numpy as np # from models.networks import * OPS = { 'V_None' : lambda args: V_None(args), 'V_I' : lambda args: V_I(args), 'V_Max' : lambda args: V_Max(args), 'V_Mean' : lambda args: V_Mean(args), 'V_Min' : lambda args: V...
StarcoderdataPython
183837
<gh_stars>1-10 from flask import Flask,render_template app=Flask(__name__) @app.route('/') def home(): return render_template('templateinherictence(home).html') @app.route('/puppy/<name>') def puppy(name): return render_template('puppy.html',name=name) @app.route('/flow') def controloverflow(): ...
StarcoderdataPython
1733964
from IPython import embed import random if __name__ == "__main__": adjectives = [] f = open("adjectives.txt", "r") for x in f: if ("\n" in x): x = x.split("\n")[0] adjectives.append(x) colors = [] f = open("colors.txt", "r") for x in f: if ("\n" in x): ...
StarcoderdataPython
199589
# coding: utf-8 from flask import render_template, Blueprint bp = Blueprint('site', __name__) @bp.route('/') def index(): """Index page.""" return render_template('site/index/index.html') @bp.route('/about') def about(): """About page.""" return render_template('site/about/about.html')
StarcoderdataPython
59921
<gh_stars>0 import numpy as np from keras import objectives from keras import backend as K import tensorflow as tf from ipdb import set_trace as stop import scipy.stats as st import scipy.misc as mi _EPSILON = K.epsilon() def _loss_tensor(y_true, y_pred): y_pred = K.clip(y_pred, _EPSILON, 1.0-_EPSILON) out = ...
StarcoderdataPython
1734978
from datetime import datetime from math import sqrt, log, ceil from os.path import join, dirname, abspath from helper.helper import std from two_thinning.full_knowledge.RL.DQN.neural_network import * N = 1000 M = 1000 def EXPONENTIAL_POTENTIAL(loads, alpha=0.5): t = sum(loads) n = len(loads) potential =...
StarcoderdataPython
146103
<filename>Lab 2/FNN/mnist_FNN.py from __future__ import print_function import argparse import torch # torch.cuda.set_device(0) import nni import logging import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torchvision from torchvision import datasets, transforms from torch.optim.lr_s...
StarcoderdataPython
21291
import json import urllib2 import traceback import cgi from flask import render_template, request import web.util.tools as tools import lib.http as http import lib.es as es from web import app from lib.read import readfile def get(p): host = p['c']['host']; index = p['c']['index']; # debug p['debug'] = ...
StarcoderdataPython
2644
from datetime import datetime from typing import Any, Dict, Union __all__ = 'AnyDict' AnyDict = Dict[str, Any] # pragma: no mutate datetime_or_str = Union[datetime, str] # pragma: no mutate
StarcoderdataPython
1632483
<gh_stars>100-1000 # -*- coding: utf-8 -*- """ @author: <NAME> <<EMAIL>> @brief: match based features """ import re import string import numpy as np import pandas as pd import config from utils import dist_utils, ngram_utils, nlp_utils, np_utils from utils import logging_utils, time_utils, pkl_utils from feature_ba...
StarcoderdataPython
1725763
""" Module to update passwords to database """ import sys import traceback from mysql.connector import connect, Error from colr import color def update(): coluna = input(color(' Column? » ', fore='#fe7243')) ident = input(color(' ID? » ', fore='#fe7243')) update = input(color(' Write your update:...
StarcoderdataPython
183373
import json import sys import io from util import read_json, flatten, get_json_files, get_loc_dirs if sys.version_info.major < 3: raise Exception("must use python 3") def write_json(filename, data): # TODO: replace with util.write_json once sorting loc files is common. with io.open(filename, 'w', encoding=...
StarcoderdataPython
1713606
""" This module serves to provide a variety of constants for the Fantasy Football Fun package. """ POSITIONS = ["qb", "rb", "wr", "te", "e", "t", "g", "c", "ol", "dt", "de", "dl", "ilb", "olb", "lb", "cb", "s", "db", "k", "p"] # all of the terms users can order by ORDER_BY_TERM...
StarcoderdataPython
3280465
# -*- coding: utf-8 -*- import math def is_inside_cone(x, y, d, alpha): """ Проверяет точку на принадлежность коническому наконечнику волновода Точка в ск Федера """ if alpha >= 0.99 * math.pi: return False k1 = math.tan(0.5 * (math.pi - alpha)) h = 0.5 * d / math.tan(alpha / 2) ...
StarcoderdataPython