text stringlengths 2 999k |
|---|
class Solution:
def wordBreak(self, s, words):
ok = [True]
max_len = max(map(len,words+['']))
words = set(words)
for i in range(1, len(s)+1):
ok += any(ok[j] and s[j:i] in words for j in range(max(0, i-max_len),i)),
return ok[-1]
|
# !/usr/bin/env python
# Copyright 2015-2016 Yelp Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
"""NAPALM Cisco IOS Handler."""
# Copyright 2015 Spotify AB. 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/licen... |
# Copyright (c) 2019 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 app... |
[
{'base_name': 'STScI_WISE',
'service_type': 'cone',
'access_url': 'http://gsss.stsci.edu/webservices/vo/ConeSearch.aspx?CAT=WISE&',
'adql': ''
}
]
|
from data.Vocab import *
import numpy as np
import torch
from torch.autograd import Variable
def read_corpus(file_path, vocab=None):
data = []
with open(file_path, 'r') as infile:
for sentence in readDepTree(infile, vocab):
data.append(sentence)
return data
def sentences_numberize(sent... |
from django.db.models.query import QuerySet
from .io import read_frame
import django
from django.db import models
class PassThroughManagerMixin(object):
"""
A mixin that enables you to call custom QuerySet methods from your manager.
"""
_deny_methods = ['__getstate__', '__setstate__', '__getinitargs__... |
import pytz
from django.conf import settings
from django.contrib.auth import models as auth_models
from django.db import models
from django.utils.translation import ugettext_lazy as _
from user_g11n.models import UserLanguageSupportMixin, UserTimeZoneSupportMixin
class User(UserTimeZoneSupportMixin,
UserL... |
from zope.interface import implementer
from nevow import inevow
##
## How does a request come to the Page?
##
## or How to use Nevow without all the fancy automations
##
# This is a simple Root page object, the inevow.IResource interface
# tells us that it must implement 2 methods:
# locateChild and renderHTTP.
# lo... |
# !/bin/usr/
# conding:utf-8
# author:Wisdom_Tree
# get key and decode Virginia
import re
import math
c=str(input("请输入密文:"))
c=c.replace(" ","")
# print(c[0])
c_len=len(c)
# print(c_len)
c_list=list(c)
# print(len(c_list))
# for i in c_list:
# print(i)
c_list_gro={} #创建空子典
c_column_gro=[]
avg=[] ... |
#!/usr/bin/env python
import datetime
import operator
import inflect
import pandas as pd
from anytree import NodeMixin, RenderTree
from dateutil.relativedelta import relativedelta
class DateTitle(object):
"""topmost, simple task (date stuff) object"""
def __init__(self, date):
self.date = date
... |
from __future__ import absolute_import
from ocrd.model.ocrd_page_generateds import parse
if __name__ == "__main__":
doc = parse("tmp.xml", True)
print(doc.get_Page().get_TextRegion()[0].get_TextLine()[0].get_TextEquiv()[0].Unicode)
print(doc.get_Page().get_TextRegion()[0].get_TextLine()[0].get_TextEquiv()... |
# -*- coding: utf-8 -*-
#
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
#
# pylint: disable= no-member, arguments-differ, invalid-name
#
# Utilities for using pre-trained models.
import torch
from dgl.data.utils import _get_dgl_url, download
from .molecule... |
import logging
class CoreLogging(object):
"""simple logging testing and dev"""
def __init__(self):
self.name = ".simplydomain.log"
def start(self, level=logging.INFO):
logger = logging.getLogger("simplydomain")
logger.setLevel(level)
fh = logging.FileHandler(self.name)
... |
# coding=utf-8
# Copyright 2020 The HuggingFace Inc. team.
#
# 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... |
import pandas as pd
import numpy as np
import pickle
from flask import Flask, request
import flasgger
from flasgger import Swagger
app = Flask(__name__)
Swagger(app)
pickle_in = open('classifier.pkl', 'rb')
classifier = pickle.load(pickle_in)
@app.route('/')
def welcome():
return 'Welcome'
@app... |
import argparse
import cPickle
import os
import platform
import random
import requests
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import tensorlayer as tl
from PIL import Image
os.environ["CUDA_VISIBLE_DEVICES"] = "3"
def getArgs():
parser = ... |
from flaml import AutoML
from sklearn.datasets import fetch_california_housing
# Initialize an AutoML instance
automl = AutoML()
# Specify automl goal and constraint
automl_settings = {
"time_budget": 1, # in seconds
"metric": "r2",
"task": "regression",
"log_file_name": "test/california.log",
}
X_tra... |
import numpy as np
from seisflows.tools import unix
from seisflows.tools.tools import loadtxt, savetxt, loadnpy, savenpy
from seisflows.optimize.lib.LBFGS import LBFGS
class LCG(object):
""" CG solver
"""
def __init__(self, path, load=loadnpy, save=savenpy, thresh=np.inf, maxiter=np.inf, precond=None):... |
# Load libraries
import flask
import pandas as pd
import tensorflow as tf
import keras
from keras.models import load_model
# instantiate flask
app = flask.Flask(__name__)
# load the model, and pass in the custom metric function
global graph
graph = tf.get_default_graph()
model = load_model('Model_final.h5')
@app.ro... |
from distutils.core import setup
setup(
name='KoSpeech',
version='1.0',
install_requires=[
'torch>=1.4.0',
'python-Levenshtein',
'librosa >= 0.7.0',
'numpy',
'pandas',
'tqdm',
'matplotlib',
'astropy',
'sentencepiece'
]
)
|
# Random Forest Regressor Example
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
def main():
"""
Random Forest Regr... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.sparse as sparse
from beta_rec.models.torch_engine import ModelEngine
class NGCF(torch.nn.Module):
"""Model initialisation, embedding generation and prediction of NGCF."""
def __init__(self, config, norm_adj):
"""Initial... |
import requests
__all__ = ['requests']
|
"""
# Definition for a Node.
class Node:
def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
self.val = val
self.left = left
self.right = right
self.next = next
"""
class Solution:
def connect(self, root: 'Optional[Node]') -> 'Optiona... |
"""Utilities for meta-estimators"""
# Author: Joel Nothman
# Andreas Mueller
# License: BSD
from typing import List, Any
from abc import ABCMeta, abstractmethod
from operator import attrgetter
from functools import update_wrapper
import numpy as np
from ..utils import _safe_indexing
from ..base im... |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name='PermutationImportancePhysics',
version='0.12',
packages=['permutationimportancephysics',],
author='A Ghosh',
description="Permutation Importance for Physics",
long_description=long... |
def longest_increasing_subsequence(d):
'Return one of the L.I.S. of list d'
l = []
for i in range(len(d)):
l.append(max([l[j] for j in range(i) if l[j][-1] < d[i]] or [[]], key=len)
+ [d[i]])
return max(l, key=len)
if __name__ == '__main__':
for d in [[3,2,6,4,5,1], [0, 8,... |
a = input().split()
b = input().split()
c = set(input().split())
d = set(input().split())
l_1 = []
l_2 = []
for i in b:
if i in c:
l_1.append(i)
if i in d:
l_2.append(i)
print(len(l_1) - len(l_2))
|
# epoch - 0 , train_acc - 0.0754 , test_acc - 0.0728
# epoch - 1 , train_acc - 0.86505 , test_acc - 0.865
# epoch - 2 , train_acc - 0.9139 , test_acc - 0.9139
# epoch - 3 , train_acc - 0.938466666667 , test_acc - 0.9385
# epoch - 4 , train_acc - 0.95845 , test_acc - 0.9538
# epoch - 5 , train_acc - 0.967166666667 , tes... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division
import unittest
import nussl
import numpy as np
import scipy.io.wavfile as wav
import scipy.io
import os
import warnings
# Freezes essential values from DUET in its current implementation for benchmarking
# See test_benchmark_duet() in tes... |
# In both open-source and fbcode builds, these are generated into
# torch/csrc/{autgrad,jit}/generated.i
GENERATED_CPP = [
"autograd/generated/Functions.cpp",
"autograd/generated/VariableType_0.cpp",
"autograd/generated/VariableType_1.cpp",
"autograd/generated/VariableType_2.cpp",
"autograd/generate... |
# -*- coding: utf-8 -*-
from pythainlp.collation import collation
print(collation(['ไก่','ไข่','ก','ฮา'])) # ['ก', 'ไก่', 'ไข่', 'ฮา'] |
def fizzbuzz():
end = 100
counter_3s = 0
counter_5s = 0
for i in range(1, end):
counter_3s += 1
counter_5s += 1
if(counter_3s != 3 and counter_5s != 5):
print(i)
continue
#No Python-version independent way to print without a newline... so:
str = ""
if(counter_3s == 3):
... |
#!/usr/local/bin/python3
# Copyright (c) KMG. 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
##
# sbk_charts : Stora... |
__all__ = ['Keymap']
from . import key
class Keymap:
def __init__(self, bindings, on_match = None, on_nomatch = None,
on_key = None):
self._on_match = on_match
self._on_nomatch = on_nomatch
self._on_key = on_key
self._top = {}
self._cur = self._top
... |
# Copyright 2018 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/env python3
# Copyright (c) 2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test bitcoin-wallet."""
import subprocess
import textwrap
from test_framework.test_framework import Bitcoin... |
class UPnPErrorCodeDescriptions(object):
_descriptions = {
401: 'No action by that name at this service.',
402: ('Could be any of the following: not enough in args, args in the wrong order, one or m'
'ore in args are of the wrong data type.'),
403: '(Deprecated - no not use)',
... |
x, y, z = 5, 3, 4
print((x == 5) and (y == 3))
print((y == 2) or (z == 3))
print(not (x == 3))
|
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/home/karamelm1nt/Documents/Code/TEPSimulation/ui/ui_main.ui'
#
# Created by: PyQt5 UI code generator 5.14.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_main_window(object)... |
# app/company_profile.py
# modules
import json # to parse JSON
import csv # to export to CSV
import os # operating system dependent functionality
import datetime
# packages
import requests
import plotly #plotly package used to chart daily prices
import plotly.graph_objs as go
from dotenv import load_dotenv # to maint... |
"""
Grid.py
Author: Jordan Mirocha
Affiliation: University of Colorado at Boulder
Created on: Thu Sep 20 14:18:27 2012
Description:
"""
import copy, types
import numpy as np
from ..util.Stats import rebin
from collections import Iterable
from ..physics.Hydrogen import Hydrogen
from ..physics.Cosmology import Cosm... |
from flask import render_template, current_app
from app.email import send_email
# Email Verification Email
def send_moreinfo_email(email):
send_email('[Energy Savers] Information',
sender=current_app.config['ADMINS'][0],
recipients=email,
text_body=render_template('email/more_info/more_info... |
import requests
"""Sends an email to the user to give them more info
about a landmark/treasure they just found
@Params:
email(string): Email address of user
landmark(string): name of landmark/treasure
landmarkImage(string): url to image of landmark/item
landmakerURL(string): link to pa... |
# -*- coding: utf-8 -*-
def booleans(request):
'''
Allow to use booleans in templates.
See: http://stackoverflow.com/questions/4557114/django-custom-template-tag-which-accepts-a-boolean-parameter
'''
return {
'True': True,
'true': True,
'False': False,
'false': Fa... |
import trees
a = [1, 2, 3]
b = [4, 5, 6]
a.append(b)
print(a)
a = [1, 2, 3]
a.extend(b)
print(a)
myDat, labels = trees.createDataSet()
print(myDat)
print(trees.splitDataSet(myDat, 0, 1))
print(trees.splitDataSet(myDat, 0, 0))
myDat, labels = trees.createDataSet()
print(trees.chooseBestFeatureToSplit(myDat))
print(m... |
from os.path import join, dirname
from setuptools import setup
here = dirname(__file__)
long_description = (open(join(here, "README.rst")).read() + "\n\n" +
open(join(here, "CHANGES.rst")).read() + "\n\n" +
open(join(here, "TODO.rst")).read())
def get_version():
fh = op... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib import ticker
from . import cm
#https://stackoverflow.com/questions/31940285/plot-a-polar-color-wheel-based-on-a-colormap-using-python-matplotlib
def color_wheel(cmap,fig=plt.figure(),figsize=(4,4)):
#Generate a figure with... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayTradeAppMergePayModel(object):
def __init__(self):
self._pre_order_no = None
@property
def pre_order_no(self):
return self._pre_order_no
@pre_order_no.setter
... |
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import numpy as np
import pyrobot.utils.util as prutil
from pyrobot.core import Camera
from pyrobot.utils.util import try_cv2_import
cv2 = tr... |
import pickle, torch
import numpy as np
import pandas as pd
target_epsilons = [1.1, 2.0, 4.0, 8.0, 14.0]
anticipated_Ts = [2, 5, 10, 20]
models_dict = {}
for eps in target_epsilons:
models_dict[eps] = pickle.load(open('./res/models_2019-11-05_{}.p'.format(eps), 'rb'))
X_test = pd.read_csv('./onehotted_data/encoded_... |
## @package model_helper_api
# Module caffe2.python.model_helper_api
import sys
import copy
import inspect
from past.builtins import basestring
from caffe2.python.model_helper import ModelHelper
# flake8: noqa
from caffe2.python.helpers.algebra import *
from caffe2.python.helpers.arg_scope import *
from caffe2.py... |
# noinspection PyUnresolvedReferences
from appify.common.get_parameters import get_parameter_default_annotations
# noinspection PyUnresolvedReferences
from appify.common.parameter_info import NoDefault, ParameterInfo
from ..utils import PYTHON3
if PYTHON3:
from .python3.get_parameter_defaults import * # noqa: F4... |
import random
import sys
from helper_objects.strategies.PointBasedStrategy import PointBasedStrategy
from one_time_scripts.visualisations.strategy_visualisation import visualize_strategy
def generate_fully_random_strategy(seed=None, name=None, strategy_price_step_size=None, number_of_points=None,
... |
import csv
import cv2
import numpy as np
# dataPath: folder path where all IMG's and driving_log's are stored
dataPath = 'data'
driving_log_list = {'driving_log.csv':'IMG', 'driving_log2.csv':'IMG2'}
correction = 0.5 # this is a parameter to tune
def get_image_from_sourcepath(source_path, folder):
filename = sou... |
# python3
"""Example: Number set partitioning such set sum(A) == sum(B)."""
# Based on this paper:
# https://cds.cern.ch/record/467590/files/0010018.pdf
#
# For a set A of integers, can A be partitioned into
# two sets A1 and A2, such that:
# sum(A1) == sum(A2)
#
# For this to work, sum(A) must not be odd.
# We ... |
import sys
import base64
import json
import subprocess
import traceback
import os.path
from functools import wraps
try:
import ssl
except ImportError:
ssl = False
PY2 = sys.version_info < (3, 0)
try:
import __builtin__
str_instances = (str, __builtin__.basestring)
except Exception:
str_instances... |
# Copyright 2014 Cisco Systems, 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 requir... |
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Tickfont(_BaseTraceHierarchyType):
# color
# -----
@property
def color(self):
"""
The 'color' property is a color and may be specified as:
- A hex string (e.g. '#f... |
# Copyright 2018 DeepMind Technologies Limited. 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 ... |
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: Apache 2.0 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
from __future__ import (absolute_import, division, print_function, unicode_literals)
import string
from .encoding_names import encodings
space_chars = frozenset(("\t", "\n", "\u000C", " ", "\r... |
# -*- coding: utf-8 -*-
# -*- Mode: Python -*-
# vi:si:et:sw=4:sts=4:ts=4
# F3AT - Flumotion Asynchronous Autonomous Agent Toolkit
# Copyright (C) 2010,2011 Flumotion Services, S.A.
# All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Pu... |
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pylibrary.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise Impo... |
#Python2.7
import requests
import argparse
import json
import re
import sys
def webgoat_stored_xss_attacks():
#start session
session = requests.Session()
#Webgoat login page get
host = '127.0.0.1'
port = '8082'
webgoat_main_address = 'http://' + host + ':' + port + '/WebGoat/'
webgoat_session = session.get( web... |
import os
import sys
from app import app
# SQLite URI compatible
WIN = sys.platform.startswith('win')
if WIN:
prefix = 'sqlite:///'
else:
prefix = 'sqlite:////'
dev_db = prefix + os.path.join(os.path.dirname(app.root_path), 'data.db')
SECRET_KEY = os.urandom(32)
app.config['SECRET_KEY'] = SECRET_KEY
SQLAL... |
from .external.initializers import *
# initializers from modified Keras
Initializer = Initializer
Zeros = Zeros
Ones = Ones
Constant = Constant
RandomNormal = RandomNormal
RandomUniform = RandomUniform
TruncatedNormal = TruncatedNormal
VarianceScaling = VarianceScaling
Orthogonal = Orthogonal
Identity = Identity
lecun... |
from typing import Union
from cryptography.fernet import Fernet
class EncryptedString:
_key: bytes = NotImplemented
_val: str
_f = False
@property
def value(self) -> str:
return Fernet(self._key).decrypt(self._val.encode('utf-8')).decode('utf-8')
@value.setter
def value(self, val... |
#
# Copyright (c) nexB Inc. and others. All rights reserved.
# ScanCode is a trademark of nexB Inc.
# SPDX-License-Identifier: Apache-2.0
# See http://www.apache.org/licenses/LICENSE-2.0 for the license text.
# See https://github.com/nexB/scancode-toolkit for support or download.
# See https://aboutcode.org for more in... |
""" This contains a function to run Mathematica commands from python.
Inspired from http://mathematica.stackexchange.com/questions/4643/how-to-use-mathematica-functions-in-python-programs
"""
__author__ = "marchdf"
import subprocess as sp
def run_mathematica_cmd(cmd):
print("Running Mathematica command: ", c... |
import re
import json
from numpy import array, squeeze
def sanityCheck(problem):
hasNaturalConstraints = False
keywordPattern = re.compile('max|min|s\.?t\.?|subject\s*to|with|end', re.IGNORECASE)
keywords = re.findall(keywordPattern, problem)
if re.match('max|min', keywords[0], re.IGNORECASE):
... |
import calendar
import datetime
import urllib
from datetime import timedelta
from typing import Any
from unittest.mock import patch
import orjson
import pytz
from django.conf import settings
from django.http import HttpResponse
from django.test import override_settings
from django.utils.timezone import now as timezone... |
from .convlstm import *
from .convmdn import *
from .ema import *
from .residual_blocks import ResidualBlock31
from .vq import *
from .vqvae import *
|
'''
Created on 11 Aug 2017
String rotation: Assume you have a method isSubstring which checks if one word is a substring
of another. Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using only one
call to isSubstring (e.g. "waterbottle" is rotation of "erbottlewat)
@author: igoroya
'''
def ... |
# -*- coding: utf-8 -*-
"""
eve-demo settings
~~~~~~~~~~~~~~~~~
Settings file for our little demo.
PLEASE NOTE: We don't need to create the two collections in MongoDB.
Actually, we don't even need to create the database: GET requests on an
empty/non-existant DB will be served correctly ('200'... |
# coding=utf-8
from __future__ import unicode_literals
import unittest
import six
from faker import Faker
class TestJob(unittest.TestCase):
"""
Test Job
"""
def setUp(self):
self.factory = Faker()
def test_job(self):
job = self.factory.job()
assert isinstance(job, six... |
import http.server
import socketserver
from os import listdir
import os
import pathlib
import sys
import webbrowser
def runserver(app_name, settings_path):
sys.path.append(os.path.dirname(settings_path))
import dipor_settings
settings_tmp = dipor_settings.instance
settings = { key: settings_tmp[key] f... |
__copyright__ = "Copyright (c) Microsoft Corporation and Mila - Quebec AI Institute"
__license__ = "MIT"
"""Boilerplate for training models easily with PyTorch.
"""
import time
from typing import Callable, Optional, Union
import torch
from torch.utils.data import DataLoader
from torch.optim import Optimizer
from tqd... |
"""Generated client library for sqladmin version v1beta3."""
# NOTE: This file is autogenerated and should not be edited by hand.
from googlecloudsdk.third_party.apitools.base.py import base_api
from googlecloudsdk.third_party.apis.sqladmin.v1beta3 import sqladmin_v1beta3_messages as messages
class SqladminV1beta3(ba... |
import glob
import pickle
import os
import sys
from cube2map.read_map_meta_data import read_map_data # type: ignore
def map_filename_to_map_name(map_filename):
return os.path.splitext(os.path.basename(map_filename))[0]
if len(sys.argv) < 3 or sys.argv[1] not in ('-l', '-d'):
sys.exit(1)
if sys.argv[1] == '... |
#
# Copyright 2013 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 require... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 OpenStack LLC.
# 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/... |
import streamlit as st
#from src.graph_controls import graph_controls
from src.graphs import graph_controls
from src.utility import load_dataframe
from streamlit.components.v1 import iframe
def views(link):
"""
Helper function for directing users to various pages.
:param link: str, option selected from the... |
import torch
import numpy as np
import sys
import time
from aevnmt.hparams import Hyperparameters
from aevnmt.data import TextDataset, RawInputTextDataset, remove_subword_tokens, postprocess
from aevnmt.train_monolingual import create_model
from aevnmt.train_utils import load_vocabularies, load_vocabularies_monolingua... |
def handle_uploaded_file(f):
with open('nacm1/static/upload/'+f.name, 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
|
# Test the module type
import unittest
# import weakref
# from test.support import gc_collect
# from test.support.script_helper import assert_python_ok
import sys
ModuleType = type(sys)
class Descr:
def __get__(self, o, t):
raise RuntimeError
class FullLoader:
@classmethod
def module_repr(cls, m):... |
import asyncio
import datetime
import json
import re
from typing import List,NamedTuple
import sys
import aiohttp
import bs4
import requests
from utils import get_cookies, get_headers
headers = get_headers()
cookies = get_cookies()
class Course(NamedTuple):
name:str
desc:str
year:int
link:str
class... |
from setuptools import setup
from os import path
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='Flask-SimplePay',
version='0.11',
packages=['flask_simplepay'],
url='https://g... |
from importlib_metadata import version
from hnlp.node import Node, N
from hnlp.register import Register
from hnlp.dataset import Corpus, Preprocessor, Tokenizer, MapStyleDataset, DataManager
from hnlp.trainer import Trainer
from hnlp.layer import Embeddings, InteractiveSelfAttention
from hnlp.module import pretraine... |
from direct.directnotify import DirectNotifyGlobal
from direct.distributed.DistributedObjectUD import DistributedObjectUD
class RATManagerUD(DistributedObjectUD):
notify = DirectNotifyGlobal.directNotify.newCategory('RATManagerUD')
|
import pickle
from collections import Counter
import math
from loctext.util import PRO_ID, LOC_ID, ORG_ID, REL_PRO_LOC_ID, GO_NORM_ID, repo_path
import re
in_path = "resources/features/SwissProt_all_corpus_organisms_relations__2017-02-15.tsv"
# get all uniprot identifiers: cat <...>.tsv | awk '{print $1}' | sort | un... |
"""Only used to spawn multiple simulations and evaluate performance.
This script is similar to `examples/fly.py` and used by `parallelism.sh`.
"""
import os
import time
import argparse
from datetime import datetime
import pdb
import math
import random
import numpy as np
import pybullet as p
import matplotlib.pyplot a... |
# Every server should implement "run" function.
# If need reload feature, server should implement "reload" function.
# "reload" function in this module is designed for reloading programtically.
# And this "reload" will only work in the main process.
# "reload" feature for APP should be implement manually.
# Example for... |
# 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... |
class Movie:
"""
This class containes the attibutes which will be used to display the movies with the trailer.
"""
def __init__(
self,
movie_title,
movie_storyline,
poster_image,
trailer_youtube):
"""
:param movie_title: The ti... |
"""
Abhilash Reddy Malipeddi. January 2017
Calculate the mean and gaussian curvature at a vertex in a tri mesh using
using an iterative fitting method similar to what is given in [Garimella and Swartz],
[Yazdani and Bagchi], etc.
"""
import numpy as np
from numpy.linalg import lstsq
from .utils import tr... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.12 on 2018-09-05 12:30
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("spots", "0004_auto_20180602_2110")]
operations = [
migrations.AlterField(
m... |
#!/usr/bin/env python3
# coding=utf-8
# note: if you are on linux, you might have to run
# with sudo
# If you don't want to run with sudo, you can try
# adding dialout to your user (requires a logout to
# take effect:
# $ sudo usermod -a -G dialout $USER
import os
import sys
import argparse
import socket
import js... |
from uuid import uuid4
from telegram import (
Update,
InlineKeyboardButton,
InlineKeyboardMarkup,
InlineQueryResultArticle,
InlineQueryResultDocument
)
from subtitle import (
BASE_URL,
get_lang,
search_sub
)
def button(update, context):
query = update.callback_query
query.ans... |
# -*- coding: utf-8 -*-
#
# Copyright 2013 - Noorul Islam K M
#
# 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 applic... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.