content stringlengths 5 1.05M |
|---|
import json
import pytest
from app import app
@pytest.fixture
def client():
return app.test_client()
def test_response_success(client):
response = client.get('/0')
expected_response = {
'extenso': 'zero'
}
assert json.loads(response.data) == expected_response
def test_response_error(c... |
# From https://stackoverflow.com/a/31736883
from config.config import IS_WINDOWS
if (IS_WINDOWS == True):
import msvcrt
else:
import sys
import select
import termios
# Courtesy from pokeyrule (https://github.com/pokey)
class KeyPoller():
def __enter__(self):
if (IS_WINDOWS == False):
... |
import numpy as np
def split_by_timestamp(df_all, col="timestamp", perc=90):
split_timestamp = np.percentile(df_all.timestamp, perc)
df_train = df_all[df_all[col] <= split_timestamp]
df_val = df_all[(df_all[col] > split_timestamp)]
return df_train, df_val
|
"""
Analysis of scenes (features, or parts of segmented images).
# Author: Vladan Lucic (Max Planck Institute for Biochemistry)
# $Id$
"""
from __future__ import unicode_literals
from __future__ import absolute_import
__version__ = "$Revision$"
from .em_lm_correlation import EmLmCorrelation
from .neighborhood import... |
"""Tasks related to creation of notifications"""
from . import slack
__all__ = ["slack"]
|
from django.db import models
class VesselManager(object):
def create(self, code):
if not code:
raise ValueError("Vessel code can't be empty")
vessel = Vessel(code=code)
vessel.save()
return vessel
class EquipmentManager(object):
def create(self, code, name, lo... |
"""This module contains the general information for StorageHddMotherBoardTempStats ManagedObject."""
from ...ucscmo import ManagedObject
from ...ucsccoremeta import UcscVersion, MoPropertyMeta, MoMeta
from ...ucscmeta import VersionMeta
class StorageHddMotherBoardTempStatsConsts():
LEFT_INLET_TEMP_NOT_APPLICABLE... |
import configparser
from datetime import datetime
from fellowcrm import db
from flask_login import current_user
import json
config = configparser.ConfigParser()
config.read('acitivities.ini')
class Activity(db.Model):
id = db.Column(db.Integer, db.Sequence('activity_id_seq'), primary_key=True)
typ = db... |
#!/opt/conda/envs/rapids/bin/python3
#
# Copyright 2020 NVIDIA Corporation
# SPDX-License-Identifier: Apache-2.0
import os, wget, gzip
import hashlib
import logging
from datetime import datetime
from dask.distributed import Client, LocalCluster
import dask_cudf
import dask.bag as db
import cudf, cuml
import pandas a... |
""" Generator for translation, protein folding and translocation submodel for eukaryotes
:Author: Yin Hoon Chew <yinhoon.chew@mssm.edu>
:Date: 2019-06-14
:Copyright: 2019, Karr Lab
:License: MIT
"""
from wc_onto import onto as wc_ontology
from wc_utils.util.units import unit_registry
import wc_model_gen.global_vars as... |
"""
Django settings for creator project.
Generated by 'django-admin startproject' using Django 2.1.7.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
f... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... |
# %%
# Load dependencies
import numpy as np
import matplotlib.pyplot as plt
import audio_dspy as adsp
import scipy.signal as signal
import tensorflow as tf
from tensorflow import keras
import librosa
from tqdm import tqdm
import os
import random
import sys
sys.path.append('..')
from utils.utils import plot_fft, load_f... |
from setuptools import setup, find_packages
from datetime import datetime
now = datetime.now()
date_time = now.strftime("%Y%m%d%H%M%S")
version_number = "0.0." + date_time
with open("version_info.txt", "w") as f:
f.write(version_number)
with open("README.md", "r") as readme_file:
readme = readme_file.read()
... |
import serial
import time
connecting_to_dongle = 0
print("Connecting to dongle...")
# Trying to connect to dongle until connected. Make sure the port and baudrate is the same as your dongle.
# You can check in the device manager to see what port then right-click and choose properties then the Port Settings
# tab to se... |
"""
Pypkg
"""
|
"""This module contains input/output functions.
There are two types of data being handled: session data and gene library data.
Session data:
A dict containing the following attributes from the SessionData object:
* general_settings
* param_info
* advanced_mutate
* global_stats_disp... |
"""Module to allow logins on the site."""
from flask import render_template, flash, redirect, url_for, session, abort, g
from .models import db, User
from .forms import AuthForm, RegisterForm
from . import app
import functools
def login_required(view):
"""Ensure the user can only see the login page initially."""
... |
import matplotlib.pyplot as plt
import os
import pandas as pd
class Visualize():
def __init__(self, path_to_folder_of_assessment_file, path_to_folder_of_DBDs, output_folder, dbd_for_plot, task='boxplot'):
"""
:param path_to_folder_of_assessment_file: folder path from where assesment file should ... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 IBM Corp.
#
# 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 r... |
from time import perf_counter_ns as ns
from collections import deque as dq
def solution(cacheSize, cities):
if not cacheSize:
return len(cities) * 5
ans = 0
q = dq([])
for c in cities:
c = c.lower()
if c not in q:
if len(q) == cacheSize:
q.popleft()
... |
"""Module containing tests for the index based Exports Site data source"""
import os
from collections import Iterator
from datetime import date, timedelta
from typing import Optional
from unittest import TestCase, main
from unittest.mock import patch, Mock, call
from selenium import webdriver
from judah.sources.expor... |
import logging, motor.motor_asyncio
from os import environ
from typing import NamedTuple
from dotenv import load_dotenv
import nextcord
import yarl
load_dotenv()
__all__ = (
"Algolia",
"Client",
"Colours",
"Database",
"Emojis",
"Icons",
"Stats",
"Tokens",
"RapidApi",
"Redire... |
coeffs = np.polyfit(x, y, deg=3)
|
# -*- coding: utf-8 -*-
import hashlib
import json
import time
import pycurl
from ..base.multi_account import MultiAccount
def args(**kwargs):
return kwargs
class DebridlinkFr(MultiAccount):
__name__ = "DebridlinkFr"
__type__ = "account"
__version__ = "0.03"
__status__ = "testing"
__pylo... |
# Python
from __future__ import unicode_literals
import email.utils
# Django
import django
def test_site_notify_default(command_runner, mailoutbox, settings):
# Send to default recipients (admins).
assert settings.ADMINS
result = command_runner('site_notify')
assert result[0] is None
assert len(m... |
# -*- coding: utf-8 -*-
"""
api
~~~
Implements API Server and Interface
:author: Feei <feei@feei.cn>
:homepage: https://github.com/wufeifei/cobra
:license: MIT, see LICENSE for more details.
:copyright: Copyright (c) 2017 Feei. All rights reserved
"""
import socket
import errno
impo... |
import pygame as pg
import Sprites
import Alt
from random import randrange
class Player:
def __init__ (self,x,y) :
self.x=x
self.y=y
self.score = 0
self.etage = 1
self.vie = 10
self.vie_max = 10
self.range = 5
self.vel=1
self.dx = 0
self.dy = 0
self.objets... |
# Copyright 2018, The Ssite 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 by applicable law or agreed to in wr... |
import os
import xml.etree.ElementTree as ET
import cv2
in_dir = './data/imgs/'
img_dir = './data/VOCdevkit2007/VOC2007/JPEGImages/'
anno_dir = './data/VOCdevkit2007/VOC2007/Annotations/'
fd = open('./data/VOCdevkit2007/VOC2007/ImageSets/Main/', 'wt')
count = 0
dir_temp = os.path.abspath(in_dir)
for (root, dirs, file... |
# -*- coding: utf-8 -*-
from crontab import CronTab
class CrontabControl:
def __init__(self):
self.cron = CronTab()
self.job = None
self.all_job = None
def write_job(self, command, schedule, file_name):
self.job = self.cron.new(command=command)
self.job.setall(schedule... |
import os
import json
from data_classes import SingleCharacter, BaseMod
def run_test():
# load main config
with open('main_config.json', 'r') as f:
cfg = json.load(f, strict=False)
print('Hello, and Welcome to the CrusaderAI Manager!')
print('=====')
print('Choose a base-mod:')
for i,... |
# -*- coding: utf-8 -*-
#
# @Author: lijiancheng0614
# @Date: 2020-03-06
#
"""Model.
"""
import datetime
from peewee import (BigIntegerField, BooleanField, CharField, CompositeKey,
DateTimeField, FloatField, Model, MySQLDatabase,
PostgresqlDatabase, SqliteDatabase)
from settin... |
# -*- coding: utf-8 -*-
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Authors: Luc LEGER / Coopérative ARTEFACTS <artefacts.lle@gmail.com>
from django import template
from django.utils.translation import gettext_la... |
import csv
import pandas as pd
import os
import numpy as np
BASE_DIR = os.getcwd()
def merge_dev_data(result_filename, file_pos, file_neg):
"""
Description: function that merges dev data from both
sentiments into a single data structure
Input:
-result_filename: str, n... |
from django import forms
from .models import PushInformation, SubscriptionInfo
class SimplePushForm(forms.Form):
status_type = forms.ChoiceField(choices=[
('subscribe', 'subscribe'),
('unsubscribe', 'unsubscribe')
])
def save_or_delete(self, subscription, user, status_type):
data... |
#!/usr/bin/env python3
#
# This example demonstrates how to write colored text to STDOUT.
# In this case RGB colors are generated. Please note that this might not work
# on older systems if RGB is not supported.
#
from jk_console import Console
def rangef(start, end, step):
v = start
while v <= end:
yield v
... |
import example_ghactions
def test_cli():
example_ghactions.show(["27"])
|
from .lq_conv2d import *
|
# -*- coding: utf-8 -*-
'''Models application.'''
import treatment
# from cross_validation import multi_cross_validation
import numpy as np
import pandas as pd
import xgboost as xgb
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.model_selection import train_test_split
from sklearn.linear_mode... |
"""
Generate the contributors database.
FIXME: replace `requests` calls with the HTTPie API, when available.
"""
import json
import os
import re
import sys
from copy import deepcopy
from datetime import datetime
from pathlib import Path
from subprocess import check_output
from time import sleep
from typing import Any,... |
import Operacije
class Matrika:
def __init__(self, seznam):
self.sez = seznam
def __add__(self, other):
return Operacije.vsota(self.sez, other.sez)
def __sub__(self, other):
nasprotna_vrednost = Operacije.mnozenje_s_skalarjem(other.sez, -1)
return Operacije.vsota(self.se... |
"""Default configuration
Use env var to override
"""
import os
ENV = os.getenv("FLASK_ENV")
DEBUG = ENV == "development"
SECRET_KEY = os.getenv("SECRET_KEY")
|
from nose.tools import istest, assert_equal
from precisely import starts_with
from precisely.results import matched, unmatched
@istest
def starts_with_matches_when_actual_string_starts_with_value_passed_to_matcher():
matcher = starts_with("ab")
assert_equal(matched(), matcher.match("ab"))
assert_equal(ma... |
# This is currently configured to work with models produced in exploration6.ipynb
# in https://github.com/ebrahimebrahim/lung-seg-exploration
# This wrapper class will handle loading a model and running inference
import monai
import numpy as np
import torch
from .segmentation_post_processing import SegmentationPostPro... |
"""Graphical User Interface for the application that is done by kivy graphics library."""
import os
import signal
import socket
import subprocess
from subprocess import Popen
import webbrowser
from pathlib import Path
import datetime as dt
import threading
import kivy
kivy.require('1.10.1')
from kivy.app import App
... |
import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ["MOLECULE_INVENTORY_FILE"]
).get_hosts("all")
def test_nginx_installed(host):
nginx = host.package("rh-nginx18")
assert nginx.is_installed
def test_nginx_config_exists(host):
... |
import hou
import nodegraph
def getRunning():
return hou.session.scRunning
def setRunning(input):
hou.session.scRunning = input
def getLast():
return hou.session.scLastNode
def setLast(node):
hou.session.scLastNode = node
def getCurrent():
return hou.session.scCurrentNode
def setCurrent(node)... |
import sys
from pyxb.exceptions_ import ValidationError
import qsdl.parser.config01 as configPYXB
from qsdl.parser.parsedConfig import ConfigDescriptor
import qsdl.simulator.simulationRunner as simulationRunner
import qsdl.parser.cliParser as cliParser
import matplotlib as matplotlib
# Use a non-interactive matplotlib ... |
import numpy as np
import matplotlib.pyplot as plt
from simulator_ic import simul
from solar_parallel import solar
from tqdm import tqdm
########################################################################
# define the class 'the simulation_plot' for irrepresentable condition #
###########... |
import re
import os
class converter(object):
def __init__(self, params):
self.figure = params.get('figure')
self.labelled_nodes = params.get('labelled_nodes')
self.filename = params.get('filename')
def export_to_tex(self):
mod_str = self.figure.to_string()
f = open("../... |
import requests
from transbank.common.headers_builder import HeadersBuilder
from transbank.common.integration_type import IntegrationType, webpay_host
from transbank.common.options import Options, WebpayOptions
from transbank import oneclick
from transbank.error.transaction_authorize_error import TransactionAuthorizeE... |
import sys
import numpy as np
import openmdao.api as om
import pycycle.api as pyc
class Turboshaft(om.Group):
def initialize(self):
self.options.declare('design', default=True,
desc='Switch between on-design and off-design calculation.')
def setup(self):
therm... |
from django.contrib.auth.views import PasswordChangeView
from django.urls import path
from telescope_shop.accounts.views import RegisterUserView, LogoutView, LoginVew, UpdateUserView, \
PasswordsChangeView, DeleteUserView, ProfileDetailsView
urlpatterns = [
path('register/', RegisterUserView.as_view(), name='... |
from .base_action import BaseAction
class Communication(BaseAction):
pass
class Integrations(BaseAction):
pass
class Workshops(BaseAction):
pass
|
def encode(num, return_type="int"):
"""Return varint for given number"""
out = []
while True:
# get first seven bits of number
first_seven = num & 0x7f
num = num >> 7
if num:
# there are more bytes, make msb of first seven 1 and continue
out.append(fir... |
from aws_cdk import (
aws_iam as iam,
aws_lambda as lambda_,
aws_secretsmanager as sm,
custom_resources as cr,
core
)
class SecretReader(lambda_.Function):
prefix = 'EcoStruxure'
def __init__(
self, scope: core.Construct, id: str,
secret: sm.Secret,
att... |
from setuptools import setup, find_packages
INFO = {'name': 'Robot Brain',
'version': '0.2.0',
}
setup(
name = INFO['name'],
version = INFO['version'],
author = 'Jack Minardi',
packages = find_packages(),
zip_safe = False,
maintainer = 'Jack Minardi',
maintainer_email = 'jack@mina... |
import socketio
import eventlet
from typing import Text, List
from app.config import Config
from app.logging import logger
from app.services import S3Service, GoogleSpeechService
manager = socketio.BaseManager()
sio = socketio.Server(async_mode='eventlet', client_manager=manager, binary=True, cors_allowed_origins='*... |
#!/usr/bin/env python
import os
import errno
import IPython.html
import shutil
import urllib
from jinja2 import Environment
from jinja2 import FileSystemLoader
from install_lib import COLAB_ROOT_PATH
from install_lib import pjoin
from install_lib import CopyTreeRecursively
from install_lib import MakeDirectoryIfNotE... |
import dne
fob |
from decimal import Decimal, getcontext
getcontext().prec = 20
u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
print((u + v) + w)
print(u + (v + w))
u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
print((u*v) + (u*w))
print(u * (v+w))
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import csv
import sys
import json
import ckanapi
import requests
import scraperwiki
def FetchSystemArguments():
'''Fetching arguments from the command line interface.'''
arguments = {
'api_key': sys.argv[1],
'json_path': sys.argv[2],
'download_temp... |
from rest_framework import serializers
from .models import UserProfile
from allauth.account.adapter import get_adapter
from rest_auth.registration import serializers as RegisterSerializer
from roboPortal.models import portalUser
class UserProfileSerializer(serializers.ModelSerializer, RegisterSerializer.RegisterSeria... |
# -*- encoding=utf-8 -*-
"""
# **********************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
# [oecp] is licensed under the Mulan PSL v1.
# You can use this software according to the terms and conditions of the Mulan PSL ... |
import os, sys, time, json, yaml, uuid
import redis
import torch
import numpy as np
from PIL import Image
from werkzeug.utils import secure_filename
from flask import Flask, request, flash, jsonify
mlpipe_root = os.path.abspath("../..")
# sys.path.insert(1, os.path.join(sys.path[0], mlpipe_root)
sys.path.insert(0, mlpi... |
import os.path
for settings_name in ("default_settings.py", "settings.py"):
settings_path = os.path.join(os.path.dirname(__file__), settings_name)
if os.path.exists(settings_path):
execfile(settings_path, globals(), locals())
|
import matplotlib.pyplot as plt
from glob import *
from datetime import datetime, date
from statistics import mode
#input: a list of filenames
#Return: nothing, but produces and save graphs
def produce_date_graphs(date_files):
#Get the start dates and end dates from the files
start_dates, end_dates = get_date... |
r"""Cryptographic key derivation functions for the ICC Master Keys and ICC Session Keys.
ICC Master Key derivation method A:
>>> import pyemv
>>> iss_mk = bytes.fromhex('0123456789ABCDEFFEDCBA9876543210')
>>> pan = '99012345678901234'
>>> psn = '45'
>>> icc_mk = pyemv.kd.derive_icc_mk_a(iss_mk, pa... |
# coding=utf-8
import codecs
import os
from collections import Counter
class CompanyCase:
def __init__(self, language='en', ngram_length=2):
self.ngram_length = ngram_length
self.transitions = self.fetch_all_transitions(language, ngram_length)
self.norm_transitions = self.normalize_transit... |
import pytest
from ..http_status import HttpStatusBase
from ..mock_data import MockDataHandler
md_handler = MockDataHandler()
@pytest.mark.integration
@pytest.mark.mockdata
@pytest.mark.response
class TestMockDataResponseFormat(HttpStatusBase):
@pytest.mark.parametrize("frmt", ["", "json", "jsonl", "ttl"])
... |
import pytest
from seleniumbase import BaseCase
from qa327.models import db, User
from qa327_test.conftest import base_url
from unittest.mock import patch
from werkzeug.security import generate_password_hash, check_password_hash
test_user = User(
email='test_frontend@test.com',
name='testuser',
password=ge... |
from icemet_sensor import homedir, datadir
from icemet.cfg import Config, ConfigException
from icemet.pkg import name2ext
import os
import shutil
default_file = os.path.join(datadir, "icemet-sensor.yaml")
def create_config_file(dst):
os.makedirs(os.path.split(dst)[0], exist_ok=True)
shutil.copy(default_file, dst)... |
from turtle import *
from math import *
bgcolor("black")
speed(5)
ht()
colors = ["#FF4858", "#72F2EB", "#747F7F"]
x, y, r = 0, -40, 400
direction = 90
c = 0
while r > 20:
color(colors[c % len(colors)])
pu()
goto(x, y)
seth(direction)
fd(r)
right(162)
pd()
length = r * sin(pi * 2 / 5) / (1 + sin(pi / 10))
be... |
def shell_sort(arr: list) -> list:
"""Sort a list using shell sort
Args:
arr (list): the list to be sorted
Returns:
list: the sorted list
"""
# Calculate the gap to sort the items
gap = len(arr) // 2
# While the gap isn't 0
while gap > 0:
# Set i to the first e... |
# Quantum Inspire SDK
#
# Copyright 2018 QuTech Delft
#
# 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 o... |
import sqlite3
from django.contrib.auth.models import Group
from django.core.management.base import BaseCommand
from django.db import transaction
from django.utils.dateparse import parse_date
from apps.accounts.models import User
from apps.thesis.models import Thesis, Category
class Command(BaseCommand):
help =... |
from context import openrefine_wrench
wanted = {
"columnWidths": None,
"encoding": "UTF-8",
"guessCellValueTypes": False,
"headerLines": None,
"header_lines": 1,
"ignoreLines": None,
"ignore_lines": -1,
"includeFileSources": False,
"limit": -1,
"linesPerRow": None,
"processQ... |
import configargparse
def config_parser():
## Base experiment config
parser = configargparse.ArgumentParser()
parser.add_argument('--config', is_config_file=True,
help='config file path')
parser.add_argument("--expname", type=str, help='experiment name')
parser.add_argument... |
from nanopore.mappers.abstractMapper import AbstractMapper
from nanopore.mappers.last import Last
from sonLib.bioio import system, fastaRead, fastqRead, fastaWrite
import os
class LastParams(Last):
def run(self):
Last.run(self, params="-s 2 -T 0 -Q 0 -a 1")
class LastParamsChain(LastParams):
d... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2020 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in co... |
import numpy as np
from sklearn.metrics import average_precision_score
def load_data(data_path):
"""load array data from data_path"""
data = np.load(data_path)
return data['X_train'], data['y_train'], data['X_test'], data['y_test']
def calculate_average_precision(label, index, similarity, num_search_sam... |
from random import randrange
from time import sleep
import pygame
import sys
try:
pygame.init()
except:
print('\033[31mJogo nao pode ser inicializado nessa maquina :(')
# Cores
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
black = (0, 0, 0)
# Configuracoes da tela
info = p... |
filename = 'hex.txt'
def main(filename):
i = 0
with open(filename, "r") as f:
for line in f:
translate(line, i)
i = i + 1
def translate(hex, inc):
r = hex[:2]
g = hex[2:4]
b = hex[4:]
'''print(r+g+b)'''
r = str(hexToDecimal(r))
g = str(hexToDecimal(g))
... |
#!/usr/bin/env python3
import requests
filename = 'test.pdf'
container = 'attachments'
# Data
endpoint = 'azure logic app url'
payload = {
"to": 'change@me.com',
"subject": 'Testing in progress',
"body": "This is email body of test email!",
"file_name": filename,
"file_path": f'/{container}/{file... |
import os
import subprocess
from fire import Fire
def shell(command):
'''Execute bash commands'''
if isinstance(command, str):
command = [command]
[subprocess.call([c], shell=True) for c in command]
def html(pelican='pelicanconf.py', output='output', content='content', theme='theme'):
'''Build... |
import pathlib
import sys
import pytest
from testsuite.databases.mysql import discover
pytest_plugins = [
'testsuite.pytest_plugin',
'testsuite.databases.mysql.pytest_plugin',
]
def pytest_addoption(parser):
group = parser.getgroup('Example service')
group.addoption(
'--example-service-por... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# pylint: disable=C0103
# pylint: disable=C0413
# pylint: disable=W0702
'''
Script that tries list of passwords against HTTP Basic Authorization.
Dependencies:
* python2
# Debian/Ubuntu: apt-get install python
# Fedora: dnf install python
* reques... |
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from mayan.apps.smart_settings.classes import Namespace
from .literals import (
DEFAULT_DOCUMENT_BODY_TEMPLATE, DEFAULT_LINK_BODY_TEMPLATE
)
namespace = Namespace(label=_('Mailing'), name='mailer')
setting_link_subj... |
#!/usr/bin/env python3
# Import data
with open('/home/agaspari/aoc2021/dec_10/dec10_input.txt') as f:
nav_lines = f.read().split('\n')
openers = ['<', '(', '[', '{']
closers = ['>', ')', ']', '}']
# Task 1: Find all of the corrupted lines
corrupted_char = list()
for line in nav_lines:
curr_chunk = list()
... |
# Copyright (c) 2020 PaddlePaddle 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 app... |
from flask import render_template, session, redirect, url_for, abort, flash, request, current_app, make_response
from datetime import datetime
from . import main
from .forms import EditProfileForm, EditProfileAdminForm, PostForm, CommentForm
from .. import db
from ..models import User, Role, Permission, Post, Comment
... |
from flask import Flask, session, redirect, render_template, request
import random
from datetime import datetime
app = Flask(__name__)
app.secret_key='This'
@app.route('/')
def start():
if not ('gold') in session:
session['gold'] = 0;
if not ('activities') in session:
session['activities'] = {}... |
import keras
from keras.models import *
from keras.layers import *
import keras.backend as K
from .config import IMAGE_ORDERING
from .model_utils import get_segmentation_model , resize_image
from .vgg16 import get_vgg_encoder
from .mobilenet import get_mobilenet_encoder
from .basic_models import vanilla_encoder
from ... |
#!/usr/bin/env
# -*- coding: utf-8 -*-
"""
Copyright 2017-2018 Jagoba Pérez-Gómez
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 ... |
from typing import (
Any
)
from eth_utils import (
encode_hex,
)
from eth.chains.base import (
Chain
)
from eth.tools.fixture_tests import (
apply_fixture_block_to_chain,
new_chain_from_fixture,
normalize_block,
normalize_blockchain_fixtures,
)
from trinity.rpc.format import (
format_p... |
import pandas as pd
import datetime
from sklearn.linear_model import LinearRegression
from matplotlib import pyplot
import numpy as np
import random
#df.head()
#df.tail()
def rsi(df):
'''This function builds Relative Strength Indicator.
Returns:
-------------
DataFrame of stock prices and RSI
''... |
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import os
import tempfile
import unittest
import numpy as np
from torchrec.datasets.cri... |
from ..ServiceCore import Service
from .IAPICore import IAPI
from .routing.Router import Router
from ...conf.API.apis.APICoreConfig import APICoreConfig
from ...util.api.validators.InternalAPIValidators import InternalAPIValidator
from ...util.app.ErrorFactory.api.ArgumentValidation import ArgumentRequired,InvalidArgum... |
#!{PYTHON}
# example syntax: data_access_put_s2_l2.py /data/mx/sdrs
from multiply_data_access import DataAccessComponent
import logging
import os
import sys
logger = logging.getLogger('ScriptProgress')
logger.setLevel(logging.INFO)
# setup parameters
configuration_file = sys.argv[1]
start_date = sys.argv[2]
stop_dat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.