content stringlengths 5 1.05M |
|---|
"""Author: Fabio Casagrande Hirono"""
import numpy as np
from .xml_utils import save_XML, XML_calib, XML_mic
def DARP2016_MicArray():
"""
Returns the microphone coordinates for the 'near-field' planar microphone
array used in the 2016 experiments with the DARP open-jet wind tunnel at
the ISVR, Univ. o... |
import boto3
import json
from aws_lambda_powertools import Logger
cognito_client = boto3.client('cognito-idp')
logger = Logger(child=True)
def convert_to_kebab_case(name, join_character='-'):
""" Transforms incoming name into hyphen-separated lower-cased string."""
return join_character.join(name.split()).... |
#wowgic_tweet_test
import json
import pymongo
import falcon
import tweepy
from tweepy import OAuthHandler
connection = pymongo.MongoClient("localhost", 27017)
db = connection.feeds
consumer_key= 'HwvpHtsPt3LmOZocZXwtn72Zv';
consumer_secret = 'afVEAR0Ri3ZluVItqbDi0kfm7BHSxjwRXbpw9m9kFhXGjnzHKh';
access_token = '4194127... |
"""
.. _pytorch_noise:
PyTorch and noisy devices
=========================
"""
##############################################################################
# Let's revisit the original :ref:`qubit rotation <qubit_rotation>` tutorial, but instead of
# using the default NumPy/autograd QNode interface, we'll use the :d... |
"""
Copyright 2018 Edmunds.com, 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 law or agreed to in writing, softw... |
import os
import sys
import traceback
import functools
import time
import multiprocessing
from . import utils
from . import stats
from . import pslogger
pool = None
our_ncores = None
finalize_needed = False
max_tasks_per_child_seen = False
def init(system_kwargs, backend_kwargs):
global pool
global our_ncor... |
# Yahoo Finance adapter
import re
import json
import csv
import urllib.request
import numpy as np
import pandas as pd
from datetime import datetime
from datetime import timedelta
from pymongo import MongoClient
from yahoo_quote_download import yqd # https://github.com/c0redumb/yahoo_quote_download
class YahooData_Ti... |
# solar-python — Solar data calculation and prediction library for Python
# Copyright © 2014, 2015 Mattias Andrée (maandree@member.fsf.org)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundat... |
import os
path = "github_cpp_program_data"
for root, dirs, files in os.walk(path, topdown=False):
for file in files:
file_path = os.path.join(root, file)
with open(file_path, "r") as f:
data = str(f.read())
if "404" in data:
print(file_path)
os.remove(file_path)
|
# Main File
import subfile # Importing subfile to main file
hi = subfile.Hi("Kamran") # Creating an object in main file from class in subfile
hi.helloWorld() # Calling method from created object
if len(self.path) == 6:
x = 4
y = 8
param.tmaze[x][y] = 1
# make into function
row = ((const.RLENGTH... |
from federatedscope.attack.auxiliary.utils import *
from federatedscope.attack.auxiliary.attack_trainer_builder import wrap_attacker_trainer
__all__ = [
'get_passive_PIA_auxiliary_dataset', 'iDLG_trick', 'cos_sim',
'get_classifier', 'get_data_info', 'get_data_sav_fn', 'get_info_diff_loss',
'sav_femnist_ima... |
import argparse
from importlib.resources import path
import queue
from typing_extensions import Required
import numpy as np
import cv2
import math
from queue import PriorityQueue
import time
import imageio
# Creating a class Node with visited_node, parent_node and cost as members
class Node:
def __init__(self, vi... |
print('this is going to be my app') |
import pandas as pd
import matplotlib.pyplot as plt
from scripts.pre_preprocessing import process_mutations, process_rnaseq_data
def pre_preprocessing(rna_file='', mut_file = '', rna_out_file=''):
# IMPORTANT: for reference only, no need in using the function
''' Pre-preprocessing generates two files what are... |
# -*- coding: utf-8 -*-
"""
External-IO connections based on memory buffer.
The only 3 requirements for these connections are:
(1) store Moler's connection inside self.moler_connection attribute
(2) plugin into Moler's connection the way IO outputs data to external world:
self.moler_connection.how2send = self.sen... |
# No shebang line, this module is meant to be imported
#
# Copyright 2013 Oliver Palmer
#
# 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
#
# U... |
# -*- coding: utf-8 -*-
"""
CredentialsData module
This module represents the DTO that holds credential data
"""
# pylint: disable=too-few-public-methods
class CredentialsData:
"""
Used for setting user input data to login to Conjur
"""
def __init__(self, machine: str = None, login: str = None, pa... |
# -*- coding: utf-8 -*-
"""Test suite."""
import pytest
class TestSystemInstances:
@pytest.fixture(scope="class")
def apiobj(self, api_instances):
return api_instances
def test_get(self, apiobj):
data = apiobj.get()
assert isinstance(data, list)
|
'''
Solution for day 12 of the 2021 Advent of Code calendar.
Run it with the command `python -m adventofcode run_solution -y 2021 12` from the project root.
'''
import re
from collections import Counter
from adventofcode.types import Solution
def find_paths(rules):
paths = set()
## has to start with start:
... |
from abc import ABC, abstractmethod
from .Zone import Zone
from .ZoneName import ZoneName
from ...BaseRepository import BaseRepository
class ZoneRepository(BaseRepository, ABC):
@abstractmethod
def add(self, o: Zone) -> Zone:
raise NotImplementedError
@abstractmethod
def list(self) -> [Zone]... |
# -*- coding: utf-8 -*-
import scrapy
import time
from tenxun.items import TenxunItem
class TencentSpider(scrapy.Spider):
name = 'tencent'
allowed_domains = ['hr.tencent.com']
start_urls = ['http://hr.tencent.com/position.php']
def parse(self, response):
data=response.xpath("//*[@class='tablel... |
from django.shortcuts import render
from dashboard.models import Position
from dashboard.utils import verify_position
@verify_position([Position.PositionChoices.MEMBERSHIP_DEVELOPMENT_CHAIR, Position.PositionChoices.VICE_PRESIDENT, Position.PositionChoices.PRESIDENT, Position.PositionChoices.ADVISER])
def memdev_c(r... |
import json
import time
import strategies
from strategies import support_functions, goto
from tools import logger as log
def path_ten(**kwargs):
"""
Walks around to get to level ten by earning successes
:param kwargs:
:return: report
"""
strategy = kwargs['strategy']
listener = kwargs['l... |
import numpy as np
data = np.array([[ 0.50170141, 1.46027261],
[ 0.97413385, 0.6756709 ],
[-0.17649309, -1.44746182],
[-0.30586378, -1.07902476],
[ 1.20221275, -0.23151285],
[ 0.06981749, -1.06081874],
[-0.85017335, -0.84245093],
[-0.83247692, -0.95133504],
[ ... |
"""email factor models"""
from django.core.mail.backends.smtp import EmailBackend
from django.db import models
from django.utils.translation import gettext as _
from passbook.core.models import Factor
class EmailFactor(Factor):
"""email factor"""
host = models.TextField(default="localhost")
port = model... |
#!/usr/bin/env python3
def combi(r, n):
p = 1
for i in range(1, n+1):
p = p * (r-i+1) / i
return int(p)
def pascal(n):
for row in range(n+1):
print(' ' * (n - row), end='')
for num in range(row+1):
print('{:8}'.format(combi(row, num)), end='')
print()
... |
# --------------
#Importing header files
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#Reading the file
data=pd.read_csv(path)
#Code starts here
# Step 1
#Reading the file
#Creating a new variable to store the value counts
loan_status=data['Loan_Status'].value_counts()
print(loan_statu... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
from .. import _utilities
import typing
# Export this package's modules as members:
from .deploy_artifact import *
from .deploy_environ... |
from django.urls import path
class ViewContainer:
def method_view(self, request):
pass
@classmethod
def classmethod_view(cls, request):
pass
view_container = ViewContainer()
urlpatterns = [
path("", view_container.method_view, name="instance-method-url"),
path("", ViewContaine... |
from torch import nn
from types_ import *
from typing import List
import copy
import torch
from gradient_reversal import RevGrad
def clones(module, N):
"Produce N identical layers."
return nn.ModuleList([copy.deepcopy(module) for _ in range(N)])
class MoMLP(nn.Module):
def __init__(self, input_dim: in... |
#!/usr/bin/env python3
import os
import redis
import time
from datetime import datetime
from dotenv import load_dotenv, find_dotenv
from elasticsearch import Elasticsearch
from elasticsearch import helpers
class Runner:
def __init__(self):
self.r = redis.Redis(os.getenv("HOST"), db=os.getenv("DB"))
self.es = ... |
class ManagedFeatureStatus(basestring):
"""
Represents the status of a managed feature.
Possible values:
<ul>
<li> "on" - feature is entitled and turned on,
<li> "available" - feature is entitled and available to be
turned on. Its current on/off status is unknown,
<li> "on_not_conf... |
import getpass
import sys
import uuid
from ..models.base import Base, get_session, get_engine
from ..models.Category import CategoryModel # Imported for schema creation
from ..models.Secret import SecretModel # Imported for schema creation
from ..modules.carry import global_scope
from .users import validation_key_ne... |
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torch.utils.data.distributed import DistributedSampler
from torch.utils.tensorboard import SummaryWriter
import pytorch_lightning as pl
import random
import numpy as np
from omegaconf import OmegaCo... |
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_samples, silhouette_score
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
# code adaption from
# https://scikit-learn.org/stable/auto_examples/cluster/plot_kmeans_silhouette_analysis.html
def silhouette_analysis(X:... |
from thefuck.utils import eager, get_closest, for_app
@for_app('fab')
def match(command):
return 'Warning: Command(s) not found:' in command.stderr
# We need different behavior then in get_all_matched_commands.
@eager
def _get_between(content, start, end=None):
should_yield = False
for line in content.s... |
from __future__ import absolute_import, division, print_function
import pytest
pytest.importorskip('dill')
from toolz import (merge, join, pipe, filter, identity, merge_with, take,
partial, valmap)
import math
from dask.bag.core import (Bag, lazify, lazify_task, fuse, map, collect,
reduceby, bz2_strea... |
from datetime import datetime
import dash_bootstrap_components as dbc
import plotly.graph_objects as go
from dash import dcc, html
from .widget_interface import WidgetInterface
class RadarChartWidget(WidgetInterface):
def __init__(self, data_manager, data_type, start_date, end_date, name, goal):
super()... |
#**************************
# Logistic Regression
# for DNA N6-Adenine Methylation
# Tian Tian
# tt72@njit.edu
#**************************
import sys
import numpy as np
import itertools
import multiprocessing
#**************************
# import modules
#**************************
from joblib import Parallel, delayed... |
# Fibonnaci Sequence
# Difficulty: Advanced
# NOTE: This is *not* a practical example of how you'll use coding in your day to day, BUT it does appear on a surprising number of in-person coding interviews. Why employers rely on something so impractical to gauge your coding ability is beyond me.
# But since they... |
import copy
import torch
import torch.nn as nn
import torch.nn.functional as F
from graph_filters.GSN_edge_sparse_ogb import GSN_edge_sparse_ogb
from graph_filters.MPNN_edge_sparse_ogb import MPNN_edge_sparse_ogb
from models_misc import mlp, choose_activation
from utils_graph_learning import global_add_pool_sparse, ... |
from typing import List
import numpy as np
import networkx as nx
import torch
import torch.nn as nn
from torch_geometric.data import Data, Dataset
def load_data(
original_data: Data,
max_close_neighbors: int = 5,
max_total_bundle: int = 20,
) -> List[Data]:
"""Loads the data from a pre-processed JSON... |
# Copyright (c) 2017 Sodasnout
# 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 limitation the rights
# to use, copy, modify, merge, publish, distribute... |
import io
from redis.exceptions import ConnectionError
from requests import get
from os import remove
from telethon.tl.types import MessageMediaPhoto
from asyncio import TimeoutError
from pagermaid import bot, redis, redis_status
from pagermaid.listener import listener
from pagermaid.utils import obtain_message, alias_... |
#!/usr/bin/python -u
# encoding=utf8
# Writes chunks into EOS using xrootd because we do not want to re-calculate checksums on each upload.
import sys
import json
import time
import syslog
from XRootD import client
from XRootD.client.flags import *
from XRootD.client.responses import *
def log_print(s):
print >> sy... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
import ConfigParser
def _get(inifile, section, name):
return inifile.get(section, name)
class CONFIG_GET():
def __init__(self):
read_inifile = ConfigParser.SafeConfigParser()
read_inifile.read("../AWS_conf.ini")
self.db_type = _get(inifile... |
import asyncio
import html
import json
import logging
import os
import re
import shlex
import tempfile
from jupyter_server.base.handlers import APIHandler
from jupyter_server.utils import url_path_join
import tornado
import tornado.web
logger = logging.Logger(__file__)
jobIDMatcher = re.compile("^[0-9]+$")
class M... |
# Copyright (c) 2019 Georgia Tech Robot Learning Lab
# Licensed under the MIT License.
from abc import ABC, abstractmethod
import functools
import numpy as np
from numpy import linalg as la
import os
import pydart2 as pydart
pydart.init()
class EnvWithModel(ABC):
def __init__(self, horizon, predict=None, reward... |
#!/usr/bin/env python3
import sys
from setuptools import setup, find_packages
__version__ = "0.1"
if sys.version_info < (3,5):
print("python version must be at least 3.5")
sys.exit(1)
def readme():
with open('README.md') as f:
return f.read()
setup(name='pybioutils',
version='0.... |
class Doublet:
def __init__(self, x: float, y: float, strength: float):
self.x = x
self.y = y
self.strength = strength
@property
def coords(self) -> Coords:
return Coords(self.x, self.y)
def __str__(self) -> str:
return f'Doublet: ({self.x}, {self.y}), s... |
#!/usr/bin/env python
# (c) Baltasar 2016-19 MIT License <baltasarq@gmail.com>
import time
import logging
import datetime
import webapp2
from webapp2_extras import jinja2
from google.appengine.ext import ndb
from model.appinfo import AppInfo
from model.member import Member
from model.trial import Trial
from model.ne... |
# -*- coding: utf-8 -*-
"""
"""
import numpy as np
import os
import sys
import matplotlib.pyplot as plt
import re
import glob
import math
from mpl_toolkits.mplot3d import Axes3D
import copy as cp
import multiprocessing as mp
def tryint(s):
try:
return int(s)
except:
return s
def alphan... |
# menuTitle: Align Points
# shortCut: shift+command+f
'''
This script aligns selected points intelligently.
It will look at the x-coordinate offset and
the y-coordinate offset and align according to
whichever one is smaller. It will also make
an educated guess as to which direction you'd
like to align it.
Requir... |
import abc
import os
import collections
import itertools
import pyonmttok
from nmtwizard.logger import get_logger
from nmtwizard.preprocess import tokenizer
logger = get_logger(__name__)
class Consumer(abc.ABC):
"""Base class for using preprocess results."""
def __init__(self):
self._num_samples =... |
from django.http import Http404
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from backend.models import Client
from backend.serializers.clientSerializer import ClientSerializer
class ClientView(APIView):
def get_object(self, pk):
... |
__author__ = 'User'
from model.contact import Contact
testdata = [
Contact(firstname="firstname1", lastname="lastname1", address="address1", mobilephone="1111"),
Contact(firstname="firstname2", lastname="lastname2", address="address2", mobilephone="2222")
]
|
from __future__ import annotations
import io
import traceback
from typing import List, Optional, Union
import discord
from discord.ext import commands
from .environments import DEBUG, DEBUG_TOKEN, DESCRIPTION, PREFIX, STATUS, TOKEN
from .log import logger
_initial_extensions = (
"fizzbotz.cogs.admin",
"fizz... |
class DatabaseOperations(object):
"""Defining Database operation and its structure"""
def add(self, parameters):
raise NotImplementedError("Need to implement add method")
def update(self, parameters):
raise NotImplementedError("Need to implement add method")
def delete(sel... |
import csv
import networkx as nx
import sys
import numpy as np
import time
import pandas as pd
import random as rnd
#from ampligraph.datasets import load_fb15k
import traceback
from datetime import datetime
#import mp_counts
from itertools import product
#import preprocessing as prc
#from statsmodels.stats.proportion i... |
import os
import pathlib
from PyQt5.QtCore import Qt, QSize
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QGridLayout, QLabel, QPushButton, QComboBox, QSpinBox
def initui(self):
self.layout = QGridLayout()
self.logo = QLabel()
pixmap = QPixmap(os.path.join(pathlib.Path(__file__).parent.res... |
import sys
import os
_CURRENT_DIRECTORY = os.path.dirname(os.path.abspath(__file__))
_PACKAGE_DIRECTORY = _CURRENT_DIRECTORY
def add_packages_to_path():
sys.path.append(os.path.normpath(_PACKAGE_DIRECTORY))
|
# coding:utf-8
'''
funword -- 单词操作函数公用单元
Created on 2010-9-2
@author: tongjp
findword() 根据搜素关键词返回查询结果
pageword() 以分页的形式返回单词查询结果,最多3000条记录
pagenword() 以分页的形式返回生词词查询结果
'''
from django.core.paginator import *
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.db.m... |
from typing import Iterable, Optional, Union
import warnings
import torch
import torch.nn as nn
from kornia.geometry.linalg import transform_points
from kornia.geometry.linalg import inverse_transformation
class PinholeCamera:
r"""Class that represents a Pinhole Camera model.
Args:
intrinsics (torc... |
"""
:mod:`zsl.db.model.app_model_json_encoder`
------------------------------------------
.. moduleauthor:: Martin Babka
"""
from __future__ import unicode_literals
from json.encoder import JSONEncoder
from zsl.db.model import AppModel
class AppModelJSONEncoder(JSONEncoder):
def default(self, o):
if is... |
from torch.utils.data import Dataset
import os
from PIL import Image
import datasets.rs_segment.transforms as tr
import numpy as np
from utils.misc import read_txt_as_list
class RailwaySeg(Dataset):
def __init__(self, root, split, base_size=None, crop_size=None):
data_dir = os.path.join(root, ... |
#!/usr/local/bin/python
# coding:utf-8
import os
from xgboost import XGBClassifier
import numpy as np
from sklearn.metrics import accuracy_score
def get_name(filename):
name_list = os.listdir(filename)
return name_list
def readfile(filename):
with open(filename) as file:
data = file.read()
return data
def ge... |
import unittest
from calculator.calculator_actions import calculate
class CalculatorClassTest(unittest.TestCase):
def test_should_sum_positive_numbers(self):
self.assertEqual(calculate('2+2'), '4')
def test_should_sum_negative_numbers(self):
self.assertEqual(calculate('-2+-2'), '-4')
def... |
""" Tuple """
"""
A tuple is a collection like list which is ordered but unchangeable.
In Python tuples are written with round brackets.
"""
""" create a tuple """
my_tuple = ('apple', 'banana', 'orange')
print(my_tuple) # returns ('apple', 'banana', 'orange')
""" Access tuple items """
print(my_tuple[0]) ... |
"""
Train FKP
"""
import torch
from torchvision.utils import save_image
from torch.optim.lr_scheduler import MultiStepLR
from torch.utils.data import DataLoader
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "6"
import math
import argparse
impo... |
# %%
# 运行参数: --model_dir=E:\model\official_myDataset --data_dir=E:\data\my_dataset --train_epochs=10 --distribution_strategy=one_device --num_gpus=1 --download
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file ... |
from setuptools import setup, find_packages
setup(name='torchquantum',
version='0.1.0',
description='A PyTorch-centric hybrid classical-quantum dynamic '
'neural networks framework.',
url='https://github.com/Hanrui-Wang/pytorch-quantum',
author='Hanrui Wang',
author_emai... |
import pandas as pd
from typing import Union, Dict, List, Tuple, TypeVar
from .composed_selector import ComposedSelector
from .l1 import L1
from ..utilities.utils import Result
__all__ = ["Selector"]
WoE = TypeVar("WoE")
feature = Union[str, int, float]
f_list_type = List[feature]
class Selector:
"""
Кла... |
'''
Created on 9 Mar, 2015
@author: artur.mrowca
'''
|
# -*- coding:Utf-8 -*-
#####################################################################
#This file is part of Network and RGPA.
#PyLayers is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of... |
"""Automated tools for managing alacritty configurations"""
__version__ = "0.3.5"
class PycrittyError(Exception):
pass
|
import pandas as pd
from collections import defaultdict
import math
from DoD.utils import FilterType
import config as C
import os
import psutil
from tqdm import tqdm
import time
import pprint
pp = pprint.PrettyPrinter(indent=4)
# Cache reading and transformation of DFs
cache = dict()
memory_limit_join_processing = ... |
# Copyright 2016 Google 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 law or agreed to in writing, ... |
import os
import math
import numpy as np
import numpy.linalg as nplin
class JudgeInside():
def __init__(self):
print("Judge inside : ON")
def set_limit_area(self, xy_range):
# Check range area is close or not
if np.allclose(xy_range[0,:], xy_range[-1,:]):
... |
import torch
import torch.nn as nn
import numpy as np
from utils.shuffle import feature_shuffle_index
# ------------------------------- 6 expansion layers ------------------------------- #
class LinearExpansion(nn.Module):
'''expansion 1D -> 2D'''
def __init__(self, d_features, n_channel, n_depth):
s... |
# -*- coding: utf-8 -*-
from flask import Blueprint, render_template, g
from flask.ext.login import login_required
from appl.user.models import read_user
mod = Blueprint('users', __name__, template_folder='templates')
@mod.url_value_preprocessor
@login_required
def inject_wg_user(endpoint, values):
if 'uid' in ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Transmission Remote
#
# <bitbar.title>Transmission Remote</bitbar.title>
# <bitbar.version>v1.0</bitbar.version>
# <bitbar.author>Christoph Russ</bitbar.author>
# <bitbar.author.github>christophruss</bitbar.author.github>
# <bitbar.desc>
# Checking transmission status, ... |
from rest_framework import serializers
from rest_framework.validators import UniqueValidator
from decimal import Decimal
import random
import string
import uuid
from django.apps import apps
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth import get_us... |
from dynaphopy import functions as reading
__author__ = 'abel'
import sys, os
from PyQt4 import QtGui,QtCore
from GUI.main_window import Ui_MainWindow
class Dialog(QtGui.QMainWindow):
def __init__(self):
QtGui.QMainWindow.__init__(self)
# Set up the user interface from Designer.
self.ui ... |
import os
import signal
from actions import FirstBootAction
from subprocess import check_output, STDOUT, CalledProcessError
from time import sleep
import json
try:
import httplib
except:
import http.client as httplib
from ui import Menu, PrettyPrinter, DialogBox, ProgressBar, Listbox, UniversalInput, HelpOver... |
#!/usr/bin/env python
#-----------------------------------------------------------------------------
# Copyright (c) 2015--, Evguenia Kopylova.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#--------------------------------... |
import argparse
import json
import subprocess
import numpy as np
import collections
import re
import os
import time
# Reads in a json file. Each item in the json file is a job to submit. The contents are its name, and which jobs
# it depends upon. The program takes tdhe jobs, submits them to torque, and captures the jo... |
#!/usr/bin/env python3
import time
class RouteParam:
def __init__(self, name: str, type_name: str, doc: str, protocols=None, builder=None, generic_name=None,
is_builder=False, builded_variable_name=None):
self.is_builder = is_builder
self.name = name
self.type_name = type_... |
import base
# 开始真正的模型训练
import torch
import torch.nn as nn
# 实例化网络
net = base.AlexNet(len(base.classes))
# X = torch.rand(4, 28, 28)
# print(X)
# net(X)
# 定义数据集的训练迭代轮次
max_epoch = 5
# 定义学习率
learning_rate = 0.001
# 定义loss函数、定义优化器
import torch.optim as optim
criterion = nn.CrossEntropyLoss()
# optimizer = optim.SGD(... |
def test_add_review_success():
assert True
def test_add_review_failure():
assert True
def test_list_reviews_success():
assert True
def test_list_reviews_failure():
assert True
|
"""
Represent the email address OG resource
"""
import attr
from .base_data import BaseData
@attr.s(auto_attribs=True)
class EmailAddress(BaseData):
address: str = None
name: str = None
|
"""This module provides DELETE functionality.
"""
from oracle_connect import connect, commitandclose
from oracle_common import doall
def removeall(table):
"""Delete everything in table.
Args:
table (string): Table name.
"""
doall("DELETE FROM {table}".format(table=table))
|
import argparse
import xgboost as xgb
from modchooser import *
from deepevent import *
import numpy as np
import time
import pandas as pd
from osutils import *
import random
import os
from sklearn import metrics
from sklearn import manifold
from sklearn import decomposition
def load_params_boost(boost, boost_file):
i... |
import requests
from config import auth
IMGUR_UPLOAD_URL = "https://api.imgur.com/3/image"
IMGUR_UPLOAD_HEADERS = {'Authorization': 'Client-ID {}'.format(auth['imgur']['client-id'])}
def imgur_upload(url):
response = requests.post(IMGUR_UPLOAD_URL, data={'image': url}, headers=IMGUR_UPLOAD_HEADERS)
if respon... |
from django.http import request
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
return render(request,'pages/index.html')
def about(request):
return render(request,'pages/about.html')
def coffee(request):
return render(request,'pages/co... |
import numpy as np
# regression models
from sklearn.linear_model import Ridge
from sklearn.metrics import mean_squared_error
# plotting package
import matplotlib.pyplot as plt
def rr_regress(X, y, a=None, b=None):
"""
This function returns regression of input data by Ridge regression
method.
... |
import numpy as np
import tensorflow as tf
FLAGS = tf.app.flags.FLAGS
def _read_and_decode(filename_queue):
reader = tf.TFRecordReader()
_, serialized_example = reader.read(filename_queue)
features = tf.parse_single_example(
serialized_example,
features={
'height': tf.FixedLenFeatu... |
# -*- coding: utf-8 -*-
# Copyright (c) 2019, Pedro Antonio Fernández Gómez and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.website.website_generator import WebsiteGenerator
from frappe.website.render import clear... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import json
import warnings
import pulumi
import pulumi.runtime
from typing import Union
from .. import utilities, tables
class Job(pu... |
# -*- coding: UTF-8 -*-
from .file import * |
import time
import pygame
import random
import copy
class solveAlgorithm:
def __init__(self, win, HEIGHT, WIDTH, grid):
# constants
self.HEIGHT = HEIGHT
self.WIDTH = WIDTH
# pygame variables
self.win = win
# grid values that we know are right from the start
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.