repo_name stringlengths 6 97 | path stringlengths 3 341 | text stringlengths 8 1.02M |
|---|---|---|
bobkentt/Learning-machine-from-scratch- | practice/code/deeplearning/Cnn_with_keras.py |
# coding: utf-8
# # CNN 卷积神经网络
# In[1]:
import numpy as np
np.random.seed(1337) # for reproducibility
from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dense, Activation, Convolution2D, MaxPooling2D, Flatten
from keras.optimizers import ... |
caiomcg/OS-PageSubstitution | Python/OTM.py | from Algorithm import Algorithm #Base class
"""
Author: <NAME>
E-Mail: <EMAIL>
License:
MIT License
Copyright (c) 2016 <NAME>
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 restrictio... |
caiomcg/OS-PageSubstitution | Python/FIFO.py | from Algorithm import Algorithm #Base class
"""
Author: <NAME>
E-Mail: <EMAIL>
License:
MIT License
Copyright (c) 2016 <NAME>
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 restrictio... |
caiomcg/OS-PageSubstitution | Python/Algorithm.py | class Algorithm:
"""
Algorithm Class
Base class for the page substitution algorithms.
"""
def __init__(self, input = []):
"""
Algorithm Constructor.
Parameters
----------
input : list
A list containing the the input page swap.
"""
if not input: #If the list is empty throw an exception.
raise... |
caiomcg/OS-PageSubstitution | Python/LRU.py | <reponame>caiomcg/OS-PageSubstitution<filename>Python/LRU.py
from Algorithm import Algorithm #Base class
"""
Author: <NAME>
E-Mail: <EMAIL>
License:
MIT License
Copyright (c) 2016 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files... |
victorysq/flask-blog | app/__init__.py | import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from config import basedir
from flask_mail import Mail
app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)
mail = Mail(app)
lm = LoginManager()
lm.init_app(app)
lm.login_view = 'logi... |
victorysq/flask-blog | db_migrate.py | import imp
import os
from migrate.versioning import api
from app import db
from config import SQLALCHEMY_DATABASE_URI
from config import SQLALCHEMY_MIGRATE_REPO
# 第一步:创建数据库,
# 如果数据库存在,create_all()是自动不执行的。
try:
db.create_all()
if not os.path.exists(SQLALCHEMY_MIGRATE_REPO):
api.create(SQLALCHEMY_MIG... |
victorysq/flask-blog | app/views.py | <filename>app/views.py
from flask import render_template, flash, redirect, session, url_for, request, g
from app import app, db, lm
from .models import User, Post
from .forms import LoginForm, EditForm, PostForm
from flask_login import login_user, logout_user, current_user, login_required
from datetime import datetime
... |
Zain117/Misc | banscript/banplugin.py | <gh_stars>0
#IP ban script
def returnState(ip):
with open("banlist.txt","r"):
for x in f.readlines():
e = x.split("/")
if e[0] == ip:
return True
def Ban(ip):
with open("banlist.txt", "a") as f:
f.write(ip)
f.close()
if argv[1] == "!ban":
Ba... |
GeoStat-Framework/AnaFlow | examples/07_compare_extthiem3d_grfsteady.py | <gh_stars>10-100
r"""
extended Thiem 3D vs. steady solution for coarse graining conductivity
======================================================================
The extended Thiem 3D solutions is the analytical solution of the groundwater
flow equation for the coarse graining conductivity for pumping tests.
Therefo... |
GeoStat-Framework/AnaFlow | examples/10_convergence_ext_theis_tpl.py | r"""
Convergence of the extended Theis solutions for truncated power laws
====================================================================
Here we set an outer boundary to the transient solution, so this condition
coincides with the references head of the steady solution.
Reference: (not yet published)
"""
import... |
GeoStat-Framework/AnaFlow | examples/12_compare_theis_quasi_steady.py | r"""
Quasi steady convergence
========================
The quasi steady is reached, when the radial shape of the drawdown in not
changing anymore.
"""
import numpy as np
from matplotlib import pyplot as plt
from anaflow import theis, thiem
time = [10, 100, 1000]
rad = np.geomspace(0.1, 10)
r_ref = 10.0
head_ref = t... |
GeoStat-Framework/AnaFlow | examples/02_call_ext_theis2d.py | r"""
The extended Theis solution in 2D
=================================
We provide an extended theis solution, that incorporates the effectes of a
heterogeneous transmissivity field on a pumping test.
In the following this extended solution is compared to the standard theis
solution for well flow. You can nicely see... |
GeoStat-Framework/AnaFlow | examples/13_self_defined_transmissivity.py | r"""
Self defined radial conductivity or transmissivity
==================================================
All heterogeneous solutions of AnaFlow are derived by calculating an equivalent
step function of a radial symmetric transmissivity resp. conductivity function.
The following code shows how to apply this workflow... |
GeoStat-Framework/AnaFlow | examples/08_compare_extthiem2d_neuman.py | r"""
extended Thiem 2D vs. steady solution for apparent transmissivity from Neuman
=============================================================================
Both, the extended Thiem and the Neuman solution, represent an effective steady
drawdown in a heterogeneous aquifer.
In both cases the heterogeneity is repres... |
GeoStat-Framework/AnaFlow | examples/03_call_ext_theis3d.py | <filename>examples/03_call_ext_theis3d.py
r"""
The extended Theis solution in 3D
=================================
We provide an extended theis solution, that incorporates the effectes of a
heterogeneous conductivity field on a pumping test.
It also includes an anisotropy ratio of the horizontal and vertical length
sc... |
GeoStat-Framework/AnaFlow | examples/05_call_neuman2004.py | r"""
The transient heterogeneous Neuman solution from 2004
=====================================================
We provide the transient pumping solution for the apparent transmissivity from
Neuman 2004.
This solution is build on the apparent transmissivity from Neuman 2004,
which represents a mean drawdown in an ens... |
GeoStat-Framework/AnaFlow | examples/15_accruing_theis.py | <gh_stars>10-100
r"""
Accruing pumping rate
=====================
AnaFlow provides different representations for the pumping condition.
One is an accruing pumping rate represented by the error function.
This could be interpreted as that the water pump needs a certain time to
reach its constant rate state.
"""
import n... |
GeoStat-Framework/AnaFlow | examples/06_compare_extthiem2d_grfsteady.py | r"""
extended Thiem 2D vs. steady solution for coarse graining transmissivity
========================================================================
The extended Thiem 2D solutions is the analytical solution of the groundwater
flow equation for the coarse graining transmissivity for pumping tests.
Therefore the resu... |
GeoStat-Framework/AnaFlow | examples/11_convergence_ext_grf.py | <reponame>GeoStat-Framework/AnaFlow
r"""
Convergence of the general radial flow model (GRF)
==================================================
The GRF model introduces an arbitrary flow dimension and was presented to
analyze groundwater flow in rock formations.
In the following we compare the bounded transient solutio... |
GeoStat-Framework/AnaFlow | examples/09_compare_exttheis2d_neuman.py | r"""
extended Theis 2D vs. transient solution for apparent transmissivity from Neuman
================================================================================
Both, the extended Theis and the Neuman solution, represent an effective transient
drawdown in a heterogeneous aquifer.
In both cases the heterogeneity ... |
GeoStat-Framework/AnaFlow | examples/14_interval_theis.py | <reponame>GeoStat-Framework/AnaFlow
r"""
Interval pumping
================
Another case often discussed in literatur is interval pumping, where
the pumping is just done in a certain time frame.
Unfortunatly the Stehfest algorithm is not suitable for this kind of solution,
which is demonstrated in the following script... |
alckasoc/Joblisting-Webscraper | src/webscraper.py | <gh_stars>1-10
import re
import time
import pandas as pd
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from elements import ConfigElements, WebScrapingElements
class GlassdoorWebScraper(ConfigElements, WebScrapingElements):
""" A GlassdoorWebScraper obj will be able to configur... |
alckasoc/Joblisting-Webscraper | src/elements.py |
import re
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from locators import ConfigLocators as CL
from locators import WebScrapingLocators... |
alckasoc/Joblisting-Webscraper | src/locators.py | <reponame>alckasoc/Joblisting-Webscraper<gh_stars>1-10
from selenium.webdriver.common.by import By
class ConfigLocators:
"""ConfigLocators contains the locators for configuration i.e. filters.
Locators are in uppercase because they are constants and are
grouped by category. Categories are denoted by... |
chufucun/learn-python3 | samples/functional/do_map.py | <reponame>chufucun/learn-python3<gh_stars>0
#!/usr/bin/env python
# encoding: utf-8
"""
map(func, *iterables) --> map object
map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。
"""
def square(x):
return x * x
iter = map(square, [1, 2, 3, 4])
print(list(iter))
# [1, 4, 9, 16]
iter = map(l... |
chufucun/learn-python3 | samples/functional/do_reduce.py | <gh_stars>0
#!/usr/bin/env python
# encoding: utf-8
"""
reduce(function, sequence[, initial]) -> value
解释:先将 sequence 的前两个 item 传给 function,即 function(item1, item2),函数的返回值和 sequence 的下一个 item 再传给 function,即 function(function(item1, item2), item3),如此迭代,直到 sequence 没有元素,如果有 initial,则作为初始值调用。
效果等同:
reduece(f, [x1, x2, x... |
chufucun/learn-python3 | samples/functional/do_filter.py | <filename>samples/functional/do_filter.py
#!/usr/bin/env python
# encoding: utf-8
"""
filter(function or None, iterable) --> filter object
filter()也接收一个函数和一个序列。和map()不同的是,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。
filter()的作用是从一个序列中筛出符合条件的元素。由于filter()使用了惰性计算,所以只有在取filter()结果的时候,才会真正筛选并每次返回下一个筛出的元素。
"""
... |
tirth1/recipe-app-api | app/core/apps.py | from django.apps import AppConfig
# This is the corresponding application core
class BooktestConfig(AppConfig):
name = 'core'
|
SteveSunTech/GlobalTrends | backend_server/operations.py | <gh_stars>1-10
import json
import pickle
import redis
from datetime import datetime
from bson.json_util import dumps
from tap_news_utils.mongodb_client import MongoDBClient
from tap_news_utils.cloudAMQP_client import CloudAMQPClient
from tap_news_utils.news_recommender_client import NewsRecommenderClient
from config ... |
SteveSunTech/GlobalTrends | recommendation_service/click_log_processor.py | <gh_stars>0
# -*- coding: utf-8 -*-
'''
Time decay model:
If selected:
p = (1-α)p + α
If not:
p = (1-α)p
Where p is the selection probability, and α is the degree of weight decrease.
The result of this is that the nth most recent selection will have a weight of
(1-α)^n. Using a coefficient value of 0.05 as an example,... |
SteveSunTech/GlobalTrends | backend_server/operations_test.py | <gh_stars>1-10
import operations
def test_getNewsSummariesForUser_basic():
news = operations.getNewsSummariesForUser('test', 1)
print ('operations_test getNewsSummariesForUser', news)
one_news = operations.getOneNews()
print ('operations_test getOneNews', one_news)
if __name__=="__main__":
while (... |
SteveSunTech/GlobalTrends | news_pipeline/scrapers/cnn_news_scraper.py | <filename>news_pipeline/scrapers/cnn_news_scraper.py<gh_stars>0
import os
import random
import requests
from lxml import html
GET_CNN_NEWS_XPATH = """//p[contains(@class, 'zn-body__paragraph')]//text() | //div[contains(@class, 'zn-body__paragraph')]//text()"""
# Load user agents
USER_AGENTS_FILE = os.path.join(os.pa... |
SteveSunTech/GlobalTrends | common/news_recommendation_service_client.py | <filename>common/news_recommendation_service_client.py
import jsonrpclib
URL = "http://localhost:5050/"
client = jsonrpclib.ServerProxy(URL)
def getPreferenceForUser(userId):
preference = client.getPreferenceForUser(userId)
print("Preference list: %s" % str(preference))
return preference |
SteveSunTech/GlobalTrends | recommendation_service/news_classes.py | <reponame>SteveSunTech/GlobalTrends
classes = [
"World",
"US",
"Business",
"Technology",
"Entertainment",
"Sports",
"Health",
"Crime",
] |
SteveSunTech/GlobalTrends | news_pipeline/news_deduper.py | import datetime
import os
import sys
from dateutil import parser
from sklearn.feature_extraction.text import TfidfVectorizer
# import common package in parent directory
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'common'))
import mongodb_client
from cloudAMQP_client import CloudAMQPClient
DEDUPE_... |
SteveSunTech/GlobalTrends | news_pipeline/news_fetcher.py | import os
import sys
from newspaper import Article
# import common package in parent directory
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'common'))
from cloudAMQP_client import CloudAMQPClient
DEDUPE_NEWS_TASK_QUEUE_URL = "amqp://mycayzfr:E4nnofIrEfvgW4oByDmkoBjvsmobCzFG@<EMAIL>.com/mycayzfr"
DE... |
SteveSunTech/GlobalTrends | backend_server/service.py | <gh_stars>1-10
from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
import operations
from config import RPC_SERVER_HOST, RPC_SERVER_PORT
"""
RPC server = a computer program causes a procedure (subroutine) to execute in a different address space (commonly on another computer on a shared network),
... |
SteveSunTech/GlobalTrends | common/mongodb_client.py | <reponame>SteveSunTech/GlobalTrends<gh_stars>0
from pymongo import MongoClient
MONGO_DB_HOST = "localhost"
MONGO_DB_PORT = 27017
DB_NAME = "top-news"
client = MongoClient(MONGO_DB_HOST, MONGO_DB_PORT)
def get_db(db=DB_NAME):
db = client[db]
return db |
SteveSunTech/GlobalTrends | common/news_api_client.py | <filename>common/news_api_client.py<gh_stars>0
import requests
from json import loads
CNN = 'cnn'
DEFAULT_SOURCES = [CNN]
SORT_BY_TOP = 'top'
NEWS_API_KEY = '68692dceeaff48139b7728d1175d2686'
NEWS_API_ENDPOINT = "https://newsapi.org/v1/"
ARTICLES_API = "articles"
def _buildUrl(endPoint = NEWS_API_ENDPOINT, apiName = ... |
SteveSunTech/GlobalTrends | news_pipeline/news_monitor.py | <filename>news_pipeline/news_monitor.py
import datetime
import hashlib
import redis
import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'common'))
import news_api_client
from cloudAMQP_client import CloudAMQPClient
SLEEP_TIME_IN_SECONDS = 10
NEWS_TIME_OUT_IN_SECONDS = 3600 * 24 * 3
RE... |
SteveSunTech/GlobalTrends | news_pipeline/queue_helper.py |
import os
import sys
# import common package in parent directory
sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'common'))
from cloudAMQP_client import CloudAMQPClient
DEDUPE_NEWS_TASK_QUEUE_URL = "amqp://mycayzfr:E4nnofIrEfvgW4oByDmkoBjvsmobCzFG@termite.rmq.cloudamqp.com/mycayzfr"
DEDUPE_NEWS_TASK_Q... |
SteveSunTech/GlobalTrends | common/cloudAMQP_client_test.py | <filename>common/cloudAMQP_client_test.py<gh_stars>0
from cloudAMQP_client import CloudAMQPClient
CloudAMQP_URL = "amqp://mycayzfr:<EMAIL>/mycayzfr"
TEST_QUEUE_NAME = "test"
def test_basic():
client = CloudAMQPClient(CloudAMQP_URL,TEST_QUEUE_NAME )
sentMsg = {"test":"test"}
client.sendMessage(sentMsg)
revei... |
dumpmemory/roformer-sim | train/supervised.py | #! -*- coding: utf-8 -*-
# SimBERT v2 监督训练代码
# 训练环境:tensorflow 1.14 + keras 2.3.1 + bert4keras 0.10.6
import json, glob
import numpy as np
import tensorflow as tf
from bert4keras.backend import keras, K
from bert4keras.models import build_transformer_model
from bert4keras.tokenizers import Tokenizer
from bert4keras.op... |
dumpmemory/roformer-sim | test/retrieval.py | <filename>test/retrieval.py
#! -*- coding: utf-8 -*-
# 测试有监督版RoFormer-Sim-FT的相似度效果
import numpy as np
from bert4keras.backend import keras
from bert4keras.models import build_transformer_model
from bert4keras.tokenizers import Tokenizer
from bert4keras.snippets import sequence_padding
from keras.models import Model
m... |
dumpmemory/roformer-sim | test/generate.py | #! -*- coding: utf-8 -*-
# RoFormer-Sim base 基本例子
# 测试环境:tensorflow 1.14 + keras 2.3.1 + bert4keras 0.10.6
import numpy as np
from bert4keras.backend import keras, K
from bert4keras.models import build_transformer_model
from bert4keras.tokenizers import Tokenizer
from bert4keras.snippets import sequence_padding, AutoR... |
grnspace/django-oauth-toolkit | oauth2_provider/__init__.py | import pkg_resources
__version__ = pkg_resources.require("django-oauth-toolkit")[0].version
default_app_config = "oauth2_provider.apps.DOTConfig"
|
grnspace/django-oauth-toolkit | tests/test_rest_framework.py | from datetime import timedelta
from django.conf.urls import include
from django.contrib.auth import get_user_model
from django.core.exceptions import ImproperlyConfigured
from django.http import HttpResponse
from django.test import TestCase
from django.test.utils import override_settings
from django.urls import path, ... |
grnspace/django-oauth-toolkit | oauth2_provider/signals.py | <reponame>grnspace/django-oauth-toolkit<gh_stars>1000+
from django.dispatch import Signal
app_authorized = Signal() # providing_args=["request", "token"]
|
grnspace/django-oauth-toolkit | oauth2_provider/migrations/0002_auto_20190406_1805.py | from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('oauth2_provider', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='grant',
name='code_challenge',
field=models.CharField(blank=True, de... |
grnspace/django-oauth-toolkit | oauth2_provider/http.py | from urllib.parse import urlparse
from django.core.exceptions import DisallowedRedirect
from django.http import HttpResponse
from django.utils.encoding import iri_to_uri
class OAuth2ResponseRedirect(HttpResponse):
"""
An HTTP 302 redirect with an explicit list of allowed schemes.
Works like django.http.H... |
grnspace/django-oauth-toolkit | tests/models.py | from django.db import models
from oauth2_provider.models import (
AbstractAccessToken, AbstractApplication,
AbstractGrant, AbstractRefreshToken
)
from oauth2_provider.settings import oauth2_settings
class BaseTestApplication(AbstractApplication):
allowed_schemes = models.TextField(blank=True)
def ge... |
grnspace/django-oauth-toolkit | oauth2_provider/compat.py | """
The `compat` module provides support for backwards compatibility with older
versions of Django and Python.
"""
|
grnspace/django-oauth-toolkit | oauth2_provider/backends.py | <filename>oauth2_provider/backends.py
from django.contrib.auth import get_user_model
from .oauth2_backends import get_oauthlib_core
UserModel = get_user_model()
OAuthLibCore = get_oauthlib_core()
class OAuth2Backend:
"""
Authenticate against an OAuth2 access token
"""
def authenticate(self, reques... |
grnspace/django-oauth-toolkit | oauth2_provider/middleware.py | <gh_stars>1-10
from django.contrib.auth import authenticate
from django.utils.cache import patch_vary_headers
from django.utils.deprecation import MiddlewareMixin
class OAuth2TokenMiddleware(MiddlewareMixin):
"""
Middleware for OAuth2 user authentication
This middleware is able to work along with Authent... |
grnspace/django-oauth-toolkit | tests/test_token_view.py | import datetime
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from django.utils import timezone
from oauth2_provider.models import get_access_token_model, get_application_model
Application = get_application_model()
AccessToken = get_access_token_mode... |
grnspace/django-oauth-toolkit | oauth2_provider/generators.py | from oauthlib.common import UNICODE_ASCII_CHARACTER_SET
from oauthlib.common import generate_client_id as oauthlib_generate_client_id
from .settings import oauth2_settings
class BaseHashGenerator:
"""
All generators should extend this class overriding `.hash()` method.
"""
def hash(self):
rai... |
grnspace/django-oauth-toolkit | oauth2_provider/views/__init__.py | <reponame>grnspace/django-oauth-toolkit<gh_stars>0
# flake8: noqa
from .application import (
ApplicationDelete, ApplicationDetail, ApplicationList,
ApplicationRegistration, ApplicationUpdate
)
from .base import AuthorizationView, RevokeTokenView, TokenView
from .generic import (
ProtectedResourceView, ReadW... |
grnspace/django-oauth-toolkit | tests/urls.py | from django.contrib import admin
from django.urls import include, re_path
admin.autodiscover()
urlpatterns = [
re_path(r"^o/", include("oauth2_provider.urls", namespace="oauth2_provider")),
re_path(r"^admin/", admin.site.urls),
]
|
grnspace/django-oauth-toolkit | tests/utils.py | import base64
def get_basic_auth_header(user, password):
"""
Return a dict containing the correct headers to set to make HTTP Basic
Auth request
"""
user_pass = "{0}:{1}".format(user, password)
auth_string = base64.b64encode(user_pass.encode("utf-8"))
auth_headers = {
"HTTP_AUTHORI... |
grnspace/django-oauth-toolkit | oauth2_provider/contrib/rest_framework/__init__.py | # flake8: noqa
from .authentication import OAuth2Authentication
from .permissions import (
TokenHasScope, TokenHasReadWriteScope, TokenMatchesOASRequirements,
TokenHasResourceScope, IsAuthenticatedOrTokenHasScope
)
|
grnspace/django-oauth-toolkit | tests/test_oidc_views.py | <reponame>grnspace/django-oauth-toolkit<filename>tests/test_oidc_views.py<gh_stars>0
from __future__ import unicode_literals
from django.test import TestCase
from django.urls import reverse
from oauth2_provider.settings import oauth2_settings
class TestConnectDiscoveryInfoView(TestCase):
def test_get_connect_di... |
fgdorais/MarkovModel | trainer.py | from __future__ import unicode_literals # Python 2/3 compatibility #
class MarkovTrainer:
def __init__(self, depth=3):
self.tdata = {'': {}}
self.depth = depth
self.thist = []
def reset(self):
"""Clear the list of remembered tokens"""
self.thist = []
d... |
fgdorais/MarkovModel | modelio.py | import sys
import csv
# Module csv in Python 2 doesn't natively support unicode, so utf-8
# encoding/decoding must be done manually. Python 2 csv also requires
# for files to be opened in binary mode.
if sys.version_info[0] == 3:
def encode(s):
return s
def decode(s):
return s
def csvopen(f... |
fgdorais/MarkovModel | generator.py | <reponame>fgdorais/MarkovModel<gh_stars>0
from __future__ import unicode_literals # Python 2/3 compatibility #
import random
class MarkovGenerator:
"""Generate random text using Markov model"""
def __init__(self, model, depth=3):
self.depth = depth
self.model = model
self.thist = ... |
fgdorais/MarkovModel | markov.py | from __future__ import unicode_literals # Python 2/3 compatibility #
from __future__ import print_function # Python 2/3 compatibility #
import sys
import argparse
import modelio
from parser import TokenParser
from trainer import MarkovTrainer
from generator import MarkovGenerator
parser = argparse.ArgumentParser(d... |
fgdorais/MarkovModel | parser.py | from __future__ import unicode_literals # Python 2/3 compatibility #
import codecs
import unicodedata
class TokenParser:
"""Parse a Unicode text stream into space/control separated tokens
Space and control characters are identified using Unicode general
category values as defined in section 4.5 of Th... |
liqi17thu/nasbench-1shot1 | nasbench_analysis/test.py | import argparse
import pickle
import numpy as np
from nasbench_analysis.search_spaces.search_space_1 import SearchSpace1
from nasbench_analysis.search_spaces.search_space_2 import SearchSpace2
from nasbench_analysis.search_spaces.search_space_3 import SearchSpace3
import json
import logging
import os
import random
i... |
moisesejimenezg/behavioral_cloning | src/session_handler.py | <reponame>moisesejimenezg/behavioral_cloning
import csv
import cv2
import numpy as np
class SessionHandler:
def __init__(self, session_path):
self.session_path = session_path
self.data = self.__read()
def get_data(self):
return self.data
def get_center_images(self):
return... |
moisesejimenezg/behavioral_cloning | src/test/session_handler.py | <reponame>moisesejimenezg/behavioral_cloning<gh_stars>0
import pytest
from src.session_handler import SessionHandler
def test_reading_file():
session_handler = SessionHandler("data/driving_log.csv")
assert(len(session_handler.get_data()) == 4)
assert(len(session_handler.get_center_images()) == 10)
ass... |
moisesejimenezg/behavioral_cloning | main.py | from src.model import Model
from src.session_handler import SessionHandler
import numpy as np
from os.path import exists
path = "data/driving_log.csv"
session_handler = SessionHandler(path)
model = Model()
if exists('model.h5'):
model.load_model()
model.fit_model(
np.concatenate(
(
sessio... |
moisesejimenezg/behavioral_cloning | src/model.py | <reponame>moisesejimenezg/behavioral_cloning
from keras.models import Sequential, load_model
from keras.layers import Cropping2D
from keras.layers.core import Dense, Activation, Flatten, Dropout, Lambda
from keras.layers.convolutional import Conv2D, Convolution2D
from keras.layers.pooling import MaxPooling2D
from keras... |
playfire/django-dynamic-subdomains | dynamic_subdomains/defaults.py | <gh_stars>1-10
from django.core.exceptions import ImproperlyConfigured
from django.utils.datastructures import SortedDict
def patterns(*args):
subdomains = SortedDict()
for x in args:
name = x['name']
if name in subdomains:
raise ImproperlyConfigured("Duplicate subdomain name: %s"... |
playfire/django-dynamic-subdomains | setup.py | <gh_stars>1-10
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='django-dynamic-subdomains',
description="Dynamic and static subdomain support for Django.",
version='0.1',
url='http://code.playfire.com/',
author='Playfire.com',
author_email='<EMAIL>',
license=... |
playfire/django-dynamic-subdomains | dynamic_subdomains/models.py | import debug_toolbar.urls
from django.conf import settings
from django.conf.urls import patterns, include
from .urls import urlpatterns
debug_toolbar.urls.urlpatterns += patterns('',
('', include(urlpatterns)),
)
|
playfire/django-dynamic-subdomains | dynamic_subdomains/middleware.py | import re
import threading
from django.conf import settings
from django.core.exceptions import MiddlewareNotUsed, ImproperlyConfigured
from django.core.urlresolvers import set_urlconf
from .utils import from_dotted_path
_thread_local = threading.local()
class SubdomainMiddleware(object):
"""
Adjust incoming... |
Snopoff/Mapper-experiments | files/gtda/mapper/visualization.py | <filename>files/gtda/mapper/visualization.py
"""Static and interactive visualisation functions for Mapper graphs."""
# License: GNU AGPLv3
import logging
import traceback
from copy import deepcopy
from warnings import warn
import numpy as np
import plotly.graph_objects as go
from ipywidgets import widgets, Layout, HT... |
Snopoff/Mapper-experiments | files/gtda/mapper/utils/_visualization.py | """Graph layout functions and plotly layout functions."""
# License: GNU AGPLv3
from operator import iconcat
from copy import deepcopy
from functools import reduce, partial
import numpy as np
import plotly.graph_objs as go
PLOT_OPTIONS_NODE_TRACE_DEFAULTS = {
"name": "node_trace",
"mode": "markers",
"hov... |
jaskarannagi19/donkeycar | setup.py | from setuptools import setup, find_packages
import os
with open("README.md", "r") as fh:
long_description = fh.read()
setup(name='donkeycar',
version='2.5.2',
description='Self driving library for python.',
long_description=long_description,
long_description_content_type="text/markdown",... |
zaqqwerty/pennylane | pennylane/beta/plugins/expt_tensornet_tf.py | # Copyright 2019 Xanadu Quantum Technologies 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 or agre... |
zaqqwerty/pennylane | pennylane/qnodes/decorator.py | <gh_stars>1-10
# Copyright 2019 Xanadu Quantum Technologies 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 applica... |
zaqqwerty/pennylane | pennylane/beta/plugins/expt_tensornet.py | <reponame>zaqqwerty/pennylane
# Copyright 2018-2019 Xanadu Quantum Technologies 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... |
zaqqwerty/pennylane | pennylane/measure.py | # Copyright 2019 Xanadu Quantum Technologies 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 or agre... |
zaqqwerty/pennylane | tests/test_io.py | <reponame>zaqqwerty/pennylane<gh_stars>1-10
# Copyright 2020 Xanadu Quantum Technologies 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
... |
zaqqwerty/pennylane | pennylane/templates/layers.py | # Copyright 2018-2019 Xanadu Quantum Technologies 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 or... |
zaqqwerty/pennylane | pennylane/io.py | # Copyright 2020 Xanadu Quantum Technologies 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 or agre... |
zaqqwerty/pennylane | tests/test_collections.py | <filename>tests/test_collections.py
# Copyright 2018-2020 Xanadu Quantum Technologies 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
# ... |
zaqqwerty/pennylane | tests/test_templates_decorator.py | <filename>tests/test_templates_decorator.py<gh_stars>1-10
# Copyright 2020 Xanadu Quantum Technologies 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/license... |
zaqqwerty/pennylane | pennylane/templates/subroutines.py | <reponame>zaqqwerty/pennylane
# Copyright 2018-2019 Xanadu Quantum Technologies 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... |
zaqqwerty/pennylane | qchem/pennylane_qchem/qchem.py | # Copyright 2018-2019 Xanadu Quantum Technologies 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 or... |
zaqqwerty/pennylane | pennylane/collections.py | <filename>pennylane/collections.py
# Copyright 2018-2020 Xanadu Quantum Technologies 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
# U... |
ales-kunst/cpp_project | conanfile.py | from conans import ConanFile, CMake
class PocoTimerConan(ConanFile):
settings = "os", "compiler", "build_type", "arch"
requires = "spdlog/1.8.0" # "zeromq/4.3.3", "rapidjson/cci.20200410"
default_options = {
"spdlog:shared": False,
"spdlog:header_only": True,
"spdlog:no_exceptions": False
... |
Yakings/system_demo | flask_web/flask_app/deep_learning/models_mse_loss/utils.py | import numpy as np
import tensorflow as tf
## TensorFlow helper functions
WEIGHT_DECAY_KEY = 'WEIGHT_DECAY'
def _relu(x, leakness=0.0, name=None):
if leakness > 0.0:
name = 'lrelu' if name is None else name
return tf.maximum(x, x*leakness, name='lrelu')
else:
name = 'relu' if name is ... |
Yakings/system_demo | flask_web/flask_app/deep_learning/models_mse_loss/read_util/read_train_data.py | import os
import numpy as np
def get_all_file(filepath):
files = os.listdir(filepath)
file_list = []
for fi in files:
fi_d = os.path.join(filepath, fi)
if os.path.isdir(fi_d):
get_all_file(fi_d)
elif 'acc_' in fi_d:
# file_list.append(os.path.join(filepath, fi... |
Yakings/system_demo | app/cx_freeze_func.py | <filename>app/cx_freeze_func.py<gh_stars>0
#!/usr/bin/env python
# coding:utf-8
from cx_Freeze import setup, Executable
# Dependencies are automatically detected, but it might need
# fine tuning.
# cxfreeze_func.py build
import sys
import os.path
os.environ['TCL_LIBRARY'] = r'C:\Python36\tcl\tcl8.6'
os.environ['TK_L... |
Yakings/system_demo | flask_web/flask_app/bearing_master/dl_function/write_utils.py | import json
import os
import csv
def mkdir(path):
# 引入模块
import os
# 去除首位空格
path = path.strip()
# 去除尾部 \ 符号
path = path.rstrip("\\")
# 判断路径是否存在
# 存在 True
# 不存在 False
isExists = os.path.exists(path)
# 判断结果
if not isExists:
# 如果不存在则创建目录
# 创建目录操作函数... |
Yakings/system_demo | flask_web/flask_app/bearing_master/app.py | #!/usr/bin/python
#-*- coding: UTF-8 -*-
from __future__ import unicode_literals
from flask import (Flask, render_template, redirect, url_for, request, flash)
from flask_bootstrap import Bootstrap
from flask_login import login_required, login_user, logout_user, current_user
from flask import send_file, send_from_dire... |
Yakings/system_demo | flask_web/flask_app/deep_learning/pb_generation/read_util/tensorflow_input.py | import tensorflow as tf
import numpy as np
try:
from models.read_util.read_train_data import get_all_bearings
except:
from ..read_util.read_train_data import get_all_bearings
# from read_train_data import get_all_bearings
VIB_SIZE = 2000
step = 20
IMAGE_SIZE = VIB_SIZE//step
# Global constants describing ... |
Yakings/system_demo | flask_web/flask_app/bearing_master/forms.py | #!/usr/bin/python
#-*- coding: UTF-8 -*-
from __future__ import unicode_literals
from flask_wtf import FlaskForm
from wtforms import RadioField, SubmitField, StringField, PasswordField, SelectField, BooleanField, FileField
from wtforms.validators import DataRequired, Length
class TodoListForm(FlaskForm):
title = S... |
Yakings/system_demo | flask_web/flask_app/deep_learning/models_mse_loss/read_util/test_data_producer.py | # Copyright 2018 The Authors Sunyaqiang. 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.