id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
3396468 | # Copyright 2021 VMware, Inc.
# SPDX-License-Identifier: Apache-2.0
import inspect
import logging
import os
import pandas as pd
import requests
from vdk.api.job_input import IJobInput
log = logging.getLogger(__name__)
def run(job_input: IJobInput):
"""
Download datasets required by the scenario and put them... | StarcoderdataPython |
3254592 | """Sk-learn module."""
from deployml.sklearn.models.decision_tree import DecisionTree
from deployml.sklearn.models.logistic_regression import LogisticRegressionBase
from deployml.sklearn.models.neural_network import NeuralNetworkBase
| StarcoderdataPython |
3496632 | <filename>VA/main/utils/heatmaps.py<gh_stars>100-1000
import numpy as np
from .math import normalpdf2d
from .pose import get_visible_joints
class HeatMaps2D():
def __init__(self, poses, numbins, variance=0.3):
assert (poses.shape[-1] == 2) or ((poses.shape[-1] == 3)), \
'Poses are expected... | StarcoderdataPython |
12823434 | __doc__ = """Muscular snake example from <NAME>. al. Nature Comm 2019 paper."""
import sys
import numpy as np
sys.path.append("../../")
from elastica import *
from examples.MuscularSnake.post_processing import (
plot_video_with_surface,
plot_snake_velocity,
)
from examples.MuscularSnake.muscle_forces import Mu... | StarcoderdataPython |
86376 | <reponame>flyflyinit/GUI-admin-tool
from PyQt5.QtCore import Qt
try:
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QProgressBar, QPushButton, QSpinBox, QLabel, QLineEdit, \
QFormLayout, \
QHBoxLayout, QListWidget, QMessageBox, QCheckBox
except ImportError as e:
print(
f'package PyQt... | StarcoderdataPython |
360238 | <reponame>varun97/Python<filename>minimax.py
def minimax(arr):
arr.sort()
max = 0
min = 0
for i in range(len(arr)):
if i!=0:
max += arr[i]
if i!=4:
min += arr[i]
print(min,max)
if __name__=="__main__":
arr = list(map(int, input().rstrip().split()))
min... | StarcoderdataPython |
4803881 | """
Implementation of the beta-geometric/NBD (BG/NBD) model from '"Counting Your train_df" the Easy Way: An Alternative to
the Pareto/NBD Model' (Fader, Hardie and Lee 2005) http://brucehardie.com/papers/018/fader_et_al_mksc_05.pdf and
accompanying technical note http://www.brucehardie.com/notes/004/
Apache 2 License
"... | StarcoderdataPython |
3311196 | <reponame>viniciusfeitosa/basic-gevent-tutorial
import gevent
import signal
def run_forever():
gevent.sleep(1000)
if __name__ == '__main__':
gevent.signal(signal.SIGQUIT, gevent.kill)
thread = gevent.spawn(run_forever)
thread.join()
| StarcoderdataPython |
6626290 | from __future__ import division, print_function, absolute_import
import numpy as np
from numpy.testing import (assert_allclose, assert_equal,
assert_almost_equal, assert_array_equal,
assert_array_almost_equal)
from scipy.ndimage import convolve1d
from scipy.signa... | StarcoderdataPython |
6448875 | <reponame>sumau/PredictCode
"""
kde
~~~
A variety of "other" KDE methods, not drawn directly from the literature.
"""
from . import predictor
import open_cp.predictors
import tkinter as tk
import tkinter.ttk as ttk
import open_cp.kde
import open_cp.gui.tk.util as util
import open_cp.gui.tk.richtext as richtext
import... | StarcoderdataPython |
3212455 | <filename>emailextract/core/emailextractor.py
# emailextractor.py
# Copyright 2017 <NAME>
# Licence: See LICENCE (BSD licence)
"""Extract text from emails and save for application specific extraction.
These classes assume text from emails are held in files in a directory, with
no sub-directories, where each file cont... | StarcoderdataPython |
1875525 | <reponame>siweisun/hw-subterranean
#!/usr/bin/python2
# -*- coding: utf-8 -*-
import binascii
SUBTERRANEAN_SIZE = 257
def bits_to_hex_string(in_bits, big_endian=True):
string_state = ""
if(len(in_bits)%8 == 0):
final_position = len(in_bits) - 8
else:
final_position = len(in_bits) - (len(i... | StarcoderdataPython |
3364104 | from .graclus import graclus_cluster
from .grid import grid_cluster
from .fps import fps
from .nearest import nearest
__version__ = '1.2.0'
__all__ = [
'graclus_cluster',
'grid_cluster',
'fps',
'nearest',
'__version__',
]
| StarcoderdataPython |
5047828 | <reponame>Zotkin/incremental_learning.pytorch<filename>inclearn/lib/loops/__init__.py
from .generators import *
from .loops import *
| StarcoderdataPython |
3403563 | from gevent.wsgi import WSGIServer
from config import CONTAINER_CONFIG
from ContainerService import container_service
visualizer_service_server = WSGIServer(('', CONTAINER_CONFIG["port"]), container_service)
visualizer_service_server.serve_forever()
| StarcoderdataPython |
291845 | # -*- coding: utf-8 -*-
"""DNACenterAPI Application Policy API fixtures and tests.
Copyright (c) 2019 Cisco and/or its affiliates.
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 restrict... | StarcoderdataPython |
3204171 |
__all__ = ['Ring', 'CommutativeRing']
from ..basealgebra import Algebra
from .interface import RingInterface
from ..core import init_module, classes
init_module.import_heads()
init_module.import_numbers()
@init_module
def _init(m):
from ..arithmetic import mpq
Ring.coefftypes = (int, long, mpq)
class Ring(... | StarcoderdataPython |
305426 | from flask import jsonify, make_response
from flask import render_template, Blueprint
main = Blueprint('main', __name__, template_folder='templates')
@main.route('/')
def index():
return render_template('main/index.html')
@main.route('/json')
def json():
return make_response(jsonify(response='Hello world')... | StarcoderdataPython |
9712482 | # Code modified from the AlexNet implementation of torchvision(https://github.com/pytorch/vision/blob/master/torchvision/models/alexnet.py)
import torch
import logging
import torch.nn as nn
from torch.utils.model_zoo import load_url as load_state_dict_from_url
from .qa import Quantization
_name_translation = {
'... | StarcoderdataPython |
6560189 | <filename>ultracart/models/order_billing.py
# coding: utf-8
"""
UltraCart Rest API V2
UltraCart REST API Version 2
OpenAPI spec version: 2.0.0
Contact: <EMAIL>
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
c... | StarcoderdataPython |
140363 | import collections
import dominoes
import unittest
class TestSeries(unittest.TestCase):
def test_init(self):
s1 = dominoes.Series()
self.assertEqual(len(s1.games), 1)
self.assertEqual(len(s1.games[0].board), 1)
self.assertEqual(s1.games[0].board.left_end(), 6)
self.assertEq... | StarcoderdataPython |
62958 | <filename>tests/__init__.py
__author__ = 'Elad'
| StarcoderdataPython |
3302975 | <reponame>Hoter11/WebProject
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-04-19 10:25
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0003_entry_text'),
]
operations = [
mi... | StarcoderdataPython |
4939423 | <gh_stars>1-10
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import json
import getpass
"""
We start an SMTP server with gmail (the 587 is a port number). smtp_mailer.ehlo() sends a command to the server to identify ourselves. The smtplib documentation says we ... | StarcoderdataPython |
12804274 | '''
This is based on cnn35_64. This is after the first pilot.
Changes:
-don't filter out # in the tokenizer, tokenize both together. or save tokenizer https://stackoverflow.com/questions/45735070/keras-text-preprocessing-saving-tokenizer-object-to-file-for-scoring
-use 'number' w2v as representation for any digit
-shu... | StarcoderdataPython |
382470 | from __future__ import absolute_import, division, print_function, unicode_literals
import hashlib
import io
import warnings
from diskcache import Cache
from ._base import Backend
SIZE_LIMIT = 5e9
CACHE_VERSION = "v0"
class CachingBackend(Backend):
def __init__(self, cacheroot, authoritative_backend):
... | StarcoderdataPython |
8150334 | <reponame>felixfrank/Open3D
# Open3D: www.open3d.org
# The MIT License (MIT)
# See license file or visit www.open3d.org for details
from open3d import *
import numpy as np
if __name__ == "__main__":
set_verbosity_level(VerbosityLevel.Debug)
pcds = []
for i in range(3):
pcd = read_point_cloud(
... | StarcoderdataPython |
3561096 | <reponame>davjohnst/fundamentals<filename>fundamentals/binary_search_tree/binary_search_tree.py
#!/usr/bin/env python
class BSTNode(object):
def __init__(self, parent, left, right, value):
self.parent = parent
self.left = left
self.right = right
self.value = value
class BST(object... | StarcoderdataPython |
9619358 | <filename>1020.py<gh_stars>1-10
n = int(input())
h = int(n // 365)
n -= h * 365
m = int(n // 30)
n -= m * 30
print(h, 'ano(s)')
print(m, 'mes(es)')
print(n, 'dia(s)')
| StarcoderdataPython |
4976109 | import unittest
from cache_gs.utils.timestamp import (base64_to_int, int_to_base64,
section_key_hash)
class TestTimeStamp(unittest.TestCase):
def test_base64(self):
b = int_to_base64(10)
i = base64_to_int(b)
self.assertEqual(10, i)
def test_len... | StarcoderdataPython |
12858804 | import numpy as np
import torch
from torchvision.utils import make_grid
from base import BaseTrainer
from utils import inf_loop, MetricTracker, confusion_matrix_image
import copy
import sys
import time
from model.metric import Accuracy, TopkAccuracy
def get_top_k(x, ratio):
"""it will sample the top 1-ratio of th... | StarcoderdataPython |
4811873 | # Copyright 2021 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 |
6677462 | # Generated by Django 2.2 on 2019-04-17 13:45
from django.conf import settings
import django.contrib.auth.models
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '00... | StarcoderdataPython |
11312560 | <gh_stars>1-10
from django.views.decorators.csrf import csrf_exempt
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework import status
from glbl.serializers import ConfigSerializer
from glbl.models import GlobalConfig
class ConfigView(GenericAPIView):
... | StarcoderdataPython |
179600 | '''
TODO:
Median trimmer
'''
import numpy as np
def mad(arr,axis=None):
mid = np.median(arr,axis=axis)
return np.median(abs(arr-mid),axis=axis)
def bin_median(x,y,nbin):
binsize = (x.max()-x.min()) / (2*nbin)
bin_centers = np.linspace(x.min()+binsize,x.max()-binsize,nbin)
binned = np.empty(... | StarcoderdataPython |
6422674 | # --------------
#Importing header files
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#Path of the file
data = pd.read_csv(path)
data.rename(columns = {'Total':"Total_Medals"}, inplace = True)
data.head()
#Code starts here
# --------------
#Code starts here
import pandas as pd
... | StarcoderdataPython |
3470850 | <reponame>matiastang/matias-python<gh_stars>0
#!/usr/bin/python3
#coding=utf-8
def d_debug():
print(__name__)
def d_one():
print('d_one')
def d_two():
print('d_two') | StarcoderdataPython |
3310210 | <reponame>cristina-mt/biosoft_SAXS
"""
Test code for analysing SAXS data from ESRF
Created on Fri Nov 24 2017
Last modification on Mon Jan 8 2018
version: 0.0
@author: <NAME>
"""
# Import modules and functions
import numpy as np; import matplotlib.pyplot as plt
from scipy import interpolate
from saxs_open_v0 import... | StarcoderdataPython |
5105060 | <filename>minimumViableProductBasicGame.py
import itertools
WHITE = "white"
BLACK = "black"
class Game:
#ive decided since the number of pieces is capped but the type of pieces is not (pawn transformations), I've already coded much of the modularity to support just using a dictionary of pieces
def __init__(s... | StarcoderdataPython |
3249420 | <reponame>EpicEric/base_stations_django
from collections import Counter
from django.test import TestCase
from django.contrib.gis.geos import Point
from model_mommy import mommy
from base_station.models import IdentifiedBaseStation
class IdentifiedBaseStationTestCase(TestCase):
def test_one_bs_inside_bounds(self)... | StarcoderdataPython |
4892531 | <filename>aerospike_helpers/operations/hll_operations.py
'''
Helper functions to create HyperLogLog operation dictionary arguments for
the :mod:`aerospike.Client.operate` and :mod:`aerospike.Client.operate_ordered` methods of the aerospike client.
HyperLogLog bins and operations allow for your application to form fast,... | StarcoderdataPython |
5142882 | """
<NAME>
University of Manitoba
September 10th, 2021
"""
import os
import numpy as np
import matplotlib.pyplot as plt
from umbms import get_proj_path, verify_path
from umbms.loadsave import load_pickle
###############################################################################
__OUT_DIR = os.path.join(get_pr... | StarcoderdataPython |
1817318 | <filename>messdiener/serializers.py
from rest_framework import serializers
from .models import *
class LocationSerializer(serializers.ModelSerializer):
class Meta:
model = Location
fields = ('id', 'locationName')
class RoleSerializer(serializers.ModelSerializer):
class Meta:
model = ... | StarcoderdataPython |
386878 | """
Django settings for hc project.
Generated by 'django-admin startproject' using Django 1.8.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
import logging
im... | StarcoderdataPython |
1919079 | <reponame>alvations/USAAR-SemEval-2015
#!/usr/bin/env python -*- coding: utf-8 -*-
import io, os
from itertools import chain
import numpy as np
indir = 'Asiya-outputs/'
def get_asiya_scores():
feature_data = {}
for infile in os.listdir(indir):
if not infile.startswith('features'):
co... | StarcoderdataPython |
5133925 | from __future__ import division
import os
import time
from glob import glob
import tensorflow as tf
import numpy as np
from six.moves import xrange
import random
import utils
from ops import *
class SentimentRNN(object):
def __init__(self, sess, vocab_size, n_classes, batch_size,
keep_prob, max_length, n... | StarcoderdataPython |
11383329 | # Copyright 2021 <NAME>
#
# 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 writing, softw... | StarcoderdataPython |
11227242 | import os
import glob
import pandas as pd
import tarfile
import urllib.request
from experimentgenerator.experiment_generator import ExperimentGenerator
from experimentgenerator.quantiled_cache import QuantiledCache
from autoscalingsim.utils.error_check import ErrorChecker
from autoscalingsim.utils.download_bar import... | StarcoderdataPython |
3336621 | # Copyright 2017 <NAME>
import tensorflow as tf
from layers import InputLayer
from parameter import Parameter
class INeuralNetwork:
def get_input_layer(self, input_id):
pass
def set_input_layer(self, input_id, input_layer):
pass
def get_output_layer(self):
pass
def get_inpu... | StarcoderdataPython |
294133 | <gh_stars>0
from pwn import *
# context.log_level = 'debug'
p = process('./main_exe')
p.send('\n') # start game
p.sendline('q') # quit game
p.sendline('TeamH4C') # input name
p.sendline('asdf') # input comment
p.sendline('H4C') # secret mode!!!
p.recv()
for repeat in range(5):
print p.recvuntil('(New Wave!)')
... | StarcoderdataPython |
8016583 | # Rock-paper-scissors-lizard-Spock template
import random
# The key idea of this program is to equate the strings
# "rock", "paper", "scissors", "lizard", "Spock" to numbers
# as follows:
#
# 0 - rock
# 1 - Spock
# 2 - paper
# 3 - lizard
# 4 - scissors
# helper functions
def name_to_number(name):
# delete the fo... | StarcoderdataPython |
12846007 | # -*- coding: utf-8 -*-
#
# Copyright 2017 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 requ... | StarcoderdataPython |
1788144 | from googletrans import Translator
import couchdb
import os,json
import time
# couchdb_address = 'http://openwhisk:openwhisk@10.2.64.8:5984/'
# db = couchdb.Server(couchdb_address)
translator = Translator()
# def active_storage(avtive_type, user_object,document_id,filename,file_path=None,content_type=None, save_path=N... | StarcoderdataPython |
5167045 | <filename>j2p.py
#!/usr/bin/env python3
__author__ = '<NAME>'
from modules.j2ASTwalker import J2Meta
from modules import tools, delivery
import sys
import yaml
import os
import argparse
class ArgParser:
def __init__(self, args=False): # arguments should be passed by unit test only
parser = argparse.Ar... | StarcoderdataPython |
11362527 | # @file dsc_test.py
# Tests for the data model for the EDK II DSC
#
# Copyright (c) Microsoft Corporation
#
# SPDX-License-Identifier: BSD-2-Clause-Patent
##
import unittest
from edk2toollib.uefi.edk2.build_objects.dsc import dsc
from edk2toollib.uefi.edk2.build_objects.dsc import library_class
from edk2toollib.uefi.ed... | StarcoderdataPython |
9756049 | from tensorflow.python.training import py_checkpoint_reader
import tensorflow as tf
##reload the model weights from checkpoints since the model structure is changed due to modified code in /official
def load_tf2_weights_emb(tf2_checkpoint, embedding_model):
reader = tf.train.load_checkpoint(tf2_checkpoint)
e... | StarcoderdataPython |
5081994 | import ipaddress
import getpass
import json
import logging
import os
import re
import requests
import sys
import time
from urllib.request import urlopen
from urllib.error import HTTPError
from urllib3.exceptions import InsecureRequestWarning
def create_dir(directory):
"""
create directory recursively
... | StarcoderdataPython |
304832 | <gh_stars>0
import pytest
from zetemple import zetemple
@pytest.fixture
def item_source():
hosts = [{'name': 'host1', 'prefix': 'PREFIX1:'},
{'name': 'host2', 'prefix': 'PREFIX2:'}]
item_keys = ['zetemple.key1', 'zetemple.comma.KEY2', 'invalid.key']
interval = 180
func = 'ave'
items... | StarcoderdataPython |
5024647 | <reponame>jrt54/devito<filename>examples/seismic/elastic/operators.py<gh_stars>1-10
from devito import Eq, Operator, TimeFunction, NODE
from examples.seismic import PointSource, Receiver
def stress_fields(model, save, space_order):
"""
Create the TimeFunction objects for the stress fields in the elastic formu... | StarcoderdataPython |
8035094 | import numpy as np
import matplotlib.pyplot as plt
import sys
import sklearn.linear_model
import sklearn.utils.graph
import sklearn.decomposition
DISTANCE = "D1"
SUBTRACT_BIAS = True
THRESHOLD_OUT_OF_MAX = 0.5
distance_file = DISTANCE + ".npy"
try:
D = np.load(distance_file)
except IOError:
print("Distance f... | StarcoderdataPython |
183761 | # -*- coding: utf-8 -*-
"""
@author: <EMAIL>
@site: e-smartdata.org
"""
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
df = pd.read_csv('./data/ten_d.csv', index_col=0)
df.columns = ['Open', 'High', 'Low', 'Close', 'Volume']
clean_price = df[['Open', 'High', 'Low', 'Close']]
# %%
corr_ma... | StarcoderdataPython |
11220916 | """
@author: magician
@date: 2019/12/18
@file: palindrome.py
"""
def is_palindrome(x: int) -> bool:
"""
is_palindrome
:param x:
:return:
"""
return bool(str(x) == str(x)[::-1])
if __name__ == '__main__':
assert is_palindrome(121) is True
| StarcoderdataPython |
9770160 | <reponame>WIM-TRD/Avanza<filename>avanza4java/src/main/java/org/avanza4java/Utils/totp/getTotp.py<gh_stars>0
import argparse
import mintotp
import sys
description = """Script to generate TOTP secret for provided TOTP key """
def createTotpKey(totpKey):
return mintotp.totp(totpKey)
def main(argv):
parser = ... | StarcoderdataPython |
5053085 | from django.db import models
# from django.dispatch import receiver
from django.contrib.auth.models import AbstractUser
# from django.conf import settings
# from django.contrib.contenttypes.fields import GenericForeignKey
# from django.contrib.contenttypes.models import ContentType
# from rest_framework.authtoken.model... | StarcoderdataPython |
9767045 | import collections
import itertools
import logging
from pathlib import Path
import cmws
import numpy as np
import pyro
import scipy
import torch
from cmws.examples.csg.models import (
heartangles,
hearts,
hearts_pyro,
ldif_representation,
ldif_representation_pyro,
neural_boundary,
neural_bo... | StarcoderdataPython |
3560522 | <reponame>AbanobEffat/Pick-and-Place-Udacity
#!/usr/bin/env python
# Copyright (C) 2017 Udacity Inc.
#
# This file is part of Robotic Arm: Pick and Place project for Udacity
# Robotics nano-degree program
#
# All Rights Reserved.
# Author: <NAME>
# import modules
import rospy
import tf
from kuka_arm.srv import *
from... | StarcoderdataPython |
11308242 | <gh_stars>0
# -*- coding: utf-8 -*-
import sqlalchemy as sa
import ujson
from aiohttp import web, WSMsgType
from .db import TLE
from .log import logger
from .utils import parse_sa_filter, parse_sa_order, check_sa_column, get_sa_column
async def query(request):
filters = []
if 'filters' not in request.query:... | StarcoderdataPython |
6637132 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | StarcoderdataPython |
11229353 | # Moved to test/python/test_torch_ad
| StarcoderdataPython |
206262 | import sys
sys.stdin = open('input.txt')
raw_input()
result = []
while True:
line = raw_input().strip()
if line == '___________':
break
binStr = line.replace(' ', '0').replace(
'o', '1').strip('|').replace('.', '')
# print binStr
n = int(binStr, base=2)
result.append(chr(n))
pri... | StarcoderdataPython |
8041314 | # coding=utf-8
import datetime
import time
from inter.CheckRandCodeAnsyn import checkRandCodeAnsyn
from inter.GetPassengerDTOs import getPassengerDTOs
from inter.GetRandCode import getRandCode
from inter.QueryOrderWaitTime import queryOrderWaitTime
class confirmSingleForQueue:
def __init__(self, session, ifShowP... | StarcoderdataPython |
3418688 | <reponame>J-E-J-S/aaRS-Pipeline
#
# pubkey.py : Internal functions for public key operations
#
# Part of the Python Cryptography Toolkit
#
# Written by <NAME>, <NAME>, and others
#
# ===================================================================
# The contents of this file are dedicated to the public domain. ... | StarcoderdataPython |
233544 | import itertools
import threading
import time
import sys
import os
from os import name, system
DEFAULT_FPS = 3
class Animator:
"""Base animator classes"""
def __init__(self):
self.fps = DEFAULT_FPS # the default frames per second
self.done = False
try:
self.columns, self... | StarcoderdataPython |
6533051 | from __future__ import unicode_literals
from numpy.random import choice
from collections import Counter
import pandas as pd
import numpy as np
from django.apps import apps
import string
def sample_no_replacement(full_set, previous_set=None):
# print "starting sample_no_replacement"
# if previous_set:
# print "prev... | StarcoderdataPython |
3437439 | import asyncio
import traceback
import time
import re
from pyrogram import filters
from bot import alemiBot
from util.permission import is_allowed, is_superuser, allow, disallow, serialize, list_allowed, ALLOWED
from util.user import get_username
from util.message import edit_or_reply, get_text, is_me
from util.text... | StarcoderdataPython |
12820734 | <reponame>javiergayala/jenkins-job-wrecker<filename>jenkins_job_wrecker/modules/scm.py
# encoding=utf8
import jenkins_job_wrecker.modules.base
class Scm(jenkins_job_wrecker.modules.base.Base):
component = 'scm'
def gen_yml(self, yml_parent, data):
scm = []
scm_class = None
if 'class' ... | StarcoderdataPython |
245281 | <filename>src/fbsrankings/infrastructure/sqlite/write/record.py<gh_stars>0
import sqlite3
from typing import List
from typing import Optional
from typing import Tuple
from typing import Union
from uuid import UUID
from pypika import Parameter
from pypika import Query
from pypika.queries import QueryBuilder
from fbsra... | StarcoderdataPython |
9666115 | def resolve():
'''
code here
'''
X = int(input())
X = X//100
if X < 6:
res = 8
elif X < 8:
res = 7
elif X < 10:
res = 6
elif X < 12:
res = 5
elif X < 14:
res = 4
elif X < 16:
res = 3
elif X < 18:
res = 2
el... | StarcoderdataPython |
3577475 | <filename>python/led_fun.py
# Simple test for NeoPixels on Raspberry Pi
import time
import board
import neopixel
# Choose an open pin connected to the Data In of the NeoPixel strip, i.e. board.D18
# NeoPixels must be connected to D10, D12, D18 or D21 to work.
pixel_pin = board.D18
# The number of NeoPixels
num_pixel... | StarcoderdataPython |
8015409 | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright © 2013 OnlineGroups.net and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this d... | StarcoderdataPython |
1685592 | """
Python 3.9 стартовая программа на Python по изучению обучения с подкреплением - Reinforcement Learning
Название файла 00. start.py
Version: 0.1
Author: <NAME>
Date: 2021-12-19
воспользуемся одной из тестовых игр OpenAI, в частности, со средой «MountainCar-v0»
"""
import gym # библиотека OpenAI с простыми играми
... | StarcoderdataPython |
1905515 | import pandas as pd
from db_pool.mysqlhelper import MySqLHelper
from matplotlib import pyplot as plt
db = MySqLHelper()
mertics1_sql = "SELECT pharmacy_order.store_id, SUM(orderdetail.final_total) AS 'October 2021 Sales' FROM orderdetail INNER JOIN pharmacy_order ON pharmacy_order.order_id=orderdetail.order_id INNER ... | StarcoderdataPython |
5026474 | from setuptools import setup, find_packages
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='darktree',
version='0.1.0',
description='Yosys JSON Netlist Hierarchical Viewer',
lo... | StarcoderdataPython |
1755413 | for _ in range(int(input())):
m,s = map(int,input().split())
print(m//s) | StarcoderdataPython |
4823609 | import click
import pygments
import pygments.formatters
from suricata_prettifier.beautify import beautify_file
from suricata_prettifier.lexer import SuricataLexer
@click.command(context_settings=dict(
ignore_unknown_options=True,
))
@click.option('-f', '--formatter', default='terminal')
@click.argument('input', ... | StarcoderdataPython |
6534607 | from __future__ import print_function
import statemachine as fsm
class TrafficLight(fsm.Machine):
initial_state = 'red'
count = 0
@fsm.after_transition('red', 'green')
def chime(self):
print('GO GO GO')
self.count += 1
@fsm.after_transition('*', 'red')
def apply_brakes(self):
... | StarcoderdataPython |
6410952 | from abc import ABC, abstractmethod
from typing import List, Union
import torch
from torch.optim.optimizer import Optimizer
from parseridge.corpus.corpus import Corpus
from parseridge.corpus.training_data import ConLLDataset
from parseridge.parser.modules.data_parallel import Module
from parseridge.parser.training.ca... | StarcoderdataPython |
6554109 | <reponame>codecakes/algorithms_monk
#!/bin/python
"""
Your local library needs your help! Given the expected and actual return dates for a library book, create a program that calculates the fine (if any). The fee structure is as follows:
If the book is returned on or before the expected return date, no fine will be c... | StarcoderdataPython |
394720 | <filename>practicas/voice_call/t2.py
import pyaudio
p = pyaudio.PyAudio()
for i in range(p.get_device_count()):#list all available audio devices
dev = p.get_device_info_by_index(i)
print((i,dev['name'],dev['maxInputChannels'])) | StarcoderdataPython |
1864844 | <filename>LIVE/labs/tmp.py
alist = [
"351",
"222",
"143"
]
def f0(x): return x[0]
def f1(x): return x[1]
def f2(x): return x[2]
sort_by_index = [f0, f1, f2]
sorted_st = sorted(alist, key=sort_by_index[2])
print( sorted_st )
# print( student_tuples.sort(reverse=False)) | StarcoderdataPython |
1822949 | <reponame>theshiv303/kegbot-server
"""Checks a central server for updates."""
from builtins import str
from django.core.cache import cache
from django.utils import timezone
from pykeg.core import models
from pykeg.core import util
from pykeg.core.tasks import core_checkin_task
from pykeg.core.util import SuppressTask... | StarcoderdataPython |
8068956 | width = 2448
height = 2048
i = 0
for image in images:
xml_file = open(str(i)+".xml","w+")
xml_file.write("<annotation><filename>"+str(i)+".png</filename>\
<size><width>"+str(width)+"</width><height>"+str(height)+"</height>\
<depth>3</depth></size>\
<ob... | StarcoderdataPython |
9790156 | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
# ----------------------------------------------------------------------------
from spack import *
class RCa(RPackage):
... | StarcoderdataPython |
5195969 | <gh_stars>0
from json import load
from os import path, getcwd
from feature.feature_defintions.Histogram import Histogram
from feature.feature_defintions.AlexNet import AlexNet
from feature.feature_defintions.VGGNet import VGGNet
from feature.feature_defintions.ResNet50 import ResNet50
from feature.feature_defintions.Co... | StarcoderdataPython |
4959380 | <reponame>heltonricardo/estudo-python
n = input('Digite algo: ')
print('O tipo da entrada é {}'.format(type(n)))
print('É alfanumérico? ', n.isalnum())
print('É alfabético? ', n.isalpha())
print('É decimal? ', n.isdecimal())
print('É dígito? ', n.isdigit())
print('É identificador? ', n.isidentifier())
... | StarcoderdataPython |
8042824 | <reponame>553269487/ConvLSTM-on-TIANCHI-CIKM-2017
from torch import nn
import torch.nn.functional as F
import torch
class activation():
def __init__(self, act_type, negative_slope=0.2, inplace=True):
super().__init__()
self._act_type = act_type
self.negative_slope = negative_slope
... | StarcoderdataPython |
4997129 | <gh_stars>0
#Hangman Trivia!!
#make variables for
#[questions]
#right_answer
#wrong_answers
#bad_pictures
#good_pictures
#name
#
#
#register all graphics and pictures
#ask user to input name
#welcome the user to <NAME>
#do the following 5 times
#ask user question
#show answers
#take answers
... | StarcoderdataPython |
3200371 | from selia.views.create_views.manager_base import CreateManagerBase
class CreatePhysicalDeviceManager(CreateManagerBase):
manager_name = 'selia:create_physical_device'
def view_from_request(self):
if 'device' not in self.request.GET:
return 'selia:create_physical_device_select_device'
... | StarcoderdataPython |
3558290 | <reponame>kdr-s/clipboard-img-to-Y<filename>clipboard-img-to-Y.py
from PIL import ImageGrab, ImageChops, Image
from time import sleep
from ctypes import windll
import numpy as np
last_im = Image.new("RGB", (512, 512), (128, 128, 128))
Ctrl = 0x11
def isPressed(key):
return(bool(windll.user32.GetAsyncKeyState(key)... | StarcoderdataPython |
8150249 | from pygears.core.hier_node import HierVisitorBase
class HDLGearHierVisitor(HierVisitorBase):
def RTLGear(self, node):
gear = node.gear
if hasattr(self, gear.definition.__name__):
return getattr(self, gear.definition.__name__)(node)
def flow_visitor(cls):
def svgen_action(top, con... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.