content stringlengths 5 1.05M |
|---|
#!/bin/python
import numpy as np
from graphviz import Digraph
from graphviz import Graph
import warnings
from utilities import get_accuracy, scale_output_0_1
import time
from optimizers import no_optimizer
class Layer:
def __init__(self, activation, bias, weights):
self.a = activation
self.b = bias
self.... |
from utils.email import add_outgoing_email
import logging
logger = logging.getLogger("bornhack.%s" % __name__)
def add_creditnote_email(creditnote):
# put formatdict together
formatdict = {"creditnote": creditnote}
subject = "BornHack creditnote %s" % creditnote.pk
# add email to outgoing email que... |
# Copyright (c) 2021 Friedt Professional Engineering Services, Inc
# SPDX-License-Identifier: MIT
import json
import io
import sys
from machotools.enums import *
from machotools.sections import *
class MachHeader(object):
def __init__(self, file):
# mach magic number identifier
self._magic = MHM... |
# coding=utf-8
"""
配置环境变量
"""
import os
import sys
import json
import logging, logging.handlers, logging.config
# 设定相关的路径地址
# 获取 BASE_DIR 也就是 server 所在的目录,所以需要做两次的 dirname
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
BASE_DIR = os.path.dirname(BASE_DIR)
# jobs 离线文件所在目录
JOBS_DIR = os.path.join(BASE_DIR, "jobs"... |
import logging
import os
import sys
from logging import handlers
from datetime import datetime
import uuid
class Logger():
def __init__(self, file, level, rollsize, backup, mode="a"):
logging.addLevelName(5, "TRACE")
self.logger = logging.getLogger()
self.logger.setLevel(level)
... |
def to_bool(str):
"""
Converts a given string to a boolean value. Leading and trailing
whitespace is ignored, so strings of whitespace are evaluated as
``False``.
"""
if str:
return bool(str.strip())
return False |
# vim:fileencoding=utf-8:noet
# (c) 2011 Michał Górny <mgorny@gentoo.org>
# Released under the terms of the 2-clause BSD license.
from .git_r3 import GitR3Support
class Git2Support(GitR3Support):
def __init__(self, *args, **kwargs):
kwargs['want_r2'] = True
GitR3Support.__init__(self, *args, **kwargs)
|
# -*- coding: utf-8 -*-
"""py.test fixtures."""
#------------------------------------------------------------------------------
# Imports
#------------------------------------------------------------------------------
from pytest import yield_fixture
#---------------------------------------------------------------... |
# -*- coding: utf-8 -*-
# Copyright 2016 CloudFlare, Inc. All rights reserved.
#
# The contents of this file are 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... |
"""
Access the table using SQL Alchemy core
user: postgres
password: postgres
"""
from sqlalchemy import create_engine, func
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
# connect to the database
engine = create_engine('postgres://postgres:postgres@localhost/red30')... |
"""
To decrease the complexity of building data pipelines for data engineers, an expert system or
business rules engine can be used to automatically build and configure a data pipeline based on
context variables, groomed metadata, and relevant rules.
"""
from __future__ import print_function
from builtins import objec... |
import src.frontend.utility.utility as utility
def parsing_error(parser, error_message=''):
ERROR_FALLBACK = 5
context_string = ''
if parser.count > ERROR_FALLBACK:
for i in range(ERROR_FALLBACK, 0, -1):
if parser.tokens[i].line == parser.current_line():
context_string += parser.token(i) + ' '
raise Excep... |
from gailtf.baselines.common.console_util import *
from gailtf.baselines.common.dataset import Dataset
from gailtf.baselines.common.math_util import *
from gailtf.baselines.common.misc_util import *
|
from django.urls import path
from sis_gastronomico.insumos.views import (
CreateInsumo,
DeleteInsumo,
ListInsumo,
UpdateInsumo,
)
app_name = "insumos"
urlpatterns = [
path("", ListInsumo.as_view(), name="index"),
path("create_insumo", CreateInsumo.as_view(), name="create_insumo"),
path("de... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 12 13:48:52 2018
@author: adrienauriol
"""
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 4 13:01:29 2018
@author: adrienauriol
"""
import numpy as np
import matplotlib.pyplot as plt
#####################################... |
# -*- coding: utf-8 -*-
'''
Design Decision Log
-------------------
1. I have decided to not use dews/dexml approach to field description as it
doesn't give good distinction between element and attribute. It is not a
problem when parsing a XML, but it is quite important for rendering and XSD
generation. The ... |
# Золотая подкова + Выигрышные номера тиража + предыдущий тираж к примеру 1600
def test_goldhorseshoe_winning_draw_numbers_for_previous_draw(app):
app.ResultAndPrizes.open_page_results_and_prizes()
app.ResultAndPrizes.click_game_goldhorseshoe()
app.ResultAndPrizes.click_winning_draw_numbers()
app.Re... |
import sqlite3
conn = sqlite3.connect('buddymove_holidayiq.sqlite3')
cur = conn.cursor()
cur.execute('SELECT * FROM review')
cur.fetchall()
cur.execute(
'SELECT "User Id" FROM review WHERE Nature >= 100 AND Shopping >= 100')
cur.fetchall()
|
#!/usr/bin/env python
# --------------------------------------------------------
# Tensorflow Faster R-CNN
# Licensed under The MIT License [see LICENSE for details]
# Written by Xinlei Chen, based on code from Ross Girshick
# --------------------------------------------------------
"""
Demo script showing detections... |
import cv2.cv2 as cv2
video = cv2.VideoCapture('./vid/eye.mp4')
while True:
ok, frame = video.read()
if not ok:
break
cv2.imshow("Original", frame)
key = cv2.waitKey(1)
if key == 27:
break
|
import time
import scipy.sparse
import numpy as np
from lightfm import LightFM
from lightfm.evaluation import precision_at_k
from lightfm.cross_validation import random_train_test_split
def select_n_users(X, n):
users = np.random.randint(X.shape[0], size=n)
Y = X[users, :].tocoo()
return scipy.sparse.csr... |
load(
"@io_bazel_rules_go//go:def.bzl",
"go_library",
)
def go_grpc_gateway_library(name, src):
basename = src[:-len(".proto")]
protoc_label = str(Label("@protobuf//:protoc"))
go_plugin_label = str(Label("@com_github_golang_protobuf//protoc-gen-go"))
grpc_gateway_plugin_label = str(Label("@com_github_g... |
from sqlite3 import Error
from createDB import create_connection, create_database, initialize_tables
from queries import QUERIES
from import_data import load_data
from console import *
import uuid
import os
import datetime
from dateutil import parser
import math
DEF_DIR = './database/'
DATABASE = DEF_DIR + 'stream.db... |
import numpy as np
def check_iod_format(fname):
iod_input_lines = get_iod_lines(fname)
number_of_lines = len(iod_input_lines["yr"])
confirmed_lines = 0
for line in range(number_of_lines):
year = iod_input_lines["yr"][line]
station = iod_input_lines["station"][line]
stations... |
#-----------------------------------------------------------------------------
# Runtime: 40ms
# Memory Usage:
# Link:
#-----------------------------------------------------------------------------
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type tar... |
# Generated by Django 2.1.3 on 2018-11-21 09:19
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('monsterapi', '0019_auto_20181121_1006'),
]
operations = [
migrations.AlterModelOptions(
name='monster',
options={'ordering':... |
import pygame, sys
import os
import random
player_lives = 3 #keep track of lives
score = 0 #keeps track of score
fruits = ['melon', 'orange', 'pomegranate', 'guava', 'bomb'] #entities in the game
# initialize pygam... |
"""
Original created by terryltang.
Modified by Wavky since 2018/2/8.
"""
import threading
class LoopyTimer(object):
"""Python equivalent of JavaScript setInterval function
Call a function after a specified number of seconds:
timer = LoopyTimer(5.0, handler_func, args=[], kwargs={})
... |
# Copyright (c) 2020 Cloudbase Solutions Srl
#
# 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 ... |
import commands
commands.start() |
from typing import List, Dict
from utils import solr_access, mongo_access, config
import csv
def get_alleles_from_file(file_path) -> Dict:
alleles = {}
with open(file_path) as f:
for row in csv.DictReader(f, skipinitialspace=True):
allele = {k: v for k, v in row.items()}
allel... |
import wx
import wx.lib.dialogs
import wx.stc as stc
import os
faces = {
'times': 'Times New Roman',
'mono': 'Courior New',
'helv': 'Arial',
'other': 'Comic Sans MS',
'size': 10,
'size2': 8,
}
class MainWindow(wx.Frame):
def __init__(self, parent, title):
self.dirna... |
"""
Asked in Google online challenge 2020
TODO: return max(maximum range of increasing subsequence of prime numbers in minarr, maxarr)
if a number is not prime, change it to nearest prime less or greater than that number and find the LIS
1<= N <=1000
1<= Ai <= 10^6
Example:
8, 7, 19, 1, 2
O/P: 2
Explanation:
2 - [1... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import datetime
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('councilmatic_core', '0008_bill_ocr_full_text'),
]
operations = [
migra... |
#!/usr/bin/env python3
from urllib.request import (urlopen, URLError)
from time import sleep
from threading import Thread
import argparse
import os
import subprocess
import sys
import re
def openfifo(filename):
try:
os.mkfifo(filename)
except:
os.remove(filename)
os.mkfifo(filename)
return open(fil... |
# -*- coding: utf-8 -*-
"""
feign geometry module
zs. elter 2019
"""
import math
import numpy as np
eps=1e-7
class Point(object):
"""
A class used to represent a Point.
Parameters
----------
x : float
x coordinate of Point in cm
y : float
y coordinate of Point in cm
Attri... |
'''Server for visualization.'''
#%%
from __future__ import (absolute_import, print_function, unicode_literals, division)
import json
import itertools
import numpy as np
from bokeh.layouts import column, gridplot
from bokeh.models import Button
from bokeh.palettes import Set1
from bokeh.plotting import figure, curdoc,... |
from itertools import count
import tempfile
import os
from collections import OrderedDict
import shutil
from migen.fhdl.namer import build_namespace
def vcd_codes():
codechars = [chr(i) for i in range(33, 127)]
for n in count():
q, r = divmod(n, len(codechars))
code = codechars[r]
whi... |
"""Mailgun Driver Module."""
import requests
from masonite.contracts.MailContract import MailContract
from masonite.drivers import BaseMailDriver
class MailMailgunDriver(BaseMailDriver, MailContract):
"""Mailgun driver."""
def send(self, message=None):
"""Send the message through the Mailgun service... |
import sys
import re
import pathlib
import random
from random import sample
from itertools import chain
import operator
from collections import defaultdict
import pickle
def save_model(model, file_name):
pickle.dump(model, open(file_name, "wb"))
def load_model(file_name):
try:
model = pickle.load(op... |
from rpy.robjects import r
def traceback():
r['traceback'](max_lines=10)
def func_lineno(func_name):
cmd = 'as.list(body({0}))'.format(func_name)
lines = str(r(cmd))
return lines
def trace(what, tracer, at):
cmd = 'trace("{0}",{1}, at={2})'.format(what, tracer, at)
r(cmd)
def untrace(what):
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from decimal import Decimal
class Migration(migrations.Migration):
dependencies = [
('promotions', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='p... |
from abc import abstractmethod
from typing import List, TYPE_CHECKING
from discordmenu.embed.base import Box
from discordmenu.embed.text import BoldText, Text
from discordmenu.embed.view import EmbedView
from tsutils.enums import LsMultiplier
from padinfo.common.emoji_map import get_awakening_emoji, get_emoji
from pa... |
import setuptools
import os
__version__ = None
with open(os.path.join(os.path.dirname(__file__), 'apgsa', 'version.py')) as f:
exec(f.read())
with open("README.rst", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="apgsa",
version=__version__,
author="Kelvin Gao",
author_email... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.weblogs, name='weblogs'),
#url(r'^/download/$', views.download, name='download'),
#url(r'^weblog/(?P<channel>[^, ]{1,200})/', views.channel, name='channel'),
url(r'^(?P<channel>[^, ]{1,200})/', views.channel, name="channel"),
] |
# Copyright (c) 2021, kavin and Contributors
# See license.txt
# import frappe
import unittest
class TestTSEmployeePayroll(unittest.TestCase):
pass
|
import os
import sys
import unittest
import random
import datetime as dt
from openpyxl import Workbook, load_workbook
BASE_DIR = os.path.abspath(os.pardir)
path = os.path.join(BASE_DIR,'ma_option_vol')
sys.path.append(path)
from data_workbooks import Data_WorkSheet, Merger_Sample_Data
import update_excel_workbooks as... |
# http://github.com/timestocome
#
# load in data from finance.yahoo.com
# match dates
# 1985-2107 Nasdaq, Dji, S&P
# saves opening price, volume for each day market is open
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# pandas display options
pd.options.display.max_rows = 100
pd.option... |
from glob import glob
import sys
import pandas as pd
import numpy as np
from loguru import logger
from genomepy.annotation import query_mygene
from genomepy import Genome
__version__ = "0.1.0"
FMTS = {
"kallisto": (
["length", "eff_length", "est_counts", "tpm"],
["tpm", "est_counts", "eff_lengt... |
import jsbsim
import airsim
import os
import time
from typing import Dict, Union
import jsbsim_properties as prp
from jsbsim_aircraft import Aircraft, cessna172P, x8
import math
"""Initially based upon https://github.com/Gor-Ren/gym-jsbsim/blob/master/gym_jsbsim/simulation.py by Gordon Rennie"""
class Si... |
from html import unescape
# https://docs.python.org/3/library/types.html#types.SimpleNamespace
# let's us construct an object from a dict
from types import SimpleNamespace
from .utilities import strip_prefix, PORTAL_STATUSES
class Course(SimpleNamespace):
def __repr__(self):
return "{} {} {}".format(se... |
import csv
import datetime
writer = csv.writer(open('report_out.csv', 'w'))
fmt1 = '%m/%d/%y %H:%M:%S'
with open('report.csv') as csvfile:
reader = csv.reader(csvfile)
# first row
for i, row in enumerate(reader):
# Service, Operation, UsageType, Resource, StartTime, EndTime, UsageValue
... |
#!/usr/bin/env python
####################################################################################
### Copyright (C) 2015-2019 by ABLIFE
####################################################################################
####################################################################################
###... |
from logging.handlers import DatagramHandler
from .asyncronous import AsyncWrapperHandler
from ..formatters import logstash
class UDPLogstashHandler(DatagramHandler):
"""Logging handler for Logstash over UDP."""
def __init__(
self, host, port=5959, message_type="logstash", fqdn=False, service_name=N... |
__author__ = "Xinqiang Ding <xqding@umich.edu>"
__date__ = "2019/11/04 17:27:27"
import numpy as np
import torch
torch.set_default_dtype(torch.double)
import math
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rc('font', size = 16)
mpl.rc('axes', titlesize = 'large', labelsize = 'large')
mpl.rc('xtick', ... |
# coding: utf-8
# In[1]:
import sys
from utils import *
import numpy as np
import argparse
import os
import pickle
import cv2
from tqdm import tqdm
from loader import TestLoader
sys.path.append('../')
from train.model import P_Net,R_Net,O_Net
import train.config as config
from detection.detector import Detector
fro... |
#!/usr/bin/env python
# -*-coding:utf-8 -*-
'''
@File : target.py
@Time : 2021/05/27 12:46:26
@Author : Xin Dong
@Contact : xindong9511@gmail.com
@License : (C)Copyright 2020-2021, XinDong
'''
# from multiprocessing import Process, Pool
import os
import scipy
import numpy as np
import pandas as pd
imp... |
from .validator import RequiredMixin
from uuid import UUID as pyUUID
class UUID(RequiredMixin):
def __assert_uuid(self, data, attribs):
if data is None:
return self.validation_success(data)
try:
return self.validation_success(pyUUID(data))
except Exception:
... |
from learnz.ml.data import read_libsvm
# Read data for using in training and testing
data_train = read_libsvm("learnz/examples/data/perceptron_train")
data_test = read_libsvm("learnz/examples/data/perceptron_test")
from learnz.ml.models import Perceptron
model = Perceptron()
# Define hyperparamter ranges
hyperparame... |
import glob
import os
import shutil
import unittest
from collections import Counter
from typing import Dict, Optional
import mock
import pytest
from demisto_sdk.commands.common.constants import (
DEFAULT_CONTENT_ITEM_TO_VERSION, FileType)
from demisto_sdk.commands.common.handlers import JSON_Handler
from demisto_... |
#!/usr/bin/python3
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name='zbxtpltools',
version='0.1.4',
author="Robin Roevens",
author_email="Robin.Roevens@disroot.org",
description="Export/Import Zabbix templates to/from GIT repository",
... |
score = []
for i in range(5):
temp = list(map(int,input().split()))
score.append(sum(temp))
# y = index, x = score
y = score.index(max(score))
x = max(score)
temp = score
temp.sort()
temp.reverse()
if temp[0] != temp[1]:
print(y+1,x)
|
# Copyright 2016 The TensorFlow 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 applica... |
import json
def handler(event, context):
"""
FunctionA in leaf template
"""
return {"statusCode": 200, "body": json.dumps({"hello": "world"})}
|
import pprint
import json_eval
import collections
import z3
class SymbolicJSON(object):
def __init__(self, context):
self.context = context
self.base_types = {}
self.bool_sort = None
self.sumbool_sort = None
self.unit_tt = None
self.last_option_type = None
def s... |
import unittest
from myapp.utils.utilidades import Util, DisplayablePath, MyClone, MyEncoder
import os.path
import git
from myapp.services.check_commits import CheckCommits
class TestCheckCommits(unittest.TestCase):
def setUp(self):
self.git_url = "https://github.com/mining-software-repositories/sysrepomsr... |
import unittest
class TestKafkaProducerConfig(unittest.TestCase):
pass
|
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn import tree
from sklearn.metrics import classification_report
# from sklearn.multiclass import OneVsRestClassifier
# Matplotlib中文显示问题
# plt.rcParams['font.family'] = 'simhei'
# plt.rcParams['axes.unicode_minus'] ... |
# wxPython
import wx
import wx.lib.agw.floatspin
# BeatDown
from .constants import * # noqa
from .utils import * # noqa
class MidiNoteTextCtrlProxy(object):
def __init__(self, wrapped):
self.__dict__['_wrapped'] = wrapped
def _unwrap(self):
return self._wrapped
def GetValue(self):
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 15 13:35:23 2018
@author: Victor Onink
Here we create a figure that has the 24h and the 3h densities
for the North Atlantic
"""
import numpy as np
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
from scipy import io
import pandas as pd
def AreaC... |
import time
from collections import OrderedDict
from malcolm.core import Spawnable, Loggable
from malcolm.core.vmetas import BooleanMeta, TableMeta
from malcolm.compat import queue
from malcolm.parts.pandabox.pandaboxblockmaker import PandABoxBlockMaker
from malcolm.parts.pandabox.pandaboxtablepart import PandABoxTabl... |
import django_admin_relation_links
from authtools import admin as authtools_admin
from django.contrib import admin
from rangefilter.filter import DateRangeFilter
from solo.admin import SingletonModelAdmin
from ..profiles import models as profiles_models
from . import models
@admin.register(models.User)
class UserAdm... |
#!/usr/bin/python3
import sqlite3
import json
import threading
import requests
import urllib3
import datetime
import time
import asyncio
import tornado.autoreload
from tornado.concurrent import run_on_executor
from concurrent.futures import ThreadPoolExecutor
import sys
sys.path.append('./web/control/')
sys.path.appen... |
if __name__ == '__main__':
score_name = {}
scores = set()
for _ in range(int(input())):
name = input()
score = float(input())
if str(score) in score_name:
score_name[str(score)].append(name)
else :
score_name[str(score)] = [name]
scores.add(sco... |
class Solution:
# @param A : list of integers
# @param B : integer
# @return an integer
def solve(self, A, B):
n = len(A)
table = []
left = 0
for i, num in enumerate(A) :
if len(table) > 0 :
table[-1][2] = i-1
if num % 2 == 1 :
... |
import numpy as np
import itertools
import sys
import os
import random
import copy
import scipy
import time
import pandas as pd
import pickle
import qmla.exploration_strategies.genetic_algorithms.genetic_exploration_strategy
from qmla.exploration_strategies.genetic_algorithms.genetic_exploration_strategy import (
... |
import logging
log = logging.getLogger(__name__)
import requests
import requests.exceptions
import plugins.streams
def make_twitch_stream(data):
channel_data = data.get("channel", {})
channel = channel_data.get("name", "").lower()
title = channel_data.get("status", "")
game = data.get("game")
r... |
'''
Classes for observing property changes on objects.
'''
from __future__ import with_statement
from contextlib import contextmanager
from collections import defaultdict
from util.introspect import funcinfo
from util.primitives.refs import better_ref as ref
from weakref import ref as weakref_ref
from peak.util.import... |
# Be able to call directly such as `python test_annotators.py`
try:
from .context import loctext
except SystemError: # Parent module '' not loaded, cannot perform relative import
pass
from pytest import raises
from loctext.util import PRO_ID, LOC_ID, REL_PRO_LOC_ID, repo_path, UNIPROT_NORM_ID, GO_NORM_ID
from... |
from accounts.models import Profile
from django.shortcuts import redirect, render
from django.contrib.auth.models import User
from django.contrib import messages
from .models import *
import uuid
from django.conf import settings
from django.core.mail import send_mail
from django.contrib.auth import authenticate,login
f... |
import collections
import contextlib
import logging
from itertools import chain, groupby
import operator
from configuration.models import Project, Institution, Configuration
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.exceptions import ValidationError
... |
# This module, via find_functions(), takes in a cfml/lucee source file string and
# returns a python list containing tuples of the function name and a map of data
# about the function.
# The structure looks like this:
# [
# ("function_name", {
# "access": "public/private/etc",
# "returntype": "any/st... |
from __future__ import absolute_import as _absolute_import
from pkg_resources import get_distribution as _get_distribution
from pkg_resources import DistributionNotFound as _DistributionNotFound
try:
__version__ = _get_distribution('limix_tool').version
except _DistributionNotFound:
__version__ = 'unknown'
d... |
class mossbauer_sample_set:
def __init__(self):
self._sample_name = None
self._dana_group = None
self._group_folder = None
self._weight = None
self._is_post = None
self._perc_comp = None
self._url = None
|
from unittest.mock import patch
import os
import pytest
from pypsi.shell import Shell
from pypsi.core import Command
class PypsiTestCommand(Command):
CHOICES = ['run', 'me', 'now']
def run(self, shell, args):
return 0
def complete(self, shell, token, prefix):
return [choice for choice in... |
"""
byceps.events.guest_server
~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from dataclasses import dataclass
from typing import Optional
from ..services.guest_server.transfer.models import ServerID
from ..typing import PartyID, User... |
# -*- coding: utf-8 -*-
# --------------------------------------------------------
# RefineDet in PyTorch
# Written by Dongdong Wang
# Official and original Caffe implementation is at
# https://github.com/sfzhang15/RefineDet
# --------------------------------------------------------
import torch
import torch.nn as nn
... |
#!/usr/bin/python
# Filename: ex_local.py
x = 50
def func(x):
print('x is ', x)
x = 2
print('Changed local x to ', x)
func(x)
print('Value of x is ', x)
|
import responses # https://github.com/getsentry/responses
from datacrunch.instance_types.instance_types import InstanceTypesService, InstanceType
TYPE_ID = "01cf5dc1-a5d2-4972-ae4e-d429115d055b"
CPU_DESCRIPTION = "48 CPU 3.5GHz"
NUMBER_OF_CORES = 48
GPU_DESCRIPTION = "8x NVidia Tesla V100"
NUMBER_OF_GPUS = 8
MEMORY_... |
"""Tensorflow datasets for paccmann."""
import os
import logging
import tensorflow as tf
logger = logging.getLogger('datasets')
# TFRecords metadata.
DATASETS_METADATA = {
'smiles_character_tokens': tf.FixedLenFeature((158), tf.int64),
'smiles_atom_tokens': tf.FixedLenFeature((155), tf.int64),
'fingerprin... |
from uuid import uuid4
from django.db import models
from FreeChart.settings import AUTH_USER_MODEL
class Board(models.Model):
class Meta:
db_table = 'board'
verbose_name = 'board'
owner = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True)
parent = models.ForeignKey('se... |
"""
Crie um programa que tenha uma tupla única com nomes de produtos
e seus respectivos preços, na sequência. No final, mostre uma
listagem de preços, organizando os dados em forma tabular.
"""
|
# This Python program displays day of week
#
# by Aleksander Rohozinski
# Febuary 16, 2022
# ICS 2O - Ashbury College
# Mr. Giansante
# -------------------------------------------------------
print(" ______ ___ _ __ ____ ____ __ ")
print("|_ _ ... |
import re
class IPv4:
def __init__(self, segment1, segment2, segment3, segment4):
self.segment1 = segment1
self.segment2 = segment2
self.segment3 = segment3
self.segment4 = segment4
def print_ip(self):
print("{0}.{1}.{2}.{3}".format(self.segment1, self.segment2,
... |
"""Tests for the cases controllers"""
from flask import Flask, url_for
from scout.server.extensions import store
from scout.server.blueprints.cases.controllers import case, case_report_content
def test_case_report_content(adapter, institute_obj, case_obj, variant_obj):
adapter.case_collection.insert_one(case_obj... |
from PyQt4.QtGui import *
app = QApplication([])
win = QWidget()
win.show()
app.exec_()
|
import pandas as pd
from dagster import ModeDefinition, execute_pipeline, io_manager, pipeline, solid
from docs_snippets.concepts.assets.materialization_io_managers import (
PandasCsvIOManager,
PandasCsvIOManagerWithAsset,
)
class DummyClass(pd.DataFrame):
def to_csv(self, _path): # pylint: disable=argu... |
# Copyright 2020 - Nokia Software.
#
# 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 a... |
import rlp
from eth_utils import (
keccak,
to_checksum_address,
to_bytes
)
from brownie import (
network,
accounts,
config,
interface,
Contract,
FuzzyIdentityChallenge,
FuzzyIdentityAttack,
)
from scripts.helpful_scripts import (
get_account,
get_challenge_contract,
... |
import sqlite3
from sqlite3 import Error
import pandas as pd
def create_connection(db_file):
""" create a database connection to the SQLite database
specified by db_file
:param db_file: database file
:return: Connection object or None
"""
try:
conn = sqlite3.connect(db_file)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.