content stringlengths 5 1.05M |
|---|
# Compatibility Python 2/3
from __future__ import division, print_function, absolute_import
from builtins import range
from past.builtins import basestring
# ----------------------------------------------------------------------------------------------------------------------
import numpy as np
import opto.log as log
... |
from tokens import *
from baseorder import BaseOrder, log
from dexible.common import Price, as_units
from dexible.exceptions import *
import asyncio
TOKEN_IN = DAI_KOVAN
TOKEN_OUT = WETH_KOVAN
IN_AMT = as_units(500, 18)
async def main():
sdk = BaseOrder.create_dexible_sdk()
token_in = await sdk.token.lookup(... |
import os
import json
import yaml
class Context:
"""
Conversation Context Object
"""
def __init__(self, db, userProfile):
"""
Initialize Context Object
:param db: database for state storage
:param userProfile: user profile object
:type db: db object
:type userProfile: json/dictionary... |
# Standard libraries
import contractions
import re
import string
import enum
# Nltk download
import nltk
nltk.download('stopwords')
nltk.download('punkt')
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
class TextCleaner:
def __init__(self):
... |
# Copyright 2015-2021 Mathieu Bernard
#
# This file is part of phonemizer: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# Phonemizer is distributed ... |
from .base import *
DEBUG=True
HOST = os.getenv("DEBUG_HOST")
ALLOWED_HOSTS = ["*"]
AUTH_SERVER_LOGIN = ROOT_SERVER + "/login"
AUTH_SERVER_AUTHENTICATE = ROOT_SERVER + "/authenticate"
AUTH_SERVER_LOGOUT = ROOT_SERVER + "/logout"
AUTH_SERVER_TOKEN = ROOT_SERVER + "/token"
if os.getenv("GITHUB_WORKFLOW"):
DATA... |
# -*- coding: utf-8-*-
'''
Copyright 2015 David J Murray
License: MIT
'''
# Python Library imports
import feedparser
import logging
import re
from datetime import datetime
logger = logging.getLogger(__name__)
WORDS = ["HOROSCOPE", ]
PRIORITY = 1
def getDailyHoroscope(zodiacSign):
'''
Get horosco... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#######################################################
import numpy as np
######################################
##### ネットワークの初期設定を行う #####
######################################
class NWSetup:
def __init__(self, nw_cond, target_cond):
# self.nw_model = nw_cond[0]
sel... |
from django.urls import path, include
from rest_framework import routers
# from rest.l2_serializers import DoctorSerializer, PodrazdeleniyaSerializer
# from rest.l2_view_sets import UserViewSet
router = routers.DefaultRouter()
# router.register(r'users', UserViewSet)
# router.register(r'doctorprofiles', DoctorSeriali... |
import numpy as np
from state import *
count_in_center=0
index_diff_block=-1
opposite_block=-1
def eval(cur_state:State):
global_point=np.zeros(9)
i=0
for block in cur_state.blocks:
point=0
countX_row=-np.count_nonzero(block==1, axis=1)
countX_col=-np.count_nonzero(block==1, axis=... |
import os
import time
import threading
import tkinter.messagebox
import json
from mutagen.mp3 import MP3
from pygame import mixer
from tkinter import *
from tkinter import ttk
from tkinter.filedialog import askdirectory
# dir
sounderdir = os.getcwd()
# sounderdir = os.path.dirname(sys.executable)
userdir =... |
#simple sphinx extension to add json support
def setup(app):
from sphinx.highlighting import lexers
import pygments.lexers
lexers['json'] =pygments.lexers.get_lexer_by_name('javascript')
|
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
from subprocess import check_output
import io
import bson # this is installed with the pymongo package
import matplotlib.pyplot as plt
from skimage.data import imread # or, whatever image ... |
"""Hyperparameter search strategies."""
import itertools
import json
import random
def generate_trials(strategy, flat_params, nb_trials=None):
r"""Generates the parameter combinations to search.
Two search strategies are implemented:
1. `grid_search`: creates a search space that consists of the
p... |
from .src.core import show_dataset, list_datasets, get_dataset
__version__ ="0.0.1"
__author__ = "Siddesh Sambasivam Suseela" |
import time
import sqlite3 as db
from datetime import datetime as dt
con = db.connect("parentsdb.db")
with con:
#hostsPath="hosts"
hostsPath="C:\Windows\System32\drivers\etc\hosts"
redirect="127.0.0.1"
cur = con.cursor()
phone_number = int(input("Enter phone numer :"))
web = ('SELECT website... |
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.config import settings
from app.routes import sentence, text_complexity, tokens
app = FastAPI(
title=settings.PROJECT_NAME,
docs_url=f"{settings.API_STR}/docs",
openapi_url=f"{settings.API_STR}/openapi.json",
)
app.ad... |
#!/usr/bin/env python
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "... |
from src.data.preprocessing.AbstractPreprocessing import AbstractPreprocessing
from skimage.transform import resize
class Resize5050(AbstractPreprocessing):
def preprocess(self, x):
return resize(x, [50, 50])
|
from .base import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
TEMPLATE_DEBUG = False
# CHANGE THE ALLOWED_HOSTS LIST TO FIT YOUR NEEDS
ALLOWED_HOSTS = ['.borsachart.herokuapp.com', 'localhost', '127.0.0.1', '[::1]']
ADMINS = [(os.environ.get('ADMIN_USER'), os.environ.get('ADMI... |
import os
import yaml
import numpy as np
from mspasspy.ccore.utility import MetadataDefinitions
from mspasspy.ccore.utility import MDtype
from mspasspy.ccore.utility import MsPASSError
def index_data(filebase, db, ext='d3C', verbose=False):
"""
Import function for data from antelope export_to_mspass.
Th... |
from server.api import api, custom_types
from flask_restful import Resource, reqparse, abort, marshal, marshal_with
from server import auth, db
from server.models.orm import TeacherModel, ClassroomModel
from server.parsing import parser
from server.parsing.utils import create_students_df
import pandas as pd
from server... |
import sys
sys.path.append('../..')
from pyramid.config import Configurator
from pyramid.session import UnencryptedCookieSessionFactoryConfig
from sqlalchemy import engine_from_config
from social.apps.pyramid_app.models import init_social
from .models import DBSession, Base
def main(global_config, **settings):
... |
# Generated by Django 2.2 on 2019-05-28 22:47
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import taggit.managers
class Migration(migrations.Migration):
initial = True
dependencies = [
('sites', '0002_alter_domain_unique'),
('tag... |
""" Plot matrix of pairwise distance histograms for two sets of conformations. """
from conformation.compare_pairwise_distance_histograms import compare_pairwise_distance_histograms, Args
if __name__ == '__main__':
compare_pairwise_distance_histograms(Args().parse_args())
|
import numpy as np
import sys
sys.setrecursionlimit(10000)
class Knapsack:
def __init__(self, txt_name):
self.size = 0
self.num_items = 0
self.items = [(0, 0)] # (value, weight)
self.array = np.array([])
self.read_txt(txt_name)
self.cache = {}
self.value = s... |
from flask import render_template, request, session, redirect
from . import app, db, default_error, send_email
from .models import School, Department, Course, CourseRequest
@app.route('/')
def index():
""" Renders the home page where the user selects their school. """
return render_template('index.html', sch... |
from pynput import keyboard
import pyglet
from motor_test import motor
M1 = motor(18, 20)
M2 = motor(12, 21)
M3 = motor(13, 5)
M4 = motor(19, 6)
motors = [M1, M2, M3, M4]
window = pyglet.window.Window(width=10, height=10)
@window.event
def on_key_press(key, mod):
key = chr(key)
print("Pressed", key)
if (... |
""" Data wrapper class
Manages loading data and prepping batches. Dynamically stores and loads chunks of data to disk to support datasets
larger than the available RAM. Uses numpy for saving and loading data, as it is much faster than pickle and allows
compression.
It can be instantiated with 4 different shuffle_* fl... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from telegram.ext import Updater, MessageHandler, Filters
import yaml
from telegram_util import log_on_fail, AlbumResult
import album_sender
with open('token') as f:
tele = Updater(f.read().strip(), use_context=True)
debug_group = tele.bot.get_chat(-1001198682178)
... |
#!/usr/bin/env python
#-*- encoding=utf-8 -*-
'''
purpose: 实现命令行下的EMS(邮件营销系统)的管理
author : set_daemon@126.com
date : 2017-06-23
history:
'''
import sys
file_dir = sys.path[0]
sys.path.insert(0, file_dir + "/./")
sys.path.insert(0, file_dir + "/../")
sys.path.insert(0, file_dir + "/../common")
sys.p... |
import re, cStringIO, logging
import striga.core.context
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
try:
import html2text
except:
html2text = None
###
#TODO: Based on security settings send only partial information (no version)
StrigaVersion = 'Striga Server %s' % striga.V... |
from selenium.webdriver.support.ui import Select
from model.contact import Contact
import re
class ContactHelper:
def __init__(self, app):
self.app = app
def add(self, contact):
# Add Contact
wd = self.app.wd
self.app.wd.get("http://localhost/addressbook/edit.php")
wd.... |
from bs4 import BeautifulSoup
import requests
import json
url = "http://nutrias.org/~nopl/photos/wpa/wpa30.htm"
all_my_data = []
home_page = requests.get(url)
home_page_html = home_page.text
soup = BeautifulSoup(home_page_html, 'html.parser')
column_map = {
1: "series_number",
2: "project",
3: "series_title",
... |
import os, os.path as p
import logzero
import logging
from logzero import logger
LOG_LEVEL = logging.INFO
logdir = p.abspath(p.join(p.dirname(__file__), "../logs"))
os.makedirs(logdir, exist_ok=True)
logfile = "logs.txt"
# Setup rotating logfile with 3 rotations, each with a maximum filesize of 1MB:
logzero.logfile(... |
# Approach 1:
def N_Largest_Elements(Arr, Upto):
result = []
for i in range(0, Upto):
max = 0
for j in range(0, len(Arr)):
if Arr[j] > max:
max = Arr[j]
Arr.remove(max)
result.append(max)
return result
Given_List = []
n = int(in... |
# coding: utf-8
# # Tables (2) - Making a table
# In this lesson we're going to learn how make a table in Plotly.
#
# We'll learn how to make one from a list and a Pandas DataFrame.
# ## Module Imports
# In[1]:
#plotly.offline doesn't push your charts to the clouds
import plotly.offline as pyo
#allows us to crea... |
from kronos_modeller.strategy_base import StrategyBase
class FillingStrategy(StrategyBase):
required_config_fields = [
"type",
"priority"
]
|
__author__ = "Dave Wapstra <dwapstra@cisco.com>"
import warnings
from unicon.plugins.iosxe.sdwan import SDWANSingleRpConnection
class SDWANConnection(SDWANSingleRpConnection):
os = 'sdwan'
platform = 'iosxe'
def __init__(self, *args, **kwargs):
warnings.warn(message = "This plugin is deprecated ... |
# Copyright (c) 2021 PaddlePaddle 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 appli... |
from abc import ABCMeta
from torch import nn, Tensor
import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import Callable
from torch.utils.data import DataLoader
from torch.optim.optimizer import Optimizer
class Discriminator(nn.Module):
def __init__(self, in_size):
super().__init... |
from django.db import models
from core.models import TimeStampedEnabledModel, Cities
class AbstractBuilding(TimeStampedEnabledModel):
city = models.ForeignKey(Cities, on_delete=models.DO_NOTHING, null=False)
name = models.CharField(max_length=50)
desc = models.CharField(max_length=100, blank=True)
ad... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 1 08:02:39 2020
@author: Edson Cilos
"""
#Standard packages
import os
import numpy as np
import pandas as pd
#Sklearning package
from sklearn.preprocessing import MinMaxScaler
#Graphics packages
from matplotlib import pyplot as plt
from matplotl... |
import smart_imports
smart_imports.all()
class HeroDescriptionTests(utils_testcase.TestCase):
def setUp(self):
super().setUp()
game_logic.create_test_map()
account = self.accounts_factory.create_account(is_fast=True)
self.storage = game_logic_storage.LogicStorage()
se... |
import ray
import pytest
from ray.tests.conftest import * # noqa
import numpy as np
from ray import workflow
from ray.workflow.tests import utils
from ray.workflow import workflow_storage
@ray.remote
def checkpoint_dag(checkpoint):
@ray.remote
def large_input():
return np.arange(2 ** 24)
@ray.r... |
# -*- coding: UTF-8 -*-
import numpy as np
from scipy.optimize import minimize
from scipy.linalg import kron, circulant, inv
from scipy.sparse.linalg import cg
from scipy.sparse import csr_matrix, diags
from scipy.io import mmwrite, mmread
# ----------------
#MINIMIZE = True
MINIMIZE = False
COST = 0
#method = 'CG'
... |
"""
Number of Connected Components in an Undirected Graph
You have a graph of n nodes. You are given an integer n
and an array edges where edges[i] = [ai, bi] indicates that there is an edge between ai and bi in the graph.
Return the number of connected components in the graph.
Example 1:
Input: n = 5, edges ... |
from .autogen import DocumentationGenerator
from .gathering_members import get_methods
from .gathering_members import get_classes
from .gathering_members import get_functions
|
import torch
import torch.nn as nn
import numpy as np
import model_search
from genotypes import PRIMITIVES
from genotypes import Genotype
import torch.nn.functional as F
from operations import *
class AutoDeeplab (nn.Module) :
def __init__(self, num_classes, num_layers, criterion, num_channel = 20, multiplier = 5,... |
from .individual_history_resource import *
|
"""
This file includes the reimplementations of GSLIB functionality in Python. While
this code will not be as well-tested and robust as the original GSLIB, it does
provide the opportunity to build 2D spatial modeling projects in Python without
the need to rely on compiled Fortran code from GSLIB. If you want to use the... |
from collections import deque
chocolate = [int(num) for num in input().split(",")]
milk = deque([int(num) for num in input().split(",")])
milkshakes = 0
milkshakes_success = False
while chocolate and milk:
current_chocolate = chocolate[-1]
current_milk = milk[0]
if current_chocolate <= 0 and current_mi... |
# -*- coding: utf-8 -*-
""" Language, locale and alphabet encapsulation module
Copyright (C) 2020 Miðeind ehf.
Original author: Vilhjálmur Þorsteinsson
The GNU General Public License, version 3, applies to this software.
For further information, see https://github.com/mideind/Netskrafl
The class... |
import pandas as pd
from pulp import *
def remove_prefix(text, prefix):
if text.startswith(prefix):
return text[len(prefix):]
return text
def best_reco(required_resources, instance_df):
prob = LpProblem("InstanceRecommender", LpMinimize)
instances = instance_df['name'].values
instance_... |
import os
import sys
from setuptools import setup, find_packages
extra = {}
if sys.version_info < (3, 2):
extra['install_requires'] = "futures >= 2.1.6" # backport of py32 concurrent.futures module
if sys.version_info >= (3,):
extra['use_2to3'] = True
setup(
name='pySmartDL',
version='1.2.5',
url... |
import logging
import sys
import os
# SECRETS
DATABASE_URL = os.getenv('DATABASE_URL')
# Logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
formatter = logging.Formatter('[%(asctime)s][%(levelname)s] - %(message)s')
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(formatter)
log... |
# coding: utf-8
# Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... |
from moto.iam.responses import IamResponse, GENERIC_EMPTY_TEMPLATE
from moto.iam.models import iam_backend as moto_iam_backend
from localstack import config
from localstack.constants import DEFAULT_PORT_IAM_BACKEND
from localstack.services.infra import start_moto_server
def patch_moto():
def delete_policy(self):
... |
# 200. Number of Islands
'''
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
Example 1:
Input: grid = [
... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
name = "Hello World"
return name
@app.route('/good')
def good():
name = "Good"
return name
# メイン・プログラムとして走らせるとき。
if __name__ == "__main__":
app.run(debug=True) |
def main():
print("In Bake") |
import tarfile
import os
import numpy as np
import cv2
import h5py
import random
# Parameters
test_count = 1000
dataset_name = "basic_io"
directory = "/media/neduchal/data2/datasety/miniplaces/images"
categories_filename = "./categories_io.txt"
output_path = "/media/neduchal/data2/datasety/places365_256x256_prepared"
... |
import RPi.GPIO as GPIO
import time
front_lights_left_pin = 5
front_lights_right_pin = 6
rear_lights_pin = 13
power_pin = 12
fwd_pin = 17
back_pin = 27
left_pin = 24
right_pin = 23
pwm_fwd = None
pwm_back = None
pwm_left = None
pwm_right = None
pwm_front_lights_left = None
pwm_front_lights_right = None
pwm_rear_... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'Soulweaver'
import os
import logging
import argparse
from randomizer import PROG_NAME, PROG_VERSION, config, Randomizer
def add_enable_disable_argument(p, name, default=False, help_enable=None, help_disable=None,
default_pas... |
import sys # For argv
import getopt # For options
import re # regex replacing
import numpy as np
from itertools import combinations
class Coalition:
def __init__(self,coalition,numplayers):
self.input_coalitions = coalition
self.numplayers = numplayers
self.best_structure = {}
self.... |
''' Base class for the test cases.
Python ``unittest`` framework does not allows large scale of
parameterized tests. This simple base class is just a workaround
to allow to run the tests for various conditions.
'''
import unittest
import numpy as np
import torch
FLOAT_TOLPLACES = 2
FLOAT_TOL = 10 ** (-FLOAT_TOLP... |
# coding: utf-8
from PIL import Image, ImageFont, ImageDraw
from subprocess import call
class WordGenerator:
"""
Generates pithy statements for our visual content
"""
source = None
@staticmethod
def get_content(length=100):
return "I sat on a rug, biding my time, drinking her wine"
... |
#!/usr/bin/python -u
# From https://learn.adafruit.com/adafruits-raspberry-pi-lesson-11-ds18b20-temperature-sensing/software
import os
import glob
import time
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
base_dir = '/sys/bus/w1/devices/'
# Grabs the first probe out of the directory
device_folder = g... |
def curry(f, *a, **kw):
def curried(*more_a, **more_kw):
return f(*(a+more_a), dict(kw, **more_kw))
return curried
|
from setuptools import setup, find_packages
import codecs
import os
with open("README.md", "r") as fh:
long_description = fh.read()
# Setting up
setup(
name="auto-machine-learning",
version='0.0.12',
license='MIT',
author="Mihir Gada, Zenil Haria, Arnav Mankad, Kaustubh Damania",
author_emai... |
# Generated by Django 3.1.1 on 2020-11-13 19:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mascotas', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Mascotas',
fields=[
('id'... |
import graphene
from .book import BookCreateMutation, BookDeleteMutation
from .auth import AuthMutation, RefreshMutation
class MainMutation(graphene.ObjectType):
book = BookCreateMutation.Field()
delete = BookDeleteMutation.Field()
auth = AuthMutation.Field()
refresh = RefreshMutation.Field()
|
from . import _endpoints as endpoints
import requests
import json
from statham.schema.elements import Object
from statham.schema.constants import NotPassed
class StathamJSONEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, Object):
return {type(o).properties[k].source: v for k,... |
from typing import Optional
from xml.dom import minidom as dom
import time
class Message:
'Represents a fragment of message.'
def __init__(self, user: Optional[str], message: str, timestamp: float):
'Initializes a new instance.'
self._user = user
self._message = message
self._ti... |
import atexit
import collections
import logging
import os
import os.path
import re
from pathlib import Path
from tempfile import NamedTemporaryFile, gettempdir
from typing import IO, Any, Dict, List, Optional
import mypy
from mypy import api as mypy_api
from mypy.defaults import CONFIG_FILES as MYPY_CONFIG_FILES
from ... |
# Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from .aws import Action as BaseAction
from .aws import BaseARN
service_name = "AWS Elemental Appliances and Software Activation Service"
prefix = "elemental-activations"
class Action(BaseAction):
d... |
import torch
import torch.nn as nn
from torch.nn import CrossEntropyLoss, MSELoss
from transformers.modeling_outputs import SequenceClassifierOutputWithPast
from .modeling_hart import HaRTBasePreTrainedModel
from .hart import HaRTPreTrainedModel
class HaRTForSequenceClassification(HaRTBasePreTrainedModel):
# _ke... |
import torch
import torch.nn as nn
import logging
logger = logging.getLogger(__name__)
def get_concat(concat: str, embedding_dim: int):
"""
:param concat: Concatenation style
:param embedding_dim: Size of inputs that are subject to concatenation
:return: Function that performs concatenation, Size ... |
# Generated by Django 3.1.4 on 2021-12-12 17:00
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Category',
fields=[
... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox(executable_path = '/media/vivek/Coding Stuffs/Python_Projects/geckodriver')
driver.get("http://wwww.python.org")
assert "Python" in driver.title
elem = driver.find_element_by_name("q")
elem.clear()
elem.send_keys... |
n = input()
s = ""
for i in n:
if i==" ":
s += i
elif i.isdigit():
s += i
elif i.islower():
j = ord(i)+13
s += chr(j) if j<123 else chr(j-26)
elif i.isupper():
j = ord(i)+13
s += chr(j) if j<91 else chr(j-26)
print(s)
|
import os
import shutil
SOURCE = 'source'
QRC_FILE = 'resource.qrc'
primary_icons = os.listdir(SOURCE)
contex = [
('disabled', '#ff0000'),
('primary', '#0000ff'),
]
qrc = {
'icon': [],
}
# ----------------------------------------------------------------------
def replace_color(content, replace, colo... |
import feedparser
import html
from datetime import datetime
from park_api.geodata import GeoData
from park_api.util import utc_now
geodata = GeoData(__file__)
def parse_html(xml_data):
feed = feedparser.parse(xml_data)
try:
last_updated = feed["entries"][0]["updated"]
last_updated = datetime... |
"""
molconfviewer - Visualize molecule conformations in Jupyter
"""
__version__ = "0.1.0"
import ipywidgets
import py3Dmol
from ipywidgets import interact, fixed
from rdkit import Chem
from rdkit.Chem.rdchem import Mol
from typing import Tuple
class MolConfViewer():
"""Class to generate views of molecule confor... |
#!/usr/bin/python
###################
# Library Imports #
###################
from Oedipus.utils.data import *
from Oedipus.utils.misc import *
from Oedipus.utils.graphics import *
from sklearn import metrics
from sklearn.feature_selection import SelectKBest
from sklearn.decomposition import PCA
from sklearn.cross_val... |
class Swimmers:
def getSwimTimes(self, distances, speeds, current):
def time(d, s):
if d == 0:
return 0
if s <= current:
return -1
d = float(d)
return int(d / (s + current) + d / (s - current))
return map(time, distance... |
#%%
# import packages
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
matplotlib.use('Agg')
import datetime
from finrl.apps import config
from finrl.marketdata.yahoodownloader import YahooDownloader
from finrl.preprocessing.preprocessors import FeatureEngineer
from finrl.prepro... |
import unittest
from libpysal.examples import load_example
import geopandas as gpd
import numpy as np
from segregation.aspatial import Dissim
from segregation.decomposition import DecomposeSegregation
class Decomposition_Tester(unittest.TestCase):
def test_Decomposition(self):
s_map = gpd.read_file(load_e... |
#!/usr/bin/python3
from typing import List
import re
class GanetiNode:
name = ""
shortname = ""
total_memory = 0
used_memory = 0
free_memory = 0
total_disk = 0
free_disk = 0
total_cpus = 0
status = ""
group_uuid = ""
spindles = 0
tags: List[str] = []
exclusive_storag... |
from __future__ import print_function
import argparse
import codecs
import logging
import time
import numpy
import pandas as pd
from pandas.io.json import json_normalize
import os
import json
def read_data(folderpath):
start = time.time()
logging.debug("reading data from %s", folderpath)
# creating empt... |
import rospy
from visualization_msgs.msg import Marker
from . import make_markers
class MarkerHelper(object):
def __init__(self, topic, frame_id='/world'):
self.pub = rospy.Publisher(topic, Marker)
self.frame_id = frame_id
def publish(self, marker):
self.pub.publish(marker.to_msg(fr... |
import importlib
import logging
logger = logging.getLogger(__name__)
class CI:
def __init__(self, module):
self.module = module
def __enter__(self):
try:
importlib.import_module(self.module)
self.module_available = True
except ModuleNotFoundError:
... |
#! python3
"""Prints a grid from a list of lists of characters."""
test_grid = [['.', '.', '.', '.', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['O', 'O', 'O', 'O', 'O', '.'],
['.', 'O', 'O', 'O', 'O', 'O'],
['O', 'O', 'O', 'O', 'O', '.'],
... |
# Hash Table; Trie
# In English, we have a concept called root, which can be followed by some other words to form another longer word - let's call this word successor. For example, the root an, followed by other, which can form another word another.
#
# Now, given a dictionary consisting of many roots and a sentence. ... |
import io
import re
from setuptools import setup
from setuptools import find_packages
DESCRIPTION = "Python client for the https://api.radio-browser.info"
def get_version():
content = open("pyradios/__init__.py").read()
mo = re.search(r"__version__\s+=\s+'([^']+)'", content)
if not mo:
raise Run... |
"""This module calculates max ramp rates for each plant component in the EPA CEMS dataset.
Outputs:
<user_arg>.csv:
component-level aggregates.
See results/README.md for field descriptions.
<user_arg>_crosswalk_with_IDs.csv:
inner join of EPA crosswalk and CEMS id columns.
This ... |
"""
Event store.
"""
import psycopg2
from microcosm_postgres.models import Model
from microcosm_postgres.store import Store
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.exc import OperationalError
from microcosm_eventsource.errors import (
ConcurrentStateConflictError,
ContainerLockNotAva... |
# image process
import cv2
import os
import numpy as np
IMGDIR="D:/apidoc/python/OpenCV-3.2.0"
img = cv2.imread(IMGDIR + os.sep + "roi.jpg", )
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
lower_blue = np.array([110,50,50])
upper_blue = np.array([130,255,255])
mask = cv2.inRange(hsv, lowerb=lower_blue, up... |
'''
Author: Ful Chou
Date: 2021-01-07 11:38:03
LastEditors: Ful Chou
LastEditTime: 2021-01-07 11:38:33
FilePath: /leetcode/flatten-binary-tree-to-linked-list.py
Description: What this document does
链接:https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list/
'''
class Solution:
def flatten(self, root: Tr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.