id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
337039 | # flake8: noqa E501
import dash_core_components as dcc
import dash_html_components as html
from flask_login import current_user
def navigation():
return html.Nav(
[
html.Button(
html.I(className="fa fa-bars"),
id="sidebarToggleTop",
className="b... | StarcoderdataPython |
3568506 | from flask import Flask
import json
import random
app = Flask(__name__)
with open('config.json', 'r', encoding='utf-8') as f:
json_data = json.load(f)
@app.route('/verify', methods=['POST'])
def summary():
random_id = ''.join([str(random.randint(0, 999)).zfill(3) for _ in range(2)])
... | StarcoderdataPython |
4809163 | <filename>aiida_phonopy/data/band_structure.py<gh_stars>0
from aiida.orm.nodes.data.array import ArrayData
# from aiida.orm import DataFactory
# ArrayData = DataFactory('array')
class BandStructureData(ArrayData):
"""
Store the band structure.
"""
def __init__(self, *args, **kwargs):
super(Ba... | StarcoderdataPython |
6516767 | <reponame>imnetdb/imnetdb
from ipaddress import ip_network
# from itertools import chain
def test_rpools_add_batch_idempotent(rpoolsdb):
pool = rpoolsdb.resource_pool('idaddbatch')
pool.reset()
pool.add_batch(ip_network('9.9.1.0/28').hosts(), rt_name='global')
pool.add_batch(ip_network('9.9.1.0/28')... | StarcoderdataPython |
3593663 | <filename>ltbot.py
#!/usr/bin/env python3
import src.main as ltbot
bot = ltbot.Ltbot()
bot.connect()
bot.send("Hello World!")
bot.loop()
| StarcoderdataPython |
9652089 | <gh_stars>1-10
import logging
import six
import smtplib
from cached_property import cached_property
from datetime import datetime
from email.mime.text import MIMEText
logger = logging.getLogger(__file__)
def get_email_server(host):
"""Return an SMTP server using the specified host.
Abandon attempts to conne... | StarcoderdataPython |
306775 | import requests
r = requests.get('https://pokeapi.co/api/v2/pokemon/ditto')
print(r.json()) | StarcoderdataPython |
11251213 | import json
from urllib.parse import urljoin
from zope.component import getMultiAdapter
from zope.schema import getFieldsInOrder
from bst.pygasus.core import ext
from bst.pygasus.scaffolding import interfaces
from bst.pygasus.wsgi.interfaces import IRequest
from bst.pygasus.core.interfaces import IBaseUrl
from bst.py... | StarcoderdataPython |
4915361 | <reponame>drmeerkat/IQN-and-Extensions<gh_stars>0
###########
# Authors:<NAME> 2021.04.06 -- set up the template wrappers and abstract FeatureVecWrapper class
#
# Authors: <NAME> 2021.04.06
# _get_feature_vec(), ship_x(),
# ship_laser_mid_air(), num_enemies(), lowest_enemy_height(), ufo_on_screen(),
# ufo_sign_distanc... | StarcoderdataPython |
6611882 | <reponame>lhuett/insights-core
from insights.tests import context_wrap
from insights.parsers.crypto_policies import CryptoPoliciesStateCurrent
from insights.parsers import SkipException
import pytest
CONFIG = """
DEFAULT
""".strip()
def test_crypto_policies_state_current():
result = CryptoPoliciesStateCurrent(co... | StarcoderdataPython |
6557864 | <gh_stars>10-100
class ejeShow():
def __init__(self, tablaActual, baseActual, conectar, ts , listaTablas):
self.conectar = conectar
self.ts = ts
self.tablaActual = tablaActual
self.baseActual = baseActual
self.listaTablas = listaTablas
def iniciarShow(self, instru):
... | StarcoderdataPython |
6652350 | <gh_stars>1-10
# NOTHING TO SEE HERE!
| StarcoderdataPython |
3318406 | import logging
logger = logging.getLogger(__name__)
import tarfile, os, fnmatch
from tarfile import TarError
import django_rq
from django.db import transaction
from thresher.models import UserProfile
from data.load_data import load_article_atomic, parse_batch_name
def import_archive(orig_filename, filename, owner_p... | StarcoderdataPython |
8016207 | <filename>urlshortener/assets.py<gh_stars>1-10
"""
Exports asset bundles to be used in the UI.
"""
from flask_assets import Bundle
bundles = {
'all_js': Bundle(
'**/*.js',
filters='jsmin',
output='build/bundle.min.js'
),
'all_css': Bundle(
'**/*.css',
filters='cssmi... | StarcoderdataPython |
5164318 | <reponame>troydai/Mali<gh_stars>0
from sqlalchemy import Column, String, Integer, ForeignKey
from sqlalchemy.engine import Engine
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
# pylint: disable=invalid-name, too-few-public-methods
Base = declarative_base()
class Pro... | StarcoderdataPython |
3457458 | from time import time
from pygerrit2.rest import GerritRestAPI
from requests.auth import HTTPDigestAuth
class GerritReview:
def __init__(self, change):
self.change = change
self.doc_id = None
def __getitem__(self, key):
if key == 'verify':
return 'approved' in self.change.get('labels', {}).get('Verified',... | StarcoderdataPython |
3326975 | <gh_stars>1-10
from splango import RequestExperimentManager
class ExperimentsMiddleware:
def process_request(self, request):
request.experiments = RequestExperimentManager(request)
return None
def process_response(self, request, response):
if getattr(request, "experiments", None):
... | StarcoderdataPython |
102992 |
# coding: utf-8
# In[15]:
import numpy as np
import Tkinter
import time
import sys
# In[16]:
class Board:
"""
rows: board size
board: a 8x8 matrix of colors
color: a value in [0,1,2]: none, black, white, respectively.
move: a array [row,col]
directions: a set of all nine unit vectors
o... | StarcoderdataPython |
3418749 | <gh_stars>0
from __future__ import unicode_literals
from app import MegaRestApp
from api import MegaRestAPI
print "Starting Arduino Mega REST API Server"
options = {
'bind': '%s:%s' % ('0.0.0.0', '8080'),
'workers': 1,
'timeout': 1000
}
MegaRestApp(MegaRestAPI(), options).run()
| StarcoderdataPython |
1725565 | <filename>2018/Day21.py
from Day19 import Device, make_command
script = """\
#ip 3
seti 123 0 1
bani 1 456 1
eqri 1 72 1
addr 1 3 3
seti 0 0 3
seti 0 0 1
bori 1 65536 2
seti 10605201 9 1
bani 2 255 5
addr 1 5 1
bani 1 16777215 1
muli 1 65899 1
bani 1 16777215 1
gtir 256 2 5
addr 5 3 3
addi 3 1 3
seti 27 3 3
seti 0 3 5... | StarcoderdataPython |
1904665 | # Generated by Django 3.1.5 on 2021-02-15 13:05
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('backend', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='income',
name='category',
),
]
| StarcoderdataPython |
5066055 | from __future__ import division
import itertools
from sympy.matrices.dense import zeros, MutableDenseMatrix
from BasisMatricesHelper import *
from MatricesHelper import *
import bisect
class DualSimplexMethod(object):
def __init__(self, A_matrix, b_matrix, c_matrix, d_lower, d_upper, eps=0.000001):
"""
... | StarcoderdataPython |
9704964 | <reponame>bihealth/varfish-cli<gh_stars>1-10
"""Code for accessing VarFish Server API."""
from .case import * # noqa: F403, F401
from .models import * # noqa: F403, F401
| StarcoderdataPython |
1999840 | import json
import os
import traceback
import numpy as np
import tensorflow as tf
import time
from azureml.core.model import Model
def load_graph(graph_path):
global graph
global input_operation
global output_operation
print("loading graph from", graph_path, time.strftime("%H:%M:%S"))
graph = tf.... | StarcoderdataPython |
1890102 | # Copyright (C) 2020 GreenWaves Technologies, SAS
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# This progr... | StarcoderdataPython |
6636242 | <reponame>samimoftheworld/google-appengine-wx-launcher
#!/usr/bin/env python
#
# Copyright 2008 Google 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/licen... | StarcoderdataPython |
9769781 | import argparse
import os
from habitat.config.default import get_config
from src.evaluators.habitat_evaluator import HabitatEvaluator
from src.constants.constants import NumericalMetrics
from src.utils import utils_logging, utils_visualization, utils_files
def main():
# parse input arguments
parser = argpar... | StarcoderdataPython |
3314937 | '''
Visualize sequences prepared by tools.prepare
Run after running main.py
'''
from tools import dataset
from tools.dataset import Dataset
from tools import prepare
import random
import os
import argparse
from glob import glob
import numpy as np
import cv2
import imageio
from tools import augmentation as augment... | StarcoderdataPython |
8071033 | import os
import shutil
def get_files(path):
filename_set = set()
filename_details = {}
for dirpath, dirnames, filenames in os.walk(path):
for fn in filenames:
if not fn in filename_set:
filename_set.add(fn)
filename_details[fn] = (dirpath, fn)
... | StarcoderdataPython |
3218627 | from mapa import Map
import math
import random
def find_corner(mapa):
for x in range(mapa.hor_tiles):
for y in range(mapa.ver_tiles):
if not mapa.is_blocked((x, y)):
return (x, y)
# para qualquer posicao retorna um lista de possoveis movimentos
def get_possible_ways2(mapa, pos... | StarcoderdataPython |
4969575 | <filename>ceilometer/tests/db.py
#
# Copyright 2012 New Dream Network, LLC (DreamHost)
# Copyright 2013 eNovance
#
# Author: <NAME> <<EMAIL>>
# <NAME> <<EMAIL>>
#
# 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
#... | StarcoderdataPython |
12861074 | <filename>model/modules/capsules.py
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from torch.distributions import Normal
def squash(s, dim=-1, eps=1e-8):
"""
"Squashing" non-linearity that shrunks short vectors to almost zero
length and long vectors to a le... | StarcoderdataPython |
3373878 | import pickle
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
def findBestCluster(clust: list) -> int:
return max(clust)
def cluster(data, ret_fn):
clustering = KMeans(n_clusters=5, random_state=5)
pickle.dump(clustering.fit(data), open(ret_fn, 'wb'))
return clustering | StarcoderdataPython |
6553692 | import os
from tensorflow.python import pywrap_tensorflow
checkpoint_path = "/home/niehaodong/tsn/out_sleepedf_nobn/train/19/best_ckpt/best_model.ckpt-27236.index"
# Read data from checkpoint file
reader = pywrap_tensorflow.NewCheckpointReader(checkpoint_path)
var_to_shape_map = reader.get_variable_to_shape_map(... | StarcoderdataPython |
370977 | from django.contrib import admin
from .models import Audio_store1
class AudioAdmin(admin.ModelAdmin):
list_display=('id','video','wpm','pauses','meanpitch','duration','pronunciation','balance','Spotwords','Sensitivewords','Fillerwords','freq')
# Register your models here.
admin.site.register(Audio_store1,A... | StarcoderdataPython |
1635284 | <reponame>MerintT/Deal-Prediction-Tool
import numpy as np
import pandas as pd
import pickle
#Loading the Pickle file of the classifier trained in Deal_forecaster.py
with open('model_pkl', 'rb') as f:
mp = pickle.load(f)
#Function to load data from Google sheets
def dataGS(gs,ws):
googleSheetId = gs
worksheetName =... | StarcoderdataPython |
296739 | # -*- coding:utf-8 -*-
import socket
# 创建套接字, TCP传输方式.
tcpserver = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# 绑定端口和IP。
tcpserver.bind(("",8882))
# 开启监听(设置套接字为被动模式)
# 设置tcpserver套接字为被动监听模式,不能再主动发送数据.
# 在windows系统 128 有效. 在linux上无效.
tcpserver.listen(128)
"""
等待客户端连接.accept 开始接受客户端连接,程序会默认进入阻塞状态(等待客户端连接),如果由客户端连... | StarcoderdataPython |
1733217 | <gh_stars>0
from PyQt4 import QtCore, QtGui
class SqChatWidget(QtGui.QWidget):
def __init__(self, parent=None):
super(SqChatWidget, self).__init__(parent)
self.sendBtn = QtGui.QPushButton('Send', self)
self.sendBtn.resize(self.sendBtn.sizeHint())
self.settingsBtn = QtGui.QPushButt... | StarcoderdataPython |
3467121 | <reponame>bsudy/markdown-to-confluence
from dataclasses import dataclass
from enum import Enum
import os
from typing import Optional
INVALID_CHARS = [' ', '!' , '#', '&', '(', ')', '*', ',', '.', ':', ';', '<', '>', '?', '@', '[', ']', '^']
class ArticleState(Enum):
TO_BE_SYNCED = 'to_be_synced'
CREATED = 'cr... | StarcoderdataPython |
178330 | <filename>utils/optimizers.py<gh_stars>1-10
import tensorflow as tf
import tensorflow_addons as tfa
def get_optimizer(CFG):
opt_name = CFG.optimizer
lr = CFG.lr
if opt_name=='Adam':
opt = tf.keras.optimizers.Adam(learning_rate=lr)
elif opt_name=='AdamW':
opt = tfa.optimizers.AdamW... | StarcoderdataPython |
11210935 | <filename>wafw00f/plugins/fortiweb.py
#!/usr/bin/env python
'''
Copyright (C) 2019, WAFW00F Developers.
See the LICENSE file for copying permission.
'''
NAME = 'FortiWeb (Fortinet)'
def is_waf(self):
schema1 = [
self.matchCookie(r'^FORTIWAFSID='),
self.matchContent('.fgd_icon')
]
schema2 ... | StarcoderdataPython |
6703585 | from django.db import models
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db.models.signals import post_save, post_delete
ALLOW_ALL, REQUIRE_LOGIN, DISALLOW_ALL = range(3)
SUBSITE_POST_STATUS = (
(ALLOW_ALL, 'Allow All Posts'),
(REQUIRE_LOGIN, 'Require Lo... | StarcoderdataPython |
1910994 | <gh_stars>10-100
name = "pysolarmanv5"
| StarcoderdataPython |
12804231 | #!/usr/bin/env python
import math
import numpy as np
import signal
import scipy.ndimage as ndimage
import pdb
"""
This file contains scripts to filter ALOS data.
"""
def enhanced_lee_filter(img, window_size = 5, n_looks = 16):
'''
Filters a masked array with the enhanced lee filter.
Based on formulatio... | StarcoderdataPython |
6576434 | import numpy as np
import pandas as pd
from scipy.optimize import minimize
class Calibrator():
def __init__(self, method):
self.method = method
def swapRates(t, p, matrix):
tmax = matrix[-1]
ttemp = np.arange(0.5, tmax + 0.5, 0.5)
ptemp = np.interp(ttemp, t, p)
di... | StarcoderdataPython |
5106240 | <filename>backend/src/base/serializers.py
from io import BytesIO
import json
import requests
from rest_framework import serializers
from src.base.models import Setting
class SettingSerializer(serializers.ModelSerializer):
class Meta:
model = Setting
fields = '__all__'
def to_representation(sel... | StarcoderdataPython |
1755787 | <reponame>hobbitsyfeet/3DMeasure
import math
import ctypes
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
class Bone():
def __init__(self):
#type (Name) of bone: String
self.bone_type = None
#3D model definitions of outer bounding box: F... | StarcoderdataPython |
6643193 | <filename>src/evaluation/fscore_evaluator.py
"""
This script evaluates the results of SUM-GAN-AAE, SUM-GAN-sl, and CSNET using F1-score metric
"""
import numpy as np
import os.path as osp
from os import listdir
import json
import argparse
import h5py
from summary_loader import load_processed_dataset
from summary_genera... | StarcoderdataPython |
9635310 | <filename>omnibus/omnibus_test.py
import io
import multiprocessing as mp
import sys
import time
import pytest
from omnibus import Sender, Receiver, Message, server
from omnibus.omnibus import OmnibusCommunicator
class TestOmnibus:
@pytest.fixture(autouse=True, scope="class")
def server(self):
# star... | StarcoderdataPython |
5041718 | import tempfile
import unittest
from rendermd.toc import TocGenerator
class TocTest(unittest.TestCase):
def test_toc_generator(self) -> None:
g = TocGenerator()
with tempfile.NamedTemporaryFile() as fp:
original_content = f"""
{g.block_start}
{g.block_end}
# h1
## h2
"""
... | StarcoderdataPython |
8107971 | # Run using:
# casapy --nologger --nogui --log2term -c ms_to_mat <MS name>
import os
import sys
import scipy.io
import collections
# Get MS name from command line.
ms_path = os.path.abspath(sys.argv[-1])
if not os.path.isdir(ms_path):
raise ValueError('Specified measurement set not found!.')
print '=' * 80
prin... | StarcoderdataPython |
8083921 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2017, 2018 <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 r... | StarcoderdataPython |
8153253 | from django.contrib import admin
from api_basic.models import ArticleModel1
# Register your models here.
admin.site.register(ArticleModel1)
| StarcoderdataPython |
3550706 | import collections
import shutil
import tempfile
import itertools
import unittest
import unittest.mock
from kilda.traffexam import model
from kilda.traffexam import context as context_module
from kilda.traffexam import service as service_module
from kilda.traffexam import system
IpIfaceStub = collections.namedtuple('... | StarcoderdataPython |
8036263 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
from .models import Location, Category, Image
# Create your tests here.
class LocationTestClass(TestCase):
'''
Tests Location class and its functions and methods
'''
#Set up method
def setUp(self):
... | StarcoderdataPython |
4911632 | import re
import csv
import json
import sqlite3
try:
import mojimoji
except ImportError:
import sys
print("Building the json requires mojimoji for character conversion. Run this to install it:")
print()
print(" pip install mojimoji")
sys.exit(1)
# original data README:
# https://www.post.ja... | StarcoderdataPython |
8012085 | <filename>heimdall/users/migrations/0010_product_slug.py
# Generated by Django 3.2.12 on 2022-05-19 09:30
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0009_productkeyword_is_removed'),
]
operations = [
migrations.AddField(
... | StarcoderdataPython |
12804320 | from __future__ import annotations
from typing import Optional, List
import pandas as pd
from whyqd.base import BaseMorphAction
class Action(BaseMorphAction):
"""Rename all header column labels.
Script::
"RENAME_ALL > ['column_name', 'column_name', etc.]"
Where `column_name` is a new `string` ... | StarcoderdataPython |
4918063 | <filename>export.py
import trimesh as trimesh
from recordings import Recording, SingleRecordingDataset
import numpy as np
recording = Recording.from_dir("E:/carla/town03/cloudy/noon/cars_40_peds_200_index_0")
def get_spherical_export(data: SingleRecordingDataset, outfile, frame: int = 200):
fx, cx, fy, cy = np.l... | StarcoderdataPython |
17278 | import numpy as np
import numpy.testing as npt
import slippy
import slippy.core as core
"""
If you add a material you need to add the properties that it will be tested with to the material_parameters dict,
the key should be the name of the class (what ever it is declared as after the class key word).
The value should ... | StarcoderdataPython |
5153474 | from segtypes.n64.img import N64SegImg
import png
from util import iter
from util.color import unpack_color
# TODO: move common behaviour to N64ImgSegment and have all image segments extend that instead
class N64SegRgba16(N64SegImg):
def split(self, rom_bytes):
path = self.out_path()
path.parent.mk... | StarcoderdataPython |
1805456 | # Copyright 2014 Facebook, Inc.
# You are hereby granted a non-exclusive, worldwide, royalty-free license to
# use, copy, modify, and distribute this software in source code or binary
# form for use in connection with the web services and APIs provided by
# Facebook.
# As with any software that integrates with the Fa... | StarcoderdataPython |
11215437 | """
Signal Processing
~~~~~~~~~~~~~~~~~
Common signal processing functions, which often handle multiple dimension
"""
import numpy_force as numpy
from . import array_create
from . import bhary
from . import ufuncs
from . import linalg
from . import summations
from . import numpy_backport
from . import _bh
# 1d
# --... | StarcoderdataPython |
3408221 | # -*- coding: utf-8 -*-
"""
Ephemeris calculations using SunPy coordinate frames
"""
import datetime
import warnings
import numpy as np
import astropy.units as u
from astropy.time import Time
from astropy.coordinates import (SkyCoord, Angle, Longitude,
ICRS, PrecessedGeocentric, AltAz,... | StarcoderdataPython |
5039367 | <filename>mayday/objects/user.py
from telegram import User as TelegramUser
class User:
'''Convert Telegram User Dict to User Object'''
def __init__(self, user_profile: dict = None, telegram_user: TelegramUser = None) -> None:
if telegram_user:
self._user_id = telegram_user.id
... | StarcoderdataPython |
3400661 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import hashlib
import hmac
import sys
import requests
import json
#curl -X POST -H "Content-Type: application/json" -d '{
#"message": {
#"channel_uuid": "XXX",
#"service_uuid": "a5273c4b-1d39-4594-ae59-0748b317da2a",
#"user_uuid": "USER_UUID",
#"type": "te... | StarcoderdataPython |
9696979 | <gh_stars>10-100
# -*- coding: utf-8 -*-
"""Handy.Keypad()."""
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('Handy', '1')
from gi.repository import Gtk, Gio, Pango
from gi.repository import Handy
class MainWindow(Gtk.ApplicationWindow):
def __init__(self, **kwargs):
super().__init__(*... | StarcoderdataPython |
1676048 | from apps.dailytrans.builders.amis import Api as WholeSaleApi
from apps.dailytrans.builders.utils import (
director,
date_generator,
DirectData,
)
from .models import Flower
MODELS = [Flower]
# This api only provide one day filter
WHOLESALE_DELTA_DAYS = 1
LOGGER_TYPE_CODE = 'LOT-flowers'
@director
def ... | StarcoderdataPython |
9677323 | <reponame>nicolasanjoran/omnizart<gh_stars>1000+
# pylint: disable=W0102,W0221
import tensorflow as tf
from tensorflow.python.framework import ops
from omnizart.models.t2t import positional_encoding, MultiHeadAttention
from omnizart.models.utils import shape_list
class FeedForward(tf.keras.layers.Layer):
"""Feed... | StarcoderdataPython |
6630296 | <gh_stars>0
# Copyright 2021 The KubeEdge Authors.
#
# 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 ... | StarcoderdataPython |
62175 | <filename>reports/migrations/0001_initial.py
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-07-10 15:25
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
... | StarcoderdataPython |
319197 | <filename>fdk_client/platform/models/EventSubscription.py
"""Platform Models."""
from marshmallow import fields, Schema
from marshmallow.validate import OneOf
from ..enums import *
from ..models.BaseSchema import BaseSchema
from .EventSubscriptionTemplate import EventSubscriptionTemplate
class Event... | StarcoderdataPython |
6506102 | <reponame>daboross/screeps-ai-v2<filename>src/empire/targets.py
from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union, cast
from creep_management import spawning
from directories import target_functions
from jstools.screeps import *
from position_management import locations
if TYPE_CHECKING:
from cre... | StarcoderdataPython |
4844305 | from . import Model, CollectionModel
class Template(Model):
"""
A Template object model (Message Template)
.. attribute:: id
.. attribute:: name
.. attribute:: content
.. attribute:: lastModified
"""
class Templates(CollectionModel):
name = "templates"
form = "template"
... | StarcoderdataPython |
1826290 | <gh_stars>1-10
import argparse
import logging
import sys
import pkg_resources
from . import packager
lgr = logging.getLogger()
def ver_check():
version = None
version = pkg_resources.get_distribution('cloudify-agent-packager').version
return version
def _run(args):
packager.set_global_verbosity_... | StarcoderdataPython |
6583733 | <reponame>Unacademy/kubernetes-py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is subject to the terms and conditions defined in
# file 'LICENSE.md', which is part of this source code package.
#
from kubernetes_py.models.v1.ContainerStatus import ContainerStatus
from kubernetes_py.models.v1.PodConditio... | StarcoderdataPython |
163118 | from django.contrib.auth.decorators import permission_required
from django.urls import path, include
from . import views
app_name = 'staffing'
department = [
path('', views.DepartmentList.as_view(), name='list'),
path('create/', permission_required('is_superuser')(views.DepartmentCreate.as_view()), name='cr... | StarcoderdataPython |
11270350 | import torch
from .torch_util import Module
class Normalizer(Module):
def __init__(self, dim, epsilon=1e-6):
super().__init__()
self.dim = dim
self.epsilon = epsilon
self.register_buffer('mean', torch.zeros(dim))
self.register_buffer('std', torch.zeros(dim))
def fit(s... | StarcoderdataPython |
6675183 | <filename>pychess/board/standard/standard_board.py
# <NAME>
# <EMAIL>
#
from pychess.board import board
from pychess.pieces import King, Queen, Rook, Bishop, Knight, Pawn, PieceColor
class StandardBoard(board.Board):
def __init__(self):
board.Board.__init__(self)
self.pieces = {(4, 0): King(self... | StarcoderdataPython |
6698338 | <filename>Python_code/C.py
# Minimum cost of addition
import heapq
def minimum_cost(numbers: list) -> int:
heapq.heapify(numbers)
heap_length = len(numbers)
total_cost = 0
while heap_length > 1:
cost = heapq.heappop(numbers) + heapq.heappop(numbers)
total_cost += cost
heapq.hea... | StarcoderdataPython |
8163778 | <reponame>baduy9x/AlgorithmPractice<gh_stars>0
# Python3 program to print all paths of
# source to destination in given graph
from typing import List
from collections import deque
# Utility function for printing
# the found path in graph
def printpath(path: List[int]) -> None:
size = len(path)
for i in ... | StarcoderdataPython |
8150851 | # pylint:disable=unused-import
"""Constants for Sample Similarity display module."""
from app.analysis_results.constants import SAMPLE_SIMILARITY_NAME as MODULE_NAME
| StarcoderdataPython |
3417104 | #!/usr/bin/python3
#
# Copyright (c) 2016-2020 The Khronos Group Inc.
#
# SPDX-License-Identifier: Apache-2.0
# insertTags.py - insert // refBegin and // refEnd tags in Vulkan
# spec source files.
#
# Usage: insertTags.py output-dir files
# Short descriptions of ref pages, if not found
from refDesc import *
# Utilit... | StarcoderdataPython |
11221786 | <reponame>Daisy-Zhang/General_Image_Classification_Pytorch
import os
import sys
import numpy
import torch
import torchvision.transforms as transforms
import torchvision.datasets as datasets
from torch.utils.data import DataLoader
from torch.utils.data import Dataset
import conf
from utils import image_preprocess
de... | StarcoderdataPython |
9720467 | module_array = [ ]
try:
import sqlite3
except ImportError:
module_array.append("sqllite3")
print("Module SQLITE3 not available.")
try:
from ncclient import manager
except ImportError:
module_array.append("ncclient")
print("Module NCC Client not available.")
try:
import ncclient... | StarcoderdataPython |
9749463 | <filename>Machine_Learning/sklearn_trading_bot.py
from sklearn.ensemble import IsolationForest
class IsolationModel:
"""
Simple Isolation Model based on contamination
"""
def __init__(self, data):
self.normalized_data = (data - data.mean()) / data.std()
self.iso = IsolationForest(co... | StarcoderdataPython |
9663427 | import pymysql
# 连接数据库
db = pymysql.connect("localhost", "root", "lyc12030017",
"CarApp", charset='utf8')
print("数据库已连接")
# 获取操作游标
cursor = db.cursor()
# 插入Car
car_ids = ['京A88888', '皖CTJ876', '皖A92141']
usernames = ['张红', '黎明', '小二']
phones = ['14265786411', '15467898765', '10387653456']
addrs =... | StarcoderdataPython |
1879927 | <reponame>Yanis17971/Project_zero<gh_stars>1-10
from django.apps import AppConfig
class IcecreamConfig(AppConfig):
name = 'icecream'
| StarcoderdataPython |
5017330 | from Bio import SeqIO
from Bio.Alphabet import generic_dna, generic_protein, DNAAlphabet,\
ProteinAlphabet
from Bio.SeqRecord import SeqRecord
from Bio.Seq import Seq
from Bio.Data import CodonTable
from FluGibson import utils
class NucleotideProteinConverter(object):
"""
A class that performs converts on... | StarcoderdataPython |
12803842 | <filename>pyocd/target/builtin/target_CY8C6xx7.py
# pyOCD debugger
# Copyright (c) 2006-2013 Arm Limited
# SPDX-License-Identifier: Apache-2.0
#
# 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
... | StarcoderdataPython |
3223294 | # Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... | StarcoderdataPython |
8029619 | import ast
import os
import pickle
import zipfile
import korbinian
import numpy as np
import pandas as pd
from korbinian import utils as utils
from multiprocessing import Pool
import sys
# import debugging tools
from korbinian.utils import pr, pc, pn, aaa
def run_slice_TMDs_from_homologues(pathdict, s, logging):
"... | StarcoderdataPython |
3250831 | import glob
import unittest
from unittest.mock import patch
from ancient_invasion import *
class MyTestCase(unittest.TestCase):
################################################################################################################
# Tests for user input to ensure that the game does not crash when th... | StarcoderdataPython |
4945952 | <gh_stars>1-10
ENTRY_POINT = "any_int"
# [PROMPT]
def any_int(x, y, z):
"""
Create a function that takes 3 numbers.
Returns true if one of the numbers is equal to the sum of the other two, and all numbers are integers.
Returns false in any other cases.
Examples
any_int(5, 2, 7) ➞ True
an... | StarcoderdataPython |
6705743 | import os
def format_frame_number(frame_number: int):
return '{:0>6}'.format(frame_number)
def get_bounding_boxes(detections_path: str, video_name: str, frame_number: int):
frame_number_formatted = format_frame_number(frame_number)
detections_file_path = os.path.join(detections_path, f'{video_name}_{frame... | StarcoderdataPython |
9654761 | # -*- coding: utf-8 -*-
"""
textGenerator.py
create (generate) numerical annotated data
<NAME>
copyright Xerox 2017
READ project
Developed for the EU project READ. The READ project has received funding
from the European Union's Horizon 2020 research and innovation p... | StarcoderdataPython |
1718268 | <reponame>katosh/multi_bary_plot
from .GenBary import GenBary
__all__ = ['GenBary', ]
| StarcoderdataPython |
4897425 | from tensorflow import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from tensorflow.keras.layers import BatchNormalization
from tensorflow.keras.utils import to_categorical
from keras.callbacks import Callback
import argparse
f... | StarcoderdataPython |
243044 | <filename>homepage/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('users/', views.users_list_view, name='users-list'),
]
| StarcoderdataPython |
1621469 | __all__ = ('WrapperBase', )
from ..helpers import hash_object
from scarletio import RichAttributeErrorBaseType, include
WrapperChainer = include('WrapperChainer')
class WrapperBase(RichAttributeErrorBaseType):
"""
Base class for test wrappers defining shared functionality.
Attributes
--------... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.