text stringlengths 1 927k |
|---|
# -*- coding: utf-8 -*-
import config as cfg
import pyodbc
"""
Fill in closest Police Stations within 10 miles
If there is no closest PS, then ClosestPSDistance = MeanPSDistance = 10.5 miles
Latitude/Longitude distance coefficients:
--Miles 3958.75
--Kilometers 6367.45
--Feet 20890584
--Meters 6367450
"""
def calc... |
i = 0
while i < 21474826:
i = i + 1
if i % 1000000 == 0:
print i |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @author: Wesley
# @time: 2020-12-11 10:47
import os
import time
import torch
from torch import nn
from models.dinknet34 import DinkNet34
from loss import dice_bce_loss
from models.unet import UNet
from dataset import MyDataset
from torch.utils.data import DataLoader
im... |
"""
Convert a large audio wav file (album length, i.e. > 30 minutes typically)
into a series of videos consisting of the audio synchronized with images of the
spectrogram.
"""
import os
import sys
import multiprocessing as mp
import subprocess
import tqdm
import numpy as np
import librosa.core
import librosa.display
i... |
import requests
parameters = {
"amount": 10,
"type": "multiple"
}
response = requests.get(url="https://opentdb.com/api.php", params=parameters)
question_data = response.json()["results"]
"""
Sample Response
[
{
'category': 'Sports',
'type': 'multiple',
'difficulty': 'medium', ... |
from imageio import imread
import matplotlib.pyplot as plt
def plot_animal_tree(ax=None):
import graphviz
if ax is None:
ax = plt.gca()
mygraph = graphviz.Digraph(node_attr={'shape': 'box'},
edge_attr={'labeldistance': "10.5"},
format="... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-11-21 23:48
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('property_api', '0001_initial'),
]
operations = [
migrations.RemoveField(
... |
import _plotly_utils.basevalidators
class SizemodeValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(
self, plotly_name="sizemode", parent_name="scattercarpet.marker", **kwargs
):
super(SizemodeValidator, self).__init__(
plotly_name=plotly_name,
p... |
from typing import List
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from dispatch.database import get_db, search_filter_sort_paginate
from .models import (
TeamContactCreate,
TeamContactRead,
TeamContactUpdate,
TeamPagination,
)
from .service import... |
'''
only for RRP Hopper
Shihao Feng
2021.10.28
'''
import numpy as np
import pybullet as p
from leg_kinematics import LegKinematicsRRP
import pinocchio as pin
class JointPDController(object):
def __init__ (self):
self.kp = np.array([70, 70, 1500])
self.kd = np.array([2, 2, 10])
def solve(self... |
"""A collection of classes and methods to deal with collections of
rates that together make up a network."""
# Common Imports
from __future__ import print_function
import functools
import math
from operator import mul
import os
from collections import OrderedDict
from ipywidgets import interact
import matplotlib as... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import torch
import numpy as np
import matplotlib.pyplot as plt
# from MMDBalancing import MMDBalancing as MMDB
# from OptimalTransportBalancing import OptimalTransportBalancing as OTB
# from NeuralAdversarialBalancing import NeuralAdversarialBalancing as NAB
#get_ipyth... |
# -*- coding: utf-8 -*-
import datetime
from django.db.models import Count
import os
from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
from django.db.models.signals import post_save
from djang... |
from pathlib import Path
from PIL import Image, ImageOps
def generate_thumbnail(file_path, max_height):
size = (max_height, max_height)
thumbnail = ImageOps.fit(Image.open(file_path), size, Image.ANTIALIAS)
thumbnail.save(f'{Path(file_path).stem}_thumb_{max_height}.jpg', 'JPEG')
return thumbnail |
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... |
import matplotlib.pyplot as plt
import seaborn as sns
class PlotTree():
def __init__(self,tree_class):
self._tree_class=tree_class
self._decision_node = dict(boxstyle="sawtooth", fc="0.8")
self._leaf_node = dict(boxstyle="round4", fc="0.8")
self._arrow_args = dict(arrowstyle="<-")... |
"""
Delta E z.
https://www.osapublishing.org/oe/fulltext.cfm?uri=oe-25-13-15131&id=368272
"""
from ..distance import DeltaE
import math
from .. import util
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING: # pragma: no cover
from ..color import Color
class DEZ(DeltaE):
"""Delta E z class."""
NAM... |
from typing import Union, Tuple, Sized, Container, Any, TypeVar, Callable
from typing import Iterable, Iterator, Sequence, Dict, Generic, cast
from typing import Optional, List, overload
from dataclasses import dataclass
import numpy
import sys
try:
import cupy
get_array_module = cupy.get_array_module
except ... |
"""Talk""" |
"""Debugger basics"""
import fnmatch
import sys
import os
__all__ = ["BdbQuit", "Bdb", "Breakpoint"]
class BdbQuit(Exception):
"""Exception to give up completely."""
class Bdb:
"""Generic Python debugger base class.
This class takes care of details of the trace facility;
a derived class should imp... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import os
ANSIBLE_SSH_PORT = '2222'
def get_args():
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('--list', action='store_true')
parser.add_argument('--host')
return parser.parse_args()
def wd_to_scrip... |
"""ThreatConnect TI Address"""
from ..indicator import Indicator
class Address(Indicator):
"""Unique API calls for Address API Endpoints"""
def __init__(self, tcex, **kwargs):
"""Initialize Class Properties.
Args:
ip (str): The value for this Indicator.
active (bool, ... |
#
# PySNMP MIB module A3COM-HUAWEI-LswIGSP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/A3COM-HUAWEI-LswIGSP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 16:51:01 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.... |
#!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you ma... |
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2020
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
#... |
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import logging
from lineuzinho import Lineuzinho
def main():
logging.getLogger(__name__)
logging.basicConfig(format='%(asctime)s [%(levelname)s]: %(message)s', level=logging.INFO)
lineuzinho = Lineuzinho()
updater = Updater(lin... |
# Goal: get ebola/Lassa for Bonnie's plasma samples.
# Simple clean and merge
import pandas as pd
import os
os.chdir("/Users/laurahughes/GitHub/cvisb_data/sample-viewer-api/src/static/data/")
import helpers
df = pd.read_excel("/Users/laurahughes/GitHub/cvisb_data/sample-viewer-api/src/static/data/input_data/sample_... |
#!/usr/bin/env python
#
# Licensed to the .NET Foundation under one or more agreements.
# The .NET Foundation licenses this file to you under the MIT license.
#
##
# Title :run-pmi-diffs.py
#
# Notes:
#
# TODO: Instead of downloading and extracting the dotnet CLI, can we convert
# to using init-tools.cmd/... |
# coding: utf-8
import pprint
import re
import six
from huaweicloudsdkcore.sdk_response import SdkResponse
class ListApisBindedToRequestThrottlingPolicyV2Response(SdkResponse):
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute ty... |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from .base_weapon import Weapon
from ... import dice as D, material as M
class BaseClub(Weapon):
pass
class Club(Ba... |
# coding: utf-8
"""
Isilon SDK
Isilon SDK - Language bindings for the OneFS API # noqa: E501
OpenAPI spec version: 6
Contact: sdk@isilon.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class AuditProgressProgress(obje... |
"""
LoRaWAN Specification v1.0.2
Test Case Group: Functionality
Test Name: FUN_02
"""
#################################################################################
# MIT License
#
# Copyright (c) 2018, Pablo D. Modernell, Universitat Oberta de Catalunya (UOC),
# Universidad de la Republica Oriental del Uruguay (Ude... |
#!/usr/bin/env python
"""settings.py
Udacity conference server-side Python App Engine app user settings
$Id$
created/forked from conference.py by wesc on 2014 may 24
"""
# Replace the following lines with client IDs obtained from the APIs
# Console or Cloud Console.
WEB_CLIENT_ID = '1006324622497-9qlhtun5go635oe5... |
"""
Another Main module.
"""
if __name__ == "__main__":
import stuntcat.cli
cli = stuntcat.cli.Cli()
cli.cli_main() |
import os, shutil, subprocess
import ase.build
import pypospack.io.vasp as vasp
import pypospack.crystal as crystal
import pypospack.io.slurm as slurm
class VaspCalculateBulkProperties(object):
def __init__(self,sim_dir,obj_structure):
self.sim_dir = sim_dir
self.sim_task_list = ['min0','conv_encu... |
import electric_car
my_tesla = electric_car.ElectricCar('tesla', 'roadster', 2016)
print(my_tesla.get_descriptive_name()) |
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 23 22:07:01 2018
@author: yoelr
"""
from ._tank import MixTank
from ._hx import HXutility
class EnzymeTreatment(MixTank):
"""Create an EnzymeTreatment unit that is cost as a MixTank with a heat exchanger."""
_N_outs = 1
#: Residence time (hr)
_tau = ... |
# Copyright Contributors to the Amundsen project.
# SPDX-License-Identifier: Apache-2.0
import datetime
import logging
import re
from collections import defaultdict
from operator import attrgetter
from random import randint
from typing import (Any, Dict, Generator, List, Optional, Set, Tuple, Type,
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 25 12:13:19 2020
@author: metalcorebear
"""
from model import propagation_model
import model_params
import argparse
import os
import pandas as pd
# Specify arguments
def get_path():
parser = argparse.ArgumentParser()
parser.add_argument('-o', '--output', help='E... |
# -*- coding: utf-8 -*-
#
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
# -*- coding: utf-8 -*-
# from cms_bs3_theme.models import ThemeSite
def settings(request):
"""
"""
from . import conf
conf = dict(vars(conf))
# conf.update(ThemeSite.objects.get_theme_conf(request=request, fail=False))
data = request.session.get('cms_bs3_theme_conf', {})
conf.update(data)... |
#!/usr/bin/env python
# ***********************IMPORTANT NMAP LICENSE TERMS************************
# * *
# * The Nmap Security Scanner is (C) 1996-2013 Insecure.Com LLC. Nmap is *
# * also a registered trademark of Insecure.Com LLC. This prog... |
import sys
import cli
intf= sys.argv[1:]
intf = ''.join(intf[0])
print "\n\n *** Configuring interface %s with 'configurep' function *** \n\n" %intf
cli.configurep(["interface loopback55","ip address 10.55.55.55 255.255.255.0","no shut","end"])
print "\n\n *** Configuring interface %s with 'configure' function ***... |
from tello import Tello
import sys
from datetime import datetime
import time
import TelloPro
tello = Tello()
command_lst = []
command_lst.append(TelloPro.get_instance('takeoff', -1, ""))
command_lst.append(TelloPro.get_instance('up', 30, ""))
command_lst.append(TelloPro.get_instance('down', 30, ""))
command_lst.appen... |
"""
Skeleton data structures
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2013, yt Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#------------------... |
from django.contrib import admin
from .models import Article, Category, User
from django import forms
from pagedown.widgets import AdminPagedownWidget
class ArticleForm(forms.ModelForm):
text = forms.CharField(widget=AdminPagedownWidget())
class Meta:
model = Article
fields = '__all__'
clas... |
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("//third_party:repo.bzl", "clean_dep")
def configure_snappy():
http_archive(
name = "com_github_google_snappy",
build_file = clean_dep("//third_party/snappy:BUILD.bzl"),
sha256 = "e170ce0def2c71d0403f5cda61d6e2743373f... |
#!/usr/bin/env python
import logging
import os
import sys
if os.environ.get("ALLENNLP_DEBUG"):
LEVEL = logging.DEBUG
else:
level_name = os.environ.get("ALLENNLP_LOG_LEVEL")
LEVEL = logging._nameToLevel.get(level_name, logging.INFO)
sys.path.insert(0, os.path.dirname(os.path.abspath(os.path.join(__file__, ... |
from datetime import datetime
from jose import jwt
from jose.utils import base64url_decode
from jose.exceptions import JWTError
from vds_vault_oauth.utilities import OAuthContainer
# Token that stores the necessary tokens and provides the ability to decode & log them.
class Token():
def __init__(self, token_value,... |
from django.views.generic import (TemplateView, ListView,
DetailView, CreateView, UpdateView)
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy
from django.conf import settings
from .forms import ChildEditForm, ChildAddForm
from .models impo... |
# Generated by Django 3.1.7 on 2021-05-11 21:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('MatchApp', '0061_apadrinamiento'),
]
operations = [
migrations.AlterField(
model_name='apadrinamiento',
name='tipo_i... |
from torch import nn
class ConvolutionalBlock(nn.Module):
def __init__(self, in_channels=128, out_channels=256, kernel_size=3, padding=1, stride=1, padding_mode='zeros'):
super().__init__()
self.conv1 = nn.Conv1d(in_channels, out_channels, kernel_size=kernel_size, padding=padding, stride=stride,
... |
import sklearn.metrics as metrics
import pandas as pd
import numpy as np
def repair_chrdata(df, tCol):
### Parameters:
# df: input dataframe
# tCol: targeted column label with NaN
### Output
# df: repaired dataframe
# word: string of related dataframe column with some records have NaN in target... |
import os
import numpy as np
import pytest
from ci_framework import FlopyTestSetup, base_test_dir
import flopy
base_dir = base_test_dir(__file__, rel_path="temp", verbose=True)
ex_pth = os.path.join("..", "examples", "data", "mf2005_test")
testmodels = [
os.path.join(ex_pth, f) for f in os.listdir(ex_pth) if f.... |
from urlparse import urlparse
from django import forms
from tower import ugettext_lazy as _lazy
import amo
from mkt.api.forms import SluggableModelChoiceField
from mkt.webapps.models import Addon
class ReceiptForm(forms.Form):
app = SluggableModelChoiceField(
queryset=Addon.objects.filter(type=amo.ADDO... |
from entities.workflow import Workflow
class Main(Workflow):
def _run(self, job):
return {} |
import operator
s1 = "#include <boost/"
lines1 = {}
with open('./boost_includes_1') as f:
lines=f.readlines()
for line in lines:
if s1 in line:
line1 = line[line.find('#'):line.find('\n')]
if lines1.has_key(line1):
lines1[line1] = lines1[line1] + 1
else:
lines1[line1]=1;
sorted_x = sorted(lines1.... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from google.appengine.ext import ndb
from ndb_relations.relations import OneToMany
class User2(ndb.Model):
name = ndb.StringProperty()
class Order2(ndb.Model):
pass
class OrderItem2(ndb.Model):
name = ndb.StringProperty... |
# Copyright 2017 Google Inc.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
#... |
from os import environ
import os
import time
from urllib.parse import urlparse
import aiohttp
from pyshorteners import Shortener
from bs4 import BeautifulSoup
import requests
import re
from pyrogram import Client, filters
API_ID = environ.get('API_ID')
API_HASH = environ.get('API_HASH')
BOT_TOKEN = environ.get('BOT_TO... |
from .aggregate_interval_play import AggregateIntervalPlay
from .milestone import Milestone
from .models import (
AggregateDailyAppNameMetrics,
AggregateDailyTotalUsersMetrics,
AggregateDailyUniqueUsersMetrics,
AggregateMonthlyAppNameMetrics,
AggregateMonthlyPlays,
AggregateMonthlyTotalUsersMetr... |
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
from pip.req import parse_requirements
import re, ast
# get version from __version__ variable in file_management/__init__.py
_version_re = re.compile(r'__version__\s+=\s+(.*)')
with open('file_management/__init__.py', 'rb') as f:
version = str(as... |
# Generated by Django 1.11.7 on 2018-01-12 17:21
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("letters", "0009_auto_20170826_0742")]
operations = [
migrations.AlterModelOptions(
name="letter",
options={
"ordering": ... |
from ranger.api.commands import Command
class paste_as_root(Command):
def execute(self):
if self.fm.do_cut:
self.fm.execute_console('shell sudo mv %c .')
else:
self.fm.execute_console('shell sudo cp -r %c .')
class fzf_select(Command):
"""
:fzf_select
Find a file using fzf.
With a prefix ... |
# This file helps to compute a version number in source trees obtained from
# git-archive tarball (such as those provided by githubs download-from-tag
# feature). Distribution tarballs (built by setup.py sdist) and build
# directories (produced by setup.py build) will contain a much shorter file
# that just contains th... |
#!/usr/bin/env python3
# Copyright (c) 2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Check that it's not possible to start a second muskcoind instance using the same datadir or wallet."""
impor... |
from ConfigParser import SafeConfigParser
import errno
import logging
import os
import urllib2
class Config(object):
# S3 settings
AWS_ACCESS_KEY_CONFIG = ('aws', 'access_key', 'AWS_ACCESS_KEY')
AWS_SECRET_KEY_CONFIG = ('aws', 'secret_key', 'AWS_SECRET_KEY')
AWS_TEST_RESULT_BUCKET_CONFIG = ('aws', 'test_result... |
######################################################################
# This file should be kept compatible with Python 2.3, see PEP 291. #
######################################################################
"""
Generic dylib path manipulation
"""
import re
__all__ = ['dylib_info']
DYLIB_RE = re.compile(r"""(?x... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import math
import operator
import warnings
from typing import Any, List, Union, Dict, Optional, Callable, Iterable, NoReturn, TypeVar
import torch
import torch.nn as nn
from nni.common.serializer import Translatable
from nni.retiarii.serialize... |
# -*-coding:utf-8-*-
import logging
"""避免被ban策略之一:使用useragent池。
使用注意:需在settings.py中进行相应的设置。
"""
import random
from scrapy.downloadermiddlewares.useragent import UserAgentMiddleware
class RotateUserAgentMiddleware(UserAgentMiddleware):
def __init__(self, user_agent=''):
self.user_agent = user_agent
... |
# Copyright (C) 2010 Apple Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the f... |
"""Copyright 2021 Google LLC.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, sof... |
#!/usr/bin/env python
#
# Copyright 2016 Cisco Systems, 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 applicab... |
"""
Django settings for startupmoney project.
Generated by 'django-admin startproject' using Django 2.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os... |
from django.test import TestCase
from core.govdelivery import MockGovDelivery
from data_research.forms import ConferenceRegistrationForm
from data_research.models import ConferenceRegistration
class ConferenceRegistrationFormTests(TestCase):
capacity = 100
govdelivery_code = 'TEST-CODE'
govdelivery_quest... |
# mysql/__init__.py
# Copyright (C) 2005-2017 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
from . import base, mysqldb, oursql, \
pyodbc, zxjdbc, mysqlconnector, pymysql... |
# Southrn trees bare strage fruit
days = "Mon Tue Wed Thu Fri Sat Sun"
months = 'Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug\nSep\nOct\nNov\nDec'
print "Here are the days:", days
print 'Here are the months:', months
print """
There's something going on here.
With the three double-quotes.
We'll be able to type as much as ... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
from threading import Thread, Event
from time import sleep
def func1():
sleep(2) # Initially sleep for 2 secs
myeventobj.set() # E2
print("func1 sleeping for 3 secs....")
sleep(3) # E3
myeventobj.clear() # E4
def func2():
print("Initially myeventobj is: ", myeventobj.isSet()) # E1
m... |
##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... |
from typing import Tuple
import unittest
import numpy as np
from openml.tasks import get_task
from .test_task import OpenMLTaskTest
class OpenMLSupervisedTaskTest(OpenMLTaskTest):
"""
A helper class. The methods of the test case
are only executed in subclasses of the test case.
"""
__test__ = F... |
# Copyright 2018 The TensorFlow 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 applica... |
QUERY_HASH = '42323d64886122307be10013ad2dcc44'
STORIES_QUERY_HASH = '45246d3fe16ccc6577e0bd297a5db1ab'
SHORTCODE_QUERY_HASH = 'fead941d698dc1160a298ba7bec277ac'
BASE_URL = "https://www.instagram.com"
LOGIN_REFERER = f'{BASE_URL}/accounts/login'
LOGIN_URL = f'{BASE_URL}/accounts/login/ajax/'
LOGOUT_URL = f'{BASE_URL}/... |
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
'''
@File : main.py
@Author : guoliang.wgl
@version : 1.0
@Description: smart_fan案例 - 智能控制小风扇
board.json - 硬件资源配置文件
'''
from fan import Fan
from aht21b import AHT21B
from driver import PWM, I2C
import time
from aliyunIoT import ... |
# coding=utf-8
#
# Copyright 2020 Heinrich Heine University Duesseldorf
#
# Part of this code is based on the source code of BERT-DST
# (arXiv:1907.03040)
# Part of this code is based on the source code of Transformers
# (arXiv:1910.03771)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may no... |
###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2015, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""... |
# exported from PySB model 'model'
from pysb import Model, Monomer, Parameter, Expression, Compartment, Rule, Observable, Initial, MatchOnce, Annotation, ANY, WILD
Model()
Monomer('Ligand', ['Receptor'])
Monomer('ParpU', ['C3A'])
Monomer('C8A', ['BidU', 'C3pro'])
Monomer('SmacM', ['BaxA'])
Monomer('BaxM', ['BidM', '... |
import tensorflow as tf
import keras.backend as K
import numpy as np
from Utils import *
from generators.MotionBlurGenerator import *
from generators.CelebAGenerator import *
K.set_learning_phase(0)
from glob import glob
import os
# paths
Orig_Path = './results/CelebA/Original Images/*.png'
Range_Path = '.... |
# 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... |
class cryto:
def decryp_Vige() :
cyphertext=input("cyphertext=")
key=input("key=")
print("plaintext=",end='')
j=0
for i in cyphertext :
c=ord(key[j])
if c < 97 :
c=c+32
c=c-97
x=ord(i)+26
if x < 123... |
""" Calcualte p-values, ROC, AUC, and proportion of significant observations for
a set of observations given the null hypothesis distribution
Args:
variable: array of observed values
hypothesis: optional null hypotheis distribution (beta distribution by default)
alpha: optional significance... |
# Plot polynomial regression on 1d problem
# Based on https://github.com/probml/pmtk3/blob/master/demos/linregPolyVsDegree.m
import numpy as np
import matplotlib.pyplot as plt
from pyprobml_utils import save_fig
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
fr... |
# coding: utf-8
"""
LogicMonitor REST API
LogicMonitor is a SaaS-based performance monitoring platform that provides full visibility into complex, hybrid infrastructures, offering granular performance monitoring and actionable data and insights. logicmonitor_sdk enables you to manage your LogicMonitor account... |
from pydantic import BaseModel
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
import pkg_resources
from typing import Any
def build_api(handler, endpoint):
def get_version():
pkg_name = "msgflow"
try:
version = pkg_resources.get_distributi... |
import os
from montreal_forced_aligner.corpus.acoustic_corpus import AcousticCorpus
def test_save_text_lab(
basic_corpus_dir,
generated_dir,
):
output_directory = os.path.join(generated_dir, "gui_tests")
corpus = AcousticCorpus(
corpus_directory=basic_corpus_dir,
use_mp=True,
... |
import os
def tfoutputtoAzdo(outputlist, jsonObject):
"""
This function convert a dict to Azure DevOps pipelines variable
outputlist : dict { terraform_output : azure devpops variable}
jsonOject : the terraform output in Json format (terraform output -json)
"""
if(len(outputlist) > 0):
... |
import numpy as np
import torch
import torch.nn as nn
from torch.nn import functional as F
from tqdm import tqdm
class _BaseWrapper():
def __init__(self, model):
super().__init__()
self.model = model
self.handlers = []
def forward(self, images):
self.image_shape = images.shape[... |
import unittest
import numpy as np
from hmc.applications.cox_poisson import forward_transform, inverse_transform, generate_data, gaussian_posterior_factory, hyperparameter_posterior_factory
from hmc.applications.cox_poisson.prior import log_prior, grad_log_prior, hess_log_prior, grad_hess_log_prior
class TestCoxPoi... |
"""
Created on Fri Oct 29 18:54:18 2021
@author: Krishna Nuthalapati
"""
import numpy as np
def iou(boxA, boxB):
# determine the (x, y)-coordinates of the intersection rectangle
xA = max(boxA[0], boxB[0])
yA = max(boxA[1], boxB[1])
xB = min(boxA[2], boxB[2])
yB = min(boxA[3], boxB[3])
# compute the area of int... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from future.utils import viewvalues
from collections import defaultdict
import logging
import time
logger = logging.getLogger(__name__)
def index_list():
return defaultdict(list)
class Blocker:
'''Takes in a record and returns all blocks that record belongs to'''... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.