id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
1657229 | import urllib.request
pagina = urllib.request.urlopen(
'http://beans.itcarlow.ie/prices-loyalty.html')
texto = pagina.read().decode('utf8')
preço = texto[234:238]
print (preço)
| StarcoderdataPython |
190578 | <filename>3.5.py
# %%
import d2lzh as d2l
from mxnet.gluon import data as gdata
from mxnet import autograd, nd
import sys
import time
def softmax(X):
X_exp = X.exp()
partition = X_exp.sum(axis=1, keepdims=True)
return X_exp / partition
def net(X):
XX = nd.dot(X.reshape((-1, num_inputs)), W1) + b1
... | StarcoderdataPython |
52526 | from botorch.models.gpytorch import GPyTorchModel
from gpytorch.distributions import MultivariateNormal
from gpytorch.kernels import MaternKernel, ScaleKernel
from gpytorch.likelihoods import GaussianLikelihood
from gpytorch.means import ConstantMean
from gpytorch.models import ExactGP
from greattunes.transformed_kern... | StarcoderdataPython |
283426 | import re
from operator import itemgetter
from os import path, mkdir, listdir, remove
from kivy.logger import Logger
from linktypes.settings import MultipleChoiceSetting
active = True
name = 'Steam Library'
defaults = {'game': {}}
def locate_steam_main():
candidates = ['C:\\Program Files\\Steam',
'C:\\Pr... | StarcoderdataPython |
11257577 | # -*- coding: utf-8 -*-
import unittest
from qscu import QSCU
class TestQSCU(unittest.TestCase):
def setup_test(self):
"""Instantiate a databse in memory for the test."""
self.shop = QSCU(":memory:")
self.shop.setup_db()
def test_no_sold_items(self):
"""Test if the quantity of... | StarcoderdataPython |
87205 | <filename>interfaces/python/bable_interface/models/__init__.py
from .bable_exception import BaBLEException
from .characteristic import Characteristic
from .controller import Controller
from .device import Device
from .packet import Packet, PacketUuid
from .service import Service
| StarcoderdataPython |
5121370 | """Common test utilities."""
from unittest.mock import Mock
class AsyncMock(Mock):
"""Implements Mock async."""
# pylint: disable=W0235
async def __call__(self, *args, **kwargs):
"""Hack for async support for Mock."""
return super(AsyncMock, self).__call__(*args, **kwargs)
| StarcoderdataPython |
135991 | import pytest
from flask import Flask, render_template_string
from flask_mobility import Mobility
from flask_mobility.decorators import mobile_template, mobilized
class TestDecorators(object):
@pytest.fixture()
def app(self):
app = Flask(__name__)
Mobility(app)
@app.route("/")
... | StarcoderdataPython |
1823721 | <filename>fowd/tests/test_quality_flags.py
"""
tests/test_quality_flags.py
Unit tests for QC flags.
"""
from fowd import operators
import numpy as np
def create_datetime(offset):
return np.datetime64('now') + (1e9 * offset).astype('timedelta64[ns]')
def test_flag_a():
res = operators.check_flag_a(
... | StarcoderdataPython |
3438316 | <reponame>subhamengine/3rd-Sem<filename>Lab-classes/PCC-CS-393/FirstPrograms(28-09-21).py
//opeartor
x = int(input("Enter the First Number:\n"))
y = eval(input("Enter the second Numder:\n"))
print("addition = ",x+y)
print("Substraction = ",x-y)
print("Multiplication = ",x*y)
print("Division = ",x/y)
print("Power = ",x... | StarcoderdataPython |
78827 | <reponame>ratnania/caid
# coding: utf-8
import numpy as np
import matplotlib.pyplot as plt
from caid.quadrangles.hermite_bezier import rectangle, square, circle
def test_rectangle():
geo = rectangle(n=[25,25], origin=[5.,4.], lengths=[1.,2.])
geo.save(label="rectangle")
geo.plot()
plt.title("Rectangula... | StarcoderdataPython |
1609616 | <gh_stars>0
"""Module for the custom Django sampledata command."""
from django.core import management
from django.conf import settings
from django.contrib.auth import get_user_model
from users.models import UserType
from allauth.account.models import EmailAddress
from tests.users.factories import UserFactory
from test... | StarcoderdataPython |
6434259 | <filename>Python/kraken/plugins/maya_plugin/synchronizer.py
from kraken.core.maths import Xfo, Vec3, Quat
from kraken.core.synchronizer import Synchronizer
from kraken.plugins.maya_plugin.utils import *
from kraken.plugins.maya_plugin.utils.curves import curveToKraken
class Synchronizer(Synchronizer):
"""The Syn... | StarcoderdataPython |
11390720 | <filename>pyNastran/converters/dev/calculix/nastran_to_calculix.py
"""
defines:
- CalculixConverter
"""
from collections import defaultdict
from numpy import array, zeros, cross
from numpy.linalg import norm # type: ignore
from pyNastran.bdf.bdf import BDF, LOAD # PBAR, PBARL, PBEAM, PBEAML,
from pyNastran.bdf.ca... | StarcoderdataPython |
4844321 | <gh_stars>1-10
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='nameko-atomicity',
version='1.0.0',
description='Atomicity dependency for nameko services',
author='jeremy-jin',
author_email='<EMAIL>',
url='https://github.com/jeremy-jin/nameko-atomicity',
packag... | StarcoderdataPython |
12813576 | <reponame>Tilapiatsu/blender-custom_conf
from itertools import chain
from collections import defaultdict
from .. utils.nodes import getAnimationNodeTrees, iterAnimationNodesSockets
class ForestData:
def __init__(self):
self._reset()
def _reset(self):
self.nodes = []
self.nodesByType = ... | StarcoderdataPython |
11220962 | <filename>NaiveBayes/bayes.py
import numpy as np
class Bayes:
@staticmethod
def mean(X):
return np.mean(X,axis=0)
@staticmethod
def variance(X):
return np.mean((X-Bayes.mean(X))**2,axis=0)
def gaussian(self,x,avg,var):
return (1./np.sqrt(2*np.pi*var)) * np.exp... | StarcoderdataPython |
4854606 | <reponame>knowsuchagency/django-mako-plus<gh_stars>0
from ..util import merge_dicts
from .static_links import CssLinkProvider, JsLinkProvider
from .base import BaseProvider
import os
import os.path
import posixpath
class WebpackCssLinkProvider(CssLinkProvider):
'''
Generates a CSS <link> tag for the sitewi... | StarcoderdataPython |
1942730 | """An improved base task implementing easy (and explicit) saving of outputs."""
import os
import logging
from inspect import getfullargspec
import numpy as np
from caput import pipeline, config, memh5
class MPILogFilter(logging.Filter):
"""Filter log entries by MPI rank.
Also this will optionally add MPI ... | StarcoderdataPython |
6587302 | # Copyright 2018 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""This module is to process the code coverage metadata.
The code coverage data format is defined at:
https://chromium.googlesource.com/infra/infra/+/refs/he... | StarcoderdataPython |
9650074 | <gh_stars>10-100
'''list_quota.py - list Compute usage quota for specific regions or all'''
import json
import sys
import azurerm
SUMMARY = False
def print_region_quota(access_token, sub_id, region):
'''Print the Compute usage quota for a specific region'''
print(region + ':')
quota = azurerm.get_compute... | StarcoderdataPython |
12847021 | <gh_stars>1-10
from douyinspider.structures.hot import *
from douyinspider.structures.base import Base
from douyinspider.structures.music import Music
from douyinspider.structures.user import User
from douyinspider.structures.video import Video
from douyinspider.structures.address import Address
from douyinspider.struc... | StarcoderdataPython |
11349958 | from flask_restful import reqparse
from werkzeug import datastructures
_help = 'Désolé, ce champ est obligatoire'
post_parser = reqparse.RequestParser()
post_parser.add_argument('name', type=str, required=True, help=_help)
post_parser.add_argument('email', type=str, required=True, help=_help)
post_parser.add_argument('... | StarcoderdataPython |
4941707 | <reponame>nurhapandi/labpy03<filename>latihan 2.py
print(' ')
print('-----Program Menampilkan bilangan terbesar-----')
print(' ')
max = 0
while True:
a = int(input('Masukkan bilangan:'))
if a >= max:
max = a
if a == 0:
break
print('Nilai terbesarnya adalah :',max)
prin... | StarcoderdataPython |
1716750 | # coding=utf-8
# Copyright 2021 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | StarcoderdataPython |
363123 | <reponame>MarcDufresne/m0rk-blog-examples
import time
import click
def demo():
with click.progressbar(range(7)) as entries:
for _ in entries:
time.sleep(1)
if __name__ == '__main__':
demo()
| StarcoderdataPython |
381389 | import time
import sys
class _Getch:
"""Gets a single character from standard input. Does not echo to the
screen."""
def __init__(self):
try:
self.impl = _GetchWindows()
except ImportError:
self.impl = _GetchUnix()
def __call__(self): return self.impl()
class _Ge... | StarcoderdataPython |
232902 | # -*- coding: utf-8 -*-
"""
Graphical summary of the RA-RM sweep.
@author: <NAME> / ray dor subhasis at <EMAIL> dot <EMAIL>
"""
from __future__ import print_function
import sys
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import neurograph as ng
... | StarcoderdataPython |
1900732 | def add(a, b):
print(f"ADDING {a} + {b}")
return a + b
def subtract(a, b):
print(f"SUBTRACTING {a} - {b}")
return a - b
def multiply(a, b):
print(f"MULTIPLYING {a} * {b}")
return a * b
def divide(a, b):
print(f"DIVIDING {a} / {b}")
return a / b
answer1 = 24 + 34 / 100 - 1023
answ... | StarcoderdataPython |
1916495 | <gh_stars>0
from django.shortcuts import render
import os
import boto3
from pprint import pprint as pp
from datetime import datetime
LOGS_TABLE_NAME = os.environ['LOGS_TABLE_NAME']
USERS_TABLE_NAME = os.environ['USERS_TABLE_NAME']
MACHINES_TABLE_NAME = os.environ['MACHINES_TABLE_NAME']
# known_users = []
# known_mach... | StarcoderdataPython |
1937620 | from .bot import *
from .cog import *
from .context import *
from .help import *
| StarcoderdataPython |
9739018 | <filename>tpo/migrations/0004_lti_23_oct_degreepassyear.py
# Generated by Django 2.2.3 on 2019-10-04 11:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tpo', '0003_auto_20191002_1454'),
]
operations = [
migrations.AddField(
... | StarcoderdataPython |
3422669 | import json
import requests
import config
CLIENT_ID = config.client_id
CLIENT_Secret = config.client_secret
AUTH_URL = 'https://accounts.spotify.com/api/token'
auth_response = requests.post(AUTH_URL, {
'grant_type': 'client_credentials',
'client_id': CLIENT_ID,
'client_secret': CLIENT_Secret,
})
#conv... | StarcoderdataPython |
1603128 | <filename>MUNDO1/Ex029_Multa.py
from time import sleep
print('\n')
print('=+'*15)
print('O limite de velocidade é de 80km/h...')
vel = int(input ('Qual a sua velocidade agora? '))
if vel > 80:
multa = (vel-80)*7
print('Bonito, hein...')
sleep(1.5)
print('Você será multado em: R${:.2f}'.format(multa))
el... | StarcoderdataPython |
3533779 | <filename>securicad/azure_collector/services/application_insights.py
# Copyright 2021-2022 Foreseeti AB <https://foreseeti.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https:/... | StarcoderdataPython |
8158783 | import numpy as np
f = lambda x: np.sum(x ** 2)
def numerical_gradient(f, x):
h = 1e-4
grad = np.zeros_like(x)
for idx in range(x.size):
# f(x + h)
fxh1 = f( x[idx] + h )
# f(x - h)
fxh2 = f( x[idx] - h )
# grad = ( f( x + h ) - f( x - h ) ) / ( 2 * h )
... | StarcoderdataPython |
4829963 | <filename>ortools/sat/samples/step_function_sample_sat.py<gh_stars>1-10
# Copyright 2010-2018 Google LLC
# 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/L... | StarcoderdataPython |
4873673 | import json
from django.urls import reverse
from rest_framework.views import status
from rest_framework.test import APITestCase, APIClient
class RegistrationTestCase(APITestCase):
def setUp(self):
self.client = APIClient()
self.login_url = reverse('authentication:auth-login')
self.signup_u... | StarcoderdataPython |
8137912 | <gh_stars>0
# Generated by Django 3.0.5 on 2020-05-20 15:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('poems', '0009_auto_20200518_2230'),
]
operations = [
migrations.AlterField(
model_name='poet',
name='fat... | StarcoderdataPython |
3489612 | <reponame>jayktee/scrapers-us-municipal<gh_stars>10-100
from pupa.scrape import Scraper
from pupa.scrape import Person, Organization
from .utils import Urls
legislators_url = 'http://mayor.cityofboise.org/city-council/'
class PersonScraper(Scraper):
def scrape(self):
urls = Urls(dict(list=legislators_u... | StarcoderdataPython |
5124610 | <filename>2 - Big O/logarithmic.py
def binary_search(a):
left = 0;
right = len(a) - 1
while(left<=right):
mid = left // 2
| StarcoderdataPython |
8113354 | g#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed May 29 10:31:37 2019
@author: evapool
"""
import sys
# this is just for my own machine
sys.path.append("/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/")
from mvpa2.suite import *
from pymvpaw import *
impo... | StarcoderdataPython |
3533736 | def csv_columns(csv, indices):
temp=[i.split(",")for i in csv.split("\n")]
index=[i for i in sorted(set(indices)) if i<len(temp[0])]
if not index:
return ""
res=[]
for i in range(len(temp)):
string=[]
for j in index:
string.append(temp[i][j])
res.appen... | StarcoderdataPython |
8045203 | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.IndexView, name="checkoutView"),
url(r'^remove$', views.removeItem , name="checkout_remove"),
url(r'^update$', views.updateQuantity, name="checkout_update"),
url(r'^total$', views.getTotal, name="checkout_update"),
url(r'^pay$... | StarcoderdataPython |
1656422 | """
Description: This script runs d_steiner on synthetic data
"""
from utils.networkx_operations import *
from utils.pandas_operations import *
from utils.time_operations import *
from utils.steiner_tree_te import *
# from utils.steiner_tree_v3 import *
from tqdm import tqdm
# import pickle
import pandas as pd
import ... | StarcoderdataPython |
8162874 | """
Build microwave pulse sequences for an arbitrary waveform generator in order to perform diamond NV-center experiments.
This module constructs waveforms for use with an arbitrary waveform generator (hereafter referred to as an AWG)
in performing microwave manipulation of electronic state populations in negatively-c... | StarcoderdataPython |
6539797 | <reponame>srm-mic/EfficientNe
from utils import *
import tensorflow as tf
from tensorflow.keras.models import Model, Sequential
from tensorflow.keras.layers import Input, Dense, Conv2D, DepthwiseConv2D, BatchNormalization, Dropout, GlobalAveragePooling2D, Reshape, multiply, add, Activation
def EfficientNet_B0(channels... | StarcoderdataPython |
145517 | <gh_stars>1000+
"""
Parameter retrieval exceptions
"""
class GetParameterError(Exception):
"""When a provider raises an exception on parameter retrieval"""
class TransformParameterError(Exception):
"""When a provider fails to transform a parameter value"""
| StarcoderdataPython |
11343293 | <reponame>Insert-Generic-Name-Here/ReCOn<gh_stars>0
from lib.rfilecmp import cmp
from colorama import Fore, Style
from time import sleep
import stat,csv,time
import pandas as pd
import threading
import paramiko
import os,errno
'''(Hint: Check threading -> Attempt to connect (required data on ssh_client_dict) every X ... | StarcoderdataPython |
4862387 | <reponame>jakemcaferty/pyesg<gh_stars>10-100
"""Wiener Process"""
from typing import Dict, List, Union
import numpy as np
from pyesg.stochastic_process import StochasticProcess
from pyesg.utils import to_array
class WienerProcess(StochasticProcess):
"""
Generalized Wiener process: dX = μdt + σdW
Example... | StarcoderdataPython |
9742442 | <gh_stars>1-10
# Orca
# Copyright (C) 2016 UrbanSim Inc.
# See full license in LICENSE.
from .orca import *
version = __version__ = '1.5.4'
| StarcoderdataPython |
8085284 | import seaborn as sns
import pandas as pd
from matplotlib import pyplot as plt
import lib_plot
from lib_fmt import fmt_barplot, fmt_thousands
from lib_db import DBClient
def main(db_client: DBClient, threshold=500):
sns.set_theme()
results = db_client.query(
f"""
WITH cte AS (
SE... | StarcoderdataPython |
5117868 | <filename>examples/plotting/bar_plot.py
import numpy as np
from vispy import scene, app
if __name__ == "__main__":
canvas = scene.SceneCanvas(keys='interactive', vsync=False)
canvas.size = 1280, 720
canvas.show()
grid = canvas.central_widget.add_grid()
grid.padding = 10
vb1 = grid.add_view(ro... | StarcoderdataPython |
1722461 | from itertools import product
from guess import guess
from typing import Dict, Set, Tuple, List
from multiprocessing import Pool
import pickle
from tqdm import tqdm
import sys
def calculate(i):
idx, query, dict_ans = i
outcomes: Dict[Tuple[int, int, int, int, int], Set[str]] = {}
for iidx, word in enumera... | StarcoderdataPython |
3578962 | <gh_stars>0
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# 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... | StarcoderdataPython |
9681039 | #!/usr/bin/env python
'''
Convert lecture/slides from pptx to Slidoc Markdown format.
Use blank lines between list elements
If --embed_slides, embed whole slide as an image by default,
unless the string 'Answer:' occurs in the text of the slide at the start of a line.
All the text in the notes portion of a Powerpoi... | StarcoderdataPython |
1650641 | <gh_stars>0
class IntegrationRouter:
"""
A router to control all database operations on models in the
auth and contenttypes applications.
"""
call_center_models = {
'agent',
'audit',
'break',
'callattribute',
'callentry',
'callprogresslog',
'ca... | StarcoderdataPython |
4956170 | # -*- coding: utf-8 -*-
'''This script contains the functions for FITS file and raw image manipulations'''
import numpy as np
from glob import glob
import astropy.io.fits as pyfits
import re, os
# from matplotlib import pyplot as plt
# from matplotlib.ticker import MultipleLocator
import pickle as pickle
from medis.D... | StarcoderdataPython |
5122321 | <filename>tests/test_get_column_info.py
import pandas
import pytest
from pytest_postgresql import factories
from subgraph_extractor.cli import *
postgresql_my_proc = factories.postgresql_proc(load=["tests/resources/example_db.sql"])
sample_subgraph = factories.postgresql("postgresql_my_proc")
@pytest.fixture
def db... | StarcoderdataPython |
154760 | <filename>application/events/forms.py<gh_stars>1-10
from flask_wtf import FlaskForm
from flask_login import current_user
from wtforms import TextAreaField, IntegerField, validators
from wtforms.ext.sqlalchemy.fields import QuerySelectField
from application.categories import models
class EventForm(FlaskForm):
cat... | StarcoderdataPython |
1608586 | """
Speedml Model component with methods that work on sklearn models workflow. Contact author https://twitter.com/manavsehgal. Code, docs and demos https://speedml.com.
"""
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
from .base im... | StarcoderdataPython |
3596929 | __author__ = "<NAME>"
__copyright__ = "Copyright 2017-2019, <NAME>"
__license__ = "apache-2.0"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
import subprocess
import logging
import hashlib
import os
import settings
class Pandoc(str):
in_format = "html"
in_options = []
out_format = "plain"
out_optio... | StarcoderdataPython |
6603316 | <reponame>magnusja/metriculous
"""
This module provides various default Evaluator implementations that are useful for the
most common machine learning problems, such as classification and regression.
"""
from metriculous.evaluators._classification_evaluator import ClassificationEvaluator
from metriculous.evaluators._re... | StarcoderdataPython |
3233428 | <reponame>tobeannouncd/AdventOfCode
from collections import defaultdict, deque
import advent
SAMPLE_DATA = '''x=495, y=2..7
y=7, x=495..501
x=501, y=3..7
x=498, y=2..4
x=506, y=1..2
x=498, y=10..13
x=504, y=10..13
y=13, x=498..504'''
def peek(position, direction, map):
x, y = position
if direction == 'left'... | StarcoderdataPython |
3274287 | import sys
import argparse
sys.path.append('./modules/')
from knn import execute as execute_knn
from kmeans import execute as execute_k_means
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Trabalho 1 da classe Sistema Inteligentes Aplicados')
parser.add_argument('--knn',action='store_tr... | StarcoderdataPython |
3380176 | from selenium import webdriver
import time
from datetime import datetime
import os
import warnings
import yaml
from win10toast import ToastNotifier
from os.path import exists
#TODO: Automatically install correct chromedriver version and delete old versions if they exist in directory
version = "1.2.1"
# Di... | StarcoderdataPython |
287616 | #!/bin/python3
from src.SimController import Controller
from src.SamplerMethods import MonteCarlo_normal, Linear
if __name__ == "__main__":
# Project_folder relative to main.py
project_folder = "PhysiCellProject"
# xml_file relative to project_folder
xml_file = "config/PhysiCell_settings.xml"
# binary_name shoul... | StarcoderdataPython |
1731199 | import argparse
import glob
import os
import bconv
parser = argparse.ArgumentParser()
parser.add_argument(
'--in_dir',
help='the input PMC NXML file',
default="data/pmc_articles/3_Biotech/PMC4829572.nxml",
)
parser.add_argument(
'--stamp',
help='the name of the complete stamp to add to the directo... | StarcoderdataPython |
3204242 | import cloudinary
from django.contrib.sites.models import Site
def site_processor(request):
return {
'site': Site.objects.get_current()
}
def consts(request):
return dict(
ICON_EFFECTS = dict(
format="png",
type="facebook",
transformation=[
... | StarcoderdataPython |
3544228 | from django import forms
class ImgForm(forms.Form):
title = forms.CharField(max_length=250)
file = forms.ImageField()
| StarcoderdataPython |
4876572 | import torch
import torch.nn as nn
class Communacation(nn.Module):
def __init__(self, input_size, hid_size):
super(Communacation, self).__init__()
self.encoder_layer = nn.TransformerEncoderLayer(input_size, dim_feedforward = 128, nhead=2, dropout=0)
self.encoder = nn.TransformerEncoder(self... | StarcoderdataPython |
4904660 | <reponame>hcieslewicz/PC
from flask import Flask
from flask_restplus import Api
from api_v1 import blueprint
from resources.games import Games#, GamesLog
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.register_blueprint(bluep... | StarcoderdataPython |
5192364 | # -*- coding: utf-8 -*-
import copy
def make_empty_maze(m, n):
return [[0 for i in range(n)] for k in range(m)]
def init_maze_for_distance(maze):
for i in range(len(maze)):
for k in range(len(maze[i])):
maze[i][k] = -1
def make_maze(m, n):
maze = make_empty_maze(m, n)
for i in ... | StarcoderdataPython |
11243853 | N = int(input())
max_guesses_correct = 0
guesses_correct = 0
swap_a = []
swap_b = []
guess_array = []
for x in range(N):
temp_list = input().split()
swap_a.append(int(temp_list[0]))
swap_b.append(int(temp_list[1]))
guess_array.append(int(temp_list[2]))
main_array = [True, False, False]
... | StarcoderdataPython |
9721928 | <gh_stars>1-10
# encoding: utf-8
'''Python utilities, like finding and loading modules
'''
import sys, os, imp
from smisk.util.collections import unique_wild
from smisk.util.string import strip_filename_extension
from smisk.util.type import None2
__all__ = ['format_exc', 'wrap_exc_in_callable', 'classmethods', 'unique... | StarcoderdataPython |
1717728 | <reponame>SBfin/UniStrategy
from brownie import chain, reverts
from pytest import approx
import math
def test_rebalance_swap(vault,
strategy,
pool,
user,
keeper,
tokens):
tick = pool.slot0()[1]
print("tick \n" + str(tick))
tickFloor = tick // 60 * 60
print("tick floor\n" +... | StarcoderdataPython |
5022892 | #!/home/XLS_PlatForm/hue-release-3.9.0/build/env/bin/python2.7
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
| StarcoderdataPython |
6541478 | <filename>WritePage.py
import tkinter as tk
import random
import requests
import json
from tkinter import messagebox
import geocoder
import reverse_geocoder as rg
from tkinter import font as tkfont
import time
class WritePage(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, pare... | StarcoderdataPython |
5118561 | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE.txt in the project root for
# license information.
# -------------------------------------------------------------------------
import asyn... | StarcoderdataPython |
1620833 | <reponame>edersondisouza/linux-tsn-eval
# perf script event handlers, generated by perf script -g python
# Licensed under the terms of the GNU GPL License version 2
# The common_* event handler fields are the most useful fields common to
# all events. They don't necessarily correspond to the 'common_*' fields
# in th... | StarcoderdataPython |
12831899 | <filename>baseline_fasttext.py<gh_stars>0
import pandas as pd
import fasttext
from scipy.spatial import distance
from itertools import product
import sys
import numpy as np
model = fasttext.load_model("embedding/wiki.en/wiki.en.bin")
#Return sentence embeddings for a list of words
def get_word_embedding(list_of_words... | StarcoderdataPython |
1945514 | <filename>wheelhouse_uploader/cmd.py
"""Custom distutils to automate commands for PyPI deployments
The 'fetch_artifacts' command download the artifacts from the matching project
name and version from public HTML repositories to the dist folder.
The 'upload_all' command scans the content of the `dist` folder for any
p... | StarcoderdataPython |
9630286 | <reponame>1997alireza/Persian-Telegram-WordCloud<filename>telegram_crawler/crawler.py
from telethon import TelegramClient
from telethon.tl.types import Dialog
class Crawler:
def __init__(self, dialog: Dialog, client: TelegramClient, target_entity_id, max_messages_count,
ignore_forwarded_messages)... | StarcoderdataPython |
41537 | <filename>models/faster_rcnn.py
# --------------------------------------------------------
# Written by <NAME> at 11:54 AM 5/7/2020
# --------------------------------------------------------
import torch
from torch import nn
from utils.config import opt
class FasterRCNN(nn.Module):
def __init__(self, feature_ext... | StarcoderdataPython |
5104197 | <reponame>kd-kinuthiadavid/testing-deploy-ig-clone
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.http import Http404
from django.shortcuts import render, redirect
import datetime as dt
from friendship.exceptions import AlreadyExistsError
from .models... | StarcoderdataPython |
1832784 | <reponame>kian1377/falco-python
# Copyright 2018-2020 by the California Institute of Technology. ALL RIGHTS
# RESERVED. United States Government Sponsorship acknowledged. Any
# commercial use must be negotiated with the Office of Technology Transfer
# at the California Institute of Technology.
# -----------------------... | StarcoderdataPython |
3284312 | from cocoa.neural.utterance import Utterance
from cocoa.neural.utterance import UtteranceBuilder as BaseUtteranceBuilder
from symbols import markers, category_markers
from core.price_tracker import PriceScaler
from cocoa.core.entity import is_entity
class UtteranceBuilder(BaseUtteranceBuilder):
"""
Build a wo... | StarcoderdataPython |
4887798 | from datetime import datetime
from flask_dance.consumer.storage.sqla import OAuthConsumerMixin
from sqlalchemy.orm.collections import attribute_mapped_collection
from flask_login import LoginManager, UserMixin
from . import db, login_manager
class SerializableMixin(object):
def _serialize(self):
"""Jsoni... | StarcoderdataPython |
6406817 | <filename>client.py
#!/usr/bin/env python2
import sys, time, urllib2
def getResults(url):
conn = urllib2.urlopen(url + "/output.txt")
result = conn.read()
conn.close()
return result
def transmitCommand(cmd, url):
i = 1
cmdlen = len(cmd)
for char in list(cmd):
print "\rTransmitting command (%d/%d)" % (i, cmdl... | StarcoderdataPython |
9796076 | """ Color based K-means"""
import numpy as np
import cv2
import os
import glob
from glob import glob
from PIL import Image
from matplotlib import pyplot as plt
import pdb
heatMap_image_path = '/Users/monjoysaha/Downloads/CT_lung_segmentation-master/check/test/'
save_path = '/Users/monjoysaha/Downloads/CT_lung_segment... | StarcoderdataPython |
9620738 | # fail-if: '-x' not in EXTRA_JIT_ARGS
def f():
if True:
1
2
| StarcoderdataPython |
6597352 | # import some necessary functions for plotting as well as the diffusion_map class from pydiffmap.
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from pydiffmap import diffusion_map as dm
# set parameters
length_phi = 15 #length of swiss roll in angular direction
length_Z ... | StarcoderdataPython |
6498226 | <reponame>cuijiaxing/DatasetCondensation
import os
import time
import copy
import argparse
import numpy as np
import torch
import torch.nn as nn
from torchvision.utils import save_image
from utils import get_loops, get_dataset, get_network, get_eval_pool, evaluate_synset, get_daparam, match_loss, get_time, Tens... | StarcoderdataPython |
6586184 | <gh_stars>0
import os
import logging
from flask import Flask, g, url_for, request, flash, redirect, jsonify, render_template, make_response, current_app
from flask_login import LoginManager
from flask_uploads import patch_request_class, configure_uploads
from benwaonline.exceptions import BenwaOnlineError, BenwaOnline... | StarcoderdataPython |
9741461 | <reponame>santiagoRuizSchiphol/squeezenext-tensorflow
from __future__ import absolute_import
import tensorflow as tf
import multiprocessing
def caffe_center_crop(image_encoded,image_size,training,resize_size=256):
"""
Emulates the center crop function used in caffe
:param image_encoded:
Jpeg strin... | StarcoderdataPython |
127514 | <gh_stars>1-10
"""Endpoint URLs for sheets app"""
from django.urls import re_path
from sheets import views
urlpatterns = [
re_path(r"^sheets/admin/", views.sheets_admin_view, name="sheets-admin-view"),
re_path(
r"^api/sheets/auth/", views.request_google_auth, name="request-google-auth"
),
re_p... | StarcoderdataPython |
5062019 | # -*- coding: utf-8 -*-
# vim:tabstop=4:expandtab:sw=4:softtabstop=4
from django.conf import settings
from django.test import TestCase
from django.utils.unittest.case import skipIf
from billing.gateway import CardNotSupported
from billing.utils.credit_card import Visa, CreditCard
from billing import get_gateway
from ... | StarcoderdataPython |
9674257 | from setuptools import setup, find_packages
setup(
name='aggravator',
version='0.4.4',
description='Ansible inventory script to aggregate other inventory sources',
long_description=open('README.rst').read(),
license='MIT',
url='https://github.com/petercb/aggravator',
keywords='ansible',
... | StarcoderdataPython |
3487462 | import csnd6
# Import SPI library (for hardware SPI) and MCP3008 library.
import Adafruit_GPIO.SPI as SPI
import Adafruit_MCP3008
from random import randint, random
import time
# For Directory Searching
import glob
# Hardware SPI configuration:
SPI_PORT = 0
SPI_DEVICE = 0
class RandomLine(object):
... | StarcoderdataPython |
5057972 | <gh_stars>0
"""
Various tests intended for testing the reading data from sources,
identification of data types of features as well as a corresponding
borders for numerical attributes.
"""
from unittest import TestCase
from niaarm.dataset import Dataset
import os
class TestReadCSVAbalone(TestCase):
def test_read_... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.