content stringlengths 5 1.05M |
|---|
"""
utilities
"""
import random
import datetime
def unique_filename(
extension,
mode='timestamp',
base=None,
position='base_first'
):
"""
creates unique filenames, using methods corresponding to the 'mode' argument.
# TODO: add more methods
argument
extension
The ... |
"""
Name: Advance
breif: inputdeck for MCDC-TNT
Author: Jackson Morgan (OR State Univ - morgjack@oregonstate.edu) CEMeNT
Date: Dec 2nd 2021
"""
import math
import numpy as np
import numba as nb
#@nb.jit(nopython=True)
#@profile
def Advance(p_pos_x, p_pos_y, p_pos_z, p_mesh_cell, dx, p_dir_y, p_dir_z, p_dir_x, p_speed... |
#!/usr/bin/env python
# -- Content-Encoding: UTF-8 --
"""
Simple bundle registering a service
:author: Thomas Calmant
"""
import os
from pelix.constants import BundleActivator
__version_info__ = (1, 0, 1)
__version__ = ".".join(str(x) for x in __version_info__)
SVC = "greetings"
FACTORY = None
SVC_NO_CLEAN = "fact... |
'''
Created on 09.09.2016
@author: gongy
'''
import functools
SZ_ZERO = 1
SZ_VARIABLE = 2
class JPEGMarker(object):
def __init__(self, marker, desc=None, name=None, is_rst=False, is_app=False, is_jpg=False):
self.marker = marker
self.identifier = marker & 0xff
self.name = name
se... |
#!/bin/python3
# Problem description: https://www.hackerrank.com/challenges/pairs/
# GitHub: https://github.com/kwasnydam
import os
def pairs(k, arr):
present_numbers = set(arr)
pairs_count = 0
for value in arr:
complement = value - k
if complement in present_numbers:
... |
#!/usr/bin/env python3
""" the DeBlob Inator
joins the blobs to rebuild the original stuff
"""
############## system modules
import itertools, sys, os, io, copy, string, argparse, importlib, shutil, re, json
import os.path
from os.path import join as osjoin
if __name__ == '__main__':
a = os.path.realpath(sys.a... |
from pathlib import Path
from typing import Optional
import wx
import wx.lib.inspection
import wx.lib.scrolledpanel
class ImagePanel(wx.lib.scrolledpanel.ScrolledPanel):
def __init__(self, *args, **kw) -> None:
super().__init__(*args, **kw)
self.on_drag_start_mouse_position: Optional[wx.Point] =... |
import os
import click
import flask_s3
from app import app
@click.command()
def upload_assets():
flask_s3.create_all(app)
if __name__ == '__main__':
upload_assets()
|
'''
TODO:
- Set up program to allow for mid-experiment parameter changes
- Send a pull request to have the option of not resetting K2400
'''
# database manipulation/operations
import pandas as pd
import numpy as np
# data plotting
import matplotlib.pyplot as plt
import seaborn as sns
# import drivers... |
# Generated by Django 2.2 on 2020-01-08 14:27
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
opera... |
#! /usr/bin/python
# -*- coding: utf-8 -*-
# @Time : 2017/6/22 00:27
# @Author : HouJP
# @Email : houjp1992@gmail.com
import ConfigParser
import os
import random
import time
from bin.featwheel.utils import LogUtil, DataUtil
from evaluator import Evaluator
from feature import Feature
from model import Model
c... |
from setuptools import setup, find_packages
NAME = 'myproject'
VERSION = '1.0'
AUTHORS = 'Henrik Finsberg'
setup(name=NAME,
description='Dummy package for this tutorial',
version=VERSION,
author=AUTHORS,
license='LGPL version 3 or later',
author_email="henrikn@simula.no",
packages=... |
from typing import Dict
from fastapi import APIRouter, UploadFile, File
from fastapi.param_functions import Depends
router = APIRouter(prefix="/pdf")
@router.post("/extract", tags=["PDF Info Extraction"])
async def extract(file: UploadFile = File(...)):
return {"message": "Successfully Uploaded!"} |
if __name__ == "__main__":
print("Oh hello")
Lol = [12, 3, 4]
war = Lol[4.5] |
# -*- coding: utf-8 -*-
from sqlalchemy.exc import IntegrityError
from sqlalchemy import desc
from Crud.core import Conexao
from Crud.Models import Cliente
class CrudCliente(object):
def __init__(self, id="", nome="", sobrenome="", cpf="", rg="",
celular="", telefone="", email="", obs="", cep... |
import numpy as np # type: ignore
class UniformSampling:
def __init__(self,dimension):
self.dimension = dimension # dimension of simplex
# generate training points and evaluation points
def simplex(self,num_sample,seed,dimension):
'''
num_sample: number of sample points
dim... |
import dlib
import cv2
import numpy
predictor_68_path = "../../models/shape_predictor_68_face_landmarks.dat"
predictor = dlib.shape_predictor(predictor_68_path)
detector = dlib.get_frontal_face_detector()
def get_landmarks(im):
rects = detector(im, 1)
if len(rects) > 1:
raise Exception("Encontrado mais de u... |
#####################################################################
# #
# /labscript_devices/imaqdx_server.py #
# #
# Copyright 2018, Joint Quantum Institut... |
"""Specification/abstract parent for BLE2LSL device files.
To support a new BLE device, create a new module in `ble2lsl.devices` and
include the following module-level attributes:
NAME (str): The device's name.
Used for automatically finding the device address, so should be some
substring of the n... |
#!/usr/bin/python3
#==========================================================================
# FILE: make-json-parse
#
# DESCRIPTION: Parse a json string into a readble format
#
# AUTHOR: Mihai Gătejescu
# VERSION: 1.0.0
# CREATED: 10.10.2017
#======================================================... |
from asyncio import AbstractEventLoop
from twisted.internet.asyncioreactor import AsyncioSelectorReactor
_reactors = {}
def get_reactor(loop: AbstractEventLoop):
"""Helper factory to get a Twisted reactor for the provided loop.
Since the AsyncioSelectorReactor on POSIX systems leaks file descriptors
ev... |
# generate_transfer_configs.py
# Desc:
# Generates a config file that can be used for transferring task representations
# Usage:
# python generate_transfer_configs.py -h
import argparse
import os
import shutil
import subprocess
import sys
parser = argparse.ArgumentParser(description='Extract representations of en... |
import struct
import socket
import threading
import select
import time
import datetime
import traceback
import random
import logging
import urllib
import re
from emonitor.extensions import db, events, signal
from emonitor.modules.events.eventhandler import Eventhandler
from emonitor.modules.monitors.monitor import Moni... |
# video ID, uploader, age, category, length, views, rate, ratings, comments, related ID
# mNyLXihvAIQ,Ceniale90,1236,Music,204,515,5,6,3
CREATE_DETAILS_TABLE_SQL = """
CREATE TABLE IF NOT EXISTS details (
date VARCHAR(20) NOT NULL,
video_id VARCHAR(20) NOT NULL,
uploader VARCHAR(256) NOT NULL,
age TIMESTAMP NOT NULL,
c... |
import torch.nn as nn
from transformer.layers.layer_norm import LayerNorm
from transformer.utils.functions import clones
# 解码器
class Decoder(nn.Module):
def __init__(self, layer, N):
super(Decoder, self).__init__()
self.layers = clones(layer, N)
self.norm = LayerNorm(layer.size)
def ... |
"""
The :mod:`skmultiflow.bayes` module includes Bayes learning methods.
"""
from .utils import do_naive_bayes_prediction
from .naive_bayes import NaiveBayes
__all__ = ["do_naive_bayes_prediction", "NaiveBayes"]
|
#coding=utf-8
from django.template import Library, Node, Variable
from ..models import Attachment
register = Library()
class AttachmentsForObjectNode(Node):
def __init__(self, obj, var_name):
self.obj = obj
self.var_name = var_name
def resolve(self, var, context):
"""Resolves a varia... |
"""Tests related to the ``devhub.addons.owner`` view."""
from django.core import mail
from pyquery import PyQuery as pq
from olympia import amo
from olympia.activity.models import ActivityLog
from olympia.addons.models import Addon, AddonUser
from olympia.amo.tests import TestCase, formset
from olympia.devhub.forms i... |
#
# Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
#
import gevent
from gevent import monkey; monkey.patch_all()
import argparse
import os
import socket
import random
import math
import uuid
from netaddr import IPAddress
from pysandesh.sandesh_base import *
from pysandesh.util import UTCTimestampUsec
f... |
# Write your solution for 1.1 here!
sum = 0
for i in range(100):
if i % 2 == 0:
sum += i
print(sum) |
import json
from pprint import pprint
with open('Cert_262081_262328_5TeV_PromptReco_Collisions15_25ns_JSON.txt') as json_data:
data = json.load(json_data)
# pprint(data)
runs = data.keys()
lumis = data.values()
#print data
#print runs
#print len(runs)
sum=0
for i in range(0, len(runs)):
for j in range(0, ... |
# Generated by Django 3.0.5 on 2020-11-01 06:51
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
... |
#!/usr/bin/env python3
import unittest
import rospy
import socket
from std_srvs.srv import Trigger
from geometry_msgs.msg import Point
from z_laser_msgs.msg import Figure
from z_laser_msgs.srv import ProjectionElement, ProjectionElementRequest
def ip_open(ip,port):
s = socket.socket(socket.AF_INET, socket.SOCK_ST... |
# -*- coding:utf-8 -*-
from re import sub
from itertools import islice
'''
如何调整字符串的文本格式
'''
# 将日志文件中的日期格式转变为美国日期格式mm/dd/yyyy
# 使用正则表达式模块中的sub函数进行替换字符串
with open("./log.log","r") as f:
for line in islice(f,0,None):
#print sub("(\d{4})-(\d{2})-(\d{2})",r"\2/\3/\1",line)
# 可以为每个匹配组起一个别名
print... |
import math
class LimitError(Exception):
pass
class Default(Exception):
pass
class Exposure:
def __init__(self, total_dose=0.0, tilts=[], dose=0.0, exposure=0.0,
exposure_min=None, exposure_max=None):
self.total_dose = total_dose
self.tilts = tilts
self.dose... |
"""
module part of beaker37
base class for Movierecommenders
interfaces to applications
"""
import os
import pandas as pd
from sqlalchemy import create_engine
from fuzzywuzzy import process
class BaseRecommender:
"base class as interface to web app"
movies = pd.DataFrame() # contains movies-database for all ... |
#! /opt/local/bin/python
# stock.py contains StockError, stock object defintion, and portfolio object definition
import sys, os, csv, math
import urllib2
from datetime import datetime, date, timedelta
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from matplotlib import lines, rc
import numpy as np... |
import numpy as onp
from jax import vmap
import jax.numpy as np
import jax.random as random
# This code is taken from the here: https://github.com/google/jax/blob/master/examples/gaussian_process_regression.py
epsilon = 1e-5
def cov_map(cov_func, xs, xs2=None):
"""Compute a covariance matrix from a covariance f... |
# Generated by Django 3.1.8 on 2021-08-24 19:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("listings", "0008_listing_hero_image_url"),
]
operations = [
migrations.AddField(
model_name="listing",
name="read_mo... |
import logging
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt # noqa: E402
from vr2c import visaln # noqa: E402
logger = logging.getLogger(__name__)
def calc_figure_height(df_reads):
# +1 for the contig
num_reads = df_reads.shape[0] + 1
height_per_read = 0.3 # a... |
import populartimes
from datetime import date, datetime # Monday is 0 and Sunday is 6
from flask import Flask, jsonify, request
from flask_cors import CORS
# Instantiate app
app = Flask(__name__)
app.config.from_object(__name__)
# Allow Cors access
CORS(app, resources={r'/*': {'origins': '*'}})
@app.route('/GetBusy'... |
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from engine.classes import Game
from game import labels
from game.data import room_data, object_data
def home(request):
game = request.session.get('game')
context = dict(game=game, labels=labels)
... |
"""
link: https://leetcode-cn.com/problems/4sum-ii
problem: 给 A, B, C, D 四个等长数组,问共有多少元组 (i, j, k, l) 满足 A[i]+B[j]+C[k]+D[l] == 0,数组长度小于 500
solution: 枚举。预计算 AB / CD 各自两个数组元素的所有可能和存进 dict,再扫一遍查相反数。
"""
class Solution:
def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:
... |
from flask import Flask
def create_app():
# Instantiate Flask application
app = Flask(__name__)
@app.route('/')
def home():
return 'Hello World!'
return app
|
from django.db.models.signals import post_save
from django.db.models.signals import pre_delete
from django.dispatch import receiver
from .models import Message
from .models import User
from .tasks import delete_user
from .tasks import send_text_from_message
@receiver(pre_delete, sender=User)
def pre_delete_user(send... |
from django.db import models
from django.utils.functional import cached_property
from django.contrib.auth.models import User
from django.contrib.postgres.fields import JSONField
from django.utils import timezone
from postgresqleu.confreg.models import Conference, RegistrationType, PrepaidBatch
from postgresqleu.confre... |
from typing import Sequence
from typing import Tuple
from typing import Union
import torch
import torch.distributions as D
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
def weights_init(m):
if isinstance(m, nn.Conv2d):
nn.init.kaiming_uniform_(m.weig... |
# -*- coding: utf-8 -*-
# Copyright 2018 The Blueoil 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
#
# Unles... |
# Copyright 2015 CMU
# Author: Yihan Wang <wangff9@gmail.com>
#
# 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 applic... |
from __future__ import print_function
from setuptools import setup, find_packages
import os
import shutil
here = os.path.abspath(os.path.dirname(__file__))
check_fpath = os.path.join("_swigvearch.so")
if not os.path.exists(check_fpath):
print("Could not find {}".format(check_fpath))
# make the vearch python pack... |
#! /usr/bin/env python
from python_qt_binding.QtWidgets import QLabel, QStyle
import rospy
class StatusIndicator(QLabel):
def __init__(self, *args):
super(StatusIndicator, self).__init__(*args)
self.set_stopped()
def set_running(self):
self.setPixmap(
self.style().standard... |
import os
from PIL import Image
import numpy as np
import pandas as pd
import torch
import torch.utils.data as data
from ..utils import gaussianHeatmap, transformer
class Hand(data.Dataset):
def __init__(self, prefix, phase, transform_params=dict(), sigma=10, num_landmark=19, size=[1000, 1400],use_background_c... |
__author__ = 'Stefan Fischer'
__email__ = 'sfischer13@ymail.com'
__version__ = '0.1.0'
|
__version__ = "1.5.1"
class DataType:
sample = "sample"
ob = "ob"
df = "df"
normalized = "normalized"
|
#!/bin/python3
import os
if __name__ == '__main__':
exit(os.system('./target/main'))
|
#!/usr/bin/env pytest
# -*- coding: utf-8 -*-
###############################################################################
# $Id$
#
# Project: GDAL/OGR Test Suite
# Purpose: Test DDS driver
# Author: Even Rouault <even dot rouault at spatialys.com>
#
##############################################################... |
import pandas as pd
import pytest
import torch
import poptimizer.data.app.bootstrap
from poptimizer.dl.features import FeatureType, data_params, dividends
PARAMS = {
"batch_size": 100,
"history_days": 8,
"features": {"Label": {"div_share": 0.9}, "Prices": {}, "Dividends": {}, "Weight": {}},
}
@pytest.fi... |
"""
SAR Manipulator is an application for translating between .sar files used in PSO2 (Symbol Arts) and standard
image file formats.
"""
__author__ = 'Alex Alkire'
__version__ = '0.1'
__license__ = 'MIT'
from sar_crypto import *
from symbol_art import *
from ui import *
loaded_sar = None
raw_sar = None
with open(... |
import json
from .oauth import OAuth2Test
class AmazonOAuth2Test(OAuth2Test):
backend_path = 'social_core.backends.amazon.AmazonOAuth2'
user_data_url = 'https://api.amazon.com/user/profile'
expected_username = 'FooBar'
access_token_body = json.dumps({
'access_token': 'foobar',
'token_... |
##################################
# #
# Last modified 2017/11/08 #
# #
# Georgi Marinov #
# #
##################################
import sys
import os
READS_LOG_INTERVAL = 5000000
MILLION = 1000000
def... |
import unittest
import numpy as np
from commonroad.prediction.prediction import TrajectoryPrediction, SetBasedPrediction, Occupancy
from commonroad.geometry.shape import Rectangle, Circle, ShapeGroup
from commonroad.common.util import Interval
from commonroad.scenario.trajectory import Trajectory, State
class TestOc... |
# Generated by Django 4.0.2 on 2022-02-19 04:00
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... |
#! /usr/bin/env python
from peyotl.amendments import get_empty_amendment
from peyotl.utility.str_util import UNICODE
from peyotl.amendments.validation import validate_amendment
from peyotl.test.support import pathmap
from peyotl.test.support.helper import testing_write_json, testing_read_json
from peyotl.utility import... |
#!/usr/bin/env python3
import yaml
def read_yaml(in_file):
f = open(in_file, 'r')
return yaml.load(f, Loader=yaml.SafeLoader)
def write_yaml(out_file, yaml_list, append=False):
if append :
with open(out_file, 'a') as outf:
yaml.dump(yaml_list, outf, Dumper=ListIndentDumper)
else :... |
def build(bld):
bld.thirdparty('motor.3rdparty.system.dbghelp')
|
from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np
import pandas as pd
import pickle
import random
from scipy import sparse
import itertools
from scipy.io import savemat, loadmat
from pathlib import Path
# Maximum / minimum document frequency
max_df = 0.7
min_df = 100 # choose desired valu... |
# -*- coding: utf8 -*-
# Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. 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... |
x=int(type(input("first no")))
|
import pybullet as p
import time
useDirect = False
usePort = True
p.connect(p.GUI)
id = p.loadPlugin("grpcPlugin")
#dynamically loading the plugin
#id = p.loadPlugin("E:/develop/bullet3/bin/pybullet_grpcPlugin_vs2010_x64_debug.dll", postFix="_grpcPlugin")
#start the GRPC server at hostname, port
if (id<0):
print("C... |
def calculate_investment_value(initial_value, percentage, years):
result = initial_value * (1 + percentage / 100) ** years
return result
def ask_for_int_value(message):
input_value = input(message)
return int(input_value)
def run_investment_calculator():
print("Kalkulator wartości lokaty z rocz... |
#import wurst as w
import tempfile
from wurst.brightway.extract_database import add_input_info_for_indigenous_exchanges
from . import w
from . import warn
#import brightway2 as bw2
from bw2data import projects, databases
from bw2io import ExcelImporter, SingleOutputEcospold2Importer, bw2setup, create_core_migrations... |
import zapp
import zframe
import zborderframe
import zlabel
import zkeylabel
import zlineedit
import ztextedit
import ztable
import zutils
import os
import re
import pwd
class zop(zapp.zapp):
PROC_DIR = "/proc"
def get_user(self, id):
try:
return str(pwd.getpwuid( id ).pw_name)
except:
return str(id)
... |
from django.db.models import Q
import django_filters
from core.models import ApplicationVersionBootScript as ImageVersionBootScript
from api.v2.serializers.details import ImageVersionBootScriptSerializer
from api.v2.views.base import AuthModelViewSet
class VersionFilter(django_filters.FilterSet):
version_id = d... |
from __future__ import unicode_literals
# -*- coding: utf-8 -*-
from math import pi
# Faça um Programa que peça o raio de um círculo, calcule e mostre sua área.
raio = int(raw_input("Informe o raio do circulo: "))
print "A área do círculo é {}".format(pi*raio**2) |
# Copyright 2021 The Private Cardinality Estimation Framework Authors
#
# 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 b... |
def remv_row(df,exp_case):
index = []
for case in list(df["patient_id"]):
if case in exp_case:
index += list(df[df["patient_id"]==case].index)
df.drop(index, inplace = True)
return df.reset_index(drop = True) |
#!/usr/bin/env python
# coding=utf-8
import logging
logging.basicConfig(level=logging.INFO)
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import os
from pymongo import MongoClient
import config
from utils import *
import rutracker_api as api
import datetime
import qbt_api as qbt
def compact_torrent_stats(s... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
from typing import Any, Dict, TypeVar, Hashable, Callable, Union
V = TypeVar('V')
K = TypeVar('K', bound=Hashable)
D = TypeVar('D', None, Any)
def findKey(obj: Dict[K, V], iteratee: Union[Callable[[V], bool], V], default: D = None) -> Union[K, D]:
if callable(iteratee):
for k, v in obj.items():
... |
from ipykernel.kernelapp import IPKernelApp
from .kernel import NgnkKernel
IPKernelApp.launch_instance(kernel_class=NgnkKernel)
|
# Variables for configuring the Backend's behavior
DEV_MODE = False
|
class N:
def __init__(self,position=0,colour="white",capture=False):
"""
-------------------------------------------------------
Initializes a Knight class
Use: node = bb(value)
-------------------------------------------------------
Parameters:
colour-th... |
# -*- coding: utf-8 -*-
__author__ = 'Mathew Cosgrove'
__email__ = 'cosgroma@gmail.com'
__version__ = '0.1.0'
from engine.card import Card
|
from vyper.codegen.core import getpos, make_setter
from vyper.codegen.lll_node import LLLnode, push_label_to_stack
from vyper.codegen.types import TupleType
from vyper.exceptions import StateAccessViolation, StructureException
_label_counter = 0
# TODO a more general way of doing this
def _generate_label(name: str) ... |
# coding=utf-8
# --------------------------------------------------------------------------
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from ... |
from django.contrib.admin import ModelAdmin, register
from django.contrib import admin
from import_export import resources
from import_export.fields import Field
from import_export.admin import ImportExportActionModelAdmin
from django.contrib.auth.admin import UserAdmin
from . models import PersonInfo, User
# Admin se... |
import unittest
from RNN import RNN, RNN_MODEL_DIR
from data_prepare import SENETRawDataBuilder, DataPrepare, Encoder
from feature_extractors import SENETFeaturePipe
class TestDataPrepare(unittest.TestCase):
def test_raw_prepare(self):
rb = SENETRawDataBuilder("test.db")
def test_encoder(self):
... |
from maya import OpenMayaMPx #(1)
import playsound
class SoundPlayer(OpenMayaMPx.MPxCommand): #(2)
def doIt(self, args): #(3)
playsound.play_sound(playsound.GOBBLE)
def create_plugin(): #(4)
return OpenMayaMPx.asMPxPtr(SoundPlayer())
plugin_name = 'playSound' #(5)
def _toplugin(mobject): #(6)
re... |
# Author: Jintao Huang
# Time: 2020-6-6
import torch
import numpy as np
from collections import OrderedDict
class AccCounter:
def __init__(self, labels):
"""
:param labels: List[str]
"""
self.labels = labels
self.acc_sum_num = None
def init(self):
self.acc_sum... |
import re
import requests
url = "https://es.wiktionary.org/wiki/Ap%C3%A9ndice:C%C3%B3digos_de_idioma"
with requests.get(url) as req:
req.raise_for_status()
content = req.text
pattern = r"<tr>\s+<td>([^<]+)</td>\s+<td>([^<]+)\s+</td></tr>"
matches = re.findall(pattern, content)
print("langs = {")
for iso, lan... |
"""Tests for the standard set of rules."""
import pytest
from sqlfluff.core import Linter, FluffConfig
from sqlfluff.core.rules.base import BaseCrawler, LintResult, LintFix
from sqlfluff.core.rules.std import std_rule_set
def get_rule_from_set(code, config):
"""Fetch a rule from the rule set."""
for r in st... |
import pytest
from gitlabform.gitlabform.test import (
get_gitlab,
create_group,
create_project,
get_random_name,
create_users,
run_gitlabform,
delete_users,
)
@pytest.fixture(scope="session")
def gitlab():
gl = get_gitlab()
yield gl # provide fixture value
@pytest.fixture(scop... |
# Not working properly unfortunately!
import numpy as np
import os
import torch as T
import torch.nn.functional as F
import torch.nn as nn
import torch.optim as optim
from torch.distributions.normal import Normal
import numpy as np
import os
import torch as T
import torch.nn.functional as F
import numpy as np
import w... |
# -*- coding: utf-8 -*-
import numpy
from color_modem import comb, qam
class NtscVariant(qam.QamConfig):
def __new__(cls, fsc, bandwidth3db=1300000.0, bandwidth20db=3600000.0):
return NtscVariant.__base__.__new__(cls, fsc, bandwidth3db, bandwidth20db)
NtscVariant.NTSC = NtscVariant(fsc=227.5 * 15750.0... |
# -*- coding: utf-8 -*-
# Licensed under the MIT license
# http://opensource.org/licenses/mit-license.php
# Copyright 2014, Hartmut Goebel <h.goebel@goebel-consult.de>
"""
Test cases for L{backends.ampache_storage}
"""
from lxml import etree
from twisted.trial import unittest
from coherence.backends import ampache... |
from examples import acquire_token_client_credentials
from office365.graph_client import GraphClient
client = GraphClient(acquire_token_client_credentials)
idp_col = client.identityProviders.get().execute_query()
for idp in idp_col:
print(idp.id)
|
import json
import pytest
from unittest.mock import patch
from configmanager import ConfigManager
from message_handler import MessageHandler
from message_consumer import MessageConsumer
@patch("twilio.rest.Client")
@patch("pika.channel.Channel")
@patch("pika.spec.Basic.Deliver")
@patch("pika.spec.BasicProperties")
... |
# -*- coding: utf-8 -*-
# *****************************************************************************
# NICOS, the Networked Instrument Control System of the MLZ
# Copyright (c) 2009-2021 by the NICOS contributors (see AUTHORS)
#
# This program is free software; you can redistribute it and/or modify it under
# the t... |
# user package
|
from django.urls import path, re_path
from . import views
app_name = "wiki"
urlpatterns = [
path("", views.index, name="index"),
path("encyclopedia/search", views.search_entries, name="search_entry"),
re_path(r"^encyclopedia/(?P<action>new|edit)$", views.add_new, name="add_new"),
path("encyclopedia/ran... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.