content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python3
"""
Module containing functions to calculate structural environment profiles of AAs
"""
# TODO Tests to make sure these are producing correct profiles
import sys
from collections import defaultdict
import numpy as np
from Bio.SeqUtils import seq1#, seq3
from Bio.Alphabet.IUPAC import protein as... |
import importlib.metadata
name = "Dramakul"
DISTRIBUTION_METADATA = importlib.metadata.metadata(name)
description = DISTRIBUTION_METADATA["description"]
__version__ = DISTRIBUTION_METADATA["version"]
|
##############################################################################
#
# Copyright (c) 2004 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOF... |
"""
Самая простая программа tkinter с пустым окном
"""
import tkinter
app = tkinter.Tk()
app.mainloop()
|
name = "sprich"
|
# Copyright 2021 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://www.apache.org/licenses/LICENSE-2.0
#
# or in the "license... |
#!/usr/bin/python3
# variable_window_split_documents_pipeline.py
# Date: 20.10.2021
# Author: Stratulat Ștefan
# Email: stefan.stratulat1997@gmail.com
import sys
sys.path.append("/opt/airflow/")
sys.path = list(set(sys.path))
from airflow.decorators import dag, task
from dags.etl_dags import DEFAULT_DAG_ARGUMENTS
im... |
import os
import magic
from django.core.exceptions import ValidationError
def validate_uploaded_image_extension(value):
valid_mime_types = ['image/svg+xml', 'image/jpeg', 'image/png']
file_mime_type = magic.from_buffer(value.read(2048), mime=True)
if file_mime_type not in valid_mime_types:
raise Va... |
from openopt import LCP as openLCP
from fltk import *
import copy
import numpy as np
import time
import numpy.linalg as npl
def main():
A = np.array(((1., 0.), (0., 1.)))
x = np.array((0., 0.))
b = np.array((30., -1.))
lo = np.array((0., 0.))
hi = np.array((100000000000., 100000000000.))
p = o... |
"""
ASSUMPTIONS
- this tool created to bump versions, so if it can't do that it will exit with
return code 1, meaning failure. This is so it can be used in CI/CD tooling
OVERVIEW
- [x] parse tag spec and compare with latest tag
- [x] bump the version number
- [x] write changelog
- [x] append to existing changelog f... |
# For detailed comments on animation and the techniqes used here, see
# the wiki entry http://www.scipy.org/Cookbook/Matplotlib/Animations
from __future__ import print_function
import matplotlib
matplotlib.use('TkAgg')
import sys
import pylab as p
import numpy as npy
import time
ax = p.subplot(111)
canvas = ax.figu... |
import warnings
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.lines import Line2D
warnings.filterwarnings("ignore")
from excercises.T1TheData import get_data_matrix_and_set
from excercises.T21PCA import compute_pca
datamatrix, dataset = get_data_matrix_and... |
import click
from GLOBAL_VARIABLES import DATABASE_LOCATION
from db_api.tables.buyin_report import buyin_report
@click.command()
def show_report_by_buyin():
print(buyin_report(DATABASE_LOCATION))
|
import unittest
from parameterized import parameterized
import numpy as np
import tensorflow as tf
import learner
import networks
import data
import paths
import utils
import embed
from policies import get_p1_controller
def assert_tensors_close(t1, t2):
np.testing.assert_allclose(t1.numpy(), t2.numpy())
def defau... |
import zipfile
import datafiles
import datetime
import xml.sax.handler
import xml.sax.xmlreader
import util
import newdb
import xdrlib
import os
database = newdb.get_db()
def _date(date):
return datetime.datetime.strptime(date, "%Y-%m-%dT%H:%M:%S")
def _datePlusOne(date, delta=datetime.timedelta(days=1)):
re... |
"""This module supports puzzles where closed loops are filled into a grid.
# Attributes
L (int): The #LoopConstrainer.inside_outside_grid value indicating that a cell
contains part of a loop.
I (int): The #LoopConstrainer.inside_outside_grid value indicating that a cell
is inside of a loop.
O (int): The #LoopC... |
from avalon.vendor.Qt import *
from avalon.vendor import qtawesome
from avalon import style
HelpRole = QtCore.Qt.UserRole + 2
FamilyRole = QtCore.Qt.UserRole + 3
ExistsRole = QtCore.Qt.UserRole + 4
PluginRole = QtCore.Qt.UserRole + 5
PluginKeyRole = QtCore.Qt.UserRole + 6
from ..resources import get_resource
from .bu... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... |
import re
from typing import Text
_CONVRULES = [
# Conversion of 2 letters
"アァ/ a:",
"イィ/ i:",
"イェ/ j e",
"イャ/ i a",
"ウゥ/ u:",
"エェ/ e:",
"オォ/ o:",
"カァ/ k a:",
"キィ/ k i:",
"クゥ/ k u:",
"クャ/ k u a",
"クュ/ k u u",
"クョ/ k u o",
"ケェ/ k e:",
"コォ/ k o:",
"ガァ/ ... |
"""
Test upstreamATG.predict_on_sample
"""
# import pytest
from gfeat.upstreamAUG import UpstreamAUG
# from tests.uATG.config_uATG import uATG_object
import numpy as np
def test_predict_on_sample():
uATG_object = UpstreamAUG()
res = uATG_object.predict_on_sample("GTCCTAGAGCAGCTCCAGCAGGATGGCGGCTCCAGCGTCTCTAAG... |
import logging
from django.db.models import F
from dear_petition.petition.types import dismissed, not_guilty
from dear_petition.petition import constants
logger = logging.getLogger(__name__)
TYPE_MAP = {
constants.DISMISSED: dismissed.get_offense_records,
constants.NOT_GUILTY: not_guilty.get_offense_records... |
from yacs.config import CfgNode as CN
# Parameters for generate_simulation_data.py
gen_sim_data = CN()
gen_sim_data.names = CN()
# directory names
gen_sim_data.names.data_names = ['v2lcRun_sm1_laneChange', 'v2lcRun_sm2_platoonFormExit', 'v2lcRun_sm3_comparisonSoA']
gen_sim_data.names.folder_names = ['1/', '2/', '3/']
... |
# 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
# d... |
# from Olivia Ng via https://codepen.io/oliviale/pen/OrxWyK
def write_card(
card_title,
card_subtitle,
squares,
):
card_header = f'''
<html lang="en"><head>
<meta charset="UTF-8">
<title>{card_title}</title>
'''
card_header += '''<link href="https://fonts.googleapi... |
bl_info = {
"name": "Hyi format exporter",
"author": "ゲーニー",
"version": (0, 1),
"blender": (2, 80, 0),
"location": "File > Import-Export >Hui format ",
"description": "Import to Hui",
"warning": "",
"wiki_url": "",
"category": "Import-Export",
}
from bpy.props import StringProper... |
#!/usr/bin/env python3
import argparse
import os
import re
import sys
IMPORTS = """import React from "react"
import PropTypes from "prop-types"
"""
INITIAL_EXPORT = "export default class <COMPONENT-NAME> extends React.Component {"
INDENT = " "
PROP_TYPES_START = " static propTypes = {"
PROP_TYPES_END = "}"
DEFAUL... |
from torch import nn
import torch
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import Dataset, DataLoader
#from skimage import io, transform
import numpy as np
import torch.nn.functional as F
from torch.autograd import Variable
class beta_VAE(nn.Module):
# Simple beta_vae impl... |
"""
Test that all the examples are valid instances of the schema.
Run with ``python3 -m pytest ``
"""
import pathlib
import functools
import pytest
import jsonschema
from ruamel.yaml import YAML
import hypothesis
import hypothesis_jsonschema
@functools.lru_cache(maxsize=None)
def load_yaml(filename):
with open(... |
#!/usr/bin/python
# Copyright 2020 Red Hat, Inc.
# 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 ... |
# phos bindings for python.
#
# You probably don't want to import this directly, use rather the
# phos.client and phos.server submodules.
import asyncio
import ctypes
ERROR = -1
WANT_READ = -2
WANT_WRITE = -3
async def wait_for_read(fd):
loop = asyncio.get_running_loop()
future = loop.create_future()
lo... |
from spectrum import transfer
from numpy.testing import assert_almost_equal
import numpy as np
def test_tf2zpk():
from scipy import signal
[b,a] = signal.butter(3,.4);
z,p,k = transfer.tf2zpk(b,a)
assert_almost_equal(k, 0.09853, 4)
assert_almost_equal(z[0], -1.00000293 +5.07009147e-06j, 4)
asse... |
import unittest
import pyperclip
from user_details import User, Detail
class TestUser(unittest.TestCase):
'''
Test class that defines test cases for the user class behaviours.
Args:
unittest.TestCase: helps in creating test cases
'''
def setUp(self):
'''
Function to create a user account before each tes... |
from hyde.hyde_callable import HydeCallable
from hyde.hyde_instance import HydeInstance
class HydeClass(HydeCallable):
arity = 0
def __init__(self, name, superclass, methods):
self.name = name
self.superclass = superclass
self.methods = methods
def call(self, interpreter... |
from flask import Blueprint
from flask_restful import Api
from redis import exceptions
from redisolar.api.capacity import CapacityReportResource
from redisolar.api.meter_reading import GlobalMeterReadingResource
from redisolar.api.meter_reading import SiteMeterReadingResource
from redisolar.api.metrics import MetricsR... |
import json
import logging
import datetime
import jwt
import requests
from decouple import config
from grpc_adenine import settings
from grpc_adenine.implementations.rate_limiter import RateLimiter
from grpc_adenine.implementations.utils import get_api_from_did
from grpc_adenine.settings import REQUEST_TIMEOUT
from gr... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 The Project U-Ray Authors.
#
# Use of this source code is governed by a ISC-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/ISC
#
# SPDX-License-Identifier: ISC
# Break frames into WORD_SIZE bit words.
... |
#!/usr/bin/python3
from server import Server
import signal
import sys
start_server: bool
start_help: bool
use_gui: bool
args = sys.argv
start_server = args.__contains__("run")
start_help = args.__contains__("help")
if start_server:
server_instance: Server = Server()
def on_exit(sig, frame):
server... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
import numpy as np
from numpy.testing import assert_allclose
from astropy import units as u
from astropy.coordinates import SkyCoord
from astropy.io import fits
from regions import CircleSkyRegion
from gammapy.maps import HpxGeom, HpxMap, Hpx... |
from datacode.typing import IntOrNone, FloatOrNone, Union
def missing_more_than_str(missing_tolerance: IntOrNone, missing_quantile: FloatOrNone,
missing_display_str: str, id_var: str) -> str:
return f'More than {_t_or_q(missing_tolerance, missing_quantile)} {missing_display_str} {id_var}'... |
from django import forms
from django.contrib.auth import views
from django.contrib.auth.forms import AuthenticationForm
from django.utils.translation import gettext_lazy as _
# from django.forms import ValidationError, modelformset_factory
from django_countries.widgets import CountrySelectWidget
from django_countries.... |
import os
import unittest
from utils.TextClient import TextClient
class TextClientTestCase(unittest.TestCase):
def setUp(self):
self.tc_sendgrid = TextClient(debug=os.environ['DEBUG'])
self.tc_twilio = TextClient(msg_svc='twilio', debug=os.environ['DEBUG'])
def tearDown(self):
pass
... |
import os
import pdb
import random
from random import randrange
import gin
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import torch
from loader.episode import Episode
from meta_dataset.data import config
from meta_dataset.data import dataset_spec as dataset_spec_lib
from meta_dataset.dat... |
"""This is main runner of generator
"""
import logging
import re
import sys
from argparse import ArgumentParser
from collections import namedtuple, OrderedDict
from datetime import date
from inspect import getfile
from itertools import groupby
from json import JSONDecodeError, loads
from os.path import basename
from ... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# This script updates the problems table in README.md
# It needs to be run every time new solutions are added to the project
import os
import re
info = """# Leetcode Solutions
*Author: Yihao Wang*
This repository contains my record of [Leetcode](https://leetc... |
"""build"""
import sys
# pylint: disable=too-many-branches, consider-using-enumerate
def generate_data(data_path, target_path):
"""
:param data_path: 源数据路径
:param target_path: 生成数据路径
源数据文件格式:
#路线名1 (#表示接下来为一条地铁线)
站点名1 站点名2 ... 站点名n
#$路线名2 ($表示该路线为环形)
... |
#!/usr/bin/env python3
import sys
import os
import re
import cv2
import torch
import argparse
import numpy as np
import torch.nn as nn
import torch.optim as optim
import unet_model as UNET
from copy import deepcopy
from helper import *
from torchvision import transforms, utils
from create_ground_truth import get_rot_... |
#! /usr/bin/python3
import collections
import datetime
import hashlib
import os
import psycopg2
import re
import sys
import time
import urllib.parse
import zlib
zlib_nothing = zlib.compress(b'')
class savepoint:
def __init__(self, cur, name):
self._cur = cur
self._name = name
def __enter__(... |
#!/usr/bin/env python3
import json
import warnings
import random
import numpy as np
from datetime import datetime
from pathlib import Path
from tqdm import tqdm
from PIL import Image, ImageEnhance
class MaskJsonUtils():
""" Creates a JSON definition file for image masks.
"""
def __init__(self, output_dir... |
# Copyright 2010-2011 OpenStack Foundation
# Copyright 2011 Piston Cloud Computing, Inc.
# 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... |
def pytest_addoption(parser):
parser.addoption("--n", action="store", default='5')
parser.addoption("--t", action="store", default='Hello')
|
import datetime
from django.conf import settings
from django.test import TestCase
from timepiece import utils
from timepiece.tests import factories
from timepiece.reports.utils import generate_dates
class ReportsTestBase(TestCase):
def setUp(self):
super(ReportsTestBase, self).setUp()
self.use... |
# -*- coding: utf-8 -*-
"""
Handles old Tidbinbilla data files
NEEDS MAJOR UPDATES FROM MODULE Observatory TO MonitorControl
"""
import time
import Astronomy as A
import Physics as P
import Data_Reduction.FITS.SDFITS as SDF
diag = False
class Tid_scan():
"""
Make a Tidbinbilla spectral scan object
This cover... |
import numpy as np
from scipy.optimize import linprog
def lp(A, b, tol):
# LP Solve Basis Pursuit via linear programing
#
# Solves the following problem:
# min_x || x ||_1 s.t. b = Ax
#
# We convert the problem by splitting x into the
# positive and negative entries x=u-v, u,v>=0.
#
... |
# Generated by Django 2.0.3 on 2018-07-16 23:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("apostello", "0023_smsoutbound_status")]
operations = [
migrations.AddField(
model_name="recipient",
name="never_contact",
... |
import unittest
import numpy as np
from autodiff.decorators import function, gradient, hessian_vector
from autodiff.functions import tag
#========= Tests
class TestFunction(unittest.TestCase):
def test_basic_fn(self):
@function
def fn(x):
return x
self.assertTrue(np.allclose(... |
from mcpi.minecraft import Minecraft
from math import *
import time
import enum
# ----enums----
class direction(enum.Enum):
LEFT = 0
RIGHT = 1
UP = 2
DOWN = 3
KEEP_SAME = 4
class heading(enum.Enum):
DOWN = 0
UP = 1
NORTH = 2
SOUTH = 3
WEST = 4
EAST = ... |
#!/usr/bin/env python3
print('hello world - exemplo de conflito') |
''' Stuff to control a bitcoind-instance. Either directly by access to a bitcoind-executable or
via docker.
'''
import os
import atexit
import logging
import shutil
import subprocess
import tempfile
import time
import click
from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
import docker
from bit... |
"""Background processor for ESI knife."""
import re
import gc
import copy
import random
from traceback import format_exception
from concurrent.futures import as_completed
from concurrent.futures import ThreadPoolExecutor
import gevent
from esi_knife import LOG
from esi_knife import ESI
from esi_knife import Keys
fr... |
#!/usr/bin/env python
'''test replication of depots in perforce sampledepot with complex
mappings.
test cases includes:
- replicate files from multiple directories
- replicate files and reorganize directories in target depot
- exclude certain file types '-//depot/James/....exe'
- exclude some directories
- rep... |
class Node():
def __init__(self, x, y, r):
self.x = x
self.y = y
self.r = r
self.next = None
self.prev = None
pass
@classmethod
def from_np(cls, index, pos):
return cls(pos[index][0], pos[index][1], pos[index][2])
def __str__(self):
retu... |
# Generated by Django 2.2 on 2021-03-13 17:53
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('table', '0002_auto_20210313_2305'),
]
operations = [
migrations.AlterField(
model_name='table',
... |
from jumpscale import j
import gevent
import sys
from importlib import import_module
JSBASE = j.application.jsbase_get_class()
class GedisChatBotFactory(JSBASE):
def __init__(self, ws):
JSBASE.__init__(self)
self.ws = ws
self.sessions = {} # open chatsessions
self.chat_flows = {}... |
import bpy
from .. base_types.update_file import updateFile
class TagRetryExecution(bpy.types.Operator):
bl_idname = "an.tag_retry_execution"
bl_label = "Tag retry execution"
bl_description = "Rebuild internal node structures and check for problems again"
def execute(self, context):
updateFile... |
# Copyright (C) 2018 Garth N. Wells
#
# SPDX-License-Identifier: MIT
"""This module contains a collection of functions related to
geographical data.
"""
from math import radians, cos, sin, asin, sqrt
from .utils import sorted_by_key # noqa
def haversine(func_coordinate, func_p):
"""
Calculate the great circ... |
#!/usr/bin/env python3
import io
import os
from contextlib import redirect_stderr
from unittest import TestCase, main
from lxml import etree
from readalongs.text.add_elements_to_xml import add_images, add_supplementary_xml
class TestConfig(TestCase):
@classmethod
def setUpClass(cls):
data_dir = os.... |
from setuptools import setup, find_packages
setup(
name='myegg',
version='1.0.0',
install_requires=[
],
packages=find_packages(exclude=['tests']),
entry_points={
'console_scripts': [
'myegg = myegg.commands:run'
]
},
test_suite='tests'
)
|
from functools import partial
from ...fileio.adm.exceptions import AdmError
# functions which take a path through the audioPackFormats and an
# audioChannelFormat, and extract some parameter for a single HOA channel
def _get_pack_param(audioPackFormat_path, audioChannelFormat, name, default=None):
"""Get a param... |
from functools import partial
from devito.core.operator import CoreOperator, CustomOperator
from devito.exceptions import InvalidOperator
from devito.passes.equations import buffering, collect_derivatives
from devito.passes.clusters import (Blocking, Lift, cire, cse, eliminate_arrays,
... |
from typing import Sequence
def file_contains_tag(filename: str, *, tag: str) -> bool:
with open(filename, 'r') as f:
lines = f.read().split('\n')
contains_tag = False
for i, line in enumerate(lines, start=1):
if tag in line:
print(f'{filename}: line {i} contains tag "{tag}"')... |
class SpaceXException(Exception):
pass
class UnexpectedArguments(SpaceXException):
def __init__(self, reason=None):
super().__init__(f'An unexpected arguments has arrived. {reason}') |
#!/usr/bin/env python3
import subprocess
import requests
import os
import time
FNAME_START = "+++"
CLOUDFLARE_URL = "https://api.cloudflare.com/client/v4/zones/4fc6fb1d46e87851605aa7fa69ca6fe0/purge_cache"
# we have changes in revision and commit sha on all pages
# so such changes have to be ignored
MIN_CHANGED_WOR... |
class Box:
def __init__(self, x, y, w, h):
self.x = x
self.y = y
self.width = w
self.height = h
self.inner_height = max(0, h - 2)
self.inner_width = max(0, w - 2)
def size(self):
return self.width * self.height
def inner_size(self):
return se... |
"""
Сначала зайдите в файл my_tables.py
"""
from typing import List
from example.my_tables import Students, Points, Position
# Используем 1-й способ инициализации
students = Students("example.db") # Инициализируем таблицу `Students`
points = Points("example.db") # Инициализируем таблицу `Points`
print("\n П... |
import sys
sys.path.append('../')
from pathlib import Path
import shutil
import numpy as np
import pickle
from py_diff_pd.common.common import ndarray, create_folder
from py_diff_pd.common.common import print_info, print_ok, print_error
from py_diff_pd.common.hex_mesh import hex2obj_with_textures, filter_hex
from py_... |
import json
from os.path import exists
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from .. import builder
from ..registry import RECOGNIZERS
from ..tenons.losses import HordeLoss, MaxEntropyLoss, TotalVarianceLoss
@RECOGNIZERS.register_module
class ASLNet3D(nn.Module):
... |
"""
core handler
"""
import typing
from abc import abstractmethod, ABCMeta
from . import m
from .m import is_dataclass
from ex_dataclass import type_
from ex_dataclass.type_ import Field_, ignore_type, handle_eclass_forward_ref
class _FieldTyping(m.ToolImpl, metaclass=ABCMeta):
debug = False
# field type nam... |
import time
from django.http import HttpResponseRedirect
from django.shortcuts import render, reverse
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.core import management
from django.utils import timezone
class ItemViewMixin:
model = None
template = None
context_nam... |
from src.application.commands_service import post, read, follow, wall
from .fixtures.commands_service_fixtures import mocked_mongo_repo
class TestCommandsService(object):
def test_001_post(self, mocked_mongo_repo):
rc = post(repo = mocked_mongo_repo, username = 'dummy_user', message = 'dummy_message')
... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2009 Rene Liebscher
#
# This program 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 3 of the License, or (at your option) any
# later version.... |
# -*- coding: utf-8 -*-
''' Unit Tests
'''
# pylint: skip-file
# pylint: disable=C0103
import sys
if sys.version_info < (2, 7):
import unittest2 as unittest
else:
import unittest
import os
from ioflo.aid.odicting import odict
from ioflo.aid.timing import Timer, StoreTimer
from ioflo.base.storing import Store... |
from datetime import datetime
import click
import pytz
import yaml
from click import ClickException
from tabulate import tabulate
from casper import utils
from casper.main import cli, context
from pyghost.api_client import ApiClientException
from .utils import regex_validate
@cli.group('deployment', help="Manage de... |
# Generated by Django 3.2 on 2021-07-18 12:41
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('blog', '0003_rename_content_comment_body'),
]
operations = [
migrations.AddField(
model_name='categor... |
# -*- coding:utf-8 -*-
from anwen.base import BaseHandler
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.httpclient
from tornado.web import asynchronous
from tornado.httpclient import HTTPRequest
from tornado.curl_httpclient import CurlAsyncHTTPClient... |
"""
DICpy: digital imahe correlation with python
========================================
"""
import pkg_resources
import DICpy.DIC_2D
import DICpy.utils
from DICpy.DIC_2D import *
from DICpy.utils import *
try:
__version__ = pkg_resources.get_distribution("DICpy").version
except pkg_resources.DistributionNotFo... |
from ds.core.base import Base
import shap
from sklearn.metrics import mean_absolute_percentage_error, mean_absolute_error, mean_squared_error, r2_score
METRICS = {
"r2": r2_score,
"mse": mean_squared_error,
"mape": mean_absolute_percentage_error,
"mae": mean_absolute_error
}
class BaseModel(Base):
... |
"""
Ejercicio1. Hacer un programa que tenga una lista
de 8 numeros enteros y haga lo siguiente:
- Recorrer la lista y mostrarla
- Ordenarla y mostrarla
- Mostrar su longitud
- Buscar algun elemento (que el usuario pida por el teclado)
"""
lista1 = list(range(1,9))
numeros = [15,24,19,28,20,33,16,25]
print(numeros)
... |
# Minhyuk Sung (mhsung@cs.stanford.edu)
#------------------------------------------------------------------------------
# Define all the global variables for the project
#------------------------------------------------------------------------------
from __future__ import division
import os, sys
BASE_DIR = os.path.no... |
import sys
import socket
import os
import subprocess as sp
import json
from flask import Flask
from flask.ext.restful import reqparse, abort, Api, Resource
from flask import request, make_response
from datetime import datetime
from nltk import word_tokenize
import random
host = "holst.isi.edu"
ports = [10030]
size = 1... |
from django.conf.urls import url
from django.views.generic import TemplateView
from . import views
urlpatterns = [
url(r'^(?P<slug>[\w-]+)/$', views.SimpleNewsDetailView.as_view(), name="simple_news_detailview"),
url(r'^cat/(?P<slug>[\w-]+)/$', views.SimpleNewsListView.as_view(), name="simple_news_listview"),
... |
import numpy as np
import pandas as pd
def _prob_to_class(df):
if isinstance(df, np.ndarray):
return df.argmax(axis=1)
elif isinstance(df, pd.DataFrame):
return df.idxmax(axis=1)
class CrowdClassifier:
"""
Assumptions:
1. Binary or Multiclass classification (single task)
2. m... |
from collections import namedtuple
import random
import matplotlib
matplotlib.use("TkAgg")
from matplotlib import pyplot as plt
import torch
# Experience Replay Memory
Transition = namedtuple('Transition', ('state', 'action', 'next_state', 'reward'))
class ReplayMemory(object):
def __init__(self, capacity):
... |
import time
from functools import wraps
from inspect import Traceback
from typing import Any, Callable, Optional, Type
import docker.errors
import psycopg2
from asyncpg import Connection
from asyncpg.pool import Pool
from docker import APIClient
class FakePoolAcquireContext:
def __init__(self, pool: "FakePool") ... |
from interpreter import PolishNotation
from .WindowIOI import WindowIOI
from os import system
from platform import system as getNameOS
import pyperclip
class ConsoleIOI:
__interpreter = PolishNotation()
__commands = {
"exit": [".q", ".exit", ".quit", ".ex"],
"help": [".h", ".help"],
"interprete to Poli... |
from refextract import extract_references_from_url
references = extract_references_from_url('https://arxiv.org/pdf/1503.07589.pdf')
print(references[0]) |
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from UI.qrangeslider import QRangeSlider
import main
import viewer
class mainWindow(QDialog):
"""This class will hold buttons and checkboxes
to specify parameters as inputs to the program
Arguments:
QDialog {[C... |
import os
import sys
import uuid
OMPI="OMPI"
OMPI_HOSTFILE_FLAG="-hostfile"
IMPI="IMPI"
IMPI_HOSTFILE_FLAG="-hostfile"
SLURM="SLURM"
SLURM_HOSTLIST_FLAG="--nodelist="
DEFAULT_MPI="IMPI"
def config_multinode( properties , all_mpi=True):
mpi_env = os.environ.get("MULTINODE_MPI_ENV")
if mpi_env is None:
... |
# TODO - compile to SAS+ like representation
# TODO - analyse the Domain Transition Graph for each variable
# NOTE - fixed set of operators, types, and predicates is good
# TODO - still may be infinitely many varaibles |
# Dejavu
# DEJAVU JSON RESPONSE
SONG_ID = "song_id"
SONG_NAME = 'song_name'
RESULTS = 'results'
HASHES_MATCHED = 'hashes_matched_in_input'
# Hashes fingerprinted in the db.
FINGERPRINTED_HASHES = 'fingerprinted_hashes_in_db'
# Percentage regarding hashes matched vs hashes fingerprinted in the db.
FINGERPRINTED_CONFI... |
#!/usr/bin/env python
# Copyright (C) 2018 Emanuel Goncalves
import numpy as np
import crispy as cy
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from natsort import natsorted
from scipy.stats import ttest_ind
from analysis.DataImporter import DataImporter
from statsmodels.stats.multitest i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.