content stringlengths 5 1.05M |
|---|
# -*- coding: utf8- -*-
import unittest
import os
from androguard.misc import clean_file_name
import tempfile
class MiscTest(unittest.TestCase):
def testCleanPath(self):
self.assertEqual("foobarfoo_", clean_file_name("foobarfoo ", unique=False))
self.assertEqual("foobarsdf_", clean_file_name("foob... |
import numpy as np
from scipy import sparse
import math
from sklearn.metrics.pairwise import euclidean_distances as ecdist
from sklearn.metrics import pairwise_distances_chunked as pdist_chunk
from sklearn.cluster import KMeans
from sklearn.cluster.k_means_ import _init_centroids
from src.bound_update import bound_upda... |
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import versioneer
setup(
name='glassure',
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
license='MIT',
author='Clemens Prescher',
author_email="clemens.prescher@gmail.com",
url='https://github.com/... |
from enum import Enum
class SRLType(Enum):
SRL = 1
ENVIRONMENT = 2 # defined as anything from the environment (joints, ground_truth, ...)
|
#!/usr/bin/env python3
#
# Copyright 2019-present MongoDB 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 skimage.io import imread
from skimage.transform import radon, resize
import warnings
import numpy as np
import pywt
import scipy.interpolate as interpolate
from scipy.optimize import minimize
from scipy.signal import correlate
import time
import math
import sys
import scipy.sparse as sp
import scipy.linalg as sla
... |
from flask import Blueprint
api_controller = Blueprint('api', __name__)
@api_controller.route('/')
def index():
return 'api not found'
|
from model.contact import Contact
import random
import string
import os.path
import jsonpickle
import getopt
import sys
try:
opts, args = getopt.getopt(sys.argv[1:], "n:f:", ["number of groups", "file"])
except getopt.GetoptError as err:
getopt.usage()
sys.exit(2)
n = 5
f = "data/contacts.json"
print(opt... |
from django.conf import settings
from django.utils.module_loading import import_string
from ratelimit.exceptions import Ratelimited
class RatelimitMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
"""
Sets REMOTE_ADDR correctl... |
"""empty message
Revision ID: ff12276c797c
Revises: c7c115127d45
Create Date: 2018-08-28 11:33:09.683738
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'ff12276c797c'
down_revision = 'c7c115127d45'
branch_labels = None
depends_on = None
def upgrade():
# ... |
# <<BEGIN-copyright>>
# Copyright 2021, Lawrence Livermore National Security, LLC.
# See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: BSD-3-Clause
# <<END-copyright>>
"""
This module contains the xData class that must be the base class for all xData classes.
"""
import abc
__metaclass__ = ... |
# -*- coding: utf-8 -*-
import base64
import json
import re
import sys
from config import ESMConfig
from httpclient import HTTPClient
from exceptions import ESMError
class ESM(object):
def __init__(self, esmcfg, api_version='2'):
"""Initialize the ESM class.
Args:
esmc... |
import logging
import emission.core.get_database as edb
import emission.storage.timeseries.abstract_timeseries as esta
import pandas as pd
import matplotlib as mpl
mpl.use('AGG')
import matplotlib.pyplot as plt
import datetime as dt
import matplotlib.dates as mdates
def get_app_analytics():
df = pd.DataFrame()
... |
# -*- coding: utf-8 -*-
"""User models."""
import enum
from flask_login import UserMixin
from sqlalchemy import and_
from sqlalchemy.ext.hybrid import hybrid_method
from sqlalchemy_utils import ChoiceType
from ups.database import (Column, Model, UuidPrimaryKey, db)
from ups.extensions import bcrypt
class UserType(... |
from django.contrib.auth.decorators import login_required
from AuShadha.apps.ui.ui import ui as UI
#from .models import VisitDetail, VisitComplaint
PatientDetail = UI.get_module("PatientRegistration")
VisitDetail = UI.get_module("OPD_Visit")
VisitComplaint = UI.get_module("OPD_Visit_Complaint")
def get_all_compla... |
import sys, os
import getopt
import tornado.wsgi
import tornado.httpserver
import tornado.ioloop
hostname = '127.0.0.1'
port = 80
opts, args = getopt.getopt(sys.argv[1:], "h:p:", [])
for o, a in opts:
if o == '-h':
hostname = a
elif o == '-p':
port = int(a)
path = os.path.dirname(os.path.absp... |
from unittest.mock import MagicMock
from two1.wallet import fees
def test_get_fees():
f = fees.get_fees()
assert 'per_kb' in f
assert 'per_input' in f
assert 'per_output' in f
assert f['per_kb'] >= 0 and f['per_kb'] <= 100000
# Mock a response that doesn't have the correct data
fees._f... |
from datetime import datetime
import numpy as np
from exrec.core.interface import Logger
from exrec.model.interface import Model
from exrec.model.optimizer import als
from exrec.preprocessing.interface import RatingDataset
class MF:
cls_name: str
# Basic information
name: str
n_users: int
n_item... |
from fastapi.testclient import TestClient
from app.main import app
client = TestClient(app)
email = "bsmith@aol.com"
password = "sup3r$ecreT"
def test_signUp():
response = client.post(
"/user/signup",
json={
"fullname": "Bob Smith",
"email": email,
"passwor... |
import json
from datetime import datetime
import simpy
from schema import Schema, SchemaError
class SimulationWorld:
def __init__(self,
sim_duration: int,
initial_time: int,
config_file,
measured_latency,
measured_throughput_rece... |
import unittest
import logging
from optlib.gbs import (
_psi,
_phi,
_cbnd,
_bjerksund_stensland_1993,
_bjerksund_stensland_2002,
_american_option,
_gbs,
_approx_implied_vol,
_gbs_implied_vol,
_american_implied_vol,
merton,
black_76,
garman_kohlhagen,
black_schole... |
import os
os.environ["MKL_NUM_THREADS"] = "1"
os.environ["NUMEXPR_NUM_THREADS"] = "1"
os.environ["OMP_NUM_THREADS"] = "1"
import itertools
import numpy as np
from scipy import linalg
'''
import matplotlib
matplotlib.use('agg')
from matplotlib import pyplot as plt
'''
import pandas as pd
from random import randint
from... |
# -*- coding: utf-8 -*-
"""
Tool for downloading data from the North American Regional Reanalysis (NARR) product
Note that this requires the netCDF4 module to be compiled with opendap support (libcurl)
Created on Thu Nov 08 17:22:40 2012
@author: mrayson
"""
import numpy as np
from netCDF4 import Data... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.apps import AppConfig
class HydroshareConfig(AppConfig):
name = 'hydroshare'
|
import os
from discord.ext import commands
def alpha_vantage_command():
async def predicate(ctx: commands.Context):
if os.environ['ALPHA_VANTAGE_TOKEN'] is None:
await ctx.send("**An Alpha Vantage API key must be provided in order to use this command.** :key:")
return False
... |
# Generated by Django 3.1.3 on 2020-11-21 08:39
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Question',
fields=[
... |
import keras
from keras import Sequential
from keras.initializers import he_normal
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, BatchNormalization, Activation, Dropout
from palmnet.layers.pbp_layer import PBPDenseDensify
from palmnet.layers.random_sparse_facto import RandomSparseFactorisationConv2D, ... |
import numpy as np
from sklearn.metrics import confusion_matrix
def get_intersection_union_per_class(confusion_matrix):
number_of_labels = confusion_matrix.shape[0]
matrix_diagonal = [confusion_matrix[i][i] for i in range(number_of_labels)]
errors_summed_by_row = [0] * number_of_labels
for row... |
from autorop import PwnState, Pipeline, bof, leak, libc, call, constants
def classic(
find: constants.TYPE_PIPE = bof.corefile,
leak: constants.TYPE_PIPE = leak.puts,
lookup: constants.TYPE_PIPE = libc.auto,
shell: constants.TYPE_PIPE = call.system_binsh,
) -> constants.TYPE_PIPE:
"""Perform a "cl... |
from django.db import models
from django.conf import settings
from django.dispatch import receiver
from django.db.models.signals import post_save
import logging
logging.basicConfig()
logger = logging.getLogger(__name__)
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=... |
from unittest import TestCase
from unittest.mock import Mock
from objective.domain.objective import Objective
from objective.service.objectiveService import ObjectiveService
class TestObjectiveService(TestCase):
def setUp(self) -> None:
self.observer = Mock()
self.service = ObjectiveService()
... |
# Time complexity: O(n)
# Approach: Adding carry till it reaches the most significant digit and then if it still remains, then create new array and extend.
class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
n, carry = len(digits), 0
s = digits[n-1]+1
digits[n-1], carry = s%1... |
"""
InteractiveSceneElements can be activated by an agent.
"""
from __future__ import annotations
from typing import Dict, Optional, Union, List, Type, TYPE_CHECKING
if TYPE_CHECKING:
from simple_playgrounds.element.elements.gem import GemElement
from abc import ABC
from simple_playgrounds.common.definitions im... |
# coding: utf-8
import json
import watson_developer_cloud
discovery = watson_developer_cloud.DiscoveryV1(
'2016-11-07',
username='YOUR SERVICE USERNAME',
password='YOUR SERVICE PASSWORD')
environments = discovery.get_environments()
print(json.dumps(environments, indent=2))
news_environments = [x for x in... |
from django import forms
from django import forms
from django.conf import settings
from django.forms.renderers import TemplatesSetting
from django.utils.translation import ugettext_lazy as _
from crispy_forms import bootstrap, helper, layout
from .models import Bulletin, Category, TYPE_CHOICES
TYPE_FILTER_CHOICES = (... |
#!/usr/bin/env python3
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import text
from opentelemetry import trace
from opentelemetry.instrumentation.flask import FlaskInstrumentor
from opentelemetry.instrumentation.sqlalchemy import SQLAlchemyInstrumentor
import uptrace
uptrace.config... |
# MIT License
#
# Copyright (C) 2021. Huawei Technologies Co., Ltd. All rights reserved.
#
# 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 th... |
# MIT License
# Copyright (c) 2022 Izhar Ahmad
# 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, pu... |
#!/usr/bin/python3
def ratio_one(libraries):
ratioArray = list()
for library in libraries:
ratioArray.append((sum(library["books"]) * library["signup_days"]) / (library["book_count"] * library["books_per_day"]))
return ratioArray
def ratio_two(libraries):
ratioArray = list()
for library in... |
import pystache
from os import path
WIFIS = [
"msl",
"robo_dev_net",
"coimbra"
]
def gen_interfaces(robot_type, robot_id, wifi):
# get template
template_path = path.join(path.dirname(__file__), "data/network/interfaces_template.mustache")
f = open(template_path, "r")
template = f.read()
... |
from diffgram.core.directory import Directory
class Job():
def __init__(self,
client,
job_dict=None):
self.client = client
if self.client.project_string_id is None:
raise Exception("\n No project string id in client.")
# TODO review way to ... |
from __future__ import annotations
from dataclasses import dataclass, field
from enum import Enum
from functools import wraps
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Type, Union
from retry.api import retry_call # type: ignore
from lisa import notifier, schema,... |
from datetime import datetime
import requests
import sys
import time
'''
This is a script to grab HTML from a website and compare it to a previous state.
`python main.py debug` to run three quick loops
`python main.py` to run in infinite loop with waitTime (second) waits
'''
# this dictionary will be modified in-pla... |
import unittest
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
from llvm.core import Module
from .support import TestCase, tests
class TestOperands(TestCase):
# implement a test function
test_module = """
define i32 @prod(i32, i32) {
entry:
%2 = mul i32 %0, %1
... |
import os
os.environ["CUDA_VISIBLE_DEVICES"]="-1"
import numpy as np
import ismo.iterative_surrogate_model_optimization
import ismo.train.trainer_factory
import ismo.train.multivariate_trainer
import ismo.samples.sample_generator_factory
import ismo.optimizers
import matplotlib.pyplot as plt
class Objective:
def _... |
#!/usr/bin/env python
#
# cli.py
#
"""
Wandbox CLI for Python
"""
import os
import sys
import json
import traceback
import fnmatch
from . import __version__ as VERSION
from .wandbox import Wandbox
from .runner import Runner
from .wrapper import Wrapper
from argparse import ArgumentParser
from argparse import SUPPRES... |
"""
Copyright 2018-2019 EPCC, University Of Edinburgh
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... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2017-08-03 17:42
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('comics', '0002_auto_20170802_1611'),
]
operations = [
migrations.AlterModel... |
# -*- coding: utf-8 -*-
"""
Ref:
- https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Client.list_buckets
"""
from __future__ import unicode_literals
import attr
from ..aws_resources import ResData, AwsResourceSearcher, ItemArgs
from ...settings import SettingValues
from ...cache i... |
import platform
import json
from urllib.parse import urlencode
from ykdl.extractors.douyu.util import ub98484234
from ykdl.util.jsengine import chakra_available, quickjs_available, external_interpreter
from ykdl.util.html import get_content
from .. import config
from ..engine.decorators import Plugin
from ..plugins i... |
import os
import sys
dir = sys.argv[1]
for file in os.listdir(dir):
#sub_dir = dir + '/'+ folder
#design_file = os.path.join(sub_dir,'multilier_dc.v')
if os.path.isdir(os.path.join(dir,file)):
continue
target = file.split('.')[0]
with open(os.path.join(dir,file),'r') as f:
lines = f... |
from .filefolder_tools import *
|
from enum import Enum
class TestType(Enum):
PRIMARY = "primary"
REPLICA = "replica"
|
################################
# population simulations routines
##############################
#imports
from .initialize import *
from astropy.coordinates import SkyCoord
import scipy.integrate as integrate
from scipy import stats
from ..utils.tools import drop_nan, splat_teff_to_spt,kernel_density
from ..data... |
"""Climate Change Awareness (ChiChA)
This file is automatically generated by Scrapy.
Copyright (c) 2020 Akshat Naik and Tony Hu.
Licensed under the MIT License. See LICENSE in the project root for license information.
"""
# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.... |
# https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers
total_binary_sum = 0
def sum_root_to_leaf(root):
if root is None: return
helper(root, str(root.val))
return total_binary_sum
def helper(node, path):
if node.left:
helper(node.left, path + str(node.left.val))
i... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Script for testing parsers
"""
# This code is a part of coolisf library: https://github.com/letuananh/intsem.fx
# :copyright: (c) 2014 Le Tuan Anh <tuananh.ke@gmail.com>
# :license: MIT, see LICENSE for more details.
import unittest
import logging
from coolisf.mode... |
# @Author : guopeiming
# @Datetime : 2019/10/31 22:13
# @File : dataset.py
# @Last Modify Time : 2019/10/31 22:13
# @Contact : 1072671422@qq.com, guopeiming2016@{gmail.com, 163.com}
import torch
import torch.nn as nn
import torch.nn.init as init
class StackLSTMCell(nn.Module):
"""
StackLSTMCell
"""
de... |
import abc
import os
from pkg_resources import DistributionNotFound, get_distribution
from six.moves.configparser import SafeConfigParser
from six import add_metaclass
from . import log_utils
try:
__version__ = get_distribution(__name__).version
except DistributionNotFound:
# package is not installed
pas... |
from collections import OrderedDict
import logging
from logging.config import fileConfig
import os
import sys
from paste.deploy import loadapp, loadserver, loadfilter, appconfig
import paste.deploy.loadwsgi as loadwsgi
from plaster import ILoader
from plaster.protocols import IWSGIProtocol
PY2 = sys.version_info[0] ... |
# 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, software
# distributed under t... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import random
import os, sys
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def get_noise(shape, noise_type):
if noise_type == "gaussian":
return torch.randn(*shape).cuda()
elif noise_type == "uniform":
... |
# Based on: http://www.djangosnippets.org/snippets/73/
#
# Modified by Sean Reifschneider to be smarter about surrounding page
# link context. For usage documentation see:
#
# http://www.tummy.com/Community/Articles/django-pagination/
from django import template
register = template.Library()
def paginator(c... |
import unittest
from bleachfields import BleachField
class BleachFieldTest(unittest.TestCase):
def test_simple_tag(self):
test_bleach_field = BleachField()
simple_html = '<span>Tags are not allowed</span>'
simple_html_result = 'Tags are not allowed'
self.assertEqual(
... |
#!/usr/bin/env python
# coding: utf-8
# # データ拡張します。
from sklearn import preprocessing
from tqdm import tqdm, trange
import tensorflow as tf
import cv2
from PIL import Image, ImageDraw, ImageFilter
import matplotlib.pyplot as plt
import numpy as np
import os
import shutil
import csv
from Union import csv_read
import sy... |
# Copyright 2015-2017 Capital One Services, LLC
# Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
from datetime import datetime, timedelta
from botocore.exceptions import ClientError
import boto3
import json
import logging
def bucket_info(c, bucket):
result = {'Bucket': bucket}
r... |
from django import forms
from clientmanagement import views as main_views
from django.urls import reverse
from django.shortcuts import render, render_to_response, redirect
from datetime import datetime
from models import updates
from clientmanagement.widget import quill
import pytz
class SystemUpdateForm(forms.ModelFo... |
from unittest.mock import MagicMock
import box
import pytest
import yaml
import prefect
from prefect.agent.ecs.agent import (
merge_run_task_kwargs,
ECSAgent,
DEFAULT_TASK_DEFINITION_PATH,
)
from prefect.storage import Local, Docker
from prefect.run_configs import ECSRun, LocalRun, UniversalRun
from prefe... |
from . import HeroDoesNotExistError
from .heroes_data import HEROES
class Hero:
"""Hero is able to represent a hero that exists in the game, as
well as convert to different representations (battle.net slug,
CSS class)."""
PUNCTUATION_BLACKLIST = (",", ".", "`", "'", "-")
def __init__(self, name)... |
# -*- coding: utf-8 -*-
"""
Prepares the figure and table descriptions in html.
"""
import os
import sys
import subprocess
# Add the path to bbob_pproc
if __name__ == "__main__":
(filepath, filename) = os.path.split(sys.argv[0])
sys.path.append(os.path.join(filepath, os.path.pardir))
import matplotlib
... |
import numpy as np
import pygsti.algorithms.fiducialselection as fs
import pygsti.circuits as pc
from . import fixtures
from ..util import BaseCase
class FiducialSelectionUtilTester(BaseCase):
def test_build_bitvec_mx(self):
mx = fs.build_bitvec_mx(3, 1)
# TODO assert correctness
class Fiducial... |
from utils import *
class Element:
"""
Some element of the code, which has JsDoc.
@param {string} code Code of an element.
@param {jsCodeParser.jsDoc.JsDoc} jsDoc JsDoc object of an element.
@attribute {string} code Code of an element.
@attribute {jsCodeParser.jsDoc.JsDoc... |
def main():
x = 0
while (x < 5):
print(x)
x = x + 1
for x in range(5, 10):
# if(x==7): break
if (x % 2 == 0): continue
print(x)
days = ["Mon", "Tue"]
for d in days:
print(d)
for i, d in enumerate(days):
print(i, d)
if __name__ == "__m... |
from ..models import TransactionViolation, AccountResponse
from ..decorators import validator
from .operation_controller import OperationController
class TransactionOperationController(OperationController):
'''Transaction operation controller.'''
@validator
def validate_account_initialization(self, operation, ... |
import numpy as np
from neural_nets import *
import unittest
class TestNeuralNetwork(unittest.TestCase):
def test_relu(self):
self.assertEqual(rectified_linear_unit(-3), 0)
self.assertEqual(rectified_linear_unit(0), 0)
self.assertEqual(rectified_linear_unit(9), 9)
def test_relu_deriva... |
import requests
import sqlite3
from ratelimit import limits, sleep_and_retry, RateLimitException
from backoff import on_exception, expo
'''
System Necessary Variables
'''
FIVE_MINUTES = 300
connection = sqlite3.connect('database.db') # connect to database
cursor = connection.cursor() # instantiate the cursor objec... |
from .vgg16_bn import init_weights, vgg16_bn
__all__ = ['init_weights', 'vgg16_bn'] |
"""
Mine negative images for Null class with Yolo training
"""
import click
import pandas as pd
from vframe.utils import click_utils
from vframe.settings import types
from vframe.settings import vframe_cfg as cfg
from vcat.settings import vcat_cfg
# --------------------------------------------------------
# testing
#... |
import textwrap
REDSHIFT_SQL_STATEMENT = """
SELECT DISTINCT ss.userid,
ss.query,
sui.usename,
ss.tbl,
sq.querytxt,
sti.database,
sti.schema,
sti.table,
sq.starttime,
sq.endtime,
sq.aborted
... |
"""Background Jobs for Welcome Wizard."""
from collections import OrderedDict
from django.utils.text import slugify
from nautobot.dcim.forms import DeviceTypeImportForm
from nautobot.dcim.models import (
ConsolePortTemplate,
ConsoleServerPortTemplate,
DeviceBayTemplate,
FrontPortTemplate,
Interface... |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 2 11:19:50 2018
@author: mayank
"""
import numpy as np
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics.pairwise import linear_kernel,rbf_kernel,manhattan_distances,polynomial_kernel,sigmoid_kernel,cosine_similarity,laplacian_kernel,pair... |
"""
Script for loading pickle file with trajectories and
animating them.
"""
import gym
import pickle
import click
import sys, os
sys.path.insert(0, os.path.abspath('..'))
from utils import helpers
DESC = '''
Helper script to visualize optimized trajectories (list of trajectories in format).\n
USAGE:\n
$ pyth... |
# Generated by Django 3.1.2 on 2020-10-19 21:47
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('references', '0004_publisher'),
('products', '0001_initial'),
]
operations = [
migrations.AlterFiel... |
from dash import dcc, html
layout = html.Div([
html.H1("Reference Page", className="display-2 mb-5 "),
html.Hr(),
html.P("opsies usually occur with 2 things wrong file input the table format does not have the right headers")
]) |
#Author : Guru prasad Raju
#Function signature with parameter name
def welcome_greetings(name):
#Printing message
print("Namaste: "+name)
#Calling function with argument 'Ram'
welcome_greetings('Ram') |
'''
Created by auto_sdk on 2015.06.23
'''
from aliyun.api.base import RestApi
class Rds20140815DescribeDBInstancesByExpireTimeRequest(RestApi):
def __init__(self,domain='rds.aliyuncs.com',port=80):
RestApi.__init__(self,domain, port)
self.ExpirePeriod = None
self.PageNumber = None
self.PageSize = None
def ge... |
import os
import time
from alive_progress import alive_bar
import requests as rq
from bs4 import BeautifulSoup as bs
# TODO
# Generates an SQL database of the UK data to be queried by data processing applications
CWD = os.path.dirname(os.path.realpath(__file__)) + "/"
print("Working In {}".format(CWD))
def cleanup(... |
# -*- encoding=utf-8 -*-
import uuid
import threading
# 基本任务对象
class Task:
def __init__(self, func, *args, **kwargs):
# 任务具体逻辑,通过函数引用传递进来
self.callable = func
self.id = uuid.uuid4()
self.args = args
self.kwargs = kwargs
def __str__(self):
return 'Task id: ' + ... |
_base_ = [
'../../_base_/models/bmn_400x100.py', '../../_base_/default_runtime.py'
]
# dataset settings
dataset_type = 'ActivityNetDataset'
data_root = 'data/NetballNet/mmaction_feat/'
data_root_val = 'data/NetballNet/mmaction_feat/'
ann_file_train = 'data/NetballNet/nnet_anno_train.json'
ann_file_val = 'data/Netb... |
"""
Functionality to instantiate and upload the lambda in AWS.
"""
import os.path
import boto3
import factoryfactory
from lambda_tools import configuration
class DeployError(Exception):
pass
class Deployer(factoryfactory.Serviceable):
def __init__(self, func, name):
if not func.deploy:
... |
import pytest
import responses
from osf.models import SpamStatus
from osf_tests.factories import AuthUserFactory
@pytest.mark.django_db
class TestSpam:
@pytest.fixture()
def user(self):
return AuthUserFactory()
@pytest.fixture()
def request_headers(self):
return {
'Remo... |
from __future__ import division
import scitbx.rigid_body
import scitbx.graph.tardy_tree
import scitbx.math
from scitbx.array_family import flex
from libtbx.str_utils import show_string
from libtbx.utils import sequence_index_dict
from libtbx.utils import Sorry
import math
rotamer_info_master_phil_str = """\
tor_ids = ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 31 20:35:18 2017
@author: Anderson Banihirwe
"""
from itertools import product, combinations
assignments = []
rows = 'ABCDEFGHI'
cols = '123456789'
def assign_value(values, box, value):
"""
Please use this function to update your values ... |
from ml_tutor.model import BaseModelClassification
from sklearn.decomposition import PCA
import random
import numpy as np
import matplotlib.pyplot as plt
class KNeighbourClassifier(BaseModelClassification):
def __init__(self, n_neighbors=5, visual_training=True, number_of_visual_steps=-1):
"""
Create the K-Nea... |
import pytest
from refpapers.schema import BibtexKey
@pytest.mark.parametrize(
'inp,author,year,word',
[
('foo2021bar', 'foo', 2021, 'bar'),
('a1000b', 'a', 1000, 'b'),
('hyphen-name1024multiWord', 'hyphen-name', 1024, 'multiWord'),
('aa9999word2profit', 'aa', 9999, 'word2prof... |
# Implement By https://github.com/jusidama18
# Based on this https://github.com/DevsExpo/FridayUserbot/blob/master/plugins/updater.py
import sys
import subprocess
import heroku3
from datetime import datetime
from os import environ, execle, path, remove
from git import Repo
from git.exc import GitCommandError, Invali... |
import json
import sys
import io
import time
sys.path.append('../gen-py')
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from slidinghyper import SlidingHyperService
host, port = 'localhost', 9007
transport = TSocke... |
from astropy.coordinates import SkyCoord
import numpy as np
import astropy.coordinates
from astropy.coordinates import AltAz, FK5, Galactic
import astropy.units as u
import astropy.time
import astropy.constants as c
import xarray as xr
import necstdb
from datetime import datetime
from tqdm import tqdm
from .kisa_rev im... |
print("Hello World from PYthon")
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Code harvested 00:35 MDT 24 NOV 2015 and derived from these sources:
# http://www.wadewegner.com/2014/05/create-an-ibeacon-transmitter-with-the-raspberry-pi/
# https://github.com/tyarkoni/transitions
"""
* (dispatcher.py) Function:
* Reads sensor
* Posts using ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.