content stringlengths 5 1.05M |
|---|
'''
Created on June 6, 2018
Filer Guidelines: esma32-60-254_esef_reporting_manual.pdf
Taxonomy Architecture:
Taxonomy package expected to be installed:
@author: Mark V Systems Limited
(c) Copyright 2018 Mark V Systems Limited, All rights reserved.
'''
import os, re
from collections import defaultdict
from lxml.et... |
#!/usr/bin/env python
import json
import os
import six
import sys
from subprocess import Popen, PIPE
from ansible.module_utils.basic import *
DOCUMENTATION = '''
---
module: discovery_diff
short_description: Provide difference in hardware configuration
author: "Swapnil Kulkarni, @coolsvap"
'''
def get_node_hardwa... |
# -*- coding: utf-8 -*-
"""
.. module:: __init__
"""
from os import path
from django.conf import settings
from django.conf.urls import include
from django.conf.urls import url
from django.contrib import admin
from django.views.static import serve
PROJECT_ROOT = path.dirname(path.dirname(__file__))
urlpatterns = [... |
"""
Module containing a class for converting a PySB model to a set of ordinary
differential equations for integration or analysis in Mathematica.
For information on how to use the model exporters, see the documentation
for :py:mod:`pysb.export`.
Output for the Robertson example model
=================================... |
from django.db import models
from django.core.mail import send_mail
from django.contrib.auth.models import User
help_text="Please use the following format: <em>YYYY-MM-DD</em>"
class Address( models.Model ):
first_line = models.CharField( max_length=64 )
second_line = models.CharField( ... |
# You're going to hate me for this
# Import all required packages
import os
import discord
from discord.ext import commands
from dotenv import load_dotenv
# Load the vars as system environment variables
load_dotenv()
# Define the client
client = commands.Bot(command_prefix='&_')
# This tells d.py that this function... |
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from action_logging import Logger
class Response:
def __init__(self, data = None, logger = None):
"""
:param data:
:param logger:
"""
if logger is None:
self.logger = Logger(log_flag = True, l... |
# Made by Christian Oliveros on 09/10/2017 for MMKF15
# Imports Used
try:
from .instruction import Instruction, InterpretedInstruction
except SystemError as e:
from instruction import Instruction, InterpretedInstruction
try:
from .vector import Vector3, interpolatePoints
except SystemError as e:
from vector impo... |
#
# Copyright (c) 2018-2020 by Kristoffer Paulsson <[email protected]>.
#
# This software is available under the terms of the MIT license. Parts are licensed under
# different terms if stated. The legal terms are attached to the LICENSE file and are
# made available on:
#
# https://opensource.org/lice... |
# -*- coding: utf-8 -*-
'''
Project: Product Aesthetic Design: A Machine Learning Augmentation
Authors: Alex Burnap, Yale University
Email: [email protected]
License: MIT License
OSS Code Attribution (see Licensing Inheritance):
Portions of Code From or Modified from... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2021 The SymbiFlow Authors.
#
# Use of this source code is governed by a ISC-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/ISC
#
# SPDX-License-Identifier: ISC
from typing import List
import jinja2
from ... |
#!/bin/python3
import argparse
import luxafor
import time
def main():
parser = argparse.ArgumentParser(description='Change Luxafor colour')
parser.add_argument('color', choices=['green', 'yellow', 'red', 'blue', 'white', 'off'], help='color to change to')
args = parser.parse_args()
l = luxafor.LuxaFo... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright CNRS 2012
# Roman Yurchak (LULI)
# This software is governed by the CeCILL-B license under French law and
# abiding by the rules of distribution of free software.
import sys
import os, os.path
import hashlib
import warnings
import numpy as np
import tables
with wa... |
class ORSolver(object):
"""Solver Class of the JobShop Problem"""
def solve_with_disunctive_model(self, config_path, init_path, sol_path, max_time):
"""Minimal jobshop problem."""
import collections
import time
import xml.etree.ElementTree as ET
import numpy as np
... |
# Generated by Django 2.2.14 on 2020-07-29 19:05
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Recipes',
fields=[
('id', models.AutoField... |
def main():
height = get_height()
draw(height, height)
def draw(height, h):
if height == 0:
return
draw(height - 1, h)
print(" " * (h - height), end='')
print("#" * height, end='')
print(" ", end='')
print("#" * height)
def get_height():
while True:
try:
... |
T = int(input())
max_val = (2 ** 32) - 1
for _ in range(T):
print (max_val - int(input()))
|
import sys
import yaml
import pandas as pd
import numpy as np
from .regression import Regression
from .classification import Classification
from .model import Model
from .preprocessing import Preprocessing, file_split_X_y
from .images import Images
class UnicornML:
__problem: str
__algorithms: list
__met... |
__title__ = 'logbook-dptk'
__description__ = 'File summary pipeline for DPTK'
__url__ = 'https://github.com/sbdp/logbook-dptk'
__version__ = '0.1a0'
__author__ = 'SBDP'
__author_email__ = '[email protected]'
|
from django.db import models
from django.utils import timezone
class Comment(models.Model):
name = models.CharField(max_length=20)
comment = models.TextField()
date_added = models.DateTimeField(default=timezone.now)
def __str__(self):
return '<Name: {}, ID: {}>'.format(self.name,sel... |
from ctapipe.utils import get_dataset_path
from ctapipe.io.eventsource import EventSource
def test_construct():
try:
EventSource(config=None, tool=None)
except TypeError:
return
raise TypeError("EventSource should raise a TypeError when "
"instantiated due to its abstra... |
from django.shortcuts import render, get_object_or_404
from .forms import AddEventForm
from .models import Event
def index(request):
events = Event.objects.all()
return render(request, 'index.html', {'events': events})
def event_detail(request, pk):
event = get_object_or_404(Event, pk=pk)
return ren... |
# @name: Katana-DorkScanner
# @repo: https://github.com/adnane-X-tebbaa/Katana-ds
# @author: Adnane tebbaa (AXT)
# Bit.ly-file Dev
"""
MIT License
Copyright (c) 2020 adnane tebbaa
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentatio... |
from typing import NoReturn
from uuid import uuid4
from sqlalchemy import (
Boolean,
Column,
DateTime,
ForeignKey,
Integer,
String,
sql,
)
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.hybrid import hybrid_propert... |
# -*- coding: utf-8 -*-
#
# Authors: Swolf <[email protected]>
# Date: 2021/3/4
# License: MIT License
"""
High-gamma dataset.
"""
import re
from typing import Union, Optional, Dict, List, Tuple
from pathlib import Path
import numpy as np
import h5py
import mne
from mne.io import Raw
from mne.channels import make... |
# vi: set shiftwidth=4 tabstop=4 expandtab:
import datetime
import itertools
RUN_LONG_TESTS = False
def get_public_keys_from_file(file_path="../../resources/year2020_day25_input.txt"):
with open(file_path) as f:
return [int(l) for l in f]
MODULO = 20201227
def transform(subject_number, loop_size):
... |
import sqlite3
conn = sqlite3.connect('resultsdb.sqlite')
c = conn.cursor()
#c.execute("CREATE TABLE Results (address text, burglaries integer)")
c.execute("INSERT INTO Results VALUES ('Queen Vic', 2)")
conn.commit()
conn.close() |
import numpy as np
arrs = []
for i in xrange(60):
arrs.append(np.load('latent_means/latent_means_%d.npy' % i))
full = np.concatenate(arrs)
np.save('latent_means/latent_means.npy', full)
|
#File: Ex019_Counter_Sunk_Holes.py
#To use this example file, you need to first follow the "Using CadQuery From Inside FreeCAD"
#instructions here: https://github.com/dcowden/cadquery#installing----using-cadquery-from-inside-freecad
#You run this example by typing the following in the FreeCAD python console, making su... |
from __future__ import absolute_import, division, print_function
from __future__ import unicode_literals
import os
import sys
import collections
import numpy as np
from random import randint
import pytest
from mmgroup.dev.hadamard.hadamard_t import bitparity
from mmgroup.dev.mm_op.mm_op import MM_Op, INT_BITS... |
#
# PySNMP MIB module PPVPN-TC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PPVPN-TC-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:04:56 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019,... |
#=========================================================================
# BehavioralRTLIR.py
#=========================================================================
"""Provide behavioral RTLIR AST node types.
This file is automatically generated by BehavioralRTLIRImplGen.py.
"""
class BaseBehavioralRTLIR:
"""... |
from django.contrib import admin
from django.urls import path
from eventlog import views
from eventlog.models import LoginSession, Event
class SessionAdmin(admin.ModelAdmin):
readonly_fields = ('id', 'user', 'startedAtTime', 'endedAtTime', 'userAgent')
list_filter= ('user', 'startedAtTime')
list_display ... |
import os
if not SENTRY_DSN: # type: ignore # noqa: F821
SENTRY_DSN = os.getenv('SENTRY_DSN')
if SENTRY_DSN:
import logging
import sentry_sdk
# TODO(dmu) HIGH: Enable Celery integration once Celery is added
# from sentry_sdk.integrations.celery import CeleryIntegration
from sentry_sdk.integr... |
#!_PYTHONLOC
#
# (C) COPYRIGHT 2006-2021 Al von Ruff, Ahasuerus and Dirk Stoecker
# ALL RIGHTS RESERVED
#
# The copyright notice above does not evidence any actual or
# intended publication of such source code.
#
# Version: $Revision$
# Date: $Date$
from isfdb import *
from common import... |
from application import *
from database.models import AccountData
from database.database import SessionLocal
import uuid
from hashlib import sha256, sha512
import time
class Account:
def __init__(self, request):
self.db = SessionLocal()
self.request = request
@staticmethod
def exists_or_not_found(email, db):
... |
#
# 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 us... |
import json
def get_stored_username():
"""Get Stored Username"""
filename = 'numbers.json'
try:
with open(filename) as file_object:
username = json.load(file_object)
except FileNotFoundError:
return None
else:
return username
def get_new_username():
username = input("What is your name? ")
filename = '... |
from os import remove, sep
from os.path import isfile
from queue import Queue
from parse_audio import validate, youtube_download
class Track:
def __init__(self, chunk_size, filename=None, url=None):
if filename and isfile(filename):
self.trackname, self.filename, self.length = validate(filena... |
antigos = float(input('digite o valor o salário: '))
rj = (antigos*15)/100
ns = antigos + rj
print('O salário antigo é R${}'.format(antigos))
print('O novo salário é R${}'.format(ns))
print('Recebeu um reajuste de R${}'.format(rj)) |
#!/usr/bin/env python
# encoding: utf-8
import json
from flask import Flask, request, jsonify
from flask_mongoengine import MongoEngine
app = Flask(__name__)
app.config['MONGODB_SETTINGS'] = {
'db': 'your_database',
'host': 'localhost',
'port': 27017
}
db = MongoEngine()
db.init_app(app)
cl... |
"""
This module create HTML template for displaying videos
Example
$python template.py --startI 10 --end 40
create HTML file which presenets images with index between 10 and 40
"""
import os
from jinja2 import Environment, FileSystemLoader
from dataloader import MITDataLoader
ROOT_DIR = os.path.join("/", *os.pa... |
# Copyright 2018 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.
"""Unit tests for translation_helper.py."""
import unittest
import os
import sys
import translation_helper
here = os.path.realpath(__file__)
testdata_path =... |
class VCenterDeployVMFromLinkedCloneResourceModel(object):
def __init__(self):
self.vcenter_vm = ''
self.vcenter_vm_snapshot = ''
self.vm_cluster = ''
self.vm_storage = ''
self.ip_regex = ''
self.vm_resource_pool = ''
self.vm_location = ''
self.auto_po... |
import uuid
import numpy.testing as npt
from skyportal.tests import api
def test_candidate_list(view_only_token, public_candidate):
status, data = api("GET", "candidates", token=view_only_token)
assert status == 200
assert data["status"] == "success"
def test_token_user_retrieving_candidate(view_only_to... |
import appdaemon.plugins.hass.hassapi as hass
from ping3 import ping
class Backup(hass.Hass):
def initialize(self):
pass
# self.log('initializing backup script')
# self.notify('initializing backup script', title='appdaemon: Backup', name='pushbullet')
# self.run_every(self.check_p... |
#!/usr/bin/python3
safe_print_integer_err = \
__import__('100-safe_print_integer_err').safe_print_integer_err
value = 89
has_been_print = safe_print_integer_err(value)
if not has_been_print:
print("{} is not an integer".format(value))
value = -89
has_been_print = safe_print_integer_err(value)
if not has_been_... |
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import time
import compas
from compas.geometry import dot_vectors
from compas.utilities import i_to_blue
from compas_rhino.helpers import mesh_from_surface
from compas_rhino.helpers import mesh_select_face
... |
import os
"""
Logic to check if a dataset is valid
Parameters
----------
dataset_folder: str
folder of the dataset
labels_type: str
labels_type
Returns
-------
Boolean
true if the dataset is valid, false otherwise
"""
def validate_dataset(dataset_folder, labels_type):
valid... |
# -*- coding: utf-8 -*-
'''
Created on Mar 27, 2017
@author: hustcc
'''
from warpart import app
# from gevent.wsgi import WSGIServer
# from gevent import monkey
# monkey.patch_all() # patch
def runserver(port=10028, debug=False):
app.run('0.0.0.0', port, debug=debug, threaded=False)
# http_server = WSGIServ... |
import unittest
import firstlib
class TestFirstLib(unittest.TestCase):
def testFunction(self):
self.assertEqual(3, 3, "3 and 3 are indeed equal... aren't they?")
# assertTrue()
# assertRaises()
self.assertEqual(firstlib.analysis.test(), 1, "test not working...")
# aslo availabl... |
from imdbmovie_scrap import *
from pprint import pprint
a = scrap_top_list()
def movis():
realeas_yr=[]
for i in a:
if i['years'] not in realeas_yr:
realeas_yr.append(i['years'])
realeas_yr=sorted(realeas_yr)
movie_dict={i:[] for i in realeas_yr}
for i in a:
yr=i['years'... |
# Generated by Django 2.0.13 on 2019-04-11 03:46
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('sis_provisioner', '0005_auto_20190408_1712'),
]
operations = [
migrations.DeleteModel(
name='EmployeeAppointment',
),
m... |
"""Implementation of the SSL Adapter for the TLS Pool.
When you use cheroot directly, you can specify an
`ssl_adapter` set to an instance of this class.
Using the WSGI standard example, you might adapt
it thusly:
from cheroot import wsgi
from cheroot.ssl.tlspooladapter import TLSPoolAdapter
def my_cr... |
from funcx.executors.high_throughput.executor import HighThroughputExecutor
__all__ = ['HighThroughputExecutor']
|
from functools import wraps
def singleton(cls):
"""装饰器,被装饰的类为单例模式"""
instances = {}
@wraps(cls)
def getinstance(*args, **kw):
if cls not in instances:
instances[cls] = cls(*args, **kw)
return instances[cls]
return getinstance
|
from __future__ import unicode_literals
from functools import reduce
from sys import stdout
from django.db.models import Model
from django.db.models.query import QuerySet
from django.utils import six
from .utils import (
get_rendition_key_set,
get_url_from_image_key,
validate_versatileimagefield_sizekey_... |
import uuid
import datetime
from django.db import models
from django.core.exceptions import ValidationError
from django.contrib.auth.models import User
from taggit.managers import TaggableManager
from preferences.models import Preferences
from epl.custommodels import IntegerRangeField, FloatRangeField
from util.file_v... |
import unittest
from aws_lambda_decorators.classes import Parameter, SSMParameter, BaseParameter
class ParamTests(unittest.TestCase):
def test_can_create_base_parameter(self):
base_param = BaseParameter("var_name")
self.assertEqual("var_name", base_param.get_var_name())
def test_annotations_... |
"""The Bocadillo API class."""
import os
from functools import partial
from typing import Any, Dict, List, Optional, Tuple, Type, Union, Callable
from starlette.middleware.cors import CORSMiddleware
from starlette.middleware.gzip import GZipMiddleware
from starlette.middleware.httpsredirect import HTTPSRedirectMiddlew... |
from .supportr import Supportr
from .predict import predict |
#!/usr/bin/env python3
import sys
# Functions
def read_numbers():
try:
n = int(sys.stdin.readline())
k = int(sys.stdin.readline())
v = [int(sys.stdin.readline()) for _ in range(n)]
except ValueError:
return 0, 0, None
return n, k, v
def compute_unfairness(n, k, v):
v... |
def pourcent(chaîne_de_caractères):
nombre_de_0 = chaîne_de_caractères.count('0')
if len(chaîne_de_caractères):
return nombre_de_0 / len(chaîne_de_caractères)
else:
return 0
def non_lue():
pass
|
#!/usr/bin/env python3
"""
Tolkein.
usage: tolkein [<command>] [<args>...] [-h|--help] [--version]
commands:
-h, --help show this
-v, --version show version number
"""
from docopt import docopt
from ._version import __version__
if __name__ == '__main__':
docopt(__doc__,
version=__ver... |
"""Implementation of Rule L012."""
from sqlfluff.core.rules.std.L011 import Rule_L011
class Rule_L012(Rule_L011):
"""Implicit aliasing of column not allowed. Use explicit `AS` clause.
NB: This rule inherits its functionality from obj:`Rule_L011` but is
separate so that they can be enabled and disabled s... |
import argparse
import os
import tempfile
from unittest import TestCase
import unittest
from mimic.utils.filehandling import create_dir_structure
from dataclasses import dataclass
from unittest import TestCase
import torch
import torch.optim as optim
from tensorboardX import SummaryWriter
from mimic.networks.classifi... |
from server.models import *
from django.db import migrations, models
def enable_plugins(apps, schema_editor):
Machine = apps.get_model("server", "Machine")
MachineDetailPlugin = apps.get_model("server", "MachineDetailPlugin")
plugin_count = MachineDetailPlugin.objects.exclude(name='MachineDetailSecuri... |
import json
import cgi
from datetime import datetime, timedelta
from uuid import uuid4
from libs.contents.contents import *
from libs.table.table import del_row, update_cell, create_empty_row_, update_row_
from libs.perm.perm import is_admin, user_has_permission
from core.core import *
from core.union import cache, in... |
from datetime import datetime
import math
import requests
import json
API_URL = 'http://api-ubervest.rhcloud.com'
API_DEVICE_BPM_URL = '%s/devices/%s/bpm' % (API_URL, '%s')
now = int(math.floor(datetime.now().timestamp() * 1000))
print(now)
for i in range(1000):
timestamp = 101 + i
bpm = 60 + (i % 30)
d... |
import gym
from dm_control import suite
from dm_control.rl.control import flatten_observation, FLAT_OBSERVATION_KEY
from gym import spaces
from gym.envs.registration import register
import numpy as np
from gym_dmcontrol.viewer import Viewer
class DMControlEnv(gym.Env):
"""
Wrapper for dm_control suite task ... |
from django.test import LiveServerTestCase
from selenium import webdriver
class AdminFuncTests(LiveServerTestCase):
fixtures = ['functest_users.json']
def setUp(self):
self.browser = webdriver.Firefox()
self.browser.implicitly_wait(3)
def tearDown(self):
self.browser.quit()
def test_admin_sit... |
import os
class Settings():
env_list = [
{'name':'PORTAINER_ACCESSKEY', 'mandatory': True, 'default':''},
{'name':'PORTAINER_URL', 'mandatory': True, 'default':''},
{'name':'BACKUP_USERNAME', 'mandatory': True, 'default':''},
{'name':'BACKUP_HOST', 'mandatory': True, 'default':''}... |
# View more python tutorials on my Youtube and Youku channel!!!
# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
# Youku video tutorial: http://i.youku.com/pythontutorial
# 9 - tick_visibility
"""
Please note, this script is for python3+.
If you are using python2+, please modify it a... |
# Copyright 2013 Leighton Pritchard. All rights reserved.
#
# This file is part of the Biopython distribution and governed by your
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
# Please see the LICENSE file that should have been included as part of this
# package.
"""Classes and function... |
from CRABClient.UserUtilities import config, getUsernameFromSiteDB
config = config()
config.General.requestName = 'w01_hijing8tev_gensimtreeproduction'
config.General.workArea = 'project_w01_hijing8tev_gensimtreeproduction'
config.General.transferOutputs = True
config.General.transferLogs = False
config.JobType.plugi... |
"""Database URL parser."""
from typing import Any, NewType
from urllib import parse as urlparse
from .utils import is_truthy
DBConfig = NewType('DBConfig', dict[str, Any])
DBConfig.__qualname__ = 'yaenv.db.DBConfig'
# Supported schemes.
SCHEMES: dict[str, str] = {
'mysql': 'django.db.backends.mysql',
'oracl... |
import os
import sys
import simplejson as json
import logging
from io import open
from dogpile.cache import make_region
from swag_client.backend import SWAGManager
from swag_client.util import append_item, remove_item
logger = logging.getLogger(__name__)
try:
from json.errors import JSONDecodeError
except Impor... |
from sqlalchemy.dialects import mssql
from sqlalchemy.engine import default
from sqlalchemy.exc import CompileError
from sqlalchemy.sql import and_
from sqlalchemy.sql import bindparam
from sqlalchemy.sql import column
from sqlalchemy.sql import exists
from sqlalchemy.sql import func
from sqlalchemy.sql import literal
... |
from dtl.dag import *
|
from .LocalDatabricksConfig import LocalDatabricksConfig
from .secret_lookup import *
|
from buzzard._actors.message import Msg
import collections
class ActorProducer(object):
"""Actor that takes care of waiting for cache tiles reads and launching resamplings"""
def __init__(self, raster):
self._raster = raster
self._alive = True
self._produce_per_query = collections.de... |
# pylint: disable=invalid-name,pointless-statement
def f() -> None:
4 # noqa: B018
def g() -> int:
return 4
|
# време + 15 минути
# Да се напише програма, която въвежда час и минути от 24-часово денонощие и изчислява колко ще е часът след 15 минути.
# Резултатът да се отпечата във формат hh:mm. Часовете винаги са между 0 и 23, а минутите винаги са между 0 и 59.
# Часовете се изписват с една или две цифри.
# Минутите се изписва... |
# Code based on https://github.com/OpenNMT/OpenNMT-py/blob/master/preprocess.py
import pickle
import numpy as np
import argparse
import sys
import dsol
from keras.preprocessing import text
__author__ = 'Sameer Khurana'
__email__ = '[email protected]'
__version__ = '0.2'
parser = argparse.ArgumentParser(des... |
from __future__ import unicode_literals
from django.apps import AppConfig
class EncryptiburConfig(AppConfig):
name = 'Encryptibur'
|
import numpy as np
import cv2
import subprocess
import sys
import shutil
import os
import argparse
import configparser
import midi
import note
def is_note_on(event):
"""
Sometimes Note Offs are marked by
event.name = "Note On" and velocity = 0.
That's why we have to check both event.name and
velo... |
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated
from api.grades.models import Grade, Module
from rest_framework.response import Response
from rest_framework.decorators import action
from api.grades.serializers import ModuleSerializer
class ModuleViewSet(viewsets.ModelViewSe... |
import os
import shutil
def parse_lines_in_file(filename):
file = open(filename, 'r')
lines = list()
try:
lines_origin = file.readlines()
for line in lines_origin:
lines.append(line[:-1])
finally:
file.close()
return lines
del_files = parse_lines_in_file('delete... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created Nov 2020
@author: hassi
"""
from qiskit import QuantumCircuit, Aer, execute
from qiskit.visualization import plot_histogram
from IPython.core.display import display
print("Ch 4: Upside down quantum coin toss")
print("-----------------------------------")
... |
# Copyright (C) 2017 Seeed Technology Limited
#
# 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 agree... |
import os
import numpy as np
import torch
from .helper_func import tensor_to_np
class Dataset:
def __init__(self, path):
self.path = path
self.data = dict()
self.files = set(os.listdir(path))
def __getattr__(self, item):
xname = item + "_x"
yname = item + "_y"
... |
import os
import codecs
from collections import OrderedDict
import l20n.format.lol.parser as parser
import l20n.format.lol.serializer as serializer
import l20n.format.lol.ast as ast
import pyast
import l10ndiff
def read_file(path):
with codecs.open(path, 'r', encoding='utf-8') as file:
text = file.read()
... |
from importlib import import_module, metadata
from inspect import isclass, stack, getmodule
from django.templatetags.static import static
from django.utils.safestring import mark_safe
class SourceBase:
static_path = None
cdn_path = None
filename = None
js_filename = None
css_filename = None
l... |
import librosa
import numpy as np
import sklearn
from tqdm import tqdm
import itertools
# helper Function
def normalize(x, axis=0):
return sklearn.preprocessing.minmax_scale(x, axis=axis)
def Extract_Mfcc(DataFrame):
features = []
for audio_data in tqdm(DataFrame['File_List'].to_list()):
x , sr =... |
import errno
import os
import os.path as osp
def makedirs(path: str):
r"""Recursive directory creation function."""
try:
os.makedirs(osp.expanduser(osp.normpath(path)))
except OSError as e:
if e.errno != errno.EEXIST and osp.isdir(path):
raise |
import json
from django.conf import settings
from go.api.go_api import client
from go.base.tests.helpers import GoDjangoTestCase
from mock import patch
class TestClient(GoDjangoTestCase):
@patch('requests.post')
def test_rpc(self, mock_req):
client.rpc('123', 'do_something', ['foo', 'bar'], id='abc... |
import stomp
import time
host_and_ports = [('0.0.0.0', 61613)]
conn = stomp.Connection(host_and_ports=host_and_ports)
conn.start()
conn.connect('admin', 'password', wait=True)
counter = 0
while counter <= 5:
test_msg = "BookmarkMessage" + str(counter) + "{status=status, userId=userId, element=element, rate=rate,... |
# File: oletools_connector.py
# Copyright (c) 2021 Splunk Inc.
#
# Licensed under Apache 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt)
# Python 3 Compatibility imports
from __future__ import print_function, unicode_literals
# Phantom App imports
import phantom.app as phantom
from phantom.base_connector import... |
from django.shortcuts import redirect, render
from .models import userlist
# Create your views here.
def database():
return ()
def login_check(request):
if request.method == "POST":
uid = request.POST.get('email')
passwd = request.POST.get('pass')
context = {}
ulist = userlist.... |
from os.path import dirname, basename, isfile, abspath
import glob
modules = glob.glob(dirname(abspath(__file__))+"/*/*.py")
print '1', dirname(abspath(__file__))
print '2', modules
__all__ = [ basename(f)[:-3] for f in modules if isfile(f)]
print '3', __all__
# import pkgutil
# import sys
# def load_all... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.