id stringlengths 2 8 | text stringlengths 16 264k | dataset_id stringclasses 1
value |
|---|---|---|
9610340 | <gh_stars>0
import model.m_mysql as db
class MUser(object):
@staticmethod
def get_user_id_of_account_id(account_id):
'''
获取账户编号所对应的用户编号
@param account_id:int 账户编号
@return int user_id用户编号
@version v0.0.1 闫涛 2019-03-16
'''
sql = 'select user_id from t_user ... | StarcoderdataPython |
11343400 | <filename>step1/util/metrics.py
import torch
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
from math import exp
import math
from . import pytorch_ssim
import pdb
def gaussian(window_size, sigma):
gauss = torch.Tensor([exp(-(x - window_size/2)**2/float(2*sigma**2)) for x in ran... | StarcoderdataPython |
1815327 | <reponame>blackhatethicalhacking/dfirtrack
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from dfirtrack_main.logger.default_logger import info_logger
from dfirtrack_main.models import System
import csv
from time import strftime
@login_required(login_url="/login")
def sy... | StarcoderdataPython |
4998404 | import random
import string
EOL = '\r\n'
def gen_str(length=10, letters=string.ascii_letters+string.digits):
return "".join([random.choice(letters) for n in range(length)])
| StarcoderdataPython |
6575558 | import os
def count_lines(start=".", lines=0, blacklisted_dirs=["venv"], file_extensions=["py"]):
for file in os.listdir(start):
relative_path = os.path.join(start, file)
if os.path.isfile(relative_path) and relative_path.split(".")[-1] in file_extensions:
with open(relative_path, 'r',... | StarcoderdataPython |
6648042 | <reponame>AdamKlekowski/moler<gh_stars>1-10
# -*- coding: utf-8 -*-
"""
Testing command specific API
Command is a type of ConnectionObserver.
Testing ConnectionObserver API conformance of Command is done
inside test_connection_observer.py (as parametrized tests).
- call as function (synchronous)
- call as future (as... | StarcoderdataPython |
142971 | """
996. Number of Squareful Arrays
Given an array A of non-negative integers, the array is squareful if for every pair of adjacent elements, their sum is a perfect square.
Return the number of permutations of A that are squareful. Two permutations A1 and A2 differ if and only if there is some index i such that A1[i]... | StarcoderdataPython |
112553 | <reponame>smurfix/distkv
import pytest
import io
from functools import partial
from distkv.mock import run
from distkv.mock.mqtt import stdtest
from distkv.client import ServerError
from distkv.util import PathLongener, P
import logging
logger = logging.getLogger(__name__)
async def collect(i, path=()):
res =... | StarcoderdataPython |
4896250 | #!/usr/bin/python
#PIN 0-8 3v3 pull-up default, 9-27 pull-down default
# Raspberry Pi SPI Port and Device
spi_port = 0
spi_dev = 0
# Pin # for relay connected to heating element
he_pin = 26
brew_pin = 17
steam_pin = 22
#overriding the time config when wanting to heat up not during normal hours
overRide = 16
# D... | StarcoderdataPython |
11299447 | <filename>tests_3_8/async/test_exceptions.py
# The module ``unittest`` supports async only from 3.8 on.
# That is why we had to move this test to 3.8 specific tests.
# pylint: disable=missing-docstring, invalid-name, unnecessary-lambda
import unittest
from typing import Optional, List
import icontract
class TestSyn... | StarcoderdataPython |
4864432 | <gh_stars>10-100
#
# Copyright 2015 Quantopian, Inc.
#
# 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 o... | StarcoderdataPython |
8042191 | # =================================================
# <EMAIL>
# 11. 이미지 변환 - 리사이징, 이동, 회전, 원근효과
# Reference : <EMAIL>
# =================================================
import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
# A. Image Resizing
def transform_resize():
img = cv.imread('../Images/11.Ji.jpg... | StarcoderdataPython |
68796 | import tensorflow as tf
import os
import time
import numpy as np
import glob
import matplotlib.pyplot as plt
import PIL
import imageio
import argparse
import dataset as dt
INPUT_SHAPE = (32, 32, 1)
tf.random.set_seed(777)
NORM_LIST = ["interframe_minmax", "est_minmax", "zscore"]
class ConvVAE(tf.keras.Model):
... | StarcoderdataPython |
276816 | <gh_stars>0
# minesweeper.py - Minesweeper
from random import randint
from colorama import Fore, Back, Style, init, deinit
from re import compile, match
class Board(object):
'''
A minesweeper board loaded with mines and numbers.
Properties:
height: An integer for the board's height / number of rows
width: An... | StarcoderdataPython |
285562 | <reponame>zerodine/krypton<filename>krypton/hkpserver/libs/gossip/gossiptask.py
from krypton.hkpserver.libs.recon import ReconPartner, Recon
__author__ = "<NAME>, <NAME>"
__copyright__ = "Copyright 2013, Zerodine GmbH (zerodine.com) "
__credits__ = ["<NAME>", "<NAME>"]
__license__ = "Apache-2.0"
__maintainer__ = "<NAM... | StarcoderdataPython |
8151320 | <reponame>pplotn/team6
from F_modules import *
# Plotting
def numstr(x):
string = str('{0:.2f}'.format(x))
return string
def F_nrms(mat,mat_true):
nrms = np.linalg.norm((mat-mat_true),ord=2)/np.linalg.norm(mat_true,ord=2)
return nrms
def F_r2(mat,mat_true):
r2=1- (np.std(mat_true.flatten()-mat.fla... | StarcoderdataPython |
12805698 | <reponame>Joes-BitGit/Leetcode
# DESCRIPTION
# Given a non-empty binary tree, find the maximum path sum.
# For this problem, a path is defined as any sequence of nodes
# from some starting node to any node in the tree along the parent-child connections.
# The path must contain at least one node and does not need to go ... | StarcoderdataPython |
8096177 | <reponame>billyrrr/onto
def default_field_resolver(source, info, **args):
"""Default field resolver.
If a resolve function is not given, then a default resolve behavior is used which
takes the property of the source object of the same name as the field and returns
it as the result, or if it's a functio... | StarcoderdataPython |
6634371 | <reponame>prasoon-uta/IBM-coud-storage<gh_stars>0
# Copyright 2014 IBM Corp.
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | StarcoderdataPython |
8048370 | <filename>solutions/problem_038.py
def is_valid(board, row):
if row in board:
return False
column = len(board)
for occupied_column, occupied_row in enumerate(board):
if abs(occupied_row - row) == abs(occupied_column - column):
return False
return True
def get_queen_config... | StarcoderdataPython |
8048356 | <reponame>HappyHackingNinja/HappyHackingMCDSSurprise
import sys
from hhmcds.model import 早安鬧鐘資料
from hhmcds.surprise import 抽獎
from hhmcds.smurf import 分身
from hhmcds.imei import get_imei
import datetime
from openpyxl import workbook, styles
from hhmcds.gmail import active_then_delete
import time
def 抽獎流程(gmail, pass... | StarcoderdataPython |
12809387 | # noqa: D, V, E241
import sublime
import ctypes
import time
import platform
import subprocess
_debug = False
def debug(*args):
if _debug:
print(*args)
SPEC = {
# dir explorer
'dir': {
'Darwin': ['open', '<__path__>'],
'Linux': ['nautilus', '--browser', '<__path__>']... | StarcoderdataPython |
11212348 | from django.conf import settings
from django.conf.urls import url
from django.contrib import admin
from django.urls import include
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
url(r'^admin/', admin.site.urls),
] + static(settings.MEDI... | StarcoderdataPython |
1669605 | <reponame>Zalewa/doomstats
#!/usr/bin/python
#-*- coding: utf-8 -*-
from django.core.management.base import BaseCommand
from django.apps import apps
class Command(BaseCommand):
def handle(self, *args, **options):
app_models = apps.get_app_config('presentation').get_models()
for model in app_models... | StarcoderdataPython |
1838558 | <reponame>willf/pypatgen
'''
Created on Feb 19, 2016
@author: mike
'''
from __future__ import print_function
import codecs
import re
import argparse
TEMPLATE = r'''
\documentclass{article}
\usepackage{polyglossia}
\usepackage{xltxtra}
\usepackage{testhyphens}
\setdefaultlanguage{churchslavonic}
\newfontfamily\churc... | StarcoderdataPython |
1838834 | from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.screenmanager import ScreenManager, Screen
class Gerenciador(ScreenManager):
pass
class Menu(Screen):
pass
class Tarefas(Screen):
def __init__(self, tarefas=[], **kwargs):
super().__init__(**kwargs)
for t i... | StarcoderdataPython |
3205350 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Z-Wave Interpreter - Constants © Autolog 2020
#
# Z-Wave Interpreter common constants
# Z-Wave Command Classes and ZW_COMMANDS
# ### Shared Constants ###
ZW_BATTERY_LEVEL = 1
ZW_BATTERY_LEVEL_UI = 2
ZW_COMMAND = 4
ZW_COMMAND_BYTES = 5
ZW_COMMAND_BYTES_UI = 6
ZW_COM... | StarcoderdataPython |
6476618 | from visual import *
# <NAME>, March 2002
# Import this module to create buttons, toggle switches, sliders, and pull-down menus.
# See test routine at end of this module for an example of how to use controls.
lastcontrols = None # the most recently created controls window
gray = (0.7, 0.7, 0.7)
darkgray = (0.... | StarcoderdataPython |
6645893 | from flask import g
from lowball.builtins.error_handler import default_error_handler
from lowball.builtins.response_class import LowballResponse
class TestDefaultErrorHandler:
def test_basic_exception_handled_properly(self, basic_exception, client_with_response_class):
response = default_error_handler(ba... | StarcoderdataPython |
12803192 | <gh_stars>0
from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt
import base64,time,random,hashlib,json,re,django,platform
from . import server_helper,match,view,web_socket,search_process,GlobalVar,anticheatz
from www.index import player... | StarcoderdataPython |
3489323 | '''
Common testing environment configuration.
'''
import os
# Default environment configuration file.
DEFAULT_ENVIRONMENT="environment/default.json"
# Default image comparison tolerance.
DEFAULT_TOLERANCE = 1e-12
# Default image test timeout.
DEFAULT_TIMEOUT = 600
IMAGE_TESTS_DIR = "Tests/image_tests"
# Supported... | StarcoderdataPython |
8082890 | # Generated by Django 3.0.6 on 2020-05-27 22:54
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0011_update_proxy_permissions'),
... | StarcoderdataPython |
6449985 | <filename>mapproxy/test/system/test_mapserver.py
# This file is part of the MapProxy project.
# Copyright (C) 2011 Omniscale <http://omniscale.de>
#
# 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... | StarcoderdataPython |
8139238 | <reponame>iribirii/daily_scripts
#!/usr/bin/env python3
# Author: <NAME>
# 01-12-2020
'''
##################
## Description: ##
##################
This script generates gaussian inputs from the selected xyz files.
############
## Usage: ##
############
xyztogjf file 'commands for gaussian'
'''
# Imports
imp... | StarcoderdataPython |
6688007 | <filename>archived/image_transfer/client/client.py
import socket
from PIL import Image
import numpy as np
port = 8001
host = 'localhost'
s = socket.socket()
s.connect((host,port))
imageFolder = "./images/"
imageFormat = ".png"
imageIndex = 0
n = 0
while True:
imagebytes = s.recv(307200*4)
if imagebyt... | StarcoderdataPython |
3498697 | def lucky_sum(a, b, c):
sm = 0
for n in (a, b, c):
if n != 13:
sm += n
else:
break
return sm
def close_far(a, b, c):
a_b_diff = abs(a - b)
a_c_diff = abs(a - c)
b_c_diff = abs(b - c)
return (
(a_b_diff <= 1 and a_c_diff >= 2 and b_c_diff >= 2... | StarcoderdataPython |
1741725 | """Funções de suporte para Árvore Binária."""
def gerar_nova_sub_arvore(esquerda, direita):
"""Combina ambos os galhos para formar uma nova sub-árvore, se necessário.
Se o nodo a ser removido possui dois filhos, um será ser promovido ao espaço
do que está sendo removido, mas o outro galho não pode ser pe... | StarcoderdataPython |
8118410 | <reponame>andersfischernielsen/ROS-dependency-checker
#!/usr/bin/env python
#
# Copyright 2017 Fraunhofer Institute for Manufacturing Engineering and Automation (IPA)
#
# 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... | StarcoderdataPython |
3291419 | <gh_stars>0
"""
Per session GetMute() SetMute() using ISimpleAudioVolume.
"""
from __future__ import print_function
from pycaw.pycaw import AudioUtilities, ISimpleAudioVolume
def main():
sessions = AudioUtilities.GetAllSessions()
for session in sessions:
volume = session._ctl.QueryInterface(ISimpleAud... | StarcoderdataPython |
8049761 | from .checker import Checker
template_path = "example/template.json"
conf_valid_path = "example/config_valid.json"
conf_error_path = "example/config_with_error.json"
checker = Checker(template_path)
error = checker(conf_valid_path)
print(error)
error = checker(conf_error_path)
print(error) | StarcoderdataPython |
343176 | import numpy as np
import sympy as sp
from functools import singledispatch
import FIAT
from FIAT.polynomial_set import mis, form_matrix_product
import gem
from finat.finiteelementbase import FiniteElementBase
from finat.sympy2gem import sympy2gem
class FiatElement(FiniteElementBase):
"""Base class for finite e... | StarcoderdataPython |
5185636 | <reponame>hiraksarkar/BioBombe<filename>10.gene-expression-signatures/scripts/nbconverted/2.investigate-sex-signature-genes.py
#!/usr/bin/env python
# coding: utf-8
# # Investigating Sex Signature Features
#
# **<NAME>, 2019**
# In[1]:
import os
import sys
import matplotlib.pyplot as plt
import seaborn as sns
impo... | StarcoderdataPython |
1830643 | """
A module to encapsulate the user experience logic
"""
from __future__ import with_statement
import os
import re
import subprocess
import sys
import time
import traceback
import chalk
from twisted.logger import globalLogPublisher
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Ob... | StarcoderdataPython |
3419169 | <reponame>dutxubo/nni
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import pycuda.driver as cuda
import pycuda.autoinit # pylint: disable=unused-import
import tensorrt as trt
EXPLICIT_BATCH = 1
def GiB(val):
return val * 1 << 30
# Simple helper data class that's a little nicer ... | StarcoderdataPython |
4804528 | <reponame>KOSMAsubmm/kosma_gildas_dlc<gh_stars>0
from sicparse import OptionParser
#
import numpy as np
import matplotlib
#if options.plot != "interactive":
# matplotlib.use('Agg')
import matplotlib.pyplot as plt
import sys
from scipy.optimize import leastsq, least_squares
import time
#
from scipy.interpolate impo... | StarcoderdataPython |
94936 | <gh_stars>1-10
import sys
import os
from venv import create
import iotpackage.ModelTraining as mt
import iotpackage.FeatureSelection as fsec
import time
import pandas as pd
import numpy as np
import iotpackage.Utils as utils
from iotpackage.__vars import dictGroups, featureGroups
import argparse
import json
VERBOSE =... | StarcoderdataPython |
4902520 | """Tests for logger: model Comment."""
from django.test import TestCase
from geokey.core.models import LoggerHistory
from geokey.users.tests.model_factories import UserFactory
from geokey.projects.tests.model_factories import ProjectFactory
from geokey.categories.tests.model_factories import CategoryFactory
from geok... | StarcoderdataPython |
5169473 | #
# Copyright (C) 2015 <NAME>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the h... | StarcoderdataPython |
4875151 | from ..utils import DataikuException
from ..utils import DataikuUTF8CSVReader
from ..utils import DataikuStreamedHttpUTF8CSVReader
import json
import time
from .metrics import ComputedMetrics
from .ml import DSSMLTask
from .utils import DSSDatasetSelectionBuilder
class DSSAnalysisStepBuilder(object):
def __init__(... | StarcoderdataPython |
1760544 | from ..geometry import Position, Size
from . import toolkit
class Stack(toolkit.Container, toolkit.Widget):
"""Free form container where all children are stacked on top of each other.
Widgets are rendered in FIFO order and each widget use whole panel.
Will overdraw previous ones if they overlap.
"... | StarcoderdataPython |
9726757 | # <NAME>, ИУ7-12
# Защита (текст)
# Найти предложения, в которых все слова состоят из чередующихся
# согласных и гласных букв.
sogl = 'бвгджзйклмнпрстфхцчшщъьБВГДЖЗЙКЛМНПРСТФХЦЧШЩЪЬ'
sogl = list(sogl[:])
gl = 'аеёиоуыэюяАЕЁИОУЫЭЮЯ'
gl = list(gl[:])
razd = '.?!'
razd = list(razd[:])
#print(gl,sogl,razd)
... | StarcoderdataPython |
185331 | from __future__ import absolute_import
from logging import getLogger
logger = getLogger("gui_builder.fields")
import traceback
from .widgets import wx_widgets as widgets
try:
unicode
except NameError:
unicode = str
class UnboundField(object):
creation_counter = 0
_GUI_FIELD = Tr... | StarcoderdataPython |
1784164 | <filename>SC001 (beginner)/SC001_Assignment4/mirror_lake.py
"""
File: mirror_lake.py
----------------------------------
This file reads in mt-rainier.jpg and
makes a new image that creates a mirror
lake vibe by placing an inverse image of
mt-rainier.jpg below the original one.
"""
from simpleimage import SimpleImage
... | StarcoderdataPython |
6473299 | #!/usr/bin/env python
from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup
setup_args = generate_distutils_setup(
packages=['interfaces'],
package_dir={'': 'test'},
)
setup(**setup_args) | StarcoderdataPython |
4844853 | <reponame>pd-Shah/FlaskRecycle
from app import ma
from app.models import Task
class TaskSchema(ma.ModelSchema):
class Meta:
model = Task
task_schema = TaskSchema()
tasks_schema = TaskSchema(many=True)
| StarcoderdataPython |
3234955 | from os import mkdir, walk, remove
from os.path import exists, join as joinpath
from pickle import PicklingError, UnpicklingError
from collections import namedtuple
from redlib.api.py23 import pickledump, pickleload
from . import const
AutocompInfo = namedtuple('AutocompInfo', ['command', 'access', 'version'])
c... | StarcoderdataPython |
364819 | # Copyright (c) 2013, <NAME> and Contributors
# See license.txt
import frappe
import unittest
test_records = frappe.get_test_records('Jasper Reports')
class TestJasperReports(unittest.TestCase):
pass
| StarcoderdataPython |
5114688 | <reponame>esdc-esac-esa-int/pyesasky
"""
pyesasky setup
"""
import json
from pathlib import Path
from os.path import join as pjoin
from jupyter_packaging import (
wrap_installers,
npm_builder,
get_data_files,
install_npm
)
import setuptools
HERE = Path(__file__).parent.resolve()
# The name of the pr... | StarcoderdataPython |
9693878 | <filename>peon/window.py
from types import (ItemTypes, InventoryTypes, ENCHANT_ITEMS)
import time
import logging
import fastmc.proto
from textwrap import dedent
log = logging.getLogger(__name__)
class Window(object):
def __init__(self, window_id, action_num_counter, send_queue,
proto, recv_cond... | StarcoderdataPython |
8012943 | <reponame>genyrosk/gym-chess
from gym_chess.gym_chess import ChessEngine # rust module
from gym_chess.envs import ChessEnvV0, ChessEnvV1, ChessEnvV2 # envs
from gym.envs.registration import register # to register envs
register(
id="ChessVsRandomBot-v0",
entry_point="gym_chess.envs:ChessEnvV0",
kwargs={... | StarcoderdataPython |
9712356 | # Licensed to Modin Development Team under one or more contributor license agreements.
# See the NOTICE file distributed with this work for additional information regarding
# copyright ownership. The Modin Development Team licenses this file to you under the
# Apache License, Version 2.0 (the "License"); you may not u... | StarcoderdataPython |
1692815 | <gh_stars>0
from random import choice
class RandomWalk:
"""A class to generate a random walk."""
def __init__(self, num_points: int = 5000):
"""Initialize attributes of a walk."""
self.num_points = num_points
# All walks start at (0, 0).
self.x_values = [0]
self.y_val... | StarcoderdataPython |
1980369 | <reponame>Chromico/bk-base
# -*- 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 |
3335002 | # demonstrate the logging api in Python
# use the built-in logging module
import logging
def main():
# Use basicConfig to configure logging
# this is only executed once, subsequent calls to
# basicConfig will have no effect
logging.basicConfig(level=logging.DEBUG,
filemode="w"... | StarcoderdataPython |
9771633 | import random
import re
import db
def preCleanKasvinimi(kasvi: str):
eliRe = r'(.+) eli (.+)'
parantheseRe = r'(.+) \((.+)\)'
latinLineRe = r'(.+) \- (.+)'
strOut = kasvi
m = re.match(eliRe, strOut)
if m:
strOut = m[2]
m = re.match(parantheseRe, strOut)
if m:
strO... | StarcoderdataPython |
9685992 | <reponame>JanWeldert/freeDOM
"""
llh client:
packages messages, sends them to the llh service, and interprets replies
provides synchronous and asynchronous interfaces
"""
from __future__ import absolute_import, division, print_function
__author__ = "<NAME>"
import uuid
import numpy as np
import zmq
class LLHClien... | StarcoderdataPython |
8031335 | # -*- coding: utf-8 -*-
import unittest
import tensorflow as tf
from madoka.utils import tfhelper
from madoka.utils.tfcompat import GLOBAL_VARIABLES_KEY
class VariablesTestCase(unittest.TestCase):
"""Unit tests for variables utility."""
def test_selector(self):
"""Test `VariableSelector()`."""
... | StarcoderdataPython |
1983562 | <reponame>ChauffeurPrive/nestor-api
"""Unit test for logger class"""
from unittest import TestCase
from unittest.mock import patch
from nestor_api.utils.logger import Logger
class TestLogger(TestCase):
@patch("nestor_api.utils.logger.logging", autospec=True)
def test_logger_debug(self, logging_mock):
... | StarcoderdataPython |
300657 | <reponame>kmonsoor/embedX<filename>setup.py
from codecs import open
from os import path
from setuptools import setup, find_packages
# bringing in __version__ data
exec(open('embedx/version.py').read())
# Load the README.md to `long_description`
try:
from pypandoc import convert
long_description = convert('R... | StarcoderdataPython |
319037 | from cliff.command import Command
class ModelUploadCommand(Command):
def get_parser(self, prog_name):
parser = super(ModelUploadCommand, self).get_parser(prog_name)
parser.add_argument('file', action='store', help='Model file to upload')
parser.add_argument('name', action='store', help="Mo... | StarcoderdataPython |
6618586 | <reponame>leetcode-pp/leetcode-pp1<gh_stars>10-100
from typing import List
class Solution:
def judgePoint24(self, nums: List[int]) -> bool:
permutations = self.permuteUnique(nums)
for permutation in permutations:
if self.compute(permutation):
return True
return ... | StarcoderdataPython |
11267086 | """
This defines a single elimination 'Tournament' object.
"""
import math
import itertools
from single_elimination.match import Match
from single_elimination.participant import Participant
class Tournament:
"""
This is a single-elimination tournament where each match is between 2 competitors.
It takes in... | StarcoderdataPython |
213518 | #!/usr/bin/env python
import time
import rospy
from osr_msgs.msg import Commands, Encoder, Status
from roboclaw_wrapper import MotorControllers
global mutex
mutex = False
motorcontrollers = MotorControllers()
def callback(cmds):
global mutex
rospy.loginfo(cmds)
while mutex:
time.sleep(0.001)
#print "cmds are ... | StarcoderdataPython |
5149040 | from __future__ import absolute_import
from functools import partial
from .lr_finder import LRFinder
from .adamw import AdamW as AdamW_my
from .radam import RAdam, PlainRAdam
from .sgdw import SGDW
from .schedulers import LinearLR, ExponentialLR
from .rmsprop import RMSprop
from .lookahead import Lookahead
from torch ... | StarcoderdataPython |
9740454 | <reponame>RoastVeg/cports
pkgname = "desktop-file-utils"
pkgver = "0.26"
pkgrel = 0
build_style = "meson"
hostmakedepends = ["meson", "pkgconf"]
makedepends = ["libglib-devel"]
triggers = ["/usr/share/applications"]
pkgdesc = "Utilities to manage desktop entries"
maintainer = "q66 <<EMAIL>>"
license = "GPL-2.0-or-later... | StarcoderdataPython |
217342 |
"""
XML pysud module.
Provides classes to deal with xml data files.
"""
import xml.etree.ElementTree as etree
import pysud
class XMLParser():
"""
Abstract class to provide basic xml files handling functionality.
Attributes:
xml_file: A valid xml file path.
xml_root: ElementTree R... | StarcoderdataPython |
178554 | <gh_stars>0
#imports to start with app.py
from flask import Flask, render_template
import requests
#instantiating the app to be called later
app = Flask(__name__)
#creating the root(home) page
@app.route('/')
#function to populate your main page
def home():
""" Make sure your folder holding templates is called te... | StarcoderdataPython |
6497514 | # -*- coding: utf-8 -*-
import numpy as np
import tensorflow as tf
slim = tf.contrib.slim
_BATCH_NORM_DECAY = 0.9
_BATCH_NORM_EPSILON = 1e-05
_LEAKY_RELU = 0.1
_ANCHORS = [(10, 13), (16, 30), (33, 23),
(30, 61), (62, 45), (59, 119),
(116, 90), (156, 198), (373, 326)]
@tf.contrib.framewo... | StarcoderdataPython |
6658619 | <gh_stars>1-10
import json
import logging
import os
import sys
from running_modes.configurations.general_configuration_envelope import GeneralConfigurationEnvelope
from running_modes.configurations.logging.create_model_log_configuration import CreateModelLoggerConfiguration
class CreateModelLogger:
def __init__(... | StarcoderdataPython |
7094 | <gh_stars>1-10
"""
Authorization Utilities
"""
from shared.models.user_entities import User
from shared.service.jwt_auth_wrapper import JWTAuthManager
manager = JWTAuthManager(oidc_vault_secret="oidc/rest",
object_creator=lambda claims, assumed_role, user_roles: User(
... | StarcoderdataPython |
12847901 | <reponame>NehzUx/autodl
# Copyright 2016 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 requir... | StarcoderdataPython |
3354256 | from valtypes.condition import is_fixed_length_tuple
def test_not_generic_alias() -> None:
"""
It returns False if the value isn't a generic alias
"""
assert not is_fixed_length_tuple(...)
def test_origin_is_not_tuple() -> None:
"""
It returns False if the origin isn't a tuple
"""
... | StarcoderdataPython |
8065503 | <filename>bert_ner/predict_QG.py
"""
For hotpot Pipeline in codalab
Rewrite eval.py
"""
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils import data
from model import Net
from data_load_QG import NerDataset, pad, VOCAB, tokenizer, tag2idx, idx2tag, EvalDataset, QueryDataset, AnswerDatase... | StarcoderdataPython |
9726146 | import xbmcgui,xbmcplugin
import sys
import urlparse
import datetime
import resources.lib.utils as utils
from resources.lib.database import Database, WatchHistory, DBSettings
class HistoryGUI:
params = None
historyDB = None
settings = None
def __init__(self,params):
self.params = params
... | StarcoderdataPython |
3511633 | # Generated by Django 2.2.13 on 2021-05-10 21:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('project', '0037_auto_20210201_1146'),
]
operations = [
migrations.AlterField(
model_name='project',
name='pi_email'... | StarcoderdataPython |
1828874 | from os import listdir, walk
from os.path import isfile, join
import shelve
from clean_stories import clean_directory
class StoryCorpus(object):
def __init__(self, path='.', dp_path='stories'):
self.path = path
self.db_path = dp_path
self.topics = 'names'
# generates db file
# requires clean_stories to be al... | StarcoderdataPython |
3407633 | <reponame>jg10545/cleanup<filename>cleanup/tests/test_plot.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 26 08:52:10 2021
@author: joe
"""
import numpy as np
import matplotlib
import os
from cleanup.plot import build_embedding_figure
def test_build_embedding_figure_returns_fig():
N =... | StarcoderdataPython |
8129068 | <filename>src/scenic/simulators/newtonian/__init__.py<gh_stars>100-1000
"""Simple Newtonian physics simulator for traffic scenarios.
Allows scenarios written using the :obj:`scenic.domains.driving` abstract
domain to be simulated without installing an external simulator.
.. raw:: html
<h2>Submodules</h2>
.. auto... | StarcoderdataPython |
4841359 | import skimage.io as io
import skimage.transform as skt
import numpy as np
from PIL import Image
from src.models.class_patcher import patcher
from src.utils.imgproc import *
from skimage.color import rgb2hsv, hsv2rgb, rgb2gray
from skimage.filters import gaussian
class patcher(patcher):
def __init__(self, body='.... | StarcoderdataPython |
1970031 | # encoding: utf-8
"""
openbikebox websocket-client
Copyright (c) 2021, binary butterfly GmbH
Use of this source code is governed by an MIT-style license that can be found in the LICENSE file.
"""
class Config:
CLIENT_UID = 'client-1'
CLIENT_PASSWORD = 'password'
OBB_CONNECT_URL = 'ws://your-server:port/... | StarcoderdataPython |
5160185 | <filename>setup.py
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
requires = ["requests == 1.2.3"]
setup(
name='pystex',
version='0.0.20',
descr... | StarcoderdataPython |
9629686 | <gh_stars>0
from django.shortcuts import render
from django.conf import settings
import jwt
from users.models import User
def decode_token(header):
access_token = header.get('HTTP_AUTHORIZATION')[4:]
decoded_access_token = jwt.decode(access_token, settings.SECRET_KEY)
user = User.objects.filter(pk=decoded... | StarcoderdataPython |
3547705 | from statsmodels.stats.multicomp import pairwise_tukeyhsd
import pandas as pd
# store the data
veryants = pd.read_csv('veryants.csv')
print(veryants)
# run tukey's test
tukey_results = pairwise_tukeyhsd(veryants.Sale, veryants.Store, 0.05)
print(tukey_results)
# determine significance
a_b_significant = True
a_c_signi... | StarcoderdataPython |
6487913 | <filename>utils/file_handling.py
import os
import re
import pandas as pd
from expworkup.devconfig import valid_input_files, workup_targets, lab_vars
from utils.globals import get_debug_header, get_debug_simple
def get_interface_filename(interface_type, working_directory, runID):
""" Searches for filename match an... | StarcoderdataPython |
9764735 | from opytimizer.optimizers.swarm import AF
# One should declare a hyperparameters object based
# on the desired algorithm that will be used
params = {
'c1': 0.75,
'c2': 1.25,
'm': 10,
'Q': 0.75
}
# Creates an AF optimizer
o = AF(params=params)
| StarcoderdataPython |
6609974 | <filename>cargaimagenes.py
import cv2
import numpy as np
#cargar imagen a color
IRGB=cv2.imread("009.jpg")
print(IRGB)
print(IRGB.shape)
print("lineas agregadas en mai")
IGS=cv2.cvtColor(IRGB,cv2.COLOR_BGR2GRAY)
print(IGS)
print(IGS.shape)
cv2.imwrite('009GS.jpg',IGS)
| StarcoderdataPython |
4864442 | import shutil,os,glob
def setup_default(out_dir='./mysite',add_as_service=True):
dir=os.path.dirname(__file__)+'/pjfiles'
if not os.path.exists(out_dir):os.makedirs(out_dir)
for i,f in enumerate(glob.glob(dir+'/*')):
if os.path.isdir(f):continue
f2=out_dir+'/'+os.path.basename(f)
shu... | StarcoderdataPython |
11367532 | """Test suite for ashley receivers"""
import json
from django.test import TestCase
from django.urls import reverse
from machina.apps.forum_permission.shortcuts import assign_perm
from ashley import SESSION_LTI_CONTEXT_ID
from ashley.factories import LTIContextFactory, PostFactory, TopicFactory, UserFactory
class Te... | StarcoderdataPython |
11258547 | import asyncio
import threading
import bleak
class BleakAdapter:
@staticmethod
def scan_toys(timeout: float = 5.0):
return asyncio.run(bleak.discover(timeout))
def __init__(self, address):
self.__event_loop = asyncio.new_event_loop()
self.__device = bleak.BleakClient(address, tim... | StarcoderdataPython |
23158 | <filename>awsshell/autocomplete.py
from __future__ import print_function
from awsshell.fuzzy import fuzzy_search
from awsshell.substring import substring_search
class AWSCLIModelCompleter(object):
"""Autocompletion based on the JSON models for AWS services.
This class consumes indexed data based on the JSON ... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.