content stringlengths 5 1.05M |
|---|
"""Ajout population suppression pathologie respi et allergie
Revision ID: e741811f9af0
Revises: ca7c02fcb035
Create Date: 2021-03-10 17:45:26.560460
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = 'e741811f9af0'
down_re... |
#!/usr/bin/env python
#
# Copyright (c) 2016, SICS, Swedish ICT
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, t... |
import mimetypes
import os
from .posts import Post
extra_content_types = (
('text/plain', ['.md', '.markdown']),
)
for type_, ext_list in extra_content_types:
for ext in ext_list:
mimetypes.add_type(type_, ext, strict=False)
class Storage(object):
content_types = ('text/plain',)
def __init... |
from __future__ import division
from cctbx.array_family import flex
import mmtbx.f_model
import mmtbx.f_model
from scitbx import lbfgs as scitbx_lbfgs
from libtbx import adopt_init_args
import random
from mmtbx import bulk_solvent
def lbfgs_run(target_evaluator,
min_iterations=0,
max_iterat... |
import asyncio
import logging
import types
from collections import defaultdict
from typing import Dict
logger = logging.getLogger(__name__)
class EventManager:
__subscribers: Dict = defaultdict(set)
@classmethod
def subscribe(cls, subscriber, event):
cls.__subscribers[event].add(subscriber)
... |
import os
from ossid.datasets.utils import getSampler
import numpy as np
from numpy.lib.type_check import imag
import torch
import time
import torchvision.transforms as transforms
from scipy.spatial.transform import Rotation as R
def expandBox(x1, y1, x2, y2, img_h, img_w, expand_ratio):
cx, cy = (x1+x2) / 2, (y1... |
"""Assortment of layers for use in models.py.
Refer to StackGAN paper: https://arxiv.org/pdf/1612.03242.pdf
for variable names and working.
Authors:
Abhiraj Tiwari (abhirajtiwari@gmail.com)
Sahil Khose (sahilkhose18@gmail.com)
"""
import torch
import torch.nn as nn
from torch.autograd import Variable
def c... |
# -------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
# ----------------------------------------------------------------------... |
class IParamProvider(object):
def __call__(self, pyfunc, param_name):
"""
:type pyfunc: rope.base.pyobjectsdef.PyFunction
:type param_name: str
:rtype: rope.base.pyobjects.PyDefinedObject | rope.base.pyobjects.PyObject or None
"""
raise NotImplementedError
class IR... |
#!/usr/bin/env python
import asyncio
import argparse
import io
import re
import aiohttp
import pandas as pd
import requests
import pytrthree
from apscheduler.schedulers.asyncio import AsyncIOScheduler
TRTH_HTTP_LIST = 'http://tickhistory.thomsonreuters.com/HttpPull/List'
TRTH_HTTP_DWLD = 'https://tickhistory.thomsonr... |
#!/usr/bin/env python
u"""
test_legendre.py (11/2021)
"""
import numpy as np
import gravity_toolkit
#-- PURPOSE: test unnormalized Legendre polynomials
def test_unnormalized(l=3, x=[-1.0, -0.9, -0.8]):
obs = gravity_toolkit.legendre(l, x)
expected = np.array([
[-1.00000, -0.47250, -0.08000],
[0... |
import numpy as np
import os
import os.path as osp
import shutil
from mmcv.utils import check_file_exist, is_str, mkdir_or_exist
import argparse
import cv2
from mmcv.fileio import FileClient
import mmcv
def reorder_image(img, input_order='HWC'):
"""Reorder images to 'HWC' order.
If the input_order is (h, w),... |
from __future__ import absolute_import
import subprocess
import sys
from typing import List
from colorama import Fore
import kslurm.text as txt
from kslurm.args import print_help
from kslurm.models import SlurmModel
from kslurm.slurm import SlurmCommand
def kbatch(script: str, args: List[str]):
"""Submit a job... |
class Solution(object):
def minTaps(self, n, ranges):
"""
:type n: int
:type ranges: List[int]
:rtype: int
"""
ranges = [(i-r,i+r) for i,r in enumerate(ranges)]
ranges.sort(reverse = True)
watered = 0
ans = 0
while ra... |
class OpenTAXIIAuthAPI(object):
'''Abstract class that represents OpenTAXII Authentication API.
This class defines required methods that need to exist in
a specific Authentication API implementation.
'''
def init_app(self, app):
pass
def authenticate(self, username, password):
... |
"""
By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.
That is, + + + = 23.
Find the maximum total from top to bottom of the triangle below:
"""
inputdata = """
75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75... |
from ..utils import Object
class GetLogVerbosityLevel(Object):
"""
Returns current verbosity level of the internal logging of TDLib. This is an offline method. Can be called before authorization. Can be called synchronously
Attributes:
ID (:obj:`str`): ``GetLogVerbosityLevel``
No parameter... |
import stringrnautils
import argparse
import os
import logging
logger = logging.getLogger(os.path.basename(__file__))
logging.basicConfig(level=logging.INFO)
def is_valid_path(arg):
if not os.path.exists(arg):
parser.error("Given master file path %s does not exist." % arg)
return arg
def main():
... |
#!/usr/bin/env python
import os
def test(testSuite):
#rt = os.system("cd ../demo && python dom_from_html_file.py employee_table.html")
#if rt:
# return 0
rt = os.system("cd ../demo && python dom_from_xml_file.py addr_book1.xml")
if rt:
return 0
#os.system("cd ../demo && python g... |
#Needs rewriting, and splitting into funcs
from collections import deque
# def create_bomb(material_sum, target):
# if material_sum == target:
# if target == 40:
# detura_b += 1
# if target == 60:
# cherry_b += 1
# if target == 120:
# smoke_b += 1
# ... |
# Databricks notebook source
# MAGIC %md-sandbox
# MAGIC
# MAGIC <div style="text-align: center; line-height: 0; padding-top: 9px;">
# MAGIC <img src="https://databricks.com/wp-content/uploads/2018/03/db-academy-rgb-1200px.png" alt="Databricks Learning" style="width: 600px">
# MAGIC </div>
# COMMAND ----------
# M... |
import pathlib
from dataclasses import asdict
import jinja2
import structlog
import yaml
from scenario_player.utils.configuration.nodes import NodesConfig
from scenario_player.utils.configuration.scenario import ScenarioConfig
from scenario_player.utils.configuration.settings import EnvironmentConfig, SettingsConfig
... |
import ctypes, sys, subprocess, threading, traceback
Kernel32 = ctypes.windll.Kernel32
class Console():
def __init__(self, ischild=True, outputonly=True):
if ischild:
# detach console if it is attached
Kernel32.FreeConsole()
# try allocate new console
result = Kernel32.AllocConsole()
if r... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import os
from celery import Celery
from django.conf import settings
from celery.schedules import crontab
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mindynode_service.settings')
app = Celery('mindynode_service')
app.config_from_object('django.conf:... |
"""Tests for Adam."""
from absl.testing import parameterized
import numpy as np
from tensorflow.python.eager import context
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.keras import combinations
fro... |
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# Name: features/base.py
# Purpose: Feature extractors base classes.
#
# Authors: Christopher Ariza
# Michael Scott Cuthbert
#
# Copyright: Copyright © 2011-2014 Michael Scott Cuth... |
import argparse
import random
from score import parse
# inp is an input file as a single string
# return your output as a string
def solve(seed, inp, log):
# TODO: Solve the problem
random.seed(seed)
ns = parse(inp)
return '0'
|
#pylint: disable=import-error
import tensorflow as tf
import tensorflow.keras as keras
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Dense, Concatenate, Convolution1D, GlobalMaxPooling1D, Embedding, Dropout, Lambda, Flatten, Add
from tensorflow.keras.layers import Conv1D
from tens... |
import cv2
def main():
cam = cv2.VideoCapture(0)
while True:
retval, img = cam.read()
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img, 'QWERTY', (10, 200), font, 1, (255, 0, 0), 2, cv2.LINE_AA)
cv2.rectangle(img, (200, 200), (400, 400), (255, 255, 255), 3)
cv2.imshow('Name', img)
if cv2.waitKey(1) == 27:... |
__author__ = 'admiral0'
import os.path as path
import re
from .Exceptions import JsonNotValid, ModDoesNotExist, ModJsonDoesNotExist, ModVersionDoesNotExistInRepo
from .Common import *
def validate_version(ver):
assert type(ver) is str
if not re.match(r'^[a-zA-Z_0-9\.\-()]+$', ver):
return ['Version ' ... |
# Problem: https://www.hackerrank.com/challenges/whats-your-name/problem
# Score: 10.0
print('Hello {0} {1}! You just delved into python.'.format(input(),input()))
|
from puma.runnable.message.status_message import RunInChildScopeStatusMessage, StartedStatusMessage, StatusMessage, status_message_type # noqa: F401
from puma.runnable.message.status_message_buffer import StatusMessageBuffer # noqa: F401
from puma.runnable.message.command_message import (CommandMessage, RemoteObjectG... |
import unittest
import gym
import abp.openai.envs
from mock import Mock, patch
from abp.openai.wrappers import RewardWrapper
class DecomposedRewardWrapperTests(unittest.TestCase):
def setUp(self):
self.env = gym.make("Yahtzee-v0")
def test_should_call_env_with_reward_decomposition(self):
wit... |
import numpy as np
import tensorflow as tf
from scipy.misc import imread
def calc_histogram(image):
values_range = tf.constant([0, 255], dtype = tf.float32)
histogram = tf.histogram_fixed_width(tf.to_float(image), values_range, 256)
return histogram
def histogram_loss(img1, img2):
hist1 = calc_histogram... |
#analisador de IMC
peso = float(input('Qual é o seu peso? (Kg) '))
altura = float(input('Qual é a sua altura? (m) '))
imc = peso / (altura ** 2)
print('Seu IMC é {:.1f}'.format(imc))
if imc < 18.5:
print('\033[1;34mVocê está abaixo do peso ideal!\033[m')
elif 18.5 <= imc < 25:
print('\033[1;32mPeso ideal!\0... |
from django.shortcuts import render
from django.urls import reverse
from django.views.generic import TemplateView
class TestView(TemplateView):
template_name = "home/test.html"
def get_context_data(self, **kwargs):
context = super().get_context_data()
context["id"] = "lorem ipsum"
retu... |
class Solution(object):
def orderOfLargestPlusSign(self, N, mines):
banned = {tuple(mine) for mine in mines}
dp = [[0] * N for _ in range(N)]
ans = 0
for r in range(N):
count = 0
for c in range(N):
count = 0 if (r, c) in banned else count+1
... |
import os
from transformers import AutoConfig
from onnxruntime_extensions.onnxprocess import trace_for_onnx, pyfunc_from_model, build_customop_model
from onnxruntime_extensions.onnxprocess import torch_wrapper as torch
# Create a cache directory to store pretrained model.
cache_dir = os.path.join(".", "cache_models")
... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from .functions import get_data, use_data, use_data_parametrize
|
# -*- coding: utf-8 -*-
import yaml
import json
import sys
import argparse
from Twittbot import Twittbot
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-a", "--account", help="Select this account", action='store')
parser.add_argument("-m", "--hashtag", help="Request twe... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'window6.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWind... |
class Solution:
def firstMissingPositive(self, nums: List[int]) -> int:
# The smallest positive number is 1, hence we set that
smallest = 1
while True:
# We check if this number is present in nums, if it does we add 1 to the number
if smallest in nums:
... |
from copy import deepcopy
from lbrynet.schema.proto import signature_pb2 as signature_pb
from lbrynet.schema.schema import VERSION_MAP, ECDSA_CURVES
from lbrynet.schema.schema.schema import Schema
class Signature(Schema):
@classmethod
def load(cls, message):
_signature = deepcopy(message)
_me... |
"""
Questo modulo contiente degli esempi per la visualizzazione 3D di poligoni tramite il pacchetto plotly.
Per approfondimenti visitare: https://plot.ly/python/
"""
import numpy as np
import plotly.graph_objs as go
import plotly.offline as poff
ottagono_3d = np.array([[-0.33095549, 2.80413031, 5.46457847, 6.63418... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 7 10:42:43 2019
@author: benka
"""
import tensorflow as tf
import Data_Reader
import BuildNetVgg16
logs_dir= "logs/"# "path to logs directory where trained model and information will be stored"
model_path="Model_Zoo/vgg16.npy"# "Path to pretrained... |
import redis
app_redis = redis.Redis() |
from indy_common.authorize.auth_actions import AuthActionAdd, AuthActionEdit
from indy_common.constants import REVOC_REG_DEF
def test_rev_reg_def_adding(write_request_validation, req, is_owner):
authorized = req.identifier in ("trustee_identifier", "steward_identifier", "trust_anchor_identifier")
assert autho... |
# Copyright 2018 DeepMind Technologies Limited.
#
# 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... |
# Copyright 2012 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 or agreed to in writing, ... |
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2019 DataONE
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you ma... |
import abc
import datetime
import argparse
from collections import namedtuple
from time import time, sleep
import multiprocessing as mp
from multiprocessing import Pool, Lock
import logging
import sys, os
from typing import Tuple
import gym
this_folder = '/'.join(os.getcwd().split('/')[:])
parent_folder = '/'.join... |
import pytest
from blight import action, tool
@pytest.mark.parametrize(
("action_class", "tool_class", "should_run_on"),
[
(action.Action, tool.CC, True),
(action.CCAction, tool.CC, True),
(action.CXXAction, tool.CC, False),
(action.CompilerAction, tool.CC, True),
(act... |
import json
from collections import OrderedDict
class PyposmatReferenceDataFile(object):
""" Used to interface with data from publications for validation purposes.
Args:
filename(str, optional): the filename of the data file to read (must be JSON).
"""
def __init__(self, filename=None):
... |
from xbrr.base.reader.base_element_schema import BaseElementSchema
import bs4
class RoleSchema(BaseElementSchema):
def __init__(self,
uri="", href="", lazy_label=None):
super().__init__()
self.uri = uri
self.href = href
self.lazy_label=lazy_label
self._labe... |
from django.test import TestCase
from cyder.cydns.txt.models import TXT
from cyder.cydns.domain.models import Domain
class TXTTests(TestCase):
def setUp(self):
self.o = Domain(name="org")
self.o.save()
self.o_e = Domain(name="oregonstate.org")
self.o_e.save()
def do_generic_a... |
#!/usr/bin/env python3 -u
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import argparse
import copy
import logging
import os
from typing import List, Dict, Iterator, Tuple, Any
import tor... |
import cv2
def drawsafelines(image_np,Orientation,Line_Perc1,Line_Perc2):
posii=int(image_np.shape[1]-(image_np.shape[1]/3))
cv2.putText(image_np,'Blue Line : Bed Line',
(posii,30),
cv2.FONT_HERSHEY_COMPLEX_SMALL, 0.8, (0,0,255), 1, cv2.LINE_AA)
... |
import unittest
from day6 import checksum, parse
class TestDay6(unittest.TestCase):
def test_example(self):
test_data = """
COM)B
B)C
C)D
D)E
E)F
B)G
G)H
D)I
E)J
J)K
K)L
""".split()
self.assertEqual(ch... |
from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import include, path, re_path
from django_project.swagger import schema_view
urlpatterns = [
path("api/provision/", include("provision.urls")),
]
if settings.DEBUG:
import debug_toolb... |
# GUI Application automation and testing library
# Copyright (C) 2006 Mark Mc Mahon
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public License
# as published by the Free Software Foundation; either version 2.1
# of the License, or (at your opti... |
# This file provides fast way for defininig new SDRAM modules.
# Modules defined in this files, after verifying that the settings are correct,
# should be later moved to LiteDRAM repository in a PR and removed from here.
from litedram.modules import _TechnologyTimings, _SpeedgradeTimings, DDR4Module
class MTA4ATF1G64... |
from grovepi import *
from grove_rgb_lcd import *
import time
import smbus
import RPi.GPIO as GPIO
from grove_i2c_barometic_sensor_BMP180 import BMP085
class WeatherStation(object):
def __init__(self, port=7):
self.dht_sensor_port = port
setRGB(0, 255, 0)
def get(self):
try:
... |
import fiona
import geopandas as gpd
from shapely.geometry import shape
import polyline
import googlemaps
from datetime import datetime, timedelta
import json
import pickle
gmaps = googlemaps.Client(key='apikey')
originalPoints = gpd.read_file('C:\\gitrepos\Commute\\LatLonPoints.shp')
#this fails if shapefile has no... |
import os
import sqlite3
from hashlib import md5
DATABASE = os.path.join(os.path.dirname(__file__), 'data.db')
'''
--------------------------------
| table users |
--------------------------------
| id | int auto primary |
--------------------------------
| username | string not null |
---... |
mun = 1
mun2 = 3
mun3 = 4
|
'''
A pseudo MSO neuron, with two dendrites (fake geometry).
There are synaptic inputs.
Second method.
'''
from brian2 import *
# Morphology
morpho = Soma(30*um)
morpho.L = Cylinder(diameter=1*um, length=100*um, n=50)
morpho.R = Cylinder(diameter=1*um, length=100*um, n=50)
# Passive channels
gL = 1e-4*siemens/cm**2
E... |
"""retriever.lib contains the core Data Retriever modules."""
|
#!/usr/bin/python -u
"""
test serial transfer between two devices
This module assumes two devices (e.g. FT232R based) are connected to the
host computer, with RX and TX of the two devices wired to each other so
they can communicate. It launches threads to send and receive traffic and
check that a random stream sent fr... |
#%%
from tensorflow.keras.applications.vgg16 import VGG16
from tensorflow.keras.applications.vgg16 import preprocess_input
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.callbacks import LearningRateScheduler
from tensorflow.keras.layers import Activation
from tensorflow.keras.layers import ... |
from io import BytesIO, BufferedIOBase
from math import ceil
from typing import List, Optional, Union
import emoji
import nonebot
from PIL import Image, ImageFont, ImageDraw
from nonebot.adapters.cqhttp.message import MessageSegment
from nonebot.log import logger
from pydantic import BaseModel
from .config import Con... |
#! /usr/bin/env python
import generator_test
import sys
if "--hwut-info" in sys.argv:
print "Pseudo Ambgiguous Post Condition: Part I"
print "CHOICES: ANSI-C-PlainMemory, ANSI-C, ANSI-C-CG, Cpp, Cpp_StrangeStream, Cpp-Template, Cpp-Template-CG, Cpp-Path, Cpp-Path-CG, ANSI-C-PathTemplate;"
print "SAME;"
... |
#Lane Carasik
#Last Modified: 12/15/2015
'''% if Pe <= 200
% Nu = 24.15*log10(-8.12 + 12.76*PtoD - 3.65*PtoD^2);
% else if Pe > 200
% Nu = 24.15*log10(-8.12 + 12.76*PtoD - 3.65*PtoD^2) ...
% + 0.0174*(1-exp(-6*(PtoD-1)))*(Pe-200)^0.9;
% end
% end'''
import numpy as np
def Nu(... |
from utils import CSVScraper
class GrandePrairieCountyNo1PersonScraper(CSVScraper):
csv_url = 'http://data.countygp.ab.ca/data/ElectedOfficials/elected-officials.csv'
|
import numpy as np
import matplotlib.pyplot as plt
import multiprocessing as mp
def color_dict(mpc_database):
orbit_color = [
"gold",
"red",
"dodgerblue",
"limegreen",
"grey",
"magenta",
"chocolate",
"blue",
"orange",
"mediumspringgre... |
# -*- coding: utf-8 -*-
#
# Copyright © 2009-2010 CEA
# Pierre Raybaut
# Licensed under the terms of the CECILL License
# (see guiqwt/__init__.py for details)
# pylint: disable=C0103
"""
guiqwt.histogram
----------------
The `histogram` module provides histogram related objects:
* :py:class:`guiqwt.histogram.His... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logforce_settings as settings
from logforce_db import db_fetch_many
def main():
sql = """
SELECT rail_car_id, car_number, sort_order FROM rail_car WHERE train_id = (
SELECT train_id FROM delivery_order WHERE delivery_order_id = 2964952
) ... |
import sys
if sys.version_info[0] >= 3 and sys.version_info[1] >= 6:
pass
else:
raise Exception("dynamic_plot: Python 3.6 or a more recent version is required.")
from .dynamic_plot import *
|
# -*- coding: utf-8 -*-
__all__ = ('Analysis',)
import attr
from .core import FileLocation
from .functions import ProgramFunctions
from .insertions import ProgramInsertionPoints
from .loops import ProgramLoops
from .project import Project
from .statements import ProgramStatements
@attr.s(slots=True, auto_attribs=Tr... |
# Takes 2 rasters: the first contains integer values defining groups of data (e.g., a rasterized shapefile)
# the second one contains values to group (e.g., slopes or elevation)
from lsdtt_xtensor_python import comparison_stats_from_2darrays as gpc
import numpy as np
# from matplotlib import pyplot as plt
#TODO add re... |
import torch
from torch import nn
from ..downstream_module import DownStreamModule
import torch.nn.functional as F
from .resnet_2d import ResNet2d
# Profile Net
class StretchNet(nn.Module):
def __init__(self, dropout):
super(StretchNet, self).__init__()
self.bilstm = nn.LSTM(20, 128, num_layers=1... |
import sys
class Graph():
def __init__(self, ver):
self.V = ver
self.graph = [[0 for column in range(ver)] for row in range(ver)]
def minDistance(self, dist, sptSet):
min = sys.maxsize
for u in range(self.V):
if dist[u] < min and sptSet[u] == False:
... |
import numpy as np
from typing import Callable, Sequence
from numbers import Number, Integral
from fractions import Fraction
def a_mu(mu: float):
return (1 - 2*mu + np.sqrt(1+4*mu**2))/2
if __name__ == '__main__':
mu = 0.0001
a = a_mu(mu)
A = np.array([
[1,0],
[0,1]
])
b... |
"""Module for Concept SPARQL-queries."""
from string import Template
def build_concepts_by_publisher_query() -> str:
"""Build query to count concepts grouped by publisher."""
return """
PREFIX dct: <http://purl.org/dc/terms/>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX skos: <http... |
# Copyright 2019, The TensorFlow Federated 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 o... |
# -*- coding: utf-8 -*-
from keras.models import load_model
from keras.optimizers import Adam, SGD
from keras import metrics
from keras.callbacks import ReduceLROnPlateau, EarlyStopping, ModelCheckpoint
from helpers import *
from keras_helpers import *
from base_cnn import AbstractCNN
class FullCNN(AbstractCNN):
... |
"""HTTP connection helpers"""
import os
import json
import socket
from urllib3.connection import HTTPConnection
import requests
from requests.auth import HTTPBasicAuth
from sap import get_logger, config_get
from sap.rest.errors import HTTPRequestError, UnexpectedResponseContent, UnauthorizedError, TimedOutRequestErr... |
# -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
"""
riko.modules.substr
~~~~~~~~~~~~~~~~~~~
Provides functions for obtaining a portion of a string.
You enter two numbers to tell the module the starting character position and
the length of the resulting substring. If your input string is "ABCDEFG", then
a From value... |
# 入力
Q = int(input())
x, d, n = (
zip(*(map(int, input().split()) for _ in range(Q))) if Q else
((), (), ())
)
MOD = 1000003
class ModInt:
def __init__(self, x):
self.x = x % MOD
def __str__(self):
return str(self.x)
__repr__ = __str__
def __add__(self, other):
retu... |
from kaikobittrex import Index
|
from math import *
au = 149600 # in million meters
''' Polar equation of an elliptical orbit with star at the origin
and the start being the smaller of the two foci
(i.e. start is the "left" focus):
r = p / (1 - e * cos(theta))
p is the semi latus-rectum
e is the eccentricity
'''... |
from random import *
n = 100
x0 = randint(-100, 100)
y0 = randint(-100, 100)
x1 = randint(-100, 100)
y1 = randint(-100, 100)
print n, x0, y0, x1, y1
for i in range(n):
x0 = randint(-100, 100)
y0 = randint(-100, 100)
x1 = randint(-100, 100)
y1 = randint(-100, 100)
print x0, y0, x1, y1
|
import os
from flask import Flask
import urllib.request
app = Flask(__name__)
url = os.getenv('URL', "it20.info")
@app.route("/")
def get_url():
with urllib.request.urlopen('http://' + url) as response:
html = response.read()
return html
if __name__ == '__main__':
app.run(host=os.getenv('IP', '0.... |
# opcode 1: 1 VARa VARb PTRc => *PTRc = VARa + VARb
# opcode 2: 2 VARa VARb PTRc => *PTRc = VARa * VARb
# opcode 3: 3 PTRa => *PTRa = input()
# opcode 4: 4 VARa => output(VARa)
# opcode 5: 5 VARa VARb => *PC = VARb if VARa != 0
# opcode 6: 6 VARa VARb => *PC = VARb if VARa == 0
#... |
from typing import Union
from loguru import logger
from sqlalchemy.dialects import postgresql
from .database import database
from .models import todos
from .schemas import TodoCreate, TodoUpdate
@database.transaction()
async def create(payload: TodoCreate) -> Union[int, None]:
logger.debug("payload: {}".format(... |
import numpy as np
import numpy.random as npr
import scipy as sc
from scipy import linalg
from operator import add
from functools import reduce, partial
from sds.utils.linalg import symmetrize
from sds.utils.general import Statistics as Stats
class _GaussianBase:
def __init__(self, dim, mu=None):
self... |
import sys
from cartomancy.brains.spaces.go_fish.actions import Actions
from cartomancy.engine.io.getch import getch
class GoFishHumanPolicy:
"""Human input policy for Go Fish.
When this policy is used, the user is asked
to for input to choose actions.
The rank_to_seek and player_to_ask method list ... |
import operator
from django.db.models import signals
from django.db.models.expressions import F, ExpressionNode
EXPRESSION_NODE_CALLBACKS = {
ExpressionNode.ADD: operator.add,
ExpressionNode.SUB: operator.sub,
ExpressionNode.MUL: operator.mul,
ExpressionNode.DIV: operator.div,
ExpressionNode.MOD:... |
'''
Gets values from special comments in the first 1024 bytes of the main script.
'''
import os
import re
import sys
import shlex
from argcomplete import USING_PYTHON2
from itertools import chain
if USING_PYTHON2:
from pipes import quote
else:
quote = shlex.quote
SEARCH_RANGE = 1024
INFO_PREFIX = 'CACHEDCOM... |
from cv_datalib.image import DataImage
import pandas as pd
from typing import List
class Split:
def __init__(self, name: str, images: List[DataImage]):
self.name = name
self.images = images
def __getitem__(self, index: int) -> DataImage:
return self.images[index]
def add_image(sel... |
from direct.directnotify import DirectNotifyGlobal
from direct.distributed.DistributedObjectUD import DistributedObjectUD
class DistributedLobbyManagerUD(DistributedObjectUD):
notify = DirectNotifyGlobal.directNotify.newCategory("DistributedLobbyManagerUD")
def announceGenerate(self):
DistributedObjec... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.