content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012-2018 Snowflake Computing Inc. All right reserved.
#
import base64
import json
import logging
import os
import sys
from logging import getLogger
from os import path
from time import gmtime, strftime, time
from datetime import datetime
from asn1crypto ... |
"""This module defines an indenter class that handles indentation
levels for automatic code generation. It also defines other
miscellaneous classes useful for the tvtk code generation.
"""
# Author: Prabhu Ramachandran
# Copyright (c) 2004-2015, Enthought, Inc.
# License: BSD Style.
import re
# Local imports (ther... |
import torch
import torch.nn as nn
from rl_replicas.common.policies.policy import Policy
class DeterministicPolicy(Policy):
"""
The deterministic policy
:param network: (nn.Module) The network.
:param optimizer: (torch.optim.Optimizer) The optimizer.
"""
def __init__(self, network: nn.Modul... |
from tqdm import tqdm
from collect_master import run_cmd, ssh_run, n_machines
if __name__ == "__main__":
for i in tqdm(range(n_machines)):
print(i)
host_name = f"c44X_{i:02d}"
run_cmd(f"scp -o StrictHostKeyChecking=no {host_name}:tvm-cost-model/scripts/dataset_part_*.zip .")
|
# Copyright (c) 2019 Intel Corporation
#
# 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 use, copy, modify, merge, publish, d... |
# Copyright (c) 2020. All rights reserved.
from abc import ABCMeta, abstractmethod
import asynctest # type: ignore
from io import StringIO
import os
import tempfile
from typing import Dict
import unittest
import yaml
from addrservice.database.addressbook_db import (
AbstractAddressBookDB, InMemoryAddressBookDB, ... |
#!/usr/bin/env python
###############################################################################
# Copyright 2017 The Apollo 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 ... |
# Copyright 2018 Google LLC.
#
# 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,
# this list of conditions and the following disclaimer.
#
#... |
import logging
import signal
import sys
from enum import Enum, auto
from multiprocessing import Pool
from pathlib import Path
from typing import Any, Optional, Union, Tuple
import attr
import click
from kipro2.incremental_bmc.incremental_bmc import IncrementalBMC
from kipro2.k_induction.incremental_k_induction import... |
def solve(th, tc, t):
ans = 0
if th == t:
ans = 1
elif 2*t <= th + tc:
ans = 2
else:
k = (th - tc)/(2*t - th - tc)
if (th - tc)%(2*t - th - tc) == 0:
if k%2 == 0:
ans = int(k)+1
else:#k%2 == 1
ans = int(k)
el... |
# -*- coding: utf-8 -*-
import torch
import torch.nn as nn
import torch.nn.functional as F
class Critic(nn.Module):
def __init__(self, state_size, action_size, seed):
super(Critic, self).__init__()
self.seed = torch.manual_seed(seed)
self.bn0 = nn.BatchNorm1d(state_size)
... |
# Test Case 2
# Overriding Declared Local Variable
i = 10
for i in range(0,3): # Here i is overridden
print i
print i |
from os import path, getenv
CONFIGFILE_PATH_DEFAULT = path.expanduser(path.join("~", ".jissue"))
class ConfigurationError(Exception):
pass
class Configuration(object):
def __init__(self):
self.jira_fqdn = ''
self.confluence_fqdn = ''
@classmethod
def get_filepath(cls):
retu... |
# to jest komentarz
import pgzrun
WIDTH = 474
HEIGHT = 842
def draw():
screen.blit("background.jpeg", (0,0))
pgzrun.go()
|
#!/usr/bin/env python3
import warnings
from logging import Logger, getLogger
from typing import Any, Dict, Optional, cast
from graphql import (
build_ast_schema,
build_client_schema,
get_introspection_query,
parse,
)
from graphql.language.ast import DocumentNode
from graphql.type.schema import GraphQL... |
# coding=utf-8
from django.db import models
class MachineOperationsInfo(models.Model):
number = models.IntegerField(default=0, verbose_name=u'操作序号')
person = models.CharField(default='', max_length=20, verbose_name=u'操作人用户名')
time = models.DateTimeField(auto_now=True, auto_now_add=False, verbose_name=u'操作... |
#!/usr/bin/python
# coding: utf8
from __future__ import absolute_import
from geocoder.google import GoogleResult, GoogleQuery
from geocoder.location import Location
class GoogleReverseResult(GoogleResult):
@property
def ok(self):
return bool(self.address)
class GoogleReverse(GoogleQuery):
"""
... |
# follow pep-386
# Examples:
# * 0.3 - released version
# * 0.3a1 - alpha version
# * 0.3.dev - version in developmentv
__version__ = '0.7.dev'
__releasedate__ = ''
|
# Importing the necessary packages
import argparse
from detector import MaskDetection
import cv2
# Constructing the argument parser
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True,
help="path to input image")
args = vars(ap.parse_args())
image = cv2.imread(args['image'])
detector = ... |
from lib.util import get_info_by_cookie, insert_to_db
__host = "mihanblog.com"
__sess = "s_id="
def parse(headers):
tmp = get_info_by_cookie(["s_id"], headers)[0]
name = str(tmp[:tmp.find("%7C")])
if name is None:
return False
insert_to_db("Mihanblog", headers, name,
"http://mihanblog.com... |
# Erstellen einer Klasse "Stack", welche von Außen nicht zugänglich ist
class Stack:
def __init__(self): #1
self.__content = []
def push(self, item): #2
self.__content = [item] + self.__content
def top(self): # wenn Liste nicht leer ist, wird ihr Inhalt... |
from datetime import datetime
import unittest
from birthday import *
class TestBirthday(unittest.TestCase):
def test_birthday_counter(self):
#self.assertEqual(birthday_counter("10-31-1948"), 100)
# will fail on October 31
self.assertTrue(birthday_counter("10-31-1948") > 0)
# w... |
from githubissuesbot import command_line
command_line.main()
|
import io
import logging
import math
import random
import re
from PIL import Image
import cv2
import lmdb
import numpy as np
import torch
from torch.utils.data import Dataset
from torchvision import transforms
from transforms import CVColorJitter, CVDeterioration, CVGeometry
from utils import CharsetMapper, onehot
... |
"""
Module:
test_board_class.py
This module contains tests for:
tictactoepy.board_class.py
"""
import pytest
from tictactoepy.board_class import Board
def test_get_players():
"""Testing the print dunder of a Board object"""
my_board = Board()
str1 = " _1_ _2_ _3_ \n"
str2 = "1|___|___|___|\n"
... |
import seaborn as sns
sns.set_style('whitegrid')
import numpy as np
import logging
logging.basicConfig(level=logging.DEBUG)
from dataset.sequence import NumberSequence, CharacterSequence, SingletonSequence
from dataset.batch import WindowedBatcher
import cPickle as pickle
import dataset
from deepx.optimize import RMSP... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.AttachmentExplainBean import AttachmentExplainBean
from alipay.aop.api.domain.SpecifyAttachmentInfo import SpecifyAttachmentInfo
class ConfigInfoBean(object):
def __init__(se... |
from math import inf
from django.db import models
from django.apps import apps
from django.contrib.auth.models import AbstractUser, UserManager
from django.db.models import Sum
from django.db.models.functions import Coalesce
from django.utils.functional import cached_property
from accounts import signals
from base.mo... |
"""
ldapurl - handling of LDAP URLs as described in RFC 4516
See http://www.python-ldap.org/ for details.
\$Id: ldapurl.py,v 1.80 2016/07/30 16:18:47 stroeder Exp $
Python compability note:
This module only works with Python 2.0+ since
1. string methods are used instead of module string and
2. list comprehensions ar... |
# -----------------------------------------------------------------------------
# CodeSignal Company Problem - Instacart - Busy Holidays
# https://app.codesignal.com/company-challenges/instacart/ZFhDcuS6BuDmhLBNN
# RUNTIME: 40-44ms
# MEMORY USED: 12.3MB
# ---------------------------------------------------------------... |
# view takes the request and sends back the http response
from django.http import HttpResponse
from django.template import loader
from django.shortcuts import render
from .models import User_Message
from .TF_Data import Bot_Response
def index(request):
#you dont need to provide templates path in directory
... |
from flask import Flask, jsonify, request
from unicode_write.inverted_index import InvertedIndex, LevenshteinRankingInvertedIndex
from unicode_write.utils import get_unicode_mapping, stem, get_emojis, merge_mappings, UnicodeWriter, get_cache_path
names = get_unicode_mapping()
emojis = get_emojis()
mapping = merge_map... |
# (c) Copyright IBM Corporation 2020.
# LICENSE: Apache License 2.0 (Apache-2.0)
# http://www.apache.org/licenses/LICENSE-2.0
from statistics import mean
from sklearn.neighbors import NearestNeighbors
from lrtc_lib.active_learning.batch_measure_api import BatchScorerApi
class DiversityCalculator(BatchScorerApi):
... |
"""
String utilities.
"""
import random
import string
def base_n_str_from_number(number, base, digits='0123456789abcdefghijklmnopqrstuvwxyz'):
"""
Express the value of 'number' as a string in base 'base'.
Based on http://code.activestate.com/recipes/65212/ (sebastianjb).
"""
if base < 2 or base... |
# -*- coding: utf-8 -*-
_author_ = 'Pylar'
from flask import Flask,render_template,session,redirect,url_for,flash
from flask_script import Manager,Shell
from flask_bootstrap import Bootstrap
from datetime import datetime
from flask_moment import Moment
from flask_wtf import Form
from wtforms import StringField,SubmitFi... |
import os
import json
import time
from google.cloud import pubsub_v1
from google.cloud import bigquery
subscriber = pubsub_v1.SubscriberClient()
# The `subscription_path` method creates a fully qualified identifier
# in the form `projects/{project_id}/subscriptions/{subscription_name}`
subscription_path = subscriber.s... |
import numpy as np
from agd.seal.seal import Evaluator, Ciphertext, CKKSEncoder, \
GaloisKeys, RelinKeys
def acg_qp(Q: np.ndarray, p: np.ndarray, beta: float, alpha: float, n: int, x0: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
def f(x): return x.T.dot(Q).dot(x) + p.dot(x)
def df(x): return Q.dot(x) + p... |
from decimal import Decimal
import pytest
from kandelero.candlestick import Candlestick
from kandelero.patterns.comparators import is_inverted_hammer
@pytest.mark.happy_path
@pytest.mark.parametrize(
"obj",
[
Candlestick(
open=Decimal("14672.60000"),
high=Decimal("14675.80000... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='CalendarProvider',
fields=[
('id', models.AutoF... |
"""Users Views."""
from http import HTTPStatus
from typing import Tuple
from flask import current_app
from flask_restx import Resource
from app.api.users.serializers import (
user_base_model,
user_create_model,
user_created_model_response,
users_list_model_response,
users_ns,
users_parser,
)
... |
# import cv2
# def render(env, scale):
# frame = env.render(mode='rgb_array')
# if frame is not None:
# h, w, c = frame.shape
# frame = cv2.resize(frame, dsize=(int(w*scale), int(h*scale)), interpolation=cv2.INTER_CUBIC)
# return frame |
# Demo Python Dictionaries - Dictionary
'''
Nested Dictionaries
A dictionary can also contain many dictionaries, this is called nested dictionaries.
Or, if you want to nest three dictionaries that already exists as dictionaries.
'''
# Create three dictionaries, than create one dictionary that will contain the other... |
"""
pid_control
- Beard & McLain, PUP, 2012
- Last Update:
2/6/2019 - RWB
"""
import sys
import numpy as np
sys.path.append('..')
class pid_control:
def __init__(self, kp=0.0, ki=0.0, kd=0.0, Ts=0.01, sigma=0.05, limit=1.0, throttle_flag=False):
self.kp = kp
self.ki = ki
sel... |
#!/usr/bin/env python
"""
Copyright (c) UChicago Argonne, LLC. All rights reserved.
See LICENSE file.
"""
# -------------------------------------------Imports-------------------------------------------------------------------#
from __future__ import unicode_literals
import PyQt5.QtCore as qtCore
import PyQt5.QtWidget... |
# Copyright 2020 OpenRCA 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 in writi... |
#!/usr/bin/env python
# Copyright 2016-2019 Biomedical Imaging Group Rotterdam, Departments of
# Medical Informatics and Radiology, Erasmus MC, Rotterdam, The Netherlands
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obt... |
from setuptools import setup
from traitschema import __version__
with open("README.rst", 'r') as f:
README = f.read()
setup(
name="traitschema",
version=__version__,
description="Serializable schema using traits",
long_description=README,
url="https://github.com/mivade/traitschema",
author... |
# 01 - Crie um programa que gerencie o aproveitamento de um jogador de futebol. O
# programa vai ler o nome do jogador e quantas partidas ele jogou. Depois vai ler a
# quantidade de gols feitos em cada partida. No final, tudo isso será guardado em um
# dicionário, incluindo o total de gols feitos durante o campeonato.
... |
"""
Stand alone samples for IXN package functionality.
Setup:
Two IXN ports connected back to back.
@author yoram@ignissoft.com
"""
import sys
from os import path
import unittest
import logging
import time
from ixnetwork.ixn_app import init_ixn
from ixnetwork.ixn_statistics_view import IxnPortStatistics, IxnTraffic... |
# Copyright (c) 2015 OpenStack Foundation.
# 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... |
# @Author: Manuel Rodriguez <valle>
# @Date: 2019-05-05T20:01:27+02:00
# @Email: valle.mrv@gmail.com
# @Last modified by: valle
# @Last modified time: 2019-05-10T01:31:33+02:00
# @License: Apache License v2.0
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
fr... |
#!/usr/bin/env python
# Tensorflow impl. of GoGAN
from common import *
from datasets import data_celeba, data_mnist
from models.celeba_models import *
from models.mnist_models import *
from eval_funcs import *
def train_gogan(data, g_net, d_net, name='GoGAN',
dim_z=128, n_iters=1e5, lr=1e-4, batch_si... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
###########################################################################
#
# convert_xml.py
#
# This takes an XML file with xml:lang attributes and text in
# some orthography, and converts it to use English ARPABET symbols
# for speech processing. (Provided, of course... |
# -*- coding: utf-8 -*-
from .io import pickle_dump, pickle_load, write_log, format_filename
from .data_loader import load_data |
import threading
from tobii.eye_tracking_io.mainloop import (Mainloop, MainloopThread)
from tobii.eye_tracking_io.browsing import (EyetrackerInfo)
from tobii.eye_tracking_io._native import tetio
class EyetrackerCreatedCallbackHandler:
def __init__(self, mycls, callback, *args, **kwargs):
self.eyetracke... |
from django.conf.urls import url
from order.views import OrderCreateView, OrderUpdateRetrieveDeleteView, OrderListView, OrderListByDriverView, OrderListByTruckView
app_name = 'order'
urlpatterns = [
url(r'create',
OrderCreateView.as_view({'post': 'create'}),
name='order_create'),
url(r'(?P<pk... |
def scale(oriimg, imgScale):
newX,newY = oriimg.shape[1]*imgScale, oriimg.shape[0]*imgScale
newimg = cv2.resize(oriimg,(int(newX),int(newY)))
return newimg
def imshow(title, img):
cv2.waitKey(1)
cv2.imshow(title, img)
def showImage(img):
imshow('img', img)
def destroyWindowOnKey():
cv2.de... |
"""
=============
=============
"""
from flask import Blueprint
api = Blueprint('mock_api_v1', __name__)
@api.route('/')
def hello():
return 'Hello World'
|
from django.apps import AppConfig
class BattleReportConfig(AppConfig):
name = 'battle_report'
|
import torch.nn as nn
import models.head.yolov5_head as yolov5_head
from models.backbone.CSPdarknet53.cspdarknet53 import CSPDarkNet
import models.backbone.CSPdarknet53.neck as neck
import models.loss.yolo_loss_baseline_module as loss
from utils.logger import print_logger
from models.layer.layer_fundation import Conv2d... |
# Generated by Django 3.0.5 on 2021-04-10 16:44
from django.db import migrations, models
import wzrd.media.utils
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Media',
fields=[
('... |
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import numpy as np
import vaex
from .tasks import Task, TaskMapReduce
from .utils import _parse_f
import six
def _asfloat(a):
if a.dtype.type == np.float64 and a.strides[0] == 8:
return a
else:
return a.astype(np.float64, ... |
drinkTemp = 40
chillByC = 8
coolingAttempt = 0
drinkToHot = True
while drinkTemp > 10:
print (f"Drink too hot to drink @ {drinkTemp}C")
# Cool the beverage
drinkTemp = drinkTemp - chillByC
# Count how many times we have to chill the drink
coolingAttempt = coolingAttempt + 1
print(f"Drink drink @ {... |
import numpy as np
import matplotlib.pyplot as plt
def logDivision(start, end, nvertices):
vertices = np.zeros(nvertices)
for idx in range(nvertices):
vertices[idx] = np.exp(idx / (nvertices - 1.0) * np.log(end-start+1.0)) - 1.0 + start
return vertices
sample1 = [0.0029774214492784834, 0.0012545... |
# _*_ coding:utf-8 _*_
from django.conf.urls import url
from . import views
urlpatterns = [
# 教师列表页
url('^list/$', views.TeacherListView.as_view(), name="list"),
# 讲师详情页
url(r'^detail/(?P<teacher_id>\d+)/$', views.TeacherDetialView.as_view(),
name="detail"),
]
|
import pytest
try:
from airflow_dbt_python.hooks.dbt_s3 import DbtS3Hook
except ImportError:
pytest.skip(
"S3Hook not available, consider installing amazon extras",
allow_module_level=True,
)
def test_get_dbt_profiles(s3_bucket, tmpdir, profiles_file):
"""Test pulling dbt profile from... |
#!/usr/bin/env python3
import argparse
import json
import sys
r"""
Validates the PEL message registry JSON, which includes checking it against
a JSON schema using the jsonschema module as well as doing some extra checks
that can't be encoded in the schema.
"""
def check_duplicate_names(registry_json):
r"""
... |
# Generated by Django 2.2.1 on 2019-07-09 05:51
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('base', '0024_auto_20190705_1748'),
]
operations = [
migrations.DeleteModel(
name='SponsorEvent',
),
]
|
from torch import nn as nn
from components.model.base_model import BaseSeq2SeqModel
from components.model.utils import sum_bidirectional_state
from components.utils.tensors import cuda_if_gpu
from components.model.modules.encoders import EncoderGRU
from components.model.modules.decoders import DecoderGRUSoftAttnBahd
f... |
# https://github.com/dvlab-research/Parametric-Contrastive-Learning/blob/main/LT/losses.py
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from .registry import register
@register("proto_moco")
class PrototypicalMOCO(nn.Module):
def __init__(self, alpha):
self.alph... |
import os
import random
import torch
import numpy as np
import glob
import pandas as pd
import cv2
from PIL import Image
from torch.utils.data import Dataset
from torchvision import transforms
import torch.nn.functional as F
def get_transforms(size=500, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]):
return ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
import re
import scrape_common as sc
def get_latest_bl_bulletin_url():
return get_all_bl_bulletin_urls()[0]
def get_all_bl_bulletin_urls():
news_url = 'https://www.baselland.ch/politik-und-behorden/direktionen/volkswirtschafts-und... |
# This config is used to generate long-term feature bank.
_base_ = ['../_base_/models/slowonly_r50.py']
# model settings
lfb_prefix_path = 'data/ava/lfb_half'
dataset_mode = 'train' # ['train', 'val', 'test']
model = dict(
roi_head=dict(
shared_head=dict(
type='LFBInferHead',
lfb_... |
from docx import Document
from .Observers import (
HighlightColor,
FontColor,
Bold,
Italic,
UpperCase,
LowerCase,
Underline,
)
from .biotools import string_is_sequence
class CrazydocParser:
"""Parser to translate MS-docx documents to Biopython records.
Examples:
---------
... |
from scipy.interpolate import splrep
from scipy.interpolate import splev
import scipy.interpolate
from numpy import pi
x = np.linspace(0, 6*np.pi, 100)
y = 5 * np.sin(x+pi/3) + 3 * np.random.random(size=x.shape)
plt.plot(x,y, 'o--')
#print(x)
#print(y)
def sin_func(x, a, b):
y = a * np.sin(x + b)
return y
... |
from django.apps import apps
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
def get_product_model():
try:
return apps.get_model(settings.PRODUCT_MODEL, require_ready=False)
except Exception as e:
raise ImproperlyConfigured(
e, 'In order to ... |
"""
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
distri... |
import os
DEBUG = False
API_URL_PREFIX = "/ulca/cron-manager"
HOST = '0.0.0.0'
PORT = 5001
ENABLE_CORS = False
ulca_db_cluster = os.environ.get('ULCA_MONGO_CLUSTER', 'mongodb://localhost:27017')
process_db = os.environ.get('ULCA_PROC_TRACKER_DB', 'ulca-process-tracker')
process_collectio... |
import torch
def test_vote_module():
from mmdet3d.models.model_utils import VoteModule
vote_loss = dict(
type='ChamferDistance',
mode='l1',
reduction='none',
loss_dst_weight=10.0)
self = VoteModule(vote_per_seed=3, in_channels=8, vote_loss=vote_loss)
seed_xyz = torch.... |
class Solution(object):
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
temp = set()
for i in range(9):
row = board[i]
for j in range(9):
c = row[j]
if '.' == c:
... |
#!/usr/bin/env python3
"""
Backfills S3Blob.size for all of the objects in S3.
We store sizes of the original content, so we need to download the data and ungzip it.
"""
import gzip
from botocore.exceptions import ClientError
from quilt_server import db
from quilt_server.models import S3Blob
from quilt_server.view... |
#!/usr/bin/env python
import sys,string
import sys, os
import argparse
import tempfile
#********************************************************************************************
# Read Swissprot program *
# ... |
class Button:
def __init__(self, title, payload_url, tp="postback"):
self.tp = tp
self.title = title
self.payload = payload_url
pass
def serialize(self):
obj = "url" if self.tp=="web_url" else "payload"
return {
"type": self.tp,
obj: self... |
'''
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... |
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
def plot_the_graph(filename, data_for_plot):
# data_for_plot = data.T
deltaloc = 0.32
locations = []
for i in range(0,8,2):
locations.extend([i + 1 - deltaloc, i + 1 + deltaloc])
locations = range(8... |
from django.contrib.auth.models import UserManager
from django.contrib.auth import get_user_model
class CustomUserManager(UserManager):
def exists(self, data):
"""Check if an email exists"""
my_user_model = get_user_model()
email = data.get('email', '')
if not email:
r... |
# -*- coding: utf-8 -*-
# --------------- WOWHONEYPOT settings ---------------
# default host: 0.0.0.0
WOWHONEYPOT_HOST = '0.0.0.0'
# default port: 8080
WOWHONEYPOT_PORT = 8080
# default server header: Apache
WOWHONEYPOT_SERVER_HEADER = 'Apache'
WOWHONEYPOT_POT_IP = ''
# art directory path
# default path: ./art/
WO... |
#!/usr/bin/env python
#coding:utf-8
# Author: mozman --<mozman@gmx.at>
# Purpose: test filters module
# Created: 04.11.2010
# Copyright (C) 2010, Manfred Moitzi
# License: GPLv3
import unittest
from svgwrite import filters
class TestFilter(unittest.TestCase):
def test_constructor(self):
f ... |
# Copyright 2019 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 os
import pandas as pd
import csv
import tensorflow as tf
config = tf.compat.v1.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.compat.v1.Session(config=config)
if not os.path.exists('/home/shyam/bridge_tech/new_view/fin_dataset/data/validation'):
os.makedirs('/home/shyam/bridge_tech/new_v... |
"""Visualization utilities for tensorboard
For online logging we provide tensorboard logging API, e.g.::
set_tensorboard_logging("test_directory/to/log/to")
log_tensorboard("accuracy", 10, step=0)
log_tensorboard("accuracy", 5, step=1)
"""
from typing import Optional, Union
import numpy as np
import to... |
def sol():
N = int(input())
for i in range(1, 10):
print(str(N) + " * " + str(i) + " = " + str(N * i))
if __name__ == "__main__":
sol()
|
from selenium import webdriver
# import time
driver = webdriver.Chrome("C:\\Users\\henry\\Desktop\\Python Training\\Python Selenium\\chromedriver.exe")
# driver.get('https://www.amazon.com/')
# driver.maximize_window()
# driver.find_element_by_id('nav-link-accountList-nav-line-1').click()
# driver.find_element_by_id(... |
from ..constant import NUMBER_OF_CATEGORY
from .get_not_nan_unique import get_not_nan_unique
def guess_type(nu___, n_ca=NUMBER_OF_CATEGORY):
un_ = get_not_nan_unique(nu___)
if all(float(nu).is_integer() for nu in un_):
n_un = un_.size
if n_un <= 2:
return "binary"
eli... |
#!/usr/bin/env python3
# from typing import *
# def solve(X: int, A: int, B: int) -> int:
def solve(X, A, B):
pass # TODO: edit here
# generated by online-judge-template-generator v4.1.0 (https://github.com/kmyk/online-judge-template-generator)
def main():
X = int(input())
A = int(input())
B = int(in... |
def expand(l):
return "".join([obj.toScript() for obj in l])
class base():
def __init__(self):
self.modifier=""
self.alignmentPoints={}
def getAligned(self,name):
if name in self.alignmentPoints:
return translate(*[-p for p in self.alignmentPoints[name]])(self)
else:
raise Exception("no alignment p... |
# -*- coding: utf-8 -*-
# =============================================================================
# Created by: Natalie LaLuzerne
# =============================================================================
import csv
dirname = r"C:\Users\nlalu\Documents\EECS_581"
diagnosis = "diagnoses.csv"
classification ... |
import random
import torch
import torch.nn as nn
try:
from NAS import genotypes
except ImportError:
import genotypes
try:
from NAS import model
except ImportError:
import model
try:
from NAS import operations
except ImportError:
import operations
def gen_layer(C_in, C_out, model_index):
... |
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import json
from colors import black, blue, cyan, green, magenta, red, white
from packaging.version import Version
from pants.option.options_fingerprinter import CoercingOptionEncoder
fr... |
import allel
import pandas as pd
import numpy as np
callset = allel.read_vcf(r"your_directory_here.vcf", numbers={'ALT': 1})
genot = callset['calldata/GT']
gt = allel.GenotypeArray(genot)
gt.to_n_alt()
genot = pd.DataFrame(gt.to_n_alt(fill=-1))
genot.columns = callset["samples"]
genot.index = callset["var... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.