content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
# Lint as: python3
# Copyright 2020 Google LLC. 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 ... | python |
import math, sys
from konlpy.tag import Okt
class BayesianFilter:
def __init__(self):
self.words=set()
self.word_dict={}
self.category_dict={}
def fit(self, text, category):
'''
텍스트를 읽어 학습
'''
pos=self.split(text)
for word in pos:
... | python |
"""Role testing files using testinfra."""
def test_kubelet_package(host):
kubelet = host.package("kubelet")
assert kubelet.is_installed
assert kubelet.version.startswith("1.21")
def test_kubelet_service(host):
kubelet = host.service("kubelet")
assert kubelet.is_running
assert kubelet.is_enab... | python |
'''entre no sistema com dois valores e saia com a soma entre eles'''
v1 = int(input('Digite o primeiro valor: '))
v2 = int(input('Digite o segundo valor: '))
print('A soma de {} + {} = {} '.format(v1, v2, v1 + v2))
print('Acabou!')
| python |
import tskit
import tszip
import matplotlib.pyplot as plt
import numpy as np
site_ts = str(snakemake.input.site_ts)
plot_path = str(snakemake.output.plot)
ts = tszip.decompress(site_ts)
for x in range(len(ts.populations())):
y = ts.tables.nodes.time[np.where(ts.tables.nodes.population==x)[0]]
plt.plot(np.lo... | python |
# import os
# import sys
# TEST_DIR = os.path.dirname(os.path.abspath(__file__))
# PROJECT_DIR = os.path.abspath(os.path.join(TEST_DIR, os.pardir, 'api'))
# sys.path.insert(0, PROJECT_DIR)
| python |
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program 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 2
# of the License, or (at your option) any later version.
#
# This program is distrib... | python |
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
import unittest as ut
import os.path
import stripeline.timetools as tt
import numpy as np
class TestTimeTools(ut.TestCase):
def testSplitTimeRangeSimple(self):
'''Test split_time_range against a very simple input'''
result = tt.split_time_range(
... | python |
#!/usr/bin/env pypy
import sys
from random import *
if len(sys.argv) < 3:
print "Usage: ", sys.argv[0], " [N] [M]"
exit(-1)
n = int(sys.argv[1])
m = int(sys.argv[2])
CMAX = 100
print n, m
assert m >= n - 1
for v in range(2, n + 1):
u = randrange(1, v)
w = randint(1, CMAX)
print u, v, w
for i i... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 23 15:24:53 2019
@author: melisa
"""
import pandas as pd
import logging
import server as connect
import math
# Paths
analysis_states_database_path = 'references/analysis/analysis_states_database.xlsx'
backup_path = 'references/analysis/backup/'
p... | python |
import sqlite3
con = sqlite3.connect("danbooru2019.db")
con.isolation_level = None
cur = con.cursor()
buffer = ""
print ("Enter your SQL commands to execute in sqlite3; terminated with semicolon (;)")
print ("Enter a blank line to exit.")
while True:
line = input()
if line == "":
break
buffer +=... | python |
from __future__ import division
from builtins import zip
from builtins import range
from builtins import object
__all__ = [
'NegativeBinomial', 'NegativeBinomialFixedR', 'NegativeBinomialIntegerR2',
'NegativeBinomialIntegerR', 'NegativeBinomialFixedRVariant',
'NegativeBinomialIntegerRVariant', 'NegativeBino... | python |
from setuptools import find_packages, setup
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setup(
name="py-royale",
version="0.1.0",
author="Kenan Džindo",
description="Asynchronous wrapper for the official Supercell Clash Royale API.",
long_description=long_... | python |
print('=== DESAFIO 011 ===')
print('Faça um programa que leia a largura e a altura de uma parede em metros, calcule a sua área \ne a quantidade de tinta necessária para pintá-la, sabendo que cada litro de tinta pinta uma área de 2m²:')
L = float(input('Digite a largura da parede: '))
A = float(input('Digite a altura d... | python |
from pad import pad1d, pad2d
def map_sequence(seq, sequence_map, unk_item_id):
""" Transform a splitted sequence of items into another sequence of items
according to the rules encoded in the dict item2id
seq: iterable
sequence_map: dict
unk_item_id: int"""
item_ids = []
for i... | python |
import argparse
from preprocess import preprocess
import os
from pathlib import Path
import wave
import numpy as np
import unicodedata
import random
from tqdm import tqdm
import re
import yaml
import sys
import librosa
## Fairseq 스타일로 변환하기
def get_parser():
parser = argparse.ArgumentParser()
parser.add_argumen... | python |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: github.com/metaprov/modelaapi/services/modelpipelinerun/v1/modelpipelinerun.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from ... | python |
import os.path
import re
from setuptools import setup
(__version__, ) = re.findall("__version__.*\s*=\s*[']([^']+)[']",
open('toms/__init__.py').read())
HERE = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(HERE, "README.md")) as fid:
README = fid.read()
setup(
... | python |
from dataclasses import dataclass, field
from typing import List
__NAMESPACE__ = "NISTSchema-SV-IV-list-time-pattern-3-NS"
@dataclass
class NistschemaSvIvListTimePattern3:
class Meta:
name = "NISTSchema-SV-IV-list-time-pattern-3"
namespace = "NISTSchema-SV-IV-list-time-pattern-3-NS"
value: L... | python |
from enum import Enum
class Colors(Enum):
GREEN = "#00C2A4"
PINK = "#FD5383"
PURPLE = "#8784FF"
BLUE_1 = "#1B2A4D"
BLUE_2 = "#384B74"
BLUE_3 = "#8699B7"
class ColorPalettes(Enum):
CATEGORY = [
Colors.BLUE_1.value,
Colors.GREEN.value,
Colors.PURPLE.value,
C... | python |
from .test_controller import JsonController, JsonArrayController, TemplateController
| python |
"""
This file is a meant to make custom frame work like set up.
It will enable us to have a enpoints/routes for our API without
using a framework like flask or Django.
We will use WebOb to create a request and response object which
is centered around the WSGI model.
For more info https://docs.pylonsproject.org/projec... | python |
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 4 18:14:29 2016
@author: becker
"""
import numpy as np
import numpy.linalg as linalg
from simfempy import fems
from simfempy.meshes.simplexmesh import SimplexMesh
import scipy.sparse as sparse
#=================================================================#
class Fe... | python |
"""
Module: 'uzlib' on esp8266 v1.9.3
"""
# MCU: (sysname='esp8266', nodename='esp8266', release='2.0.0(5a875ba)', version='v1.9.3-8-g63826ac5c on 2017-11-01', machine='ESP module with ESP8266')
# Stubber: 1.1.2 - updated
from typing import Any
class DecompIO:
""""""
def read(self, *argv) -> Any:
pas... | python |
import sys
from random import randint
import pytest
from src.app.main.model_centric.cycles.worker_cycle import WorkerCycle
from src.app.main.model_centric.processes.fl_process import FLProcess
from . import BIG_INT
from .presets.fl_process import (
AVG_PLANS,
CLIENT_CONFIGS,
CYCLES,
MODELS,
PROTOC... | python |
# -*- coding: utf-8 -*-
#########################################################################
#
# Copyright (C) 2018 OSGeo
#
# This program 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 ... | python |
"""Define the API serializers."""
| python |
__version__='1.0.3'
| python |
import os
import featuretools as ft
import pandas as pd
from vbridge.utils.directory_helpers import exist_entityset, load_entityset, save_entityset
from vbridge.utils.entityset_helpers import remove_nan_entries
def create_entityset(dataset_id, entity_configs, relationships, table_dir, load_exist=True,
... | python |
src = Split('''
rec_libc.c
rec_main.c
''')
component = aos_component('recovery', src)
component.add_global_includes('.')
| python |
import django
import sys,os
rootpath = os.path.dirname(os.path.realpath(__file__)).replace("\\","/")
rootpath = rootpath.split("/apps")[0]
# print(rootpath)
syspath=sys.path
sys.path=[]
sys.path.append(rootpath) #指定搜索路径绝对目录
sys.path.extend([rootpath+i for i in os.listdir(rootpath) if i[0]!="."])#将工程目录下的一级目录添加到python搜索路... | python |
""" The model train file trains the model on the download dataset and other parameters specified in the assemblyconfig file
The main function runs the training and populates the created file structure with the trained model, logs and plots
"""
import os
import sys
current_path=os.path.dirname(__file__)
parentdir = os.... | python |
#FLM: Calculate GCD of selected glyphs
# Description:
# Calculate the Greatest Common Denominator of selected glyphs
# Credits:
# Pablo Impallari
# http://www.impallari.com
# Dependencies
import fractions
from robofab.world import CurrentFont
# Clear Output windows
from FL import *
fl.output=""
# Fun... | python |
# Discord Packages
import discord
from discord.ext import commands
# Bot Utilities
from cogs.utils.db import DB
from cogs.utils.db_tools import get_user, get_users
from cogs.utils.defaults import easy_embed
from cogs.utils.my_errors import NoDM
from cogs.utils.server import Server
import asyncio
import operator
impor... | python |
from pybrain.structure.modules.linearlayer import LinearLayer
from pybrain.structure.moduleslice import ModuleSlice
from pybrain.structure.connections.identity import IdentityConnection
from pybrain.structure.networks.feedforward import FeedForwardNetwork
from pybrain.structure.connections.shared import MotherConnectio... | python |
from uuid import uuid4
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy_utils import (
UUIDType,
URLType,
)
db = SQLAlchemy()
class Tag(db.Model):
__tablename__ = 'tag'
object_id = db.Column('id', UUIDType(), primary_key=True, default=uuid4)
value = db.Column(db.String(40))
post =... | python |
import subprocess
import os
import json
def main():
files = os.listdir("./processed")
if os.path.isfile("concate.jsonl"):
return
pd = [[],[],[]]
for fn in files:
source = os.path.join("./processed", fn)
with open(source, "r") as f:
d = json.load(f)
pd[... | python |
"""
日 K 範例程式
"""
import asyncio
try:
from skcom.receiver import AsyncQuoteReceiver as QuoteReceiver
except ImportError as ex:
print('尚未生成 SKCOMLib.py 請先執行一次 python -m skcom.tools.setup')
print('例外訊息:', ex)
exit(1)
async def on_receive_kline(kline):
"""
處理日 K 資料
"""
# TODO: 在 Git-Bash ... | python |
#!/usr/bin/env python3
# file://mkpy3_util.py
# Kenneth Mighell
# SETI Institute
def mkpy3_util_str2bool(v):
"""Utility function for argparse."""
import argparse
if v.lower() in ("yes", "true", "t", "y", "1"):
return True
elif v.lower() in ("no", "false", "f", "n", "0"):
return Fals... | python |
import asyncio
import os
import sys
from os.path import realpath
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler as EventHandler
from watchdog.events import FileSystemEvent as Event
# Event handler class for watchdog
class Handler(EventHandler):
# Private
_fut... | python |
# pip3 install https://github.com/s4w3d0ff/python-poloniex/archive/v0.4.6.zip
from poloniex import Poloniex
polo = Poloniex()
# Ticker:
print(polo('returnTicker')['BTC_ETH'])
# or
print(polo.returnTicker()['BTC_ETH'])
# Public trade history:
print(polo.marketTradeHist('BTC_ETH'))
# Basic Private Setup (Api key/sec... | python |
"""
In the 20×20 grid below, four numbers along a diagonal line have been marked in red.
<GRID MOVED TO MAIN>
The product of these numbers is 26 × 63 × 78 × 14 = 1788696.
What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid?
"""
import mat... | python |
import unittest #importing unittest module
from credential import Credential # importing class Credential
import pyperclip # importing pyperclip module
class TestCredential(unittest.TestCase):
"""
Test class that defines the test cases for the credential class behaviours
Args:
unittest.TestCas... | python |
class KeystoneAuthException(Exception):
""" Generic error class to identify and catch our own errors. """
pass
| python |
import os
import numpy as np
import matplotlib.pyplot as plt
import networkx as nx
from torch_geometric.utils import to_networkx
def draw_nx_graph(G, name='Lobster', path='./visualization/train_nxgraph/'):
fig = plt.figure(figsize=(12,12))
ax = plt.subplot(111)
ax.set_title(name, fontsize=10)
nx.draw(G... | python |
from .xgb import XgbParser
from .lgb import LightgbmParser
from .pmml import PmmlParser | python |
from . bitbucket import BitBucket
| python |
# -*- coding: utf-8 -*-
import pickle
from os import path, makedirs
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.http import MediaIoBaseDownload
import io
import pathlib
from datetime... | python |
import unittest
from conjur.data_object.user_input_data import UserInputData
class UserInputDataTest(unittest.TestCase):
def test_user_input_data_constructor(self):
mock_action = None
mock_user_id = None
mock_new_password = None
user_input_data = UserInputData(action=mock_action, ... | python |
#!/usr/bin/env python3
######################################################################
## Author: Carl Schaefer, Smithsonian Institution Archives
######################################################################
import re
import wx
import wx.lib.scrolledpanel as scrolled
import db_access as dba
import dm... | python |
from django.urls import path
from .views import (
FlightListView,
FlightDetailView,
FlightUpdateView,
HomePageView,
search_results_view,
contact_view,
FlightCreateView,
FlightDeleteView,
AllFlightView,
EachFlightDetail,
)
urlpatterns = [
path('flights/list/', FlightListView.as_view(), name='flights_list'),... | python |
#!/usr/bin/env python
#encoding: utf-8
#####################################################################
########################## Global Variables #########################
#####################################################################
## Define any global variables here that do not need to be changed ##
... | python |
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.decorators import user_passes_test
from django.urls import reverse
import csv
from .serializers import DaySerializer
from rest_framework.views import APIView
from rest_framework.response import Response
import datetime
import calendar... | python |
import logging
from abc import abstractmethod
from datetime import datetime
import json
from dacite import from_dict
from os.path import join
from airflow.models.dag import DAG
from airflow.operators.python_operator import PythonOperator
from airflow.providers.google.cloud.hooks.gcs import GCSHook
from airflow.provide... | python |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# -----------------------------------------------------------------------... | python |
def shift(string):
for c in string:
print(chr(ord(c) + 2))
shift(input("Inserisci la stringa: ")) | python |
# Sphinx extension to insert the last updated date, based on the git revision
# history, into Sphinx documentation. For example, do:
#
# .. |last_updated| last_updated::
#
# *This document last updated:* |last_updated|.
import subprocess
from email.utils import parsedate_tz
from docutils import nodes
from sphinx.... | python |
##############################################################################
# Copyright 2009, Gerhard Weis
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code ... | python |
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import json
from auth import TwitterAuth
#Very simple (non-production) Twitter stream example
#1. Download / install python and tweepy (pip install tweepy)
#2. Fill in information in auth.py
#3. Run as: python streami... | python |
# -*- coding: utf-8 -*-
import os
import sys
import copy
import random
import numpy as np
import torch
from torchvision import transforms
from .datasets import register_dataset
import utils
@register_dataset('VisDA2017')
class VisDADataset:
"""
VisDA Dataset class
"""
def __init__(self, name, img_dir, LDS_type, i... | python |
# Sample PySys testcase
# Copyright (c) 2015-2016 Software AG, Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, and/or its subsidiaries and/or its affiliates and/or their licensors.
# Use, reproduction, transfer, publication or disclosure is prohibited except as specifically provided for in your Licens... | python |
from selenium import webdriver
from selenium.webdriver import ActionChains
driver = webdriver.Chrome() # give executabe_path = "driver_.exe" path
driver.get("https://swisnl.github.io/jQuery-contextMenu/demo.html")
driver.maximize_window() # maximze the window
button = driver.find_element_by_xpath("/html/body/div/s... | python |
import pytest
import tfchain
from stubs.ExplorerClientStub import TFChainExplorerGetClientStub
def test():
# create a tfchain client for testnet
c = tfchain.TFChainClient.TFChainClient(network_type="testnet")
# (we replace internal client logic with custom logic as to ensure we can test without requirin... | python |
from collections import defaultdict
from datetime import datetime
from schemas import Task, TaskStatus
tasks_db = defaultdict(lambda: defaultdict(dict))
def current_datetime_str():
now = datetime.now()
day_mon_date = now.strftime("%a, %b, %d")
today = now.strftime('%Y%m%d')
hr = now.strftime("%-H")
... | python |
from django import forms
from .models import User
class StudentRegistration(forms.ModelForm):
class Meta:
model=User
fields=['name','email','password']
widgets={
'name':forms.TextInput(attrs={'class':'form-control'}),
'email':forms.EmailInput(attrs={'class':'f... | python |
# -*- coding:utf8 -*-
""" SCI - Simple C Interpreter """
from ..lexical_analysis.token_type import ID
from ..lexical_analysis.token_type import XOR_OP, AND_OP, ADD_OP, ADDL_OP, SUB_OP, MUL_OP
from ..lexical_analysis.token_type import NOT_OP, NEG_OP, DEC_OP, INC_OP
from ..lexical_analysis.token_type import LEA_OP
from ... | python |
#=========================================================================
# helpers.py
#=========================================================================
# Author : Christopher Torng
# Date : June 2, 2019
#
import os
import yaml
#-------------------------------------------------------------------------
# U... | python |
from engine import Engine
from engine import get_engine | python |
#!/usr/bin/python
#----------------------------------------------------------------------
# Copyright (c) 2008 Board of Trustees, Princeton University
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and/or hardware specification (the "Work") to
# deal in the Work wit... | python |
import threading
import time
import queue
EXIT_FLAG = 0
class exampleThread(threading.Thread):
def __init__(self, threadID, name, q):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.q = q
def run(self):
print("Starting... | python |
# -*- coding: utf-8 -*-
# Copyright (c) 2010-2016, MIT Probabilistic Computing Project
#
# 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... | python |
"""Class and container for pedigree information, vcf, and bam file by sample"""
from future import print_function
import pandas as pd
import re
import func
class Ped:
"""Family_ID - '.' or '0' for unknown
Individual_ID - '.' or '0' for unknown
Paternal_ID - '.' or '0' for unknown
Maternal_ID - '.' or ... | python |
#!/usr/bin/env python3
#
# Copyright (c) 2016-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
... | python |
"""Main code for training. Probably needs refactoring."""
import os
from glob import glob
import dgl
import pandas as pd
import pytorch_lightning as pl
import sastvd as svd
import sastvd.codebert as cb
import sastvd.helpers.dclass as svddc
import sastvd.helpers.doc2vec as svdd2v
import sastvd.helpers.glove as svdg
imp... | python |
# Generated by Django 4.0 on 2021-12-17 12:12
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('src', '0012_alter_articlecategory_options_article_slug_and_more'),
('src', '0013_alter_product_description_alter_product_name'),
]
operations = [
... | python |
from hallo.events import EventInvite
from hallo.function import Function
import hallo.modules.channel_control.channel_control
from hallo.server import Server
class Invite(Function):
"""
IRC only, invites users to a given channel.
"""
def __init__(self):
"""
Constructor
"""
... | python |
from die import Die
import pygal
die_1 = Die()
die_2 = Die()
results = []
for roll_num in range(1000):
result = die_1.roll() + die_2.roll()
results.append(result)
#分析结果
frequencies = []
max_result = die_1.num_sides + die_2.num_sides
for value in range(2,max_result+1):
#results.count()查每个值出现的次数
frequen... | python |
from .index import index
from .village import village
from .voice import voice
from .confirm_voice import confirm_voice
from .selectstyle import selectstyle
| python |
try:
from .secrets import *
except ImportError:
import sys
sys.exit('secrets.py settings file not found. Please run `prepare.sh` to create one.')
from .server import *
#
# Put production server environment specific overrides below.
#
COWRY_RETURN_URL_BASE = 'https://onepercentclub.com'
COWRY_LIVE_PAYMENT... | python |
from django.db import models
import addons.myminio.settings as settings
from addons.base import exceptions
from addons.base.models import (BaseOAuthNodeSettings, BaseOAuthUserSettings,
BaseStorageAddon)
from addons.myminio import SHORT_NAME, FULL_NAME
from addons.myminio.provider import... | python |
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.11.1
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# %%
import yaml
imp... | python |
import os, sys
sys.path.append(os.path.join(os.environ['GGP_PATH'], 'analogy','rule_mapper'))
sys.path.append(os.path.join(os.environ['GGP_PATH'], 'analogy','test_gen'))
import gdlyacc
from GDL import *
from PositionIndex import PositionIndex
import rule_mapper2
import psyco
# constants to ignore, along with numbers
... | python |
# This file is subject to the terms and conditions defined in
# file 'LICENSE', which is part of this source code package.
import subprocess
import re
import numpy as np
def main():
m = 100
for methodIndex in range(18):
for n in (10, 32, 100, 316, 1000, 3162, 10000):
data = []
... | python |
#!/usr/bin/env python3
# testPyComments.py
""" Test functioning of Python line counters. """
import unittest
from argparse import Namespace
from pysloc import count_lines_python, MapHolder
class TestPyComments(unittest.TestCase):
""" Test functioning of Python line counters. """
def setUp(self):
p... | python |
import binascii
import time
from typing import List, Tuple, Union, cast
logging = True
loggingv = False
_hex = "0123456789abcdef"
def now():
return int(time.monotonic() * 1000)
def log(msg: str, *args: object):
if logging:
if len(args):
msg = msg.format(*args)
print(msg)
def l... | python |
# -*- coding: utf-8 -*-
"""Pih2o utilities.
"""
import logging
LOGGER = logging.getLogger("pih2o")
| python |
# Code generated by `typeddictgen`. DO NOT EDIT.
"""V1beta1PodDisruptionBudgetStatusDict generated type."""
import datetime
from typing import TypedDict, Dict
V1beta1PodDisruptionBudgetStatusDict = TypedDict(
"V1beta1PodDisruptionBudgetStatusDict",
{
"currentHealthy": int,
"desiredHealthy": int... | python |
import sys
import os
from src.model.userManagement import getLeaderBoard
import configparser
from discord import Client, Message, Guild, Member
from pymysql import Connection
from src.utils.readConfig import getLanguageConfig
languageConfig = getLanguageConfig()
async def getLeaderBoardTop10(self: Client, message: M... | python |
# Copyright 2019 Graphcore Ltd.
# coding=utf-8
"""
Derived from
https://www.tensorflow.org/probability/api_docs/python/tfp/mcmc/HamiltonianMonteCarlo
"""
import tensorflow as tf
from tensorflow.contrib.compiler import xla
import tensorflow_probability as tfp
import time
try:
from tensorflow.python import ipu
d... | python |
#!/usr/bin/env python
import os
# Clear the console.
os.system("clear")
def msg(stat):
print '\033[1;42m'+'\033[1;37m'+stat+'\033[1;m'+'\033[1;m'
def newline():
print ""
def new_hosts(domain):
msg(" What would be the public directory name? \n - Press enter to keep default name (\"public_html\") ")
p... | python |
from __future__ import print_function
import os
import unittest
import numpy as np
from sklearn.utils.testing import assert_array_almost_equal
from autosklearn.data.abstract_data_manager import AbstractDataManager
dataset_train = [[2.5, 3.3, 2, 5, 1, 1],
[1.0, 0.7, 1, 5, 1, 0],
[1.... | python |
# -*- coding: utf-8 -*-
__author__ = 'Grzegorz Latuszek, Michal Ernst, Marcin Usielski'
__copyright__ = 'Copyright (C) 2018-2019, Nokia'
__email__ = 'grzegorz.latuszek@nokia.com, michal.ernst@nokia.com, marcin.usielski@nokia.com'
import pytest
def test_device_directly_created_must_be_given_io_connection(buffer_conn... | python |
# Copyright 2022 Google 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 in writing, ... | python |
import mpmath
from mpsci.distributions import benktander1
def test_pdf():
with mpmath.workdps(50):
x = mpmath.mpf('1.5')
p = benktander1.pdf(x, 2, 3)
# Expected value computed with Wolfram Alpha:
# PDF[BenktanderGibratDistribution[2, 3], 3/2]
valstr = '1.090598817302604... | python |
from django import forms
from django.contrib.auth.forms import UserCreationForm
from .models import Comment, Webpage, Template, User
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['title', 'content']
class WebpageForm(forms.ModelForm):
class Meta:
model = ... | python |
import unittest
import os
from examples.example_utils import delete_experiments_folder
from smallab.runner.runner import ExperimentRunner
from smallab.runner_implementations.fixed_resource.simple import SimpleFixedResourceAllocatorRunner
from smallab.specification_generator import SpecificationGenerator
from smallab.... | python |
import os
import torch
import argparse
import numpy as np
import torch.nn.functional as F
from torch.autograd import Variable
import torch.backends.cudnn as cudnn
from model import * # NOTE : Import all the models here
from utils import progress_bar
# NOTE : All parser related stuff here
parser = argparse.ArgumentPa... | python |
#
# Copyright (c) 2005-2006
# The President and Fellows of Harvard College.
#
# 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 retain the above copyright
# notice, this li... | python |
num = int(input('Digite um número inteiro: '))
if (num % 2) == 0:
print('O número escolhido é PAR.')
else:
print('O número escolhido é ÍMPAR')
| python |
#!/usr/bin/env python3
import subprocess
from deoplete.source.base import Base
class Source(Base):
def __init__(self, vim):
super().__init__(vim)
# deoplete related variables
self.rank = 1000
self.name = "cmake"
self.mark = "[cmake]"
self.input_pattern = r"[^\w\s]... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.