id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
8113280 | """
"""
import os
from astropy.table import Table
import numpy as np
from warnings import warn
from .halo_table_cache_log_entry import get_redshift_string
try:
import h5py
_HAS_H5PY = True
except ImportError:
_HAS_H5PY = False
warn("Most of the functionality of the "
"sim_manager sub-package r... | StarcoderdataPython |
8005635 | <reponame>tjlaboss/tasty_treat
"""core.py
Provides a container class for TREAT core lattice
"""
import common_files.treat.constants as c
from common_files.treat.corebuilder import TemplatedLattice
class Core(object):
################################################################################################... | StarcoderdataPython |
9704907 | <reponame>dfhssilva/railway_traffic
from gql import Client, gql
from gql.transport.requests import RequestsHTTPTransport
def run_query(query):
"""Run a GraphQL query against the rata.digitraffic.fi server."""
# Select your transport with a defined url endpoint
transport = RequestsHTTPTransport(
ur... | StarcoderdataPython |
3266341 | from hallo.events import EventMessage
def test_avg_simple(hallo_getter):
test_hallo = hallo_getter({"math"})
test_hallo.function_dispatcher.dispatch(
EventMessage(test_hallo.test_server, None, test_hallo.test_user, "average 2 4")
)
data = test_hallo.test_server.get_send_data(1, test_hallo.test... | StarcoderdataPython |
4854930 | <filename>player.py
import pyaudio
def play(audio_output, volume, rate, channels=1, format=pyaudio.paFloat32):
sound = pyaudio.PyAudio()
stream = sound.open(
format=format,
channels=channels,
rate=rate // channels,
output=True,
)
stream.write(volume * audio_output, num_... | StarcoderdataPython |
3281269 | # ----------------------------------------------------------------
# Copyright 2016 Cisco Systems
#
# 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/LICENS... | StarcoderdataPython |
6434088 | <filename>Solutions/6kyu/6kyu_counting_duplicates.py
duplicate_count = lambda t: sum(1 for i,j in __import__('collections').Counter(t.lower()).most_common() if j>1)
| StarcoderdataPython |
5040872 | #command-shif-p set interpreter to anaconda
import shapefile as shp #shp
import numpy as np
import matplotlib.pyplot as plt
import geopandas as gpd
from pyproj import Proj, transform
import os
def GetPointsFromShp(ShpFileLocation):
listx=[]
listy=[]
test = shp.Reader(ShpFileLocation)
for sr in test.... | StarcoderdataPython |
1699950 | <reponame>ffreemt/convbot<filename>convbot/__main__.py<gh_stars>0
"""Run main.
python -m convbot
"""
from convbot import convbot
def main():
print("Bot: Talk to me (type quit to exit)")
while 1:
text = input("You: ")
if text.lower().strip() in ["quit", "exit", "stop"]:
break
... | StarcoderdataPython |
6540400 | import operator
cmat = dict()
emat = dict()
PATH="/home/cfilt/154054002/parth/OS-NMT/System/data/RUNS/RNN+OS+ATTN/"
prediction_file = ["models/as-en/as-en_128_2_1e-3_200_preds.txt",
"models/bn-en/bn-en_128_2_1e-3_100_preds.txt",
"models/gu-en/gu-en_256_2_1e-3_300_preds.txt",
... | StarcoderdataPython |
11354618 | <filename>Algorithms/Python/bubble_sort.py<gh_stars>0
'''
Пузырьковая сортировка (Bubble Sort)
Сортировка пузырьком - это метод сортировки массивов и списков
путем последовательного сравнения и обмена соседних элементов,
если предшествующий оказывается больше последующего.
Сложность: O(n^2)
Преимущества: ... | StarcoderdataPython |
104693 |
import os
import urllib.request
import csv
import yaml
from flask import Flask, request, jsonify
import numpy as np
from package.preprocessing import read_data, preprocess
from package.model_utils import train_model
from package.app_util import json_to_row
app = Flask(__name__)
# read in configuration
with open('.... | StarcoderdataPython |
3501948 | <gh_stars>100-1000
#
# Copyright (C) 2020 IBM. All Rights Reserved.
#
# See LICENSE.txt file in the root directory
# of this source tree for licensing information.
#
import logging
import pathlib
import pickle
import sys
import re
import os
from sklearn.feature_extraction.text import TfidfVectorizer
_BASE_PATH = os.p... | StarcoderdataPython |
8171753 | import re
import mlflow
import mlflow.server
from .source import Source
from ..parsers import parse_datetime, epochs_summary_parser, insert_param, tag_parser
class HttpSource(Source):
def __init__(self, addresses, mlflow_url, pbar, timer, analysis, project_indicator):
mlflow.tracking.set_tracking_uri(ml... | StarcoderdataPython |
5086317 | <filename>src/client.py
from .config import APP_HASH, APP_ID
from pyrogram import Client
from .Colored import ColoredArgParser
from .args import args as Args
parser = ColoredArgParser()
for arg in Args:
parser.add_argument(
arg['short_name'],
arg['long_name'],
help=arg['help'],
type=... | StarcoderdataPython |
277286 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2018-04-17 19:51
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('d4s2_api', '0021_auto_20180416_1932'),
]
operations = [
migrations.AlterUniqueTogeth... | StarcoderdataPython |
1616017 | <reponame>duboviy/async
clients = []
host = ''
port = 8001
def chat_echo_server(socket, address):
clients.append(socket)
while True:
line = socket.recv(1024)
for client in clients:
try:
client.send(str(len(clients)) + '\r\n')
except:
clie... | StarcoderdataPython |
117426 | from yunionclient.common import base
class Dbinstanceaccount(base.ResourceBase):
pass
class DbinstanceaccountManager(base.StandaloneManager):
resource_class = Dbinstanceaccount
keyword = 'dbinstanceaccount'
keyword_plural = 'dbinstanceaccounts'
_columns = ["Id", "Name", "Dbinstance_Id", "Status",... | StarcoderdataPython |
6473173 | <reponame>the-zebulan/CodeWars
def divisible_by_four(num):
return not num % 4
| StarcoderdataPython |
1759891 | <filename>spacegraphcats/search/characterize_catlas_regions.py
#! /usr/bin/env python
"""
Choose catlas subtrees between no larger than --maxsize and no smaller
than --minsize in number of k-mers, and extract summary information on
abundances of kmers within the subtrees.
"""
import argparse
import os
import sys
import... | StarcoderdataPython |
9626095 | """The BangOlufsen Platform"""
DOMAIN="bangolufsen"
| StarcoderdataPython |
6429850 | import math
from itertools import product
import torch
from gym.spaces import Box, Discrete, Tuple
from sdriving.environments.spline_env import (
MultiAgentOneShotSplinePredictionEnvironment,
)
from sdriving.tsim import SplineModel, get_2d_rotation_matrix
class MultiAgentIntersectionSplineAccelerationDiscreteEn... | StarcoderdataPython |
6547286 | <filename>src/data_hub/tnris_org/migrations/0013_auto_20190807_1048.py
# Generated by Django 2.0.13 on 2019-08-07 15:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tnris_org', '0012_auto_20190807_1030'),
]
operations = [
migrations.... | StarcoderdataPython |
3260286 | <reponame>AndrewBiz/dotfiles<gh_stars>0
#!/usr/bin/python
import sys
cue_file = sys.argv[1]
d = open(cue_file).read().splitlines()
general = {}
tracks = []
current_file = None
for line in d:
if line.startswith('REM GENRE '):
general['genre'] = ' '.join(line.split(' ')[2:]).replace('"', '').strip()
... | StarcoderdataPython |
1821682 |
import setuptools
from setuptools import find_packages
setuptools.setup(
name='asknicely',
version='1.0',
author="<NAME>",
author_email="<EMAIL>",
description="Simple SDK for AskNicely",
url="https://github.com/luma-institute/python-asknicely",
packages=find_packages(exclude=['tes... | StarcoderdataPython |
8088479 | <gh_stars>0
"""
Downloading images via the Twitter API
for docs how to generate your own authentication file, see:
https://python-twitter.readthedocs.io/en/latest/getting_started.html
"""
from urllib.error import HTTPError
import twitter
import json
from os.path import join, isfile
from os import makedirs
from PIL... | StarcoderdataPython |
1796669 | <reponame>tamil-maker/probable_carnival
"""
Learn to click a button with Selenium
DISCLAIMER: This code is aimed at Selenium BEGINNERS
For more advanced tutorials and to learn how Qxf2 writes GUI automation, please visit our:
a) Our GUI automation guides: http://qxf2.com/gui-automation-diy
b) Other GitHub repos: https... | StarcoderdataPython |
6701386 | import datetime
from io import BytesIO
from django.conf import settings
from django.test import TestCase
from django.urls import reverse
from django.utils import timezone
from openpyxl import load_workbook
from wagtail.core.models import Page, PageLogEntry
from wagtail.tests.utils import WagtailTestUtils
class Tes... | StarcoderdataPython |
3496468 | <reponame>RadjaHachilif/agotool
### obsolete
# import os, datetime, sys
# import pandas as pd
# import numpy as np
#
# sys.path.insert(0, os.path.dirname(os.path.abspath(os.path.realpath(__file__))))
# import tools
# import variables
#
# TEST_DIR = variables.TEST_DIR
# TABLES_DIR = variables.TABLES_DIR
# LOG_DIRECTORY ... | StarcoderdataPython |
1799745 | <filename>SER.py
from asyncio.windows_events import NULL
from urllib.request import Request, urlopen
from urllib import response
import tensorflow
#import keras
from tensorflow import keras
import numpy as np
import librosa
import pyaudio
import wave
from array import array
import time
import matplotlib.pyplot as p... | StarcoderdataPython |
5132032 | <gh_stars>0
# Generated by Django 3.2.8 on 2021-10-17 14:11
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('z_gram', '0004_follow'),
]
operations = [
migrations.RenameModel(
old_name='Comment',
new_name='UserComment',
... | StarcoderdataPython |
9758386 | from detectron2.utils.visualizer import ColorMode
from detectron2 import model_zoo
from detectron2.modeling import build_model
from detectron2.engine import DefaultPredictor
from detectron2.config import get_cfg
from detectron2.utils.visualizer import Visualizer
from detectron2.data.datasets import register_coco_instan... | StarcoderdataPython |
8025753 | <gh_stars>1-10
"""
This module controls what appears on screen and allows you to record data the user
enters on the web page. A view is simply a function or class that takes a Web request
and returns a Web response.
Name: <NAME>
Date Completed: 7/31/2018
"""
from django.conf import settings
from django.core... | StarcoderdataPython |
5061319 | """Test files containging all the test cases for bnf grammar expansion."""
from unittest import TestCase
from swarms.lib.agent import Agent
from swarms.lib.model import Model
from swarms.lib.time import SimultaneousActivation
from swarms.lib.space import Grid
from swarms.behaviors.scbehaviors import (
CompositeDro... | StarcoderdataPython |
3535963 | <filename>Algorithms/Easy/506. Relative Ranks/answer.py<gh_stars>0
from typing import List
class Solution:
def findRelativeRanks(self, nums: List[int]) -> List[str]:
dict = {}
N = len(nums)
for i in range(N):
dict[nums[i]] = i
l = sorted(dict.items(), key=lambda x: x[0]... | StarcoderdataPython |
3252498 | n, m = map(int, input().split())
w = []
for i in range(1, n + 1):
x1, y1, x2, y2 = map(int, input().split())
w.append((x1, y1, x2, y2, i))
for _ in range(m):
x, y = map(int, input().split())
found = False
for i, s in reversed(list(enumerate(w))):
if x >= s[0] and x <= s[2] and y >= s[1] a... | StarcoderdataPython |
11298397 | <gh_stars>0
# -*- coding: utf-8 -*-
# This file is part of hoa-utils.
#
# hoa-utils is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
#... | StarcoderdataPython |
11398216 | from Model.jogador import *
from Model.orientacao import *
class ControleEncadeamento():
_encadeamento = None
_contador_incrementa_encadeamento = 0
_jogador = None
_tabuleiro = None
def __init__(self):
self._encadeamento = {Jogador.ADVERSARIO_1: [0,0,0,0,0], Jogador.ADVERSARIO_2: [0,0,0,0,0]}
def get_encadea... | StarcoderdataPython |
6458612 | class Rectangle:
def __init__(self, base: int, height: int) -> None:
self.base = base
self.height = height
def area(self):
return self.base * self.height
class Square(Rectangle):
def __init__(self, side: int) -> None:
super().__init__(side, side)
def main() -> None:
rectangle = Recta... | StarcoderdataPython |
331180 | import pytest
from django.urls import resolve, reverse
def test_reverse_report_list():
assert reverse("report-list") == "/api/reports/"
def test_resolve_report_detail():
assert (
resolve("/api/reports/a8986797-5664-4093-8905-9b12c17bc96f/").view_name
== "report-detail"
)
| StarcoderdataPython |
3598774 | import argparse
import glob
import os
import sys
import ass
def main():
parser = argparse.ArgumentParser(
description="Remove lines from .ass files that use specific styles"
)
parser.add_argument(
"--dir",
required=True,
dest="directory",
metavar="<directory>",
... | StarcoderdataPython |
5138367 | <filename>gaternet/utils.py
# coding=utf-8
# Copyright 2021 The Google Research 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
#
#... | StarcoderdataPython |
9673127 | import datetime
import json
import logging
from celery import current_app
class EventFormatter(logging.Formatter):
def format_timestamp(self, time):
return datetime.datetime.utcfromtimestamp(time).isoformat() + 'Z'
def levelname_to_importance(self, levelname):
if levelname == 'DEBUG':
... | StarcoderdataPython |
195380 | <filename>tools/spin-poster/loader.py
from arena import *
scene = Scene(host="arenaxr.org",realm="realm",scene="spin-poster")
rot=0
start_rot=0
sign_x=0
sign_y=0
sign_z=-10
@scene.run_once
def make_sign():
# Load a model with specific object_id that you will use for addressing later
# The url specifies the ... | StarcoderdataPython |
11302223 | <reponame>solocompt/plugs-newsletter
"""
Plugs Newsletter Models
"""
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from django.conf import settings
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth import get_... | StarcoderdataPython |
11322906 | # Copyright 2017 The Forseti Security 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 ap... | StarcoderdataPython |
5016830 | <reponame>Gsvend20/P4-Grise_Projekt
from Functions.Featurespace import Classifier
import numpy as np
import os
import pickle
# Init the classifier
c = Classifier()
# Load the trained data
c.get_classifier()
filename = input('Please enter the pkl file name\n')
parent = os.path.dirname(os.getcwd())
file_path = f'{par... | StarcoderdataPython |
3233620 | from django.core.exceptions import ValidationError
from core.tests.base_class import TestCasePlus
from ..validators import gotTextOutsideParens
class GotTextOutsideParensTests( TestCasePlus ):
#
''' test the gotTextOutsideParens() validator '''
#
def setUp(self):
self.s1 = 'abcde ... | StarcoderdataPython |
9623177 | <filename>graph_database.py
from typing import List, Dict, Any, Optional, Text
from py2neo import Graph,Node,data,Path, Relationship,NodeMatcher
from schema import schema,slot_neo4j_dict
class KnowledgeBase(object):
def get_entities(self,
entity_type:Text,
attributes:Opti... | StarcoderdataPython |
19538 | import json
import gen.Types
def loader(f):
return json.load(open('../GenerateDatas/json/' + f + ".json", 'r'), encoding="utf-8")
tables = gen.Types.Tables(loader)
print(tables)
r = tables.TbFullTypes.getDataList()[0].__dict__
print(r)
| StarcoderdataPython |
5152053 | <reponame>DavidMutchler/pyparrot
"""
Find the BLE address for a mambo. To run this,
sudo python findMambo.py
Note that the sudo is necessary for BLE permissions on linux. It is only needed on
this program and nothing else.
Author: <NAME>
"""
try:
from bluepy.btle import Scanner, DefaultDelegate
BLEAvailab... | StarcoderdataPython |
3540556 | <filename>databucket/databucket.py
"""Bucket source code.
"""
import os
import shutil
import warnings
from astropy.table import Table
# import numpy as np
import pandas as pd
from databucket import configure
from databucket import name
from databucket import xselect_handler
def _acquire_dirname(object_name: str):
... | StarcoderdataPython |
4853659 | # -*- coding: utf-8 -*-
"""
@Module SARibbonGlobal
@Author ROOT
"""
# ribbon的数字版本
SA_RIBBON_BAR_VERSION = 0.1
# ribbon 的文字版本
SA_RIBBON_BAR_VERSION_STR = '0.1'
"""
@def 属性,用于标记是否可以进行自定义,用于动态设置到@ref SARibbonCategory 和@ref SARibbonPannel
值为bool,在为true时,可以通过@ref SARibbonCustomizeWidget 改变这个SARibbonCategory和SARib... | StarcoderdataPython |
4841668 | <filename>jtr/stats/span_stats.py
import sys
import json
def read_data(data_filename):
with open(data_filename) as data_file:
data = json.load(data_file)
return data
def tree_stats(data):
span2counts = {}
for instance in data:
for question in instance['questions']:
supp... | StarcoderdataPython |
3312993 | <reponame>jamesbond007dj/py-data-structures-and-algorithms<gh_stars>0
class Node:
def __init__(self, value):
self.value = value
self.next = None
class Animal:
def __init__(self, type=None):
self.type = None
class Dog(Animal):
def __init__(self, type=None):
self.type... | StarcoderdataPython |
9742308 | import os
import numpy as np
import tensorflow as tf
class DataGenerator(tf.keras.utils.Sequence):
def __init__(self, data, path, batch_size=32):
self.data = data
self.path = path
self.batch_size = batch_size
def __len__(self):
return len(self.data) // self.batch_size
def... | StarcoderdataPython |
6401117 | <reponame>Kzra/CoreMS
import time
from numpy import where, average, std, isnan, inf, hstack, median, argmax, percentile
from corems import chunks
import warnings
#from matplotlib import pyplot
__author__ = "<NAME>"
__date__ = "Jun 27, 2019"
class NoiseThresholdCalc:
def get_noise_threshold(self) -> ( (float, fl... | StarcoderdataPython |
6632456 | <filename>lldb/test/API/tools/lldb-server/memory-tagging/TestGdbRemoteMemoryTagging.py
import gdbremote_testcase
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class TestGdbRemoteMemoryTagging(gdbremote_testcase.GdbRemoteTestCaseBase):
mydir = Tes... | StarcoderdataPython |
196369 | <gh_stars>10-100
# Python 3 program to find
# factorial of given number
#Author sspeedy
def factorial(n):
# single line to find factorial
return 1 if (n==1 or n==0) else n * factorial(n - 1);
# Driver Code
num = int(raw_input())
print factorial(num)
| StarcoderdataPython |
198067 | <reponame>nnyx7/plaso<filename>tests/parsers/mac_wifi.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for the Mac wifi.log parser."""
from __future__ import unicode_literals
import unittest
from plaso.formatters import mac_wifi as _ # pylint: disable=unused-import
from plaso.parsers import mac_wifi
from... | StarcoderdataPython |
103818 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Author : Joshua
@Time : 2020/6/30 6:09 下午
@File : get_spot_check_data_from_kafka.py
@Desc : 从kafka队列获取谛听标注数据
"""
import kafka_handler
import time
# kafka.
kafka_user = "recommend_online"
kafka_password = "<PASSWORD>=="
kakfa_servers = "moli-kafka.prd.<EMAI... | StarcoderdataPython |
1644241 | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import pulumi
import pulumi.runtime
from .. import utilities, tables
class Snapshot(pulumi.CustomResource):
"""
Creates a new ... | StarcoderdataPython |
6494576 | import pdb
import time
import urllib
import Utility
import configparser
from deep_translator import GoogleTranslator
def translate(src_lang, tgt_lang, list_text):
list_transed_text = list()
googleTranslator = GoogleTranslator(source=tgt_lang, target=src_lang)
time_except = 360
for text in list_text:
... | StarcoderdataPython |
6404967 | # -*- coding: cp1252 -*-
'''
Created on Jun 9, 2010
@author: coelho
'''
import re
from datetime import datetime
from dateutil.relativedelta import relativedelta
class TxtParser:
'''
Classe responsavel por realizar o parse do arquivo txt da fatura de cartoes
disponibilizada pelo banco do brasil.
Anal... | StarcoderdataPython |
117582 | <reponame>Rajarshi07/cktsim<filename>cktsim/sim/urls.py<gh_stars>0
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('allckts/', views.allckts, name='allckts'),
path('adder/hadd/', views.hadd, name='halfadder'),
path('adder/fadd/', views.fadd, nam... | StarcoderdataPython |
11335088 | """
Utilities for downloading and unpacking the CIFAR-10 dataset, originally published
by Krizhevsky et al. and hosted here: https://www.cs.toronto.edu/~kriz/cifar.html
"""
import os
import sys
import tarfile
from six.moves import urllib
import numpy as np
import pyfits as fits
def rebin_factor( a, newsha... | StarcoderdataPython |
4961892 | import os
import logging
from . import util
from . import default
from .package_stub import PackageStub
class CachedPackage(PackageStub):
def __init__(self, path):
meta = util.json_load(os.path.join(path, default.META_FILENAME))
super(CachedPackage, self).__init__(defaults=meta['package'])
... | StarcoderdataPython |
6434865 | # Copyright 2021 DeepMind Technologies Limited. 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 |
4936443 | import numpy as np
from scipy import signal, interpolate
from model_functions import GaussianSum
class experimental_pattern(object):
def __init__(self, filename, max_2theta=40.0, delimiter=''):
exp_pattern = np.genfromtxt(filename, delimiter=delimiter)
exp_pattern = exp_pattern[:,0:2]
# n... | StarcoderdataPython |
3783 | # -*- coding: utf-8 -*-
# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
from frappe.model.document import Document
from frappe.contacts.address_and_contact import load_address_and_contact
class Member(Docum... | StarcoderdataPython |
8083169 | import numpy as np
from scipy import stats
from sklearn.metrics import pairwise_distances
from sklearn.preprocessing import normalize
from .DATE import DATESampling
from .badge import init_centers
from utils import timer_func
class bATESampling(DATESampling):
""" bATE strategy: Our proposed model for better explo... | StarcoderdataPython |
4858892 | <reponame>Bruna-Fernandes/Python<filename>12_Granja.py<gh_stars>0
# 12_A granja Frangotech possui um controle automatizado de cada frango da sua
# produção. No pé direito do frango há um anel com um chip de identificação; no pé
# esquerdo são dois anéis para indicar o tipo de alimento que ele deve consumir.
# Sabendo q... | StarcoderdataPython |
1912025 | <gh_stars>0
import os
import torch
import transformers
class Settings:
PROJ_NAME = 'Entity-Extraction-Bert'
root_path = os.getcwd().split(PROJ_NAME)[0] + PROJ_NAME + "\\"
APPLICATION_PATH = root_path + "backend\\services\\entity_extraction\\application\\"
MAX_LEN = 128
TRAIN_BATCH_SIZE = 16
V... | StarcoderdataPython |
3357880 | <reponame>ProSeCo-Planning/proseco_planning<gh_stars>0
"""To be used in conjunction with stateAnalysis.cpp. This file generates plots of the respective action classes given a specific vehicular state."""
import plotly.express as px
import pandas as pd
import json
import tool as tl
from typing import Tuple, Dict
def ... | StarcoderdataPython |
9791792 | """Local test settings and globals which allows us to run our test suite
locally.
"""
import logging
from settings.base import * # noqa
logging.disable(logging.CRITICAL)
LOGGING_CONFIG = None
########## DEBUG
DEBUG = False
TEMPLATES[0]["OPTIONS"]["debug"] = DEBUG # noqa
SERVE_MEDIA = DEBUG
########## TEST
# T... | StarcoderdataPython |
5059450 | <gh_stars>0
"""Factories for reductions."""
import operator as op
import tensorflow as tf
import numpy as np
from .magik import tensor_compat
from .types import has_tensor, cast
from .shapes import size, shape
from .various import name_tensor
from ._math_for_indexing import sqrt
# --- FACTORY -----------------------... | StarcoderdataPython |
9766639 | import base64
import channels
import graphene
from django.contrib.auth.forms import AuthenticationForm
from django.core.files.base import ContentFile
from graphql_jwt.shortcuts import get_token
from serious_django_graphene import FormMutation, ValidationErrors
from server.tasks import reset_password_email
from asgire... | StarcoderdataPython |
1656064 | from urllib import request as http
import json
from flask import current_app, request
from werkzeug.urls import url_encode
from wtforms import ValidationError
from .._compat import to_bytes, to_unicode
HCAPTCHA_VERIFY_SERVER = 'https://hcaptcha.com/siteverify'
HCAPTCHA_ERROR_CODES = {
'missing-input-secret': 'T... | StarcoderdataPython |
5013138 | # This script uses the RPi Pico's Analog to Digital Converter to print & plot on board temperature data
# Electronics concepts used in the script
# Analog to Digital Converter
# An analogue-to-digital converter (ADC) measures some analogue signal and encodes it as a digital number
# The ADC on RP... | StarcoderdataPython |
1935699 | <reponame>RomanZakaliak/PyMosaic
"""
Binding web paths with views
"""
from config import STATIC_PATH
def setup_routes(app, handler):
router = app.router
router.add_get('/', handler.index, name='index')
router.add_post('/upload_file', handler.upload_file, name='upload_file')
router.add_get('/download/{... | StarcoderdataPython |
1796419 | # -*- coding: utf-8 -*-
# (c) YashDK [yash-dk@github]
from datetime import datetime,timedelta
def human_readable_bytes(value, digits= 2, delim= "", postfix=""):
"""Return a human-readable file size.
"""
if value is None:
return None
chosen_unit = "B"
for unit in ("KiB", "MiB", "GiB", "TiB"... | StarcoderdataPython |
3416358 | # Copyright (c) 2020-2021 by Fraunhofer Institute for Energy Economics
# and Energy System Technology (IEE), Kassel, and University of Kassel. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
import copy
import numpy as np
import pytest
import p... | StarcoderdataPython |
1652905 | ##
# tests for mktDataCoincp
# @author <NAME>
from tradingBot.src.mktDataModule.mktData import mktDataCoincp
from tradingBot.src.utils.exceptions import BadKwargs, SymbolNotSupported
from unittest import TestCase
from unittest.mock import patch
import sys
sys.path.insert(0, r'')
class TestmktDataBaseCoincp(TestCas... | StarcoderdataPython |
1992602 | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from... | StarcoderdataPython |
4832111 |
from glob import glob
import pandas as pd
import numpy as np
from datetime import datetime
import xml.etree.ElementTree as ET
import requests
# function strips white space from downloaded text file
def read_csv_regex(data, date_columns=[]):
df = pd.read_csv(data, sep="\t", quotechar='"', parse_dates=date_columns... | StarcoderdataPython |
9714022 | <gh_stars>0
# Copyright The PyTorch Lightning team.
#
# 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 |
11305655 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from django.contrib.auth.models import Group, User
username = os.environ["PROMORT_USER"]
password = os.environ["<PASSWORD>"]
user = User.objects.get_or_create(username=username)[0]
user.set_password(password)
user.save()
rois_manager_group = Group.objects.get(n... | StarcoderdataPython |
6547847 | <gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 22 19:58:03 2022
@author: aihub
"""
import os
os.system("sudo apt update;sudo snap install multipass")
os.system("multipass launch --name foo;multipass exec foo -- lsb_release -a;multipass launch -n bar --cloud-init cloud-config.yaml")
... | StarcoderdataPython |
4987803 | <reponame>jpnewman/elasticsearch-scripts
import sys
import elasticsearch
import elasticsearch.helpers
from utils.output import *
from utils.es_helpers import get_all_indices
def reindex_via_api(es, index_names, reindex_suffix, reindex_force_delete, elasticsearch_host):
"""Reindex Elasticsearch"""
header("Re... | StarcoderdataPython |
1649242 | <filename>Classifier/KNeighborsClassifier.py
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import f1_score, hamming_loss
from utils.utils import generate_stacking_csv
use_stacking = True
csv_file = r'D:\dataset\2021智慧農業數位分身... | StarcoderdataPython |
11243735 | import io
from PIL import Image
import numpy as np
import h5py
from keras.models import model_from_json
from glob import glob
def load_model(folder_path):
# load json and create model
json_file = open("{}/model.json".format(folder_path), 'r')
model_json = json_file.read()
json_file.close()
model =... | StarcoderdataPython |
399997 | <filename>commands/base_commands/guest.py
"""
Guest (OOC) commands. These are stored on the Player object
and self.caller is thus always a Player, not an Object/Character.
These commands will be used to implement a character creation
setup based on look and entered prompts.
To-Do list - have character creator prompt ... | StarcoderdataPython |
5085941 | from service.db import db
class Base(db.Model):
__abstract__ = True
id = db.Column(db.Integer(), primary_key=True, nullable=False, autoincrement=True)
date_created = db.Column(db.DateTime, default=db.func.current_timestamp())
date_modified = db.Column(db.DateTime, default=db.func.current_timestamp(),... | StarcoderdataPython |
6663685 | from sphero import request
from sphero.connection.exceptions import ConnectionLost
from sphero.connection import Connection
from sphero.response import parser
class Sphero(object):
def __init__(self, addr):
self._addr = addr
self._connection = Connection.connect(addr)
self._sequence = 0
... | StarcoderdataPython |
3491497 | <reponame>MartinSpiessl/benchexec<gh_stars>100-1000
# This file is part of BenchExec, a framework for reliable benchmarking:
# https://github.com/sosy-lab/benchexec
#
# SPDX-FileCopyrightText: 2007-2020 <NAME> <https://www.sosy-lab.org>
#
# SPDX-License-Identifier: Apache-2.0
import benchexec.tools.condtest as condtes... | StarcoderdataPython |
4816729 | <reponame>z3by/tweety-django-vue
from django import template
register = template.Library()
@register.filter(name="is_following")
def is_following(first_user, second_user):
return first_user.is_following(second_user)
@register.filter(name="is_liking")
def is_liking(user, tweet):
return tweet.is_liked(user)
... | StarcoderdataPython |
6553189 | <gh_stars>100-1000
from app.kernel import Kernel
from app.service_container import ServiceContainer
from app.plugin import Plugin
kernel = Kernel()
| StarcoderdataPython |
11273742 | from flatland.evaluators.client import FlatlandRemoteClient
from flatland.core.env_observation_builder import DummyObservationBuilder
# from my_observation_builder import CustomObservationBuilder
from src.graph_observations import GraphObsForRailEnv
from src.predictions import ShortestPathPredictorForRailEnv
import num... | StarcoderdataPython |
6435423 | <filename>utils/smmssqlutils.py<gh_stars>0
import sys
class smmssqlutils():
def __init__(self, **kwargs):
sys.dont_write_bytecode = True
import re
DBTYPES_RGX = re.compile(r'(?:sqlite3|mysql|mssql|oracle|postgre)', re.IGNORECASE)
DEFAULT_PORTS = {}
DEFAULT_PORTS['mssql'] =... | StarcoderdataPython |
3281147 | #!flask/bin/python
from functionalbc import app
#Do not add debug=True
#app.run(debug=True)
if __name__ == '__main__':
app.run()
| StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.