content stringlengths 5 1.05M |
|---|
import os
import json
import subprocess
import traceback
import datetime
from urllib.parse import quote_plus
from pprint import pprint
import requests
from minecraft_server_tools import sync_mods
from minecraft_server_tools.constants import (
COMMENT_JSON,
MC_VERSION,
COMPONENT_SEPS,
NON_NAME_COMPONEN... |
try:
import json
except ImportError:
import simplejson as json
import sqlite3
from sqlite3 import *
import urllib.request
import csv
import os
import requests
global API_KEY
global count
count = 0
def isApiActive():
try:
url = 'https://api.guildwars2.com/v2'
... |
"""This is a separate module so we can cleanly getcwd() before anyone
does chdir().
"""
import sys, os
startdir = os.getcwd()
def exe():
return (os.environ.get('BUP_MAIN_EXE') or
os.path.join(startdir, sys.argv[0]))
def exedir():
return os.path.split(exe())[0]
def exefile():
return os.pat... |
import sqlite3
import pandas as pd
from PyQt5.QtGui import QFont, QColor
openapi_path = 'D:/OpenAPI'
system_path = 'D:/PythonProjects/PyStockTrader'
graph_path = f'{system_path}/backtester/graph'
db_setting = f'{system_path}/database/setting.db'
db_backtest = f'{system_path}/database/backtest.db'
db_tradelist = f'{sys... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.1 on 2017-07-02 04:10
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('competitions', '0001_initial'),
]
operations = [
migrations.AddField(
... |
"""
@Author: xxxmy
@Github: github.com/VectXmy
@Date: 2019-10-06
@Email: xxxmy@foxmail.com
"""
import torch.nn as nn
import torch
import math
class ScaleExp(nn.Module):
def __init__(self, init_value=1.0):
super(ScaleExp, self).__init__()
self.scale = nn.Parameter(torch.tensor([init... |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class ProcpsNg(AutotoolsPackage):
"""Utilities that provide system information."""
homepage... |
import numpy as np
from py import social_distancing_config as config
from scipy.spatial import distance as dist
import cv2
first = True
pastCentroids = []
lines = []
def getMap(centroids, frame, iteration):
global pastCentroids, first, lines
if first:
pastCentroids = centroids
first = False... |
import os
from dotenv import load_dotenv
import requests
from pprint import pprint
from mojang import MojangAPI
load_dotenv()
class Player(object):
def __init__(self, ign):
super().__init__()
self.uuid = MojangAPI.get_uuid(str(ign))
self.api = os.environ["API_KEY"]
self.link = f"htt... |
from paramiko import SSHClient, AutoAddPolicy, RSAKey
from config import SSH_HOST, SSH_PORT, SSH_USER, KEY_FILE, PASSPHRASE
with SSHClient() as ssh:
# 秘密鍵ファイルからキーを取得
if PASSPHRASE is None:
# 秘密鍵ファイルにパスフレーズを設定していない場合
rsa_key = RSAKey.from_private_key_file(KEY_FILE)
else:
# 秘密鍵ファイルにパ... |
import os
try:
from PIL import Image
except ImportError:
exit("This script requires the pillow module\nInstall with: sudo pip install pillow")
font = {}
# font image contains a grid of 3 x 32 characters each of which is
# contained in a 6x6 box. The first character is ASCII 0x20 which
# increments down the ... |
"""REST client handling, including SlackStream base class."""
import time
from typing import Any, Dict, Text, Optional, List
from singer_sdk.streams import RESTStream
from singer_sdk.authenticators import BearerTokenAuthenticator
class SlackStream(RESTStream):
"""Slack stream class."""
_page_size = 500
... |
"""
PROFIT: A Novel Training Method for sub-4-bit MobileNet Models
Progressive quantization training
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from __future__ import print_function
import argparse
import numpy as np
import copy
import torch
im... |
from program import Program
from prints import *
from getpass import getpass
from time import sleep
from os import urandom
from base64 import b64encode
passwlocker=Program()
import sys
#This is the in Terminal version of the program use gui.py for graphical version
def showcreds(username):
userobject=passwlocker.users... |
import os
DEBUG = True
SECRET_KEY='hunter2'
SITE_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_ROOT = os.path.join(SITE_ROOT, 'media')
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(SITE_ROOT, 'assets')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(SITE_ROOT, 'static')... |
from ev3dev.ev3 import Leds
import threading
from time import sleep
_MIN_BLINK_PERIOD_ = 0.7
class LedControl(threading.Thread):
def __init__(self, init_left_color = Leds.GREEN, init_right_color = Leds.GREEN):
self.init_left_color = init_left_color
self.init_right_color = init_right_color
... |
import os
import string
import random
import tempfile
import subprocess
import pytest
import minus80 as m80
from click.testing import CliRunner
from minus80.Freezable import FreezableAPI
from minus80.cli import minus80 as cli
def test_project_init_cwd():
tmpdir = tempfile.mkdtemp()
os.chdir(f"{tmpdir}")
... |
# 테스트 케이스 개수 T
t = int(input('테스트 케이스 1이상 50 이하의 숫자를 입력해 주세요 : '))
# 카운딩은 결과값 출력 형식에 필요한 인덱스 갑
counting = 1
# 해당 while 문은 테스트 케이스 수만큼 프로그램을 반복하기 위한 장치임
while t > 0:
# 요구범위 밖의 숫자가 입력되었을때 오류메시지 출력 후 재입력
while (t > 50) or (t <= 0):
print('범위 밖의 숫자입니다 다시 입력해주세요')
test_case = int(input('테스트 케이스 1이상 ... |
"""
Usage:
pip install git+https://github.com/Pebaz/bloxel.git
"""
from distutils.core import setup
setup(
name='bloxel',
version='1.2.2',
description='Isometric Voxel Generator',
author='Samuel Wilder',
packages=['bloxel'],
install_requires=[
'Pillow>=6.2.2',
'docopt==0.6.2'
],
entry_points={
'console_... |
# -*- coding: utf-8 -*-
# Resource object code
#
# Created: Sat Jun 1 18:43:15 2013
# by: The Resource Compiler for PySide (Qt v4.7.0)
#
# WARNING! All changes made in this file will be lost!
from PySide import QtCore
qt_resource_data = "\
\x00\x00\x04\x54\
\x89\
\x50\x4e\x47\x0d\x0a\x1a\x0a\x00\x00\x00\x0d\x49... |
#!/usr/bin/python
# Copyright (c) PLUMgrid, Inc.
# Licensed under the Apache License, Version 2.0 (the "License")
from bcc import BPF
from builtins import input
from pyroute2 import IPRoute, NetNS, IPDB, NSPopen
from random import shuffle
from time import sleep
from simulation import Simulation
import sys
ipr = IPRou... |
from django.db.models.signals import post_save
from .models import UsedDiscount
def used_discount_updated(**kwargs):
used_discount = kwargs.get('instance')
if kwargs['created']:
discount = used_discount.discount
discount.total_usages += 1
discount.save()
post_save.connect(used_disco... |
import os
import json
import math
import requests
import torch
from collections import OrderedDict
def download_gdrive(gdrive_id, fname_save):
""" source: https://stackoverflow.com/questions/38511444/python-download-files-from-google-drive-using-url """
def get_confirm_token(response):
for key, value ... |
# pylint: disable=wildcard-import
# pylint: disable=unused-wildcard-import
import io
import os
import re
import sys
import math
import time
import random
import string
import typing as typ
import itertools
import collections
import click
import pytest
import pexpect
import click.testing
import sbk.cli
import sbk.cli... |
import sys
# package need to be installed, pip install docker
import docker
import time
import yaml
import os
import random
import subprocess
import signal
import shutil
import urllib2
test_pull = False
pwd = os.getcwd()
client = docker.from_env()
def empty_cache():
# docker system prune -a
p = subprocess.... |
# -*- coding: utf-8 -*-
"""Extract descriptive statistics for the time series
This script is used to extract descriptive statistics regarding features of the
time series from the summary files.
Author: Gertjan van den Burg
Copyright (c) 2020 - The Alan Turing Institute
License: See the LICENSE file.
"""
import a... |
import numpy as np
import pandas as pd
import xarray as xr
from scipy.ndimage import filters
from typing import Union
from imctoolkit.multichannel_image import MultichannelImage
try:
import cv2
CV2_BORDER_DEFAULT = cv2.BORDER_DEFAULT
except:
cv2 = None
CV2_BORDER_DEFAULT = 4
def _apply_to_multicha... |
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
BaseModel = declarative_base()
class ProviderInfo(BaseModel):
__tablename__ = 'provider_info'
id = Column(Integer, primary_key=True, autoincrement=True)
provider_name = Column(String(128))
status =... |
#
# PySNMP MIB module CISCO-DOT11-RADIO-DIAGNOSTIC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-DOT11-RADIO-DIAGNOSTIC-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:38:33 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Pyt... |
import numpy as np
import pandas as pd
class KFoldCrossValidator:
def __init__(self, number_of_folds: int, random_state: int = 42, is_binary_classification: bool = True, verbose: bool = False):
self.number_of_folds = number_of_folds # TODO: Needs to have one or more
self.random_state = random_sta... |
class Builder:
def build(self):
self.preparaPan()
self.agregaCarne()
self.agregaVerduras()
self.agregaCondimentos()
self.hazlaCombo()
def preparaPan(self):
pass
def agregaCarne(self):
pass
def agregaVerduras(self):
pass
def agregaCo... |
#!/usr/bin/env python
"""
This script performs the following tasks:
1) Makes cleft regions and analyzes their greyscale density. If they
alreadyexist, cleft layers can be read. The following regions can be made
(from 0 to all 3):
a) Layers (parallel to the cleft)
b) Columns (perpendicular to the c... |
# rotate.py
# -------------------------------------------------------------------------
# Define function to rotate a vector in two dimensions.
# -------------------------------------------------------------------------
import numpy as np
def rotate_vector(vector, angle):
"""
Rotate two-dimensional vector through g... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright 2018 Ozer Ozkahraman (ozkahramanozer@gmail.com)
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must ret... |
import logging
from importlib.machinery import SourceFileLoader
import argparse
from data.data_switch import data_switch
import os
import config.system as sys_config
import shutil
import utils
from phiseg import phiseg_model
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')
def main(exp_confi... |
import RPi.GPIO as ir
print "PIN 18 High"
ir.setwarnings(False)
ir.setmode(ir.BOARD)
ir.setup(18,ir.OUT)
ir.output(18,ir.HIGH)
|
import os
import torch
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # sets device for model and PyTorch tensors
# Model parameters
image_w = 112
image_h = 112
channel = 3
emb_size = 512
# Training parameters
num_workers = 1 # for data-loading; right now, only 1 works with h5p... |
""" Alpha Vantage Model """
__docformat__ = "numpy"
import logging
import pandas as pd
import requests
from alpha_vantage.sectorperformance import SectorPerformances
from openbb_terminal.rich_config import console
from openbb_terminal import config_terminal as cfg
from openbb_terminal.decorators import log_start_end... |
from celery import Celery
celery_app = Celery(
"tasks",
broker="redis://127.0.0.1:6379/0",
backend="redis://127.0.0.1:6379/0",
)
celery_app.config_from_object('worker.celeryconfig')
|
# Copyright (c) 2020 Graphcore Ltd. All rights reserved.
import numpy as np
import popart
import torch
from op_tester import op_tester
def test_log1p_0(op_tester):
input_data = np.array([0.01, 0.1, 0.5, 1, 2, 12345], dtype=np.float32)
def init_builder(builder):
i1 = builder.addInputTensor(input_data)... |
import logging
from datetime import datetime, timezone
from django.core.management.base import BaseCommand, CommandError
from django.db import DatabaseError
from compte.models import EmailToken
from core import mattermost
logger = logging.getLogger(__name__)
class Command(BaseCommand):
help = "Supprime les de... |
#!/usr/bin/env python
""" Tests of Larch Scripts """
import unittest
import time
import ast
import numpy as np
from sys import version_info
from utils import TestCase
from larch import Interpreter
class TestScripts(TestCase):
'''testing of asteval'''
def test01_basic(self):
self.runscript('a.lar', dir... |
"""Podcast registration tests."""
from httplib import OK
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test import TestCase
class RegistrationTestCase(TestCase):
def setUp(self):
self.account_login_url = reverse('account_login')
self.regist... |
import json
from django.contrib import messages
from django.shortcuts import get_object_or_404, Http404
from django.http import HttpResponse, HttpResponseServerError, HttpResponseBadRequest, HttpResponseForbidden
from django.db import transaction, models
from django.utils.translation import ugettext_lazy as _
from djan... |
import xml.etree.ElementTree as ET
import cv2
from tensorflow_infer import inference
from load_model.tensorflow_loader import load_tf_model, tf_inference
from utils.anchor_generator import generate_anchors
import numpy as np
class Evaluation():
def __init__(self,thresh_iou,image_names):
self.thresh_iou=th... |
class InvalidStartParameter(Exception):
def __init__(self):
super(InvalidStartParameter, self).__init__('\nУказан неверный параметр для запуска. Доступные параметры:\n'
'train - тренировка сети\n'
'test -... |
# Created by matveyev at 23.02.2021
from datetime import datetime
from PyQt5 import QtCore, QtGui
from petra_viewer.asapo_tree_view.asapo_table_headers import headers
# ----------------------------------------------------------------------
class Node(object):
def __init__(self, parent, row=-1, info=None):
... |
"""Summarise hazard data
Get OD data and process it
"""
import ast
import itertools
import math
import operator
import os
import subprocess
import sys
import geopandas as gpd
import igraph as ig
import matplotlib as mpl
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
import numpy as np
import pa... |
from flask import Blueprint, jsonify, request
from cache import cache, make_cache_key
from db import db
from models.hospital import (Hospital, HospitalsPerBundesland,
HospitalsPerLandkreis,
HospitalsPerRegierungsbezirk)
from models.icuDevelopments import IcuDev... |
"""
A python module for interacting and scripting with DAOphot command-line tools.
Note that this is a work-in-progess and not yet functional
"""
from __future__ import division, print_function
__all__ = ['DaophotBase', 'Daophot']
class DaophotBase(object):
"""
A superclass for running various DAOphot tools... |
from django.db import models
from .storage_config import *
class AppFile(models.Model):
id = models.AutoField(primary_key=True)
display_id = models.CharField(editable=False, max_length=16, null=False)
file = models.FileField(upload_to='uploads/', storage=PrivateMediaStorage())
thumbnail = models.FileFi... |
# Generated by Django 2.2.10 on 2020-03-06 19:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("organisations", "0002_auto_20200210_1326"),
]
operations = [
migrations.AddField(
model_name="organisation",
name="... |
"""
Author: Faidon Mitzalis
Edited from VL-BERT impelementation
Generates json file for training set with caption/images/frcnn for multi30k dataset
"""
captions_en = []
captions_de = []
urls = []
images = []
frcnns = []
with open('train.txt') as fp:
for cnt, line in enumerate(fp):
image_id = (line.split('... |
# coding: utf-8
# Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... |
import random
import datetime
import string
import json
from . import redis
from .models import User
from .lobby_names import LOBBY_ADJECTIVES, LOBBY_NOUNS
from .game.game_config import GameConfig as gc
# max num of players in a game
MAX_PLAYER_COUNT = 4
# Below dicts describe the loose schema being used to manage ga... |
# Copyright 2018 The Bazel 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 applicable la... |
import logging
import socket
import remoto
import ceph_medic
from execnet.gateway_bootstrap import HostNotFound
logger = logging.getLogger(__name__)
def get_connection(hostname, username=None, threads=5, use_sudo=None, detect_sudo=True, **kw):
"""
A very simple helper, meant to return a connection
that w... |
# -*- coding: utf-8 -*-
# Copyright (c) 2020.
#
# Created by AnyKeyShik Rarity
#
# Telegram: @AnyKeyShik
# GitHub: https://github.com/AnyKeyShik
# E-mail: nikitag594@gmail.com
import json
import pkg_resources
from core.exceptions import TagNotFoundException, RatingNotFoundException, CommandNotFoundExcepti... |
import threading
import time
import copy
class ClientKeyValueStore(object):
def __init__(self):
self._rlock = threading.Lock()
self._wlock = threading.Lock()
self._cache = {}
#dict : {"key","value","status"} status could be deleted , expired
def write(self, key, value, ttl= -1... |
from django.shortcuts import render
def index(request):
return render(request, 'mainapp/index.html')
def evidence(request):
return render(request, 'mainapp/evidence.html')
def list(request):
return render(request, 'mainapp/list.html')
def description(request):
return render(request, 'mainapp/desc... |
# 匯入自定義錯誤,不然有些函式會找不到哪裡raise錯誤
from .. import UserDifineException as aspen_UDE
from . import UserDifineException as visio_UDE
class AspenConnector:
"""Some functions can connect the data from AspenFile."""
def __init__(self, visio_master):
self.visio_master = visio_master
self.visio = visio_mas... |
###############################################################################
# LokyProcess implementation
#
# authors: Thomas Moreau and Olivier Grisel
#
# based on multiprocessing/process.py (17/02/2017)
# * Add some compatibility function for python2.7 and 3.3
#
import os
import sys
from .compat import ... |
import numpy as np
from sklearn.metrics import accuracy_score
'''
-------------- Activation Functions ----------------------
Each object has two methods:
g: The activation function
dg: The partial derivative
'''
class Sigmoid():
def g(self, z):
return 1 / (1 + np.exp(-z))
def dg(self, z)... |
# Copyright (c) The Diem Core Contributors
# SPDX-License-Identifier: Apache-2.0
import context, secrets
from operator import attrgetter
from typing import Dict, List, Optional
from diem import identifier
from diem_utils.precise_amount import Amount
from diem_utils.types.currencies import DiemCurrency, FiatCurrency
f... |
# Modifications copyright 2022 AI Singapore
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
from ....content_providers.content_manager import ContentManager
from ....utilities import datamodel
from .session import Session
def open_session(path):
ContentManager().scan_for_content(path)
dmx_session = datamodel.load(path)
return Session(dmx_session.root)
|
cadastro = {}
pessoas = []
soma = media = 0
while True:
cadastro['nome'] = input('Nome: ').capitalize()
while True:
sexo = input('Sexo [M/F]: ').upper().strip()[0]
if sexo in 'MF':
cadastro['sexo'] = sexo
break
else:
print('ERRO! Por favor, digite apen... |
from yt_velmodel_vis import seis_model as sm
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import yt,os
import numpy as np
fname='NWUS11-S_percent.nc'
model=sm.netcdf(fname)
model.moveToUnstructured(fields=['dvs'],coordfields=['depth'])
fig = plt.figure()
ax = fig.add_subplot(111, projectio... |
"""calculates the value of an investment after a given time frame"""
import locale
locale.setlocale(locale.LC_ALL, '')
#use locale.currency(var, symbol=True, grouping=True) for currency formating
#def func:
def create():
"""creates the list"""
global stocks
stocks = [["Columbia Sportswear", 15], ["Dean F... |
'''
Created on 28 Oct 2017
@author: chrisd
'''
from com.camding.plexpostprocess.PlexPostProcessState import PlexPostProcessState
class ScannedFile(object):
'''
classdocs
'''
def __init__(self, row):
'''
Constructor
'''
self.__state = row['state']
self.__filename = row['filename']
self.... |
from typing import Tuple
import numpy as np
def expected_mahalanobis(sigma, diff, accprob):
sigma_inv = np.linalg.inv(sigma)
maha = np.sum((diff@sigma_inv) * diff, axis=-1)
emaha = maha * accprob
not_nan = ~np.isnan(emaha)
emaha = emaha[not_nan]
return emaha, not_nan
def jump_statistics(sigm... |
from rest_framework.serializers import ModelSerializer
from auth.serializers import UserDetailSerializer
from tag.models import Tag, EntityTag
class TagSerializer(ModelSerializer):
class Meta:
model = Tag
fields = "__all__"
class EntityTagSerializer(ModelSerializer):
class Meta:
mod... |
# Copyright 2021 Modelyst LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
"""
An Introduction to Interactive Programming in Python (Part 1)
Practice exercises for timers # 3.
Canvas color with timer.
"""
import simpleguitk as simplegui
color = "Red"
# Timer handler
def tick():
global color
if color == "Red":
color = "Blue"
else:
color = "Red"
... |
__all__ = ['BaseStorage', 'KeyError']
import os
class KeyError(Exception):pass
class BaseStorage(object):
def __init__(self, cache_manager, options):
self.cache_manager = cache_manager
self.options = options
def get(self, key):
raise NotImplementedError()
def set(self, key, ... |
from django.http import HttpRequest
from django.test import SimpleTestCase
from django.urls import reverse
import datetime
from dateutil.relativedelta import relativedelta
import iexfinance
# Create your tests here.
from . import views
from . import logic
class StatusCodeTests(SimpleTestCase):
# Check if all page... |
"""
Detect Cube Sat and Processing Plant artifacts
"""
from datetime import timedelta
import os
from io import StringIO
from statistics import median
import cv2
import numpy as np
from pathlib import Path
from osgar.node import Node
from osgar.bus import BusShutdownException
from moon.moonnode import CAMERA_WIDTH, ... |
"""JSON implementations of osid records."""
# pylint: disable=no-init
# Numerous classes don't require __init__.
# pylint: disable=too-many-public-methods,too-few-public-methods
# Number of methods are defined in specification
# pylint: disable=protected-access
# Access to protected methods allowed in pack... |
# -*- coding: utf-8 -*-
from ... import arquivos
from . import blocos
from . import registros
from .blocos import Bloco0
from .blocos import BlocoB
from .blocos import BlocoC
from .blocos import BlocoD
from .blocos import BlocoE
from .blocos import BlocoG
from .blocos import BlocoH
from .blocos import BlocoK
from .blo... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/cloud/vision_v1/proto/geometry.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protob... |
from challenge import Challenge
import itertools
import numpy as np
import re
class ChallengeSolution(Challenge):
########################################################################
# Load data #
##############################################... |
import os
import time
import logging
from torch.autograd import Variable
from memcnn.utils.stats import AverageMeter, accuracy
from memcnn.utils.tensorboard import parse_logs
from tensorboardX import SummaryWriter
logger = logging.getLogger('trainer')
def validate(model, ceriterion, val_loader, use_cuda):
"""va... |
import sys
from twitter_scraping.cli import twitter_scraping
sys.exit(twitter_scraping())
|
from __future__ import annotations
import threading
import time
import logging
from random import uniform
from typing import Tuple
from dining_philosophers.constants import PhilosopherState
from dining_philosophers.forks import Fork
logger = logging.getLogger(__name__)
class Philosopher(threading.Thread):
EAT_T... |
"""
Example of module documentation which can be
multiple-lined
"""
from sqlalchemy import Column, Integer, String
from wopmars.Base import Base
class FooBase7(Base):
"""
Documentation for the class
"""
__tablename__ = "FooBase7"
id = Column(Integer, primary_key=True, autoincrement=False)
na... |
import logging
import hikari
import tanjun
from hikari.colors import Color
from avgamah.core import Client
from avgamah.modules.Utilities.embeds import EMBED_MENU
from avgamah.utils.utilities import get
from models import ColorModel
from . import color_dict, permissions
color_component = tanjun.Component()
COLOR_M... |
import argparse
import torch
import pdb
st = pdb.set_trace
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Extract factor/eigenvectors of latent spaces using closed form factorization"
)
parser.add_argument(
"--out", type=str, default="factor.pt", help="name of t... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from typi... |
# 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... |
opener = '\nif ( <fytbk_advance_line>({:d}) ) then\n'
closer = '\nend if\n'
def open_line(lineno):
return opener.format(lineno)
def close_line():
return closer
|
from django.db import models
from authors.apps.authentication.models import User
class Profile(models.Model):
"""Model for creating User profile"""
profile_user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.CharField(max_length=100, default="")
image = models.URLField(max_length... |
"""Code to run integration tests for the pizza cutter.
We are going to coadd a Gaussian blob with various WCS models and
masking effects.
Things the code does:
1. We will define a few noise bits to check various code features
SIM_BMASK_BAD 2**0 # images that have a bad pixel
SIM_BMAS... |
"""Generated client library for ml version v1."""
# NOTE: This file is autogenerated and should not be edited by hand.
from apitools.base.py import base_api
from googlecloudsdk.third_party.apis.ml.v1 import ml_v1_messages as messages
class MlV1(base_api.BaseApiClient):
"""Generated client library for service ml ver... |
"""
erodedImage = cv2.morphologyEx(maskedImage, cv2.MORPH_ERODE, kernel)
cv2.imshow("Eroded Image", erodedImage)
dilatedImage = cv2.morphologyEx(maskedImage, cv2.MORPH_DILATE, kernel)
cv2.imshow("Dilated Image", dilatedImage)
filledImage = openedImage.copy()
h, w = openedImage.shape[:2]
mask = np.zeros((h+2, w+2), np.... |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 26 16:36:47 2021
@author: utente
"""
#
#
#
# Run everything by running this script.
# For me it works best to click "Run" -> "Run Without Debugging" for that.
# Also the game window always opend behind the editor for some reason.
#
# Please not that right now 'moves_till... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
def dyenname_to_languagedata(apps, schema_editor):
# move (possible) contents of the DyenName table to
# Language.data["dyen_name"] in preparation for dropping
# DyenName table
DyenName = apps.get_model("l... |
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import json
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
#pathToDataFile = '~/data/clean_data.csv'
pathToDataFile = '~/data/heart.csv'
data = pd.read_csv(pathToDataFile)
msk = np.random.rand(len(data)) < 0.8
train = ... |
# -*- coding: utf-8 -*-
from sense_hat import SenseHat
import numpy as np
from configholder import configholder
# ----- Configuration -----
config_data = configholder.get_config_data()
use_led_matrix = configholder.get_use_led_matrix()
# ----- The X -----
npcolor2 = np.array([0, 208, 193])
npcolor3 = np.array([... |
import os
from argparse import ArgumentParser
from cbm3_aws import log_helper
from cbm3_aws.aws import resources
def main():
parser = ArgumentParser(
description="Deploy a cbm3_aws cluster for processing CBM3 runs")
parser.add_argument(
"--region_name", required=True,
help="The regio... |
from __future__ import print_function
import sys, hashlib, time, threading, socket, signal, os, re
import random, sqlite3, requests, pickle, feedparser
try:
import queue
except ImportError:
import Queue as queue
try:
import urllib.parse as urlparse
except ImportError:
import urlparse
from . import param, norma... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.