id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
3312114 | import re
st="hello \\doggy"
print(st)
r=re.search(r'\\doggy',st)
print(r)
print(type(r))
| StarcoderdataPython |
4824139 | <reponame>glentner/globus-cli
import click
import globus_sdk
from globus_sdk.exc import AuthAPIError
from globus_cli.config import (
AUTH_AT_EXPIRES_OPTNAME,
AUTH_AT_OPTNAME,
AUTH_RT_OPTNAME,
CLIENT_ID_OPTNAME,
CLIENT_SECRET_OPTNAME,
TRANSFER_AT_EXPIRES_OPTNAME,
TRANSFER_AT_OPTNAME,
TRA... | StarcoderdataPython |
164006 | from typing import Dict, List, Union
from pandas import DataFrame
from pytiingo.rest.configuration import Configuration
from pytiingo.rest.http.http_response import HttpResponse
class ApiMixin(object):
def _execute_request(self, query_url: str, query_parameters: Dict) -> HttpResponse:
request = self.con... | StarcoderdataPython |
1711341 | #!/usr/bin/env python
import sys
from openmoltools import amber_parser
if __name__ == "__main__":
if len(sys.argv[1:]) <= 1:
print("""Usage: processAmberForceField.py some_path/gaff.dat ligand_name.mol2 ligand_name.frcmod
""")
else:
parser = amber_parser.AmberParser()
parser.parse_filen... | StarcoderdataPython |
1695864 | <filename>var/spack/repos/builtin/packages/py-nara-wpe/package.py
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack.package import *
class PyNaraWpe(PythonPack... | StarcoderdataPython |
1752176 | <filename>main.py
import dotenv
import requests
from urllib.parse import urlparse
import os
import argparse
import sys
def createParser():
parser = argparse.ArgumentParser()
parser.add_argument('-l', '--link')
return parser
def shorten_link(token, url):
response = requests.post(
'https://api... | StarcoderdataPython |
1721339 | import keras.backend as K
import numpy as np
import pandas as pd
from datetime import time, datetime
import tensorflow as tf
from argparse import ArgumentParser
def get_flops(model):
run_meta = tf.RunMetadata()
opts = tf.profiler.ProfileOptionBuilder.float_operation()
# We use the Keras session graph in ... | StarcoderdataPython |
1778552 | <filename>scmoib/__init__.py
from . import plotting as pl
from . import preprocessing as pp
from . import tools as tl
# from .utils import check_versions, annotate_doc_types
from ._version import get_versions # version generated by versioneer
__author__ = ', '.join([
'<NAME>',
'<NAME>',
'<NAME>',
])
__ema... | StarcoderdataPython |
152301 | """
test if we can construct the input graph from the obs of actual mujoco env using for loop.
"""
import gym
import tensorflow as tf
from graph_nets import modules
from graph_nets.my_utils.input_graph_generator import GraphOperator
from graph_nets.my_utils.mujoco_parser import parse_mujoco_graph
tf.compat.v1.enable_e... | StarcoderdataPython |
3253044 | from .models import NotificationComments
from .forms import NotificationCommentsForm
def get_model():
return NotificationComments
def get_form():
return NotificationCommentsForm | StarcoderdataPython |
3301771 | # Crie um programa que leia o nome completo de uma pessoa e mostre:
#
# – O nome com todas as letras maiúsculas e minúsculas.
#
# – Quantas letras ao todo (sem considerar espaços).
#
# – Quantas letras tem o primeiro nome.
nome = str(input('Digite seu noem completo: ')).strip() # strip = elimina os espaços desnecessar... | StarcoderdataPython |
3222778 | <reponame>jhgg/dissonance
import functools
from gevent.lock import RLock
def once(wrapped):
"""
Decorates a function that takes no arguments, ensuring it's only called once & that the result
is memoized. This function is greenlet safe.
"""
wrapped._once_called = False
wrapped._once_retval = No... | StarcoderdataPython |
3381139 | <filename>src/scripts/visualisation/cannon_performance/internal_model_per_spectrum.py<gh_stars>0
#!../../../../../virtualenv/bin/python3
# -*- coding: utf-8 -*-
# NB: The shebang line above assumes you've installed a python virtual environment alongside your working copy of the
# <4most-4gp-scripts> git repository. It... | StarcoderdataPython |
3321016 | # implementation based on https://github.com/lisa-1010/transfer_rl/blob/master/code/gym_pipeline.py
import gym
import matplotlib.pyplot as plt
# TODO: import agents
ENV_NAME = 'CartPole-v0'
NUM_TEST_TRIALS = 100
class EnvWrapper(object):
"""
Wraps the Environment class from gym, so we can make environment... | StarcoderdataPython |
116107 | #!/usr/bin/env python3
from setuptools import setup
import setuptools.command.build_py
from distutils.spawn import find_executable
import subprocess
from subprocess import check_call
proto = 'detd/ipc.proto'
class OverrideBuildPy(setuptools.command.build_py.build_py):
def run(self):
self.gen_stub(pr... | StarcoderdataPython |
3364940 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('raster', '0014_remove_rastertile_is_base'),
]
operations = [
migrations.AddField(
model_name='l... | StarcoderdataPython |
159495 | """ Unit tests to cover the osm2pgsql_recommendation module."""
import os
import unittest
import osm2pgsql_recommendation
class Osm2pgsqlRecommendationTests(unittest.TestCase):
def test_get_recommended_script_returns_str(self):
expected = str
system_ram_gb = 2
osm_pbf_gb = 10
app... | StarcoderdataPython |
3296118 | <gh_stars>0
# !/usr/bin/env python
#!-*- coding: utf-8 -*-
# * for ChromeModel
import getpass
import os
import shutil
import database
from threading import Thread
from timeit import Timer
from statistics import mean
# version 2.2 test with chrome browser profile with threading
__version__ = "0.2.2"
# * choose thread... | StarcoderdataPython |
4832734 | def HeadCore(
Title="Bionic-Ui",
Css=True,
ThemeColor="#0000000",
SiteUrl="www.hey.com",
Image_description="this is an image description",
Imageurl="",
Type="",
Keywords="",
Description="",
Author="",
Icon="./src/icon.ico",
):
if Css == False:
return f"""<meta cha... | StarcoderdataPython |
197187 | <reponame>hujiang001/iot-X<gh_stars>0
#-*-coding=utf8-*-
from setuptools import setup,find_packages
setup(
name = 'iotX',
version = '1.0',
author = '<NAME>',
author_email = '<EMAIL>',
url = 'www.iotx.com',
summary = 'iotX - a simple framework for connecting devices with the web cloud',
lic... | StarcoderdataPython |
387 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import io
import json
import os
import random
import re
import string
import time
from functools import wraps
from hashlib import sha1
import six
try:
from secrets import choice
except ImportError:
from random import choice
str... | StarcoderdataPython |
3383656 | <gh_stars>1-10
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Testing Database operations functions.
Testing common Database operations. Starting with www.faunadb.com.
"""
import logging
import pytest
from faunadb.client import FaunaClient
from broccolini.authentication_functions import VaultFunctions
from broccol... | StarcoderdataPython |
159959 | from napalm import get_network_driver
from ping3 import ping
from ipaddress import ip_network, ip_address
driver = get_network_driver('huawei_vrp')
device = driver(hostname='IP', username='usernama', password='password')
device.open()
# Return general device information
get_interfaces_ip = device.get_interfaces_ip(... | StarcoderdataPython |
3242726 | <gh_stars>1-10
####################IMPORTS####################
#Imports from python
import json
#Imports from subprocess
import subprocess
#Imports from os
import os
from os import listdir
#Imports from os.path
from os.path import isfile
from os.path import join
####################CONSTANTS####################
B... | StarcoderdataPython |
150129 | <filename>tests/sources/local/tools/0_tracing_thread_clasification/result.py
import sys
import os
import time
from PrvLine import PrvLine
from PrvHeader import PrvHeader
TH_IDENT_EVENT="8001003"
runcompssThreads = {}
agentThreads = {}
runcompssHeader = ""
agentHeader = ""
runcompssThIdentEvents = {}
agentThIdentEven... | StarcoderdataPython |
114948 | import os
from pymongo import *
myclient = MongoClient(os.environ["COMTRIS_MONGODB_URI"])
db = myclient['COMTRIS']
col = db['pc_quote']
col.update({}, {'$inc' : {'id' : 2000000}}, multi=True) # id 200만 증가
# col.update({}, {'$inc' : {'id' , '2000000'}})
# 이 에러는 key : value를 맞추지 않은 경우에 발생한다.
# bson.errors.InvalidDocu... | StarcoderdataPython |
3331494 | import argparse
import pandas as pd
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--annotations_file", type=str, required=True,
help="CSV file of annotations.")
parser.add_argument("--mrsty_file", type=str, required=True,
help="Pa... | StarcoderdataPython |
3253328 | <gh_stars>1-10
import matplotlib.pyplot as plt
from matplotlib import style
from sklearn.cluster import KMeans
X = [[1.0, 1.0], [7.0, 9.0], [9.5, 8.0], [1.5, 2.0], [1.4, 1.7], [10, 10], [9.0, 8.0], [2.0, 1.8]]
kmeans = KMeans(n_clusters=2)
kmeans.fit(X)
centroids = kmeans.cluster_centers_
labels = kmeans.labels_
pr... | StarcoderdataPython |
1641771 | from django.conf.urls import include, url # noqa
from django.contrib import admin
from django.contrib.auth import views as auth_views
import django_js_reverse.views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^jsreverse/$', django_js_reverse.views.urls_js, name='js_reverse'),
url(r'^login/$'... | StarcoderdataPython |
13844 | __version__ = '5.2.158 f.LUM'
| StarcoderdataPython |
42175 | from sqlalchemy import Boolean, Column, ForeignKey, Integer, String, DATE
from sqlalchemy.orm import relationship
from database import Base
class User(Base):
__tablename__ = "users"
username = Column(String, primary_key=True, index=True)
email = Column(String, unique=True, index=True)
name = Column(... | StarcoderdataPython |
21926 | <filename>ch02/number_eight.py<gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 9 00:00:43 2018
@author: joy
"""
print(5 + 3)
print(9 - 1)
print(2 * 4)
print(16//2) | StarcoderdataPython |
78900 | <filename>application/apps.py
from django.apps import AppConfig
class ApplicationConfig(AppConfig):
name = 'application'
DB_APP_TABLE_PRE = 'app_'
DB_APP_LABEL = 'application'
# 过滤的UID
EXPECT_ID_LIST = [2, 4, 5, 7, 8, 9, 10]
| StarcoderdataPython |
1765884 | <reponame>morgunovvb/anfisa4friends<gh_stars>0
# ice_cream/views.py
from django.http import HttpResponse
# Импортируем загрузчик.
from django.template import loader
# Импортируем рендеринг
from django.shortcuts import render
# Главная страница
def index(request):
template = 'ice_cream/index.html'
return rende... | StarcoderdataPython |
67912 | <filename>pytest_xpara/plugin.py
from __future__ import absolute_import
import py.path
def pytest_configure(config):
config.addinivalue_line(
"markers", "xparametrize: mark test to run only on named environment"
)
def pytest_addoption(parser):
group = parser.getgroup('xpara', 'extended parametr... | StarcoderdataPython |
1688802 | # -*- coding: utf-8 -*-
from numpy import abs, newaxis, array
def get_cell_area(self, indices=None):
"""
Return the area of the cells on the outer surface.
#TODO address multiple cell type issue, i.e. distracted indices
Parameters
----------
self : MeshMat
a MeshMat object
indices ... | StarcoderdataPython |
149766 | <gh_stars>0
"""Implementation of basic nature-inspired algorithms."""
from niapy.algorithms.basic.abc import ArtificialBeeColonyAlgorithm
from niapy.algorithms.basic.ba import BatAlgorithm
from niapy.algorithms.basic.bea import BeesAlgorithm
from niapy.algorithms.basic.bfoa import BacterialForagingOptimizationAlgorith... | StarcoderdataPython |
165407 | # coding=utf8
from __future__ import unicode_literals, absolute_import, division, print_function
"""
This is the SpiceBot Logs system.
This Class stores logs in an easy to access manner
"""
import threading
import os
import sys
from sopel_modules.spicemanip import spicemanip
from .Config import config as botconfig
... | StarcoderdataPython |
19303 | <filename>models/015_bolasso.py<gh_stars>0
# %% Imports
from numpy.lib import select
import pandas as pd
import sys
import numpy as np
import random
from functools import partial
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sktools import IsEmptyExtractor
from lightgbm import LG... | StarcoderdataPython |
3369820 | <gh_stars>10-100
import Queue
import threading
from receita.tools.client import Client
class Runner(object):
"""Client runner.
We are keeping multiple requests running at the same time, but
in a limited fashion. This will allow a better performance while
getting data from the web service.
This ... | StarcoderdataPython |
1793923 | <filename>test/test_airtunnel/metadata/test_entities.py
from datetime import datetime, timedelta
from typing import Tuple
import pytest
from airtunnel.data_asset import ShellDataAsset
from airtunnel.metadata.adapter import SQLMetaAdapter, BaseMetaAdapter
from airtunnel.metadata.entities import Lineage, LoadStatus, In... | StarcoderdataPython |
1788478 | <reponame>ailyntong/implementation
class RelationNotExistError(Exception):
def __init__(self, tablename):
self.name = tablename
def __str__(self):
return "Relation %s does not exist" % self.name
class RelationOverwriteError(Exception):
def __init__(self, tablename):
self.name = tablename
def ... | StarcoderdataPython |
3260224 | import os
import unittest
from tests.config_reader import read_tpc_config
from wbtools.lib.nlp.literature_index.textpresso import TextpressoLiteratureIndex
@unittest.skipIf(not os.path.exists(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "data",
"loca... | StarcoderdataPython |
3212296 | # Importing pafy library
import pafy
# Taking url as input from the user
url = input("Enter URL: ")
# Creating a video instance
video = pafy.new(url)
# Using 'bestaudio()' to select the best audio file
bestaudio = video.getbestaudio()
# Using 'download()' to download the selected audio file
bestaudio.download()
| StarcoderdataPython |
144353 | #!/usr/bin/env python3
"""
Module to implement the Modified Seminario Method
Originally written by <NAME>, TCM, University of Cambridge
Modified by <NAME> and rewritten by <NAME>, Newcastle University
Reference using AEA Allen, MC Payne, DJ Cole, J. Chem. Theory Comput. (2018), doi:10.1021/acs.jctc.7b00785
"""
from Q... | StarcoderdataPython |
3221045 | <reponame>jsfillman/execution_engine2
"""
Unit tests for the EE2Runjob class.
"""
# Incomplete by a long way. Will add more unit tests as they come up.
import copy
import time
from logging import Logger
from typing import List, Dict, Any
from unittest.mock import create_autospec, call
from bson.objectid import Objec... | StarcoderdataPython |
15910 | <gh_stars>0
#!/usr/bin/env python
# By <NAME>
def fasta2dic(fastafilename): #read a fasta file into a dict
fasta_dict = {}
with open(fastafilename) as fastafile:
for line in fastafile:
if line[0] == ">":
head = line.strip()
fasta_dict[head] = ''
... | StarcoderdataPython |
74897 | <gh_stars>0
from time import time
TARGET_SUM = 200
COINS = [1, 2, 5, 10, 20, 50, 100, 200]
DYNAMIC_TABLE = {}
def calculate(point, coinset):
if point - coinset[0] < 0:
return 0
elif point == coinset[0]:
return 1
else:
if (point, str(coinset)) in DYNAMIC_TABLE:
return ... | StarcoderdataPython |
3399503 | <gh_stars>0
import numpy as np
import pandas as pd
def transform_email(df):
for col in ['P_emaildomain', 'R_emaildomain']:
col1 = col.replace('domain', '_suffix')
df[col1] = df[col].str.rsplit('.', expand=True).iloc[:, -1]
col2 = col.replace('domain', 'Corp')
df[col2] = df[col]
... | StarcoderdataPython |
145284 | <gh_stars>0
from ast import Str
from tkinter.messagebox import NO
from xmlrpc.client import TRANSPORT_ERROR
import colorama
import sys
from pyclbr import Function
import py
import pygame.gfxdraw
import pygame_widgets
import pygame
import keyboard
import math
import time
import random
import mouse
... | StarcoderdataPython |
3311619 | """Unit tests for q0502.py."""
import unittest
from src.q0502 import fraction_to_binary_digits
class MyFractionToBinaryDigits(unittest.TestCase):
def test_0_and_1(self):
self.assertEqual(fraction_to_binary_digits(0), 'Error')
self.assertEqual(fraction_to_binary_digits(1), 'Error')
def test... | StarcoderdataPython |
3377512 | import urllib3
import socket
import requests
import csv
import os
import PIL
from PIL import Image, UnidentifiedImageError
from urllib.error import HTTPError
from io import BytesIO
from concurrent.futures import ThreadPoolExecutor
class ImageManager():
'''
Class responsible to download and r... | StarcoderdataPython |
3379692 | nga_config = {
'top_categories': ['大时代', 'CS:GO', 'DOTA2', '网事杂谈']
} | StarcoderdataPython |
3312474 | <reponame>friendliai/crane-public
# Copyright (C) 2018-2021 Seoul National University
#
# 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
#
# Un... | StarcoderdataPython |
3292809 | # pylint: skip-file
#
# #!/usr/bin/env python
"""Tests for `cd_dot_cz_price_search` package."""
import unittest
# from cd_dot_cz_price_search import cd_dot_cz_price_search
class TestCd_dot_cz_price_search(unittest.TestCase):
"""Tests for `cd_dot_cz_price_search` package."""
def setUp(self):
"""Se... | StarcoderdataPython |
1724463 | import numpy as np
from pathlib import Path
class Experiment_Information:
def __init__(self, name, path, parameters, modulation):
'''
name: str
path: str
parameters: dict
'''
self.name = name
self.path = path
self.parameters = parameters
self.... | StarcoderdataPython |
4816165 | import uuid
from django.contrib.auth.hashers import make_password
from rest_framework_simplejwt.tokens import RefreshToken
from rest_framework.test import APITestCase
from django.urls import reverse
from .models import User
# Create your tests here.
class UserReadUpdateAPITestView(APITestCase):
url = reverse("us... | StarcoderdataPython |
1605925 | # -*- coding: utf-8 -*-
# -*- coding: mbcs -*-
#explanation:
#structure:frame
#load:ConcentratedForce in the edge
#post:RF,RM,U
#set Connector(BEAM) in the interaction point
#comment by lindinan in 20170831
from abaqus import *
from abaqusConstants import *
from caeModules import *
from interaction import *
from ... | StarcoderdataPython |
3350624 | import json
from typing import Tuple
import torch
from spert import util
from spert.input_reader import BaseInputReader
def convert_predictions(batch_entity_clf: torch.tensor, batch_rel_clf: torch.tensor,
batch_rels: torch.tensor, batch: dict, rel_filter_threshold: float,
... | StarcoderdataPython |
3380433 | <filename>src/sniffles/snifflesconfig.py
import calendar
import datetime
import getopt
import os
import re
import sys
import time
from os.path import join, normcase
from pkg_resources import DistributionNotFound, get_distribution
from sniffles.rulereader import (OPEN_PORT_CHANCE, SYN_SCAN,
... | StarcoderdataPython |
3259414 | <gh_stars>10-100
"""
Unit Tests for Misc Models
"""
import pytest
import vcr
from blaseball_mike.models import SimulationData, League, Season, GlobalEvent, \
SeasonStatsheet, Standings, Item, Modification, Weather
from blaseball_mike.tables import Tarot
from .helpers import TestBase, base_test, CASSETTE_DIR
from d... | StarcoderdataPython |
3361418 | <filename>pal/writer/access_mechanism/gas_aarch32.py
from pal.logger import logger
from pal.writer.access_mechanism.access_mechanism \
import AccessMechanismWriter
class GasAarch32AccessMechanismWriter(AccessMechanismWriter):
def call_readable_access_mechanism(self, outfile, register,
... | StarcoderdataPython |
3297841 | from _stories.mounted import ClassMountedStory
def contract_in(cls, *args):
def setter(contract):
for attrname in dir(cls):
attribute = getattr(cls, attrname)
if type(attribute) is ClassMountedStory:
attribute.contract(contract)
return contract
if args:... | StarcoderdataPython |
1756318 | <filename>src/api/dataflow/stream/job/job.py
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-BASE 蓝鲸基础平台 is licensed under the MIT License.
License for BK-BASE 蓝鲸基础平... | StarcoderdataPython |
1740649 | """Configuration variables for img_pipe."""
# Authors: <NAME> <<EMAIL>>
#
# License: BSD (3-clause)
import numpy as np
from matplotlib.colors import LinearSegmentedColormap
VOXEL_SIZES = np.array([256, 256, 256])
IMG_RANGES = [[0, VOXEL_SIZES[1], 0, VOXEL_SIZES[2]],
[0, VOXEL_SIZES[0], 0, VOXEL_SIZES[2]... | StarcoderdataPython |
3274486 | # The Vision Egg: Dots
#
# Copyright (C) 2001-2003 <NAME>.
# Copyright (C) 2005,2008 California Institute of Technology
#
# URL: <http://www.visionegg.org/>
#
# Distributed under the terms of the GNU Lesser General Public License
# (LGPL). See LICENSE.TXT that came with this file.
"""
Random dot stimuli.
"""
#######... | StarcoderdataPython |
31852 | <filename>tests/techniques/test_train_policy_gradient.py
import functools
from unittest import TestCase
from common.base_game_spec import BaseGameSpec
from common.network_helpers import create_network
from games.tic_tac_toe import TicTacToeGameSpec
from games.tic_tac_toe_x import TicTacToeXGameSpec
from techniques.tra... | StarcoderdataPython |
3210130 | """dict implementation specialized for object loaded by the _pypyjson module.
Somewhat similar to MapDictStrategy, also uses a map.
"""
from rpython.rlib import jit, rerased, objectmodel, debug
from pypy.objspace.std.dictmultiobject import (
UnicodeDictStrategy, DictStrategy,
create_iterator_classes, W_DictO... | StarcoderdataPython |
1787648 | <filename>labs/timeTrial.py
import sys
import cv2 as cv
import numpy as np
from nptyping import NDArray
from typing import Any,Tuple,List,Optional
sys.path.insert(0, "../library")
import racecar_core
import racecar_utils as rc_utils
rc = racecar_core.create_racecar()
BLUE = (( 90,200, 50),(110,255,255))
GREEN = (( ... | StarcoderdataPython |
1717419 | import logging
import torch
from ml.licchavi import Licchavi
""" LicchaviDev(Licchavi) class used for experiments only
Allows to use ground truths of generated data
"""
class LicchaviDev(Licchavi):
def __init__(
self, nb_vids, vid_vidx, crit,
test_mode=False, device='cpu', verb=1):
... | StarcoderdataPython |
1676409 | <filename>ddtrace/profiling/profiler.py
# -*- encoding: utf-8 -*-
import logging
import os
from ddtrace.profiling import recorder
from ddtrace.profiling import scheduler
from ddtrace.vendor import attr
from ddtrace.profiling.collector import exceptions
from ddtrace.profiling.collector import memory
from ddtrace.profil... | StarcoderdataPython |
113546 | x = 50
def func(x):
print('x is', x)
x = 2
print('Changed local x to', x)
func(x)
print('x is still', x) | StarcoderdataPython |
4835957 | #!/usr/bin/env python3
# Linear search
def linear_search(lst, item):
return item in lst
def linear_search_index(lst, item):
try:
return lst.index(item)
except ValueError:
return None
# Main execution
if __name__ == '__main__':
data = [1, 3, 6, 8, 9]
for i in range(10):
... | StarcoderdataPython |
191783 | <reponame>jercas/ML_DL_aiPlayground<gh_stars>0
# ========================================================== #
# File name: retrain_cifar-10_bn.py
# Author: BIGBALLON
# Date created: 07/27/2017
# Python Version: 3.5.2
# Tensorflow Vetsion: 1.2.1
# Result: test accuracy about 93.95 - 94.05%
# ============================... | StarcoderdataPython |
3210221 | '''
Clipboard Android
=================
Android implementation of Clipboard provider, using Pyjnius.
'''
__all__ = ('ClipboardAndroid', )
from kivy.core.clipboard import ClipboardBase
from kivy.clock import Clock
from jnius import autoclass, cast
from android.runnable import run_on_ui_thread
AndroidString = autocla... | StarcoderdataPython |
21794 | # This file was automatically generated by SWIG (http://www.swig.org).
# Version 4.0.2
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info as _swig_python_version_info
if _swig_python_version_info < (2, 7, 0):
raise Runtime... | StarcoderdataPython |
1717354 | <filename>ctci-solutions/3.1 stacks-in-array.py
# Problem: Implement 3 stacks in one array & keep min (3.1 + 3.2)
# Solution: Create push, pop, length functions for all 3 stacks and this should solve our purpose
import math
# TODO: Add check condition on pop when there's nothing in stack to respond with a message
class... | StarcoderdataPython |
1760690 | #!/usr/bin/env python
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
import django
django.setup()
# your imports, e.g. Django models
from buckets.models import *
all = ImageInfo.objects.all()
| StarcoderdataPython |
1702567 | <reponame>dgfonseca/Kata-Rest<filename>galleryTddProject/gallery/urls.py<gh_stars>0
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('addUser/', views.add_user_view, name='addUser'),
path('image/<int:params>', views.get_user_image, name='getUserIma... | StarcoderdataPython |
1627944 | """
@title vae.py
@author: <NAME>
@email: <EMAIL>
This script builds a Convolutional Variationel Autoencoder using keras framework with tensorflow backend.
"""
from keras.layers import Input, Dense, Reshape, Flatten, Lambda, Dropout
from keras.layers import BatchNormalization, MaxPooling2D
from keras.layers.advanced_... | StarcoderdataPython |
1763307 | <reponame>edaa-org/pyEDAA.ToolSetup<filename>pyEDAA/ToolSetup/Lattice/__init__.py<gh_stars>1-10
from typing import Dict
from pyTooling.Decorators import export
from .. import Tool, Vendor
from ..Aldec import ActiveHDL
from ..SiemensEDA import ModelSim
@export
class Diamond(Tool):
pass
@expor... | StarcoderdataPython |
1751107 | <filename>careless/utils/distributions.py
import tensorflow as tf
from tensorflow_probability.python.internal import special_math
from tensorflow_probability import distributions as tfd
import tensorflow_probability as tfp
from tensorflow_probability import bijectors as tfb
from tensorflow_probability.python.internal i... | StarcoderdataPython |
1694739 | """ Users' URLS """
# Django
from django.urls import path
# Local
from welcome import views
urlpatterns = [
path(
route='',
view=views.LandingPage.as_view(),
name='landing'
),
path(
route='base/',
view=views.LandingPage.as_view(),
name='home'
),
]
| StarcoderdataPython |
1698864 | import pandas
from detectors.tmd_base import TravelModeDetector
from sklearn import tree
from sklearn.metrics import accuracy_score
class DecisionTreeTMD(TravelModeDetector):
"""
Wrapper that uses DecisionTree to train a travel mode detector through smartphone sensors
"""
MODEL_FILENAME = 'model.pkl'... | StarcoderdataPython |
115267 | from collections import OrderedDict
from urllib import urlencode
from admino.serializers import ModelAdminSerializer
from django.core.urlresolvers import reverse_lazy
from django.http import JsonResponse
from django.views.generic import View
class APIView(View):
def json_response(self, data, *args, **kwargs):
... | StarcoderdataPython |
188510 | # Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
from google.cloud.datastore_v1.proto import (
datastore_pb2 as google_dot_cloud_dot_datastore__v1_dot_proto_dot_datastore__pb2,
)
class DatastoreStub(objec... | StarcoderdataPython |
178140 | """
SGDP Optimizer Implementation copied from https://github.com/clovaai/AdamP/blob/master/adamp/sgdp.py
Paper: `Slowing Down the Weight Norm Increase in Momentum-based Optimizers` - https://arxiv.org/abs/2006.08217
Code: https://github.com/clovaai/AdamP
Copyright (c) 2020-present NAVER Corp.
MIT license
"""
import ... | StarcoderdataPython |
160693 | import datetime
import os
from datetime import timedelta
import numpy
from esdl.cube_provider import NetCDFCubeSourceProvider
all_vars_descr = {'E': {
'evaporation': {
'source_name': 'E',
'data_type': numpy.float32,
'fill_value': numpy.nan,
'units': 'mm/day',
'long_name': ... | StarcoderdataPython |
1702388 | '''
Application mimicing actions of server.
'''
from flask import Flask, request, jsonify, Response
import requests
import json
import os,inspect
server = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
chunkedset = os.path.dirname(server)
from chunkedset import ChunkedSet
import sys
sys.pa... | StarcoderdataPython |
1658973 | <gh_stars>1-10
import networkx as nx
import dgl
from collections import defaultdict
from torch.utils.data import DataLoader
def regress(device, model, bg):
"""
Run a Graph model with DGL
:param device: Device to move to
:param model: DGL GCN
:param bg: Batched Graph
:return:
"""
bg = b... | StarcoderdataPython |
158822 | <reponame>ebi-ait/hca_util
import os
import filetype
from ait.commons.util.settings import DIR_SUPPORT, MAX_DIR_DEPTH
from ait.commons.util.common import format_err
from ait.commons.util.local_state import get_selected_area
import concurrent.futures
from concurrent.futures import ThreadPoolExecutor
from ait.commons.ut... | StarcoderdataPython |
178560 | <reponame>vicwjb/Pycad
from __clrclasses__.System.Collections.Specialized import BitVector32
from __clrclasses__.System.Collections.Specialized import CollectionsUtil
from __clrclasses__.System.Collections.Specialized import HybridDictionary
from __clrclasses__.System.Collections.Specialized import INotifyCollectionCha... | StarcoderdataPython |
146694 | import numpy as np
import re
import decimal
rule_names=[]
rules=[]
### Parsing
r1=re.compile("(.+): (\d+)-(\d+) or (\d+)-(\d+)")
with open('resources/day_16_tickets-data.txt','r') as f:
while(True):
m=r1.match(f.readline().strip())
if not m:
break
rule_names.append(m.groups()... | StarcoderdataPython |
68446 | # test waiting within async with enter/exit functions
import sys
if sys.implementation.name == 'micropython':
# uPy allows normal generators to be awaitables
coroutine = lambda f: f
else:
import types
coroutine = types.coroutine
@coroutine
def f(x):
print('f start:', x)
yield x + 1
yield x... | StarcoderdataPython |
3206300 | <gh_stars>0
import logging
import time
from modules.api import moduleBase
from modules.api import schemaBase
from modules.api import api_callback
from modules.base.util.mavlink import get_meta_string
# mavros & ros imports
import rospy
import mavros
import mavros.utils
from std_msgs.msg import String
from rosgraph_m... | StarcoderdataPython |
3216787 | # -*- coding: utf-8 -*-
import numpy as np
def load_streamflow(path):
"""load streamflow into memory
Args:
path (str|DataFrame): path of streamflow csv file, or pandas DataFrame
Returns:
tuple: (date of np.datetime64, streamflow of float)
"""
if isinstance(path, str):
dat... | StarcoderdataPython |
4808181 | <filename>create_game/tools/ladder.py
from .basic_obj import BasicObj, LINE_THICKNESS
from .gravity_obj import MOVING_OBJ_COLLISION_TYPE
from pymunk import Body
import pymunk
import pygame as pg
import numpy as np
from .img_tool import ImageTool
from .ramp import Ramp
def touching_handler(arbiter, space, data):
if... | StarcoderdataPython |
3364355 | <filename>tests/dashboard/test_category.py
from unittest.mock import Mock, patch
from django.urls import reverse
from remote_works.product.models import Category
from tests.utils import create_image
def test_category_list(admin_client, category):
url = reverse('dashboard:category-list')
response = admin_cli... | StarcoderdataPython |
82113 | <reponame>xuanqing94/fairseq<filename>fairseq/optim/new_lars.py
from fairseq.optim import FairseqOptimizer, register_optimizer
from torch.optim import SGD
@register_optimizer('lars')
class FairseqLARS(FairseqOptimizer):
"""LARS optimizer."""
def __init__(self, args, params):
super().__init__(args)
... | StarcoderdataPython |
1711839 | #!/usr/bin/env python3
import re
from lxml import etree, objectify
from pyquery import PyQuery as pq
p_xmlns = re.compile(r"xmlns\S+\s")
parser = etree.XMLParser(remove_blank_text=True)
def layers(dessin: etree.Element) -> (str, etree.Element):
for layer in dessin.findall('{http://www.w3.org/2000/svg}g'):
... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.