id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
48769 | '''Escreva um programa que leia dois numeros inteiros e compare-os, mostrando na tela uma
mensagem:
-0 primeiro valor é maior.
-0 segundo valor é maior.
-Não existe valor maior, os dois são iguais.'''
numero1 = int(input('Primeiro número: '))
numero2 = int(input('Segundo número: '))
if numero1 > numero2:
print('O p... | StarcoderdataPython |
146841 | <reponame>fabianfallasmoya/authorship_classification<filename>authordetect/embedding.py
#! /usr/bin/python3
import os
# import multiprocessing
import psutil
from gensim.models import Word2Vec
from typing import Iterable
__all__ = ['EmbeddingModel']
class EmbeddingModel:
def __init__(self, **kwargs):
se... | StarcoderdataPython |
62416 | <filename>systematic_errors/stem-random-walk-nin-20-43/blur_images.py
import cv2
from scipy.misc import imread
from PIL import Image
import numpy as np
parent_dir = "Z:/Jeffrey-Ede/models/stem-random-walk-nin-20-43/"
io_pairs = [(parent_dir+"truth-450000.tif", parent_dir+"blurred_truth-450000.tif"),
... | StarcoderdataPython |
17776 | <gh_stars>1-10
__author__ = 'wektor'
from generic import GenericBackend
import redis
class RedisBackend(GenericBackend):
def __init__(self):
pool = redis.ConnectionPool(host='localhost', port=6379, db=0)
self.store = redis.Redis(connection_pool=pool)
def get_typecode(self, value):
... | StarcoderdataPython |
1730679 | <reponame>coderMaruf/leetcode-1
'''
Description:
Given a positive integer num consisting only of digits 6 and 9.
Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6).
Example 1:
Input: num = 9669
Output: 9969
Explanation:
Changing the first digit results in 6669.
C... | StarcoderdataPython |
3304240 | import sys, atexit
from time import sleep
from mowaysim import *
print 'Executing ' + __name__ + ' test...'
if __name__ == '__main__':
atexit.register(exit_mow)
channel = 8
moway.usbinit_moway()
ret = moway.init_moway(channel)
if ret == 0:
print 'Moway RFUSB Connected'
else:
print ... | StarcoderdataPython |
1757826 | ######################################
# Copyright (c) <NAME> ,2021 #
# This help window of MrPlayer #
######################################
from PySide2 import QtCore, QtGui, QtWidgets
class Ui_HelpWindow(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.setObjectName("He... | StarcoderdataPython |
1775552 | <filename>Item85/namespace_package/main4.py
#!/usr/bin/env PYTHONHASHSEED=1234 python3
import analysis.utils
import frontend.utils
value = 33
if (analysis.utils.inspect(value) ==
frontend.utils.inspect(value)):
print('Inspection equal!') | StarcoderdataPython |
1789521 | import streamlit as st
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.datasets import load_diabetes, load_boston
from sklearn.neural_network impor... | StarcoderdataPython |
36301 | <filename>tests/conftest.py
"""conftest.py for stepseries."""
from threading import Event
from typing import Dict, Tuple
import pytest
from stepseries.responses import DestIP
from stepseries.step400 import STEP400
# store history of failures per test class name and per index in parametrize (if parametrize used)
_te... | StarcoderdataPython |
78599 | from colorama import Fore, Style #for styling and coloring
import socket #for communication
soc = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #TCP socket initiation
port = 1025 ... | StarcoderdataPython |
156131 | <reponame>duckpodger/connect4
from channels import Group
from channels.auth import channel_session_user, channel_session_user_from_http
@channel_session_user_from_http
def connect_game(message, game):
Group('game-' + game).add(message.reply_channel)
message.reply_channel.send({'accept':True})
@channel_session... | StarcoderdataPython |
3275446 | <reponame>PeterWoolery/SEmagic<gh_stars>0
''' This is the main method of interacting with SmartEtailin in the same way a human would. This should only be used in situations where a documented API does not exist... which is most situations.
start - creates a webdriver instance in headless mode. Can be specified as non-... | StarcoderdataPython |
196005 | from pycoingecko import CoinGeckoAPI
cg = CoinGeckoAPI()
answer = cg.get_coins_markets(vs_currency='usd')
print(answer)
| StarcoderdataPython |
163902 | #!python
import ipaddress
import socket
import time
import os
import sys
currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os.path.dirname(currentdir)
sys.path.append(parentdir)
# Protocol Scanner imports
from scan_mods.protocol_scanners.http_scanner import http_scanner
from scan_mods.protocol_sca... | StarcoderdataPython |
32053 | <reponame>ckamtsikis/cmssw<filename>Configuration/Eras/python/Modifier_run2_GEM_2017_cff.py
import FWCore.ParameterSet.Config as cms
run2_GEM_2017 = cms.Modifier()
| StarcoderdataPython |
3252031 | from typing import List
class Solution:
def findMaxLength(self, nums: List[int]) -> int:
if len(nums) < 2:
return 0
sumDict = {0: -1}
currSum, maxLen = 0, 0
for index, num in enumerate(nums):
currSum += 1 if num == 1 else -1
if currSum in sumDict:
... | StarcoderdataPython |
1655138 | <gh_stars>0
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
import os
import json
import shutil
import subprocess
from os import path
from lxml import etree
EXTRACTS_PATH = "/storage/emulated/0/Android/data/com.she.eReader/.hamibookEx/extracts/"
GDRV_PDF_DIR = "/publics/hamis/最新/"
DAILY_NEWSPAPERS = ['聯合報', '聯合晚報'... | StarcoderdataPython |
132001 | <reponame>JonathanLehner/nnabla-examples<filename>frame-interpolation/zooming-slow-mo/authors_scripts/data_utils.py<gh_stars>0
# Copyright (c) 2017 Sony Corporation. 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... | StarcoderdataPython |
13968 | <reponame>jfcarter2358/Ceres
import requests
from datetime import datetime
import time
headers = {
'Content-Type': 'application/json'
}
with open('test/logs.txt', 'r') as f:
logs = f.read().split('\n')
levels = ['INFO', 'WARN', 'DEBUG', 'ERROR', 'TRACE']
messages = []
for i in range(0, len(logs)):
if i... | StarcoderdataPython |
3253618 | <filename>Python/292.py
class Solution:
def canWinNim(self, n: int) -> bool:
return not n % 4 == 0
| StarcoderdataPython |
3381215 | <reponame>rudecs/jumpscale_core7<filename>apps/osis/logic/system/grid/system_grid_osismodelbase.py
from JumpScale import j
class system_grid_osismodelbase(j.code.classGetJSRootModelBase()):
def __init__(self):
pass
self._P_id=0
self._P_name=""
self._P_useavahi=True
self._P_s... | StarcoderdataPython |
30618 | <gh_stars>1-10
class Node():
def __init__(self,data):
self.data=data
self.ref=None
class LinkedList():
def __init__(self):
self.head=None
def Print_ll(self):
n=self.head
if n is None:
print("LinkedList is empty")
else:
while n is not No... | StarcoderdataPython |
33540 | <filename>Gather_Data.py<gh_stars>1-10
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 28 19:51:12 2018
@author: ozkan
"""
import pandas as pd
import numpy as np
#from sklearn.preprocessing import MinMaxScaler, LabelEncoder
from scipy import stats
import gc
import GatherTables
def one_hot_encod... | StarcoderdataPython |
84400 | import cv2.cv as cv
from datetime import datetime
import time
class KaptisCodigo():
def cambioUsuarioValores(self, val):
self.threshold = val
#Constructor de clase
def __init__(self,threshold=5, camara=0, mostrarVentana=True):
self.writer = None
self.font = None
... | StarcoderdataPython |
3326799 | from utils.run_sql_command import run_sql_command
from utils.make_line_plot import make_line_plot
from GLOBAL_VARIABLES import FOLDER_PLOT_DUMP
def money_graph(sigma, database_file_path, buyin=None):
query = '''
SELECT
prize, price, Entries
FROM
tournaments
WHE... | StarcoderdataPython |
130232 | <filename>ssm/observations.py
import copy
import warnings
import autograd.numpy as np
import autograd.numpy.random as npr
from autograd.scipy.special import gammaln, digamma, logsumexp
from autograd.scipy.special import logsumexp
from ssm.util import random_rotation, ensure_args_are_lists, \
logistic, logit, one... | StarcoderdataPython |
1605821 | from .timm_encoder import TimmUniversalEncoder
from .timm_coat_encoder import TimmCoatEncoder | StarcoderdataPython |
3263040 | <filename>tloen/gridui/overview.py
class ClipDetailView:
pass
| StarcoderdataPython |
3386844 | <filename>src/sqlalchemy_dqlite/constants.py
__version__ = "HEAD"
__project__ = "sqlalchemy-dqlite"
__author__ = "<NAME>"
__email__ = "<EMAIL>"
__copyright__ = "Copyright (C) 2016 <NAME>"
__license__ = "MIT"
__description__ = "A SQLAlchemy dialect for dqlite"
| StarcoderdataPython |
1768693 | import os
import tqdm
import torch
import importlib
import numpy as np
from trainers.base_trainer import BaseTrainer
from trainers.utils.loss_utils import *
from evaluation.evaluation_metrics import *
class Trainer(BaseTrainer):
def __init__(self, cfg, args):
self.cfg = cfg
self.args = args
... | StarcoderdataPython |
3217785 | <gh_stars>0
#
# Copyright (c) 2019, NVIDIA CORPORATION. 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... | StarcoderdataPython |
1698563 | import json
import os
import logging
import boto3
from botocore.exceptions import ClientError
# import requests
# Handle logger
logger = logging.getLogger()
logger.setLevel(logging.os.environ['LOG_LEVEL'])
dynamodb = boto3.resource('dynamodb')
aws_environment = os.environ['AWSENV']
logger.info("Finished handling var... | StarcoderdataPython |
3278109 | <gh_stars>0
from atm import ATM
class MainMenuActions:
def __init__(self):
self.atm = ATM()
def handle_deposit(self, amt=-1):
if amt == -1:
self.atm.deposit()
else:
self.atm.deposit(amt)
def handle_withdraw(self, amt=-1):
if amt... | StarcoderdataPython |
3340681 | from aiohttp import web
import aiohttp_debugtoolbar
import asyncio
import asyncpg
import click
import logging
from app.utils.data_structures import DBAccessVars
from app.routes import setup_routes
async def add_connection_pool(app, db_access_vars):
app['pool'] = await asyncpg.create_pool(user=db_access_vars.user... | StarcoderdataPython |
1650423 | <gh_stars>1-10
from microprediction import MicroReader
from statsmodels.tsa.api import SimpleExpSmoothing
import os
import random
MODEL_FIT_PATH = os.path.dirname(os.path.realpath(__file__)) + os.path.sep + 'modelfits' + os.path.sep + 'expsmooth'
mr = MicroReader()
STREAMS = mr.get_stream_names()
def fit_one():
... | StarcoderdataPython |
1710751 | <gh_stars>10-100
from typing import Tuple
import numpy as np
from napari.layers.points import Points
from napari.utils.events import Event
from scipy.spatial import distance
import warnings
class Anchors(Points):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.events.add(
... | StarcoderdataPython |
100042 | import numpy as np
import scipy.integrate
from scipy.interpolate import interp1d, interp2d, RectBivariateSpline,UnivariateSpline,griddata
from scipy.spatial import Delaunay, ConvexHull
from matplotlib.collections import LineCollection
from scipy.interpolate import splprep,splev
from scipy.optimize import fmin
from matp... | StarcoderdataPython |
24833 | <filename>typotools.py
#!usr/bin/env python
#! -*- coding: utf-8 -*-
from __future__ import unicode_literals
import re
import traceback
import urllib
import pprint
OPENING_QUOTES = set(['«', '„', '“'])
CLOSING_QUOTES = set(['»', '“', '”'])
QUOTES = OPENING_QUOTES | CLOSING_QUOTES | set(['"', "'"])
WHITESPACE = set([' ... | StarcoderdataPython |
44080 | <reponame>Liam-Deacon/antlr4-vba-parser
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# type: ignore
"""Setup script for package."""
import os
import sys
import configparser
import datetime
import distutils.cmd
import distutils.log
import subprocess
import glob
import shutil
from pathlib import Path
setup_kwargs = {}... | StarcoderdataPython |
3317603 | # -*- coding: utf-8 -*-
"""
Profile: http://hl7.org/fhir/StructureDefinition/Claim
Release: R5
Version: 4.5.0
Build ID: 0d95498
Last updated: 2021-04-03T00:34:11.075+00:00
"""
from pydantic.validators import bytes_validator # noqa: F401
from fhir.resources import fhirtypes # noqa: F401
from fhir.resources import clai... | StarcoderdataPython |
3390256 | <filename>huaweicloud-sdk-mrs/huaweicloudsdkmrs/v1/model/auto_scaling_policy.py
# coding: utf-8
import re
import six
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class AutoScalingPolicy:
"""
Attributes:
openapi_types (dict): The key is attribute name
... | StarcoderdataPython |
1795367 | from pennylane import math
from ..postprocessing import even_parity_ids
from ..qnodes import joint_probs_qnode, local_parity_expval_qnode
def post_process_I_3322_joint_probs(probs_vec):
"""Applies post-processing to multi-qubit probabilities in order to coarse-grain
them into the dichotomic parity observables... | StarcoderdataPython |
1620314 | <gh_stars>0
#
# Objetivo: Automatizar a geracao de documentos no formato markdown para o portal de documentacao MKDocs.
# Dsenvolvedor: Junior
# Data: 07/10/2016
#
import sys
import json
import glob
#
# TODOS:
# - Criar gatilho para o github.
# - O programa devera ler arquivos em determinado diretorio, gerar a docu... | StarcoderdataPython |
3294226 | import torch
from eqv_transformer.classfier import Classifier
from eqv_transformer.eqv_attention import EquivariantTransformer
from lie_conv.lieGroups import SE3, SE2, SO3, T, Trivial
# from lie_conv.datasets import SE3aug
from forge import flags
flags.DEFINE_boolean(
"data_augmentation",
False,
"Apply... | StarcoderdataPython |
1699667 | import pytest
from busy_beaver.apps.slack_integration.blocks import AppHome
from busy_beaver.common.wrappers.slack import SlackClient
from busy_beaver.config import SLACK_TOKEN
from busy_beaver.exceptions import SlackTooManyBlocks
MODULE_TO_TEST = "busy_beaver.common.wrappers.slack"
@pytest.fixture(scope="module")
... | StarcoderdataPython |
1644644 |
def install(distro, version_kind, version, adjust_repos, **kw):
"""
Install bundle that contains ceph on the clear host.
Since clear does not have alternate channels, we will just run the command
"""
logger = distro.conn.logger
packages = ['storage-cluster']
logger.info("Installing storag... | StarcoderdataPython |
59043 | """My2h JOP Transform Utility
Usage:
loco.py convert <input.lok> <output.2lok>
loco.py (-h | --help)
loco.py --version
Options:
-h --help Show this screen.
--version Show version.
"""
import os
import logging
import configparser
from docopt import docopt
#Tady je soubor specifikace hnacíh... | StarcoderdataPython |
3326747 | """
Activate a virtual environment from Python.
Activation logic taken from https://github.com/pypa/virtualenv
"""
import os
import site
import sys
from glob import glob
def is_venv():
"""Return true if a virtual environment is active."""
return getattr(sys, "base_prefix", sys.prefix) != sys.prefix or hasat... | StarcoderdataPython |
110134 | <reponame>danizen/apache-replay<gh_stars>0
import re
from datetime import datetime
import attr
import sys
__all__ = (
'CommonLog',
'ParserException',
'COMMON_LOG_PATTERN',
'Parser',
'parse_entries_from',
)
# Model
@attr.s(frozen=True)
class CommonLog(object):
remote_host = attr.ib()
times... | StarcoderdataPython |
3303329 | <filename>bot/com/pub/rev.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*
#/// DEPENDENCIES
import discord #python3.7 -m pip install -U discord.py
import logging
from discord.ext import commands
from discord.ext.commands import Bot, MissingPermissions, has_permissions
from chk.enbl import enbl
##/... | StarcoderdataPython |
1787999 | <gh_stars>0
'''
using smtplib module to send mail from posoco mail id
'''
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def sendEmail(address_book, sender, subject, html, username, password):
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = ','.jo... | StarcoderdataPython |
1701055 | <gh_stars>0
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import calendar
cal = calendar.TextCalendar() # Create an instance
#cal.setfirstweekday(3)
#cal.pryear(2012) # What happens here?
#print('\n')
#cal2 = calendar.TextCalendar()
#cal.prmonth(2020, 4)
#calend... | StarcoderdataPython |
165888 | import numpy as np
import tflearn
import sys
# Load CSV file
# For some reason, the CSV must have a single label column. So the dataset has a last dummy column.
from tflearn.data_utils import load_csv
input_data, dummy = load_csv("data.csv", columns_to_ignore=[5, 6, 7, 8])
input_labels, dummy = load_csv("data.csv", co... | StarcoderdataPython |
4821656 | <reponame>StutiSri/smart-plant-care
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# ---------------------------------------------... | StarcoderdataPython |
1780106 | <filename>profscraper.py
#!/usr/bin/env python
import scrapy
from scrapy.crawler import CrawlerProcess
from bs4 import BeautifulSoup
crn = '94371'
class ProfSpider(scrapy.Spider):
name = 'prof'
start_urls = [
'https://www.uvm.edu/coursedirectory/search.php?subject=ECLD&number=056&term=202109§ion'... | StarcoderdataPython |
1650777 | # Copyright (c) 2021 Works Applications 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 a... | StarcoderdataPython |
1712593 | <filename>tests/test_read_data.py
"""
Unit tests for the utils/read_data.py module
"""
import unittest
import numpy as np
import time
import utils.read_data as read_data
class TestReadData(unittest.TestCase):
def test_read_data(self):
name = "aces"
read_data.read_data(name=name)
name ... | StarcoderdataPython |
106865 | <gh_stars>1-10
import os, imp, sys
from datatypes import *
import content
import network
def create_enum_table(names, num):
lines = []
lines += ["enum", "{"]
lines += ["\t%s=0,"%names[0]]
for name in names[1:]:
lines += ["\t%s,"%name]
lines += ["\t%s" % num, "};"]
return lines
def create_flags_table(names):
... | StarcoderdataPython |
1612379 | from django.core.management import call_command
from django.test import TestCase
from openhub_django.models import Organization
from openhub_django.variables import ORG_NAME
class ImportOrganizationDataTest(TestCase):
@classmethod
def setUpTestData(cls):
call_command('import_organization_data')
... | StarcoderdataPython |
3275398 | <filename>tests/test_segmented.py
"""Tests for special segmented system handling."""
import pytest
import numpy as np
from prysm import coordinates, segmented, polynomials
def test_segmented_hex_functions():
x, y = coordinates.make_xy_grid(256, diameter=2)
csa = segmented.CompositeHexagonalAperture(x, y, 2,... | StarcoderdataPython |
4840671 | <gh_stars>1-10
import numpy as np
import json
import sys
class TimeseriesGenerator(object):
"""Utility class for generating batches of temporal data.
This class takes in a sequence of data-points gathered at
equal intervals, along with time series parameters such as
stride, length of history, etc., to... | StarcoderdataPython |
3278419 | <filename>codeforces/a2oj/magicNumbers.py
s=input()
f=0
if len(s)<2:
if s[0]=='1':
print("YES")
else:
print("NO")
exit()
if s[0]!='1' or (s[1]!='1' and s[1]!='4'):
f=1
print('NO')
exit()
for i in range(2,len(s)):
if s[i]=='1':
continue
elif s[i]=='4':
if s[i-1]=='1' or s[i-2]=='1':
... | StarcoderdataPython |
1668735 | from django.contrib import admin
from models import LinkedDataAPIEndpoint
class LinkedDataAPIEndpointAdmin(admin.ModelAdmin):
list_display = LinkedDataAPIEndpoint._meta.get_all_field_names()
admin.site.register(LinkedDataAPIEndpoint, LinkedDataAPIEndpointAdmin) | StarcoderdataPython |
3358232 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
from mpl_toolkits.axes_grid1 import make_axes_locatable
from .PlotPlanet import PlotPlanetXY
from .GCPM import GCPM
def PlotEqSlice(Date,ut,Parameter='ne',Rmax=10.0,dR=0.5,Kp=1.0,fig=None,
maps=[1,1,0,0],zlog=True,cmap='gnuplot',sc... | StarcoderdataPython |
3313143 | import os
bind = "127.0.0.1:8005"
workers = 3
loglevel = "error"
proc_name = "drum"
| StarcoderdataPython |
3277138 | import sys
# if int(sys.version[0]) == 2:
# import tkinter as Tkinter
# elif int(sys.version[0]) == 3:
# import Tkinter
import tkinter as tk
class ip_port:
def __init__(self,tt):
self.window =tk.Tk()
self.window.title("Minecraft-CS")
self.window.geometry("400x400")
self.name... | StarcoderdataPython |
3380881 | from django.contrib import admin
from django.urls import path
from django.conf import settings
from blog.views import blog_view
from django.conf.urls.static import static
urlpatterns = [
path('', blog_view, name='blog'),
#path('blog/', blog_view),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) | StarcoderdataPython |
3373536 | """
Paint smooth weights tool in Maya using the weights of neighbouring vertices.
Installation
============
Copy the **rjSkinningTools** folder to your Maya scripts directory
::
C:/Users/<USER>/Documents/maya/scripts
Usage
=====
Select a skinned object and run the following code
::
from rjSkinningTools imp... | StarcoderdataPython |
3286414 | #!/usr/bin/python
import MySQLdb as mdb
import psycopg2
import psycopg2.extras
import psycopg2.extensions
from psycopg2 import OperationalError
import os
import sys
import pprint
import argparse
con_old = None
con_new = None
old = dict()
new = dict()
parser = argparse.ArgumentParser(description='Generate an SQL fil... | StarcoderdataPython |
149601 | from exams.models import Exam
from exams.serializers import ExamSerializer
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from courses.models import Course
class ExamView(APIView):
def get(self, request, *args, **kwargs):
exams = Ex... | StarcoderdataPython |
3371346 | import xmltodict
from loguru import logger
from rdkit.Chem.rdchem import KekulizeException
from typing import List
from substituent_replacement.utils.utils import canonicalise_smiles, prep_mol
class ReplacementMap:
"""Class that maps substituents to be replaced by other substituent"""
def __init__(self, ma... | StarcoderdataPython |
1636622 | <reponame>awesome-archive/causalml<gh_stars>0
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
import pandas as pd
import numpy as np
from sklearn.dummy import DummyRegressor
from sklearn.metrics import mean_squared_error as mse
from sklearn.met... | StarcoderdataPython |
3250503 | <reponame>Probely/CTF-Challenges<gh_stars>10-100
#!/usr/bin/env python
""" Generate a bunch of new/random entries
Module "utmp" provides class UtmpEntry, correcponding to one
entry in UTMP/WTMP file.
UtmpEntry has the following attributes (values after "=" demonstrate default values)
ut_type = EMPTY
ut_pid = 0
ut_lin... | StarcoderdataPython |
1765824 | """Utilities for visualization."""
import matplotlib.pyplot as plt
from matplotlib.cm import get_cmap
import numpy as np
from gspx.utils.quaternion_matrix import explode_quaternions
import networkx as nx
from gspx.utils.graph import to_networkx
def visualize_quat_mtx(M, dpi=None):
"""Plot heatmap of quaternion m... | StarcoderdataPython |
3276421 | <filename>MINIBATCH_saving.py
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# ============================================================================================= #
# MINIBATCH_saving.py #
# Author: <NAME> ... | StarcoderdataPython |
84297 | <filename>leetcode-solutions/python/lru_cache.py
# https://oj.leetcode.com/problems/lru-cache/
# 17 / 17 test cases passed.
# Design and implement a data structure for Least Recently Used (LRU) cache.
# It should support the following operations: get and set.
#
# get(key) - Get the value (will always be positive) of th... | StarcoderdataPython |
186552 | <filename>__init__.py
"""
k3color creates colored text on terminal.
"""
from .color import Str
from .color import blue
from .color import cyan
from .color import danger
from .color import dark
from .color import fading_color
from .color import green
from .color import loaded
from .color import normal
from .color impor... | StarcoderdataPython |
1694822 | from flask import (
Blueprint, redirect, render_template, request, url_for, jsonify, make_response, current_app
)
from . import token_required
from ..models.user import User
from ..models.product import Product
from .. import db
#creating blueprint
bp = Blueprint('likes', __name__, url_prefix='/api/likes')
@bp.r... | StarcoderdataPython |
3364962 | import enum
import logging
from etl.common import StepController
class LogLevel(enum.IntEnum):
Error = logging.ERROR,
Warning = logging.WARNING,
Info = logging.INFO,
Debug = logging.DEBUG
class Logging(StepController):
def log(self, level: LogLevel, message: str):
# self.ctx.logger.log(... | StarcoderdataPython |
145057 | DATABASES_PATH="../tmp/storage"
CREDENTIALS_PATH_BUCKETS="../credentials/tynr/engine/bucketAccess.json"
CREDENTIALS_PATH_FIRESTORE = '../credentials/tynr/engine/firestoreServiceAccount.json'
INGESTION_COLLECTION = "tyns"
INGESTION_BATCH_LIMIT = 1000 | StarcoderdataPython |
80206 | <gh_stars>0
#!/usr/bin/env python
import os
import glob
import shutil
import itertools
import pathlib
import random
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.lines import Line2D
from IPython import get_ipython
from matplotlib import style
from matplotlib.gridspec import GridSpec
from nu... | StarcoderdataPython |
126400 | # AntiBiofilm Peptide Research
# Department of Computer Science and Engineering, Santa Clara University
# Author: <NAME>
# A python script that performs forward selection and hyperparameter optimization
# in order to find the best performing SVR model for the MBEC peptides
# Loss function used is RMSE
# The script dum... | StarcoderdataPython |
21737 | <filename>inpainting/common/eval_test.py
import os
import pandas as pd
import torch
from torch import nn
import common.utils as util
import scipy.misc as spmi
def save_img(img_np, file_name, out_dir='./'):
if not os.path.exists(out_dir):
os.makedirs(out_dir)
image = img_np.copy().transpose(1, 2, 0)
... | StarcoderdataPython |
1627889 | from json import load
from random import choice, randrange, randint
import datetime
names = ['Максим', 'Матвій', 'Артем', 'Андрій', 'Олександр', 'Владислав', 'Денис', 'Роман', 'Юрій', 'Дмитро', 'Данило',
'Богдан', 'Маркіян', 'Олег', 'Максим', 'Максим', 'Максим', 'Максим', 'Софія', 'Анна', 'Анастасія', 'Віктор... | StarcoderdataPython |
4808841 | """
[2015-12-21] Challenge # 246 [Easy] X-mass lights
https://www.reddit.com/r/dailyprogrammer/comments/3xpgj8/20151221_challenge_246_easy_xmass_lights/
**Description**
We are going to calculate how long we can light our X-mass lights with 1 battery.
First off all some quick rules in the electronics.
All things conne... | StarcoderdataPython |
3346889 | from django.contrib import admin
from .models import Template
# Register your models here.
admin.site.register(Template) | StarcoderdataPython |
104320 | """Test drawing module
"""
import pytest
import numpy as np
from shellplot.axis import Axis
from shellplot.drawing import (
LegendItem,
_draw_canvas,
_draw_legend,
_draw_x_axis,
_draw_y_axis,
_pad_lines,
)
def test_draw_legend():
legend = [LegendItem(1, "one"), LegendItem(2, "two")]
... | StarcoderdataPython |
4831155 | <reponame>erpeg/biopython
# Copyright 2006-2014 by <NAME>. All rights reserved.
# Revisions copyright 2011 <NAME>. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""Tests for B... | StarcoderdataPython |
3323450 | <gh_stars>100-1000
__author__ = "<NAME> (<EMAIL>)"
import os
import re
import time
from pathlib import Path
from shutil import copyfileobj, rmtree
from pyicloud import exceptions
from src import config_parser
def wanted_file(filters, file_path, verbose=False):
if not file_path:
return False
if not f... | StarcoderdataPython |
1646905 | import math
all_Steps = float(input())
dancers = float(input())
days_For_Learning = float(input())
steps_per_day = math.ceil(((all_Steps/days_For_Learning)/all_Steps)*100)
steps_per_dancer = steps_per_day/dancers
if steps_per_day<=13:
print(f'Yes, they will succeed in that goal! {steps_per_dancer:.2f}%.')
else:
... | StarcoderdataPython |
4821817 | from ..methods.general import General
from ..services import PeerService
from .utils import log_message
from pony import orm
from .. import utils
@orm.db_session
def sync_peers():
peers = General.peers()
if peers["error"] is None:
total = len(peers["result"])
log_message(f"Syncing {total} pee... | StarcoderdataPython |
1651999 | #!/usr/bin/evn python
#--coding:utf-8--*--
# Name:建设工程质量监督系统任意文件上传
# Refer:http://www.wooyun.org/bugs/wooyun-2010-0119750
# Author:xq17
import re
import random
def get__EVENTVALIDATION(arg):
url = arg + 'PKPMBS/common/upload/FileUpload.aspx'
code, head, res, errcode, _ = curl.curl2(url)
try:
... | StarcoderdataPython |
194784 | # -*- coding: utf-8 -*-
# Copyright (c) 2018, Frappe Technologies and Contributors
# License: MIT. See LICENSE
import json
import unittest
import frappe
class TestPreparedReport(unittest.TestCase):
def setUp(self):
self.report = frappe.get_doc({"doctype": "Report", "name": "Permitted Documents For User"})
self.... | StarcoderdataPython |
133507 | from pathlib import Path
from setuptools import setup
VERSION = "0.1.6"
def get_long_description():
readme_path = Path(__file__).parent / "README.md"
with open(readme_path.absolute(), mode="r", encoding="utf8") as fp:
return fp.read()
setup(
name="datasette-dashboards",
description="Datase... | StarcoderdataPython |
1671733 | <gh_stars>10-100
# encoding: utf-8
BLOCK_ID = [
'15', # 亞洲有碼原創區
'2', # 亞洲無碼原創區
'4', # 歐美原創區
'25', # 國產原創區
'26' # 中字原創區
] | StarcoderdataPython |
3203477 | <filename>data/external/repositories/147511/kaggle-malware-master/src/ngramms_extractor.py
import glob
from joblib import Parallel, delayed
import set_up
import pickle
import os
import sys
print '[n-gramm extractor]'
if sys.argv[1]=='train':
in_dir = set_up.train_folder_path + '*.bytes'
elif sys.argv[1]=='test':
... | StarcoderdataPython |
60743 | # -*- coding: utf-8 -*-
# SPDX-License-Identifier: MIT
from __future__ import absolute_import, print_function, unicode_literals
from pymta.test_util import SMTPTestCase
from pythonic_testcase import *
from schwarz.mailqueue import SMTPMailer
from schwarz.mailqueue.compat import IS_PYTHON3
class SMTPMailerFullstack... | StarcoderdataPython |
3244011 | #!/usr/bin/python3
import os
import sys
import res
#method to accept input
def main():
while True:
command = input("$ ")
args = command.split()
if command == "exit":
break
elif command == "help":
print("Type 'exit' to exit. That is all.")
... | StarcoderdataPython |
126173 | <reponame>vespos/pcdsdevices
import copy
import functools
import typing
import numpy as np
from ophyd.device import Component as Cpt
from ophyd.pseudopos import pseudo_position_argument, real_position_argument
from .device import GroupDevice
from .epics_motor import BeckhoffAxis
from .interface import FltMvInterface
... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.