content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
""".. moduleauthor:: Artur Lissin"""
from typing import Dict, Final
from bann.b_frameworks.pytorch.p_truth.implementation.matrix_distance import TruthMSimClass
from bann.b_frameworks.pytorch.p_truth.implementation.one_class import TruthOneClass
from bann.b_frameworks.pytorch.interfaces.truth_in... |
#!/usr/bin/python
#
# -*- coding: utf-8 -*-
# vim: set ts=4 sw=4 et sts=4 ai:
import atexit
import cStringIO as StringIO
import json as simplejson
import os
import platform
import pprint
import re
import socket
import sys
import time
import urllib2
import zipfile
import argparse
parser = argparse.ArgumentParser()
pa... |
from django.db import models
from django.contrib.auth.models import User
class Student(models.Model):
user=models.OneToOneField(User,on_delete=models.CASCADE)
mobile = models.CharField(max_length=20,null=False)
@property
def get_name(self):
return self.user.first_name+" "+self.user.last_name
... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
import numpy as np
import pandas as pd
import logging
from scipy import sparse
from reco_utils.common.python_utils import (
jaccard,
lift,
exponential_decay,
get_top_k_scored_items,
)
from reco_utils.common ... |
#!/bin/env python3
import re
from typing import List
import numpy as np
import matplotlib.pyplot as plt
filtered_users = ["join-backup", "join-slave", "ucs-sso"]
filtered_groups = ["computers", "dc backup hosts", "dc slave hosts"]
class LDAPUser:
name: str
def __init__(self, name):
self.name = name
... |
"""This module is the core of the library, containing the definitions of the
low-level components and architectures."""
import numpy as np
from .util import *
class Gate:
"""
This represents a gate used for delay-based PUFs. The gate is instantiated
with an RNG that should represent the PDF that models t... |
from django.contrib.auth.signals import user_logged_out
from django.dispatch import receiver
@receiver(user_logged_out)
def logged_out_handler(sender, **kwargs):
"""
User logout signal
"""
from .backends import reset_api_auth
reset_api_auth()
|
import matplotlib.pyplot as plt
import yfinance as yf
stock = yf.download('FB', start = '2011-1-1', end = '2021-1-1')
close = stock['Close']
plt.xticks([])
plt.yticks([])
plt.plot(close)
plt.show()
|
""" cgiLib.py : A library of helper functions for CGI scripts.
"""
import logging, cgitb, cgi, Cookie, time, os
import config
def initLogging(logFilename):
""" Initialize the logging module.
"""
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s: %(levelname)s: %(message)s',
... |
import logging
from contracts_lib_py.utils import process_fulfill_condition
from nevermined_sdk_py.nevermined.keeper import NeverminedKeeper as Keeper
logger = logging.getLogger(__name__)
def fulfill_lock_payment_condition(event, agreement_id, price, consumer_account, lock_condition_id):
"""
Fulfill the lo... |
#
# PySNMP MIB module ICF-VG-RPTR (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ICF-VG-RPTR
# Produced by pysmi-0.3.4 at Wed May 1 13:35:52 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 0... |
from django.contrib import admin
from .models import Event, Talk, Speaker
@admin.register(Event)
class EventModelAdmin(admin.ModelAdmin):
list_display = ['title', 'date_start', 'start', 'description']
@admin.register(Talk)
class TalkModelAdmin(admin.ModelAdmin):
list_display = ['title', 'date_start', 'start... |
import gdb
try:
top_stack = gdb.newest_frame()
iter = gdb.FrameIterator.FrameIterator(top_stack)
final_stack_str = ''
for frame in iter:
frame_name = frame.name()
if frame_name is None:
frame_name = '??noname??'
sal = frame.find_sal()
line = sal.line
... |
# -*- coding: utf-8 -*-
from locoresponse import LocoResponse
from locomember import *
class LocoMemberResponse(LocoResponse):
def chat_id(self):
return self._data["chatId"]
def members(self):
return map(LocoMember, self._data["members"])
|
"""
Model with function to validate the args
"""
import sys
def validate_args(args):
"""
Function to validate the args
"""
if len(args) == 2:
try:
args = int(args[1])
except ValueError:
print(f"Error: wrong argument {args[1]}, it should be an integer")
... |
#%%
#Import Required Libraries
try:
import cv2
import numpy as np
import face_recognition
import warnings
import os
from datetime import datetime
print("---Libraries Imported Successfully---")
DeprecationWarning("ignore")
except:
print("---Libraries Not Imported---")
# %%
#Change D... |
from seqviz import TaggedSequence
def test_from_iob1_simple():
data = [
("Alex", "I-PER"),
("is", "O"),
("going", "O"),
("to", "O"),
("Los", "I-LOC"),
("Angeles", "I-LOC"),
("in", "O"),
("California", "I-LOC"),
]
seq = TaggedSequence.from_bi... |
from doubly_linked_list import DoublyLinkedList
__all__=[DoublyLinkedList]
|
#!/usr/bin/env python
from __future__ import print_function
from cv_bridge import CvBridge, CvBridgeError
from sensor_msgs.msg import CameraInfo
from sensor_msgs.msg import Image
import cv2
import message_filters
import rospy
import sys
import time
import copy
import roslib
import numpy as np
import rospkg
class Cor... |
"""
Django settings for SuperB project.
Generated by 'django-admin startproject' using Django 3.2.7.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib ... |
%matplotlib inline
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
import sklearn.datasets
import tensorflow as tf
from tensorflow.python.framework.ops import reset_default_graph
# Do not worry about the code below for now, it is used for plotting later
def plot_decision_boundary(pred_func, X, y):... |
# Compiler settings for running the tests on a simulated atmega1284.
def set_avr_platform(env):
native = env.Clone()
native.Append(LIBS = ["simavr", "libelf"], CFLAGS = "-Wall -Werror -g")
runner = native.Program("build/run_test", "site_scons/platforms/avr/run_test.c")
env.Replace(EMBEDDED = "AVR"... |
from collections import defaultdict
import glob
import os
from typing import Dict, List
import numpy as np
import pandas as pd
from scipy.stats import mannwhitneyu, shapiro
from analysis.utils import order_columns_of_df
DATA_PATH = "runs/v10/models"
def pretty(li, decimal: int = 2):
assert len(li) == 5
return... |
import django
from django_opentracing.db.common import DatabaseWrapperMixin
import psycopg2.extensions
if django.VERSION >= (1, 9):
from django.db.backends.postgresql import base
else:
from django.db.backends.postgresql_psycopg2 import base
class DatabaseFeatures(base.DatabaseFeatures):
"""Our database... |
import abc
import sys
NewPython = sys.version_info[0] > 3 or (sys.version_info[0] == 3 and sys.version_info[1] > 3)
if (NewPython):
from enum import IntFlag
class TpmEnum(IntFlag):
pass
class TpmMarshaller(abc.ABC):
'Base interface for all marshalable non-trivial TPM data types'
... |
from __future__ import annotations
from ..typing import *
from .object import TES3Object
from .enums import EffectId, EffectSchool
class MagicEffect(TES3Object):
flags1: u32
flags2: u32
effect_id: EffectId
data: MagicEffectData | None
icon: str | None
texture: str | None
bolt_sound: str |... |
"""A golden test to verify attribute default values."""
def _my_rule_impl(ctx):
return []
def _my_aspect_impl(target, ctx):
return []
my_aspect = aspect(
implementation = _my_aspect_impl,
doc = "This is my aspect. It does stuff.",
attr_aspects = ["deps", "attr_aspect"],
attrs = {
"_x"... |
# -*- coding: utf-8 -*-
# Authors: Victor Férat <victor.ferat@live.fr>
#
# License: BSD (3-clause)
import struct
import numpy as np
def read_is(filename):
"""Read Cartool inverse solution (.is) file.
Parameters
----------
filename : str or file-like
the Inerse solution file (.is) to read.
... |
import os
import schemas.clara_items.schema as clara_items_schema
import schemas.response_options.schema as response_options_schema
import schemas.student_classes.schema as student_classes_schema
import schemas.clara_responses.schema as clara_responses_schema
import schemas.whitelist.schema as whitelist_schema
CLARA_E... |
# -*- coding: utf-8 -*-
import pytest
from aws_tools.search.aws_res import reg
def test_register():
reg.get("ec2-instances").list_res()
if __name__ == "__main__":
import os
basename = os.path.basename(__file__)
pytest.main([basename, "-s", "--tb=native"])
|
from components import NavBar, Header, EmailInput, EmailIssueSelect, ProblemDescriptionInput, NameInput, Footer
import dash_html_components as html
import dash_bootstrap_components as dbc
from utils import UrlIndex
def Body():
return html.Div(
[
dbc.Spinner(html.Div(id='contact-form-modal-div'... |
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 14 01:09:46 2021
@author: Efe Kurdoğlu
"""
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from PIL import Image
from mss import mss
def onehot_labels(values):
label_encoder = LabelEncoder()
integer_encoded = label_encoder.fit_transfor... |
# coding: utf-8
from datetime import datetime
from typing import Optional
from domain.entities import ClickStatistics
from domain.interfaces import IShortenedLinkDAO, IClickStatisticsDAO
class TransitionResponse:
def __init__(
self,
is_target_url_founded: bool,
target_link: Optional[str]... |
"""retina_resnet50"""
import keras
from perceptron.zoo.retinanet_resnet_50 import models
import tensorflow as tf
def Retina_Resnet50(weights_file="resnet50_coco_best_v2.1.0.h5"):
from perceptron.utils.func import maybe_download_model_data
keras.backend.tensorflow_backend.set_session(get_session())
... |
import requests
import ast
asvr = "http://192.168.1.82:8520"
es = ast.literal_eval(requests.get(asvr+"/elements/type/tpm2").text)
for e in es:
el = ast.literal_eval(requests.get(asvr+"/element/"+e).text)
pl = ast.literal_eval(requests.get(asvr+"/policy/name/Check Credentials").text)
print("\n\nAttesting ... |
from ..models import Post
from ..serializers import PostSerializer
from rest_framework import viewsets, permissions
class PostViewSet(viewsets.ModelViewSet):
permission_classes = [
permissions.AllowAny
]
lookup_field = 'id'
serializer_class = PostSerializer
queryset = Post.objects.all()
|
import os
from pathlib import Path
from logic.apt import Apt
from logic.dnf import Dnf
class Facts:
def __init__(self):
self.HOME = None
self.PC = None
self.DE = None
self.GPU = None
self.package_manager = None
def collect_facts(self):
self.HOME = str(Path.hom... |
from flask import render_template
from . import app, db
@app.route('/')
def index():
app.logger.debug('DEBUG log message')
app.logger.info('INFO log message')
app.logger.warn('WARN log message')
app.logger.error('ERROR log message')
# Database connection test
result = None
try:
r... |
class ReportLayoutMetric:
def __init__(self, name: str, minimize: bool):
self.name = name
self.minimize = minimize
@staticmethod
def from_dict(data: dict):
name = data.pop('name')
minimize = data.pop('minimize')
assert len(data) == 0, f'Unknown parameter in ' \
... |
# Yu Zhang yz2729
# Lab 2 Date: 09/23/21
import RPi.GPIO as GPIO
import os
import time
CODERUN = True
def GPIO17_callback(channel):
print("Button 17 has been pressed")
cmd = 'echo "pause" > /home/pi/video_fifo'
print("Pause the Video")
os.system(cmd)
def GPIO22_callback(channel):
print("Button 22... |
from django.urls import path
from .views import Main
urlpatterns = [
path('home', Main),
]
|
import subprocess
#####################
# TESTED, ALL GOOD! #
#####################
#START UFW
#====================
subprocess.call("ufw allow ssh".split())
subprocess.call("ufw allow http".split())
subprocess.call("ufw deny 23".split())
subprocess.call("ufw default deny".split())
subprocess.call("ufw enable".split(... |
import datasets
def get_data(args):
dm = datasets.available_datasets[args.dataset_type](**vars(args))
dm.setup("fit")
dm.setup("test")
return dm, args
|
#!/usr/bin/env python
from SOAPpy import Config, HTTPTransport, SOAPAddress, WSDL
username = 'YOUR_USERNAME'
apiKey = 'YOUR_API_KEY'
wsdlFile = 'https://flightxml.flightaware.com/soap/FlightXML3/wsdl'
# This is a custom HTTP transport that allows Basic Authentication.
class myHTTPTransport(HTTPTransport):
username ... |
from .HeartbeatNetworkLayer import HeartbeatNetworkLayer |
#
# python_linter.py
# Part of SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Aparajita Fishman
#
# Project: https://github.com/SublimeLinter/SublimeLinter3
# License: MIT
#
"""This module exports the PythonLinter subclass of Linter."""
import importlib
import os
import re
from . import ... |
"""jc - JSON CLI output utility `id` command output parser
Usage (cli):
$ id | jc --id
or
$ jc id
Usage (module):
import jc.parsers.id
result = jc.parsers.id.parse(id_command_output)
Compatibility:
'linux', 'darwin', 'aix', 'freebsd'
Examples:
$ id | jc --id -p
{
"uid": {... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT license.
import re
from typing import Match, Pattern
from ._typing import Regex, Replacement
def compile_regex(regex: Regex) -> Pattern[str]:
if isinstance(regex, str):
return re.compile(regex)
else:
return ... |
### Function for Vader Analysis
import pandas as pd
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer
nltk.downloader.download('vader_lexicon')
analyser = SentimentIntensityAnalyzer()
# read VADER scores
def read_news_vader_path(df):
print('Reading in VADER datasets...')
cs = []
#... |
import numpy as np
import time
from math import log
import ftsc.sprl as sprl
from ftsc.solradm import solradm
from ftsc.aca import aca_symm
from ftsc.singular_values import calculate_best_relative_error_rank
from tests.plotting_utils import bar_plot, multiple_plot
from tests.tests_utils import create_cluster_problem,... |
import unittest
from sourced.ml.utils.engine import get_bblfsh_dependency, get_engine_package
class EngineTests(unittest.TestCase):
def test_bblfsh_dependency(self):
self.assertEqual(get_bblfsh_dependency("localhost"),
"spark.tech.sourced.bblfsh.grpc.host=localhost")
def tes... |
# Copyright (C) 2018-2021 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
from openvino.tools.mo.ops.elementwise import Div
from openvino.tools.mo.ops.transpose import Transpose
from openvino.tools.mo.front.common.partial_infer.utils import int64_array
from openvino.tools.mo.front.common.replacement import Fro... |
import graphene
from graphql_starter.db.link import Link
class LinkType(graphene.ObjectType):
id = graphene.Int()
url = graphene.String()
description = graphene.String()
class Query(graphene.ObjectType):
links = graphene.List(LinkType)
async def resolve_links(self, info):
all_links = a... |
from datetime import date
import datetime
#datetime.datetime(year=year,month=month,day=day,hour=hour)
def days_in_month(year, month):
return month.days
def is_valid_date(year, month, day):
tot_days = year.days+month.days+day
if tot_days == 365 or tot_days == 366:
return True
else:
return False
def days_betwe... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: group.py
#
# Copyright 2018 Costas Tyfoxylos
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without l... |
#!/usr/bin/python
# Copyright (c) 2020, 2021, Oracle and/or its affiliates.
# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
"""Provide Module Description
"""
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~#
__author__ =... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 CESNET Prague.
#
# CIS theses repository is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Schemas for marshmallow."""
from .dataset import DataSetMetadataSchemaV2
__all__ = 'DataSetMet... |
# not really sure the best way to test besides just visualizing some
# simulations and seeing if they make sense.
# TODO update and validate.
import numpy as np
import sys
sys.path.append("..")
import state_history
import scene
# for argparsing
def str2bool(v):
return v.lower() == "true"
import argparse
parser... |
class Solution(object):
# 暴力
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
maxArea = 0
for i, l in enumerate(height):
for j, r in enumerate(height):
if j <= i: continue
area = min(l, r) * (j - ... |
# -*- coding: utf-8 -*-
"""
Update object command group.
:author: Joe Joyce <joe@decafjoe.com>
:copyright: Copyright (c) Joe Joyce and contributors, 2016-2019.
:license: BSD
"""
from safe.app import safe
@safe(alias='up')
def update():
"""Update objects in the database."""
yield
|
from random import randint
num = (randint(1, 10), randint(1, 10), randint(1, 10),
randint(1, 10), randint(1, 10))
print('Os valores sorteados foram: ', end='')
for n in num:
print(f'{n} ', end='')
print(f'\nO maior valor é {max(num)}')
print(f'O menor valor é {min(num)}') |
class OmniMetricException(Exception):
pass
class TokenNotFoundException(OmniMetricException):
def __init__(self, message="Not token provided!"):
self.message = message
super().__init__(self.message)
|
#!/usr/bin/env python2
# --------------------------------------------------------------------------------------------------
# Alictf 2016 - VSS - Very Secure System (Pwn 100)
# --------------------------------------------------------------------------------------------------
import struct
import sys
import socket
impor... |
from itertools import product
from Tables import query
from .ImageHelper import *
get_width = lambda v: int(21 + 4*(v - 1))
def get_position_info(version:int) -> list:
width = get_width(version)
info = list()
color = [
[1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 1],
[1, 0, 1, 1, 1, 0... |
from typing import *
import numpy as np
from roosterize.sexp.SexpNode import SexpNode
class SexpString(SexpNode):
def __init__(self, content: str = None):
self._content = content if content is not None else ""
return
def __deepcopy__(self, memodict={}):
return SexpString(self.conte... |
#
# Autogenerated by Thrift Compiler (0.13.0)
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
# options string: py
#
from thrift.Thrift import TType, TMessageType, TFrozenDict, TException, TApplicationException
from thrift.protocol.TProtocol import TProtocolException
from thrift.TRecursive impo... |
import unittest
from os.path import join
from praatio import audio
from praatio.utilities import utils
from test.praatio_test_case import PraatioTestCase
class AudioTests(PraatioTestCase):
def test_get_audio_duration(self):
"""Tests that the two audio duration methods output the same value."""
w... |
from ampel import FsmEfe
import time
class AmpelFsm(FsmEfe):
pass
#ampel = FsmEfe("ROT", "GELB", "GRÜN", 10, 2, 10)
ampel2 = FsmEfe()
while True:
ampel2.kirmiziyi_yak()
ampel2.sariyi_yak()
ampel2.yesili_yak()
|
# container-service-extension
# Copyright (c) 2020 VMware, Inc. All Rights Reserved.
# SPDX-License-Identifier: BSD-2-Clause
import pyvcloud.vcd.client as vcd_client
from container_service_extension.client.metadata_based_ovdc import MetadataBasedOvdc # noqa: E501
from container_service_extension.client.policy_based_... |
# SCC
def strongly_connected_component(G: list) -> list:
n = len(G)
G_rev = [[] for i in range(n)]
for i in range(n):
for v in G[i]:
G_rev[v].append(i)
vs = []
visited = [False] * n
def dfs(v):
visited[v] = True
for u in G[v]:
if not visited[u]:
dfs(u)
vs.append(v)
for i in range(n):
if not v... |
#!/usr/bin/env python3
# vim: aw:sts=4:ts=4:sw=4:et:cin:fdm=manual:tw=120:ft=python
# autowrite, softtabstop, tabstop, shiftwidth, expandtab, cindent, foldmethod, textwidth, filetype
import argparse
from pathlib import Path
import os
import random
import re
import shlex
from subprocess import run, CalledProcessError, ... |
import pytest
from selenium import webdriver
from selenium_tests.Config.config import TestData
# @pytest.fixture(params=["chrome", "firefox"], scope="class")
from selenium_tests.Data.TemplateData import TemplateData
from selenium_tests.Pages.HomePage import HomePage
from selenium_tests.Pages.LoginPage import LoginPage... |
from base import BaseAPITestCase
from contentcuration.models import Task
from contentcuration.tasks import create_async_task, non_async_test_task
# from celery.contrib.testing.worker import start_worker
# from contentcuration.celery import app
class AsyncTaskTestCase(BaseAPITestCase):
"""
These tests check t... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from optionaldict import optionaldict
from teambition.api.base import TeambitionAPI
class Tasklists(TeambitionAPI):
def get(self, id=None, project_id=None):
"""
获取任务分组列表
详情请参考
http://docs.teambition... |
from typing import Any, Dict, List, Optional, Union
import boto3
import pandas as pd
from cepan import _utils, exceptions
from cepan._filter import Filter, _build_filter
from cepan._sort_by import SortBy, _build_sort_by
from cepan._time_period import TimePeriod, _build_time_period
_COST_AND_USAGE_DIMENSIONS = [
... |
# SISO program matchingCharIndices.py
# This program computes solutions to the computational problem
# MatchingCharIndices.
# inString: A single string consisting of two alphanumeric ASCII words w1, w2
# separated by a space.
# returns: A list of all pairs of indices in the input words that match. More
# precisely, ... |
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
from airflowlivy.hooks.livy_batch_hook import LivyBatchHook
class LivyBatchOperator(BaseOperator):
"""
Quoted from `airflow-livy-operators <https://github.com/panovvv/airflow-livy-operators>`_:
.. highlight:: non... |
import warnings
warnings.filterwarnings("ignore")
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
import gym
from stable_baselines.deepq import DQN
env_id = "CartPole-v1"
env = gym.make(env_id)
model = DQN('MlpPolicy', env, learning_rate=1e-4, verbose=1)#, tensorboard_log="MLP/")
#model.learn(int(2e5))
#model.sav... |
from utils import setup_distrib, disk, square, rank_print, plot_matrix
import torch.distributed as dist
import torch.multiprocessing as mp
import torch
# operation performed by the reduce
OPERATION = dist.ReduceOp.MAX
def main_process(rank: int, world_size: int = 2):
device = setup_distrib(rank, world_size)
... |
import discord
from discord.ext import commands
client = commands.Bot(command_prefix = '.')
@client.event
async def on_message(message):
# メッセージ送信者がBotだった場合は無視する
if message.author.bot:
return
# 「/neko」と発言したら「にゃーん」が返る処理
if message.content == 'おい槇原':
await message.channel.send('もうシャブなんて... |
# -*- coding: utf-8 -*-
import torch
import numpy as np
from .negative_sample import global_neg_sample, global_perm_neg_sample, local_neg_sample
from utils import cal_recall
def get_pos_neg_edges(split, split_edge, edge_index=None, num_nodes=None, neg_sampler_name=None, num_neg=None):
if 'edge' in split_edge['trai... |
def HammingDistance(p,q):
c = 0
for i, j in zip(p,q):
if i != j:
c+=1
return c
|
# -*- coding: utf-8 -*-
"""Keras Using Wine DataSet.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1l3QsdlYJKsoQ6lycpBYj_TndZ34E2RqV
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function... |
import numpy as np
from natasy.data_preparation.dataset import Dataset
from natasy.neural_network.network import NeuralNetwork
from natasy.optimization import Optimizer
class MyDataset(Dataset):
def __init__(self, dev_size=0.2, shuffle=False, normalize_input_features=False, name='ex2data1'):
data = np.loa... |
class PpdPyError(Exception):
pass
class DirectiveSyntaxError(PpdPyError):
def __init__(self, message:str='invalid directive syntax'):
self.message = message
class ExpressionSyntaxError(PpdPyError):
def __init__(self, message:str='invalid expression syntax'):
self.message = message
|
import argparse
import os
from datetime import date
import multiprocessing
import pandas as pd
from pybaseball.utils import date_range
from pybaseball import statcast
NUM_THREADS = 8
RESULTS_FILE = "statcast_dates.csv"
def _parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--min-year", de... |
from fastapi import APIRouter
from app.api.v1 import clients, ws
api_router = APIRouter()
# Include routers.
api_router.include_router(ws.router, prefix="/ws")
api_router.include_router(clients.router, prefix="/clients")
|
import RPi.GPIO as GPIO
# Needed to allow the program to `sleep` for 1 second after displaying a digit.
# Else the display will be more like a light show!
import time
GPIO.setmode(GPIO.BCM)
# Dictionary of GPIO pins used and the segment they correspond to
pins = {'a': 17, 'b': 22, 'c': 6, 'd': 13, 'e': 19, 'f': 27, ... |
"""Implementation of Rule L044."""
from typing import Dict, List
from sqlfluff.core.rules.analysis.select_crawler import SelectCrawler
from sqlfluff.core.dialects.base import Dialect
from sqlfluff.core.rules.base import BaseRule, LintResult
class RuleFailure(Exception):
"""Exception class for reporting lint fail... |
import httpx
import time
import datetime
import sys
if (len(sys.argv) != 2):
raise Exception("Invalid arguments!")
baseURL = ["https://cdn.finra.org/equity/regsho/daily/", "shvol", ".txt"]
def main(args):
ticker = bytes(args[1].upper(), "utf-8")
request = httpx.get("https://finance.yahoo.com/quote/" + ar... |
"""
# This file was adapted from the DEAP.
#
# DEAP is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
#
# DEAP i... |
#!/usr/bin/python
#
# Copyright 2018-2022 Polyaxon, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... |
from __future__ import print_function, division
import numpy as np, astropy.io.fits as pyfits
import matplotlib.pyplot as plt
import os,sys
import psf_marginalise as pm
import scipy.ndimage as nd
def deconvolve(tgt_cubes,cal_cubes,savedir):
header = pyfits.getheader(tgt_cubes[0])
radec = [header['RA'],header['... |
import pandas as pd
import matplotlib.pyplot as plt
import os
def pretty_print(name, to_print):
print(f'{name}:')
print(f'{to_print}\n\n')
insurance = pd.read_csv(filepath_or_buffer='data/insurance.csv',
sep=',',
header=0)
pretty_print("insurance dataframe", insu... |
import streamlit as st
def draw_sidebar(state):
st.sidebar.header('Customise plots')
all_draw_params = []
for i, s in enumerate(state.schedulers):
draw_params = {}
scheduler_name = list(s.keys())[0]
new_scheduler = st.sidebar.selectbox(
'Select type of lr scheduler',
... |
#! python3
grid = [['.', '.', '.', '.', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['O', 'O', 'O', 'O', 'O', '.'],
['.', 'O', 'O', 'O', 'O', 'O'],
['O', 'O', 'O', 'O', 'O', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['.', 'O', 'O', '.',... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_orderedset
----------------------------------
Tests for `orderedset` module.
"""
import sys
if sys.version_info < (2, 7):
import unittest2 as unittest
else:
import unittest
import weakref
import gc
import copy
import pickle
from orderedset import *
cl... |
# Trainning
#
# from model import create_model
nn4_small2 = create_model()
from keras import backend as K
from keras.models import Model
from keras.layers import Input, Layer
# Input for anchor, positive and negative images
in_a = Input(shape=(96, 96, 3))
in_p = Input(shape=(96, 96, 3))
in_n = Input(shape=(96, 96,... |
# Created by Zachary Andrews
# Github: ZachAndrews98
import datetime
file_name = '.events/event_list.evt'
# list of events
class event_list:
event_list = list()
def __init__(self):
self.event_list.clear()
# adds event to list
def add_event(self, event):
self.event_list.append(event... |
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import os
import errno
from typing import List
from typing import Optional
from typing import Text
def relative_normpath(f, path):
# type: (Optional[Text], Text) ->... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.