id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
11392727 | from ....models.models import Role
from ...generics.create import CreateAction
from ...util.default_schema import DefaultSchema
from ...util.register import register_action
from .deduplicate_permissions_mixin import DeduplicatePermissionsMixin
@register_action("role.create")
class RoleCreate(DeduplicatePermissionsMix... | StarcoderdataPython |
351955 | import configparser
import copy
import re
import sys
import types
from dikort.print import print_error
_FILE_CONFIG_INT_OPTIONS = ("min_length", "max_length")
_FILE_CONFIG_BOOL_OPTIONS = (
"enable_length",
"enable_capitalized_summary",
"enable_trailing_period",
"enable_singleline_summary",
"enable... | StarcoderdataPython |
5126375 | <filename>fondInformatica/python/Esercitazione2_max3n (lupia).py
x = int(input("Inserisci il primo numero:> "))
y = int(input("Inserisci il secondo numero:> "))
z = int(input("Inserisci il terzo numero:> "))
if x >= y and x >= z:
massimo = x
elif y >= x and y >= z:
massimo = y
else:
massimo = z
print('Il... | StarcoderdataPython |
4926052 | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | StarcoderdataPython |
6605552 | <gh_stars>0
from .excerpt_search import audio_features
from .utils import farthest_points
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from scipy.spatial.distance import pdist, squareform
from scipy.spatial import distance
import essentia.standard as esst
import numpy as np
imp... | StarcoderdataPython |
6439620 | <filename>template/simple/setup.py
from distutils.core import setup
setup(
name="[project_name]",
version=(open("VERSION").read()).rstrip(),
author="author",
author_email="author_email",
license="MIT",
url="https://github.com/[ProjectSpace]/[project_name]",
description="Project description... | StarcoderdataPython |
1847332 | <filename>computeFV.py
import os, sys, collections
import numpy as np
from yael import ynumpy
import IDT_feature
from tempfile import TemporaryFile
"""
Encodes a fisher vector.
"""
def create_fisher_vector(gmm_list, video_desc, fisher_path):
"""
expects a single video_descriptors object. videos_desciptors objects... | StarcoderdataPython |
241216 |
'''
'''
import json
# Json format Running Info list string
Running_Info = '''
{
"Setting_Lists" :
{
"Vpv-Start":
{
"Unit": "V",
"UnitVal" : 0.1,
"Description" : "PV1 start-up voltage",
"Length" : 2,
"V... | StarcoderdataPython |
1866699 | <gh_stars>0
#!/usr/bin/env python
"""
This code holds the solution for part 2 of day 16 of the Advent of Code for 2015.
"""
known_facts = """children: 3
cats: 7
samoyeds: 2
pomeranians: 3
akitas: 0
vizslas: 0
goldfish: 5
trees: 3
cars: 2
perfumes: 1"""
aunts = {}
known_aunt = {}
def extract_field(aunt_info, pieces, ... | StarcoderdataPython |
356921 | import nisyscfg
import nisyscfg.xnet
import sys
class DeviceNotFoundError(Exception):
pass
class PortNotFoundError(Exception):
pass
def nixnet_assign_port_name(serial_number, port_number, port_name):
with nisyscfg.Session() as session:
# Search for the NI-XNET device with the sp... | StarcoderdataPython |
5014306 | <reponame>jay-tyler/data-structures<gh_stars>1-10
def insort(unlist):
"""Insertion sort a list
Implementation follows after gif here
https://en.wikipedia.org/wiki/Insertion_sort"""
slist = unlist[:]
for i in range(1, len(slist)):
j = i - 1
while j >= 0:
if slist[i] < sli... | StarcoderdataPython |
273889 | <reponame>agupta-io/testplan
"""Unit tests for MultiTest base functionality."""
import os
from testplan.common.utils import path
from testplan.testing import multitest
from testplan.testing.multitest import base
from testplan.testing import filtering
from testplan.testing import ordering
from testplan import defaults... | StarcoderdataPython |
224298 | <filename>main.py<gh_stars>0
from PyQt5.QtWidgets import QApplication, QWidget, QFileDialog, QPushButton, QLabel, QGridLayout, QHBoxLayout
from PyQt5.QtCore import pyqtSlot, pyqtSignal, QThreadPool, QRunnable, QTimer, QSize, QObject
from PyQt5.QtGui import QPixmap
import sys
import os
import json
import subprocess
impo... | StarcoderdataPython |
112949 | from super_gradients.common.factories.base_factory import BaseFactory
from super_gradients.training.losses import LOSSES
class LossesFactory(BaseFactory):
def __init__(self):
super().__init__(LOSSES)
| StarcoderdataPython |
11311012 | <filename>backend/api/permissions.py
# -*- coding: utf-8 -*-
from rest_framework.permissions import BasePermission, SAFE_METHODS
from api.models import Blog
class IsOwner(BasePermission):
"""Custom permission class to allow only Blog owners to edit them."""
def has_object_permission(self, request, view, obj):... | StarcoderdataPython |
3417343 | with open("/Users/apoorv/aoc/aoc_2018/data/aoc_7_data.txt") as inp:
data = inp.read().splitlines()
data = [(x[5], x[36]) for x in data]
m = dict()
for x in data:
m[x[0]] = set()
m[x[1]] = set()
for a, b in data:
m[b].add(a)
l = []
out = []
for key in m:
if len(m[key]) == 0:
l.append(ke... | StarcoderdataPython |
11351807 |
import groads
| StarcoderdataPython |
1612627 | # -*- coding: utf-8 -*-
"""Tests.
"""
import pytest
from mss.utils.utils_collections import arrange_by_alphabet, group_to_size
@pytest.fixture
def input_data_arrange():
return [
'#',
'acquire',
'acquire',
'constrain',
'enthusiastic',
'think',
'edge',
]... | StarcoderdataPython |
12809549 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# Created by <NAME>
# Rev.2020Jan28
#
"""This package generates the Input of microkinetic models for Maple.
Possible expansions:
* Put is and fs as lists, to support H2 dissociative adsorption for instance.
* Non-isothermal reactors, T dependent on time.
... | StarcoderdataPython |
6529899 | <reponame>goelyash/Spider
from pybloom import ScalableBloomFilter
import os
from threading import Lock
MAX_BUF_WRITES = 10
#BloomSet is used to maintain visited status of the urls
class BloomSet:
#initialize member variables
def __init__(self, name):
self.name = name
self.multiDir = "MultiBloom"
self.multiNa... | StarcoderdataPython |
9604183 | <gh_stars>0
import sys
L = [ m.split('|') for m in open(sys.argv[1]).readlines() ]
m = [0,0,8,1,7,4]
M = lambda l,x: m[l] or 15-x[0]*9-x[1]*6 if l else 5-x[0]-x[1]*2
a = sum(sum(bool(m[len(x)-5]) for x in l[1].split()) for l in L)
b=0
for n,o in L:
S = [set(c for c in n if n.count(c)==i) for i in m]
e,c = *S[5], *... | StarcoderdataPython |
4864190 | <filename>FNNMCMultiDim.py
#!/usr/bin/env python
# PyTorch 1.8.1-CPU virtual env.
# Python 3.9.4 Windows 10
# -*- coding: utf-8 -*-
"""The script implement the classical longstaff-schwartz algorithm for pricing american options.
This script focus on the multidimensional case for rainbow option
"""
import numpy as np
i... | StarcoderdataPython |
4908236 | <reponame>ansonb/NeuralNetwork<filename>lib/ops.py
from abc import ABC, abstractmethod
class Op(ABC):
def __init__(self, node_name, is_trainable=False):
super().__init__()
self.val = None
self.variable_type = 'none'
self.node_name = node_name
def bprop(self, input_nodes, cur_node, target_node, grad_table... | StarcoderdataPython |
5110522 | <reponame>aschneuw/road-segmentation-unet
import code
import glob
import os
import time
from datetime import datetime
import numpy as np
import tensorflow as tf
import images
import unet
from constants import NUM_CHANNELS, IMG_PATCH_SIZE, FOREGROUND_THRESHOLD
from summary import Summary
tf.app.flags.DEFINE_integer('... | StarcoderdataPython |
5000281 | # Generated by Django 3.1.1 on 2020-09-25 10:25
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Car',
fields=[
... | StarcoderdataPython |
11363135 | import pandas as pd
import numpy as np
import abc
from copy import copy
from time import time
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.utils.random import check_random_state
from robusta.crossval import crossval
from ._verbose import _print_last
from ._subset import FeatureSubset
from .... | StarcoderdataPython |
11245636 | <reponame>erteck/textHighlighter
from abc import ABC, abstractmethod
from math import pi
class GeometricObject(ABC):
def perimeter(self):
pass
def area(self):
pass
class Circle(GeometricObject):
def __init__(self,radius = 1.0):
self._radius = radius
def perimeter(self):
... | StarcoderdataPython |
4849328 | <reponame>UAL-RE/ReM
from typing import Union, Optional
import requests
from ldcoolp_figshare import FigshareInstituteAdmin
from fastapi import APIRouter, HTTPException
router = APIRouter()
api_key: Optional[str] = None
stage_api_key: Optional[str] = None
def figshare_metadata_readme(figshare_dict: dict) -> dict:... | StarcoderdataPython |
4875764 | <reponame>PetkoAndreev/Python-basics<gh_stars>0
change = float(input())
num_coins = 0
while change != 0:
if change >= 2:
change = round(change - 2, 2)
num_coins += 1
elif change >= 1:
change = round(change - 1, 2)
num_coins += 1
elif change >= 0.5:
change = round(cha... | StarcoderdataPython |
1658635 | # Assuming the recorded transactions to be in the following format:
# [[[T-Nrt][Item 1, Item 2, Item 3]],[[T-3689], [1,2,2,3,8,7]]]
#from powerset import potenzmenge
from itertools import combinations, product
from create_transactions import create_transactions
import timeit
def apriori (transactions, min_trashhold, ... | StarcoderdataPython |
5030812 |
class Struct(object):
def __init__(self, d):
for key, value in d.items():
if isinstance(value, (list, tuple)):
setattr(
self,
key,
[
Struct(item) if isinstance(item, dict)
... | StarcoderdataPython |
8002342 | <filename>src/AoC_2016/d9_decompress_str_re_recursion/expand_compressed_re_recurse.py
"""
Author: Darren
Date: 11/06/2021
Solving https://adventofcode.com/2016/day/9
Solution 2 of 2:
X(8x2)(3x3)ABCY
Original solution replaced src str with target str, i.e. by expanding.
However, part 2 was taking too ... | StarcoderdataPython |
6685827 | from __future__ import unicode_literals
from django.core.paginator import Page, Paginator
from django.urls import reverse
from django.shortcuts import redirect
from django.utils.functional import cached_property
from .blocks import SkipState
class SkipLogicPaginator(Paginator):
"""
Breaks a series of questi... | StarcoderdataPython |
6487979 | <reponame>EliahKagan/old-practice-snapshot<filename>main/group-anagrams/group-anagrams.py
class Solution:
def groupAnagrams(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
indices = {} # indexes into groups
groups = []
for word in strs:
... | StarcoderdataPython |
4816873 | n1 = int(input('Um valor:'))
n2 = int(input('Outro valor:'))
soma = n1 + n2
multiplicacao = n1 * n2
divisao = n1 / n2
divisaoint = n1 // n2
potencia = n1 ** n2
print('A soma é {} , \no produto é {} e a divisão é {:.3f}'.format(soma, multiplicacao, divisao), end=' ')
print('Divisão inteira {} e potencia {}'.format(divis... | StarcoderdataPython |
262184 | <gh_stars>0
import numpy
from astropy.io import fits
hdu = fits.open('filter_curves.fits')
# WARNING: These filter curves include the telescope and detectors!
for band in ['U', 'G', 'R', 'I', 'Z']:
data_file = 'gunn_2001_{0}_response.db'.format(band.lower())
numpy.savetxt(data_file, numpy.transpose([hdu[ban... | StarcoderdataPython |
4943645 | def main():
from argparse import ArgumentParser
parser = ArgumentParser(description='Gerar etiquetas para postagem nos Correios através de um arquivo CSV.')
parser.add_argument('arquivo_csv')
parser.add_argument('-o', '--arquivo-output', help='Arquivo de output. O output sairá para stdout se não especi... | StarcoderdataPython |
3315548 | <reponame>alex-dya/security_scanner
import logging
from scanner import transports, types, controls
from scanner.detect import detect
logging.basicConfig(level=logging.DEBUG)
LOGGER = logging.getLogger(__name__)
def scan(config: dict) -> list:
transports.config = config
detect()
controls.run_controls()
... | StarcoderdataPython |
3216023 | <filename>survival/lifespan-bannedsimVsdata.py
# encoding: utf-8
import os
import csv
from pylab import *
from numpy import *
from loadData import loadData
from mymath import statistic, revcumsum
from random import sample as spl
#sim
N = 200000 # number of users
t0 = 500 # initial time for observation
T = t0 +320
P = [... | StarcoderdataPython |
3473100 | <reponame>e-gills/running-log<gh_stars>1-10
from pymysql import connect, cursors
from utilities.creds import mysql_creds
from utilities.mysql_query import Query
def get_charts_for_page(render_page):
conn = connect(host=mysql_creds['host'], port=mysql_creds['port'], user=mysql_creds['user'],
pa... | StarcoderdataPython |
1997181 | from rest_framework import viewsets, generics
from rest_framework.generics import get_object_or_404
from rest_framework.permissions import IsAuthenticated
from salary_calculator.models import Salary, Payout
from salary_calculator.serializers import DaySerializer, SalarySerializer, PayoutSerializer
from salary_calculat... | StarcoderdataPython |
3463713 | <filename>timelogger/urls.py
"""timelogger URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', v... | StarcoderdataPython |
4871618 | GREEN = 0
YELLOW = 1
WHITE = 2
BLUE = 3
RED = 4
ALL_COLORS = [GREEN, YELLOW, WHITE, BLUE, RED]
COLORNAMES = ["green", "yellow", "white", "blue", "red"]
HINT_COLOR = 0
HINT_NUMBER = 1
PLAY = 2
DISCARD = 3
class Action(object):
def __init__(self, type, pnr=None, col=None, num=None, cnr=None, comme... | StarcoderdataPython |
11286929 | <filename>HTMLReport/src/tools/log/handler_factory.py
"""
Copyright 2017 刘士
Licensed under the Apache License, Version 2.0 (the "License"): you may
not use this file except in compliance with the License. You may obtain
a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applic... | StarcoderdataPython |
3436983 | fname = input('Enter the file name:')
try :
fhand = open('ch07\\' + fname)
except :
print('File cannot be opened:',fname)
quit()
count = 0
conf = 0.
for str in fhand :
if not str.startswith('X-DSPAM-Confidence:') :
continue
count += 1
conf += float(str.lstrip('X-DSPAM-Confidence: '))
pri... | StarcoderdataPython |
382035 | __author__ = '<NAME>'
from electricitycostcalculator.electricity_rate_manager.rate_manager import ElectricityRateManager
from electricitycostcalculator.openei_tariff.openei_tariff_analyzer import *
import pandas as pd
# ----------- TEST DEMO -------------- #
READ_FROM_JSON = False
# useful functions
def utc_to_local... | StarcoderdataPython |
11248731 | from django.shortcuts import render, get_object_or_404
from .models import Mentiq
from .forms import MentiqForm
from taggit.models import Tag
from django.template.defaultfilters import slugify
def home_view_mentiq(request):
mentiqs = Mentiq.objects.all()
common_tags = Mentiq.tags.most_common()[:4]
form ... | StarcoderdataPython |
8066981 | <gh_stars>0
dict={"Usain":1, "Me":2, "Qazi":3}
def choice_to_number(choice):
return dict[choice]
def number_to_choice(number):
for x in dict:
if dict[x]==number:
return x
usr_choice=input("Person of choice:")
print(choice_to_number(usr_choice))
usr_number=int(input("Number of choice:"))
pr... | StarcoderdataPython |
11368381 | <filename>pythondesafios/desafio067.py
#Faça um programa que mostre a tabuada de vários números, um de cada vez, para cada valor digitado pelo usuário. O programa será interrompido quando o número solicitado for negativo.
número = contador = total = 0
while True:
número = int(input('Quer ver a tabuada de qual número... | StarcoderdataPython |
3570471 | import requests
from chalicelib import util
import time
def order():
datas = {
"symbol": "TRX/USDT",
"position": "short",
"target_price": 1,
"trade_condition": "exit_short"
}
headers = {'Content-Type': 'application/json; charset=utf-8'}
url = "http://localhost:8000/tr... | StarcoderdataPython |
3586836 | <gh_stars>1-10
from setuptools import setup
setup(
name='tripledraw',
version='0.1',
py_module=['tripledraw'],
install_requires=[
'click>=4.0',
'ansicolors'
],
author='<NAME>',
author_email='<EMAIL>',
entry_points='''
[cons... | StarcoderdataPython |
1698229 | <filename>app/src/main/jni/src/test_healthd.py
#!/usr/bin/python
import sys
import dbus
import re
import dbus.service
import dbus.mainloop.glib
import os
import glib
from test_healthd_parser import *
dump_prefix = "XML"
system_ids = {}
def get_system_id(path, xmldata):
if path in system_ids:
return system_ids[pa... | StarcoderdataPython |
9661762 | import numpy as np
import cv2
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture(0)
# overlay_img = cv2.imread('laughingMan.png', cv2.IMREAD_UNCHANGED)
# ratio = overlay_img.shape[1] / overlay_img.shape[0]
boundingBox = {
"x":0,
... | StarcoderdataPython |
5119461 | <reponame>PawWitGit/bentley-ottmann-api
from typing import Any, Optional, Union
from pydantic import BaseSettings, PostgresDsn, validator
class Settings(BaseSettings):
"""
Settings for `Geometry api` project.
"""
db_user: str
db_password: str
db_name: str
db_port: str
db_host: str
... | StarcoderdataPython |
3223643 | <filename>python/701.insert-into-a-binary-search-tree.py
#
# @lc app=leetcode.cn id=701 lang=python3
#
# [701] 二叉搜索树中的插入操作
#
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 递归思路
def insert... | StarcoderdataPython |
12857746 | <filename>app.py<gh_stars>1-10
# Import from system libraries
from flask import Flask
from flask_bcrypt import Bcrypt
from flask_cors import CORS
from flask_jwt_extended import JWTManager
from flask_restful import Api
# Import from application modules
from errors import errors
from models.User import User
from models.... | StarcoderdataPython |
9783874 | import sys
import copy
import json
import numpy as np
import numpy.linalg
#import scipy
#import scipy.linalg
from ..geometry import vertex_all_in_set
use_geom_accel=True
if use_geom_accel:
from ..geometry_accel import point_in_polygon_2d
from ..geometry_accel import polygon_intersects_box_2d
from .... | StarcoderdataPython |
3312989 | from ._pixel_classifier import PixelClassifier
import numpy as np
class ObjectClassifier():
def __init__(self, opencl_filename="temp_object_classifier.cl", max_depth: int = 2, num_ensembles: int = 10):
"""
A RandomForestClassifier for label classification that converts itself to OpenCL after traini... | StarcoderdataPython |
11351725 | #!/bin/python3
###############################################################################
# Copyright 2020 UChicago Argonne, LLC.
# (c.f. AUTHORS, LICENSE)
# SPDX-License-Identifier: BSD-3-Clause
##############################################################################
import argparse
import re
import os
fr... | StarcoderdataPython |
232032 | <filename>src/__init__.py
from .view import *
from .service import *
| StarcoderdataPython |
1944084 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 28 19:59:24 2019
@author: avelinojaver
"""
import pandas as pd
from pathlib import Path
import matplotlib.pylab as plt
import numpy as np
#from py4j.java_gateway import JavaGateway
from openslide import OpenSlide
#%%
if __name__ == '__main__':
... | StarcoderdataPython |
6692385 | <gh_stars>0
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) IBM Corporation 2020
# Apache License, Version 2.0 (see https://opensource.org/licenses/Apache-2.0)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.module_utils.basic import AnsibleModule, missin... | StarcoderdataPython |
3346763 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# MIT License
#
# Copyright (c) 2019 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation t... | StarcoderdataPython |
1647937 |
# Generate a report of all new staged test centers, optionally push to Unverified table.
import requests
import os
import importlib
from helpers import preprocessing_utils, gtc_auth
from dotenv import load_dotenv
import time
import click
import json
import boto3
DAY_IN_MILLIS = 60 * 60 * 24 * 1000
S3_BUCKET = 'stagi... | StarcoderdataPython |
49098 | #!/usr/bin/env python
"""Creates or updates distribution files"""
import subprocess
print "Updates JavaScript and Type Definition files..."
subprocess.call(['rm', 'dist', '-rf'])
subprocess.call(['tsc', '--declaration'])
| StarcoderdataPython |
9686569 | import logging
import os
from src.python_discord_logger.utils import get_discord_logger
def initialize_logger() -> logging.Logger:
logger = get_discord_logger(
__name__,
os.environ["WEBHOOK_URL"],
os.environ["WEBHOOK_USER_ID"],
)
logger.setLevel(logging.DEBUG)
return logger
... | StarcoderdataPython |
190218 | <reponame>cristianmtr/improved-initiative
import json
spells = json.load(open("spell-list.json", 'r', encoding="utf8"))
for s in spells:
try:
s["Description"] = s["Description"][0]
for learner in s["learnedBy"]:
if "level" in learner.keys():
s["Level"] = learner["level"... | StarcoderdataPython |
3564395 | <filename>info/utils/common.py
import functools
import qiniu
from flask import current_app
from flask import g
from flask import session
def do_index_class(index):
"""自定义过滤器,过滤点击排序html的class"""
if index == 1:
return "first"
elif index == 2:
return "second"
elif index == 3:
ret... | StarcoderdataPython |
8023693 | from datetime import datetime
from typing import Any
from unittest.mock import ANY, MagicMock
import pytest
from starlette import status
from starlite import TestClient
from app import models, repositories
from app.config import app_settings
from app.types import BeforeAfter, LimitOffset
from tests.utils import USERS... | StarcoderdataPython |
351272 | <gh_stars>10-100
import numpy as np
import scipy.ndimage as ndimage
import scipy.signal
def bahorich_coherence(data, zwin):
ni, nj, nk = data.shape
out = np.zeros_like(data)
padded = np.pad(data, ((0, 0), (0, 0), (zwin//2, zwin//2)), mode='reflect')
for i, j, k in np.ndindex(ni - 1, nj - 1, nk - 1):
... | StarcoderdataPython |
3517861 | <filename>LearningPython.py
datalist = [1, 3, 4, 7, 2, 9,55]
biggest = datalist[2]
for val in datalist:
if val > biggest:
biggest = val
print(biggest) | StarcoderdataPython |
3479709 | <filename>setup.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import sys
try:
from setuptools.core import setup
except ImportError:
from distutils.core import setup
with open('SimpleHOHMM/package_info.json') as f:
_info = json.load(f)
def setup_package():
needs_sphinx = {'build_sphinx... | StarcoderdataPython |
6415607 | <reponame>silentos1/OpenCV
import cv2
import numpy as np
plik1 = open('test1.txt', 'w')
plik2 = open('test2.txt', 'w')
MinProg = 5
MaxProg = 120
MinObszar = 60
MinKolistosc = .1
MinInertia = .3
kamera = cv2.VideoCapture(0) # kamerka... | StarcoderdataPython |
367685 | # wujian@2018
import os
import json
def dump_json(obj, fdir, name):
"""
Dump python object in json
"""
if fdir and not os.path.exists(fdir):
os.makedirs(fdir)
with open(os.path.join(fdir, name), "w") as f:
json.dump(obj, f, indent=4, sort_keys=False)
| StarcoderdataPython |
5142421 | <reponame>dansuh17/deep-supervised-hashing<filename>model.py
import torch
from torch import nn
import torch.nn.functional as F
class ResBlock(nn.Module):
def __init__(self, in_channels: int, out_channels: int, stride=1):
super().__init__()
self.net = nn.Sequential(
nn.Conv2d(
... | StarcoderdataPython |
156596 | #!/usr/bin/env python
"""
Copyright (c) 2004-Present Pivotal Software, Inc.
This program and the accompanying materials are made available under
the terms of the under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License ... | StarcoderdataPython |
4913536 | <reponame>dukundejeanne/neighbourhood_django<gh_stars>0
from django.db import models
from django.contrib.auth.models import User
from tinymce.models import HTMLField
from django.core.validators import MaxValueValidator
# Create your models here.
class Neighbour(models.Model):
name=models.CharField(max_length=30)
... | StarcoderdataPython |
8131727 | <gh_stars>0
import typing as T
from contextlib import contextmanager
from pathlib import Path
from click.utils import LazyFile
OpenFileLike = T.Union[T.TextIO, LazyFile]
FileLike = T.Union[OpenFileLike, Path, str]
@contextmanager
def open_file_like(
file_like: T.Optional[FileLike], mode, **kwargs
) -> T.Context... | StarcoderdataPython |
1607384 | <gh_stars>0
"""
Given an array of integers, find the pair of adjacent elements that has the largest product and return that product.
Example
For inputArray = [3, 6, -2, -5, 7, 3], the output should be
adjacentElementsProduct(inputArray) = 21.
7 and 3 produce the largest product.
Input/Output
[execution time limit]... | StarcoderdataPython |
154651 | """
LC89. Gray Code
The gray code is a binary numeral system where two successive values differ in only one bit.
Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.
Example 1:
Input: 2
Output: [0,1,3,2]
Explanation... | StarcoderdataPython |
6567646 | from __future__ import absolute_import
from sentry.testutils import AcceptanceTestCase
FEATURE_NAME = "organizations:events"
class OrganizationEventsTest(AcceptanceTestCase):
def setUp(self):
super(OrganizationEventsTest, self).setUp()
self.user = self.create_user("<EMAIL>")
self.org = s... | StarcoderdataPython |
5068422 | <filename>xfdnn/tools/compile/network/__init__.py
#!/usr/bin/env python
#
# // SPDX-License-Identifier: BSD-3-CLAUSE
#
# (C) Copyright 2018, Xilinx, Inc.
#
import os, sys
for d in ["codegeneration","graph","memory","network","optimizations", "weights","version","tests"]:
path = "%s/../%s" % (os.path.dirname(os.path.r... | StarcoderdataPython |
8095794 | from telethon.tl.custom.message import Message
from ..Filter import Filter
class All(Filter):
def valid(self, msg: Message ) -> bool:
return True
| StarcoderdataPython |
6603384 | import gi
gi.require_version('Ahoviewer', '1.0')
gi.require_version('Gtk', '3.0')
from gi.repository import Ahoviewer, GObject, Gtk
class PythonHelloPlugin(Ahoviewer.WindowAbstract):
# This is just an exmaple of using the open_file member function, using a dialog
# here is obviously redundant because ahoviewer ha... | StarcoderdataPython |
11346743 | <filename>controle_colaboradores_api/apps/usuarios/management/commands/criar_grupos_do_projeto.py
from django.core.management.base import BaseCommand
from django.db import transaction
from django.conf import settings
from django.contrib.auth.models import Group
class Command(BaseCommand):
help = "Cria ou confirm... | StarcoderdataPython |
1707850 | from utils import timer_decorator
@timer_decorator
def find_min_1(array: list) -> int:
"""
O(n^2)
:param array: list of integers
:return: integer
"""
overallmin = array[0]
for i in array:
is_smallest = True
for j in array:
if i > j:
is_smallest... | StarcoderdataPython |
9771868 | <gh_stars>0
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
#Created on Tue Jul 29 10:12:58 2014
#@author: mcollado
"""
import Adafruit_DHT
import time
import sqlite3 as lite
import sys
import ConfigParser
import os
# If ConfigParser code fails this values are hardcoded
# To be removed when code works
sensor = Adafru... | StarcoderdataPython |
6692164 | <reponame>TIFOSI528/icefall
#!/usr/bin/env python3
# Copyright 2021 Xiaomi Corp. (authors: <NAME>
# <NAME>)
#
# See ../../../../LICENSE for clarification regarding multiple authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance wi... | StarcoderdataPython |
6418281 | #!/usr/bin/env python
import os
import re
from setuptools import setup
DIRNAME = os.path.abspath(os.path.dirname(__file__))
rel = lambda *parts: os.path.abspath(os.path.join(DIRNAME, *parts))
README = open(rel('README.md')).read()
INIT_PY = open(rel('flask_cqlengine.py')).read()
VERSION = re.findall("__version__ =... | StarcoderdataPython |
70845 | <gh_stars>1-10
from datetime import date
import pytest
from quickbase_client.orm.field import QB_DATE
from quickbase_client.orm.field import QB_TEXT
from quickbase_client.orm.field import QuickBaseField
from quickbase_client.query import ast
from quickbase_client.query.ast import eq_
from quickbase_client.query.ast i... | StarcoderdataPython |
1764043 | #!/usr/bin/python
import os, re
import numpy as np
import matplotlib.pyplot as plt
debug = True
def compute_rcr_parameters(area, Q_goal, P_min, P_max, P_mean, Q_mean, ratio_prox_to_distal_resistors, decay_time, C_prefactor=1.0):
tol = 1e-12
# total resistances
R_total = []
for Q in Q_goal:
... | StarcoderdataPython |
174233 | # -*- coding: utf-8 -*-
"""
Created on Tue Jul 10 09:48:18 2018
@author: a002028
"""
import yaml
import numpy as np
import pandas as pd
class YAMLwriter(dict):
"""Writer of yaml files."""
# TODO Ever used?
def __init__(self):
"""Initialize."""
super().__init__()
def _check_format(s... | StarcoderdataPython |
3325715 | <filename>molecool/io/__init__.py<gh_stars>0
"""
IO subpackage
molssi workshop: A python package for analyzing and visualizing xyz file.
"""
# Add imports here
from .pdb import open_pdb
from .xyz import open_xyz, write_xyz | StarcoderdataPython |
4930317 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-10-24 17:59
from __future__ import unicode_literals
import django.core.files.storage
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operati... | StarcoderdataPython |
1813046 | # Copyright 2018 Iguazio
#
# 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, softwa... | StarcoderdataPython |
11222072 | <reponame>billyrrr/onto
from unittest import mock
from unittest.mock import Mock, patch
import flask
import pytest
from flask import Flask
from onto import auth
import flask_restful
from flask_restful import Resource, ResponseBase
from firebase_admin import auth as firebase_admin_auth
import firebase_admin
from .fi... | StarcoderdataPython |
6412320 | from flask import Flask, jsonify, request
# from flask.ext.store import Store
import json
from .DataUploadAPI import data_upload_api
from .DataReqAPI import data_req_api
from .NewTaskAPI import new_task_api
from .GetModelAPI import get_model_api
from .InferAPI import infer_api
from .ModelUploadAPI import model_upload_... | StarcoderdataPython |
1863856 | from django.conf.urls import url
from django.views.generic import TemplateView
from django.views.generic import RedirectView
from rest_framework_jwt.views import (obtain_jwt_token,
verify_jwt_token,
refresh_jwt_token)
from restLogin import ... | StarcoderdataPython |
3370015 | """
A Collection of custom types for static type checking
"""
from typing import Union
RealNumber = Union[int, float]
Number = Union[RealNumber, complex]
| StarcoderdataPython |
11288411 | <filename>server/stylegan2_hypotheses_explorer/logic/evaluator/evaluator.py
from pathlib import Path
from typing import List, Type
import torch
from ...models import Evaluator as EvaluatorModel
from ..backend_lazy_loader import BackendLazyLoader
from .evaluator_backend import EvaluatorBackendT
class Evaluator(Backe... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.