id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
9651831 | <gh_stars>10-100
from matplotlib.backends.backend_macosx import _BackendMac, FigureCanvasMac
from . import _util
from .base import FigureCanvasCairo
class FigureCanvasMacCairo(FigureCanvasCairo, FigureCanvasMac):
# A bit hackish, but that's what _macosx.FigureCanvas wants...
def _draw(self):
if self... | StarcoderdataPython |
12808107 | import os
import random
import pyglet
import subprocess
#from mutagen.mp3 import MP3
import pygame
import time
import globals
from helpers import r3
from datacollector import DataCollector
class Radio(object):
def __init__(self, show=-1):
self.started = False
self.condition = ''
self.ful... | StarcoderdataPython |
80596 | import json
import os
import sys
from unittest import mock
import gemmi
from relion.cryolo_relion_it import mask_soft_edge_external_job
@mock.patch("relion.cryolo_relion_it.mask_soft_edge_external_job.subprocess")
def test_mask_soft_edge_main(mock_subprocess, tmpdir):
# Prepare things
os.chdir(tmpdir)
c... | StarcoderdataPython |
253143 | <gh_stars>1-10
from .doctor import *
from .edit import *
from .help import *
from .install import *
from .list import *
from .move import *
from .remove import *
from .setup import *
from .update import *
| StarcoderdataPython |
3584591 | from .MPR121 import MPR121_t, MPR121Error, MPR121SampleInterval
from types import MethodType
from math import ceil, log, pow
# simple wrapper over C++ MPT121_t so we can easily:
# import MPR121
# sensor = MPR121.begin()
# overwrite for setSamplePeriod so user can set arbitrary value instead of relying on struct f... | StarcoderdataPython |
1925864 | <filename>src/application/__init__.py
"""
Initialize Flask app
"""
from flask import Flask
from flask_debugtoolbar import DebugToolbarExtension
from gae_mini_profiler import profiler, templatetags
from werkzeug.debug import DebuggedApplication
#from flaskext.mail import Mail
import jinja2
#from flaskext.flask_googlel... | StarcoderdataPython |
9685778 | import torch
from torch.profiler import profile, record_function, ProfilerActivity
class CPUProfiler(object):
def __init__(self, model):
self.model = Model()
def start_gpu_profiler(inputs):
with profile(activities=[ProfilerActivity.CPU], record_shapes=True,profile_memory=True) as prof:
... | StarcoderdataPython |
370383 | <reponame>fun4jimmy/piaudio<gh_stars>0
"""Flask site application factory for switching between audio applications on the host system."""
import os.path
from flask import render_template
from flask_assets import Environment
from flask_assets import Bundle
import connexion
from piaudio import api
from piaudio.blueprin... | StarcoderdataPython |
5133784 | <filename>src/python_repository.bzl<gh_stars>1-10
def _get_actual_python_version(binary,p_repository_ctx):
command_result = p_repository_ctx.execute([binary, "-c", """import sys; print(".".join(map(str, sys.version_info[:3])))"""])
if command_result.return_code != 0:
fail("Could not acquire actual pytho... | StarcoderdataPython |
11239176 | """ this is akebono package, and modified normally."""
__version__ = "0.0.1"
| StarcoderdataPython |
3436417 | <filename>django_rebel/api/responses.py<gh_stars>1-10
import requests
from django_rebel.api.constants import EVENT_TYPES
class Response(dict):
def __init__(self, mailgun, base_response: requests.Response, base_request: requests.PreparedRequest, **kwargs):
from django_rebel.api.mailgun import Mailgun
... | StarcoderdataPython |
11373107 | import os
import torch
import logging
import torchvision.transforms as transforms
from torchexpresso.callbacks import Callback
from torchexpresso.utils import mkdir_if_not_exists, store_json_to, image_to_patches_2d
logger = logging.getLogger(__file__)
class SaveImageByLabel(Callback):
"""
Stores the i... | StarcoderdataPython |
8136339 | <gh_stars>1-10
"""
# trans-tool
# The translation files checker and syncing tool.
#
# Copyright ©2021 <NAME> <mail [@] <EMAIL>>
# https://github.com/MarcinOrlowski/trans-tool/
#
"""
from typing import Tuple, Union
from transtool.config.config import Config
from transtool.decorators.overrides import overrides
# ####... | StarcoderdataPython |
3208448 | from math import ceil
from copy import copy
import torch
import numpy as np
import skimage
from skimage import io
from skimage import color
from sklearn.decomposition import PCA
from sklearn.preprocessing import minmax_scale
class RunningAverage:
def __init__(self):
self.iter = 0
self.avg = 0.0
... | StarcoderdataPython |
8075297 | """Constants used by PyNest."""
from .models import NestEnvironment
USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36"
NEST_ENVIRONMENTS: dict[str, NestEnvironment] = {
"production": NestEnvironment(
name="Google Account... | StarcoderdataPython |
1880854 | import gfapy
import json
import re
def unsafe_decode(string):
return json.loads(string)
def decode(string):
validate_all_printable(string)
return unsafe_decode(string)
def validate_encoded(string):
# both regex and JSON parse are necessary,
# because string can be invalid JSON and
# JSON can contain forb... | StarcoderdataPython |
4848786 | <reponame>CNLPT/lightNLP
import torch
from torchtext.data import Dataset, Field, BucketIterator, ReversibleField
from torchtext.vocab import Vectors
from torchtext.datasets import SequenceTaggingDataset
from sklearn.metrics import f1_score, accuracy_score, recall_score, precision_score
from ...base.tool import Tool
fr... | StarcoderdataPython |
8031144 | <filename>functions_ml_models.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
************************************************************
user_engagement_compare_models.py
Humon
<NAME>
05-July-2018
Copyright 2017 Humon. All rights reserved.
------------------------------------------------------------
This code... | StarcoderdataPython |
11347981 | import lib.datastructures
def test_classified_get_hash():
c = lib.datastructures.Classified("Something", "Some street")
c.id = 1
assert (
c.get_hash()
== "95e2b9327793f1781bfb212047301a992e8e7b0b9b4c38ede46a8044a96c6d25"
)
def test_classified_str():
c = lib.datastructures.Classif... | StarcoderdataPython |
203216 | """
- O(1), O(1)
Approach 1: Flip Bit by Bit
Approach 2: Compute Bit Length and Construct 1-bits Bitmask
Approach 3: Built-in Functions to Construct 1-bits Bitmask
Approach 4: highestOneBit OpenJDK algorithm from Hacker's Delight
"""
from math import log2, floor
class Solution:
def findComplement1(self, num):... | StarcoderdataPython |
5106637 | <filename>common.py
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
"""The common component contains the logger, error logging, and
flair sanitizing functions that are used by both routines.
There are no functions that connect to Reddit in this component.
"""
import datetime
import logging
import re
import time... | StarcoderdataPython |
3354822 | class ServiceSnapshot(object):
def __init__(self, service, status, limit):
self.service = service
self.status = status
self.limit = limit
def as_header(self):
return "{0}={1}:{2}".format(self.service, self.status, self.limit)
def as_dict(self):
return {self.service:... | StarcoderdataPython |
1981678 |
# DETECT ARBITRAGE
import math
# O(N^3) time and O(N^2) space
def detectArbitrage(exchangeRates):
# Write your code here.
logExchangeRates = convertToLogMatrix(exchangeRates)
return foundNegativeWeightCycle(logExchangeRates, 0)
def foundNegativeWeightCycle(graph, start):
distancesFromStart = [float("inf... | StarcoderdataPython |
3528539 | <reponame>rubiorubio/online-shop
from django.views.generic import View
from .models import Cart, Customer
class CartMixin(View):
def dispatch(self, request, *args, **kwargs):
if request.user.is_authenticated:
customer = Customer.objects.filter(user=request.user).first()
if not cu... | StarcoderdataPython |
6538328 | <filename>ferenda/sources/legal/se/riksdagen.py
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from builtins import *
from future import standard_library
standard_library.install_aliases()
# A abstract base class for fetching documen... | StarcoderdataPython |
3296906 | <gh_stars>0
from twofish import Twofish
def xor(a, b):
w = [0 for _ in range(len(a))]
for i in range(len(a)):
w[i] = a[i] ^ b[i]
return bytes(w)
def kc(data: bytes, key: bytes):
key = list(key)
i = 0
h = len(data) - data[3] - 4
while h > 0:
t = (h ^ key[i]) & 0xff
k... | StarcoderdataPython |
55923 | <reponame>RaitzeR/VAL<filename>Render/RobotViewRenderer.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 9 22:10:55 2017
@author: RaitzeR
"""
from Helpers.Helpers import getEndPoint
from Render.Camera import Camera
from Render.Display import Display
from typing import Type, Tuple
from Robot.Ro... | StarcoderdataPython |
11290894 | #!/usr/bin/env python
# coding: utf-8
# # Starbucks Capstone Challenge
#
# ### Introduction
#
# This data set contains simulated data that mimics customer behavior on the Starbucks rewards mobile app. Once every few days, Starbucks sends out an offer to users of the mobile app. An offer can be merely an advertisemen... | StarcoderdataPython |
3275175 | from math import dist
from re import S
from typing import Optional, Tuple, Union
from _pytest.python_api import raises
from cadquery.occ_impl.shapes import Wire
from numpy.lib.function_base import angle
from paramak.parametric_shapes.extruded_mixed_shape import ExtrudeMixedShape
import numpy as np
import cadquery as cq... | StarcoderdataPython |
1868523 | #!/usr/bin/python3
# Zip Extractor v1.0
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.uic import loadUi
import zipfile
import sys
class Window(QWidget):
def __init__(self):
super(Window,self).__init__()
loadUi("./Form/page.ui",self)
self.setW... | StarcoderdataPython |
3252941 | from mylang import ast
from mylang import tokens
def parse(lexemes):
# TODO-TEST: other ID's (eg no) do nothing
result = ast.Module()
lexemes = iter(lexemes)
for lexeme in lexemes:
if lexeme == tokens.ID('hello'):
result = type(result)(*(result.datas + (ast.Hello(),)))
elif... | StarcoderdataPython |
3524506 | <reponame>HPI-MachineIntelligence-MetaLearning/multi-building-detector<filename>multibuildingdetector/trainchains/__init__.py<gh_stars>1-10
from .multiboxtrainchain import MultiboxTrainChain
from .triplettrainchain import TripletTrainChain
| StarcoderdataPython |
5005331 | import data_loader
import network
training_data, test_data = data_loader.load_data()
net = network.Network([4800, 500, 30, 1]) # Try to experiment with different layer sizes
net.SGD(training_data, 80, 20, 2.0, test_data=test_data) # Try to experiment with these training hyperparameters
| StarcoderdataPython |
1989501 | """
Example use:
cat bs_data.csv | python3 binary_search_iterative.py > bsi.csv
"""
import sys
sys.path.append('..')
sys.setrecursionlimit(100000000)
from util import benchmark_search, test_search
alg = "binary_search"
kind = "iterative"
def binary_search(arr, x):
lo = 0
hi = len(arr)
while(lo < hi):
... | StarcoderdataPython |
1896211 | <reponame>smallarmyofnerds/blasteroids
class PlayerInputs:
def __init__(self):
self.left = False
self.right = False
self.up = False
self.fire = False
def __repr__(self) -> str:
return f"{self.left} {self.right} {self.up} {self.fire}"
def is_anything_pressed(self):
... | StarcoderdataPython |
8113213 | import numpy as np
import time,os,sys
import util
print(util.toYellow("======================================================="))
print(util.toYellow("eval_STGAN.py (ST-GAN with homography)"))
print(util.toYellow("======================================================="))
import tensorflow as tf
import data
import gr... | StarcoderdataPython |
1922499 | <filename>src/primaires/scripting/utile/fonctions.py
# -*-coding:Utf-8 -*
# Copyright (c) 2012 <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must ret... | StarcoderdataPython |
11218530 | <gh_stars>0
import sqlalchemy as sa
import sqlalchemy.connectors.pyodbc
from .connector import TurbODBCConnector
tmap = {
0: sa.types.String,
1: sa.types.Integer,
2: sa.types.Float,
3: sa.types.Date,
4: sa.types.Time,
5: sa.types.Float,
6: sa.types.Float,
7: sa.types.Boolean,
8: sa... | StarcoderdataPython |
5183940 | <filename>cm/consumer_cm_compute.py
#!/usr/bin/env python
import pika
import socket
import requests
import logging
from app.constant import PORT,CM_ID,CELERY_BROKER_URL,RPC_Q,TRANFER_PROTOCOLE
LOG_FORMAT = ('%(levelname) -10s %(asctime)s %(name) -30s %(funcName) '
'-35s %(lineno) -5d: %(message)s')
log... | StarcoderdataPython |
9658018 | # Copyright (c) 2004-2006 gocept gmbh & co. kg
# See also LICENSE.txt
# $Id$
import unittest
from AccessControl import getSecurityManager
from Products.PluginIndexes.common.PluggableIndex import \
PluggableIndexInterface
from Products.CMFCore.utils import getToolByName
from Products.CMFCore import permission... | StarcoderdataPython |
8110375 | import asyncio
import importlib
from pyrogram import idle
from chatbot import app, LOGGER
importlib.import_module("chatbot.bot.chat_bot")
async def start_bot() -> None:
await app.start()
LOGGER.info(
"Simple chatbot written using the pyrogram library.\n "
"Uses Intellivoid's Coffeehouse API... | StarcoderdataPython |
8100830 | <gh_stars>0
#!/usr/bin/python
# This program logs a Raspberry Pi's CPU temperature to a Thingspeak Channel
# To use, get a Thingspeak.com account, set up a channel, and capture the Channel Key at https://thingspeak.com/docs/tutorials/
# Then paste your channel ID in the code for the value of "key" below.
# Then run as... | StarcoderdataPython |
1764938 | # -*- coding: utf-8 -*-
"""
ldp.globals
~~~~~~~~~~~~~
Defines all the global objects that are proxies to the current
active context.
"""
import sys
import types
from werkzeug.local import LocalStack, LocalProxy
class GlobalsModule(types.ModuleType):
__all__ = ('_dataset_ctx_stack', 'dataset', 'da... | StarcoderdataPython |
282513 | """
pysettings.__init__
Handler namespace registry.
Usage: ::
# in package top-layer entry point
import pysettings
pysettings.loadfrom_yaml("package_key", "path/to/settings.yaml")
# in package submodules or subpackages
import pysettings
nm = pysettings.get_namespace("package_key")
# a... | StarcoderdataPython |
1959800 | <gh_stars>10-100
# -*- coding: UTF-8 -*-
# -----------------------------------------------------------------------------
#
# P A G E B O T
#
# Copyright (c) 2016+ <NAME> + <NAME>
# www.pagebot.io
# Licensed under MIT conditions
#
# Supporting DrawBot, www.drawbot.com
# Supporting Flat, xxyxyz.or... | StarcoderdataPython |
303159 | <reponame>maikel/TaxiCam<filename>taxicam/camera.py
# -*- coding: utf-8 -*-
"""Control a surveillance/video camera in a car.
This module grabs single frames from a running video device to process
them and stores only gpg-encrypted data on the file system. For this to
be effective, the underlying operating system must ... | StarcoderdataPython |
5140648 | <filename>scripts/check_copyright.py
#!/usr/bin/env python3
# (C) 2022 GoodData Corporation
from __future__ import annotations
import argparse
import fileinput
import re
from collections import OrderedDict
from datetime import date
from pathlib import Path
from typing import AnyStr, Pattern
COPYRIGHT_RE: re.Pattern[A... | StarcoderdataPython |
6443837 | <filename>Django-Python-Full-Stack-Web-Devloper-master/Django_Level_Two/first_project/first_app/urls.py
from django.conf.urls import url
from first_app import views
urlpatterns = [
url(r'^$',views.index,name='index'),
]
| StarcoderdataPython |
1931372 | <filename>healthgen/apps/utils.py
"""
2021 <NAME>, ETHZ, MPI IS
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('font',**{'family':'serif','serif':['Computer Modern Roman'], 'size':15})
def plot_reconstructions(orig_data, recon_data, patient_idx, data_mode='feats_mask', feature_nam... | StarcoderdataPython |
281103 | <gh_stars>1-10
from .pyomexmeta import (
PersonalInformation,
EnergyDiff,
PhysicalProcess,
_PropertyBearer,
PhysicalProperty,
RDF,
Editor,
PhysicalEntity,
SingularAnnotation,
OmexMetaException,
Logger,
Message
)
from .pyomexmeta_api import PyOmexMetaAPI, get_version, eUri... | StarcoderdataPython |
1886273 | import hawkesbook as hawkes
import numpy as np
import numpy.random as rnd
from tqdm import tqdm
from numpy.testing import assert_allclose
empMean, empVar, empAutoCov = hawkes.empirical_moments([1, 2, 2.1, 2.3, 4.5, 9.9], T=10, τ=2, lag=1)
assert min(empMean, empVar) > 0
assert hawkes.hawkes_intensity(1, [], [1, Non... | StarcoderdataPython |
1837971 | # imoort relatefile
import sys
from threading import Thread
import drivers
from time import sleep
import RPi.GPIO as GPIO
import random
# setup hardware
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.IN,pull_up_down=GPIO.PUD_UP)
GPIO.setup(24, GPIO.IN,pull_up_down=GPIO.PUD_UP)
display = drivers.Lcd()
pin_list = [random.... | StarcoderdataPython |
306446 | import asyncio
import getopt
import sys
from collections import namedtuple
from datetime import timedelta
from examples.cluster_hello_world.messages.protos_pb2 import DESCRIPTOR, HelloRequest
from protoactor.actor.actor_context import RootContext
from protoactor.remote.response import ResponseStatusCode
from protoacto... | StarcoderdataPython |
8145665 | # Copyright (c) 2020. <NAME>, <EMAIL>
import numpy as np
"""
================================================
=== Library for Point Cloud Utility Function ===
================================================
adapted from https://github.com/facebookresearch/hgnn/blob/master/utils/EarlyStoppingCriterion.py
Argu... | StarcoderdataPython |
1928682 | <filename>pyfda/pyfda_io_lib.py
# -*- coding: utf-8 -*-
#
# This file is part of the pyFDA project hosted at https://github.com/chipmuenk/pyfda
#
# Copyright © pyFDA Project Contributors
# Licensed under the terms of the MIT License
# (see file LICENSE in root directory for details)
"""
Library with classes and functi... | StarcoderdataPython |
1899883 | <gh_stars>1-10
#!/usr/bin/env python3
# Copyright (c) 2016-2018 The Bitcoin Core developers
# Copyright (c) 2010-2021 The Freicoin Developers
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of version 3 of the GNU Affero General Public License as published
# by the Free Sof... | StarcoderdataPython |
212422 | """The Xiaomi AirFryer component."""
# pylint: disable=import-error
import asyncio
import logging
from datetime import timedelta
from collections import defaultdict
from functools import partial
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.const import (
ATTR_ENT... | StarcoderdataPython |
6483086 | import logging
import json
from flask import Blueprint, request, make_response, jsonify
from flask.views import MethodView
from burgeon import bcrypt, db
from burgeon.models import User
log = logging.getLogger('burgeon.auth.registration')
class RegistrationAPI(MethodView):
"""
User Registration
"""
... | StarcoderdataPython |
8144880 | <reponame>sbienkow/eg
from eg import core
core.run_eg()
| StarcoderdataPython |
9643632 | <reponame>cmcguinness/flvoter2db
import os
import pymysql.cursors
import csv
class Registration:
"""
Load voter registration data into a table
"""
def __init__(self, connection, dbname):
"""
Initialize the class with
:param connection: a pymsql database connection
... | StarcoderdataPython |
5022078 | #! /usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import tensorflow as tf
import math
import numpy as np
# reference to PaddlePaddle paddle.optimizer.lr
__all__ = [
'LRScheduler', 'NoamDecay', 'PiecewiseDecay', 'NaturalExpDecay', 'InverseTimeDecay', 'Polynom... | StarcoderdataPython |
373345 | <reponame>ONLYA/blog_resources
print("-------- Deleting --------")
import sys
import os
if len(sys.argv) < 2:
print("Nothing to be deleted!")
sys.exit()
import cloudinary
cloudinary.config(
cloud_name = os.environ['CLOUD_NAME'],
api_key = os.environ['API_KEY'],
api_secret = os.environ['API_SECRET']
)
imp... | StarcoderdataPython |
11221705 | <gh_stars>10-100
from model import Stage2Model, FaceModel, SelectNet
from tensorboardX import SummaryWriter
from dataset import HelenDataset
from torchvision import transforms
from preprocess import ToPILImage, ToTensor, OrigPad, Resize
from torch.utils.data import DataLoader
from helper_funcs import calc_centroid, aff... | StarcoderdataPython |
4992937 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-03-30 21:53
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import podrobnosti.models
class Migration(migrations.Migration):
dependencies = [
('popisi', '0001_initial'),
... | StarcoderdataPython |
3385378 | <reponame>Joelpls/discord-bot
import discord
from discord.ext import commands
# A-Z Emojis for Discord
AZ_EMOJIS = [(b'\\U0001f1a'.replace(b'a', bytes(hex(224 + (6 + i))[2:], "utf-8"))).decode("unicode-escape") for i in
range(26)]
EMOJI_LETTERS = [
"\N{REGIONAL INDICATOR SYMBOL LETTER A}",
"\N{RE... | StarcoderdataPython |
9788764 | from rest_framework import permissions
import amika
from amika.models import *
class Permissoes(permissions.BasePermission):
def has_permission(self, request, view):
param = request.path.split('/')[1].title().lower()
if param in ['agenda-realizada', 'agendas-realizadas', 'agendas-realizadas-aluno... | StarcoderdataPython |
9744118 | from django import forms
from . import models
class UserSettingForm(forms.ModelForm):
"""Form to update UserSetting."""
class Meta:
model = models.UserSetting
fields = ['language']
| StarcoderdataPython |
26347 | from urllib.parse import urlencode
from ebrains_drive.files import SeafDir, SeafFile
from ebrains_drive.utils import raise_does_not_exist
class Repo(object):
"""
A seafile library
"""
def __init__(self, client, **kwargs):
self.client = client
allowed_keys = ['encrypted', 'group_name', ... | StarcoderdataPython |
8139851 | from Jumpscale import j
import hashlib
from datetime import datetime, timedelta
from tfchain.encoders import encoder_rivine_get, encoder_sia_get
from tfchain.crypto.utils import blake2_string
from tfchain.types.PrimitiveTypes import BinaryData, Hash
from tfchain.types.ConditionTypes import ConditionFactory, OutputLoc... | StarcoderdataPython |
3242127 | from typing import Union
import arcade
from arcade import View, Window, SpriteSolidColor
from arcade.gui import UILabel, UIElement, UIFlatButton
from arcade.gui.layouts import UILayout
from arcade.gui.layouts.box import UIBoxLayout
from arcade.gui.layouts.manager import UILayoutManager
from arcade.gui.layouts.utils im... | StarcoderdataPython |
11286519 | import time
start = time.time()
cipher_file = open('p059_cipher.txt', 'r')
cipher_text = cipher_file.read()
char_list = cipher_text.split(',')
def XOR(chars,key): # key = 'exp' aka [101,120,112]
result = []
for i in range(0,int(len(chars)/len(key))*len(key),len(key)):
for j in range(len(key)):
... | StarcoderdataPython |
3554833 | from pyramid.view import view_config
from chsdi.models.utilities import Files
@view_config(route_name='adminkml', renderer='chsdi:templates/adminkml.mako')
def admin_kml(request):
files = kml_load(request)
return {
'files': files,
'count': len(files),
'bucket': request.registry.settin... | StarcoderdataPython |
3522098 | #!/usr/bin/python3.7
# -*- coding: utf-8 -*-
# @Time : 2019/6/11 16:06
# @Author: <EMAIL>
from jtyoui.web import headers_ua
from jtyoui.error import LibraryNotInstallError
import requests
"""爬虫网站。请求Get和Post封装"""
def get(url, cookie=None):
"""Get网站"""
headers = headers_ua()
if cookie:
headers['co... | StarcoderdataPython |
1660415 | # Desafio 096 -> C. um programa que tenha uma função chamada área(), que receba as dimensões de um terreno
# retangular (largura e comprimento) e mostre a área do terreno
def área(a, b):
c = a * b
print(f'-' * 31)
print(f'A área de {a} x {b} é igual a {c}²')
print(f'-' * 31)
while T... | StarcoderdataPython |
4954505 | <reponame>shan18/Image-Captioning
from tensorflow.keras.models import load_model
from models.inception_v3 import load_inception_v3
def load_pre_trained_image_model(topic_weights_path):
print('Loading pre-trained image models...')
topic_model = load_model(topic_weights_path)
feature_model = load_inception... | StarcoderdataPython |
1838960 | <reponame>rdevans0/acgc_performance
"""
Modified from https://github.com/utsaslab/MONeT/blob/master/examples/imagenet.py
"""
import sys
import argparse
import json
import os
import random
import shutil
import time
import warnings
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn ... | StarcoderdataPython |
11239459 | # Generated by Django 3.1.1 on 2020-09-13 21:03
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Cat',
fields=[
... | StarcoderdataPython |
3392069 | <filename>Data Structures/Arrays and Linked List/linked_lists/linked_lists_intro_solution_05.py
def create_linked_list_better(input_list):
head = None
tail = None
for value in input_list:
if head is None:
head = Node(value)
tail = head # when we only have 1... | StarcoderdataPython |
9702744 | <reponame>YorBoyBlue/PomTracker_FastAPI<filename>pom_tracker/controllers/user.py<gh_stars>0
from fastapi import Request, Response, Depends, Form
from fastapi.responses import RedirectResponse
from fastapi.templating import Jinja2Templates
from sqlalchemy.orm import Session
from sqlalchemy.exc import IntegrityError
fro... | StarcoderdataPython |
1870714 | <filename>function/python/brightics/function/text_analytics/tfidf.py<gh_stars>0
import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
def tfidf(table, input_col, hold_cols=None, min_df=None, max_df=None, max_features=None, idf_weighting_scheme='unary',
... | StarcoderdataPython |
8022244 | #! /usr/bin/env python
import os
import subprocess
import sys
import time
from pulselib import *
MASTER_PORT = 7688
AGENT_PORT = 7689
def log(message):
print '%s: %s' % (time.strftime('%d %b %Y %H:%M:%S'), message)
def getRoot(programName):
path = os.path.split(programName)[0]
path = os.path.... | StarcoderdataPython |
5108402 | <gh_stars>1-10
# Open3D: www.open3d.org
# The MIT License (MIT)
# See license file or visit www.open3d.org for details
# examples/python/reconstruction_system/debug/pairwise_rgbd_alignment.py
import argparse
import json
import sys
import open3d as o3d
sys.path.append("../utility")
from file import *
from visualizatio... | StarcoderdataPython |
11278309 | import numpy as np
from scipy.sparse import coo_matrix
"""
Mutation matrices for reversible mutations, given spectrum dimension, u and v
"""
# three populations
def calc_FB_3pop(dims, u, v):
d = int(np.prod(dims))
d1, d2, d3 = dims
# arrays for the creation of the sparse (coo) matrices
data1 = []
... | StarcoderdataPython |
8063145 | #!/usr/bin/env python
# encoding: utf-8
import glob
import os
from zipfile import ZipFile
from datetime import date
DATASTORE = './data/'
PLOTDETAILSSTORE = './plot_details/'
ARCHIVESTORE = './archived_plot_data/'
CHARTSTORE = './output/'
def get_file_names(directory):
"""
Get the names of the completed csv... | StarcoderdataPython |
6515979 | <reponame>marv1913/lora_multihop
import time
import unittest
from unittest.mock import patch, MagicMock
from lora_multihop import serial_connection
__author__ = "<NAME>"
class SerialConnectionTest(unittest.TestCase):
def setUp(self) -> None:
self.ser = MagicMock()
serial_connection.ser = self.se... | StarcoderdataPython |
8173100 | #!/usr/bin/env python3
from unittest.mock import MagicMock, call
import aiounittest
from monitor.build_monitor import BuildMonitor
from monitor.gpio.constants import Lights
from monitor.service.aggregator_service import Result
class AsyncMock(MagicMock):
async def __call__(self, *args, **kwargs):
return ... | StarcoderdataPython |
84268 | from Statistics.mean import mean
from Statistics.samplestand import samplestand
from Calculator.subtraction import subtraction
from Calculator.division import division
def zscore(data):
x = 64
u = mean(data)
sample_sd = samplestand(data)
y = subtraction(x, u)
return division(sample_sd, ... | StarcoderdataPython |
3379566 | <reponame>Tismas/bigflow
from unittest import TestCase
class ExampleTestCase(TestCase):
def test_should_pass(self):
self.assertTrue(True) | StarcoderdataPython |
1791530 | <gh_stars>1-10
from app import db
"""
拆五笔赛文系统账号,用于将赛文同步到该系统上
"""
class ChaiWuBiUser(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), nullable=False)
password = db.Column(db.String(128), nullable=False) # 拆五笔要求明文。。
# 账号所有者(级联)
main_user_id = db.Column(d... | StarcoderdataPython |
287677 | '''Functions used to retrieve data by use of the API available from Vinmonopolet''' | StarcoderdataPython |
11397401 | import os
from os.path import join
import pandas as pd
import torch.utils.data as data
import datetime
from skimage.exposure import equalize_adapthist
import SimpleITK as sitk
from data_io.utils import merge_mip_stack
from common.file_io import load_nrrd
from data_io.my_transformer import CropPad
from data_io.data_aug... | StarcoderdataPython |
11355969 | <gh_stars>0
#!/usr/bin/env python3
"""This file contains the functions which are performed on a DC/OS bundle.
"""
import sys
import os
import re
import pandas
import d2yabt
def extract_diag(bundle_name):
"""Expand the DC/OS bundle into a directory.
"""
bundle_name = d2yabt.util.relocate_bundle(bundle_name)
bu... | StarcoderdataPython |
385467 | from scipy.misc import imread, imsave
img101 = imread('frames/saida_101.bmp')
img103 = imread('frames/saida_103.bmp')
img109 = imread('frames/saida_109.bmp')
img111 = imread('frames/saida_111.bmp')
img117 = imread('frames/saida_117.bmp')
img119 = imread('frames/saida_119.bmp')
imsave('inter_102.bmp', img101 / 2 + i... | StarcoderdataPython |
3480680 | def test_create_access_service(publisher_instance):
service = publisher_instance.services.create_access_service(1, 'service_endpoint')
assert service[0] == 'access'
assert service[1]['attributes'] == 1
assert service[1]['serviceEndpoint'] == 'service_endpoint'
| StarcoderdataPython |
11366877 | <gh_stars>0
# this is bad - figure out a better way
class Wrapper():
def __init__(self, face, connection, event, config, util):
self.face = face
self.connection = connection
self.event = event
self.config = config
self.util = util
| StarcoderdataPython |
1857931 | # IMPORT ORDER MATTERS!
# inherit from BaseConfig
from cumulusci.core.keychain.base_project_keychain import (
BaseProjectKeychain,
DEFAULT_CONNECTED_APP,
)
# inherit from BaseProjectKeychain
from cumulusci.core.keychain.BaseEncryptedProjectKeychain import (
BaseEncryptedProjectKeychain,
)
from cumulusci.c... | StarcoderdataPython |
8159454 | import demistomock as demisto
class TestParseWordDoc:
@staticmethod
def mock_results(mocker):
mocker.patch.object(demisto, "results")
@staticmethod
def mock_context(mocker, args_value=None):
if not args_value:
args_value = {
"entryID": "entry_id",
... | StarcoderdataPython |
12843879 | """
This is a nifty little tool to create really cool looking Readme files.
Its essentially a templating tool for such. The initial steps to create a template are the following:
- create a super cool ANSI Art design for your readme.
- create a template that uses this image and defines fields where text can be inserted.... | StarcoderdataPython |
6603198 | from setuptools import setup
import os.path
def require(*modules):
"""Check if the given modules are already available; if not add them to
the dependency list."""
deplist = []
for module in modules:
try:
__import__(module)
except ImportError:
deplist.append(modu... | StarcoderdataPython |
11363451 | from libra_client.canoser import Struct, Uint64
from libra_client.move_core_types.identifier import Identifier
from libra_client.move_core_types.account_address import AccountAddress
from libra_client.move_core_types.move_resource import MoveResource
from libra_client.lbrtypes.account_config.constants.libra import LIBR... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.