content stringlengths 5 1.05M |
|---|
import collections
import itertools as it
import sys
import time
import torch as T
import torchvision
from . import utility
Batch = collections.namedtuple('Batch', ('epoch', 'batch', 'example', 'x', 'y'))
Batch.cuda = lambda self: self._replace(x=self.x.cuda(), y=self.y.cuda())
def batches(dataset, batch_size, lo... |
# solo existe en python
class primera:
def __init__(self):
print("clase padre")
def metodo_1(self):
print("metodo padre")
class segunda:
def __init__(self):
print("clase hija")
def metodo_2(self):
print("metodo hijo")
class tercera(segunda, primera):
def metodo_3... |
#
# James Boocock and Murray Cadzow
# July 2013 / Sept 2014
# University of Otago
#
import re
import vcf
from optparse import OptionParser
from pyfasta import Fasta
#
# Command Line Arguments
#
# --haps phased haps
# --aa ancestral allele annotation
# --chr Chromosome
# --output Output file
# --format |High|Low|
# opti... |
from django.contrib import admin
from django.template.defaulttags import url
from django.urls import path, include
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('index/', views.index, name='index'),
path('login/', views.login, name='login'),
path('register/', views.registe... |
"""deserialize icd hierarchies computed in datacleaning.py"""
from typing import Optional, Sequence, Tuple
import json
from datetime import datetime
import networkx as nx
from . import data
try:
import importlib.resources as importlib_resources
except ModuleNotFoundError:
import importlib_resources
def icd9... |
import json
from hmmlearn import hmm
import numpy as np
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
with open('corpus.json') as f:
corpus = json.load(f)
# init model for phoneme 'a'
model_a = hmm.GaussianHMM(n_components=3, covariance_type='diag')
# init model for phoneme 'n'
mo... |
# Copyright Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompan... |
import torch
from scipy.linalg import toeplitz
from sdtw.distance import SquaredEuclidean
import gc
from .sinkhorn import divergencekl, amarikl, convol_imgs
from .utils import tonumpy
class SinkhornDistance(object):
def __init__(self, x, y, K, return_grad=True,
ot=True, autodiff=False, warmsta... |
import telegram
from telegram import ChatAction, InlineKeyboardButton,InlineKeyboardMarkup
from telegram.ext import Updater, CommandHandler,MessageHandler,Filters,CallbackQueryHandler,PicklePersistence
from telegram.ext.dispatcher import run_async
import logging
import requests
import wikipedia
import os
logging.basicC... |
#!/usr/bin/python
import random
import logging
from collections import defaultdict
from messages import Upload, Request
from util import even_split
from peer import Peer
class JZASStd(Peer):
def post_init(self):
print "post_init(): %s here!" % self.id
self.optimistic_id = None #the current optimi... |
# -----------------------------------------------------------------------
# Name: inputs.py
# Purpose: Read in input parameters to set up and run the model.
# Read in meteorological data, and if desired calculate derived
# data to run the model.
# Author: Leah Jackson-Blake
# Created: 06/1... |
"""SCons.Tool.cpython
Tool-specific initialization for Python binary builder.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001-7,2010 The SCons Foundation
#
# Permission is hereby grant... |
# Generated by Django 2.2.11 on 2021-06-14 09:08
from django.db import migrations, connection
from django.db.backends.utils import split_identifier, names_digest
def _django_index_name(table, field_name):
table_name = f"database_table_{table.id}"
return _copied_django_internal_index_name_calculator(table_name... |
# indeed_scrape.py - scrape major tech job listings from indeed
import re
import os
import csv
import shelve
from urllib import parse
from ast import literal_eval
from pdb import set_trace as bp
import logging
import requests
from bs4 import BeautifulSoup
FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
logging.b... |
from artiq.experiment import *
from jax import Sequence
from jax.examples.sequences.doppler_cool import DopplerCool
from jax.examples.sequences.state_detect import StateDetect
__all__ = ["Example2"]
class Example2(Sequence):
"""Pulse sequence for the example 2 experiment."""
kernel_invariants = {}
requ... |
import cv2
import os
import uuid
import argparse
from utils import httpreq
from constants import constants
parser = argparse.ArgumentParser()
parser.add_argument("--name")
parser.add_argument("--lastName")
parser.add_argument("--phoneNumber")
args = parser.parse_args()
index = httpreq.send_staff_credentials(args.name,... |
from setuptools import setup
import os
def get_long_description():
with open(
os.path.join(os.path.dirname(os.path.abspath(__file__)), "README.md"),
encoding="utf8",
) as fp:
return fp.read()
setup(
name="nb-serverproxy-openrefine",
packages= ['nb_serverproxy_openrefine'],
... |
"""Diagnostics support for Shelly."""
from __future__ import annotations
from homeassistant.components.diagnostics import async_redact_data
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import HomeAssistant
from . import Block... |
import requests
from lib.configloader import config
class UserAgent:
""" A thin wrapper around Requests. For now, provides a `get` method
applying the User-Agent.
"""
def get(self, url, *args, headers={}, **kwargs):
headers.update({"User-Agent": config.user_agent})
r... |
"""Tests basemodels."""
from typing import Any
from typing import Dict
from typing import List
from typing import Optional
from datetime import date
import pytest
from babel.dates import format_date # type: ignore
# from faker import Faker # type: ignore
from pydantic import ValidationError
from tia.basemodels im... |
dia = input('Dia ? ')
mes = input('Mes ? ')
ano = input('Ano ? ')
print('Você nasceu no dia {} de {} de {}. Correto ?'.format(dia, mes, ano))
fim = input('\nCurso de Python no YouTube, canal CURSO EM VIDEO.') |
import random
from whitesymex.strategies import Strategy
class Random(Strategy):
def select_states(self):
index = random.randrange(len(self.path_group.active))
state = self.path_group.active.pop(index)
return [state]
|
import numpy as np
from perlin import PerlinNoiseGenerator
from hilbert import HilbertCurves
class BGTextureType:
Plain = "plain"
Perlin = "perlin"
Gaussian = "gaussian"
HilbertCurve = "hilbert"
PeanoCurve = "peano"
class Background(object):
def __init__(self, texture=None, size = (0, 0),
... |
n1=int(input("Entre com o primeiro numero: "))
n2=int(input("Entre com o segundo numero: "))
n3=int(input("Entre com o terceiro numero: "))
lista=[n1,n2,n3]
lista=(sorted(lista))
print("O menor numero é {}".format(lista[0]))
print("O maior numero é {}". format(lista[2]))
|
from .classification_transformer import (
ClassificationTransformer,
install_classification_extensions,
)
|
#!/usr/bin/python
#Local library imports
import multiprocessing
def infiniteLoopTest(number):
while 1:
print number
if __name__ == '__main__':
pool = multiprocessing.Pool(processes=len(range(5)))
pool.map(infiniteLoopTest, range(5)) |
# coding: utf-8
#
# Copyright 2022 :Barry-Thomas-Paul: Moss
#
# 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 applicab... |
from resource.base import Base_Resource
from docstring import docstring
from document.agent.catalog import Agent_Catalog_Document
from schema.agent.catalog import Agent_Catalog_Schema
@docstring(ext='yaml')
class Agent_Catalog_Resource(Base_Resource):
doc = Agent_Catalog_Document
name = 'agent catalog'
n... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/12/11 9:42 AM
# @Author : Insomnia
# @Desc : TODO
# @File : StackPushPopArr.py
# @Software: PyCharm
class Solution:
def pushAndPopOrder(self, pushArr, popArr):
s = []
index = 0
for val in pushArr:
s.append(va... |
from .test_models import *
from .test_admin import *
from .test_commands import *
from .test_manager import *
|
# Copyright 2020 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 agreed to in writing, s... |
def leiaInt(valor):
while True:
num = input(valor).strip()
if num.isnumeric() == True:
return num
break
else:
print('\033[31mERRO! Digite um número inteiro válido.\033[m')
n = leiaInt('Digite um número: ')
print(f'Você acabou de digitar o número {n}')
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 2 21:17:17 2020
@author: casper
"""
import os
import pandas as pd
colnames = ['min', 'max', 'char', 'code']
df = pd.read_csv('../inputs/02', sep=",", names=colnames)
count = 0
for index, row in df.iterrows():
n = row['code'].count(row['char'... |
import os
import torch
import itertools
import numpy as np
from itertools import cycle
from numpy import interp
import matplotlib.pyplot as plt
from sklearn.metrics import roc_curve, auc, precision_score, recall_score, f1_score, accuracy_score, classification_report, confusion_matrix
def create_dirs(output_path):
... |
from .wallet import Wallet
from .base_env import Environnement
from .reward import Reward
from .state import state
from .dataloader import dataLoader
from .inventory import Inventory
from .orders import orders, order
|
import falcon
import mimetypes
from typing import Optional
from smpa.resources.core import Resource, ListResource
from smpa.services.document import _document_sizes, _document_files, _document_types
from smpa.schemas.document import document_upload_schema
class DocumentFileDownloadResource(Resource):
_service... |
import unittest
import numpy as np
from mtrack.graphs import cost_converter, graph_converter, g1_graph, g2_solver
from mtrack import g2_to_g1_solution
class SmallSquareGraphTestCase(unittest.TestCase):
# orientation = (1, 0, 0)
# --->
# 1----2
# | |
# | |
# 0-... |
# module to create callback for age group filter for cultural participation
from dash.dependencies import Input, Output
import plotly.graph_objs as go
import sys
# app server
sys.path.append('../..')
from server import app
# data loaders
from dataloaders.CultureCentreDistances import culture_centre_distances
# Acces... |
from datetime import datetime
from os.path import dirname, join
import pytest
from city_scrapers_core.constants import BOARD
from city_scrapers_core.utils import file_response
from freezegun import freeze_time
from city_scrapers.spiders.il_capital_development import IlCapitalDevelopmentSpider
test_response = file_re... |
import os
import sys
from setuptools import setup
from setuptools.command.test import test as TestCommand
here = os.path.abspath(os.path.dirname(__file__))
PACKAGE_NAME = 'quickcert'
packages = [PACKAGE_NAME]
requires = [
'cryptography>=2.5',
'python-interface>=1.5'
]
test_requirements = [
'pytest-cov... |
from typing import Set, Dict
from pydantic import BaseModel, Field
from pydantic.types import OptionalInt, NoneStr
class ConnectionOptions(BaseModel):
name: str
type: NoneStr
host: NoneStr
port: OptionalInt
platform: NoneStr
class Device(BaseModel):
name: str
host: NoneStr
username: ... |
# -*- coding: utf-8 -*-
'''
Created on 18.05.2016
@author: rdebeerst
'''
from __future__ import absolute_import
import logging
import json
import uuid
import bkt
import bkt.library.powerpoint as pplib
import bkt.dotnet as dotnet
ppt = dotnet.import_powerpoint()
office = dotnet.import_officecore()
TOOLBOX_AGENDA ... |
# Generated by Django 2.1.7 on 2019-04-02 16:57
# -*- coding: utf-8 -*-
from django.db import migrations, models
import xlrd
booksindex = {
'name': 0,
'filename': 1,
'fileinfo': 2,
'introduction': 3,
'imagefilename': 4,
'money':5
}
booksinfo = [
('2013年大学英语六级词汇表', 'bookfiles/2013年大学英语六级词汇表... |
import time
import board
import busio
import adafruit_mpl115a2
i2c = busio.I2C(board.SCL, board.SDA)
mpl = adafruit_mpl115a2.MPL115A2(i2c)
while True:
print("Pressure: {} Temperature: {}".format(mpl.pressure, mpl.temperature))
time.sleep(1)
|
#!/usr/bin/env python3
import datetime
import os
import subprocess
import sys
UPDATE_TIMEOUT = datetime.timedelta(hours=1)
TASK_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
LAST_UPDATE_FILE = os.path.join(TASK_DIR, "_repo_updated_at")
NO_COMMIT_ENV = "TW_NO_COMMIT"
os.chdir(TASK_DIR)
if... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file contains all the necessary settings, constants and paths the Flask web application uses.
:Date: 2017-12-10
:Author: Pierre-Luc Delisle
:Version: 1.0
:Credit: None
:Maintainer: Pierre-Luc Delisle
:Email: pierre-luc.delisle.1@ens.etsmtl.ca
"""
i... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `sports-manager` models module."""
# Django
from django.contrib.auth import get_user_model
from django.test import TestCase
# Current django project
from sports_manager.models import Category, Team
from sports_manager.models.category import image_upload_to
... |
# coding: utf8
# Modified by Dmytro Kalpakchi, 2020
# Adapted from spaCy's built in visualization suite for dependencies and named entities.
# https://github.com/explosion/spaCy/tree/master/spacy/displacy
from __future__ import unicode_literals
import uuid
from .templates import TPL_DEP_SVG, TPL_DEP_WORDS, TPL_DEP_... |
import setuptools
from distutils.core import setup
setup(
name = 'pub-data-visualization',
version = '0.1.dev0',
packages = setuptools.find_packages(),
scripts = [],
author = 'CRE',
author_email = 'opensource[at]cre.fr',
lice... |
import unittest
import os
import shutil
import numpy as np
from osgeo import gdal
from osgeo import ogr
from pygeoprocessing import geoprocessing as raster_utils
from invest_natcap.nutrient import nutrient
BASE_DATA = os.path.join('data', 'base_data', 'terrestrial')
NUTR_INPUT = os.path.join('data', 'nutrient', 'inp... |
from rest_framework import serializers
from .models import Account
class AccountRepresentationSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = ('id', 'name')
class AccountListSerializer(serializers.ModelSerializer):
class Meta:
model = Account
... |
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/06_core.rq_collection.ipynb (unless otherwise specified).
__all__ = ['get_user_collection_folders', 'create_new_user_collection_folder', 'get_folder_metadata',
'change_collection_folder_name', 'delete_collection_folder', 'get_collection_folder_by_release',
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 20 14:48:01 2019
@author: leeh43
"""
import os
import numpy as np
import matplotlib.pyplot as plt
final_list = []
for num in range(100):
if num + 1 < 10:
img_num = 'img000' + str(num + 1)
data_dir = '/nfs/masi/leeh43/M... |
import numpy as np
from scipy.linalg import hadamard
import math
def wiener_filtering_hadamard(group_3D_img, group_3D_est, nSx_r, kWien, chnls, sigma_table, weight_table, doWeight):
kWien_2 = kWien * kWien
coef = 1.0 / nSx_r
for c in range(chnls):
weight_table[c] = 0.
for n in range(kWien_2 * ... |
import shutil
import tensorflow as tf
from benchmark import start_benchmark
# Configurations
#########################################################
# To enable xla compiler
import os
from log import init_logger
from utils import base_path
os.environ['TF_XLA_FLAGS'] = '--tf_xla_enable_xla_devices'
###############... |
import tensorflow as tf
class New_Start_Invariant_Spiral_Opts( object ):
def __init__( self ):
self.batch_size = 64
self.sample_shape = [ 3 ]
self.label_shape = [ 2 ]
self.num_class = 2
self.lr = 1e-4
self.train_alt = 100
self.train_iter = 1000000
... |
from .juster import justify, example |
import calendar
import json
import time
from logger import logger
from perfrunner.helpers.cbmonitor import timeit, with_stats
from perfrunner.helpers.misc import pretty_dict
from perfrunner.helpers.profiler import with_profiles
from perfrunner.helpers.worker import (
pillowfight_data_load_task,
pillowfight_tas... |
from __future__ import division
import iotbx.pdb
def exercise_rna_dna_atom_names():
for atom_name in [None, ""]:
info = iotbx.pdb.rna_dna_atom_names_info(atom_name=atom_name)
assert info.reference_name is None
assert info.compatible_residue_names() == "None"
assert not info.is_compatible_with(residue... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import rospy
import cv2
from sensor_msgs.msg import Image
import sys
import numpy as np
from rospy.numpy_msg import numpy_msg
from std_msgs.msg import Int32MultiArray
import argparse
import logging
import os
import torch
import torch.nn.functional as F
from PIL import Im... |
#!/usr/bin/env python3
#
# Copyright (c) 2018 Tatu Ylonen. See LICENSE and https://ylonen.org
from setuptools import setup
with open("README.md", "r") as f:
long_description = f.read()
setup(name="wiktextract",
version="0.2.0",
description="Wiktionary dump file parser and multilingual data extractor... |
"""
Copyright (c) 2014-2015 F-Secure
See LICENSE for details
"""
|
#!/usr/bin/python
"""
Intended use:
This script can receive a pub-sub socket and detects if an automatic
periodic message does not arrive before a threshold period.
It can also generate such periodic messages for other hosts to receive.
The detection of disconnections can be useful for automatic reconnection.
"""
i... |
# insert][].insert
words = ['apple', 'banana', 'cat']
print(words) # ['apple', 'banana', 'cat']
words.insert(2, 'zebra')
print(words) # ['apple', 'banana', 'zebra', 'cat']
words.insert(0, 'dog')
print(words) # ['dog', 'apple', 'banana', 'zebra', 'cat']
# Instead of this, use append (next slide)
words.insert(len(wor... |
from edu_web_app import app
|
"""Spider for ixigua.com"""
from urllib.parse import urlparse, parse_qsl, urlencode, urlunparse
from video_dl.extractor import Extractor
from video_dl.spider import Spider
from video_dl.toolbox import info
from video_dl.video import Media
def add_params(url: str, **params) -> str:
"""add parameters into url"""
... |
import json
from jsonschema import validate
def parse_to_dict(json_file: str, schema_file: str) -> dict:
"""
Ensures that both json_file and schema_file are valid JSON, and that json_file conforms to the schema_file schema.
Returns a dict from the parsed JSON from json_file.
:param json_file: path t... |
#!/usr/bin/env python3
import time
seen = ''
curr_pos = (0, 0)
prev_pos = None
dts = set([(-1, 0), (0, 1), (1, 0), (0, -1)])
curr_dt = None
def get_map_pos(pos):
try:
return map[pos[0]][pos[1]]
except IndexError:
return None
with open('input/day19.txt') as fh:
map = [[ch for ch in lin... |
"""
Controller to interface with the Yle Areena app namespace.
"""
from ..config import APP_YLEAREENA
from .media import MediaController, STREAM_TYPE_BUFFERED, TYPE_LOAD, MESSAGE_TYPE
class YleAreenaController(MediaController):
""" Controller to interact with Yle Areena app namespace. """
# pylint: disable=... |
import torch.nn as nn
import torch.nn.functional as F
from dgl.nn.pytorch import GraphConv # type: ignore
from indigo.ml.mpp.models.blocks import ( # type: ignore
EdgeGraphConv,
InputInitializer,
WeightedSumAndMax,
)
from indigo.ml.mpp.models.regressor import BaseGNNRegressor # type: ignore
class GCNL... |
#!/usr/bin/env python
# Version 3.0.6 Created by Z.Cao 20/Mar/2019
import os, sys, getopt, math
import numpy as np
from decimal import Decimal
import pandas as pd
newchgcar = []
Mode = ''
atoms = []
oatoms = []
def readfiles(name):
"""
Args:
name (str): Name of file
Returns:
files (str): Content of file
Functi... |
from sqlalchemy.exc import IntegrityError
from core.clientes.exceptions import (
ClienteNotFoundException,
RequiredDataException,
DuplicatedEntityException,
)
from api.database.models import Cliente
class ClienteGateway(object):
def __init__(self, session):
self.session = session
def get... |
import numpy as np
from sklearn.decomposition import TruncatedSVD
from sklearn.decomposition import LatentDirichletAllocation
from sklearn.decomposition import PCA
import sklearn
from scipy import sparse as sp
import pandas as pd
user_tfidf = None #tfidf values per user
user_id_dict = None #numeric_index->id eg. 0->10... |
from colorama import Fore
from colorama import Style
from colorama import init
import sys
import socket
import utility
import time
init()
rec_ip = "127.0.0.1"
rec_port = 5555
rec_data = 'received-test.txt'
if len(sys.argv) >= 2:
if utility.isstrint(sys.argv[1]):
rec_port = int(sys.argv[1])
else:
... |
# -*- coding: utf-8 -*-
import asyncio
import thriftpy2
from thriftpy2.rpc import make_aio_server
echo_thrift = thriftpy2.load("echo.thrift", module_name="echo_thrift")
class Dispatcher(object):
async def echo(self, param):
print(param)
await asyncio.sleep(0.1)
return param
def main():... |
""" Base class for different nearest neighbor search methods
"""
from .. import config as c
from .. import store
from ..sample import Sample
from ..logger import get_logger
import os
import numpy as np
from sklearn.externals import joblib
from importlib import import_module
from operator import itemgetter
log = get_... |
from collections import Counter
n,k=map(int,input().split())
a=Counter(input().split())
print(sum(sorted(a.values(),reverse=True)[k:])) |
import gym
from gym.spaces import Discrete, Box
def is_discrete(space):
if isinstance(space, Discrete):
return True
elif isinstance(space, Box):
return False
else:
raise NotImplementedError
def get_act_dim(action_space):
if isinstance(action_space, Discrete):
return a... |
def print_array(a):
'''Prints a byte array'''
output = [hex(byte) for byte in a] #creates a list
print(output)
def b_to_list(a):
'''Convert byte array to list to make printing easier'''
output = [hex(byte) for byte in a] #creates a list
return output
def create_bytearray_str(b):
'''Conve... |
import vmraid
def execute():
vmraid.db.sql('''
UPDATE tabFile
SET folder = 'Home/Attachments'
WHERE ifnull(attached_to_doctype, '') != ''
AND folder = 'Home'
''')
|
'''
Copyright 2022 Airbus SAS
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 writing, software
dis... |
from .generic import log, log_async
|
postnr = [30617, 78203, 44169, 56874, 14139, 23995, 32388, 29000, 58876, 28384, 54256, 49174, 32850, 14216, 71966, 80128, 82515, 82053, 29693, 60955, 28076, 49328, 77972, 29308, 66653, 60493, 50175, 62418, 32311, 78357, 11367, 17758, 21993, 41089, 36777, 27383, 37701, 49636, 79512, 40473, 69502, 16988, 56797, 19452, 77... |
import os
from numpy import array, cumsum, nditer, roll, setdiff1d, where
workPath = os.path.expanduser("~/Documents/Code/Advent_of_code/2020")
os.chdir(workPath)
with open("day-9_data.txt", "r") as in_file:
data = array([int(row.strip()) for row in in_file])
# Part 1:
num_rows = len(data)
preamble_length = 25
... |
Num1=int(input())
Num2=int(input())
if Num1 >= Num2:
print(Num1)
else:
print(Num2) |
# Copyright 2019-2020 Xanadu Quantum Technologies 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 or... |
"""
Given a directed graph, check if it contains a cycle.
What's the real time application of this?
Imagine there is a deadlock detection in a system.
Processes can be determined by vertices a&
edge can be - Process is waiting for process B to release the mutex
There are 2 approaches to this:
1. Using color theory
2... |
class Forecast(object):
def __init__(self, forecast_data):
self._forecast_data = forecast_data
def text(self):
return self._forecast_data['text']
def date(self):
return self._forecast_data['date']
def high(self):
return self._forecast_data['high']
def low(self):
... |
from source.decisoes.estrutura_veiculo import Estrutura_veiculo
from pygame import mixer
from pyautogui import sleep
from emoji import emojize
def Coreia():
print()
print(emojize(' :airplane: ' * 10, use_aliases=True))
sleep(0.25)
print()
mixer.music.load('library/main/decolagem.mp3')
mixer.mu... |
import pytest
import stix2
from .constants import (
CAMPAIGN_ID, CAMPAIGN_KWARGS, FAKE_TIME, IDENTITY_ID, IDENTITY_KWARGS,
INDICATOR_ID, INDICATOR_KWARGS, MALWARE_ID, MALWARE_KWARGS,
RELATIONSHIP_IDS,
)
@pytest.fixture
def ds():
cam = stix2.v21.Campaign(id=CAMPAIGN_ID, **CAMPAIGN_KWARGS)
idy = s... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Applies REF_PANEL_GENOTYPES filter to a single sample VCF file given the cleaned final VCF for the reference panel cohort
#
# The general objective is to remove calls in the single sample VCF which do not match a call or calls in the reference
# panel VCF AND have varian... |
from .problem import Biclique as Problem
|
# -*- coding: utf-8 -*-
from odoo import models, fields, api, _
from odoo.exceptions import ValidationError, UserError
import pprint
import logging
_logger = logging.getLogger(__name__)
class ReloadTranslations(models.TransientModel):
_name = 'wizard.reload_translations'
# Default methods
def get_lang... |
__author__ = 'ZSGX'
from sys import maxsize
class Contact:
def __init__(self, firstname=None, middlename=None, lastname=None, nickname=None, title=None, company=None,
address=None, homephone=None, mobilephone=None, workphone=None, fax=None, email=None, email2=None,
email3=None, h... |
from collections import Counter
from aoc.util import load_input, load_example
def column_counts(lines, pos):
result = ""
for i in range(len(lines[0].strip())):
result += Counter(line[i] for line in lines).most_common()[pos][0]
return result
def part1(lines):
"""
>>> part1(load_example(_... |
# Copyright 2017 The dm_control 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 i... |
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 9 08:07:47 2018
@author: jel2
"""
def stratifiedSurvival(t,eventTime,eventIndicator=None,followupTime=None,group=None):
import matplotlib.pyplot as plt
import lifelines as lf
from lifelines.plotting import add_at_risk_counts
import panda... |
from __future__ import annotations
from abc import abstractmethod
from typing import Any
import numpy as np
from dnn.utils import HeightWidthAttribute
from .activations import ActivationType
from .base_layer import BaseLayer, LayerInputType
from .utils import add_activation
from .utils import conv_utils as cutils
... |
from worlddata.APISections.base import WorldDataBase
class WorldDataSearch(WorldDataBase):
def search(self, search_text, **kwargs):
return self.call_api_post("search", search_text=search_text, kwargs=kwargs)
|
#
# 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.