content stringlengths 5 1.05M |
|---|
"""
Please implement a `test` (e.g. pytest - this is up to you) for the method `compute_phenotype_similarity()`
- The details are up to you - use whatever testing framework you prefer.
"""
|
# Aula 10 - Desafio 31: Custo da viagem
# Pedir a distancia de uma viagem em seguida:
# se a viagem for até 200Km de distancia, o valor da passagem será de R$0,50 por Km rodado
# se for maior que 200 Km, o valor sera de R$0,45 por Km rodado
d = int(input('Informe a distancia em Km da sua viagem: '))
if d <= 200:
... |
import os,shutil
from .ExtensibleFileObject import ExtensibleFileObject
def file_list_dedup(file_list):
new_list=list(set(file_list))
new_list.sort(key=file_list.index)
return new_list
def relpath(a,b):
pass
def check_vfile(func):
pass
def refresh_directory(path):
if os.path.exists... |
import nuke
t=nuke.menu("Nodes")
u=t.addMenu("Pixelfudger", icon="PxF_Menu.png")
t.addCommand( "Pixelfudger/PxF_Bandpass", "nuke.createNode('PxF_Bandpass')", icon="PxF_Bandpass.png" )
t.addCommand( "Pixelfudger/PxF_ChromaBlur", "nuke.createNode('PxF_ChromaBlur')", icon="PxF_ChromaBlur.png")
t.addCommand( "Pixelfud... |
BOT_NAME = 'naver_movie'
SPIDER_MODULES = ['naver_movie.spiders']
NEWSPIDER_MODULE = 'naver_movie.spiders'
ROBOTSTXT_OBEY = False
DOWNLOAD_DELAY = 2
COOKIES_ENABLED = True
DEFAULT_REQUEST_HEADERS = {
"Referer": "https://movie.naver.com/"
}
DOWNLOADER_MIDDLEWARES = {
'scrapy.downloadermiddlewares.useragent.U... |
import asyncio
import uvloop
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from scrapper import scrap
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
if __name__ == "__main__":
scheduler = AsyncIOScheduler()
scheduler.add_job(scrap, 'interval', seconds=5)
scheduler.start()
... |
from ..classes import WorkflowAction
class TestWorkflowAction(WorkflowAction):
label = 'test workflow state action'
def execute(self, context):
context['workflow_instance']._workflow_state_action_executed = True
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Written by Lucas Sinclair and Paul Rougieux.
JRC biomass Project.
Unit D1 Bioeconomy.
"""
# Built-in modules #
import os
# Third party modules #
# First party modules #
from autopaths import Path
from autopaths.auto_paths import AutoPaths
from autopaths... |
import numpy as np
import interconnect
import copy
# # VARIABLES
N = 3001 # max clock cycles +1
FW = 16 # flit width
FPP = 32 # flits per packet
def get_header(FW=16):
'''
generates a random header for a flit-width of FW)
'''
return np.random.random_integers(0, (1 << FW)-1)
# data, day = np.loa... |
from py_db import db
import NSBL_helpers as helper
# Re-computes the team hitting tables
db = db('NSBL')
def process():
print "processed_team_hitting"
db.query("TRUNCATE TABLE `processed_team_hitting_basic`")
db.query("TRUNCATE TABLE `processed_team_hitting_advanced`")
yr_min, yr_max = db.query("... |
"""
The MIT License (MIT)
Copyright (c) 2020-Current Skelmis
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, mer... |
# -*- coding: utf-8 -*-
try:
import mdp
use_mdp = True
except ImportError:
print 'mdp (modular data processing) module not installed. Cannot do PCA'
use_mdp = False
import numpy as np
from neuropype import node
from itertools import imap, repeat
from copy import deepcopy, copy
from neuropype import par... |
import json
import codecs
import tldextract
urls = dict()
duplicates = list()
with codecs.open('/home/rkapoor/Documents/ISI/data/Network/intersecting-urls.jsonl', 'r', 'utf-8') as f:
for line in f:
doc = json.loads(line)
url = doc['url']
if url in urls:
urls[url] += 1
el... |
import subprocess
from uuid import uuid1
import yaml
from jinja2 import Environment, PackageLoader
from sanetrain.workflow_builder import generate_training
def test_generate_training():
env = Environment(loader=PackageLoader('sanetrain', 'templates'))
template = env.get_template('test_template.py')
wit... |
#!/usr/bin/python
import time
fact_arr = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
class memoize:
def __init__(self, function):
self.function = function
self.memoized = {}
def __call__(self, *args):
try:
return self.memoized[args[0]]
except KeyError:
... |
#! /usr/bin/env python
def condense(w):
return w[0] + str(len(w)-2) + w[-1:]
def expand(w):
length = int(w[1:-1]) + 2
for word in get_words(length):
if word.startswith(w[0]) and word.endswith(w[-1:]):
print word
def get_words(length, filename = '/usr/share/dict/words'):
return (wor... |
#
#
# Use: genKey(5)
# => "xmckl"
#
#
import math, random
def genKey(n):
alphabet = list("abcdefghijklmnopqrstuvwxyz")
out = ""
for i in range(n):
out += alphabet[math.floor(random.randint(0, 25))]
return out
|
linha1 = input().split(" ")
linha2 = input().split(" ")
cod1, qtde1, valor1 = linha1
cod2, qtde2, valor2 = linha2
total = (int(qtde1) * float(valor1)) + (int(qtde2) * float(valor2))
print("VALOR A PAGAR: R$ %0.2f" %total) |
# https://github.com/dannysteenman/aws-toolbox
#
# License: MIT
#
# This script will set a CloudWatch Logs Retention Policy to x number of days for all log groups in the region that you exported in your cli.
import argparse
import boto3
cloudwatch = boto3.client("logs")
def get_cloudwatch_log_groups():
kwargs... |
from backend.util.crypto_hash import crypto_hash
HEX_TO_BINARY_CONVERSION_TABLE ={
'0': '0000',
'1': '0001',
'2': '0010',
'3': '0011',
'4': '0100',
'5': '0101',
'6': '0110',
'7': '0111',
'8': '1000',
'9': '1001',
'a': '1010',
'b': '1011',
'c': '1100',
... |
import numpy as np
from numpy.linalg import inv, cholesky
from scipy.stats import norm, rankdata
from synthpop.method import NormMethod, smooth
class NormRankMethod(NormMethod):
# Adapted from norm by carrying out regression on Z scores from ranks
# predicting new Z scores and then transforming back
def ... |
from caty.core.spectypes import UNDEFINED
from caty.core.facility import Facility, AccessManager
class MongoHandlerBase(Facility):
am = AccessManager() |
nome=input('digite seu nome completo =')
nomeup=nome.upper()
nomelo=nome.lower()
nomese=nome.strip()
dividido=nome.split()
print('em maiusculas = {}'.format(nomeup.strip()))
print('em minusculas = {}'.format(nomelo.strip()))
print('o seu nome tem {} letras'.format(len(nomese)-nomese.count(' ')))
print('o seu primeiro n... |
from flask import render_template, request
from sqlalchemy import desc
from app.proto import bp
from app.models import Share
@bp.route('/', methods=['GET', 'POST'])
@bp.route('/index', methods=['GET', 'POST'])
def index():
user_id = request.args.get('user_id')
shares = Share.query.filter_by(user_id=user_id).o... |
import ProblemFileHandler as handler
import OJTemplate
# 生成一个题目文件
# 第一种方法:problem_text_file + test_cases_file
text_file1 = '../resources/OJ/demo_problem1_text.txt'
test_cases_file1 = '../resources/OJ/demo_problem1_test_cases.txt'
output_file1 = '../resources/OJ/Problems/Problem1.plm'
handler.generate_problem(p... |
import random
import os
import time
import server
import discord
import ctypes
import server
from discord.ext import commands
from cogs.musiccog import Music
from cogs.funcog import Fun
find_opus = ctypes.util.find_library('opus')
discord.opus.load_opus(find_opus)
TOKEN = os.getenv("DISCORD_TOKEN")
# Silence useless... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch.nn as nn
from maskrcnn_benchmark.utils.checkpoint import DetectronCheckpointer
from maskrcnn_benchmark.layers.non_local import init_nl_module
from .generalized_rcnn import GeneralizedRCNN
import torch
from maskrcnn_benchmark.layers i... |
# Copyright 2017 ForgeFlow S.L.
# Copyright 2018 Carlos Dauden - Tecnativa <carlos.dauden@tecnativa.com>
# License AGPL-3.0 or later (https://www.gnu.org/licenses/lgpl.html).
from odoo import _, api, fields, models
from odoo.exceptions import ValidationError
class AccountPaymentMode(models.Model):
_inherit = "ac... |
''' FUNCTIONS
Functions are pieces(block) of code that does something.
''' |
from classifiers.base_stance_classifier import BaseStanceClassifier
from classifiers.random_stance_classifier import RandomStanceClassifier
from classifiers.greedy_stance_classifier import MSTStanceClassifier
from classifiers.maxcut_stance_classifier import MaxcutStanceClassifier
|
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
#
import threading
import time
from opentelemetry.context import attach, detach, set_value
from opentelemetry.sdk.metrics import Meter
from opentelemetry.sdk.metrics.export import MetricsExportResult
from azure_monitor.sdk.a... |
from art import logo
import os
clear = lambda: os. system('cls')
def new_bidder():
global greater_bid
bidder = input("What's your name?: ")
bid = int(input("What's your bid?: "))
new_bidder_dict = {"Bidder": bidder, "Bid": bid}
if bid > greater_bid["Bid"]:
greater_bid = new_bidder_dict
... |
from geocoder import main
from geocoder import STARTTIME, NUM_DOCS
import re
import os
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
from datetime import datetime #for testing time of script execution
RE_URLS = 'http[s]?:\/\/(?:[a-z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-f][0-9a-f]))+'
RE_AT_M... |
#Making List l
l = [11, 12, 13, 14]
#Using append function on list
l.append(50)
l.append(60)
print("list after adding 50 & 60:- ", l)
#Using remove function on list
l.remove(11)
l.remove(13)
print("list after removing 11 & 13:- ", l)
#Using the sort function with their parameters changed
#Implementing sorting in a... |
budget_wanted = float(input())
total = 0
money_full = False
command = input()
while command != "Party!":
drink_name = command
number_of_drinks = int(input())
price = int(len(drink_name))
drinks_price = price * number_of_drinks
if drinks_price % 2 == 1:
drinks_price -= drinks_price * 25 / ... |
#!/usr/bin/env python
# coding:utf-8
#DESCRICAO
#Esse script foi desenvolvido para facilitar a forma como cadastramos,
#alteramos ou excluímos os principais ativos em dois ou mais servidores zabbix.
#A ideia é utilizar esse script para ambientes onde os eventos não estão sincronizados,
#permitindo uma ótima facilida... |
# ToggleButton examples.
import os
from ocempgui.widgets import *
from ocempgui.widgets.Constants import *
def _create_vframe (text):
frame = VFrame (Label (text))
frame.spacing = 5
frame.align = ALIGN_LEFT
return frame
def create_button_view ():
states = ("STATE_NORMAL", "STATE_ENTERED", "STATE_A... |
from sys import stdin
def print_karte(karte):
for i in range(len(karte)):
liste = [str(x) for x in karte[i]]
print(''.join(liste))
zeilen = []
max_x = 0
max_y = 0
for line in stdin:
eingabe = line.strip()
eingabe = eingabe.split(" ")
eins = [int(x) for x in eingabe[0].split(",")]
zw... |
from django.apps import apps
from .models import State, Workflow
def create_builtin_workflows(sender, **kwargs):
"""
Receiver function to create a simple and a complex workflow. It is
connected to the signal django.db.models.signals.post_migrate during
app loading.
"""
if Workflow.objects.exi... |
import os
from codecs import open
from setuptools import setup
import suit_rq
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'DESCRIPTION.rst'), encoding='utf-8') as f:
long_description = f.read()
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
set... |
import os
import wget
## Verify if directory exists. Create if it doesnt exist.
def check_dir(file_path):
directory = os.path.dirname(file_path)
if not os.path.exists(directory):
os.makedirs(directory)
## Download source Files from urls
def download_files(urls, out_path='downloads/', silent=False):
for url ... |
"""Morse code handling"""
from configparser import ConfigParser
import os
from pathlib import Path
import sys
import warnings
import numpy as np
import sklearn.cluster
import sklearn.exceptions
from .io import read_wave
from .processing import smoothed_power, squared_signal
class MorseCode:
"""Morse code
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from sklearn.preprocessing import StandardScaler
X = [[0, 15],
[1, -10]]
# scale data according to computed scaling values
print(StandardScaler().fit(X).transform(X))
|
#!/usr/bin/env python3
#Author: Stefan Toman
if __name__ == '__main__':
print("Hello, World!")
|
from l_00_inventory import inventory
import json
with open("m02_files/l_00_inventory.json", "w") as json_out:
json_out.write(json.dumps(inventory))
with open("m02_files/l_00_inventory.json", "r") as json_in:
json_inventory = json_in.read()
print("l_00_inventory.json file:", json_inventory)
print("\njson pre... |
import datetime
import time as samay
try:
from pac import voice_io
except ModuleNotFoundError:
import voice_io
def date():
x = datetime.datetime.now().strftime("%d/%m/%Y")
voice_io.show(f"Today's date is {x} (DD/MM/YYYY)")
def time():
#x=datetime.datetime.now().strftime("%H:%M:%S")
loca... |
from settings import settings
from office365.graph.graph_client import GraphClient
def get_token_for_user(auth_ctx):
"""
Acquire token via user credentials
:type auth_ctx: adal.AuthenticationContext
"""
token = auth_ctx.acquire_token_with_username_password(
'https://graph.microsoft.com',... |
import os
import pytest
import responses
from ewhs.client import EwhsClient
@pytest.fixture(scope="function")
def client():
client = EwhsClient("test", "testpassword", "9fc05c82-0552-4ca5-b588-c64d77f117a9", "ewhs")
return client
@pytest.fixture(scope="session")
def authenticated_client():
client = Ewhs... |
# -*- coding: utf-8 -*-
"""
chanjo.cli
~~~~~~~~~~~
Command line interface (console entry points). Based on Click_.
.. _Click: http://click.pocoo.org/
"""
from __future__ import absolute_import, unicode_literals
from pkg_resources import iter_entry_points
import click
from . import __version__
from ._compat import t... |
# coding: utf-8
#
# Copyright 2019 The Oppia 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 requi... |
from random import SystemRandom
import pytest
from cacheout import LFUCache
parametrize = pytest.mark.parametrize
random = SystemRandom()
@pytest.fixture
def cache():
_cache = LFUCache(maxsize=5)
return _cache
def assert_keys_evicted_in_order(cache, keys):
"""Assert that cache keys are evicted in th... |
pessoaslist = []
dicionario = {}
pessoastotal = 0
soma = media = 0
mulheres = []
acimamedia = []
while True:
dicionario['Nome'] = str(input("Nome: "))
dicionario['Sexo'] = str(input("Sexo: [M/F] "))
dicionario['Idade'] = int(input("Idade: "))
resp = str(input("Continuar?: [S/N]"))
pessoaslist.appe... |
from ..utils import Object
class MessageSchedulingStateSendAtDate(Object):
"""
The message will be sent at the specified date
Attributes:
ID (:obj:`str`): ``MessageSchedulingStateSendAtDate``
Args:
send_date (:obj:`int`):
Date the message will be sentThe date must be w... |
'''Desarrollar un programa que cargue los datos de un triángulo.
Implementar una clase con los métodos para inicializar los atributos, imprimir el valor del
lado con un tamaño mayor y el tipo de triángulo que es (equilátero, isósceles o escaleno).'''
import os
class Triangulo():
def __init__(self, lado1, lado2... |
import ldap
import pandas
import datetime.datetime
from ldap_paged_search import LdapPagedSearch
host = 'ldaps://example.com:636'
username = 'domain\\username'
password = 'password'
baseDN = 'DC=example,DC=com'
filter = "(&(objectCategory=computer))"
#attributes = ['dn']
attributes = ['*']
#ldap.set_option(ldap.OPT_... |
"""Custom pandas accessors."""
import numpy as np
import plotly.graph_objects as go
from vectorbt import defaults
from vectorbt.root_accessors import register_dataframe_accessor
from vectorbt.utils import checks
from vectorbt.utils.widgets import CustomFigureWidget
from vectorbt.generic.accessors import Generic_DFAcc... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: npu_utilization.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.prot... |
#!/usr/bin/env python
import fire
from lib.dsv.commands.dsv_command import DSVCommand
if __name__ == '__main__':
fire.Fire(DSVCommand)
|
import predpy
from predpy.predpy import *
#from predpy.predpy import predpy
from predpy.predpy import cleandata
from predpy.predpy import galgraphs
|
#
# Copyright 2020 Logical Clocks AB
#
# 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 ag... |
from rest_framework import serializers
from rest_framework.reverse import reverse
from onadata.apps.fsforms.models import FieldSightXF
from onadata.apps.logger.models import XForm
from onadata.libs.utils.decorators import check_obj
class XFormListSerializer(serializers.ModelSerializer):
class Meta:
mode... |
import numpy as np
from torch import nn, tensor
import torch
from torch.autograd import Variable
class time_loss(nn.Module):
def __init__(self, margin=0.1, dist_type = 'l2'):
super(time_loss, self).__init__()
self.margin = margin
self.dist_type = dist_type
if dist_type == 'l2':
self.dist = nn.MS... |
from types import FunctionType
import pygame
from pygame.locals import *
from pygame.font import Font
from pygameMenuPro.event import Event
COLOR_BLACK = Color(0, 0, 0)
COLOR_WHITE = Color(255, 255, 255)
class InputManager:
def __init__(self):
self.last_checked_input = []
self.last_mouse_positio... |
# Define player object
class Player:
def __init__(self, name, house):
self.name = name
self.house = house
self.hasNumber = False
# Method for setting users phonenumbers
def setPhonenumber(self, phoneNumber):
self.phoneNumber = phoneNumber
self.hasNumber = True
# 12... |
# ===============================================================================
# Copyright 2020-2021 Intel Corporation
#
# 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.ap... |
from data.station_number_data import StationNumberData
from states_machine.state_context import State
from states_machine.states.on_which_sum import OnWhichSum
class StationNumber(State):
def __init__(self):
pass
def income_handle(self) -> None:
# TODO:
#
print(f"income_handl... |
class Transformer:
def transform(self, message):
yield from map(self.map, (message,))
def map(self, message):
raise NotImplementedError('Transformer is an abstract class.')
|
import socket
import struct
from struct import *
import sys
def ethernet_head(raw_data):
dest, src, prototype = struct.unpack('! 6s 6s H', raw_data[:14])
dest_mac = get_mac_addr(dest)
src_mac = get_mac_addr(src)
proto = socket.htons(prototype)
data = raw_data[14:]
return dest_mac, src_mac, pro... |
import unittest
import random
import numpy as np
import pyquil
from cirq import GridQubit, LineQubit, X, Y, Z, PauliSum, PauliString
from openfermion import (
QubitOperator,
IsingOperator,
FermionOperator,
get_interaction_operator,
get_fermion_operator,
jordan_wigner,
qubit_operator_sparse,... |
"""UseCase for updating a metric entry's properties."""
import logging
from argparse import Namespace, ArgumentParser
from typing import Final, Optional
import jupiter.command.command as command
from jupiter.domain.adate import ADate
from jupiter.use_cases.metrics.entry.update import MetricEntryUpdateUseCase
from jup... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
USD Opinion Editor widget implementations
"""
from __future__ import print_function, division, absolute_import
__author__ = "Tomas Poveda"
__license__ = "MIT"
__maintainer__ = "Tomas Poveda"
__email__ = "tpovedatd@gmail.com"
from Qt.QtCore import *
from Qt.QtWidgets... |
# 000
# 999
#
a=['one','two','three','four']
b=range(5)
c=(9,-1,2)
#one 0 9
#...
#four 4 2
S = [4,5,3]
def next_value(current, S):
"[0,0,0] -> next one [1,0,0]"
N = current[:]
i = 0
N[i] += 1
while N[i]==S[i]:
N[i] = 0
i += 1
if i==len(N):
break
N[i]... |
# -*- coding: utf-8 -*-
#
# This file is part of the pyfixp project hosted at https://github.com/chipmuenk/pyfixp
#
# Copyright © Christian Muenker
# Licensed under the terms of the MIT License
# (see file LICENSE.txt in root directory for details)
"""
Store the version number here for setup.py and pyfixp.py
"""
__ve... |
class Card():
def __init__(self, id: int, img: str, owner, position: int):
""" Card defines a card.
Args:
id (int): card id (incremental int)
img (str): path of the card img
owner (int): card owner player, or None if in the deck/used
position (int): when it is played, the position to vote
removed... |
from django.urls import path
from .views import (
RideListView,
RideDetailView,
RideCreateView,
RideUpdateView,
RideDeleteView,
OwnerRideListView,
ShareCreateView,
SharePickRideListView,
ShareRideListView,
... |
##############################################################
# Fixing missmatches in parsing of doccano output
# The script also does not claim to be a reusable solution,
# instead it merely adapts the doccano output files to correspond
# to the entity split style of LitBank.
# Input: pandas dataframe, filename
# Ou... |
# -*- coding: utf-8 -*-
# @Date : 2017-07-18 13:26:17
# @Author : lileilei
'''
导入测试接口等封装
'''
import xlrd
def pasre_inter(filename):#导入接口
file=xlrd.open_workbook(filename)
me=file.sheets()[0]
nrows=me.nrows
ncol=me.ncols
project_name=[]
model_name=[]
interface_name=[]
interface_url=[]
interf... |
# Create a function named same_name() that has two parameters named your_name and my_name.
# If our names are identical, return True. Otherwise, return False.
def same_name(your_name, my_name):
if your_name == my_name:
return True
else:
return False
|
import numpy as np
import json
def _reject_outliers(data, m=5.):
d = np.abs(data - np.median(data))
mdev = np.median(d)
s = d / mdev if mdev else 0.
return data[s < m]
def reject(input_):
for line in input_:
d = json.loads(line)
print(_reject_outliers(np.array(d)).tolist())
|
# -*- coding: utf-8 -*-
from django.template import loader
from django.utils import formats
from django.utils.text import Truncator
import django_tables2 as tables
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _
from ..html import AttributeDict, Icon
def merge_attrs... |
"""
Implement a Caesar cipher, both encoding and decoding. The key is an integer from 1 to 25.
This cipher rotates the letters of the alphabet (A to Z).
The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A).
So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC".... |
import re
import pprint
from collections import Counter
ihaveadream = open('ihaveadream.txt', 'r')
read_dream = ihaveadream.read()
split = read_dream.split()
just_words = [re.sub('[^a-zA-Z]+','',i) for i in split]
just_long_words = []
for word in just_words:
word = word.lower()
if len(word) > 3:
j... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
import time
import os
import sys
from glob import glob
import re
import json
import random
import shutil
import re
import codecs
dones = [x for x in open("done.txt",'r').read().split("\n... |
from future.utils import with_metaclass
from openpyxl_templates.exceptions import OpenpyxlTemplateException
from openpyxl_templates.utils import OrderedType, Typed
class TemplatedWorkbookNotSet(OpenpyxlTemplateException):
def __init__(self, templated_sheet):
super(TemplatedWorkbookNotSet, self).__init__(... |
import hashlib, hmac, time
def compute_signature(message, secret):
message = message.encode('utf-8')
timestamp = str(int(time.time()*100)).encode('ascii')
hashdata = message + timestamp
signature = hmac.new(secret.encode('ascii'),
hashdata,
hashlib.sha... |
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
TEASERSWRAP_ALLOW_CHILDREN = getattr(
settings,
'TEASERS_TEASERSWRAP_ALLOW_CHILDREN',
True
)
TEASERSWRAP_PLUGINS = getattr(
settings,
'TEASERS_TEASERSWRAP_PLUGINS',
[
'TeaserPlugin',
]
)
TEAS... |
from .models_1d import *
from .models_2d import *
from .models_3d import *
def M1D(config):
if config.model_module == 'V2SD':
model = V2StochasticDepth(n=config.channels,
proba_final_layer=config.proba_final_layer,
sdrop=config.sdrop,
... |
"""Tests for the :mod:`campy.datastructures.sparsegrid` module."""
|
# -*- coding: utf-8 -*-
#
# GOM-Script-Version: 6.2.0-6
# Anja Cramer / RGZM
# Timo Homburg / i3mainz
# Laura Raddatz / i3mainz
# Informationen von atos-Projektdateien (Messdaten: *.amp / *.session)
# 2020/2021
import gom
import xml, time, os, random
import math
import datetime
## Indicates if only properties for w... |
# Generated by Django 2.2.2 on 2019-09-19 12:04
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('dcodex', '0001_initial'),
('dcodex_bible', '0001_initial'),
]
operations = [
mi... |
for i in range(0, 10, 2):
print(f"i is now {i}") |
# -- coding: utf-8 --
# Copyright 2019 FairwindsOps Inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... |
import re
import ast
import discord
from redbot.core import Config
from redbot.core import commands
from redbot.core import checks
defaults = {"Prefixes": {}}
class PrefixManager(commands.Cog):
"""Used to set franchise and role prefixes and give to members in those franchises or with those roles"""
def __i... |
#!/usr/bin/env python
"""
.. py:currentmodule:: FileFormat.Results.test_PhirhozElement
.. moduleauthor:: Hendrix Demers <hendrix.demers@mail.mcgill.ca>
Tests for the module `PhirhozElement`.
"""
# Script information for the file.
__author__ = "Hendrix Demers (hendrix.demers@mail.mcgill.ca)"
__version__ = ""... |
from json import loads
from random import choice
from .base_menti_question import BaseMentiQuestion
QUOTES_PATH = 'quotes.json'
def get_quotes(filename=QUOTES_PATH):
with open(filename) as f:
return f.read()
return ''
class MentiText(BaseMentiQuestion):
max_text_len = 140
needed_attr = []
... |
# -*- coding: utf-8 -*-
from .wiserapi import WiserBaseAPI, _convert_case
class SetPoint:
def __init__(self):
self.time = None
self.temperature = None
class Schedule(WiserBaseAPI):
"""Represnts the /Schedule object in the Restful API"""
def __init__(self, *args, **kwargs):
# Def... |
def lagrange(vec_x, vec_f, x=0):
tam,res = len(vec_x),0
L = [0]*tam
for i in range(tam):
L[i] = 1
for j in range(tam):
if j != i:
L[i] = L[i] * (x - vec_x[j])/(vec_x[i] - vec_x[j])
for k in range (tam):
res = res + vec_f[k]*L[k]
print(res)
x =... |
import os
import pandas as pd
import numpy as np
import shutil
cwd = os.getcwd()
sysname = os.path.basename(cwd)
print(sysname)
if os.path.isdir(cwd+'/lmbl/'):
shutil.rmtree(cwd+'/lmbl/')
os.mkdir('lmbl')
coor = os.path.join(cwd+ '/coordinates/')
lmbl = os.path.join(cwd+ '/lmbl/')
os.chdir(lmbl)
for filename in os.... |
# Copyright 2016 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 or at
# https://developers.google.com/open-source/licenses/bsd
"""Servlet for Content Security Policy violation reporting.
See http://www.html5rocks.com/en/tu... |
import datetime
from pathlib import Path
from typing import Iterator, Any
import pytest
import google_takeout_parser.parse_json as prj
@pytest.fixture(scope="function")
def tmp_path_f(
request: Any, tmp_path_factory: pytest.TempPathFactory
) -> Iterator[Path]:
"""
Create a new tempdir every time this run... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.