content stringlengths 5 1.05M |
|---|
__author__ = 'Todd.Hay'
# -------------------------------------------------------------------------------
# Name: SpecialActions.py
# Purpose:
#
# Author: Todd.Hay
# Email: [email protected]
#
# Created: Jan 11, 2016
# License: MIT
#-----------------------------------------------------------... |
import jax.numpy as jnp
import xarray as xr
from jax_cfd.base.grids import Grid
from jax_cfd.spectral import utils as spectral_utils
from fourierflow.utils import downsample_vorticity_hat, grid_correlation
def test_convert_vorticity_to_velocity_and_back():
path = './data/kolmogorov/re_1000/initial_conditions/tes... |
from __future__ import absolute_import
import numpy as np
import scipy.ndimage as scind
from scipy.linalg import toeplitz
from .cpmorphology import fixup_scipy_ndimage_result as fix
from six.moves import range
def minimum(input, labels, index):
return fix(scind.minimum(input, labels, index))
def maximum(input,... |
#
# @lc app=leetcode id=1446 lang=python3
#
# [1446] Consecutive Characters
#
# @lc code=start
class Solution:
def maxPower(self, s: str) -> int:
maxLen = curLen = 0; c = ''
for ch in s:
if ch == c:
curLen += 1
else:
c = ch; curLen = 1
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2016, Silvio Peroni <[email protected]>
#
# Permission to use, copy, modify, and/or distribute this software for any purpose
# with or without fee is hereby granted, provided that the above copyright notice
# and this permission notice appear in all copies.
... |
import os
import sys
sys.path.insert(0,'..')
from citylearn import CityLearn
from pathlib import Path
import numpy as np
import torch
import matplotlib.pyplot as plt
from agents.sac import SAC
import gym
from stable_baselines3 import A2C
from stable_baselines3 import TD3
from stabl... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import shutil
import sys
import tempfile
from observations.r.transact import transact
def test_transact():
"""Test module transact.py by downloading
transact.csv and testing shape of
extracted data h... |
# -*- coding:utf-8 -*-
import json
try:
JSONDecodeError = json.decoder.JSONDecodeError
except AttributeError:
JSONDecodeError = ValueError
class LoadCaseError(BaseException):
"""
组装用例时发生错误
"""
pass
class RunCaseError(BaseException):
"""
执行用例时发生错误
"""
pass
class NoSuchEleme... |
# -*- coding: utf-8 -*-
#######
# actinia-core - an open source REST API for scalable, distributed, high
# performance processing of geographical data that uses GRASS GIS for
# computational tasks. For details, see https://actinia.mundialis.de/
#
# Copyright (c) 2016-2018 Sören Gebbert and mundialis GmbH & Co. KG
#
# T... |
for i in range(1, 10, 2):
print(i)
a = ['Mary', 'had', 'a', 'little', 'lamb']
for i in range(len(a)):
print(i, a[i])
for s in a:
print(s) |
from neo4japp.models.common import NEO4JBase
class GraphNode(NEO4JBase):
def __init__(self, id, label, domain_labels, data, sub_labels, display_name, url):
self.id = id
self.label = label
self.domain_labels = domain_labels
self.data = data
self.sub_labels = sub_labels
... |
from typing import (
Any,
Awaitable,
Callable,
Sequence,
)
import trio
async def wait_first(callables: Sequence[Callable[[], Awaitable[Any]]]) -> None:
"""
Run any number of tasks but cancel out any outstanding tasks as soon as the first one finishes.
"""
async with trio.open_nursery(... |
"""binary_switch for Homematic(IP) Local."""
from __future__ import annotations
import logging
from typing import Any, Union
from hahomematic.const import HmPlatform
from hahomematic.devices.switch import CeSwitch
from hahomematic.platforms.switch import HmSwitch
from homeassistant.components.switch import SwitchEnt... |
"""
Data type conversion of different files
"""
import csv
import json
import yaml
import codecs
from itertools import islice
try:
from openpyxl import load_workbook
except ModuleNotFoundError:
raise ModuleNotFoundError("Please install the library. https://pypi.org/project/openpyxl/")
def _check_data(list_dat... |
class PersistentObject(object):
def __init__(self, **kwargs):
fields = super().__getattribute__('fields')
d = {}
for k in fields:
if not k in kwargs:
continue
d[k] = kwargs[k]
super().__setattr__('values', d)
def __getattr__(self, name)... |
# coding=utf-8
import tensorflow as tf
from base.base_model import BaseModel
class TemplateModel(BaseModel):
"""
Concrete model template.
"""
def __init__(self, config, data):
super(TemplateModel, self).__init__(config, data)
self.build_model()
self.init_saver()
def build_... |
class Solution:
def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int:
jobs = sorted(list(zip(startTime, endTime, profit)))
sortedStartedTime, N = [data[0] for data in jobs], len(jobs)
dp = [0] * (N + 1)
for k in range(N - 1, -1, -1):
... |
from bitmovin.resources.models import AbstractModel
class SmoothContentProtection(AbstractModel):
def __init__(self, encoding_id, muxing_id, drm_id, id_=None, custom_data=None):
super().__init__(id_=id_, custom_data=custom_data)
self.encodingId = encoding_id
self.muxingId = muxing_id
... |
# -*- coding: UTF-8 -*-
"""
Created on ???
@author: Cleber Camilo
"""
import os
from mpbuild import MultiProcBuilder
class CompilerBuilder :
def __init__(self, path, file, multiproc):
self.path = path
self.file = file
self.openFile = None
self.multiproc = multiproc
... |
#!/usr/bin/env python3
from typing import List
def find_numbers_with_sum(numbers: List[int], sum: int) -> (int, int):
"""Find two numbers in the ordered list with the specified sum.
Arguments:
numbers -- the ordered list of numbers to search through
sum -- the sum that two numbers should add up to... |
import argparse
from pathlib import Path
import json
from typing import Iterable
import tempfile
import random
from allennlp.models import Model
from sklearn.model_selection import train_test_split
import target_extraction
from target_extraction.data_types import TargetTextCollection
from target_extraction.dataset_par... |
from mqtt_sn_gateway import messages
class TestPuback:
def test_parse(self):
data = b'\x07\r\x00\x01q\xf6\x00'
msg = messages.Puback.from_bytes(data)
assert msg.length == len(data)
assert msg.msg_type == messages.MessageType.PUBACK
assert msg.return_code == messages.ReturnC... |
'''
Copyright 2022 Leonardo Cabral
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, su... |
import argparse
import logging
import importlib
import os
import sys
from . import (
collect_pread_gfa, collect_contig_gfa,
gen_gfa_v1,
gen_gfa_v2,
gen_bandage_csv,
)
LOG = logging.getLogger()
"""
# Collect all info needed to format the GFA-1 and GFA-2 representations of
# the a... |
"""
:codeauthor: Rupesh Tare <[email protected]>
"""
import salt.modules.mod_random as mod_random
import salt.utils.pycrypto
from salt.exceptions import SaltInvocationError
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.mock import patch
from tests.support.unit import TestCase, skipI... |
DB = 'test'
UNIQUE_ID_COLLECTION = 'unique_id'
DOC_COLLECTION = 'doc'
|
""" Unit tests for skycomponents
"""
import logging
import unittest
import astropy.units as u
import numpy
from astropy.coordinates import SkyCoord
from data_models.polarisation import PolarisationFrame
from processing_components.skycomponent.operations import create_skycomponent, find_separation_skycomponents, \
... |
# -*- coding: utf-8 -*-
# ! /usr/bin/env python
""" `medigan` is a modular Python library for automating synthetic dataset generation.
.. codeauthor:: Richard Osuala <[email protected]>
.. codeauthor:: Noussair Lazrak <[email protected]>
"""
# Set default logging handler to avoid "No handler found" warn... |
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
setup_requires=['setuptools>=30.3'],
packages=find_packages(where='src') + [
'ansible.modules.ansibilo',
'ansible.plugins.callback.ansibilo',
'ansible.plugins.filter.ansibilo',
],
package_dir={ # FIXME: wa... |
# -*- coding: utf-8 -*-
"""
Created on Wed May 27 23:20:43 2020
@author: PRAVEEN KUMAR -1
"""
import numpy as np
from utility import activation_function
class OneHiddenLayerNN:
def __init__(self,n_x,n_h,n_y):
"""
Initilizes size of input, hidden layer unit, and output layer
A... |
import sqlite3
conn = sqlite3.connect("ex_db.sqlite3")
# how can we make this more
def create_table(conn):
curs = conn.cursor()
#make sql create statement
create_table = """
CREATE TABLE Students(
id INTEBER PRIMAY KEY AUTOINCREMENT,
name CHAR(20),
fav_num IN... |
DAL_VIEW_PY = """# generated by appcreator
from django.db.models import Q
from dal import autocomplete
from . models import *
{% for x in data %}
class {{ x.model_name }}AC(autocomplete.Select2QuerySetView):
def get_queryset(self):
qs = {{ x.model_name }}.objects.all()
if self.q:
qs = ... |
# 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 or agreed to in writing, ... |
import unittest
from fractions import Fraction
from function.scalar_range_interpreter import ScalarRangeInterpreter
from tonalmodel.tonality import Tonality, ModalityType
from tonalmodel.diatonic_pitch import DiatonicPitch
class TestScalarRangeInterpreter(unittest.TestCase):
def setUp(self):
pass
d... |
"""UserObservees API Tests for Version 1.0.
This is a testing template for the generated UserObserveesAPI Class.
"""
import unittest
import requests
import secrets
from py3canvas.apis.user_observees import UserObserveesAPI
from py3canvas.apis.user_observees import Pairingcode
class TestUserObserveesAPI(unittest.Test... |
import pytest
@pytest.mark.parametrize(
"word,lemma",
[("新しく", "新しい"), ("赤く", "赤い"), ("すごく", "すごい"), ("いただきました", "いただく"), ("なった", "なる")],
)
def test_ja_lemmatizer_assigns(ja_tokenizer, word, lemma):
test_lemma = ja_tokenizer(word)[0].lemma_
assert test_lemma == lemma
@pytest.mark.parametrize(
"w... |
class MapAsObject:
def __init__(self, wrapped):
self.wrapped = wrapped
def __getattr__(self, key):
try:
return self.wrapped[key]
except KeyError:
raise AttributeError("%r object has no attribute %r" %
(self.__class__.__name__, ke... |
import json
import os
import pickle
import sys
import re
from collections import OrderedDict
import copy
from boltons.cacheutils import LRU
from boltons.cacheutils import cachedmethod
from mesa import Model
from mesa.time import StagedActivation
from simulation.Registry import registry
from simulation.pickleThis impo... |
from datetime import datetime
import pandas as pd
class Funcion_ingresar:
def Ingresar_desplegar_teclado_numerico_cedula(self):
self.campo = 'ingresar-cedula'
#self.Ingresar_desplegar_teclado_numerico()
def Ingresar_desplegar_teclado_numerico_temp(self):
self.campo = 'ingresar-temp'
... |
class TitrationData:
def __init__(self, filename):
self.residue_data = {}
self.read_residue_data(filename)
def read_residue_data(self,filename):
titration_file = open(args.titr)
for line in titration_file:
line_comment = re.search("#", line)
if line_comm... |
class VisualStateGroup(DependencyObject):
"""
Contains mutually exclusive System.Windows.VisualState objects and System.Windows.VisualTransition objects that are used to move from one state to another.
VisualStateGroup()
"""
CurrentState=property(lambda self: object(),lambda self,v: None,lambda self: Non... |
import os
import django
from django.conf import settings
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local")
def pytest_configure():
settings.DEBUG = False
settings.DATABASES["default"] = {"ENGINE": "django.db.backends.sqlite3"}
django.setup()
|
#!/usr/bin/env python
import os
import numpy as np
from mtuq import read, open_db, download_greens_tensors
from mtuq.event import Origin
from mtuq.graphics import plot_data_greens2, plot_beachball, plot_misfit_lune,\
plot_likelihood_lune, plot_marginal_vw,\
plot_variance_reduction_lune, plot_magnitude_tradeof... |
from fastapi import HTTPException, status, Depends
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError
from app.models import UserTortModel
from app.utils import JWT
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
async def get_current_user(token: str = Depends(oauth2_scheme)):
cr... |
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
class PyAccimage(PythonPackage):
"""An accelerated Image loader and preprocessor leveraging Intel IPP.
accimage ... |
from rest_framework import status
from rest_framework.views import exception_handler as drf_exception_handler
from django.http import JsonResponse
def default_handler(exc, context):
# https://www.django-rest-framework.org/api-guide/exceptions/
# Call REST framework's default exception handler first,
# to ... |
# Generated by Django 4.0.3 on 2022-03-16 02:44
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('school', '0004_alter_professor_departamento'),
]
operations = [
migrations.RemoveField(
model_name='departamento',
name='cre... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Spaghetti: Web Server Security Scanner
#
# @url: https://github.com/m4ll0k/Spaghetti
# @author: Momo Outaadi (M4ll0k)
# @license: See the file 'doc/LICENSE'
from lib.net import http
from lib.net import utils
from lib.utils import printer
class Backdoors():
def __ini... |
import numpy as np
default_Q_t = np.identity(3) * np.random.rand(3, 1) * 0.1
default_R = np.identity(3) * np.random.rand(3, 1) * 0.1
class kalman_filter():
def __init__(self, Q_t = default_Q_t, R = default_R):
"""
:param Q_t: Covariance matrix defining noise of motion model deltax§
:param... |
import os
from collections import defaultdict
import random
from typing import Dict, List
import pandas as pd
from scipy.stats import stats
from lib2vec.corpus_structure import Corpus
from experiments.predicting_high_rated_books import mcnemar_sig_text, chi_square_test
from lib2vec.vectorization import Vectorizer
fro... |
# coding=utf-8
# Copyright (c) 2021 Ant Group
import unicodedata
import numpy as np
from data_structure.syntax_tree import BinaryNode
def to_binary_root(tokens, token_tree, start=0):
if isinstance(token_tree, str):
assert token_tree == tokens[start]
return BinaryNode(None, None, start, token_tree... |
import random
import time
#You are playing an antique RPG game.
#You are asked for your age. returns a message depending on whether player is over 18.
#You are asked if you want to read an introduction to the game.
#If you choose yes, it will print out a brief introduction.
#You encounter a maze. You are given an optio... |
from model.contact_form import ContactForm
import re
def test_add_contact(app, json_data_contacts, db, check_ui):
contact = json_data_contacts
old_contacts_list = db.get_db_contacts_list()
app.contact.create(contact)
new_contacts_list = db.get_db_contacts_list()
# Append old list with new item, cl... |
#!/usr/bin/env python
#
# Copyright (c) 2019 Opticks Team. All Rights Reserved.
#
# This file is part of Opticks
# (see https://bitbucket.org/simoncblyth/opticks).
#
# 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... |
#!/usr/bin/env python3
import sys,os,json,re
assert sys.version_info >= (3,9), "This script requires at least Python 3.9"
def load(l):
f = open(os.path.join(sys.path[0], l))
data = f.read()
j = json.loads(data)
return j
def find_passage(game_desc, pid):
for p in game_desc["passages"]:
if p... |
import os
import pandas as pd
import numpy as np
import json
import pickle
import zipfile
from keras.preprocessing import image
from tqdm import tqdm
import time
from sklearn.model_selection import train_test_split
from spacekit.analyzer.track import stopwatch
def load_datasets(filenames, index_col="index", column_or... |
class Solution:
def maxDistToClosest(self, seats: List[int]) -> int:
|
from django.urls import path
from . import views
from .views import LampsView, LampDetailsHistorique
urlpatterns = [
path('', views.openApp, name='openApp'),
path('getGeojson', LampsView.as_view()),
path('lamphistorique/<int:pk>', LampDetailsHistorique.as_view()),
path('getNearestLamp/', views.nearestL... |
#!/usr/bin/python
"""
this is the code to accompany the Lesson 2 (SVM) mini-project
use an SVM to identify emails from the Enron corpus by their authors
Sara has label 0
Chris has label 1
"""
import sys
from time import time
sys.path.append("../tools/")
from email_preprocess import preproc... |
#!/usr/bin/env python
# A demonstration of using khmer to populate a count-min sketch (cms)
# with a mask.
# Put all the kmers from dataset2 into cms except those that
# are shared with dataset1.
# Typically khmer accrues a small false positive rate in order to save
# substantially on memory requirements.
import khme... |
from flask import Blueprint
from . import api, config, jinja
from .router import (
ArticleListView,
ArticleView,
ArticleRssView,
ArchiveView,
TimeLineView,
)
site = Blueprint('blog', __name__, template_folder='templates')
site.add_url_rule(
'/article',
view_func=ArticleListView.as_view('a... |
import unittest
from BahtText import bahtText
class TestBahtText(unittest.TestCase):
def testZeroDigits(self):
self.assertEqual(bahtText(0), 'ศูนย์บาทถ้วน')
self.assertEqual(bahtText(0.0), 'ศูนย์บาทถ้วน')
self.assertEqual(bahtText(00.000000), 'ศูนย์บาทถ้วน')
def testOneDigits(self):
... |
#!/usr/bin/env python3
import cmd
import expr
class DerivCalc(cmd.Cmd):
def __init__(self):
cmd.Cmd.__init__(self)
self.prompt = 'deriv-calc> '
def do_exit(self, line):
'Exit the calculator.'
return True
def do_EOF(self, line):
'Exit the calculator.'
pri... |
from rest_framework import serializers
from . import models
class DispatchSCADASerializer(serializers.ModelSerializer):
class Meta:
model = models.DispatchSCADA
fields = ['settlementdate', 'duid', 'scadavalue']
class DispatchReportCaseSolutionSerializer(serializers.ModelSerializer):
class M... |
# Generated by Django 2.2.8 on 2019-12-20 05:53
from django.db import migrations, models
import etilog.models
class Migration(migrations.Migration):
dependencies = [
('etilog', '0023_impactevent_result_parse_html'),
]
operations = [
migrations.AddField(
model_name='company',
... |
import unittest
import gym
import numpy as np
from ai_safety_gridworlds.helpers import factory
from ai_safety_gridworlds.demonstrations import demonstrations
from ai_safety_gridworlds.environments.shared.safety_game import Actions
from safe_grid_gym.envs import GridworldEnv
from safe_grid_gym.envs.gridworlds_env impo... |
# MIT License
#
# Copyright (c) 2019 Meyers Tom
#
# 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... |
import cv2
# import matplotlib.pyplot as plt
img = cv2.imread('FIRST.png', cv2.IMREAD_GRAYSCALE)
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
# plt.imshow(img, cmap='gray', interpolation='bicubic')
# plt.plot([50, 100], [80, 100], 'c', linewidth=5)
# plt.show() |
from abc import ABC, abstractmethod
from typing import Generic, Sequence, TypeVar
S = TypeVar("S")
C = TypeVar("C")
class StateUpdater(ABC, Generic[S, C]):
@abstractmethod
def update_state(self, old_state: S, control: C) -> S:
pass
class Controller(ABC, Generic[S, C]):
@abstractmethod
def c... |
"""
Classes and methods to load datasets.
"""
import numpy as np
import struct
from scipy.misc import imresize
from scipy import ndimage
import os
import os.path
import pandas as pd
import json
from collections import defaultdict
from pathlib import Path as pathlib_path
import pickle
'''
Contains helper methods and c... |
from typing import Tuple
from PyQt5.QtGui import QColor
from brainframe.api.bf_codecs import Zone
from brainframe_qt.ui.resources.video_items.base import VideoItem
class AbstractZoneItem:
BORDER_COLOR = QColor(0, 255, 125)
BORDER_THICKNESS = 6
def __init__(self, zone: Zone):
self.zone = zone
... |
import datetime
import errno
import os
import uuid
import logging
import time
import matplotlib
# Force matplotlib to not use any Xwindows backend.
matplotlib.use('Agg')
import pandas as pd
from collections import namedtuple, OrderedDict
from os.path import join
from jinja2 import Environment, FileSystemLoader
from we... |
import discord
def error(message):
embed = discord.Embed(
color=discord.Color.from_rgb(),
thumbnail="https://github.com/yashppawar/alfred-discord-bot/blob/replit/error.png?raw=true",
message=str(message),
)
def requirements():
return ""
def main(client):
pass
|
import functools
class MatchException(Exception):
def __init__(self):
pass
class Match:
def __init__(self, matching_code_container, node_matcher, match_index=0):
self.matching_code_container = matching_code_container
self.node_matcher = node_matcher
self._match_index = match_... |
import os
from django.conf import settings
from email.mime.image import MIMEImage
from datetime import date
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
def send_thanks_email(first_name, last_name, email, donation):
strFrom = settings.EMAIL_FROM
ctx ... |
from math import log, pow
import numpy as np
from scipy import stats
def shannon_entropy(p):
return stats.entropy(p)
def kl_divergence(p, q):
"""Standard KL divergence."""
return stats.entropy(p, q)
def q_divergence(q):
"""Returns the q-divergence function corresponding to the parameter value q.""... |
import re
from .. import slack_manager
@slack_manager.on('app_mention')
async def reply_message(sender, data, **extra):
event = data['event']
if re.search(r'\blife\b', event['text'], re.I):
text = 'Life, don\'t talk to me about life'
else:
text = f":robot_face: knock, knock, knock, <@{ev... |
termo = int(input('Primeiro Termo: '))
razao = int(input('Razão: '))
decimo = 0
while decimo != 10:
print(termo, end=' ')
termo += razao
decimo += 1
|
"""
Trigger an automation when a LiteJet switch is released.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/automation.litejet/
"""
import logging
import voluptuous as vol
from homeassistant.core import callback
from homeassistant.const import CONF_PLA... |
import socket, hashlib, zlib, json, time, struct, traceback
from cryptography.fernet import Fernet
from DataModel import DataModel
class RestfulApiClient(object):
def __init__(self, addr = '127.0.0.1', port = 32002):
self.addr, self.port, self.cookie = addr, port, None
def Login(self, usr, pwd):
... |
#Memory Reallocation
#Advent of Code 2017 Day 6b
import numpy as np
input = "4 1 15 12 0 9 9 5 5 8 7 3 14 5 12 3"
banks = input.split("\t")
banks = [ int(x) for x in banks ]
#banks = [0, 2, 7, 0]
steps = 0
previous = []
matched = False
while matched == False:
#store current config in history
previous.app... |
n1 = int(input('Primeiro valor: '))
n2 = int(input('Segundo valor: '))
print(f'A soma entre {n1} e {n2} é igual a {n1 + n2}')
|
# Generated by Django 2.1.7 on 2020-10-25 09:34
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('account', '0013_auto_20201023_1513'),
]
operations = [
migrations.RemoveField(
model_name='user',
name='rank_id_list',
... |
from django.contrib.auth import logout
from django.http import HttpResponse
from django.shortcuts import render # noqa
from django.views.generic import View
from rest_framework import viewsets
from rest_framework.authtoken.models import Token
from users.models import User
from users.serializers import UserSerializer... |
import boto3
from .buckets import get_s3_buckets
def search_buckets(key, search_key="", search_bucket=""):
session = boto3.Session(aws_access_key_id=key.key,
aws_secret_access_key=key.secret)
list_files = []
for bucket in get_s3_buckets(session):
if not search_bucket or... |
#!/usr/bin/python3.4
# -*- coding=utf-8 -*-
#本脚由亁颐堂现任明教教主编写,用于乾颐盾Python课程!
#教主QQ:605658506
#亁颐堂官网www.qytang.com
#乾颐盾是由亁颐堂现任明教教主开发的综合性安全课程
#包括传统网络安全(防火墙,IPS...)与Python语言和黑客渗透课程!
import sys
sys.path.append('/usr/local/lib/python3.4/dist-packages/PyQYT/ExtentionPackages')
sys.path.append('/usr/lib/python3.4/site-packages... |
# jesli zduplikowana linijka moze wystapic na koncu pliku, to musi miec "enter" np. # noqa
# "jezeli\r\n
# jezeli" to nie to samo, ale
# "jezeli\r\n
# jezeli\r\n" jest duplikatem; uzyc regexu do dodania \r\n
import os
sciezka = input("Enter the path: ")
for subdir, dirs, files in os.walk(sciezka):
for file in... |
"""
Programa 084
Área de estudos.
data 30.11.2020 (Indefinida) Hs
@Autor: Abraão A. Silva
"""
# Biblioteca que controla o tempo.
import time
# Cabeçalho da urna.
print('Eleições Presidenciais'.center(35)+'\n',
'-'*30+'\n',
'João Pé de Feijão'+'_'*10+'1'.rjust(3)+'\n',
'Inácio Pelota'+'_'*14+'2'.... |
# Copyright (c) 2014 Rackspace Hosting
#
# 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 rest_framework import serializers
from .models import Archive
from grandchallenge.cases.serializers import ImageSerializer
class ArchiveSerializer(serializers.ModelSerializer):
images = ImageSerializer(read_only=True, many=True)
class Meta:
model = Archive
fields = ("id", "name", "images... |
import copy
import numbers
import os.path
import warnings
from collections import namedtuple
import audioread
import librosa
import numpy as np
import scipy.io.wavfile as wav
import scipy
from scipy.signal import check_COLA
import soundfile as sf
import pyloudnorm
from . import constants
from . import utils
from . im... |
# -*- coding: utf-8 -*-
# Copyright 2019 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""The Binhost API interacts with Portage binhosts and Packages files."""
from __future__ import print_function
import functools... |
import time
PROGRESS_BAR_SIZE = 15
class Task:
def __init__(self, task_name):
self.name = task_name
self.start_time = time.time()
self.is_progressive_task = False
self.is_done = False
def get_execution_time(self):
return round(time.time() - self.start_time, 2)
curre... |
from dateutil.parser import parse
import os
import extract_msg
import hashlib
"""Removes the received datetime of an .msg email file that has previously been added as a prefix to the file name by another email_renamer script
Creates log file that lists original filepath, new filename, and file fixity. (| delimited)
"... |
import scrapy
class BlogSpider(scrapy.Spider):
name = 'currencyspider'
start_urls = ['https://www.bankexamstoday.com/2019/06/countries-capital-currency-and-languages.html']
def parse(self, response):
for link in response.css('tr td:nth-child(3)'):
yield {'currency': link.css('t... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import itertools
import os
import subprocess
from lab.environments import LocalEnvironment, BaselSlurmEnvironment
from lab.reports import Attribute
from downward.reports.compare import ComparativeReport
import common_setup
from common_setup import IssueConfig, IssueExp... |
from .base import HTTP
from .airos import AirOS
__all__ = [
'AirOS'
]
|
from JumpScale import j
from Network import Network
from Interface import Interface
from Disk import Disk
from Pool import Pool
from StorageController import StorageController
from KVMController import KVMController
from Machine import Machine
from CloudMachine import CloudMachine
from MachineSnapshot import MachineSna... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-04-08 19:17
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('push_notifications', '0006_webpushdevice'),
]
operations = [
migrations.AddF... |
import pyVmomi
from osbot_utils.utils.Misc import wait
from k8_vmware.vsphere.VM_Keystroke import VM_Keystroke
class VM:
def __init__(self, vm):
self.vm = vm
def config(self):
return self.summary().config
def controller_scsi(self):
controllers = self.devices_SCSI_Controllers()
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.