content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
#!/usr/bin/env python3
import os
import ssl
from base64 import b64decode, b64encode
from hashlib import sha256
from time import time
from urllib import parse
from hmac import HMAC
from azure.keyvault.secrets import SecretClient
from azure.identity import DefaultAzureCredential
from paho.mqtt import client as mqtt
def... | python |
objConstructors = {'flow_emap.get_key' : {'constructor' : 'FlowIdc',
'type' : 'FlowIdi',
'fields' : ['sp', 'dp', 'sip',
'dip', 'prot']}}
typeConstructors = {'FlowIdc' : 'FlowIdi',
... | python |
from django.conf.urls import patterns, include, url
from django.utils.translation import ugettext_lazy as _
from django.views.generic import TemplateView, RedirectView
from django.core.urlresolvers import reverse_lazy as reverse
from .views import reroute
home = TemplateView.as_view(template_name='home.html')
#: IHM... | python |
from math import ceil
from utils import hrsize
from json import dumps
from . import Sample
class SampleSet:
round = 5
def __init__(self, samples) -> None:
if not (isinstance(samples, list) and all(isinstance(sample, Sample) for sample in samples)):
raise Exception("samples parameter inval... | python |
import pytest
from django.core.exceptions import PermissionDenied
from datahub.admin_report.report import get_report_by_id, get_reports_by_model
from datahub.core.test_utils import create_test_user
pytestmark = pytest.mark.django_db
@pytest.mark.parametrize(
'permission_codenames,expected_result',
(
... | python |
def factorial(n):
if n < 1:
return 1
else:
return n * factorial(n-1)
end
end
print factorial(5) # should output 120
| python |
"""
@author: acfromspace
"""
# Make a function aardvark that, given a string, returns 'aardvark'
# if the string starts with an a. Otherwise, return 'zebra'.
#
# >>>> aardvark("arg")
# aardvark
# >>>> aardvark("Trinket")
# zebra
def aardvark(string):
# Add code here that returns the answer.
if string[0] == ... | python |
import datetime
from django.test import TestCase
from trojsten.contests.models import Competition, Round, Semester, Task
from trojsten.people.models import User, UserProperty, UserPropertyKey
from .model_sanitizers import (
GeneratorFieldSanitizer,
TaskSanitizer,
UserPropertySanitizer,
UserSanitizer,... | python |
#!/usr/bin/python
from __future__ import absolute_import, division, print_function
# Copyright 2019-2021 Fortinet, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the ... | python |
import torch.nn
from gatelfpytorchjson.CustomModule import CustomModule
import sys
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
streamhandler = logging.StreamHandler(stream=sys.stderr)
formatter = logging.Formatter(
'%(asctime)s %(name)-12s %(levelname)-8s %(messag... | python |
class TimeFrame(object):
_string_repr = [[" day", " hour", " min", " sec"],[" d", " h", " m", " s"]]
def __init__(self, seconds = 0.0):
self._seconds = 0.0
self._minutes = 0
self._hours = 0
self._days = 0
self._use_short = int(False)
self._total_seconds = seconds
self.set_with_seconds(seconds)
de... | python |
import subprocess
import sys
from optparse import OptionParser
from django.core.management import LaxOptionParser
from django.core.management.base import BaseCommand, CommandError
from cas_dev_server.management import subprocess_environment
class Command(BaseCommand):
option_list = BaseCommand.option_list[1:]
... | python |
#!/usr/bin/env python3
from dotenv import load_dotenv
load_dotenv()
import os
import logging
import argparse
import pugsql
import json
import pandas as pd
from uuid import UUID
from articleparser.drive import GoogleDrive
logging.basicConfig(level=os.getenv("LOG_LEVEL", "INFO"))
logger = logging.getLogger(__name__)
... | python |
import warnings
from collections import namedtuple, defaultdict
from functools import partial
from typing import Optional, Tuple, List, Callable, Any
import torch
from torch import Tensor
from torch import distributions
from torch import nn
class TemporalDifference(nn.Module):
def __init__(
self,
... | python |
import unittest
from httpretty import HTTPretty
from notification_log import NotificationLog
import requests
import json
class NotificationLogTests(unittest.TestCase):
def setUp(self):
HTTPretty.enable()
self.client = NotificationLog(hostname='test.example.com', protocol='http')
def tearDown... | python |
from unittest.mock import patch
from main import main_handler
import sys
@patch("main.hello_world")
def test_mock_external_incorrect(mock_hello_world):
mock_hello_world.return_value = "Hello Dolly!"
assert main_handler() == "Hello Dolly!"
for path in sys.path:
print(path) | python |
# Character field ID when accessed: 925070100
# ObjectID: 0
# ParentID: 925070100
| python |
y,z,n=[int(input()) for _ in range(3)]
print("The 1-3-sum is",str( y+z*3+n+91))
| python |
import xarray as xr
import numpy as np
import pytest
import pathlib
from xarrayutils.file_handling import (
temp_write_split,
maybe_create_folder,
total_nested_size,
write,
)
@pytest.fixture
def ds():
data = np.random.rand()
time = xr.cftime_range("1850", freq="1AS", periods=12)
ds = xr.Da... | python |
from snovault.elasticsearch.searches.interfaces import SEARCH_CONFIG
from snovault.elasticsearch.searches.configs import search_config
def includeme(config):
config.scan(__name__)
config.registry[SEARCH_CONFIG].add_aliases(ALIASES)
config.registry[SEARCH_CONFIG].add_defaults(DEFAULTS)
@search_config(
... | python |
from bs4 import BeautifulSoup as bs
import requests
import pandas as pd
import random
url = 'https://www.oschina.net/widgets/index_tweet_list'
headers = {
'Accept':
'*/*',
'Accept-Encoding':
'gzip, deflate, br',
'Accept-Language':
'zh-CN,zh;q=0.9',
'Cache-Control':
'no-cache',
'Con... | python |
from datetime import datetime
from testil import Config, eq
from .. import rebuildcase as mod
def test_should_sort_sql_transactions():
def test(sql_form_ids, couch_form_ids, expect):
sql_case = Config(
transactions=[Config(form_id=x, details={}) for x in sql_form_ids]
)
couch... | python |
#!/usr/bin/env python3
import socket, time, sys
from multiprocessing import Process
HOST = ""
PORT = 8001
BUFFER_SIZE = 1024
#TO-DO: get_remote_ip() method
def get_remote_ip(host):
print(f'Getting IP for {host}')
try:
remote_ip = socket.gethostbyname( host )
except socket.gaierror:
prin... | python |
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 26 19:56:37 2017
@author: Simon Stiebellehner
https://github.com/stiebels
This file implements three classifiers:
- XGBoost (Gradient Boosted Trees)
- Random Forest
- AdaBoost (Decision Trees)
These three base classifiers are then ensembled in two ways:
(1) Weighti... | python |
from django.shortcuts import render
from .models import Entry
from rest_framework import generics
from .serializers import EntrySerializer
# Create your views here.
class EntryCreate(generics.ListCreateAPIView):
# Allows creation of a new entry
queryset = Entry.objects.all()
serializer_class = EntrySerial... | python |
#!/usr/bin/python
#import sys
import boto3
import datetime
from Crypto import Random
from Crypto.Cipher import AES
import argparse
import base64
from argparse import Namespace
from keypot_exceptions.KeypotError import KeypotError
#VERSION
keypot_version='Keypot-0.3'
ddb_hash_key_name='env-variable-name'
#Pads the dat... | python |
import os
from dotenv import load_dotenv,find_dotenv
# not used in this stub but often useful for finding various files
project_dir = os.path.join(os.path.dirname(__file__), os.pardir)
load_dotenv(find_dotenv())
| python |
from ..views import add, configure, delete | python |
#!/usr/bin/env python
# -*- coding: iso-8859-15 -*-
# Copyright (c) 2014 The New York Times Company
#
# 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/LIC... | python |
# Author: Xinshuo Weng
# Email: xinshuow@andrew.cmu.edu
# this file includes general help functions for MUGSY data
import init_paths
init_paths.main()
from check import isstring, isscalar
from file_io import get_sheet_service, update_patchs2sheet, get_data_from_sheet, update_row2sheet
# # number of points for all par... | python |
from dataclasses import dataclass
import pytest
import argdcls
from argdcls.config import _parse
@dataclass
class Config:
lr: float
adam: bool = False
def test_load_params():
# "*"
config = argdcls.load(Config, ["@lr=1.0"])
assert config.lr == 1.0
# ""
config = argdcls.load(Config, ["... | python |
#! /usr/bin/env python
""" A simple demo using aubio and pyaudio to play beats in real time
Note you will need to have pyaudio installed: `pip install pyaudio`.
Examples:
./demo_tapthebeat.py ~/Music/track1.ogg
When compiled with ffmpeg/libav, you should be able to open remote streams. For
instance using youtube-d... | python |
'''
Created 03/20/2014
@authors: Yifan Ning
@summary: parse Molecular Formula and drugbank_id from drugbank.xml
then parse MF(Molecular Formula), FDA Preferred Term and UNNI from UNNIs records
match the results from drugbank and results of parse UNNIs records
output terms: FDA Preferred ... | python |
import pandas as pd
from ..util import generate_name
from tickcounter.questionnaire import Encoder
class MultiEncoder(object):
def __init__(self, encoding_rule):
if isinstance(encoding_rule, Encoder):
self.rules = {
encoding_rule.name: encoding_rule
}
elif isinstance(enc... | python |
from rest_framework import serializers
from accounts.models import User
class AccountSerializer(serializers.ModelSerializer):
def validate(self, attrs):
username = attrs.get('username', None)
email = attrs.get('email', None)
password = attrs.get('password', None)
try:
... | python |
import os
import pdb
import random
import sys
import time
from pprint import pformat
import numpy
import torch as tc
import torch.nn as nn
from tqdm import tqdm
from utils.logger import Logger
from utils.random_seeder import set_random_seed
from config import get_config
from training_procedure import Trainer
def mai... | python |
#!/usr/bin/env python2
# coding:utf-8
import base64
import copy
import errno
import getopt
import json
import logging
import os
import sys
import threading
import time
import traceback
import boto3
import oss2
import yaml
from botocore.client import Config
from pykit import jobq
report_state_lock = threading.RLock(... | python |
from __future__ import print_function
import os
import argparse
import numpy as np
from module.retinaface_function_in_numpy import PriorBox_in_numpy
from utils.retinaface_tool_in_numpy import py_cpu_nms_in_numpy, decode_in_numpy, decode_landm_in_numpy
import cv2
from module.retinaface_model_in_numpy import RetinaFace
f... | python |
import logging
def init_logging(log_file, log_level):
logging.getLogger().setLevel(log_level)
log_formatter = logging.Formatter('%(asctime)s %(message)s')
root_logger = logging.getLogger()
if log_file:
file_handler = logging.FileHandler(log_file, encoding='utf8')
file_handler.setFormat... | python |
from django.core.management.base import BaseCommand
from apps.boxes.models import BoxUpload
class Command(BaseCommand):
help = 'Removes expired and completed boxes uploads'
def handle(self, *args, **options):
deleted = BoxUpload.objects.not_active().delete()
self.stdout.write(
sel... | python |
from audhelper.audhelper import __version__, __author__
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="audhelper",
version=__version__,
author=__author__,
author_email="sherkfung@gmail.com",
description="Audio helper functions including visualiz... | python |
import cv2
import numpy as np
img = cv2.imread(r"EDIZ\OPENCV\basin.jpg")
gri = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
temp1 = cv2.imread(r"EDIZ\OPENCV\temp1.jpg",0)
temp2 = cv2.imread(r"EDIZ\OPENCV\temp2.jpg",0)
w,h = temp2.shape[::-1]
res = cv2.matchTemplate(gri,temp2,cv2.TM_CCOEFF_NORMED)
thresh = 0.5
loc = np.where(r... | python |
###
# Copyright 2017 Hewlett Packard Enterprise, Inc. 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 ... | python |
from __future__ import annotations
from discord.ext import commands
__all__ = ("HierarchyFail",)
class HierarchyFail(commands.CheckFailure):
...
| python |
import numpy as np
import pandas as pd
import os
import scipy.io as spio
import math
from random import sample
class ProcessData:
def __init__(self, data_set_directory, columns_to_use):
self.directory = data_set_directory
self.selected_columns = columns_to_use
self.datasets = []
sel... | python |
# coding=utf-8
""" Demo app, to show OpenCV video and PySide2 widgets together."""
import sys
from PySide2.QtWidgets import QApplication
from sksurgerycore.configuration.configuration_manager import \
ConfigurationManager
from sksurgerybard.widgets.bard_overlay_app import BARDOverlayApp
def run_demo(config_... | python |
# coding: utf-8
import sys
k_bit_rate_num_bits = [ 0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 32 ]
k_highest_bit_rate = len(k_bit_rate_num_bits) - 1
k_lowest_bit_rate = 1
k_num_bit_rates = len(k_bit_rate_num_bits)
k_invalid_bit_rate = 255
# This code assumes that rotations, translations, and sc... | python |
#!/usr/bin/python
"""
Date utilities to do fast datetime parsing.
Copyright (C) 2013 Byron Platt
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) ... | python |
'''OpenGL extension SGIS.texture_filter4
Overview (from the spec)
This extension allows 1D and 2D textures to be filtered using an
application-defined, four sample per dimension filter. (In addition to
the NEAREST and LINEAR filters defined in the original GL Specification.)
Such filtering results in higher ima... | python |
from support import print_func
import using_name
print_func("Jack")
| python |
"""Various utilities used throughout the code.
Here go various utilities that don't belong directly in any class,
photometry utils module nor or SED model module.
"""
import os
import pickle
import random
import time
from contextlib import closing
import numpy as np
from scipy.special import erf
from scipy.stats impo... | python |
import queue
import cards
import random
#create card decks
class constructBoard:
def __init__(self, lowLevelCards = queue.Queue(), midLevelCards = queue.Queue(), highLevelCards = queue.Queue()):
self.lowlevelcards = lowLevelCards
self.midlevelcards = midLevelCards
self.highlevelcar... | python |
from pytest import raises
class IndexedPropertyMapper(object):
def __init__(self, desc, instance):
self.desc = desc
self.instance = instance
def __getitem__(self, item):
return self.desc.fget(self.instance, item)
def __setitem__(self, item, value):
# hmm. is this order of ... | python |
import asyncio
import shutil
from collections import namedtuple
from concurrent.futures.thread import ThreadPoolExecutor
from datetime import datetime, timedelta, timezone
from shlex import split as lex
from subprocess import DEVNULL, Popen
import bottle as bt
import httpx
import peewee as pw
import toml
from waitress... | python |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui/ForgottenPassword2.ui'
#
# Created by: PyQt5 UI code generator 5.15.6
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 impor... | python |
# 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 u... | python |
# -*- coding: utf-8 -*-
import re
from pybuilder.core import init
from pybuilder.core import task
from pybuilder.core import depends
from pybuilder.errors import BuildFailedException
from pybuilder.pluginhelper.external_command import ExternalCommandBuilder
from pybuilder.utils import assert_can_execute
@init
def i... | python |
"""Class hierarchy for base gates."""
import math
from dataclasses import dataclass
from functools import singledispatch, reduce
from numbers import Number
from typing import Tuple, Union, Callable, Dict, Optional, Iterable, Any, List
import sympy
from typing_extensions import Protocol
import numpy as np
from ...util... | python |
import pygame, sys
from pygame.locals import *
import random
pygame.init() #initializing the pygame library
#creating sample questions
data = [
{
'question': 'Who is the president of America?',
'right-answer': 'Barack Obama',
'option1' : 'George Washington',
'option2' : 'Paul Kagame',
'option3' : 'Barack O... | python |
# example of setting up, running, and graphing landau damping in 3D
import os
import py_platypus as plat
from py_platypus.utils.params import Parameters as Parameters
from py_platypus.vis.plotter import Plotter as Plotter
if __name__ == "__main__":
# override default parameters
params = {
"dimen... | python |
#from app import Util
import aiml
import sys
def formatOutPut(text):
text = text.replace('\\t','\t')
text = text.replace('\\n','\n')
return text
def stripCommand(text):
if(text[0] == '/'):
return text[1:]
return text
def main():
#create and configurate bot knowledbase
ctfbot = ... | python |
from trackstats.models import Domain, Metric
# Domains
Domain.objects.INVESTMENT = Domain.objects.register(
ref='investment',
name='investment'
)
# Metrics, these are associated with a domain
Metric.objects.INVESTMENT_COUNT = Metric.objects.register(
domain=Domain.objects.INVESTMENT,
ref='investment_... | python |
import logging
import json
import transaction
from pyramid.view import view_config
from pyramid.request import Response
__author__ = 'max'
log = logging.getLogger(__name__)
MODULE_DIR = "newsbomb_recommends.views"
@view_config(route_name='generic', renderer='json')
def api(request):
try:
module = req... | python |
"""
Define the abstract Game class for providing a structure/ interface for agent environments.
Notes:
- Base implementation done.
- Documentation 15/11/2020
"""
from abc import ABC, abstractmethod
import typing
import numpy as np
from utils.game_utils import GameState
class Game(ABC):
"""
This class spe... | python |
x="There are %d types of people." % 10
binary="binary"
do_not="dont't"
y="Those who know %s and those who %s." % (binary,do_not)
print(x)
print(y)
print("I said: %r" % x)
print("I also said: '%s'." % y)
hilarious=False
joke_evaluation="Isn't that joke so funny?! %r"
print(joke_evaluation % hilarious)
w="This is t... | python |
# -*- encoding: utf-8 -*-
from bs4 import Tag
from datetime import datetime
from dateutil.parser import parse
from dateutil.relativedelta import relativedelta
from scrapers.helpers import jsonify_seminars
#########################################################
# This part will seriously depend on the structure of ... | python |
#============================== IBM Code Challenge =============================
# mat_gui.py
#
# Creates GUI for user to interact with
#
# Description:
# This generates a GUI that allows the user to enter two matrices, select
# a mathematical operation, and displays the operation result to the user.
# The ... | python |
"""
Uses docspec to parse docstrings to markdown.
Intended for use with static site generators where further linting / linking / styling is done downstream.
Loosely based on Numpy-style docstrings.
Automatically infers types from signature typehints. Explicitly documented types are NOT supported in docstrings.
"""
i... | python |
from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from django.urls import reverse_lazy
from status import models, forms
from django.contrib.auth.decorators import login_required
# Create your views here.
@login_required
def add_comment(request,pk):
post = get_obj... | python |
def countingSort(arr):
counter = [0]*100 # as per the constraint that arr[i] < 100
for num in arr:
counter[num] += 1
sorted = []
for num, cnt in enumerate(counter):
sorted += [num]*cnt
return sorted
| python |
#
# relu paddle model generator
#
import numpy as np
from save_model import saveModel
import sys
def relu(name: str, x):
import paddle as pdpd
pdpd.enable_static()
node_x = pdpd.static.data(name='x', shape=x.shape, dtype='float32')
out = pdpd.nn.functional.relu(node_x)
cpu = pdpd.static.cpu_plac... | python |
import os
import os.path
from dataclasses import dataclass
from os import path
import sys
from typing import List
import requests
from bs4 import BeautifulSoup
import re
import win32console # needs pywin32
import time
_stdin = win32console.GetStdHandle(win32console.STD_INPUT_HANDLE)
def input_def(prompt, default=''... | python |
import numpy as np
def get_box_from_point(x,y,kernel,pad,stride):
kernel_x = kernel[0]
kernel_y = kernel[1]
pad_x = pad[0]
pad_y = pad[1]
stride_x = stride[0]
stride_y = stride[1]
x_min = (x - 1) * stride_x + 1 - pad_x
x_max = (x - 1) * stride_x - pad_x + kernel_x
y_min = (y - 1) *... | python |
from django.urls import path
from . import views
urlpatterns = [
path("", views.OrderDetailsView.as_view()),
path("<uuid:order_id>", views.OrderDetailsView.as_view()),
path("status/<str:order_status_value>", views.OrderStatusView.as_view()),
path("incoming", views.IncomingOrders.as_view()),
path("s... | python |
# Copyright (c) 2021 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 applic... | python |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import hungrybotlib as l
from random import choice
import config as cfg
l.cacheMenus(cfg.menu_file, cfg.menu_url, cfg.days)
with open("counter", "r") as f:
count = int(f.read())
text = ["Une nouvelle semaine de bouffe !", "Et voila, je viens de mettre à jour les m... | python |
"""Output an NML file cataloging a set of audio files.
NML is an XML-based file format used by Traktor. This code generates
NML version 11, which is used by Traktor Pro.
"""
import time
import xml.sax.saxutils
from chirp.common import timestamp
from chirp.common import unicode_util
from chirp.library import artists... | python |
input = open('input/input12.txt').readlines()
plants = []
ZERO = 5
BASE_GEN_COUNT = 0
FINAL_GEN_COUNT = 50000000000
will_grow = set()
wont_grow = set()
for line in input:
line = line.strip()
if line.startswith('initial'):
pots = list(line.split(' ')[2])
BASE_GEN_COUNT = len(pots)
plants ... | python |
SOCIAL_AUTH_GITHUB_KEY = '0ec5adf60f9d0db84213'
SOCIAL_AUTH_GITHUB_SECRET = 'c4b6cd88aac6b4515c5b396be2727b21ee54725e'
SOCIAL_AUTH_LOGIN_URL = '/login'
SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/'
SOCIAL_AUTH_LOGIN_ERROR_URL = '/login-error/'
SESSION_COOKIE_DOMAIN = '.localhost.be'
USE_X_FORWARDED_HOST = True
S... | python |
from functools import lru_cache
import os
from time import time
import json
from io import StringIO
import markdown
import jwt
import requests
import github
import datetime
import logging
from time import sleep
from ruamel.yaml import YAML
yaml = YAML()
ZOOM_API = "https://api.zoom.us/v2/"
SPEAKERS_CORNER_USER_ID = ... | python |
# Clase 24. Curso Píldoras Informáticas.
# Control de Flujo. POO1.
# Clase de Teoría.
# Lenguajes orientados a objetos: C++, Java, VisualNet...
# Atributos/Propiedades: elementos que definen las clases y objetos.
# Ventajas POO:
# Se pueden establecer Módulos.
# Código muy reciclable (esto con Fo... | python |
#coding=utf-8
import tensorflow as tf
import wmodule
import basic_tftools as btf
import wml_tfutils as wmlt
from object_detection2.datadef import EncodedData
import tfop
import functools
from object_detection2.datadef import *
import numpy as np
import wnn
import wsummary
from .build import HEAD_OUTPUTS
import object_d... | python |
from sqlalchemy import Integer, Text, DateTime, func, Boolean, text
from models.database_models import Base, Column
class Comment(Base):
__tablename__ = "comment"
id = Column(Integer, primary_key=True, )
user_id = Column(Integer, nullable=False, comment="评论用户的 ID")
post_id = Column(Integer, nullable... | python |
#!/usr/bin/env python
# Copyright (C) 2009 Chia-I Wu <olv@0xlab.org>
# All Rights Reserved.
#
# This is based on extension_helper.py by Ian Romanick.
#
# 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... | python |
# -*- coding: utf-8 -*-
# see LICENSE.rst
# ----------------------------------------------------------------------------
#
# TITLE : Code for the Examples
# AUTHOR : Nathaniel Starkman
# PROJECT : TrackStream
#
# ----------------------------------------------------------------------------
"""Examples Code."""
__a... | python |
def keep_evens(nums):
new_seq = filter(lambda num: num % 2 == 0, nums)
return list(new_seq)
print(keep_evens([3, 4, 6, 7, 0, 1]))
# Saída [4, 6, 0]
'''
1. Write code to assign to the variable filter_testing all the elements in lst_check that have a w in them using filter.
'''
lst_check = ['plums', 'watermelon... | python |
from django.dispatch import Signal
signup_complete = Signal(providing_args=["user",])
activation_complete = Signal(providing_args=["user",])
confirmation_complete = Signal(providing_args=["user","old_email"])
password_complete = Signal(providing_args=["user",])
order_complete = Signal(providing_args=["user",])
email_c... | python |
#!/usr/bin/env python3
from setuptools import setup
setup(
name='lilist',
version='0.1.0',
description='A linear interpolation list class',
url='http://github.com/MatthewScholefield/lilist',
author='Matthew Scholefield',
author_email='matthew331199@gmail.com',
license='MIT',
py_modules... | python |
from unittest import TestCase
import json
import attr
from marshmallow_helpers import RegisteredEnum, attr_with_schema
def enum_to_schema(enum_cls):
@attr_with_schema(register_as_scheme=True, strict=True)
@attr.s(auto_attribs=True)
class MyEnum:
enum: enum_cls
return MyEnum.schema
def enum... | python |
from flask import Flask
from flask_cors import CORS
import json, sys, os, base64
app = Flask(__name__)
CORS(app)
import logging
logging.getLogger("werkzeug").setLevel(logging.ERROR)
@app.route("/set_contest/<contestname>/<userhash>")
def set_contest(contestname, userhash):
print(base64.b64decode(contestname.repl... | python |
from operator import mul
numstr = '73167176531330624919225119674426574742355349194934\
96983520312774506326239578318016984801869478851843\
85861560789112949495459501737958331952853208805511\
12540698747158523863050715693290963295227443043557\
66896648950445244523161731856403098711121722383113\
622298934233803081353362... | python |
import asyncio
import unittest.mock
import pytest
START = object()
END = object()
RETVAL = object()
@pytest.fixture
def mock():
return unittest.mock.Mock(return_value=RETVAL)
@pytest.fixture
async def async_fixture(mock):
return await asyncio.sleep(0.1, result=mock(START))
@pytest.mark.asyncio
async def... | python |
r = float(input('Quanto dinheiro você tem na carteira?: R$'))
print('Com R${:.2f} você pode comprar US${:.2f}'.format(r, (r/3.27)))
| python |
"""
XMLAction module.
"""
from pineboolib.core.utils import logging
import os.path
from pineboolib.core.utils.struct import ActionStruct
from .utils.path import _path, coalesce_path
from typing import Optional, Any, Union, TYPE_CHECKING
if TYPE_CHECKING:
from pineboolib.fllegacy.flaction import FLAction # noqa:... | python |
from datetime import datetime
from pathlib import Path
import unittest
import pandas as pd
import numpy as np
import vak
import article.syntax
HERE = Path(__file__).parent
DATA_DIR = HERE.joinpath('test_data')
class TestSyntax(unittest.TestCase):
def test_date_from_cbin_filename(self):
CBIN_FILENAME = ... | python |
"""
The ``fine_tune.py`` file is used to continue training (or `fine-tune`) a model on a `different
dataset` than the one it was originally trained on. It requires a saved model archive file, a path
to the data you will continue training with, and a directory in which to write the results.
. code-block:: bash
$ pyt... | python |
#!/usr/bin/python3
from brownie import HuskyTokenDeployer, accounts, HuskyToken, HuskyTokenMinter, Wei
def main():
provost = accounts.load('husky')
admin = provost
is_live = False
if provost.balance() == 0:
accounts[0].transfer(provost, Wei('1 ether'))
husky_token = HuskyToken.deploy("Husky... | python |
from pprint import pprint
import gym
env = gym.make('ChessVsRandomBot-v0')
def available_moves():
state = env.state
moves_p1 = env.get_possible_moves(state, 1)
moves_p2 = env.get_possible_moves(state, -1)
pprint(moves_p1)
pprint(moves_p2)
# no actions left -> resign
if len(moves_p1) == ... | python |
def is_valid(phrase):
words = phrase.split()
word_letters = list(map("".join, map(sorted, words)))
return len(set(word_letters)) == len(words)
passphrases = open("day4.txt").readlines()
valid_phrases = list(filter(is_valid, passphrases))
print('Valid Passphrases:', len(valid_phrases)) # = 231
| python |
import os
import datetime
import argparse
import numpy
import networks
import torch
modelnames = networks.__all__
# import datasets
datasetNames = ('Vimeo_90K_interp') #datasets.__all__
parser = argparse.ArgumentParser(description='DAIN')
parser.add_argument('--debug',action = 'store_true', help='Enable debug mode'... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.