id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
8197014 | #!/usr/bin/env python
# Designed for use with boofuzz v0.0.9
from boofuzz import *
def main():
session = Session(
target=Target(
connection=SocketConnection("127.0.0.1", 5900, proto='tcp')
),
)
s_initialize(name="Handshake")
with s_block("ProtocolVersion"):
s_strin... | StarcoderdataPython |
1634198 | from collections import namedtuple, defaultdict
MenuItem = namedtuple("MenuItem", "section order label url")
def menu_order(item):
return item.order
class MenuRegistry(object):
def __init__(self):
self.callbacks = []
def register(self, func):
self.callbacks.append(func)
def get_me... | StarcoderdataPython |
355665 | # -*- coding:utf-8 -*-
import requests
import json
from bs4 import BeautifulSoup
from gevent import monkey
monkey.patch_all()
import gevent
import time
import csv
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
class TencentSpider(object):
def __init__(self):
self.base_url = "https://hr.tencent.co... | StarcoderdataPython |
9667755 | """Methods for working with i2c devices."""
__author__ = '<NAME>'
import time
try:
import smbus
except ImportError:
import smbus2 as smbus
class I2CDevice:
"""Base I2C device class."""
def __init__(self, addr, port=1):
# type: (int, int) -> None
"""Initialization.
:param ad... | StarcoderdataPython |
6638858 | <reponame>terror/Solutions
for _ in range(int(input())):
n = int(input())
p = list(map(int, input().split()))
print((max(p) - min(p)) + (max(p) - min(p)))
| StarcoderdataPython |
6518023 | """
Project: Visual Odometry
Name : Heru-05 | M09158023
Date : 10/06/2021
"""
import sys
import math
from enum import Enum
import numpy as np
import cv2
# https://www.robots.ox.ac.uk/~vgg/publications/2012/Arandjelovic12/arandjelovic12.pdf
# adapated from https://www.pyimagesearch.com/2015/04/13/implementing-roots... | StarcoderdataPython |
9758661 | <filename>subdomain_takeover_tools/extract_domain_names.py
import re
import sys
import tldextract
def main():
for line in sys.stdin:
sys.stdout.write(extract_domain_name(line) + '\n')
def extract_domain_name(subdomain):
if "(" in subdomain:
return _handle_pattern(subdomain)
else:
... | StarcoderdataPython |
1639904 |
'''
demo for single image
'''
import numpy as np
import cv2
import face_recognition
from face import Face
from utils import putText
from utils import preprocess_input
model = Face(train=False)
model.load_weights('./face_weights/face_weights.26-val_loss-3.85-val_age_loss-3.08-val_gender_loss-0.22-val_race_loss-0.55.... | StarcoderdataPython |
17723 | # vim: set encoding=utf-8
import re
from lxml import etree
import logging
from regparser import content
from regparser.tree.depth import heuristics, rules, markers as mtypes
from regparser.tree.depth.derive import derive_depths
from regparser.tree.struct import Node
from regparser.tree.paragraph import p_level_of
from... | StarcoderdataPython |
11319760 | <gh_stars>10-100
# Copyright 2019 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applic... | StarcoderdataPython |
9797187 | from model.contact import Contact
from model.group import Group
import random
def test_delete_contact_from_group(app, db, orm):
if len(db.get_contact_list()) == 0:
app.contact.create_new_contact(
Contact(firstname="test", middlename="middlename"))
if len(db.get_group_list()) == 0:
... | StarcoderdataPython |
8067441 | # MIT License
#
# Copyright (c) 2020, <NAME> AG
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, p... | StarcoderdataPython |
12814261 | # -*- encoding:utf-8 -*-
"""
Author: Yijie.Wu
Email: <EMAIL>
Date: 2020/5/14 13:43
"""
| StarcoderdataPython |
3530158 | import adsk.core, adsk.fusion, traceback
def run(context):
ui = None
try:
app = adsk.core.Application.get()
ui = app.userInterface
# Create a document.
doc = app.documents.add(adsk.core.DocumentTypes.FusionDesignDocumentType)
product = app.activeProduct
... | StarcoderdataPython |
1971011 | <reponame>Nisenco/react_fastapi
from app.config.config import settings
__all__ = ['settings']
| StarcoderdataPython |
3589249 | # 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, Optional, Sequence, Union, overload
from . import ... | StarcoderdataPython |
5100423 | class Solution:
def XXX(self, head: ListNode, n: int) -> ListNode:
array = []
cur = head
while cur:
array.append(cur)
cur = cur.next
if n == len(array):
head = head.next
else:
array[-n-1].next = array[-n-1].next.next
re... | StarcoderdataPython |
5061808 | <reponame>jonfisik/ScriptsPython
'''Exercício Python 111: Crie um pacote chamado utilidadesCeV que tenha dois módulos internos chamados moeda e dado. Transfira todas as funções utilizadas nos desafios 107, 108 e 109 para o primeiro pacote e mantenha tudo funcionando.'''
import moeda
#from moeda import metade, dobro, au... | StarcoderdataPython |
336883 | <gh_stars>1-10
# -*- coding: utf-8 -*-
import datetime
from django.test.testcases import TestCase
from ..models import News
from .factories import NewsFactory
from freezegun import freeze_time
today = datetime.date(2019, 3, 23)
@freeze_time(today)
class NewsManagerTestCase(TestCase):
def setUp(self):
# p... | StarcoderdataPython |
1836512 | import csv
import functools
import hashlib
import logging
import sys
import warnings
from collections import Counter
from os.path import isfile as isfile
import click
import cloudpickle
import loglizer
import mlflow
import mlflow.sklearn
import numpy as np
import pandas as pd
import sklearn
from elasticsearch import E... | StarcoderdataPython |
9720159 | #!/usr/bin/env python2.7
# -*- coding:UTF-8 -*-2
u"""battle.py
Copyright (c) 2019 <NAME>
This software is released under BSD license.
戦闘関連ソーサリーモジュール。
"""
import random as _random
import sorcery as _sorcery
# ---- Break ----
class Break(_sorcery.Sorcery):
u"""装備破壊ソーサリー。
"""
__slots__ = "__target",
d... | StarcoderdataPython |
6625439 | import os
from threading import Thread
from execo.action import TaktukPut
from execo.log import style
from execo_engine import logger
from div_p2p.wrapper import DivP2PWrapper
class TestThread(Thread):
"""This class manages the consumption and execution of combinations."""
def __init__(self, host, comb_manag... | StarcoderdataPython |
1690327 | # Copyright 2021 University of Adelaide
#
# 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 in... | StarcoderdataPython |
3229549 | <reponame>angstwad/set-cover-iam-roles<filename>find_solving_roles.py
# Copyright 2020 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/LICENSE-... | StarcoderdataPython |
3232562 | """Created on Wed Sep 08 2016 13:11.
@author: <NAME>
"""
import unittest
import numpy as np
from ..lyapunov_element_steering import LyapunovElementSteering
from ..perturb_zero import PerturbZero
from ..model_mee import ModelMEE
from ..reference_coe import ReferenceCOE
from ...orbital_mech.orbit import Orbit
from ...or... | StarcoderdataPython |
3338020 | #!/usr/bin/env python
#
# 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.0OA
#
# Authors:
# - <NAME>, <<EMAIL>>, 2019
"""
performance test to insert ... | StarcoderdataPython |
1723383 | for i in range(2):
for j in range(3):
print j
print i
| StarcoderdataPython |
11222274 | """
98 / 98 test cases passed.
Runtime: 36 ms
Memory Usage: 14.9 MB
"""
class Solution:
def checkPerfectNumber(self, num: int) -> bool:
return num in [6, 28, 496, 8128, 33550336]
"""
98 / 98 test cases passed.
Runtime: 40 ms
Memory Usage: 15.1 MB
"""
class Solution2:
def checkPerfectNumber(self, num: i... | StarcoderdataPython |
6599221 | <reponame>ahonnecke/jolly-brancher
"""Jira stuff."""
import logging
from enum import Enum
from jira import JIRA
_logger = logging.getLogger(__name__)
class IssueType(Enum):
EPIC = "EPIC"
STORY = "STORY"
ENHANCEMENT = "ENHANCEMENT"
BUG = "BUG"
TASK = "TASK"
SUBTASK = "SUB-TASK"
def get_all_... | StarcoderdataPython |
4883700 | import asyncio
from time import perf_counter
import pytest
# all test coroutines will be treated as marked
pytestmark = pytest.mark.asyncio
async def test_connected(cw):
assert cw.connected
async def test_get_info(cw):
info = await cw.get_info()
lines = info.strip().split("\n")
info_dict = dict([l... | StarcoderdataPython |
3222269 | <reponame>Eerie6560/PonjoPyWrapper
"""
Copyright 2022 <NAME>. All rights reserved.
Project licensed under the MIT License: https://www.mit.edu/~amini/LICENSE.md
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS F... | StarcoderdataPython |
12832617 | # Copyright 2019 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import enum
import http
import logging
import uuid
# pylint: disable=wrong-import-order
import flask
from google.protobuf import symbol_database
# pylin... | StarcoderdataPython |
1965828 | try:
from matplotlib import pyplot as plt
import matplotlib
except:
import matplotlib
matplotlib.rcParams['backend'] = 'TkAgg'
from matplotlib import pyplot as plt
import numpy as np
import pdb
def cornertex(s, ax, offset=(0,0), fontsize=14):
plt.text(0.02+offset[0],0.95+offset[1],s,transform=a... | StarcoderdataPython |
8034501 | <reponame>jontlu/ECE303-Comm-Nets
import datetime
import logging
class Logger(object):
def __init__(self, name, debug_level):
now = datetime.datetime.now()
logging.basicConfig(filename='{}_{}.log'.format(name, datetime.datetime.strftime(now, "%Y_%m_%dT%H%M%S")),
level=... | StarcoderdataPython |
8198021 | import pandas as pd
import warnings
def add_bins_col_to_rank_df(df_feature,
n_bins,
bin_no_col='bin_no',
item_rank_col='equity_rank',
max_rank_col='max_rank'
):
"""
Descr... | StarcoderdataPython |
151244 | <gh_stars>0
import setuptools
setuptools.setup() # still required for editable installs.
| StarcoderdataPython |
348887 | <filename>CA117/Lab_8/swapletters_51.py<gh_stars>1-10
(lambda l:print(''.join([l[i+1]+l[i]for i in range(0,len(l)-1,2)])+(l[-1]if len(l)%2else'')))(list(__import__("sys").argv[1]))
| StarcoderdataPython |
3485370 | '''Simple script that outputs dataset information.'''
from src.datasets.catalog import DATASET_DICT, PRETRAINING_DATASETS, TRANSFER_DATASETS
def bold(string):
return f'\033[1m{string}\033[0m'
def main():
print(bold('All supported datasets'))
max_name_len = max(len(name) for name in DATASET_DICT.keys())... | StarcoderdataPython |
6548429 | import pymysql
#database connection
connection = pymysql.connect(host="localhost", user="root", passwd="", database="databaseName")
cursor = connection.cursor()
# queries for inserting values
insert1 = "INSERT INTO Artists(NAME, TRACK) VALUES('Towang', 'Jazz' );"
insert2 = "INSERT INTO Artists(NAME, TRACK) VALUES('Sa... | StarcoderdataPython |
1820426 | import pytest
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), "..", ".."))
from src.map.DriverProfile import DriverProfile
def get_driver_profile_name(name, o_b_f, f_t, max_a, min_a, max_s, a_t, u_t_ms):
"""
Function returns the profile name of the driver
:param name: name of... | StarcoderdataPython |
3521189 | from pygame import mixer
import json
class AudioLoader:
def __init__(self, folder_location: str):
"""
Loads in audio
:param folder_location: Folder to load in
"""
self.audio_by_id = {}
self.audio = []
with open(f"{folder_location}/data.json", "r") as f:
... | StarcoderdataPython |
3559184 | import logging
import os
import subprocess
import sys
def cpuStats():
import psutil
print(sys.version)
print(psutil.cpu_percent())
print(psutil.virtual_memory()) # physical memory usage
pid = os.getpid()
py = psutil.Process(pid)
memoryUse = py.memory_info()[0] / 2.**30 # memory use in GB... | StarcoderdataPython |
6582352 | # -*- coding: utf-8 -*-
# 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://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | StarcoderdataPython |
5002674 | <reponame>MyrtoLimnios/covid19-biblio<filename>scripts/generate_readme/generate_readme.py
# -*- coding: UTF-8
import pandas as pd
# import sys
# sys.path.append('../utils/')
GG_SPREADSHEET = "https://docs.google.com/spreadsheets/d/1WWIOWnuJuOKKNQA71qgxs7IVHtYL7ROKm7m7LwGY3gU"
GG_SPREADSHEET_NAME = GG_SPREADSHEET + "/... | StarcoderdataPython |
4920131 | import os
import jinja2
import webapp2
import json
import logging
import re
import includes
from google.appengine.ext import ndb
from google.appengine.api import urlfetch
urlfetch.set_default_fetch_deadline(60)
import Blocktrail_com
import Blockchain_info
import Insight
def validAddress(address):
valid = False
... | StarcoderdataPython |
1818950 | <gh_stars>1-10
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
class C4JtumblrPipeline(object):
def process_item(self, item, spider):
# replace image src to downl... | StarcoderdataPython |
82680 | <reponame>ChristopherBradley/rad-classify
from os.path import join, dirname
# Default stuff
src_folder = dirname(__file__)
root_folder = dirname(src_folder)
data_folder = join(root_folder, 'data')
# WOS stuff
wos_folder = join(data_folder, "WebOfScience")
WOS5736_X = join(wos_folder, "WOS5736", "X.txt")
WOS5736_Y =... | StarcoderdataPython |
4974017 | <reponame>wpfff/labcore
from typing import Any, Callable, Union
import inspect
def same_type(*args: Any, target_type: type = None) -> bool:
"""Check whether all elements of a sequence have the same type.
:param seq: Sequence to inspect
:param target_type: if not `None`, check if all elements are of that ... | StarcoderdataPython |
6650962 | # ---
# jupyter:
# jupytext:
# formats: ipynb,py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.2'
# jupytext_version: 1.2.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %% [markdown]
# # T... | StarcoderdataPython |
82399 | # -*- coding: utf-8 -*-
# @File : session.py
# @Date : 2021/2/25
# @Desc :
from Lib.api import data_return
from Lib.configs import Session_MSG_ZH, CODE_MSG_ZH, RPC_SESSION_OPER_SHORT_REQ, CODE_MSG_EN, Session_MSG_EN
from Lib.log import logger
from Lib.method import Method
from Lib.notice import Notice
from Lib.rpcc... | StarcoderdataPython |
8010678 | <gh_stars>10-100
from twitter_analysis import get_tweets
import simplejson
thefile = open('tweets.txt', 'w')
tweets = list(get_tweets('Urbandecay', tweets=100, retweets=False))
for tweet in tweets:
print(tweet['text'])
simplejson.dump(tweet,thefile)
thefile.write('\n')
thefile.close()
| StarcoderdataPython |
133716 | from typing import Any, Mapping
from ghaudit.query.sub_query_common import SubQueryCommon
from ghaudit.query.utils import PageInfo
class OrgRepoQuery(SubQueryCommon):
FRAGMENTS = ["frag_org_repo_fields.j2", "frag_org_repo.j2"]
def __init__(self) -> None:
SubQueryCommon.__init__(
self,
... | StarcoderdataPython |
11370408 | <gh_stars>0
import util.game_info as gi
import numpy as np
from time import time
from Networks.legacy.XInputReader import get_xbox_output as get_controller_output
from util.data_processor_v3 import xbox_to_rlbot_controls
from util.game_info import GameInfo
from util.vector_math import Vector3, angle
from rlbot.agents.b... | StarcoderdataPython |
5043480 | <reponame>UKPLab/arxiv2018-xling-sentence-embeddings
import tensorflow as tf
from tensorflow.contrib.layers import xavier_initializer, l2_regularizer
def weight_variable(name, shape, regularization=None):
regularizer = None
if regularization is not None:
regularizer = l2_regularizer(regularization)
... | StarcoderdataPython |
9665524 | import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import numpy as np
"""
A basic dataset for pytorch.
"""
class Dataset:
def __init__(self, data, label):
self.data = data
self.label = label
def __len__(self):
return len(self.data)
def __getitem__(self, i):... | StarcoderdataPython |
6559978 | <reponame>OUCyf/SeisFlow
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 29 20:07:31 2021
Input
1. Generate tmp file: find $(pwd) -name \*.SAC > ../tmp.sac
2. Run this script
3. KILL: ps -aux|grep python|grep -v grep|gawk '{print $2}' |xargs kill -9
Output
1.DB_output format: [... | StarcoderdataPython |
4809367 | <gh_stars>0
import argparse
import os
from datetime import datetime, timedelta, timezone
import logging
from radiko.recorder import record_time_free
def _get_args():
parser = argparse.ArgumentParser(description='record radiko')
parser.add_argument('station', type=str, help='radiko station')
parser.add_ar... | StarcoderdataPython |
1668372 | <filename>Crawler/src/database/scanner.py<gh_stars>1-10
"""
This script starts a scanner that scans through the database
to check expired links
"""
from datetime import datetime, timedelta
def db_scanner(collection):
"""
continuously check to see if any URL is expired
By expiri... | StarcoderdataPython |
11216850 | from .bme280 import Bme280
from .bme280 import HO_SKIPPED, HO_1, HO_2, HO_4, HO_8, HO_16
from .bme280 import PO_SKIPPED, PO_1, PO_2, PO_4, PO_8, PO_16
from .bme280 import TO_SKIPPED, TO_1, TO_2, TO_4, TO_8, TO_16
from .bme280 import MODE_SLEEP, MODE_FORCED, MODE_NORMAL
from .bme280 import TSTANDBY_0_5, TSTANDBY_62_5, T... | StarcoderdataPython |
30373 | from django.conf import settings
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser, \
PermissionsMixin
from django.core.mail import send_mail
from django.db import models
from django.template.loader import render_to_string
from django.utils import timezone
from django.utils.translation import... | StarcoderdataPython |
1794912 | <filename>segmenter/layers/NoisyOr.py
from tensorflow.keras.layers import Multiply
class NoisyOr(Multiply):
def _merge_function(self, inputs):
output = 1. - inputs[0]
for i in range(1, len(inputs)):
output *= 1. - inputs[i]
return 1. - output
| StarcoderdataPython |
3416954 | <reponame>Ca2Patton/PythonStuff<gh_stars>0
#!/Library/Frameworks/Python.framework/Versions/2.7/bin/python
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import NumericProperty, ReferenceListProperty, ObjectProperty
from kivy.vector import Vector
from kivy.clock import Clock
from random... | StarcoderdataPython |
5120032 | """ Handler for the hook and rhook action tags. """
# pylint: disable=too-few-public-methods,too-many-arguments,protected-access,unused-argument
__author__ = "<NAME>"
__copyright__ = "Copyright 2016-2019"
__license__ = "Apache License 2.0"
from . import ActionHandler
from ..nodes import Node
from ..tokenizer import ... | StarcoderdataPython |
1955623 | <reponame>betagouv/ecosante<filename>migrations/versions/ca7c02fcb035_add_chauffage_animaux_connaissance.py
"""Add chauffage, animaux, connaissance
Revision ID: <KEY>
Revises: 723f9ab27edf
Create Date: 2021-03-10 15:05:29.180649
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgr... | StarcoderdataPython |
9635643 | <reponame>NULLCT/LOMC
import heapq
N, Q = map(int, input().split())
INF = float('inf')
G = [[] for _ in range(N)]
for i in range(N - 1):
a, b = map(int, input().split())
G[a - 1].append([1, b - 1])
G[b - 1].append([1, a - 1])
def dijkstra(N, start, goal, edge_list):
Q = []
#始点距離=0, (dist, vertex... | StarcoderdataPython |
3417600 | #!/usr/bin/env python
# From Hendrik
import math, string, sys, os
import scipy
import scipy.integrate
def norm(k_vec): # the norm of a 3d vector
return math.sqrt(k_vec[0]**2+k_vec[1]**2+k_vec[2]**2)
def W_k(k_vec): # the Fourier transform of the survey volume
a=k_vec[0]*l[0]/2
b=k_vec[1]*l[1]/2
c=k_v... | StarcoderdataPython |
3375935 | # Copyright 2020 Huawei Technologies Co., Ltd
#
# 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 |
5093589 | <gh_stars>100-1000
"""
XX. Model inheritance
Model inheritance across apps can result in models with the same name resulting
in the need for an %(app_label)s format string. This app specifically tests
this feature by redefining the Copy model from model_inheritance/models.py
"""
from django.db import models
from mode... | StarcoderdataPython |
9661982 | <filename>fisher_score.py
from __future__ import division, print_function
import nibabel as nb
import numpy as np
import click
import os
import csv
import itertools
from tqdm import tqdm
from healthybrains.inputoutput import id_from_file_name
@click.command()
@click.option("--targets")
@click.argument("file_names", ... | StarcoderdataPython |
11290214 | <reponame>gf-atebbe/python-mandrel<filename>mandrel/test/integration_test.py
import unittest
import os
import yaml
from mandrel.test import utils
import mandrel
from mandrel import config
BOOTSTRAP = """
bootstrap.SEARCH_PATHS.insert(0, 'specific_config')
bootstrap.DISABLE_EXISTING_LOGGERS = False
"""
def logger_conf... | StarcoderdataPython |
11253843 | <reponame>johntellsall/minibatch<filename>minibatch/window.py
import datetime
from minibatch import Buffer, Stream
from minibatch.models import Window
class WindowEmitter(object):
"""
a window into a stream of buffered objects
WindowEmitter.run() implements the generic emitter protocol as follows:
... | StarcoderdataPython |
11322450 | """Test to verify that we can load components."""
from unittest.mock import ANY, patch
import pytest
from homeassistant import core, loader
from homeassistant.components import http, hue
from homeassistant.components.hue import light as hue_light
from tests.common import MockModule, async_mock_service, mock_integrat... | StarcoderdataPython |
1925509 | from wrappers.glove_obs_wrapper import GloveObsWrapper
from wrappers.tokenize_obs_wrapper import TokenizeObsWrapper
from wrappers.floor_obs_wrapper import FloorObsWrapper
from wrappers.restful_cartpole_v0_wrapper import RestfulCartPoleV0Wrapper
from wrappers.restful_acrobot_v1_wrapper_v1 import RestfulAcrobotV1WrapperV... | StarcoderdataPython |
6456410 | from django.shortcuts import render, redirect
from ..models import Assignment, AssignmentModule, Course
from .. import forms
from .utilities import alwaysContext
class ModuleWrapper():
def __init__(self, name, id, assignments):
self.name = name
self.id = id
self.assignments = assignments
... | StarcoderdataPython |
3427776 | # Copyright 2018 DeepMind Technologies Limited. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | StarcoderdataPython |
9616650 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division
import numpy as np
import math
import torch
def unNormalizeData(normalized_data, data_mean, data_std, dimensions_to_use):
T = normalized_data.shape[0] # Batch size
D = data_mean.shape[0] # 96
orig_data = np.zeros((T, D), dt... | StarcoderdataPython |
8495 | from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
urlpatterns = [
# Examples:
# url(r'^$', 'evetool.views.home', name='home'),
url(r'^', include('users.urls')),
url(r'^', include('apis.urls')),
] + static(settings.STATIC_URL, document_... | StarcoderdataPython |
1974878 | '''
Created on 11 Oct 2016
@author: <NAME>
'''
# pylint: disable=missing-docstring
import argparse
import collections
import csv
import json
import logging
import os
import re
import shutil
import sys
import zipfile
import zlib
import jinja2
import msgpack
import numpy
import pandas
import yaml
import pubtransit
... | StarcoderdataPython |
3442935 | from typing import Any, Iterable
class CustomSet:
def __init__(self, _elements: Iterable[Any] = []):
self._elements = []
for e in _elements:
self.add(e)
def isempty(self) -> bool:
return len(self._elements) == 0
def __contains__(self, element: Any) -> bool:
re... | StarcoderdataPython |
11244050 | import argparse
from pathlib import Path
from chomskIE.dataset import (Loader,
Writer,
DummyLoader,
DummyWriter)
from chomskIE.utils import (retrieve_spacy_language,
filter_invalid_sents,
... | StarcoderdataPython |
11201255 | <filename>Algorithm/QTOpt/dis/PendulumFullState1.py
import gym
import tensorflow as tf
from RunClient import runClient
def createEnvironemnt(environment = "Pendulum-v0"):
return gym.make(environment).env
enviroment = createEnvironemnt()
#enviroment.render()
print('Number of states: {} High: {} Low {}'.format(en... | StarcoderdataPython |
1860566 | import os
from os.path import dirname, abspath, join
def _get_posts():
parent_dir = dirname(dirname(abspath(__file__)))
postfiles = os.listdir(join(parent_dir, 'posts'))
posts = []
for pf in postfiles:
posts.append(
{
'link': pf[:-3],
'title': pf[10:... | StarcoderdataPython |
1936690 | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Author: <NAME>
from sonarqube.utils.rest_client import RestClient
from sonarqube.utils.config import (
API_FAVORITES_ADD_ENDPOINT,
API_FAVORITES_REMOVE_ENDPOINT,
API_FAVORITES_SEARCH_ENDPOINT,
)
from sonarqube.utils.common import POST, PAGE_GET
class SonarQu... | StarcoderdataPython |
151892 | <filename>setup.py
from setuptools import setup
setup(
name='toshiservices',
version='0.0.1',
author='<NAME>',
author_email='<EMAIL>',
packages=['toshi'],
url='http://github.com/IceExchange/ice-services-lib',
description='',
long_description=open('README.md').read(),
setup_requires=... | StarcoderdataPython |
1790389 | <gh_stars>100-1000
"""LikeTopic
Revision ID: <KEY>
Revises: <KEY>
Create Date: 2013-12-12 12:35:12.253544
"""
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = '<KEY>'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table(
'like_topic',
sa.Colu... | StarcoderdataPython |
3554930 | <gh_stars>1-10
from dataclasses import dataclass
from somerandomapi import http
from somerandomapi.constants import ANIMALS
from somerandomapi.sync_async_handler import SyncAsyncHandler
@dataclass
class AnimalResponse:
"""
Attributes
----------
- fact: `str`
- image: `str`
"""
fact: str
... | StarcoderdataPython |
8111651 | # Copyright 2014-2015 <NAME>.
# This file is part of SGGL. SGGL is licensed under the terms of the
# 2-clause BSD license. For more information, see LICENSE.txt.
import os
import xml.etree.ElementTree as etree
import collections
import io
import re
API_LIST = 'gl:core', 'gl:compatibility', 'gles1', 'gles2'
NOTICE =... | StarcoderdataPython |
348823 | <reponame>milkmiruku/diorite
#! /usr/bin/env python
# encoding: UTF-8
# Copyright 2009 <NAME>
# Copyright 2017 <NAME> <<EMAIL>>
"""
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must reta... | StarcoderdataPython |
8151347 | <filename>syncmm/spotify.py
# According to old code-style
# Written by Sergievsky
# https://github.com/yepIwt
# 2021
import spotipy
from librespot.core import Session
class Library:
__scope = "user-library-read"
__tracks = []
_access_token = None
def __init__(self, login: str = None, password: str... | StarcoderdataPython |
8071748 | import pickle
import csv
import numpy as np
import torch
from ml_logger import logger
path = 'gs://ge-data-improbable/checkpoints/model-free/model-free/rff_post_iclr/dmc/drq/4_layer/mlp/{env}/{seed}/checkpoint/replay_buffer.pkl'
envs = ['Acrobot-swingup', 'Quadruped-run', 'Quadruped-walk', 'Humanoid-run', 'Finger-tur... | StarcoderdataPython |
1611714 | #!/usr/bin/env python
from __future__ import print_function
import sys
from Bio import SeqIO
def main():
'''Extract the 20 bp sgRNA sequence from a longer seqeuence string'''
if len(sys.argv) < 2:
print('Usage: {} sequence.fa'.format(sys.argv[0]), file=sys.stdout)
record = SeqIO.read(sys.argv[1],... | StarcoderdataPython |
9726950 | <filename>tests/resources/transaction/test_dashboard.py
from twisted.internet.defer import inlineCallbacks
from hathor.transaction.resources import DashboardTransactionResource
from tests import unittest
from tests.resources.base_resource import StubSite, _BaseResourceTest
class BaseDashboardTest(_BaseResourceTest._... | StarcoderdataPython |
146792 | <filename>setup.py
#!/usr/bin/env python
# coding: utf-8
from yudzuki import __version__
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
long_description = ""
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
... | StarcoderdataPython |
4927739 | <filename>util/clavero/CNNTrainer.py
class CNNTrainer(AbstractTrainer):
"""
Trainer for a simple class classification CNN.
"""
def __init__(self, dataset_name, train_validation_split=.8, resume_checkpoint=None, batch_size=16, workers=4,
n_gpu=0, epochs=2, learning_rate=.01, momentum=.8... | StarcoderdataPython |
3234913 | # Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @param sum, an integer
# @return a list of lists of integers
def pathSum(self, root, sum):
... | StarcoderdataPython |
11318380 | <filename>src/deprecated/revaluate.py<gh_stars>1-10
import os, sys, glob
import pickle
import numpy as np
from models import *
from agents import *
from utils.World import World
def evaluate(model, algorithm, graphics = False, robot = None, save_postfix=None):
"""This function evaluate a algorithm's performance on... | StarcoderdataPython |
6649899 | <reponame>mayi140611/mayiutils
#!/usr/bin/python
# encoding: utf-8
"""
@author: Ian
@contact:<EMAIL>
@file: scikit_surprise_wrapper.py
@time: 2019/3/13 12:22
https://pypi.org/project/scikit-surprise/#description
https://surprise.readthedocs.io/en/stable/getting_started.html
pip install scikit-surprise
scikit-surprise... | StarcoderdataPython |
11235996 | <reponame>anjalijain22/mity<filename>utils/chunky_regions.py<gh_stars>10-100
#!/usr/bin/env python3
# This code is adapted from fasta_generate_regions.py from https://github.com/ekg/freebayes
# usage: python3 chunky_regions.py --chunk_size INT --region [CHR:START-END] --bam_header_path [PATH]"
# or
# Usage: bam_head... | StarcoderdataPython |
5007733 | <filename>python_files/trainer.py
import cv2
import numpy as np
from PIL import Image
import os
from get_yml import *
recognizer = cv2.face.LBPHFaceRecognizer_create()
detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
path1 = '../Dataset'
for classes in os.listdir(path1):
path2=os.path.joi... | StarcoderdataPython |
5008033 | import os
import tempfile
import numpy as np
import xarray as xr
from fv3fit.emulation.data import io
def _get_ds():
return xr.Dataset(
{
"air_temperature": xr.DataArray(
data=np.arange(30).reshape(10, 3), dims=["sample", "z"]
),
"specific_humidity": x... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.