content stringlengths 5 1.05M |
|---|
from time import sleep, time
from urllib.parse import urlparse, urljoin
import re
from typing import Pattern, Set
valid_url_pattern = re.compile(r"^(?:http(s)?://)?[\w.-]+(?:\.[\w.-]+)+[\w\-._~:/?#[\]@!$&'\(\)\*\+,;=]+$")
allow_pattern = re.compile(r'^Allow:\s+(.+)$')
disallow_pattern = re.compile(r'^Disallow:\s+(.+)... |
# pylint: disable-msg = wildcard-import, unused-wildcard-import, unused-import
from phi.flow import *
from .app import *
from .session import *
from .world import *
from .data import *
from .util import *
import tensorflow as tf
|
import numpy
import fileinput
import os
from multiprocessing import Pool
from itertools import repeat
'''
Here we precompute all the possible values for the stated input.
First, we will compute all the prime numbers in the interval from 0 to the
maximum allowed input (B value).
Then, we use these prime numbers to fac... |
# -*- coding: utf-8 -*-
# Copyright (c) 2017, Softbank Robotics Europe
# 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 must retain the above copyright notice, t... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: server.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import multiprocessing, copy
from collections import OrderedDict
from luigi import configuration
from psutil import virtual_memory
# populations
ANCIENT_POPS = ['DPC']
ALL_POPS = ['BAS', 'DNA', 'DAE', 'DEU', 'DGS', 'DLB', 'DAL', 'DGL', 'DHU', 'DMA', 'DSL', 'DME', 'DPU',... |
# file with error
def:
pass |
import torch
from genrl.agents.deep.dqn.base import DQN
from genrl.agents.deep.dqn.utils import ddqn_q_target
class DoubleDQN(DQN):
"""Double DQN Class
Paper: https://arxiv.org/abs/1509.06461
Attributes:
network (str): The network type of the Q-value function.
Supported types: ["cnn... |
import asyncio
import time
from cmyui.logging import Ansi
from cmyui.logging import log
import app.packets
import app.state
import settings
from app.constants.privileges import Privileges
#Discordbot imports
import discordbot.botconfig as configb
import discord
from discord.ext import commands
from discord_slash imp... |
import logging
import subprocess
import configparser
import os
class SSH:
def __init__(self, username, ip, port, identity_file):
self.username = username
self.ip = ip
self.port = port
self.identity_file = identity_file
def connection_str(self):
return '{}@{}'.format(se... |
"""
FastAPI for Priority Job Queue.
"""
import asyncio
import datetime
import uuid
import fastapi
import pydantic
TIMEOUT = 30
class Job(pydantic.BaseModel): # pylint: disable=no-member, too-few-public-methods
"""
Job model
"""
jobId: uuid.UUID = pydantic.Field(default_factory=uuid.uuid4)
sub... |
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
reg_profile = InlineKeyboardMarkup(row_width=3,
inline_keyboard=[
[
InlineKeyboardButton(text="Пройти опрос", callback_data="survey")... |
# Copyright 2017-2018 Wind River
#
# 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 writin... |
#!/usr/bin/python
#
# Copyright 2002-2021 Barcelona Supercomputing Center (www.bsc.es)
#
# 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
... |
#!/usr/bin/env python
__all__ = ['SignerPlugin']
|
from setuptools import find_packages, setup
setup(
name="pysen_ls",
version="0.1.2",
packages=find_packages(),
description="A language server implementation for pysen",
long_description=open("README.md").read(),
long_description_content_type="text/markdown",
author="Yuki Igarashi",
auth... |
import turtle,random
turtle.mode("logo")
turtle.shape("turtle")
turtle.bgcolor("black")
turtle.speed(0)
#draw the sun
turtle.speed(0)
turtle.pencolor("red")
size_of_sun=10
sun_x = 0
sun_y = 300
for j in range(12):
turtle.penup()
turtle.goto(sun_x,sun_y)
turtle.pendown()
for i in range(3):
tu... |
import re
class LinkHandler:
'''Matches any website links in the text'''
def __init__(self):
http_protocol = r"""h[it]tps?:"""
# generic_protocol = r"""[a-z][\w-]+"""
top_level_domain = r"""(?:com|net|org|edu|gov|mil|aero|asia|biz|""" + \
r"""cat|coop|info|int|jobs|mobi|m... |
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor, as_completed
from ploomber.exceptions import DAGWithDuplicatedProducts
from ploomber.products.metaproduct import MetaProduct
from ploomber.products import File
from ploomber.io import pretty_print
def _generate_error_message_pair(... |
"""
File: import_data.py
Author: Ian Ross
Email: iross@cs.wisc.edu
Description: # TODO
# Expected structure:
## stack_output/
# xml/ %
# html/
# img/ $
# output.csv $
# tables.csv $
# figures.csv $
## images/ &
# %: xml/annotation import
# $: kb import
# &: image import
"""
import uuid
import l... |
from fuzzywuzzy import fuzz
from fuzzywuzzy import process as fuzz_process
import regex
from will import settings
from will.decorators import require_settings
from will.utils import Bunch
from .base import GenerationBackend, GeneratedOption
class FuzzyBestMatch(GenerationBackend):
def _generate_compiled_regex(se... |
import matplotlib
matplotlib.use('Agg')
from utils.data_reader import Personas_CVAE
from model.common_layer import NoamOpt, evaluate
from utils import config
from model.CVAE.util.config import Model_Config
import torch
import torch.nn as nn
import numpy as np
from random import shuffle
from copy import deepcopy
import... |
from typing import Any
from grapl_analyzerlib.analyzer import Analyzer, OneOrMany
from grapl_analyzerlib.prelude import ProcessQuery, FileQuery, ProcessView
from grapl_analyzerlib.execution import ExecutionHit
class UnpackedFileExecuting(Analyzer):
def get_queries(self) -> OneOrMany[ProcessQuery]:
unpac... |
class Animation():
def __init__(self):
self.vertex_n = 0
self.verticies = []
def get_coord(self, V_kind):
print("\n\t***\nFor vertex %s please enter:\n" % V_kind)
x = input('X: ')
y = input('Y: ')
z = input('Z: ')
pos = [x, y, z]
return pos
def add_Vertex(self):... |
"""Helper variable or function for UI Elements."""
import numpy as np
TWO_PI = 2 * np.pi
def clip_overflow(textblock, width, side='right'):
"""Clips overflowing text of TextBlock2D with respect to width.
Parameters
----------
textblock : TextBlock2D
The textblock object whose text needs to ... |
from flask import current_app
from flask import request as current_request
from snosearch.adapters.flask.requests import RequestAdapter
from snosearch.adapters.flask.responses import ResponseAdapter
def make_search_request(request=None):
if request is None:
request = current_request
registry = curren... |
from django.contrib import admin
from django.urls import path, include
from .views import *
urlpatterns = [
path('hotels/all', HotelAllView.as_view()),
path('hotels/<int:hotel_id>', show_hotel),
path('login/', user_login),
path('register/', user_register)
]
|
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import logging
import webapp2
from dashboard.p... |
from setuptools import setup
setup( name='ishneholterlib',
version='2017.04.11',
description='A library to work with ISHNE-formatted Holter ECG files',
url='https://bitbucket.org/atpage/ishneholterlib',
author='Alex Page',
author_email='alex.page@rochester.edu',
license='MIT',... |
"""RPC client, aioamqp implementation of RPC"""
import abc
import asyncio
import aioamqp
async def declare_and_bind(channel, exchange_name, queue_name):
await channel.exchange_declare(
exchange_name=exchange_name,
type_name='fanout'
)
await channel.queue_declare(queue... |
import urllib.request as urllib2
from bs4 import BeautifulSoup
import collections
from datetime import datetime
from multiprocessing import Pool
from operator import itemgetter
import multiprocessing
ans = []
name_question = []
def link_generate(name_question,user,list_links):
for name_question in name_question:
... |
import boto3
from boto3.dynamodb.conditions import Key
from ask_sdk_dynamodb.adapter import DynamoDbAdapter
import os
import string
import random
import json
ddb_region = os.environ.get('DYNAMODB_PERSISTENCE_REGION')
ddb_table_name = os.environ.get('DYNAMODB_PERSISTENCE_TABLE_NAME')
ddb_resource = boto3.resource('dy... |
"""Service integrations."""
from .legacy_metadata import LegacyMetadataService
from .legacy_pdf import LegacyPDFService
from .legacy_source import LegacySourceService |
from termcolor import colored
from time import time
import sys
from solutions import day_01, day_02, day_03, day_04, day_05, day_06, day_07, \
day_08
NAMES = (
"No Time for a Taxicab",
"Bathroom Security",
"Squares With Three Sides",
"Security Through Obscurity",
"How About a Nice Game of Che... |
# MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
#
# Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY ... |
from __future__ import unicode_literals
import unittest
from mock import patch
from snips_nlu.constants import DATA_PATH
from snips_nlu.resources import (
MissingResource, _RESOURCES, _get_resource, clear_resources,
load_resources)
class TestResources(unittest.TestCase):
def test_should_load_resources_... |
"""Text formatting constants."""
# Text Effects
RESET = 0
BOLD = 1
FAINT = 2
ITALIC = 3
UNDERLINE = 4
REVERSE = 7
CONCEAL = 8
STRIKEOUT = 9
# Colors
BLACK = 30
RED = 31
GREEN = 32
YELLOW = 33
BLUE = 34
MAGENTA = 35
CYAN = 36
WHITE = 37
# Modifiers
BRIGHT = 60
BR = 60
BACKGROUND = 10
BG = 10
# Standard fonts
SM = "s... |
import time
import unittest
from selenium import webdriver
from selenium.webdriver.common.by import By
class TestLogin(unittest.TestCase):
user = (By.ID, 'username')
pwd = (By.ID, 'password')
login = (By.CLASS_NAME, 'radius')
msg = (By.CLASS_NAME, 'subheader')
def setUp(self) -> None:
se... |
#* A binary tree is symmetric if the left subtree from the root and the right subtree from the root are mirrors of eachother.
#1. All we need to do is make a new function, which will hold "copies" of the same tree
#2. We then simply need to check in each iteration if the values of the nodes are the same and most impo... |
import os,unittest
import pandas as pd
from igf_data.illumina.samplesheet import SampleSheet
from igf_data.utils.fileutils import get_temp_dir,remove_dir
from igf_data.utils.samplesheet_utils import get_formatted_samplesheet_per_lane
from igf_data.utils.samplesheet_utils import samplesheet_validation_and_metadata_check... |
import torch.nn as nn
import torch
import torch.nn.functional as F
import pdb
from adet.modeling.layers import qconv, norm, actv, shuffle, concat, split, add
from functools import partial
from detectron2.modeling.backbone.build import BACKBONE_REGISTRY as BACKBONES
from detectron2.modeling.backbone import Backbone ... |
from pathlib import Path
import pandas as pd
from typing import Sequence
from visions.core.model.relations import (
IdentityRelation,
InferenceRelation,
TypeRelation,
)
from visions.core.model.type import VisionsBaseType
def _get_relations() -> Sequence[TypeRelation]:
from visions.core.implementation... |
import sys
import random
import string
from sqlalchemy import Column, ForeignKey, Integer, String, DateTime
from sqlalchemy.sql import func
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy import create_engine
from passlib.apps import custom_... |
#
# @file TestSBMLNamespaces.py
# @brief SBMLNamespaces unit tests
#
# @author Akiya Jouraku (Python conversion)
# @author Sarah Keating
#
# ====== WARNING ===== WARNING ===== WARNING ===== WARNING ===== WARNING ======
#
# DO NOT EDIT THIS FILE.
#
# This file was generated automatically by converting the file ... |
from torch import nn
import numpy as np
import torch.nn.functional as F
import torch
from typing import Dict
from collections import OrderedDict
import math
##########
# Layers #
##########
class Flatten(nn.Module):
"""Converts N-dimensional Tensor of shape [batch_size, d1, d2, ..., dn] to 2-dimensional Tensor
... |
import pandas as pd
import numpy as np
import plotly
import plotly.plotly as py
import plotly.graph_objs as go
def make_link(x):
for ind in x.index:
doc_npi = ''
for col in x.columns:
if col == 'NPI':
doc_npi = x.at[ind,col]
x.at[ind,col] = ('<a href=\"..... |
# pylint: disable=unexpected-keyword-arg,no-value-for-parameter,too-many-public-methods
# pylint: disable=no-member,missing-function-docstring,redefined-outer-name,unsubscriptable-object
# pylint: disable=too-many-function-args
"""
"""
import functools
from collections import namedtuple
from contextlib import suppress
... |
"""
Copyright (c) 2017 IBM Corp.
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, sub... |
#!/usr/bin/env python3
#
# A utility to retrieve Device-to-Cloud messages
#
# Usage:
#
# $ az_d2c_recv.py EVENT_HUB_NAME CONN_STR [offset]
#
# Both EH name and conn string can be obtained from the "Endpoints" section
# of the IoT Hub page. Note that Event Hub name is not the same as IoT Hub
# name and connectio strin... |
from django.shortcuts import render, redirect, reverse, get_object_or_404
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import View
from .forms import (CreateCourseForm,
CreateCourseRegistrationForm,
CreateDepartmentForm,
... |
import tensorflow as tf
from tensorcv.train.trainer.trainer import Trainer
from tensorcv.train.hooks import CheckpointPerfactSaverHook
class MultiGPUTrainer(Trainer):
def feature_shard(self, feature, num_shards):
if num_shards > 1:
feature_batch = tf.unstack(
feature, num=self.... |
#!python
#--coding:utf-8--
"""
getBedpeFBed.py
Transfering single-end BED file to paired-end BEDPE file as input of cLoops2 .
"""
#systematic library
import os, time, gzip, argparse, sys
from datetime import datetime
from argparse import RawTextHelpFormatter
#3rd library
#cLoops2
from cLoops2.ds import PET
from cLoop... |
class Category:
def __init__(self, category):
self.category = category
self.ledger = []
def __str__(self):
title = f"{self.category:*^30}\n"
amount = 0
format_items = ""
for item in self.ledger:
format_items += f"{item['description'][0:23]:23}" + f"{item['amount']:>7.2f}\n"
am... |
#!/usr/bin/env python
'''
Advent of Code 2021 - Day 21: Dirac Dice (Part 1)
https://adventofcode.com/2021/day/21
'''
import re
import time
from collections import deque
from itertools import cycle
WINNING_SCORE = 1000
class Player():
def __init__(self, player_id, position) -> None:
self.id = player_i... |
# Generated by Django 2.1.7 on 2019-06-11 13:09
import django.utils.timezone
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("cspatients", "0017_baby_allow_nulls")]
operations = [
migrations.AlterField(
model_name="patiententry",
... |
# encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
from ._clrm import bright, cyan, green
DEFAULT_DUP_COL_HANDLER = "rename"
class ResultLogger(object):
@property
def verbosity_level(self):
return self... |
# Copyright 2016 PerfKitBenchmarker 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 appli... |
"""
=========
PointPens
=========
Where **SegmentPens** have an intuitive approach to drawing
(if you're familiar with postscript anyway), the **PointPen**
is geared towards accessing all the data in the contours of
the glyph. A PointPen has a very simple interface, it just
steps through all the points in a call from ... |
import json
import matplotlib.pyplot as plt
import requests
import server_config
def draw_plot(interval):
try:
url = "{}/id0_collection/{}".format(server_config.server_url, interval)
r = requests.get(url=url)
formatted_string = r.text.replace("'", '"')
rows = json.loads(formatte... |
# Generated by Django 3.0.2 on 2020-02-12 17:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hash', '0002_hash_turn_count'),
]
operations = [
migrations.AlterField(
model_name='hash',
name='turn_count',
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""An implementation of the overfitting test for the Transformer model.
A simple test, which often signifies bugs in the implementation of a model, is the overfitting test. To that end, the
considered model is trained and evaluated on the same tiny dataset, which it shou... |
#!/usr/bin/python3
import ssl, json
from os.path import isfile, isdir
from os import sep, name
from sys import exit, argv, version_info, stdout, stderr
from getopt import getopt
from xmlrpc.client import ServerProxy
from urllib.parse import quote_plus
fro... |
#!/usr/bin/python3
"""Encrypt and decrypt a string with a simple algorithm.
To encrypt, reverse and increase the ASCII code by 1. To decrypt, do the
reverse.
"""
def encrypt(plain):
output = []
for char in plain:
output.append(chr(ord(char)+1))
output.reverse()
return ''.join(output)
def dec... |
#!/usr/bin/env python
# -*- coding: utf-8
from datetime import timedelta
import mock
import pytest
import time
from dockerma.cache import FileCache, Entry
TEST_KEY = "test-key"
TEST_DATA = "test-data"
TEST_ENTRY_PATH = "test-entry-path"
class TestCache(object):
@pytest.fixture
def cache(self, request):
... |
from setuptools import find_packages, setup
setup(
name="PyFLocker",
version="0.3.1",
author="Arunanshu Biswas",
author_email="mydellpc07@gmail.com",
packages=find_packages(exclude=["tests"]),
description="Python Cryptographic (File Locking) Library",
long_description=open("README.md").read... |
"""Top-level package for Yet Another Workflow Language for Python."""
__author__ = """Fabio Fumarola"""
__email__ = 'fabiofumarola@gmail.com'
__version__ = '0.3.0'
|
#!/usr/bin/env python
# pyClearURLs
# Copyright (c) 2020 pilate
# Copyright (c) 2020-present Marco Romanelli
# See LICENSE for details.
from collections import defaultdict
from urllib.parse import unquote
import re
import json
import os.path
PATH_PACKAGE_DATA = os.path.join(os.path.dirname(os.path.realpath(__file__)... |
from typing import Optional
import numpy as np
from arch.univariate.distribution import SkewStudent as SS
from scipy.stats import t, uniform
from ._base import DistributionMixin, _format_simulator
class SkewStudent(DistributionMixin, SS):
def __init__(self, random_state=None):
DistributionMixin.__init__... |
################################################################################
# MIT License
#
# Copyright (c) 2017 OpenDNA Ltd.
#
# 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 re... |
#!/usr/bin/env python
# coding: utf-8
# #### Spyking circus using spikeinterface
import os
import spikeinterface.extractors as se
import spikeinterface.toolkit as st
import spikeinterface.sorters as ss
# Here are all the informations that we need like the file location
data_path = "P:\\raviku53\\test_record... |
# -*- coding: utf-8 -*-
## Variaveis
# 21.07.2020
# DB Functions for DB writes and reports
import sys
import os
sys.path.append(os.path.abspath('..'))
sys.path.append(os.path.abspath('bot'))
from bdFluxQueries import TraceReport, OccupancyReport, BestDayReport, BestDay
from config import le_config
"... |
# coding: utf-8
# # Using VGG16
# In[1]:
import numpy as np
from keras.applications import vgg16
from keras.preprocessing import image
# In[2]:
model = vgg16.VGG16(weights='imagenet')
# In[3]:
img = image.load_img('images/spoon.jpeg',target_size=(224,224))
img
# In[4]:
# Convert to Numpy array
arr = im... |
import webbrowser
from PyQt5 import QtWidgets, QtCore
import xappt
from xappt_qt.gui.widgets.tool_page.converters.base import ParameterWidgetBase
from xappt_qt.gui.widgets.file_edit import FileEdit
from xappt_qt.gui.widgets.text_edit import TextEdit
from xappt_qt.gui.widgets.table_edit import TableEdit
from xappt_qt... |
from collections import Counter
from dataclasses import dataclass, field
from urllib import request
from bs4 import BeautifulSoup
from tabulate import tabulate
@dataclass
class Person:
name: str = ''
company: str = ''
@property
def company_first_word(self):
return self.company.split(' ', 1)[... |
import os
from os.path import splitext, getmtime, isfile
from pyflu.setuptools.base import CommandBase
from pyflu.path import iter_files
from setuptools import setup, find_packages, Extension
class CompileCythonCommand(CommandBase):
description = "compile all cython files"
user_options = [
("i... |
from azure.common.credentials import ServicePrincipalCredentials
class AzureContext(object):
"""Azure Security Context.
remarks:
This is a helper to combine service principal credentials with the subscription id.
See README for information on how to obtain a service principal attributes client i... |
import torch
from torch import Tensor
from torch import nn
from torch._C import dtype
from torch.nn.utils.rnn import pad_sequence
import math
from transformers import RobertaConfig, RobertaModel
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
######################################
# Char Word Tr... |
"""
Credits: https://github.com/valeoai/BF3S
"""
import torch
def create_rotations_labels(batch_size, device):
"""Creates the rotation labels."""
labels_rot = torch.arange(4, device=device).view(4, 1)
labels_rot = labels_rot.repeat(1, batch_size).view(-1)
return labels_rot
def apply... |
# -*- coding: utf-8 -*-
###########################################################################
## Python code generated with wxFormBuilder (version Oct 8 2012)
## http://www.wxformbuilder.org/
##
## PLEASE DO "NOT" EDIT THIS FILE!
###########################################################################
impo... |
# -*- coding: utf-8 -*-
#
# MCR-Analyser
#
# Copyright (C) 2021 Martin Knopp, Technical University of Munich
#
# This program is free software, see the LICENSE file in the root of this
# repository for details
from pathlib import Path
from qtpy import QtCore, QtGui, QtWidgets
import mcr_analyser.utils as util
from mc... |
from neuroml import NeuroMLDocument
from neuroml import IzhikevichCell
from neuroml.writers import NeuroMLWriter
from neuroml.utils import validate_neuroml2
def write_izhikevich(filename="./tmp/SingleIzhikevich_test.nml"):
nml_doc = NeuroMLDocument(id="SingleIzhikevich")
nml_filename = filename
iz0 = Izh... |
# -*- coding: utf-8 -*-
#
# zernike.py
# aopy
#
# Created by Alexander Rudy on 2013-08-09.
# Copyright 2013 Alexander Rudy. All rights reserved.
#
"""
Zernike Polynomials
===================
The `zernike polynomials`_ are a modal basis set defined on a circular aperture, and so are useful for optics.
They are ... |
#!/usr/bin/env python
'''
Class 9 - Exercise 3
'''
def func3(param='Whatever'):
'''
Print a parameter when a function is called
'''
print param
if __name__ == '__main__':
print 'whatever is just a module, you need to import it'
|
import unittest
import shutil
import tempfile
import numpy as np
# import pandas as pd
# import pymc3 as pm
# from pymc3 import summary
# from sklearn.mixture import GaussianMixture as skGaussianMixture
from sklearn.model_selection import train_test_split
from pmlearn.exceptions import NotFittedError
from pmlearn.mix... |
from django.contrib import admin
from comment.models import Comment
admin.site.register(Comment)
|
import requests
import constants
import course_class
def parse_to_html(html_file):
'''Parse courses from Albert into data.html file.'''
# Constants needed for the request
url = "https://m.albert.nyu.edu/app/catalog/getClassSearch"
payload='CSRFToken=0cacdd6a262ee0c2540ca0f1d44089d2&acad_group=UH&c... |
# Copyright (c) 2019 Horizon Robotics. 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 applicab... |
# Copyright 2010-2012 Institut Mines-Telecom
#
# 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 agre... |
import re
import unittest
from unittest.mock import MagicMock, Mock
from genie.libs.sdk.apis.nxos.aci.utils import (
copy_from_device, copy_to_device)
class TestUtilsApi(unittest.TestCase):
def test_copy_from_device_nxos_aci(self):
device = MagicMock()
device.hostname = 'router'
dev... |
"""Link regular expressions used by link_transformer_preprocessor module."""
import re
# Handle TW wikilink inner text
TW_RC_LINK_RE = re.compile(
(
r"rc:\/\/"
r"(?P<lang_code>[^\[\]\(\)]+?)"
r"\/tw\/dict\/bible\/(?:kt|names|other)\/"
r"(?P<word>[^\[\]\(\)]+?)$"
)
)
# Handle wi... |
from distutils.core import setup
setup(
name='qsubpy',
version='0.1dev',
packages=['qsubpy',],
)
|
import sys
from PySide2.QtWidgets import QApplication, QListWidget
if __name__ == '__main__':
"""
Simple QListWidget showing some items
"""
app = QApplication(sys.argv)
# Let's make the QListWidget show this data
data = ["ONE", "TWO", "THREE", "FOUR", "FIVE"]
list_widget = QListWidget()... |
# 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
fro... |
import pandas as pd
import datetime
import time
import pytz
import numpy
import json
import mysql.connector
# ADMIN DATA
admin = {
'user_name': 'IngenHouzs',
'password':'ILoveIndonesia'
}
def connect_db(machine):
global local_item_list
global dropbox_items
global dtbs ... |
import bpy, _cycles
import bmesh
import random
import math
import numpy as np
from mathutils import Vector, Euler
import os
import addon_utils
import string
import pickle
from bpy_extras.object_utils import world_to_camera_view
#########################################################################################... |
class DeviceService(object):
def __init__(self):
self.serviceId = "serviceId"
self.serviceType = "serviceType"
self.data = "data"
self.eventTime = "eventTime"
def getServiceId(self):
return self.serviceId
def setServiceId(self, serviceId):
self.serviceId = ... |
import unittest
from collections import defaultdict
from unittest import mock
import torch
from reagent.core.types import PolicyGradientInput
from reagent.evaluation.evaluator import get_metrics_to_score
from reagent.gym.policies.policy import Policy
from reagent.gym.policies.samplers.discrete_sampler import SoftmaxAc... |
import unittest
from dxl.fs.path import Path
from dxl.fs.file import File, NotAFileError
from fs.memoryfs import MemoryFS
from fs.tempfs import TempFS
class TestFile(unittest.TestCase):
def test_exist(self):
mfs = MemoryFS()
mfs.touch('test.txt')
f = File('test.txt', mfs)
self.asser... |
#!/usr/bin/python3
import pytest
from brownie.test import strategy
from hypothesis import HealthCheck
class StateMachine:
coin = strategy('uint16', max_value=6)
valueEth = strategy('uint256', min_value=9 * 10 ** 17, max_value=11 * 10 ** 17)
valueUSD6 = strategy('uint256', min_value=900 * 10 ** 6, max_val... |
# -*-coding:utf-8-*-
# coding=utf-8
import random
import math
def neighbor_x(x=1, p=1, d=1):
'''
initial value:param x:
dimension:param p:
distance:param d:
a value of x's nerghbor:return:
'''
if p == 1:
N_x = (-1) ** random.randint(0, 1) * random.random() * d
N_x = N_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.