id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
8140443 | <gh_stars>10-100
"""
Entry point for a gunicorn server, serves at /api
"""
from benchmarkstt.cli.entrypoints.api import create_app # pragma: no cover
application = create_app('/api', with_explorer=True) # pragma: no cover
| StarcoderdataPython |
5081962 | <reponame>maumg1196/GearDesign
# Generated by Django 2.2.1 on 2019-06-04 03:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('design', '0014_auto_20190603_2204'),
]
operations = [
migrations.AddField(
model_name='gear',
... | StarcoderdataPython |
8035493 | from rest_framework import serializers
from rest_framework.relations import SlugRelatedField, StringRelatedField
from frontend.api.models import TweetCountCache, Tweet, Article, TweetClusterMembership, Cluster, \
TweetClusterAttributeValue
class TweetCountCacheSerializer(serializers.ModelSerializer):
class M... | StarcoderdataPython |
6547576 | <reponame>TheWebCrafters/PyCraft<gh_stars>1-10
from terrain import *
class block(Block):
def __init__(self, renderer):
super().__init__("stone", renderer)
self.tex_coords = {
"top": self.renderer.texture_manager.texture_coords["stone.png"],
"bottom": self.renderer.texture_ma... | StarcoderdataPython |
6589815 | # -*- coding: utf-8 -*-
"""
actors exceptions module.
"""
from pyrin.core.exceptions import CoreException, CoreBusinessException
class ActorsException(CoreException):
"""
actors exception.
"""
pass
class ActorsBusinessException(CoreBusinessException, ActorsException):
"""
actors business ex... | StarcoderdataPython |
8131793 | <reponame>Asap7772/railrl_evalsawyer<filename>experiments/vitchyr/rig/reset-free/pusher/relabeling_sac_state.py
import rlkit.misc.hyperparameter as hyp
from rlkit.launchers.experiments.vitchyr.multiworld import (
relabeling_tsac_experiment,
)
from rlkit.launchers.launcher_util import run_experiment
if __name__ == ... | StarcoderdataPython |
342525 | <gh_stars>10-100
from gpflow.actions import Action
class RunOpAction(Action):
def __init__(self, op):
self.op = op
def run(self, context):
context.session.run(self.op)
| StarcoderdataPython |
1791388 | def main():
puzzleInput = open("python/day04.txt", "r").read()
# Part 1
assert(part1("aa bb cc dd ee") == 1)
assert(part1("aa bb cc dd aa") == 0)
assert(part1("aa bb cc dd aaa") == 1)
print(part1(puzzleInput))
# Part 2
assert(part2("abcde fghij") == 1)
assert(part2("abcde xyz ... | StarcoderdataPython |
8103908 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'dw_inputs_fields.ui'
#
# Created by: PyQt5 UI code generator 5.14.1
#
# WARNING! All changes made in this file will be lost!
from qtpy import QtCore, QtGui, QtWidgets
class Ui_DockWidget(object):
def setupUi(self, DockWidget):
... | StarcoderdataPython |
4934685 | #! python3
class GSuggestion:
word = ""
annotation = ""
matched_length = 0
def __init__(self, word, annotation, matched_length):
self.word = word
self.annotation = annotation
self.matched_length = matched_length
class GRequest:
request = ""
suggestions = []
requeste... | StarcoderdataPython |
3268824 | <filename>python/orp/orp/authority_ner/new_extractAuthorities.py
#
# Copyright (C) Analytics Engines 2021
# <NAME> (<EMAIL>)
# <NAME> (<EMAIL>)
# <NAME> (<EMAIL>)
#
from lxml import etree as ET
import re
def checkInnerHTML(element):
children = element.getchildren()
if len(children) > 0:
resultStr = el... | StarcoderdataPython |
11282702 | """
Wrapper for loading templates from "templates" directories in INSTALLED_APPS
packages.
"""
from django.template.utils import get_app_template_dirs
from .filesystem import Loader as FilesystemLoader
class Loader(FilesystemLoader):
def get_dirs(self):
return get_app_template_dirs("templates")
| StarcoderdataPython |
11397113 | # -*- coding: utf-8 -*-
# @Author : feier
# @File : calc.py
# 计算器
class Calculator:
# 加法
def add(self, a, b):
return a + b
# 减法
def sub(self, a, b):
return a - b
# 乘法
def mul(self, a, b):
return a * b
# 除法
def div(self, a, b):
return a / b
| StarcoderdataPython |
8196694 | import multiprocessing
import os
import pickle
import numpy as np
import pandas as pd
import torch
from analysis import mig
from experiments import spec_util
from models import infogan, load_checkpoint
from morphomnist import io, measure
DATA_ROOT = "/vol/biomedic/users/dc315/mnist"
CHECKPOINT_ROOT = "/data/morphomn... | StarcoderdataPython |
327924 | <filename>scripts/gcovr-3.3/doc/examples/test_examples.py<gh_stars>1-10
# Imports
import pyutilib.th as unittest
import glob
import os
from os.path import dirname, abspath, basename
import sys
import re
currdir = dirname(abspath(__file__))+os.sep
datadir = currdir
compilerre = re.compile("^(?P<path>[^:]+)(?P<rest>:.*... | StarcoderdataPython |
1671606 | # Some Basic Examples
match = re.search(r'\d' , "it takes 2 to tango")
print match.group() # print 2
match = re.search(r'\s\w*\s', 'once upon a time')
match.group() # ' upon '
match = re.search(r'\s\w{1,3}\s', 'once upon a time')
match.group() # ' a '
match = re.search(r'\s\w*$', 'once upon a time')
match.group() # ... | StarcoderdataPython |
6501182 | import tensorflow as tf
import tensorflow_quantum as tfq
import numpy as np
import cirq
import sympy
class ReUploadPQC(tf.keras.layers.Layer):
def __init__(self, qubit, layers, obs) -> None:
super(ReUploadPQC, self).__init__()
self.num_params = len(qubit) * 3 * layers
self.layers = layers
... | StarcoderdataPython |
11344446 | <filename>Projetos Python/pythonexercicios/aula20.py<gh_stars>0
def l():
print('-='*30)
def soma(a, b):
print(f'A = {a} e B = {b}')
s = a + b
print(f'A soma é {s}')
#Programa Principal
soma(4, 5)
soma(b=8, a=9)
soma(2, 1)
l()
def contador(*num):
tam = len(num)
print(f'Recebi os valores {num... | StarcoderdataPython |
6692749 | import numpy as np
from sklearn.metrics import precision_recall_fscore_support, matthews_corrcoef
from deepbond import constants
from deepbond.models.utils import unroll, unmask
class BestValueEpoch:
def __init__(self, value, epoch):
self.value = value
self.epoch = epoch
class Stats(object):
... | StarcoderdataPython |
3534690 | <gh_stars>0
'''
The detection code is partially derived and modified from app-2Class.py by <NAME>.
'''
from flask import Flask, request, render_template, redirect
import cv2
import numpy as np
import tensorflow as tf
from utils import label_map_util
from utils import visualization_utils as vis_util
from matplotlib ... | StarcoderdataPython |
5195458 | import pandas as pd
import numpy as np
import seaborn as sb
import networkx as nx
import os
data_dir = ""
'''
sample usage for loading graph.npy:
from Graph_Helper import nodelist, delta
'''
'''
sample usage for loading graph.npy and converting the sparse arrays to numpy:
from Graph_Helper import nodelist, delta, ... | StarcoderdataPython |
9673718 | import sys
sys.path.append('../..')
import torch
import logging
from typing import Optional
from dataclasses import dataclass, field
from transformers.file_utils import cached_property, torch_required
from seqlbtoolkit.bert_ner.config import BertBaseConfig
logger = logging.getLogger(__name__)
@dataclass
class Bert... | StarcoderdataPython |
8164321 | from . import average_color, brightest_n_pixels, nucleus_detection
available_job_types = {
module.__name__.replace(f"{module.__package__}.", ''): module
for module in [
average_color,
brightest_n_pixels,
nucleus_detection,
]
}
| StarcoderdataPython |
1600650 | <filename>Imu.py<gh_stars>1-10
import ctypes
class Imu():
def __init__(self):
self.accel = list()
self.gyro = list()
def getRandom(self, factor):
self.accel.append((factor+1)*11)
self.accel.append((factor+1)*12)
self.accel.append((factor+1)*13)
self.gyro... | StarcoderdataPython |
198697 | """
Copyright 2020 Inmanta
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in ... | StarcoderdataPython |
12821130 | import grok.tests.grokker.priority
class AlphaSub(grok.tests.grokker.priority.Alpha):
pass
class BetaSub(grok.tests.grokker.priority.Beta):
pass
class GammaSub(grok.tests.grokker.priority.Gamma):
pass
| StarcoderdataPython |
3317767 | <gh_stars>1-10
"""
project metadata
"""
try:
import importlib.metadata as importlib_metadata
except ModuleNotFoundError:
import importlib_metadata
__version__ = importlib_metadata.version(__name__)
| StarcoderdataPython |
5082071 | <gh_stars>1-10
"""
Orka Discord Bot
Copyright (c) 2017 <NAME>
"""
###########
# IMPORTS #
###########
import discord
import random
import markovify
from os import path, makedirs
from scripts import *
###################
# OTHER FUNCTIONS #
###################
def add_msg(channel, text, mode='a+'):
"""
Ap... | StarcoderdataPython |
4896396 | """Tests the figures.backfill module
"""
from __future__ import absolute_import
from datetime import datetime
import pytest
from dateutil.relativedelta import relativedelta
from dateutil.rrule import rrule, MONTHLY
from six.moves import range
from six.moves import zip
from django.db import connection
from django.utils... | StarcoderdataPython |
4948763 | from itertools import zip_longest
from elecsim.role.plants.costs.plant_cost_calculation import PlantCostCalculations
"""
File name: non_fuel_lcoe_calculation
Date created: 18/12/2018
Feature: # Calculates the costs of non fuel plants such as LCOE and marginal cost.
"""
__author__ = "<NAME>"
__copyright__ = "Copyrigh... | StarcoderdataPython |
3206089 | """
combine_expression_files.py
Combine expression files
"""
import sys
sys.path.append('./volumetric_analysis')
import argparse
from collections import defaultdict
import aux
if __name__=="__main__":
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=arg... | StarcoderdataPython |
4802842 | <reponame>step21/videohash
from shutil import which
from subprocess import Popen, PIPE
from .utils import does_path_exists, get_list_of_all_files_in_dir
from .exceptions import DownloadOutPutDirDoesNotExist, DownloadFailed
# Python module to download the video from the input URL.
# Uses yt-dlp to download the video.
... | StarcoderdataPython |
5100987 |
import os
import angr
from nose.tools import assert_true
test_location = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', 'binaries', 'tests')
def test_thumb_firmware_cfg():
# Test an ARM firmware sample.
#
# This tests CFG, but also the Gym (the ThumbSpotter, etc)
# Also requ... | StarcoderdataPython |
6524475 | #!C:\Users\denis\AppData\Local\Programs\Python\Python36\python
import psycopg2
from datetime import date
class DataBaseInteraction():
def __init__(self):
self.user = 'postgres'
self.password = '<PASSWORD>'
self.host = 'localhost'
self.port = '5432'
self.database = 'ProjectManagement'
self.today = date.t... | StarcoderdataPython |
1650529 | <filename>setup.py<gh_stars>1-10
from setuptools import setup, find_packages
import codecs
import pathlib
import re
here = pathlib.Path(__file__).parent.resolve()
def read(*parts):
"""
Build an absolute path from *parts* and and return the contents of the
resulting file. Assume UTF-8 encoding.
"""
... | StarcoderdataPython |
6566459 | <gh_stars>1-10
import pytest
import cv2
import numpy as np
from skimage import img_as_ubyte
from plantcv.plantcv import image_fusion, Spectral_data
def test_image_fusion(test_data):
"""Test for PlantCV."""
# Read in test data
# 16-bit image
img1 = cv2.imread(test_data.fmax, -1)
img2 = cv2.imread(t... | StarcoderdataPython |
45598 | # -*- coding: utf-8 -*-
from django.db import models
from datetime import date
from django.utils import timezone
from user.models import Person,Customer
from .price_category import PriceCategory
from core.models import Address
from core.mixins import TimeStampedMixin,PartComposMixin,ThumbnailMixin
from core.utils impor... | StarcoderdataPython |
5162288 | <filename>kNN/kNN.py
from numpy import *
import operator
import matplotlib
import matplotlib.pyplot as plt
def createDataSet():
group = array ([[1.0, 1.1], [1.0, 1.0], [0, 0], [0, 0.1]])
labels = ['A', 'A', 'B', 'B']
return group, labels
group, labels = createDataSet()
print(group)
print(labels)
def classify0(i... | StarcoderdataPython |
3487748 | <filename>lain_cli/imagecheck.py
# -*- coding: utf-8 -*-
from argh.decorators import arg
import lain_sdk.mydocker as docker
from lain_cli.utils import check_phase, get_domain, lain_yaml
from lain_sdk.util import error, info
def _check_phase_tag(phase):
yml = lain_yaml(ignore_prepare=True)
meta_version = yml.... | StarcoderdataPython |
227987 | from datetime import datetime
class User (object):
def __init__(self, username, password):
self.username = username
self.password = password
self.role = "normal"
def __repr__(self):
return '<User {}'.format(self.username)
class Admin(User):
def __init__(self, username... | StarcoderdataPython |
3331703 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Test example app."""
import os
import signal
import subprocess
import time
impor... | StarcoderdataPython |
192836 | import tensorflow as tf
import tensorflow.keras.backend as K
from tensorflow.keras.layers import Layer
class RoiPoolingConv(Layer):
"""
Define ROI Pooling Convolutional Layer for 2D inputs.
"""
def __init__(self, pool_size, num_rois, **kwargs):
self.image_data_format = K.image_data_format()... | StarcoderdataPython |
6524050 | #!/usr/bin/python
# HockeyBox
# by <NAME>, <EMAIL>
# Based on HockeyBox3.py by <NAME>
#
# Use 4-space tabs for indentation
# vim :set ts=4 sw=4 sts=4 et:
HOCKEYBOX_VERSION = "201811.1"
import RPi.GPIO as GPIO
from time import sleep
import os, random, vlc
from collections import deque
print "------------------------... | StarcoderdataPython |
3580764 | from .evpn import *
from .evi import *
from .vni import *
from .esi import *
| StarcoderdataPython |
112790 | from __future__ import with_statement, print_function
import pytest
try:
from unittest import mock
except ImportError:
import mock
from k2catalogue import proposal_urls
@pytest.fixture
def campaign():
return 1
@pytest.fixture
def mapper(campaign):
return proposal_urls.BuildCampaignMapping(campaign)... | StarcoderdataPython |
1891465 | # #####################################################################################################################
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. #
# ... | StarcoderdataPython |
112707 | <reponame>truekonrads/mirv-metasploit
#!/usr/bin/env python
#
# this program is used to find source code that includes linux kernel headers directly
# (e.g. with #include <linux/...> or #include <asm/...>)
#
# then it lists
import sys, cpp, glob, os, re, getopt, kernel
from utils import *
from defaults import *
progr... | StarcoderdataPython |
6683848 | __authors__ = "<NAME> (1813064), <NAME> (1713179), <NAME> (1626034)"
# maintainer = who fixes buggs?
__maintainer = __authors__
__date__ = "2020-05-01"
__version__ = "1.0"
__status__ = "Ready"
# kernel imports
import numpy as np
# own data imports
from constants import activationFunction
class neuron:
def __ini... | StarcoderdataPython |
3316676 | <filename>web/admin.py
from django.contrib import admin
from django.template import loader
from django.utils.translation import ugettext_lazy as _
from web.models import Origin, DemoUser
@admin.register(Origin)
class OriginAdmin(admin.ModelAdmin):
def changeform_view(
self,
request,
... | StarcoderdataPython |
1750657 | # input for cross-testing of test LAR files with a Python environment
from larlib import *
import networkx as nx
lines = tuple(open("test/csv/test1.V", 'r'))
V = [list(eval(line)) for line in lines]
lines = tuple(open("test/csv/test1.EV", 'r'))
EV = [list(eval(line)) for line in lines]
VIEW(STRUCT(MKPOLS((V,[[u-1,v-1... | StarcoderdataPython |
5036077 | import mmap
import argparse
import logging
import os
from os import path
import random
import string
import time
FORMAT = '%(asctime)-15s %(message)s'
logging.basicConfig(format=FORMAT, level=logging.INFO)
parser = argparse.ArgumentParser(description="Parse Search query log")
parser.add_argument('-n', type=int, defa... | StarcoderdataPython |
386773 | # PROJECT : django-easy-validator
# TIME : 18-1-2 上午9:44
# AUTHOR : <NAME>
# EMAIL : <EMAIL>
# CELL : 13811754531
# WECHAT : 13811754531
# https://github.com/youngershen/
from io import BytesIO
from django.test import TestCase
from django.core.files.uploadedfile import InMemoryUploadedFile
from validator import Val... | StarcoderdataPython |
8115365 | from django.db import models
class Coordinate(models.Model):
latitude = models.FloatField()
longitude = models.FloatField()
def __str__(self):
return f"[{self.latitude}, {self.longitude}]"
| StarcoderdataPython |
6633145 | <filename>tests/inlineasm/asmblbx.py
# test bl and bx instructions
@micropython.asm_thumb
def f(r0):
# jump over the internal functions
b(entry)
label(func1)
add(r0, 2)
bx(lr)
label(func2)
sub(r0, 1)
bx(lr)
label(entry)
bl(func1)
bl(func2)
print(f(0))
print(f(1))
| StarcoderdataPython |
29043 | <reponame>neriphy/numeros_primos
#Evaludador de numero primo
#Created by @neriphy
numero = input("Ingrese el numero a evaluar: ")
divisor = numero - 1
residuo = True
while divisor > 1 and residuo == True:
if numero%divisor != 0:
divisor = divisor - 1
print("Evaluando")
residuo = True
elif numero%divisor ==... | StarcoderdataPython |
1845294 | <filename>environment.py
import logging
logging.basicConfig(level=logging.DEBUG)
def before_all(context):
context.mobile_platform = context.config.userdata.get(
'mobile_platform', 'ios')
| StarcoderdataPython |
1676910 | <reponame>DaveeFTW/infinity
from ecdsa.ellipticcurve import CurveFp, Point
import hashlib
from ecdsa.numbertheory import inverse_mod
from ecdsa import SigningKey
from ecdsa.curves import Curve
import psptool.kirk as kirk
from .common import expand_seed, prx_header, set_kirk_cmd_1
from Crypto.Util.strxor import strxor ... | StarcoderdataPython |
12825911 | import os
import time
import math
import random
import numpy as np
import h5py
import matplotlib.pyplot as plt
import torch
import torch.backends.cudnn as cudnn
import torch.nn as nn
import torch.nn.functional as F
from torch import optim
from torch.autograd import Variable
from pytorch3d.io import save_ply, save_obj... | StarcoderdataPython |
3300286 | import sys
from operator import itemgetter
import cv2
import matplotlib.pyplot as plt
import numpy as np
# -----------------------------#
# 计算原始输入图像
# 每一次缩放的比例
# -----------------------------#
def calculateScales(img):
pr_scale = 1.0
h, w, _ = img.shape
# --------------------------------------------... | StarcoderdataPython |
1680893 | """
In this file it's been declered the function to create an instance of the Flask class
using the configuration avialable in the setting python file.
the function recived a string as a configuration name passing to the dict imported
the function also return a Flask instance.
"""
from flask import Flas... | StarcoderdataPython |
6616640 | # -*- coding: utf-8 -*-
# src/app.py
"""
API
------------------------------------------------------------------------
Create app
------------------------------------------------------------------------
"""
from flask import Flask, Response
from flask_c... | StarcoderdataPython |
3315795 | {
'targets': [
{
'target_name': 'dmp',
'sources': [
'src/diff_match_patch.cpp',
'src/dmp.cc'
],
'cflags': [ '-std=c++11' ],
'cflags!': [ '-fno-exceptions' ],
'cflags_cc!': [ '-fno-exceptions'],
'conditions': [
['OS=="mac"', {
'include_dir... | StarcoderdataPython |
3446348 | <gh_stars>1-10
from tkinter import *
from PIL import ImageTk, Image
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep
from selenium.webdriver.chrome.options import Options
#Selenium Ayarları
chrome_options = Options()
chrome_options.headless = True
#CHROM... | StarcoderdataPython |
9675575 | from protorpc import messages
from protorpc import remote
from protorpc.wsgi import service
from team import Team
import logging
package = 'SaintsSchedule'
# Create the request string containing the user's name
class ScheduleRequest(messages.Message):
team_id = messages.StringField(1, required=True)
# Create the... | StarcoderdataPython |
3358576 | <filename>tests/commands/run/test_scheduler.py
import subprocess
import json
import pytest
from unittest import mock
from BALSAMIC.commands.run.scheduler import SbatchScheduler
from BALSAMIC.commands.run.scheduler import QsubScheduler
from BALSAMIC.commands.run.scheduler import submit_job
from BALSAMIC.commands.run.s... | StarcoderdataPython |
1984977 | import sys
import re
def password_check(password, rules_dict):
'''
Verify that any given password string complies
with the requirements defined in the dictionary
'''
str_len = len(password) >= rules_dict['length']
has_numbers = True
if rules_dict['must_have_numbers']:
... | StarcoderdataPython |
281812 | import pytest
from src.vk_scheduler import VkPost
from src.models import IdentifiedRedditPost
from src.postgres import get_approved_anime_posts, connect_to_db
# pytest -n auto
# OR
# pytest -x ./tests/test_vk_scheduler.py
@pytest.mark.parametrize(
"anime_posts, result_display_message, result_hidden_messages",
... | StarcoderdataPython |
8110787 | import os
import sys
import json
import pytest
import subprocess
import time
from kat.harness import Query, is_ingress_class_compatible
from abstract_tests import AmbassadorTest, HTTP, ServiceType
from kat.utils import namespace_manifest
from tests.utils import KUBESTATUS_PATH
from ambassador.utils import parse_bool
... | StarcoderdataPython |
1922231 | <filename>wordsearch.py
#!/usr/bin/env python
DEFAULT_MIN_LENGTH = 3
class InvalidInput(ValueError): pass
class Puzzle(object):
SENTINEL = object()
def __init__(self, data):
if len(data) < 2:
raise InvalidInput("Must have more than one row")
len_1 = len(data[0])
for i, row... | StarcoderdataPython |
8100516 | # flip half input images and steering angles np.fliplr(image), -steering_angle
# use l and r camera images by pretending they are in center, and adding/subtracting correction.
# if l image, add correction, if r image, subtract correction
# start with 160x320x3 image into network by reading using cv2 (W, H), output... | StarcoderdataPython |
3256416 | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | StarcoderdataPython |
11201342 | # Copyright (c) 2020 BombDash
from __future__ import annotations
from typing import TYPE_CHECKING
import random
import ba
from bastd.actor import bomb as stdbomb
from bastd.actor.bomb import BombFactory, ExplodeMessage
from bastd.gameutils import SharedObjects
from ._redefine import redefine_class_methods, redefine_f... | StarcoderdataPython |
4861929 | <gh_stars>0
import urllib.request
import validators
from flask import render_template, request, flash
from bs4 import BeautifulSoup
from app import app
from app.models import Site
def parsing_url(url):
page = urllib.request.urlopen(url)
html = BeautifulSoup(page.read(), "html.parser")
title, keywords, d... | StarcoderdataPython |
1633377 | __author__ = '<NAME>'
'''
https://codeforces.com/problemset/problem/34/B
Solution: As long as the prices are negative, Bob would be interested to buy. Hence we sort the prices and select
the prices that are negative. That sum is what he needs to have (multiplied by -1).
'''
def solve(n, m, prices):
prices.sor... | StarcoderdataPython |
4902413 | #!/usr/bin/env python
"""
Sign daemon process that maintains the count displayed on the sign.
"""
import datetime
import logging
import optparse
import signal
import sys
import time
from sign_controller import SignController
from sign_util import CURSOR_HOME, CURSOR_MAGIC_1, CURSOR_MAGIC_2, ESCAPE
from sign_util impo... | StarcoderdataPython |
4991802 | __all__ = ['Chats']
from .conversation import Conversation
from .send_read_acknowledge import SendReadAcknowledge
class Chats(Conversation, SendReadAcknowledge):
""" methods.chats """ | StarcoderdataPython |
11312006 | <gh_stars>0
# Copyright (c) 2021 <NAME>, <NAME>.
#
# Licensed under the BSD 3-Clause License
# <LICENSE.rst or https://opensource.org/licenses/BSD-3-Clause>.
# This file may not be copied, modified, or distributed except
# according to those terms.
import pytest
from inators import imp as inators_imp
@pytest.mark.p... | StarcoderdataPython |
3342589 | <filename>src/masonite/contrib/essentials/helpers/__init__.py<gh_stars>0
from .views.hashid import hashid
| StarcoderdataPython |
209195 | <filename>rambo/resources/views.py
from utils import *
from resources.api import *
from django.contrib.auth.decorators import login_required
try:
import json
except:
import simplejson as json
@login_required
def get_resources(request, user=None):
try:
return response(do_get_resources(user))
except Exception as... | StarcoderdataPython |
11283882 | <filename>utils/file_handler.py<gh_stars>1-10
# -*- coding: utf-8 -*-
"""
--------------------------------------
@File : file_handler.py
@Author : maixiaochai
@Email : <EMAIL>
@CreatedOn : 2020/8/13 23:53
--------------------------------------
"""
from os import makedirs
from os.path import exists
im... | StarcoderdataPython |
8045917 | <gh_stars>1-10
#!/usr/bin/env python
#
# Licensed under the BSD license. See full license in LICENSE file.
# http://www.lightshowpi.com/
#
# Author: <NAME>
# Author: <NAME> (<EMAIL>)
"""Empty wrapper module for wiringpi
This module is a place holder for virtual hardware to run a simulated lightshow
an a pc. This m... | StarcoderdataPython |
6480173 | '''
Created on Oct 14, 2018
@author: <NAME>
'''
import os, datetime, threading
from classes import tkinter_app
def init(datalog_path):
#Initialize the class with Datalog file path
max_file_size = 0
#Check if datalog path is a file or a directory
if not os.path.isdir(datalog_path):
datalog_fil... | StarcoderdataPython |
1624488 | <reponame>bartekpacia/informatyka<gh_stars>1-10
def jest_anagram(a: str, b: str) -> bool:
# the fast way
if a == b:
return True
a_chars: dict[str, int] = {}
for char in a:
if not a_chars.get(char):
a_chars[char] = 1
else:
a_chars[char] += 1
b_chars: ... | StarcoderdataPython |
1667989 | # Generated by Django 2.2.4 on 2019-08-31 16:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wajiha', '0012_opportunitycategory_is_featured'),
]
operations = [
migrations.AddField(
model_name='opportunitycategory',
... | StarcoderdataPython |
294111 | <gh_stars>100-1000
# Copyright 2021 D-Wave Systems 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 b... | StarcoderdataPython |
6526929 | import unittest
from typing import List
class Solution:
def twoCitySchedCost(self, costs: List[List[int]]) -> int:
weights = []
n = len(costs)
for i in range(n):
weights.append([costs[i][0]-costs[i][1], i])
weights.sort()
sum_costs = 0
middle = int(n/2... | StarcoderdataPython |
5192874 | from copy import copy
from rest_framework.compat import urlparse
from rest_framework.schemas import SchemaGenerator as BaseSchemaGenerator
import coreapi
from drf_swagger_extras.hacks import monkey_patch
monkey_patch()
class SchemaGenerator(BaseSchemaGenerator):
def get_link(self, path, method, callback, view)... | StarcoderdataPython |
1864062 | <filename>analysis/sentiment-time-graph.py<gh_stars>0
import json
import os
import matplotlib.pyplot as plt
import commonfunctions as cf
root_directory = os.path.abspath(os.path.dirname(os.path.abspath(os.curdir)))
directory = os.path.join(root_directory, cf.working_directory)
with open('sentiment-time.json', 'r') ... | StarcoderdataPython |
11281512 | # -*- coding: utf-8 -*-
#
# Copyright 2012-2014 <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... | StarcoderdataPython |
3535658 | <reponame>giangbui/fence<gh_stars>0
from boto3 import client
from boto3.exceptions import Boto3Error
from fence.errors import UserError, InternalError, UnavailableError
import uuid
class BotoManager(object):
def __init__(self, config, logger):
self.sts_client = client("sts", **config)
self.s3_clie... | StarcoderdataPython |
8055102 | <reponame>tkemps/mklaren
import numpy as np
from itertools import product, combinations
# Kernel constanes
SPECTRUM = "1spectrum"
SPECTRUM_MISMATCH = "2spectrum_mismatch"
WD = "3weighted_degree_kernel"
WD_PI = "4weighted_degree_kernel_pos_inv"
EXPONENTIAL_SPECTRUM = "5exponential_s... | StarcoderdataPython |
94205 | <reponame>THUCSTHanxu13/BMInf
from .base import Layer
from ..parameter import Parameter
from ..allocator import Allocator
import cupy
import numpy as np
from ..functions.scale_copy import elementwise_copy
class Embedding(Layer):
def __init__(self, num_embeddings, embedding_dim):
self.embedding_dim = embed... | StarcoderdataPython |
4934562 | # Tesseract 3.02 Font Trainer
# V0.01 - 3/04/2013
'''
Edited by <NAME> 17/04/2020
- support for Windows file system
- added working directory, your original files will not be affected
- Input and Output folder for better organisation of files
'''
# Complete the documentation
import os
import subprocess
fontname = ... | StarcoderdataPython |
9255 | <gh_stars>1-10
"""Fixes for CESM2 model."""
from ..fix import Fix
from ..shared import (add_scalar_depth_coord, add_scalar_height_coord,
add_scalar_typeland_coord, add_scalar_typesea_coord)
class Fgco2(Fix):
"""Fixes for fgco2."""
def fix_metadata(self, cubes):
"""Add depth (0m) ... | StarcoderdataPython |
1815208 | from easilyb.urlselector import UrlSelector
from easilyb.net.requestqueue import Requester
from lxml.html import fromstring
import logging
logger = logging.getLogger(__name__)
def _crawler_callback(resp, index=None):
url,counter, depth, crawler = index
crawler._parse_response(url, depth, resp)
class LxmlX... | StarcoderdataPython |
8026986 | from spyd.game.player.player import Player
from spyd.permissions.functionality import Functionality
from spyd.registry_manager import register
@register('gep_message_handler')
class SpydGetPlayerInfoMessageHandler(object):
msgtype = 'get_player_info'
execute = Functionality(msgtype)
@classmethod
def ... | StarcoderdataPython |
6584303 | <reponame>MisterAI/AutoTeSG
#!/usr/bin/python
import sys
import astor
from ast import parse
if sys.version_info[0] < 3:
from io import BytesIO
else:
from io import StringIO
def doRun(codeTree):
compiled_code = compile(astor.to_source(codeTree), filename="<ast>",
mode="exec")
exec(compiled_code)
def runCode(c... | StarcoderdataPython |
8058763 | from .base_metric_loss_function import BaseMetricLossFunction
from ..utils import loss_and_miner_utils as lmu
import math
import torch
import torch.nn.functional as F
###### modified from https://github.com/idstcv/SoftTriple/blob/master/loss/SoftTriple.py ######
###### Original code is Copyright@Alibaba Group #... | StarcoderdataPython |
1788991 | from dataclasses import dataclass
from uuid import uuid4
from sqlalchemy import Boolean, Column, DateTime
from sqlalchemy.dialects.postgresql import UUID
from app.configs.database import db
@dataclass
class Session(db.Model):
id: str
start: str
end: str
finished: bool
__tablename__ = "sessions... | StarcoderdataPython |
1672441 | <reponame>epedropaulo/MyPython<filename>02 - Estruturas de controle/ex038.py
num1 = float(input('Digite o primeiro valor: '))
num2 = float(input('Digite o segundo valor: '))
if num1 > num2:
print('O primeiro valor é maior!')
elif num2 > num1:
print('O segundo valor é maior!')
else:
print('Os valores ... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.