id
stringlengths
1
265
text
stringlengths
6
5.19M
dataset_id
stringclasses
7 values
3248053
<filename>train.py """ Train the MobileNet V2 model """ import os import sys import argparse import pandas as pd from mobilenet_v2 import MobileNetv2 from keras.optimizers import Adam from keras.preprocessing.image import ImageDataGenerator from keras.callbacks import EarlyStopping, ReduceLROnPlateau, ModelCheckpoint...
StarcoderdataPython
1787272
<reponame>Renovamen/tinyark<filename>flint/nn/modules/pooling.py<gh_stars>10-100 from typing import Optional from flint import Tensor from .. import functional as F from ..types import _size_1_t, _size_2_t, _tuple_any_t from .utils import _single, _pair from .module import Module class _MaxPoolNd(Module): """ ...
StarcoderdataPython
84440
import struct import ctypes import json maxBoosts = 50 maxCars = 10 class Vector3(ctypes.Structure): _fields_ = [("X", ctypes.c_float), ("Y", ctypes.c_float), ("Z", ctypes.c_float)] class Rotator(ctypes.Structure): _fields_ = [("Pitch", ctypes.c_int), ("Y...
StarcoderdataPython
147063
""" @author: Alfons @contact: <EMAIL> @file: 15-03-for.py @time: 18-7-1 下午10:48 @version: v1.0 """ for i in range(10): print("Hello, I'm little {i}.".format(i=i)) else: print("I'm else.") # 执行完for循环后运行
StarcoderdataPython
1635352
from django.template import loader from django.shortcuts import render,get_object_or_404 from django.urls import reverse from django.views import generic from django.http import HttpResponse import json from .models import * # Create your views here (except API views go in api.py) def index(request): a = [] ...
StarcoderdataPython
3323689
<filename>src/visitpy/visit_flow/visit_flow_vpe/tests/test_flow_vpe.py # Copyright (c) Lawrence Livermore National Security, LLC and other VisIt # Project developers. See the top-level LICENSE file for dates and other # details. No copyright assignment is required to contribute to VisIt. """ file: test_flow_vpe_npy...
StarcoderdataPython
3205852
<gh_stars>100-1000 """Vocabulary class module. This module implements the Vocabulary class and the helper functions that can be used to obtain a Vocabulary instance. """ import collections import json import os from typing import List, Set, Union import numpy as np import tensorflow as tf from typeguard import chec...
StarcoderdataPython
130732
<gh_stars>1-10 import datetime import hashlib import json import os import subprocess import sys import tempfile import urllib from typing import Dict, List, Optional from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.urls import reverse from django.utils import timezone...
StarcoderdataPython
3333376
__author__ = 'ziyan.yin' import asyncio import logging from urllib import parse TIMEOUT = 1000 HOST = '0.0.0.0' PORT = 11212 WHITE_LIST = None AUTH = None logger = logging.getLogger('proxy') def get_addr(uri): if ':' in uri: host = uri[:uri.rfind(':')] port = int(uri[uri.rfind(':') + 1:]) e...
StarcoderdataPython
4833799
<filename>src/Seventh Chapter/Exercise5.py # Sum all the elements in a list up to but not including the first even number. # (Write your unit tests. What if there is no even number?) def sum_up_to_even(list): evenssum = 0 for i in (list): if i % 2 == 0: break else: evenssum ...
StarcoderdataPython
160769
print(divmod(100, 7)) print(7 > 2 and 1 > 6) print(7 > 2 or 1 > 6) number_list = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] print(number_list[2:8]) print(number_list[0:9:3]) print(number_list[0:10:3])
StarcoderdataPython
165995
<gh_stars>0 from flask_restplus import Namespace, Resource, fields from restApi.models.users import User from restApi.helpers.user_helper import UserParser from restApi.helpers.login_helper import LoginParser import jwt from instance.config import Config from werkzeug.security import check_password_hash, generate_passw...
StarcoderdataPython
1725793
<reponame>abdulfaqihalm/finalProject import pydicom import os import numpy as np from skimage.morphology import disk, binary_dilation from cyvlfeat.fisher import fisher from sklearn.linear_model import LogisticRegression from numba import cuda import pickle class Classifier: def __init__(self, fileData, rawDataP...
StarcoderdataPython
3382412
<filename>radio/base.py import busio from digitalio import DigitalInOut, Direction, Pull import board import adafruit_rfm9x import RPi.GPIO as GPIO import logging import datetime def main(): # init logging logging.basicConfig(filename="logs/base.log", level=logging.DEBUG) # init LoRa CS = DigitalInOut...
StarcoderdataPython
129632
import pandas as pd import numpy as np from os import path #Read File of all the unique userids of the bots that tweeted messages regarding to the 2016 elections. dfn = pd.read_csv("/root/.encrypted/.pythonSai/kCoreBots/CoreBotEN/MachineLearning/NaiveBayes/ListIDS.csv", sep="\n", skiprows=[0], header=None, usecols=[0]...
StarcoderdataPython
3335126
<filename>nads/data/__init__.py<gh_stars>0 from .direction import create_rfft2_direction from .dataset import DirectionalLinearDataset
StarcoderdataPython
78896
<filename>Code/MQTT_thing_broker_112/src/ButtonResource.py<gh_stars>0 #!/usr/bin/env python3 ''' ___ ___ ___ ___ /\__\ /\ \ /\ \ /\ \ /::| | /::\ \ /::\ \ \:\ \ /:|:| | /:/\:\ \ /:/\ \...
StarcoderdataPython
3366752
<filename>experiments/kdf_digest_validation.py<gh_stars>0 import time import binascii import argon2 # pip install argon2-cffi from sbk import kdf VERIFY = 0 if VERIFY: DIGEST_LEN = 1024 # for comparison with sbk else: DIGEST_LEN = 32 # for comparison with https://antelle.net/argon2-browser/ def digest(...
StarcoderdataPython
142885
# Copyright 2019 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 applica...
StarcoderdataPython
63455
# Copyright 2017 DataCentred Ltd # # 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 ag...
StarcoderdataPython
1732948
<reponame>mahnve/sinor<filename>test/test_html_content.py<gh_stars>0 from sinor import html_content from nose.tools import assert_equals from data_builder import HTMLContentBuilder def test_parse_empty_string(): html = HTMLContentBuilder().build() assert_equals(html_content.from_string(html), {'title': '', ...
StarcoderdataPython
3368843
<reponame>YutingZhang/zcode from collections import OrderedDict import os import pyarrow import random import snappy import shutil from typing import Callable, List, Tuple, Iterable from z_python_utils.io import mkdir_p from threading import Lock, Thread import time __all__ = [ 'folder_to_record', "IndexedRec...
StarcoderdataPython
21262
__author__ = '<NAME>' from os import path from azure.storage.blob import BlockBlobService from flow.core.abstract_filesystem import AbstractFilesystem, splitpath class AzureBlobFilesystem(AbstractFilesystem): """ implementation of Azure Page Blob filesystem https://docs.microsoft.com/en-us/azure/storage/b...
StarcoderdataPython
4824141
<gh_stars>1-10 from win10toast_click import ToastNotifier import requests import schedule from ClointFusion import selft import datetime from datetime import timedelta import webbrowser,platform, os, time, datetime import pyinspect as pi from rich import pretty from pathlib import Path import sys windows_os = "window...
StarcoderdataPython
1643170
<reponame>deeprob/CRADLE<filename>tests/mocks/TwoBit.py class TwoBit: '''A mock for the py2bit data structure. Initialize with a dictionary of chromosome/sequence key/value pairs. E.g.: { "chr1": "actgtcgattcgctctcgatatagcatagctac", "chr2": "tctcgatcgctctcgcgctagagatccgag" } ''' def __init__(self, chromosome...
StarcoderdataPython
1698385
<filename>tests/alloc_tests/test_allocation.py import sys sys.path.append('../../scripts') import os import shutil import time from datetime import datetime from timedprocess import Command from Helper import generateResultsFromFileAllocation # from Helper import plotMean import csv import argparse from sendEmail impo...
StarcoderdataPython
1723842
import sqlite3 con = sqlite3.connect('census.db') cur = con.cursor() cur.execute('DROP TABLE IF EXISTS Density') cur.execute('CREATE TABLE Density(Name TEXT, Population INTEGER, Area REAL)') data = [ ('Newfoundland and Labrador', 512930, 370501.69), ('Prince Edward Island', 135294, 5684.39), ('Nova Scot...
StarcoderdataPython
129869
# This example scans for any BLE advertisements and prints one advertisement and one scan response # from every device found. This scan is more detailed than the simple test because it includes # specialty advertising types. from adafruit_ble import BLERadio from adafruit_ble.advertising import Advertisement from ada...
StarcoderdataPython
134948
import sys from collections import Counter def adapter_diffs(adapters): adapt = [0] + adapters + [adapters[-1] + 3] diffs = [z[1] - z[0] for z in zip(adapt[:-1], adapt[1:])] return diffs def find_paths(diffs): """ When chargers are 3 units apart, there's only one path between them. When...
StarcoderdataPython
1629378
<filename>mbed_devices/_internal/windows/logical_disk.py # # Copyright (C) 2020 Arm Mbed. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # """Defines a Logical disk.""" from typing import NamedTuple, cast from mbed_devices._internal.windows.component_descriptor import ComponentDescriptor class LogicalDi...
StarcoderdataPython
3306819
import configparser import camera_calibration """ @author(s): <NAME>, <NAME> This initializes necessary directories and files. """ import os import numpy as np db_dir = 'database' im_dir = 'database/images' def initialize(config_path='config.ini'): """ Initializes the user settings and folders. Para...
StarcoderdataPython
129879
# -*- coding: utf-8 -*- ''' :codeauthor: :email:`<NAME> (<EMAIL>)` tests.unit.modules.parted_test ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ''' # Import Python libs from __future__ import absolute_import # Import Salt Testing libs from tests.support.mixins import LoaderModuleMockMixin from tests.support.unit imp...
StarcoderdataPython
3275185
import time import random from tqdm import tqdm import numpy as np def greedy( measure, dataset_size, subset_size, start_indices, intermediate_target=None, clustering_combinations=None, verbose=True ): candidates = list(set(range(dataset_size)) - set(start_indices)) random.shuffl...
StarcoderdataPython
160381
#!/usr/bin/env python import sys import os from datetime import datetime import argparse from pyhesity import * parser = argparse.ArgumentParser() parser.add_argument('-v', '--vip', type=str, required=True) parser.add_argument('-u', '--username', type=str, required=True) parser.add_argument('-d', '--domain', type=str...
StarcoderdataPython
3260556
<gh_stars>10-100 from PIL import Image from matplotlib import pyplot as plt import numpy as np import face_recognition import keras from keras.models import load_model import cv2 image1 = Image.open("face.jpg") image_array1 = np.array(image1) plt.imshow(image_array1) image = face_recognition.load_image_file("face.jpg...
StarcoderdataPython
1627251
<reponame>Saferman/saferman.github.io<gh_stars>1-10 # -*- coding: utf-8 -*- # 查看PyQt5源代码,最终才搞明白 # https://www.cnblogs.com/hhh5460/p/5189843.html import sys from PyQt5 import QtWidgets from PyQt5.QtWidgets import QWidget,QGraphicsScene,QGraphicsView,QLabel,QScrollArea,QSlider from matplotlib.backends.backend_qt5agg i...
StarcoderdataPython
3360007
<reponame>AndersSun/pygame-puyo #!/usr/bin/env python """ runner test """ # Import Modules import pygame as pg from GreetingPanel import GreetingPanel if not pg.font: print("Warning, fonts disabled") if not pg.mixer: print("Warning, sound disabled") def main(): # Initialize Everything pg.init() ...
StarcoderdataPython
3232169
<filename>tests/test_btsmarthub_devicelist.py """The tests for the btsmarthub devicelist.""" import unittest from btsmarthub_devicelist import BTSmartHub class TestBTSmartHub(unittest.TestCase): def test_btsmarthub2_getdevicelist(self): # self.asserttrue(btsmarthub2_devicelist.detect_smart_hub2('192.168.1.2...
StarcoderdataPython
120500
import sqlite3 from sqlite3 import Error import pandas as pd def create_connection(db_file): """ create a database connection to a SQLite database """ conn = None try: conn = sqlite3.connect(db_file) c = conn.cursor() print(sqlite3.version) c.execute('''CREATE TABLE players...
StarcoderdataPython
1763342
<filename>setup.py import codecs import os from setuptools import setup, find_packages PACKAGE = 'inferencia' README = 'README.md' # REQUIREMENTS = './docker/gpu/requirements.txt' VERSION = '0.0.1' DESCRIPTION = 'The implementation of onnx model for inference.' def read(fname): # file must be read as utf-8 in ...
StarcoderdataPython
3332106
<reponame>carmelp16/anyway-etl import os ANYWAY_ETL_VENV = os.environ.get('ANYWAY_ETL_VENV') if not ANYWAY_ETL_VENV: ANYWAY_ETL_VENV = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'venv') ANYWAY_ETL_AIRFLOW_PIP_INSTALL_DEPS = os.environ.get('ANYWAY_ETL_AIRFLOW_PIP_INSTALL_DEPS') == '...
StarcoderdataPython
1610117
# Copyright © 2019 Arm Ltd. All rights reserved. # SPDX-License-Identifier: MIT from copy import copy import pytest import numpy as np import pyarmnn as ann def __get_tensor_info(dt): tensor_info = ann.TensorInfo(ann.TensorShape((2, 3)), dt) return tensor_info @pytest.mark.parametrize("dt...
StarcoderdataPython
83803
<reponame>ab7289/mercury-hardware<filename>hardware/Utils/utils.py import os import json from datetime import datetime, timezone from .logger import Logger SENSOR_KEYS = { "ALL": "all", "TEMPERATURE": "temperature", "PRESSURE": "pressure", "HUMIDITY": "humidity", "ACCELERATION": "acceleration", ...
StarcoderdataPython
1716348
from django.contrib import admin from .actions import export_as_json, export_as_csv from .models import ( Organization, Team, Response, ) class TeamInline(admin.StackedInline): model = Team can_delete = False @admin.register(Organization) class OrganizationAdmin(admin.ModelAdmin): list_dis...
StarcoderdataPython
3296874
<filename>dmsuMarket/celery_tasks/sms/tasks.py import random import time from ..main import celery_app @celery_app.task(name='send_sms_code') def send_sms_code(*args): time.sleep(random.randint(0,2)) print('>>>>>>>>>>>>Clouds Communicating>>>>>>>>>>>>>>') print('%s>>>>>>>>>>>>>>>>>>>>>>%s' % args)
StarcoderdataPython
3285269
<gh_stars>0 #This file uses TFIDF to capture the most unique terms for each park unit (according #to the visitor surveys), and to make some example word clouds based on them. import pandas as pd import pickle from sklearn.feature_extraction.text import TfidfVectorizer import wordcloud from os import path from wordclo...
StarcoderdataPython
3268159
<filename>programming/dsame/trees/NoOfLeavesRecursion.py from dsame.trees.BinaryTreeNode import * def no_of_leaves(root: BinaryTreeNode): if not root: return 0 if not root.left and not root.right: return 1 return no_of_leaves(root.left) + no_of_leaves(root.right) print(no_of_leaves(ini...
StarcoderdataPython
1671031
<reponame>softlayer/softlayer-object-storage-backup<gh_stars>1-10 #!/usr/bin/env python from setuptools import setup from slbackup import __version__ setup(name='slbackup', version=__version__, description='Backup utility for SWIFT object storage', author='<NAME>', author_email='<EMAIL>', ...
StarcoderdataPython
1753255
from tkinter.constants import ACTIVE, CENTER, DISABLED, FLAT, NORMAL, S, SOLID, GROOVE, RAISED, RIDGE, SUNKEN from tkinter import Checkbutton, filedialog as fd from tkinter import ttk import tkinter as tk from typing import Text from typing_extensions import IntVar import RPi.GPIO as GPIO from datetime import datetime ...
StarcoderdataPython
1626178
# -*- coding: utf-8 -*- """ Training script for continuous emotion recognition in VAD space. # Reference - [Emotion Recognition in Context](http://sunai.uoc.edu/emotic/pdf/EMOTIC_cvpr2017.pdf) - https://stackoverflow.com/questions/43452441/keras-all-layer-names-should-be-unique """ from __future__ import print_funct...
StarcoderdataPython
13233
<gh_stars>0 class Node: """ This object is a generic node, the basic component of a Graph. Fields: data -- the data this node will contain. This data can be any format. """ def __init__(self, data): self.data = data
StarcoderdataPython
4816645
<gh_stars>1-10 from flask import Blueprint from application.modules.system import cpuinfo,meminfo,netinfo import json mod = Blueprint('system', __name__) @mod.route('/system/cpuinfo') def sysCpuInfo(): cpuinfo_res = cpuinfo() return json.dumps(cpuinfo_res) @mod.route('/system/meminfo') def sysMemInfo(): m...
StarcoderdataPython
3229744
import csv from src.globals.paths import GS_PATH from src.handlers.writer import write_to_json NAME_INDEX = 1 YEAR_INDEX = 3 GENRE_INDEX = 4 SALES_INDEX = -1 def make_analysis(output_filepath): """Does all the work needed to complete the analysis. In this case, it makes one thing: - Wri...
StarcoderdataPython
3201162
from bs4 import BeautifulSoup import requests from typing import List, Dict import json import time def get_all_whiskys(urls: List[str], headers: Dict[str, str]) -> Dict[str, str]: """Function to scrape name and further details link from each row of whisky from every page on each url in a list of urls from master...
StarcoderdataPython
165305
<reponame>TankyFranky/Snow_Removal_GAN_ELEC825_Final_Project """ Based on the Pix2Pix GAN outlined by <NAME> https://machinelearningmastery.com/how-to-develop-a-pix2pix-gan-for-image-to-image-translation/ This helper script generates the .npz files required for the input of the cGAN """ from os import listdir from num...
StarcoderdataPython
3305606
# Gets a PALSAR unigned int 16bit dataset and returns # a 32bit float GeoTIFF image in DB values normalized # with the image global MAX and MIN DB values then filters # the result with a 9 average convolution matrix import glob import gdal from gdalconst import * import osr import numpy as np from struct import * impor...
StarcoderdataPython
4818261
<reponame>lsldragon/AITranslator from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5 import QtCore, QtGui, QtWidgets class AboutDialog(): def __init__(self): vbox = QVBoxLayout() hbox = QHBoxLayout() message = QLabel() text = """ <html> <h2>软件开...
StarcoderdataPython
97370
from __future__ import unicode_literals from django.db import reset_queries, transaction, router from reversion.models import Revision, Version, _safe_subquery from reversion.management.commands import BaseRevisionCommand from reversion.revisions import create_revision, set_comment, add_to_revision class Command(Base...
StarcoderdataPython
1653349
<reponame>w1ldy0uth/ARP-scanner<gh_stars>1-10 #!/usr/bin/env python3 # -*- coding: UTF=8 -*- import os import sys import platform from method.arp import Arp from method.ping import Ping from method.port import Port from method.sub.iface import get_iface from method.sub.ipget import get_ip from method.sub.macget import...
StarcoderdataPython
3209201
<gh_stars>0 import os from os import listdir import subprocess from tqdm import tqdm import gzip import shutil def load() -> None: """ Load and unpack Semantic Scholar Open Research Corpus. """ try: os.mkdir('tmp') except: pass try: os.mkdir('unpacked') e...
StarcoderdataPython
3305578
from .base import DeviceBase from .base_db import Device
StarcoderdataPython
158432
import torch import torchvision.models as models from CrossConv import CrossConv2d class TBResNet(models.ResNet): def __init__(self, block, layers, zero_init_residual=False, groups=1, width_per_group=64, replace_stride...
StarcoderdataPython
1640087
<filename>webbreaker/fortifyconfig.py #!/usr/bin/env python # -*- coding: utf-8 -*- try: import ConfigParser as configparser except ImportError: #Python3 import configparser import os import sys import re from webbreaker.webbreakerlogger import Logger from subprocess import CalledProcessError from cryptography...
StarcoderdataPython
3302466
<filename>working-library/background/LoginAPI/migrations/0001_initial.py # Generated by Django 2.1.8 on 2020-05-15 12:02 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name...
StarcoderdataPython
3388874
<gh_stars>10-100 # http://quantresearch.org/CSCV_2.py.txt #!/usr/bin/env python # On 20130704 by <EMAIL> #---------------------------------------------------------------------------------------- def testAccuracy_EVT(sr_base, sr_case): # Test accuracy by numerical integration # It does the same as testAccuracy_...
StarcoderdataPython
119432
import logging from django import forms from django.utils.translation import ugettext_lazy as _ from mayan.apps.documents.models import DocumentType from mayan.apps.metadata.models import MetadataType, DocumentMetadata, DocumentTypeMetadataType from mayan.apps.acls.models import AccessControlList logger = logging.get...
StarcoderdataPython
1744535
from django.shortcuts import render from django.utils import timezone from django.views.generic import (CreateView, FormView, ListView, UpdateView, View) from dss.Mixin import (FormJsonResponseMixin, JsonResponseMixin, MultipleJsonResponseMixin) from dss.Serializ...
StarcoderdataPython
1610932
import os class Config: @classmethod def toJSON(cls): import json data = dict() for item in dir(cls): if item.isupper(): data[item] = getattr(cls, item) return json.dumps(data) DEBUG = False TESTING = False DEBUG_SQL = False SQLALCHE...
StarcoderdataPython
4827150
<reponame>bigfoolliu/liu_aistuff<gh_stars>1-10 #!/usr/bin/env python3 # -*- coding:utf-8 -*- # author: bigfoolliu """ 使用生成器来实现一个并发网络应用程序 """ from socket import socket, AF_INET, SOCK_STREAM import time from collections import deque from select import select class YieldEvent: """ 调度器中通用的yield事件 """ ...
StarcoderdataPython
1753135
""" This module provides a custom DRF Permission class for supporting SAFE_METHODS to Authenticated Users, but requiring Superuser access for all other Request types on an API endpoint. """ from rest_framework.permissions import SAFE_METHODS, BasePermission from lms.djangoapps.courseware.access import has_access c...
StarcoderdataPython
40621
#!/usr/bin/env python from setuptools import setup, find_packages setup( name='django-git', version='0.1.0', description='Get git information for your django repository', author='<NAME>', author_email='<EMAIL>', license='MIT', url='https://github.com/spapas/django-git/', zip_safe=False...
StarcoderdataPython
3398259
""" Launch material server """ import io import errno import json import logging import logging.config import pkgutil import inspect from os import environ, strerror from waitress import serve from importlib import import_module from pathlib import Path from flask import Flask, jsonify, make_response, abort, reque...
StarcoderdataPython
3323538
<reponame>QRemy/gammapy # Licensed under a 3-clause BSD style license - see LICENSE.rst import numpy as np from numpy.testing import assert_allclose import astropy.units as u from astropy.io import fits from gammapy.irf import Background3D, EffectiveAreaTable2D, EnergyDispersion2D class TestIRFWrite: def setup(se...
StarcoderdataPython
3367666
#!/usr/bin/python3 # There are major unfinished elements of this implementation, some # left unfinished by Spiewak, some by me. # Me: Lazy evaluation. The problem is that this is just very hard to # do in Python and will require major rearchitecting that I'm not sure # is worthwhile for a learning project. # Spiewa...
StarcoderdataPython
148168
<gh_stars>10-100 # Sequence Equation # Find some y satisfying p(p(y)) = x for each x from 1 to n. # # https://www.hackerrank.com/challenges/permutation-equation/problem # def permutationEquation(p): # Complete this function n = len(p) q = [0] * n # p(p(𝓎)) = 𝓍 (au décalage de 1 près) for i in ra...
StarcoderdataPython
15940
<reponame>qqgg231/Allegro<gh_stars>10-100 #!/usr/bin/env python # coding=utf-8 from celery import Celery from pprint import pprint import time app = Celery('tasks', backend='redis://localhost:6379/0', broker = 'redis://localhost:6379/0') @app.task def get(message): #=========== #pprint(message) #========...
StarcoderdataPython
3240240
'''H5 data prep''' ## External modules. import csv import numpy as np import os import tables ## Internal modules. from mml.config import dir_data_toread from mml.config import dir_data_towrite from mml.utils import makedir_safe ############################################################################### ## Cl...
StarcoderdataPython
1639851
<filename>wechatsogou/five.py # -*- coding: utf-8 -*- from PIL import Image import six if six.PY2: import sys import urlparse as url_parse from urllib import urlencode from urllib import unquote from urllib import quote as quote import StringIO def readimg(content): return Image.o...
StarcoderdataPython
196599
<reponame>jovalie/causalnex # Copyright 2019-2020 QuantumBlack Visual Analytics Limited # # 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 # # THE ...
StarcoderdataPython
1671175
<gh_stars>0 # uncompyle6 version 3.7.4 # Python bytecode 3.7 (3394) # Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] # Embedded file name: T:\InGame\Gameplay\Scripts\Server\situations\situation_goal_proxy.py # Compiled at: 2020-09-17 03:28:49 # Size of source m...
StarcoderdataPython
3292936
<filename>AtCoder/ABC/129/d.py import numpy as np import sys def main(): input = sys.stdin.readline H, W = map(int, input().split()) A = [] for _ in range(H): S = [0 if c == '#' else 1 for c in input().strip()] A.append(S) A = np.array(A) up = np.zeros((H+1, W), dtype=np.int) ...
StarcoderdataPython
9238
import unittest from nanoservice import Responder from nanoservice import Requester class BaseTestCase(unittest.TestCase): def setUp(self): addr = 'inproc://test' self.client = Requester(addr) self.service = Responder(addr) self.service.register('divide', lambda x, y: x / y) ...
StarcoderdataPython
199195
<gh_stars>0 # Copyright 2015 Hewlett-Packard Development Company, L.P. # 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/licens...
StarcoderdataPython
3206138
""" Wire module. """ # ISC License # # Copyright (c) 2020–2021, <NAME>, <NAME>. <<EMAIL>> # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # T...
StarcoderdataPython
1610223
def _merge_toolchain_impl(ctx): toolchain_info = platform_common.ToolchainInfo( merge_tool = ctx.files.merge_tool.path, ) return [toolchain_info] merge_toolchain = rule( implementation = _merge_toolchain_impl, attrs = { "merge_tool": attr.label( executable = True, ...
StarcoderdataPython
190749
from errors import * from nodes import * from ifelse import * from loop import * from func import * from trycatch import * from strquot import unquote STATEMENTS = set('func labda local if elseif else while for try catch repeat'.split()) STATEMENT_CLASS = {'func': FuncStatement, 'labda': LabdaStatement, 'local': Lo...
StarcoderdataPython
140641
""" Base Container Object """ # global import re import termcolor import numpy as _np import json as _json import h5py as _h5py import pickle as _pickle import random as _random from operator import lt as _lt from operator import le as _le from operator import eq as _eq from operator import ne as _ne from operator imp...
StarcoderdataPython
3277819
import random from logging import basicConfig, getLogger, DEBUG, INFO from typing import List from discord.ext import commands import data import env import model.weapons from type.language import Language from type.weapon import Weapon env = env.Env() logger = getLogger(__name__) basicConfig(level=DEBUG if env.deb...
StarcoderdataPython
21472
<reponame>a2csuga/lektor-root-relative-path<gh_stars>1-10 # -*- coding: utf-8 -*- try: # py3 from urllib.parse import urljoin, quote except ImportError: # py2 from urlparse import urljoin from urllib import quote from lektor.pluginsystem import Plugin from furl import furl class RootRelativePath...
StarcoderdataPython
168707
import asyncio from signal import SIGTERM from custom import * from setup import database_setup from Accessory import Accessory bot = config.bot @bot.event async def on_ready(): # bot.loop.add_signal_handler( # SIGTERM, lambda: asyncio.ensure_future(terminate()) # ) await database_setup() ...
StarcoderdataPython
3298818
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Python library to communicate with an obs-websocket server. """ from .core import obsws
StarcoderdataPython
4836473
<reponame>plcrodrigues/py.BI.EEG.2013-GIPSA #!/usr/bin/env python # -*- coding: UTF-8 -*- import mne import numpy as np from . import download as dl import os import glob import zipfile from scipy.io import loadmat from distutils.dir_util import copy_tree import shutil import yaml BI2013a_URL = 'https://zenodo.org/re...
StarcoderdataPython
102862
<reponame>DangoMelon0701/PyRemote-Sensing # -*- coding: utf-8 -*- """ Created on Thu Apr 26 15:47:38 2018 @author: gerar """ import os import pandas as pd import numpy as np #%% def read_table(dataframe): data = pd.read_table(dataframe) data['Difference']=np.abs(data['AOD_AERONET']-data['AOD_MODIS']) drop...
StarcoderdataPython
3271340
<filename>utility.py ROOT = "/api" REPORT_ENDPOINT = '/api/report' API_ENDPOINT = "https://j9l4zglte4.execute-api.us-east-1.amazonaws.com/api/ctl/weather" METHOD_GET = 'GET' MIME_JSON = 'application/json'
StarcoderdataPython
27495
import logging, traceback, time from bottle import request from snuggle import configuration from snuggle import mediawiki from snuggle import errors from snuggle.data import types from snuggle.web.util import responses, user_data logger = logging.getLogger("snuggle.web.processing.users") class Events: def __init__...
StarcoderdataPython
1678534
"""Converters and helper functions for session dates and times Time handling is unfortunately a bit complicated for several reasons: - Dates/times in the input API can come in several text formats, e.g. with seconds or timezones either included or left off. - A session's time is an interval with start and end times....
StarcoderdataPython
1694718
<filename>glance/domain/proxy.py # Copyright 2013 OpenStack Foundation # 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/licens...
StarcoderdataPython
1793994
''' AMQP-consumer wrapper with dedicated thread. ''' import threading import queue import pika ###################################################### ## RabbitMQ producer (AMQP) class ConsumerThread(threading.Thread): def __init__(self, msg_queue, host, exchange_type, exchange_name, routing_key=''): '''i...
StarcoderdataPython
194260
''' Source codes for Python Machine Learning By Example 3rd Edition (Packt Publishing) Chapter 6 Scaling Up Prediction to Terabyte Click Logs Author: <NAME> (<EMAIL>) ''' from pyspark.sql import SparkSession spark = SparkSession\ .builder\ .appName("CTR")\ .getOrCreate() from pyspark.sql.types imp...
StarcoderdataPython
4802099
from torch import nn import torch.nn.functional as F class Wrapper: @staticmethod def get_args(parser): parser.add('--fm_weight', type=float, default=10.0) @staticmethod def get_net(args): criterion = Criterion(args.fm_weight) return criterion.to(args.device) class Criterion(...
StarcoderdataPython