content stringlengths 5 1.05M |
|---|
#ALGORITMO CRIADO COM O OBJETIVO DE SIMULAR UM JOGO DA VELHA PARA PRÁTICA DOS CONHECIMENTOS ADQUIRIDOS, O ÚSUARIO PODE
#JOGAR ELE COM UM AMIGO OU CONTRA O COMPUTADOR
from time import sleep
from random import choice
def cria_tabuleiro():
"""Função utilizada para montar a estrutura do tabuleiro
sem parâmetros... |
from .elastic_search_indexing import ESIndexingUtils
from .elastic_search_querying import ESQueryingUtils
from .utils import Utils
|
import os
import environ
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ENV = environ.Env()
ENV.read_env(os.path.join(BASE_DIR, '.env'))
RUNTIME_DIR = ENV.str('RUNTIME_DIR', os.path.join(BASE_DIR, 'runtime'))
# SECURITY... |
funcWithLongName(x=[
],
y=42)
|
from datetime import date
from datetime import timedelta
from uuid import uuid1
import pytest
from fastapi.testclient import TestClient
from todo.backend import schema
from todo.backend.endpoints import router
from todo.backend.schema import ToDo
from todo.backend.schema import Uuid
@pytest.fixture(scope="module", ... |
from __future__ import print_function
from distutils.command.install import install
from setuptools import setup, find_packages, Command
from setuptools.command.sdist import sdist
from setuptools.command.build_py import build_py
from setuptools.command.egg_info import egg_info
from setuptools.command.develop import de... |
class TestResult:
def __init__(self):
self.runCount = 0
self.errorCount = 0
def testStarted(self):
self.runCount = self.runCount + 1
def testFailed(self):
self.errorCount = self.errorCount + 1
def summary(self):
return "%d run, %d failed" % (self.runCount, self.er... |
#!/usr/local/python/3.3.2/bin/python3.3
#script-version: 1
import requests
## Update API Gateway URL
url = 'https://{xxxxxx}.execute-api.us-east-1.amazonaws.com/prod/'
def main():
#SEND API Requests
while (True):
print("\n\n Iterating sending requests...+++++")
response = requests.get(url)
re... |
from django.db import models
import datetime as dt
# Create your models here.
class Location(models.Model):
'''
Location model
'''
name = models.CharField(max_length =30)
def __str__(self):
return self.name
def save_location(self):
self.save()
def delete_location(self):
... |
import gym
import os
import gym.envs.mujoco
custom_envs = {
# Pusher modifications
"PusherMovingGoal-v1":
dict(path='gym_extensions.continuous.mujoco.modified_arm:PusherMovingGoalEnv',
max_episode_steps=100,
reward_threshold=0.0,
kwargs=dict()),
# Pusher modif... |
import traceback
from cryptography.fernet import InvalidToken
from fastapi import APIRouter, BackgroundTasks, HTTPException, status
from fastapi.encoders import jsonable_encoder
from fastapi.logger import logger
from fastapi.param_functions import Body, Depends
from fastapi.responses import JSONResponse
from api.secu... |
import os
import shutil
import sys
import time
import cv2
import face_recognition
import numpy as np
import label_image
def batch_job(frames, images, positions, face_counts, batch_size):
batch_of_face_locations = face_recognition.batch_face_locations(frames, number_of_times_to_upsample=0,
... |
import os
import time
try:
from Queue import Empty, Full
except ImportError:
from queue import Empty, Full
from ms_deisotope.data_source import ProcessedScan
from glycan_profiling.task import TaskExecutionSequence
from glycan_profiling.chromatogram_tree import Unmodified
from .search_space import (
Parse... |
from typing import Any, Callable, Optional, Union
from typing_extensions import Literal
from mashumaro.types import SerializationStrategy
NamedTupleDeserializationEngine = Literal["as_dict", "as_list"]
DateTimeDeserializationEngine = Literal["ciso8601", "pendulum"]
AnyDeserializationEngine = Literal[
NamedTupleD... |
# Generated by Django 3.0.2 on 2020-02-12 23:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('banco_proyectos', '0006_remove_datosresidente_usuario'),
]
operations = [
migrations.AlterField(
model_name='datosresidente',
... |
import numpy as np
from math import *
def g(x):
result = exp((-x**2)/2)/sqrt(2*pi)
return result
def f(y):
result = (g((b-a)*y+a)-c)/(d-c)
return result
n = 10**5
X = np.random.uniform(0,1,n)
Y = np.random.uniform(0,1,n)
a = 2
b = 5
c = g(5)
d = g(2)
count = 0
J0 = (a-b)*(c-d)
J1 ... |
###############################################################################
#
# Test cases for xlsxwriter.lua.
#
# Copyright 2014-2015, John McNamara, jmcnamara@cpan.org
#
import base_test_class
class TestCompareXLSXFiles(base_test_class.XLSXBaseTest):
"""
Test file created with xlsxwriter.lua against a f... |
# -*- coding: utf-8 -*-
# Copyright 2019 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
# -*- coding: utf-8 -*-
"""
Spider Download Data from https://eogdata.mines.edu/nighttime_light/monthly/v10/2021/202106/vcmcfg/
Data: Monthly Nighttime Light
Created on Tue Nov 30 11:07:40 2021
@author: M.L.
"""
from selenium.webdriver.support.ui import Select
import time
from selenium import webdriver
from seleni... |
# from django.shortcuts import render
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from reports.models import Report
from reports.serializers import ReportSerializer
from rest_fr... |
"""
Bot actions
"""
import random
UP, DOWN, LEFT, RIGHT = [[-1, 0], [1, 0], [0, -1], [0, 1]]
directions = {
"[-1, 0]" : "up",
"[1, 0]" : "down",
"[0, -1]" : "left",
"[0, 1]" : "right"
}
class Iterator:
"""
Fifo Queue
"""
def __init__(self):
self.fields = []
def isEmpty(se... |
import aiogram
from aiogram.dispatcher import FSMContext
from aiogram.types import CallbackQuery
from loader import dp
from markups.inline.calendar import InlineCalendar, calendar_cb
from states import Menus
@dp.callback_query_handler(calendar_cb.filter(), state=Menus.calendar)
async def calendar_selection(callback_... |
"""
=======
License
=======
Copyright (c) 2015 Thomas Lehmann
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 u... |
import unittest
from smartobjects.api_manager import APIManager
from smartobjects.ingestion.objects import ObjectsService
from tests.mocks.local_api_server import LocalApiServer
class TestObjectsService(unittest.TestCase):
"""
https://smartobjects.mnubo.com/documentation/api_ingestion.html#objects
"""
... |
import os
import unittest
import numpy
from sklearn.pipeline import Pipeline
from molml.fragment import FragmentMap
from molml.molecule import Connectivity
from .constants import METHANE_NUMBERS, MID_NUMBERS
from .constants import DATA_PATH, METHANE_PATH, MID_PATH
ALL = (METHANE_PATH, MID_PATH)
ALL_NUMS = [METHANE... |
import os
import sys
import time
import socket
import random
from chord import *
nnodes = int(sys.argv[1])
print "Creating chord network with : %s nodes" % nnodes
# create ports
ports_list = [random.randrange(10000, 60000) for x in range(nnodes)]
print "Ports list : %s" % ports_list
# create addresses
address_list = ... |
# Copyright 2013-2018 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)
from spack import *
class RInteractivedisplaybase(RPackage):
"""The interactiveDisplayBase package contains the the ... |
import datetime
import discord
from discord.ext import commands
class Avatar(commands.Cog):
def __innit__(self, bot):
self.bot = bot
@commands.command()
@commands.guild_only()
async def avatar(self, ctx, member: discord.Member=None):
if member == None:
member = ctx... |
#!/usr/bin/env python
# encoding=utf-8
class Res:
def __init__(self, _type, _name):
self._type = _type
self._name = _name
pass
def from_text(self, text):
# anim.close_enter_left_to_right
str_list = text.split('.')
if len(str_list) == 2:
self._type =... |
#!/usr/bin/env python3
# Copyright 2019 The Kadet Authors
# SPDX-FileCopyrightText: 2021 The Kadet Authors <kapitan-admins@googlegroups.com>
#
# SPDX-License-Identifier: Apache-2.0
"""kadet tests."""
import tempfile
import unittest
from kadet import BaseObj, Dict
class KadetTestObj(BaseObj):
"""KadetTestObj."... |
# Generated by Django 3.2.6 on 2021-08-23 12:32
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('evaluations', '0009_alter_criterion_unique_together'),
]
operations = [
migrations.AddField(
mo... |
# Generated by Django 2.0 on 2018-06-05 08:42
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('voting', '0003_auto_20180605_0842'),
('mixnet', '0003_mixnet_auth_position'),
]
operations = [
migrat... |
import os
from django.contrib import messages
from django.shortcuts import render, redirect
from django.conf import settings
from django.http import HttpResponse
from django.contrib.auth.models import User, auth
from random import randint
from . import database
from welcome.models import creds,PageView
import json
impo... |
# Step 3: takes location messages and only takes those with keywords indicating they are useful to their location.
from cliff.api import Cliff
import pandas as pd
keywords = [' area ', ' folks in ', 'a bit north ', 'a chapter in ', 'a group here in ', 'a house in ', 'a meet in ', 'a trip to ', 'active chapter in ', '... |
"""Genetic Algorithm.
"""
import copy
import numpy as np
import opytimizer.math.distribution as d
import opytimizer.math.general as g
import opytimizer.math.random as r
import opytimizer.utils.constant as c
import opytimizer.utils.exception as e
import opytimizer.utils.logging as l
from opytimizer.core import Optimi... |
from ray.util.sgd.v2 import * # noqa: F401, F403
|
# -*- coding: utf-8 -*
import face_model_video
import argparse
import cv2
import sys
import math
import os
import numpy as np
parser = argparse.ArgumentParser(description='face model test')
# general
parser.add_argument('--image-size', default='112,112', help='')
parser.add_argument('--model', default='../models/glink... |
from django.shortcuts import render_to_response, redirect
from django.core.urlresolvers import reverse
from django.template import RequestContext
from django.contrib.sites.models import Site
def welcome(request):
"""
Handles site Welcome redirects behavior.
It handles last opened page in session.
And i... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('vendors', '0020_auto_20150217_1613'),
]
operations = [
migrations.RenameField(
model_name='vendor',
old_name... |
import sys
# Задача: Вычислите расстояние редактирования двух данных непустых строк длины
# не более 10^2, содержащих строчные буквы латинского алфавита.
# Input
# short
# ports
# Output
# 3
def get_editing_distance(first: str, second: str) -> int:
if len(first) == 0 or len(second) == 0:
return max(le... |
from __future__ import unicode_literals
import boto
import pytest
import sure # noqa
from boto.exception import EC2ResponseError
from moto import mock_ec2_deprecated
@mock_ec2_deprecated
def test_create_vpn_connections():
conn = boto.connect_vpc("the_key", "the_secret")
vpn_connection = conn.create_vpn_conn... |
# # write your function here
# def population_density(population,land_area):
# return population/land_area
# # test cases for your function
# test1 = population_density(10, 1)
# expected_result1 = 10
# print("expected result: {}, actual result: {}".format(expected_result1, test1))
# test2 = population_density(864... |
"""
This submodule has functions that control opening, closing, rendering, and otherwise managing windows.
It also has commands for scheduling pauses and scheduling interval functions.
"""
import gc
import time
import pyglet
import pyglet.gl as gl
import numpy as np
from numbers import Number
from typing import Cal... |
from math import tan
"""
Funcionamento
O algoritmo implementado funciona da seguinte maneira
É necessário definir a função, os intervalos inferioes e superiores e por fim
quantidade de iterações
a = limite inferior
b = limite superior
n = iterações
f(x) = função
"""
def calcula_integral(... |
""" Utilities for time series and dates. """
import pandas as pd
import calendar
import numpy as np
from scipy import signal
def ar1(arr):
''' Fits AR(1) model.
:param arr: array-like, shape(M,)
:returns A dictionary with slope and intercept of the model.
'''
slope, intercept = np.polyfit(arr[:-... |
from typing import List, Optional, Union, Dict
import numpy as np
import pandas as pd
from feature_engine.base_transformers import BaseNumericalTransformer
from feature_engine.variable_manipulation import _check_input_parameter_variables
class CyclicalTransformer(BaseNumericalTransformer):
"""
The CyclicalTr... |
import time
from intefraces.i_game_state import IGameState
from intefraces.i_player import IPlayer
from utils.average_meter import AverageMeter
from utils.loaders import Game
from utils.loggers import evaluation as eval_log
from utils.progress import progress_bar, sec_to_time
class Evaluate:
def __init__(self, ... |
if __name__ == "__main__":
def solution(s, k):
if len(s) < k:
return "false"
lookup = {}
for i in range(len(s)):
if s[i] not in lookup:
lookup[s[i]] = 1
else:
lookup[s[i]] += 1
number = 0
f... |
#!/usr/bin/env python
#
# Copyright 2007 Google 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 law o... |
#!/usr/bin/env python3
# generate 'mandel_image.vti' first !
import vtk
# source
reader = vtk.vtkXMLImageDataReader()
reader.SetFileName('mandel_image.vti')
reader.Update()
# Set active scalars
pointData = reader.GetOutput().GetPointData()
pointData.SetActiveScalars('N')
# mapper
mapper = vtk.vtkDataSetMapper()
map... |
from .treeliker import TreeLiker
|
from django.urls import path
from django.views.generic import TemplateView
from args_app.views import AppleArgsDataTableView
app_name = 'args_app'
urlpatterns = [
path('', TemplateView.as_view(template_name='args_app/index.html')),
path('data/', AppleArgsDataTableView.as_view()),
]
|
# django imports
from django.http import Http404
from django.shortcuts import render_to_response
from django.template import RequestContext
# lfs imports
from lfs.caching.utils import lfs_get_object_or_404
from lfs.page.models import Page
def page_view(request, slug, template_name="lfs/page/page.html"):
... |
# adapter trim with reads downsampling
import sys,os
from random import sample
def reverse_complement(seq):
complement = {'A':'T', 'T':'A', 'C':'G', 'G':'C', 'a':'t', 't':'a', 'c':'g', 'g':'c'}
bases = list(seq)
bases = [complement[base] for base in bases]
return ''.join(bases[::-1])
def clean_fastq_wPrimer(inp... |
from .pyvcroid2 import VcRoid2, TtsEventType
__version__ = "0.21"
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#------------------------------------------------------
# @ File : sampler.py
# @ Description:
# @ Author : Alex Chung
# @ Contact : yonganzhong@outlook.com
# @ License : Copyright (c) 2017-2018
# @ Time : 2020/11/18 下午4:11
# @ Software : PyCharm
#... |
# answer: 1898341
input = 344
point0 = 0
point1 = 5935
skip = input
size = 5936
pos = 1
for i in range(5936, 50000000):
pos = pos + skip + 1
if pos > size:
pos = pos - size
size += 1
if pos == 1:
point1 = i
print "*", point1
# print pos, point1, size
'''
* 10545
* 41867
* ... |
from . import admin
from flask import render_template, flash, current_app
from Server.app.measurements_redis_adapter import ComputerMeasurementsRedisAdapter as redis_adapter
@admin.route("/manage")
def manage():
all_host_names = redis_adapter.get_all_monitored_hostnames()
newest_measurement_from = [redis_ada... |
try:
import cartpolewrap
except ImportError:
raise ImportError('This task needs to be compiled. Please use the script: cartpolecompile.py')
from pybrain.rl.environments.cartpole.fast_version.cartpoleenv import FastCartPoleTask |
from aiovectortiler.config_handler import Recipe, Layer, Query
def test_basic_recipe():
recipe = Recipe({
"name": "myrecipe",
"layers": [{
"name": "mylayer",
"queries": [{
"sql": "SELECT * FROM table"
}]
}]
})
assert isinstance(re... |
# <<BEGIN-copyright>>
# Copyright 2021, Lawrence Livermore National Security, LLC.
# See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: BSD-3-Clause
# <<END-copyright>>
"""
This module contains the class for the suite chemicalElement.
"""
from .. import misc as miscModule
from ..atomic impor... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""."""
import functools
from pyrigate.user_settings import settings
def configurable(setting):
"""Return a function that only gets called if a setting is enabled."""
def decorator(func):
@functools.wraps(func)
def _configurable(*args, **kwargs):... |
#coding=utf-8
import tornado
import tornado.httpserver
import tornado.ioloop
import tornado.web
import uuid
import json
from sqlalchemy.orm import scoped_session, sessionmaker
from utils.db import engine
from utils.login import login, LoginStatus
from utils.score import get_score
from utils.syllabus import get_syllab... |
from pyopp import (
cSimpleModule,
cMessage,
cQueue,
EV,
simTime,
SIMTIME_ZERO,
)
class L2Queue(cSimpleModule):
'''
Point-to-point interface module. While one frame is transmitted,
additional frames get queued up; see NED file for more info.
'''
def __init__(self):
... |
import torch
import torch.nn as nn
__all__ = ['mymodel2']
def change_dir(grad):
return -1 * grad
def custom(grad, model_output,labels_):
i = 0
for col in labels_:
label = col.data
max_ouput = torch.max(model_output[i,label,:,:])
norm_output = model_output[i,label,:,:]/max_ouput
mask = norm_ou... |
from django.core.urlresolvers import reverse
from django.test import TestCase
from rest_framework.test import APIClient
# from rest_framework.test import force_authenticate
# from ..serializers import FileSerializer
from .test_models import UserFactory
class TestUserView(TestCase):
def setUp(self):
sel... |
# -*- coding: utf-8 -*-
'''
Time decay model:
If selected:
p = (1-α)p + α
If not:
p = (1-α)p
Where p is the selection probability, and α is the degree of weight decrease.
The result of this is that the nth most recent selection will have a weight of
(1-α)^n. Using a coefficient value of 0.05 as an example, the 10th mo... |
#
# 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... |
import os
import re
from collections import namedtuple
from datetime import datetime
from functools import reduce
from operator import add
from inspect import getfullargspec
from types import MethodType, BuiltinMethodType
from js2py import eval_js
from js_date import js_date
class CommandParserModel:
def __init_... |
#! /usr/bin/python3
import os
import re
import shlex
import sys
# export MAVEN_OPTS to conditionally set -Dsonar.projectBranch option
# based on CI_COMMIT_REF_NAME value
# dev, master, mt-*: not set
# other branches: set to branch/tag name
branch = os.environ.get("CI_COMMIT_REF_NAME", None)
maven_opts = shlex.split(... |
import os
from celery import Celery
from flask import Flask, jsonify
from wordstats.blueprints.invalid_usage import InvalidUsage
CELERY_TASK_LIST = [
'wordstats.blueprints.tasks',
]
def create_app(test_config=None):
"""Create and configure an instance of the Flask application."""
app = Flask(__name__, ... |
from .imported.treelib import Tree
from .imported.treelib.exceptions import NodeIDAbsentError
from typing import Optional
import shlex
import asyncio
import inspect
class Commander:
def __init__(self, caller="", auto_node:bool=False, use_asyncio=False, loop=None):
self.caller = caller
self.tree = ... |
# Generated by Django 2.1.3 on 2018-11-09 17:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('room', '0002_auto_20181109_1709'),
]
operations = [
migrations.AlterField(
model_name='room',
name='status',
... |
#
# Created by pSkateboard (Lee_Dohyeon)
#
import re
import requests
import bs4
headers = {}
session = requests.session()
def setup(user_agent, cookie):
global headers
headers = {
"user-agent": user_agent,
"cookie": cookie
}
session.headers = headers
def get_ca... |
# %% [markdown]
# # Imports
import json
import os
import pickle
import warnings
from operator import itemgetter
from pathlib import Path
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import pandas as pd
import seaborn as sns
from joblib import Parallel, delayed
from joblib.parallel import Pa... |
import os
from ctypes import windll
from win32con import *
from PIL import Image
import xkcd
import random
# This function is by AKM licensed under the BSD license
#
def setWallPaperFromBmp( pathToBmp ):
result = windll.user32.SystemParametersInfoA(
SPI_SETDESKWALLPAPER, 0,
pathToBmp,
SPIF... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/6/27 18:22
# @Author : Tom_tao
# @Site :
# @File : views.py
# @Software: PyCharm
from datetime import datetime
from django.shortcuts import render
def greet(word):
return "hello world" % word
def index(request):
context = {
'greet':greet
... |
import os
from conans.errors import ConanException
import logging
from conans.util.env_reader import get_env
from conans.util.files import save, load
from six.moves.configparser import ConfigParser, NoSectionError
from conans.model.values import Values
import urllib
MIN_SERVER_COMPATIBLE_VERSION = '0.6.0'
default_set... |
import pandas as pd
import itertools
from scipy.stats.stats import pearsonr
import numpy as np
#raw_data = {'patient': [1,np.nan, 1, 2, 2],
#'obs': [1, 2, 3, np.nan, 2],
#'treatment': [0.3, 1.4, 0.5, 1.2, 0.9],
#'score': ['strong', 'weak', 'normal', 'weak', 'strong'],
#'city': ['ML', 'A... |
from south.db import db
from django.db import models
from webapp.librelist.models import *
class Migration:
def forwards(self, orm):
# Adding model 'Subscription'
db.create_table('librelist_subscription', (
('subscriber_name', models.CharField(max_length=200)),
... |
import unittest
import numpy as np
from ceda_icompress.InfoMeasures.bitentropy import bitentropy
from test_types import get_test_types
DIM_LEN = 128
N_BITS = 8
class bitentropyTest(unittest.TestCase):
"""Test the bitentropy function with known answers."""
def test_all_numbers(self):
# generate a dist... |
import torch
import os
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import psutil
from util.h5_util import load_h5_file
from baselines.baselines_configs import configs
from metrics.mse import mse
from competition.submission.submission import create_patches, stitch_patches
from util.monitoring... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render
from django.views import generic
from .models import Comic, ComicChapter
from django.http import Http404
from ComicPub.settings import WEBSITE_NAME, DISQUS_URL
from django.shortcuts import render_to_response
app_name ... |
# -*- coding: utf8 -*-
import os
import re
import sys
from collections import Counter
import argparse
import numpy as np
def compute_wordcount(arguments, input_file, word_freq_counter):
check_re = re.compile('[a-zA-Z0-9_-]+')
en_alphanum = '[a-zA-Z0-9]'
with open(os.path.join(arguments.clean_wikidata_path... |
from tfchain.polyfill.jsmods.promisepooljs import api as jspromisepool
def promise_new(cb):
p = None
__pragma__("js", "{}", """
p = new Promise(cb);
""")
return p
def as_promise(cb):
def f(resolve, reject):
try:
result = cb()
resolve(result)
except Excep... |
#!/usr/bin/env python3
import datetime
import sys
import os
import json
import argparse
def dump(json_data):
for key, val in json_data.items():
print("[{}]: {}".format(key, val))
def is_whitelisted(categories, whitelist):
for white in whitelist:
if white in categories:
return True
return False
if __name... |
"""
Autopsy Forensic Browser
Copyright 2016-2018 Basis Technology Corp.
Contact: carrier <at> sleuthkit <dot> org
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... |
from datetime import datetime
import pytest
from utils import snowflake_time
EXAMPLE_INTERNAL_ID = 6802059911472611845
EXAMPLE_DISCORD_ID = 144112966176997376
INVALID_ID = 144112966175
@pytest.mark.parametrize(
"test_id,is_internal,expected",
[
(EXAMPLE_DISCORD_ID, False, datetime(2016, 2, 2, 16, 1... |
import copy
from itertools import groupby
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import AuthenticationForm, PasswordResetForm
from django.contrib.auth.models import Group, Permission
from django.core import validators
from django.db import models, transac... |
""" DataPanels implementation of Conway's Game of Life
See https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life for details about
the game.
"""
import random
from typing import Tuple, Set, Optional, Union, List
import re
import numpy as np
from kivy.lang.builder import Builder
from kivy.properties import ListPropert... |
import pytest
from {{ cookiecutter.project_name }}.cli import ENVVAR_PREFIX
@pytest.fixture
def cli_invoke(cli_runner):
def func(*args, **kwargs):
kwargs.setdefault('auto_envvar_prefix', ENVVAR_PREFIX)
return cli_runner.invoke(*args, **kwargs)
return func
|
#!/usr/bin/env python3
"""
@author = Paolo Grasso
"""
import paho.mqtt.client as PahoMQTT
import time
import datetime
import json
TOPIC = '/datetime'
BROKER_IP = '192.168.1.28'
class MySubscriber:
def __init__(self, clientID, topic, serverIP):
self.clientID = clientID
self.topic = topic
... |
import gv
from pipeline import *
class ExecUnit:
def __init__(self):
self.bypassed = None
pass
def execute(self):
instr = gv.pipeline.pipe[Stages["EXECUTE"]]
gv.unit_statuses[Stages["EXECUTE"]] = "BUSY"
if instr:
instr.evaluate_operands(self.bypassed)
... |
#--------------------------CSL_WRITER-BASE-------------------------------#
##########################################################################
# ATTENTION: HUGE REWRITE IN PROGRESS !!!!!
# 2020/10/02 Status: Initial updated version done
# for any new variable use the REALLY USEFUL functions below for optimal per... |
import torch.nn as nn
from torch.autograd import Function #it represents a functions that works on tensors, i have to specify what is does forward and backward
'''
Very easy template to start for developing your AlexNet with DANN
Has not been tested, might contain incompatibilities with most recent versions of PyTor... |
print('\n <<------Calculadora Simples----->>')
print('+ Adição')
print('- Subtração')
print('* Multiplicação')
print('/ Divisão')
print('Presione a tecla "s" para encerra o programa!')
# (\n) faz uma quebra de linha
while True:
op = input('\n Qual operação deseja fazer? ')
if op == '+' or op =='-' or op =='*... |
from tkinter import *
from tkinter import messagebox
from tkinter import ttk
from tkinter import scrolledtext as tkst
from tkinter import font
# Set up fonts for text area
arial_bold = font.Font(family="Arial", size=14, weight=font.BOLD)
arial_normal = font.Font(family="Arial", size=14, weight=font.NORMAL)
# Must not... |
import numpy as np
import time
import threading
import random
import logging
logging.basicConfig(level=logging.DEBUG,
format='(%(threadName)-9s) %(message)s',)
class ActorThread(threading.Thread):
def __init__(self, agent, env, replay_buffer, parameter_server,
writer, config, explorer=None, group=None... |
#!/usr/bin/env python
import fnmatch
import os
import csv
import numpy as np
import scipy as sp
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt
import nibabel as nib
## Options ###
oPre = 'func_brain'
oMsk = 'anat_EPI_brain'
oHeadSize = 50 # head diamater in mm
oFDthresh = 2 # We wi... |
# from inspect import signature
from ..template.ets import ETSModel
from ..forecaster import MAPForecaster, FullBayesianForecaster
from ..exceptions import IllegalArgument
from ..estimators.stan_estimator import StanEstimatorMAP, StanEstimatorMCMC
from ..constants.constants import EstimatorsKeys
def ETS(seasonality=N... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.