blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
616
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
69
| license_type
stringclasses 2
values | repo_name
stringlengths 5
118
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
63
| visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 2.91k
686M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 23
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 213
values | src_encoding
stringclasses 30
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 2
10.3M
| extension
stringclasses 246
values | content
stringlengths 2
10.3M
| authors
listlengths 1
1
| author_id
stringlengths 0
212
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
80ddd57a8247d69edb42415474c4e81a66d869f2
|
63648b8d970c2739f9edc49c743fe55e8732f370
|
/TrainingGym/tools/district/filterDistricts.py
|
7bd49578b57c5e156c51c5ffff8871901b049858
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
Sahmwell/G15_Capstone
|
a0038b047fe6ba2fc4538137cb038ee1e1236463
|
6d2944a6d472e82fe01b1a9bf28a8ae153abcb77
|
refs/heads/master
| 2023-04-14T03:06:46.876134
| 2021-04-09T03:43:48
| 2021-04-09T03:43:48
| 310,671,914
| 5
| 1
|
MIT
| 2021-04-09T03:43:49
| 2020-11-06T18:09:52
|
Python
|
UTF-8
|
Python
| false
| false
| 3,112
|
py
|
#!/usr/bin/env python
# Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo
# Copyright (C) 2007-2020 German Aerospace Center (DLR) and others.
# This program and the accompanying materials are made available under the
# terms of the Eclipse Public License 2.0 which is available at
# https://www.eclipse.org/legal/epl-2.0/
# This Source Code may also be made available under the following Secondary
# Licenses when the conditions for such availability set forth in the Eclipse
# Public License 2.0 are satisfied: GNU General Public License, version 2
# or later which is available at
# https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
# SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
# @file filterDistricts.py
# @author Jakob Erdmann
# @date 2017-10-05
"""
Filters a TAZ file for a specific vehicle class
"""
from __future__ import absolute_import
from __future__ import print_function
import os
import sys
from optparse import OptionParser
SUMO_HOME = os.environ.get('SUMO_HOME',
os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..'))
sys.path.append(os.path.join(SUMO_HOME, 'tools'))
import sumolib # noqa
def getOptions():
optParser = OptionParser()
optParser.add_option(
"-v", "--verbose", action="store_true", default=False,
help="tell me what you are doing")
optParser.add_option("-n", "--net-file", dest="netfile", help="the network to read lane and edge permissions")
optParser.add_option("-t", "--taz-file", dest="tazfile", help="the district file to be filtered")
optParser.add_option("-o", "--output", default="taz_filtered.add.xml",
help="write filtered districts to FILE (default: %default)", metavar="FILE")
optParser.add_option("--vclass", help="filter taz edges that allow the given vehicle class")
(options, args) = optParser.parse_args()
if not options.netfile or not options.tazfile or not options.vclass:
optParser.print_help()
optParser.exit(
"Error! net-file, taz-file and vclass are mandatory")
return options
if __name__ == "__main__":
options = getOptions()
if options.verbose:
print("Reading net")
net = sumolib.net.readNet(options.netfile)
with open(options.output, 'w') as outf:
outf.write("<tazs>\n")
for taz in sumolib.output.parse(options.tazfile, "taz"):
if taz.edges is not None:
taz.edges = " ".join(
[e for e in taz.edges.split() if
net.hasEdge(e) and net.getEdge(e).allows(options.vclass)])
deleteSources = []
if taz.tazSink is not None:
taz.tazSink = [s for s in taz.tazSink if net.hasEdge(s.id) and net.getEdge(s.id).allows(options.vclass)]
if taz.tazSource is not None:
taz.tazSource = [s for s in taz.tazSource if net.hasEdge(
s.id) and net.getEdge(s.id).allows(options.vclass)]
outf.write(taz.toXML(initialIndent=" " * 4))
outf.write("</tazs>\n")
|
[
"samuelandersonsss@gmail.com"
] |
samuelandersonsss@gmail.com
|
bedc11276de29aefce2c028f1df14ecf7d5c3b91
|
b5d3a3f37355683d38a3d886b51fea4481b94ac8
|
/Arrays and Strings/Str3.py
|
9e2bf1a9bee1dc2ea14955055050ed8cbbe1bf40
|
[] |
no_license
|
Prad06/Python-DSA
|
b22821f58338177a29da43a862f58a03704fc227
|
b7c3044594421cf84e021a9ca5865d42ef468afb
|
refs/heads/main
| 2023-05-15T09:05:28.868140
| 2021-06-02T21:07:23
| 2021-06-02T21:07:23
| 371,734,813
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 360
|
py
|
# Pradnyesh Choudhari
# Mon May 31 22:18:40 2021
# Longest Palindromic Substring.
def lcs(X, Y, n, m):
if n == 0 or m == 0:
return 0
if X[n-1] == Y[m-1]:
return 1 + lcs(X, Y, n-1, m-1)
else:
return max(lcs(X, Y, n-1, m), lcs(X, Y, n, m-1))
string = input()
print(lcs(string, string[::-1], len(string),len(string)))
|
[
"pc612001@gmail.com"
] |
pc612001@gmail.com
|
10d235444bf5dc9bb3b89428124e8aaefa93df38
|
7cd0eea38c65bff36904a4278349ce43a69f1bfe
|
/gui/multihoproute.py
|
fb2f068d2a252fbdc7eb6ad1373751829d789d13
|
[] |
no_license
|
Majorjjamo5/mEDI_s-Elite-Tools
|
58ec0a088d6c1339b8f49ce3f6f81af48c41babd
|
c6927c79358a3781bdf9da0db82c8c7d46f70dc6
|
refs/heads/master
| 2020-03-29T00:07:24.763740
| 2017-11-27T01:27:36
| 2017-11-27T01:27:36
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 49,524
|
py
|
# -*- coding: UTF8
'''
Created on 19.08.2015
@author: mEDI
'''
from PySide import QtCore, QtGui
import elite
import timeit
import gui.guitools as guitools
__toolname__ = "Multi Hop Route Finder"
__internalName__ = "MuHoRoFi"
__statusTip__ = "Open A %s Window" % __toolname__
_debug = None
class RouteTreeInfoItem(object):
parentItem = None
def __init__(self, data, parent=None):
self.parentItem = parent
self.itemData = data
self.childItems = []
def appendChild(self, item):
self.childItems.append(item)
def child(self, row):
return self.childItems[row]
def childCount(self):
return len(self.childItems)
def columnCount(self):
return 1
def data(self, column):
if isinstance(self.itemData, str) or isinstance(self.itemData, unicode):
if column == 0:
return self.itemData
def parent(self):
return self.parentItem
def row(self):
if self.parentItem:
return self.parentItem.childItems.index(self)
return 0
class RouteTreeHopItem(object):
parentItem = None
def __init__(self, data, parent=None):
self.parentItem = parent
self.itemData = data
self.childItems = []
self._BGColor = None
def appendChild(self, item):
self.childItems.append(item)
def child(self, row):
return self.childItems[row]
def childCount(self):
return len(self.childItems)
def columnCount(self):
return 1
def BGColor(self):
return self._BGColor
def setBGColor(self, BGColor):
self._BGColor = BGColor
def data(self, column):
if isinstance(self.itemData, str) or isinstance(self.itemData, unicode):
if column == 0:
return self.itemData
def parent(self):
if self.parentItem:
return self.parentItem
def row(self):
if self.parentItem:
return self.parentItem.childItems.index(self)
return 0
class RouteTreeItem(object):
parentItem = None
childItems = []
def __init__(self, data, parent=None):
self.childItems = []
self.parentItem = parent
self.itemData = data
def appendChild(self, item):
self.childItems.append(item)
def child(self, row):
return self.childItems[row]
def childCount(self):
return len(self.childItems)
def childPos(self, child):
if isinstance(child, RouteTreeHopItem):
return self.childItems.index(child)
elif isinstance(child, list) and isinstance(child[0], QtCore.QModelIndex):
return self.childItems.index(child[0].internalPointer())
def hopPos(self, child):
if isinstance(child, list) and isinstance(child[0], QtCore.QModelIndex):
child = child[0].internalPointer()
if isinstance(child, RouteTreeHopItem):
pos = -1
for item in self.childItems:
if isinstance(item, RouteTreeHopItem):
pos += 1
if item == child:
return pos
def getListIndex(self):
if isinstance(self.itemData[0], int): # via displayed Nr.
return self.itemData[0] - 1
def columnCount(self):
return len(self.itemData)
def data(self, column):
if isinstance(self.itemData, list) and column < len(self.itemData):
return self.itemData[column]
elif isinstance(self.itemData, tuple) and column < len(self.itemData):
return self.itemData[column]
elif column != 8:
print(type(self.itemData), column)
def parent(self):
if self.parentItem:
return self.parentItem
def row(self):
if self.parentItem:
return self.parentItem.childItems.index(self)
return 0
def getInternalRoutePointer(self):
if isinstance(self.itemData[1], dict):
return self.itemData[1]
class RouteTreeModel(QtCore.QAbstractItemModel):
forceHops = None
def __init__(self, route, parent=None, forceHops=None):
super(RouteTreeModel, self).__init__(parent)
self.route = route
self.cleanModel()
self.forceHops = forceHops
self.setupModelData()
def cleanModel(self):
if _debug:
print("cleanModel")
self.rootItem = RouteTreeItem(("Nr.", "routeidx", "Profit/h", "Profit", "Ø Profit", "StartDist", "Laps/h", "LapTime", "Status"))
def columnCount(self, parent):
if parent.isValid():
return parent.internalPointer().columnCount()
elif self.rootItem:
return self.rootItem.columnCount()
def data(self, index, role):
if not index.isValid():
return None
if role == QtCore.Qt.BackgroundColorRole:
item = index.internalPointer()
if isinstance(item, RouteTreeHopItem):
return item.BGColor() # yellow or green https://srinikom.github.io/pyside-docs/PySide/QtGui/QColor.html
elif isinstance(item, RouteTreeItem):
pointer = item.getInternalRoutePointer()
if pointer and pointer["activeRoute"]:
return QtGui.QColor(QtCore.Qt.cyan)
elif isinstance(item, RouteTreeInfoItem):
return QtGui.QColor(255, 0, 0, 64)
if role == QtCore.Qt.TextAlignmentRole:
item = index.internalPointer()
if isinstance(item, RouteTreeItem):
if index.column() == 0:
return QtCore.Qt.AlignCenter
elif index.column() > 0 and index.column() < 5: # all profit = align right
return QtCore.Qt.AlignRight
else:
return QtCore.Qt.AlignCenter
if role != QtCore.Qt.DisplayRole:
return None
item = index.internalPointer()
if isinstance(index, QtCore.QModelIndex) and not self.route.locked:
return item.data(index.column())
def flags(self, index):
if not index.isValid():
return QtCore.Qt.NoItemFlags
return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
def headerData(self, section, orientation, role):
if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
return self.rootItem.data(section)
if role == QtCore.Qt.TextAlignmentRole:
return QtCore.Qt.AlignCenter
def index(self, row, column, parent=QtCore.QModelIndex()):
if not self.hasIndex(row, column, parent):
return QtCore.QModelIndex()
if not parent.isValid():
parentItem = self.rootItem
else:
parentItem = parent.internalPointer()
childItem = parentItem.child(row)
if childItem:
return self.createIndex(row, column, childItem)
else:
return QtCore.QModelIndex()
def parent(self, index):
if not index.isValid() or self.route.locked:
return QtCore.QModelIndex()
childItem = index.internalPointer()
if childItem:
parentItem = childItem.parent()
else:
return QtCore.QModelIndex()
if parentItem is None:
return QtCore.QModelIndex()
elif parentItem == self.rootItem:
return QtCore.QModelIndex()
return self.createIndex(parentItem.row(), 0, parentItem)
def rowCount(self, parent=None):
if parent is not None and parent.column() > 0:
return 0
if parent is None or not parent.isValid():
parentItem = self.rootItem
else:
parentItem = parent.internalPointer()
return parentItem.childCount()
def sort(self, col, order):
if _debug:
print("sort")
# print(col, order)
if self.route.locked:
return
if order == QtCore.Qt.SortOrder.DescendingOrder:
order = True
else:
order = False
self.layoutAboutToBeChanged.emit()
self.modelAboutToBeReset.emit()
if col == 2:
self.route.sortDealsByProfitH(order)
self.cleanModel()
self.setupModelData()
elif col == 3:
self.route.sortDealsByProfit(order)
self.cleanModel()
self.setupModelData()
elif col == 4:
self.route.sortDealsByProfitAverage(order)
self.cleanModel()
self.setupModelData()
elif col == 5:
self.route.sortDealsByStartDist(order)
self.cleanModel()
self.setupModelData()
elif col == 7:
self.route.sortDealsByLapTime(order)
self.cleanModel()
self.setupModelData()
self.modelReset.emit()
self.layoutChanged.emit()
def setupModelData(self):
if _debug:
print("setupModelData")
parents = [self.rootItem]
for routeId, deal in enumerate(self.route.deals):
if routeId >= 100:
break
timeT = "%s:%s" % (divmod(deal["time"] * deal["lapsInHour"], 60))
timeL = "%s:%s" % (divmod(deal["time"], 60))
columnData = [routeId + 1, deal, deal["profitHour"], deal["profit"], deal["profitAverage"], deal["path"][0]["startDist"], "%s/%s" % (deal["lapsInHour"], timeT), timeL]
parents[-1].appendChild(RouteTreeItem(columnData, parents[-1]))
before = { "StationB": deal["path"][0]["StationA"], "SystemB": deal["path"][0]["SystemA"], "StarDist": deal["path"][0]["stationA.StarDist"], "refuel": deal["path"][0]["stationA.refuel"] }
# follow is a child
parents.append(parents[-1].child(parents[-1].childCount() - 1))
for hopID, d in enumerate(deal["path"]):
# print(d.keys())
blackmarket = "" if not d["blackmarket"] else " (Blackmarket)"
columnData = "%s : %s (%d ls) (%s buy:%d sell:%d%s profit:%d) (%s ly)-> %s:%s" % (self.route.getSystemA(deal, hopID),
self.route.getStationA(deal, hopID),
before["StarDist"], self.route.getItemName(deal, hopID), d["StationSell"],
d["StationBuy"], blackmarket, d["profit"], d["dist"],
self.route.getSystemB(deal, hopID),
self.route.getStationB(deal, hopID))
parents[-1].appendChild(RouteTreeHopItem(columnData, parents[-1]))
if d["StationSell"] < d["StationBuy"] * 0.5:
columnData = "\tWarning: > 50% profit? Fake!"
parents[-1].appendChild(RouteTreeInfoItem(columnData, parents[-1]))
if d["blackmarket"]:
columnData = "\tWarning: %s is a Blackmarket item!?" % self.route.getItemName(deal, hopID)
parents[-1].appendChild(RouteTreeInfoItem(columnData, parents[-1]))
if before["refuel"] != 1:
columnData = "\tWarning: %s have no refuel!?" % self.route.getStationA(deal, hopID)
parents[-1].appendChild(RouteTreeInfoItem(columnData, parents[-1]))
before = d
backdist = self.route.mydb.getDistanceFromTo(deal["path"][0]["SystemAID"], deal["path"][ len(deal["path"]) - 1 ]["SystemBID"])
hopID += 1
if deal["backToStartDeal"]:
# print(deal["backToStartDeal"].keys())
columnData = "%s : %s (%d ls) (%s buy:%d sell:%d profit:%d) (%s ly)-> %s:%s" % (self.route.getSystemA(deal, hopID),
self.route.getStationA(deal, hopID),
before["StarDist"], self.route.getItemName(deal, hopID),
deal["backToStartDeal"]["StationSell"],
deal["backToStartDeal"]["StationBuy"],
deal["backToStartDeal"]["profit"],
backdist,
self.route.getSystemB(deal, hopID),
self.route.getStationB(deal, hopID))
parents[-1].appendChild(RouteTreeHopItem(columnData, parents[-1]))
if deal["backToStartDeal"]["StationSell"] < deal["backToStartDeal"]["StationBuy"] * 0.5:
columnData = "\tWarning: > 50% profit? Fake!"
parents[-1].appendChild(RouteTreeInfoItem(columnData, parents[-1]))
if deal["backToStartDeal"]["blackmarket"]:
columnData = "\tWarning: %s is a Blackmarket item!?" % self.route.getItemName(deal, hopID)
parents[-1].appendChild(RouteTreeInfoItem(columnData, parents[-1]))
else:
columnData = "%s : %s (%d ls) (no back deal) (%s ly) ->%s : %s" % (self.route.getSystemA(deal, hopID),
self.route.getStationA(deal, hopID),
before["StarDist"], backdist,
self.route.getSystemB(deal, hopID),
self.route.getStationB(deal, hopID))
parents[-1].appendChild(RouteTreeInfoItem(columnData, parents[-1]))
if before["refuel"] != 1:
columnData = "\tWarning: %s have no refuel!?" % self.route.getStationA(deal, hopID)
parents[-1].appendChild(RouteTreeInfoItem(columnData, parents[-1]))
# not more a child
parents.pop()
class tool(QtGui.QWidget):
main = None
mydb = None
route = None
activeRoutePointer = None
connectedDealsFromToWindows = None
layoutLock = None
enabelSortingTimer = None
# _debug = True
def __init__(self, main):
super(tool, self).__init__(main)
self.main = main
self.mydb = main.mydb
self.initRoute()
self.guitools = guitools.guitools(self)
self.createTimer()
self.createActions()
def getWideget(self):
gridLayout = QtGui.QGridLayout()
gridLayout.setColumnStretch(1, 1)
gridLayout.setColumnStretch(3, 2)
gridLayout.setColumnStretch(4, 1)
gridLayout.setColumnStretch(6, 2)
gridLayout.setColumnStretch(7, 1)
gridLayout.setColumnStretch(9, 2)
self.forceMaxHops = QtGui.QCheckBox("Force Max Hops")
if self.mydb.getConfig("option_mhr_forceMaxHops"):
self.forceMaxHops.setChecked(True)
self.forceMaxHops.setToolTip("Show only routes with Max Hops+Back Hop")
gridLayout.addWidget(self.forceMaxHops, 1, 0)
self.onlyLpadsize = QtGui.QCheckBox("Only L Pads")
if self.mydb.getConfig("option_mhr_onlyLpadsize"):
self.onlyLpadsize.setChecked(True)
self.onlyLpadsize.setToolTip("Find only stations with a large landingpad")
gridLayout.addWidget(self.onlyLpadsize, 2, 0)
self.autoUpdateLocation = QtGui.QCheckBox("Location Update")
self.autoUpdateLocation.setChecked(True)
self.autoUpdateLocation.stateChanged.connect(self.updateLocation)
gridLayout.addWidget(self.autoUpdateLocation, 3, 0)
label = QtGui.QLabel("Max Hops:")
self.maxHopsspinBox = QtGui.QSpinBox()
self.maxHopsspinBox.setRange(1, 20)
self.maxHopsspinBox.setAlignment(QtCore.Qt.AlignRight)
self.maxHopsspinBox.setValue(self.route.getOption("tradingHops"))
gridLayout.addWidget(label, 1, 2)
gridLayout.addWidget(self.maxHopsspinBox, 1, 3)
label = QtGui.QLabel("Search Range:")
self.searchRangeSpinBox = QtGui.QSpinBox()
self.searchRangeSpinBox.setRange(0, 1000)
self.searchRangeSpinBox.setSuffix("ly")
self.searchRangeSpinBox.setAlignment(QtCore.Qt.AlignRight)
self.searchRangeSpinBox.setValue(self.route.getOption("maxSearchRange"))
gridLayout.addWidget(label, 1, 5)
gridLayout.addWidget(self.searchRangeSpinBox, 1, 6)
label = QtGui.QLabel("Max Data Age:")
self.maxAgeSpinBox = QtGui.QSpinBox()
self.maxAgeSpinBox.setRange(1, 1000)
self.maxAgeSpinBox.setSuffix("Day")
self.maxAgeSpinBox.setAlignment(QtCore.Qt.AlignRight)
self.maxAgeSpinBox.setValue(self.route.getOption("maxAge"))
gridLayout.addWidget(label, 1, 8)
gridLayout.addWidget(self.maxAgeSpinBox, 1, 9)
label = QtGui.QLabel("Min Profit:")
self.minProfitSpinBox = QtGui.QSpinBox()
self.minProfitSpinBox.setRange(1000, 10000)
self.minProfitSpinBox.setSuffix("cr")
self.minProfitSpinBox.setSingleStep(100)
self.minProfitSpinBox.setAlignment(QtCore.Qt.AlignRight)
self.minProfitSpinBox.setValue(self.route.getOption("minTradeProfit"))
gridLayout.addWidget(label, 2, 2)
gridLayout.addWidget(self.minProfitSpinBox, 2, 3)
label = QtGui.QLabel("Max Dist:")
self.maxDistSpinBox = QtGui.QSpinBox()
self.maxDistSpinBox.setRange(0, 1000)
self.maxDistSpinBox.setSuffix("ly")
self.maxDistSpinBox.setSingleStep(1)
self.maxDistSpinBox.setAlignment(QtCore.Qt.AlignRight)
self.maxDistSpinBox.setValue(self.route.getOption("maxDist"))
gridLayout.addWidget(label, 2, 5)
gridLayout.addWidget(self.maxDistSpinBox, 2, 6)
label = QtGui.QLabel("Max Star Dist:")
self.maxStartDistSpinBox = QtGui.QSpinBox()
self.maxStartDistSpinBox.setRange(10, 7000000)
self.maxStartDistSpinBox.setSuffix("ls")
self.maxStartDistSpinBox.setSingleStep(100)
self.maxStartDistSpinBox.setAlignment(QtCore.Qt.AlignRight)
self.maxStartDistSpinBox.setValue(self.route.getOption("maxStarDist"))
gridLayout.addWidget(label, 2, 8)
gridLayout.addWidget(self.maxStartDistSpinBox, 2, 9)
label = QtGui.QLabel("Search Accuracy:")
self.searchLimitOption = QtGui.QComboBox()
searchLimitOptionsList = ["normal", "fast", "nice", "slow", "all"]
for option in searchLimitOptionsList:
self.searchLimitOption.addItem(option)
if self.mydb.getConfig("option_searchLimit"):
self.searchLimitOption.setCurrentIndex(self.mydb.getConfig("option_searchLimit"))
label.setBuddy(self.searchLimitOption)
# self.searchLimitOption.currentIndexChanged.connect(self.hmm)
gridLayout.addWidget(label, 3, 2)
gridLayout.addWidget(self.searchLimitOption, 3, 3, 1, 1) # row,col,?,size
label = QtGui.QLabel("Max Jump Dist:")
self.maxJumpDistSpinBox = QtGui.QDoubleSpinBox()
self.maxJumpDistSpinBox.setRange(0, 1000)
self.maxJumpDistSpinBox.setSuffix("ly")
self.maxJumpDistSpinBox.setSingleStep(1)
self.maxJumpDistSpinBox.setAlignment(QtCore.Qt.AlignRight)
self.maxJumpDistSpinBox.setValue(self.route.getOption("maxJumpDistance"))
gridLayout.addWidget(label, 3, 5)
gridLayout.addWidget(self.maxJumpDistSpinBox, 3, 6)
label = QtGui.QLabel("Min Stock:")
self.minStockSpinBox = QtGui.QSpinBox()
self.minStockSpinBox.setRange(1000, 1000000)
self.minStockSpinBox.setSingleStep(100)
self.minStockSpinBox.setAlignment(QtCore.Qt.AlignRight)
self.minStockSpinBox.setValue(self.route.getOption("minStock"))
gridLayout.addWidget(label, 3, 8)
gridLayout.addWidget(self.minStockSpinBox, 3, 9)
locationLabel = QtGui.QLabel("Location:")
self.locationlineEdit = guitools.LineEdit()
self.locationlineEdit.setText(self.main.location.getLocation())
self.locationlineEdit.textChanged.connect(self.triggerLocationChanged)
locationButton = QtGui.QToolButton()
locationButton.setIcon(self.guitools.getIconFromsvg("img/location.svg"))
locationButton.clicked.connect(self.setCurentLocation)
locationButton.setToolTip("Current Location")
locationGroupBox = QtGui.QGroupBox()
locationGroupBox.setFlat(True)
locationGroupBox.setStyleSheet("""QGroupBox {border:0;margin:0;padding:0;} margin:0;padding:0;""")
layout = QtGui.QHBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
self.showOptions = QtGui.QCheckBox("Show Options")
if self.mydb.getConfig("option_mhr_showOptions") != 0:
self.showOptions.setChecked(True)
self.showOptions.stateChanged.connect(self.optionsGroupBoxToggleViewAction)
self.searchbutton = QtGui.QPushButton("Search")
self.searchbutton.clicked.connect(self.startRouteSearch)
layout.addWidget(locationLabel)
layout.addWidget(locationButton)
layout.addWidget(self.locationlineEdit)
layout.addWidget(self.showOptions)
layout.addWidget(self.searchbutton)
locationGroupBox.setLayout(layout)
self.optionsGroupBox = QtGui.QGroupBox("Options")
self.optionsGroupBox.setLayout(gridLayout)
self.listView = QtGui.QTreeView()
self.listView.setAlternatingRowColors(True)
self.listView.setSortingEnabled(True)
self.listView.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
self.listView.setSelectionBehavior(QtGui.QAbstractItemView.SelectItems)
self.listView.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.listView.customContextMenuRequested.connect(self.routelistContextMenuEvent)
vGroupBox = QtGui.QGroupBox()
vGroupBox.setFlat(True)
layout = QtGui.QVBoxLayout()
layout.setContentsMargins(6, 6, 6, 6)
layout.addWidget(self.optionsGroupBox)
layout.addWidget(locationGroupBox)
layout.addWidget(self.listView)
vGroupBox.setLayout(layout)
self.guitools.setSystemComplete("", self.locationlineEdit)
self.optionsGroupBoxToggleViewAction()
return vGroupBox
def routelistContextMenuEvent(self, event):
menu = QtGui.QMenu(self)
menu.addAction(self.copyAct)
indexes = self.listView.selectionModel().selectedIndexes()
if isinstance(indexes[0].internalPointer(), RouteTreeHopItem):
if len(self.main.dealsFromToWidget) > 1:
menu.addAction(self.addRouteHopAsFromSystemInDealsFromToFinderAct)
menu.addAction(self.addRouteHopAsTargetSystemInDealsFromToFinderAct)
menu.addAction(self.markFakeItemAct)
menu.addAction(self.markIgnorePriceTempAct)
menu.addAction(self.markIgnorePriceBTempAct)
# self.testOfFacke()
elif isinstance(indexes[0].internalPointer(), RouteTreeItem):
menu.addAction(self.clipbordRouteHelperAct)
if len(self.main.dealsFromToWidget) > 1:
if self.connectedDealsFromToWindows:
menu.addAction(self.disconnectFromDealsFromToWindowAct)
else:
menu.addAction(self.connectToDealsFromToWindowsAct)
menu.addAction(self.saveSelectedRouteAct)
else:
print(type(indexes[0].internalPointer()))
menu.exec_(self.listView.viewport().mapToGlobal(event))
def optionsGroupBoxToggleViewAction(self):
if self.showOptions.isChecked():
self.optionsGroupBox.show()
else:
self.optionsGroupBox.hide()
def setCurentLocation(self):
self.locationlineEdit.setText(self.main.location.getLocation())
def initRoute(self):
''' init the route on start and set saved options'''
self.route = elite.dealsroute(self.mydb)
tradingHops = self.mydb.getConfig('option_tradingHops')
if tradingHops:
self.route.setOption("tradingHops", tradingHops)
maxJumpDistance = self.mydb.getConfig('option_maxJumpDistance')
if maxJumpDistance:
self.route.setOption("maxJumpDistance", maxJumpDistance)
maxDist = self.mydb.getConfig('option_maxDist')
if maxDist:
self.route.setOption("maxDist", maxDist)
maxSearchRange = self.mydb.getConfig('option_maxSearchRange')
if maxSearchRange:
self.route.setOption("maxSearchRange", maxSearchRange)
minStock = self.mydb.getConfig('option_minStock')
if minStock:
self.route.setOption("minStock", minStock)
maxStarDist = self.mydb.getConfig('option_maxStarDist')
if maxStarDist:
self.route.setOption("maxStarDist", maxStarDist)
minTradeProfit = self.mydb.getConfig('option_minTradeProfit')
if minTradeProfit:
self.route.setOption("minTradeProfit", minTradeProfit)
def saveOptions(self):
# save last options
self.mydb.setConfig('option_tradingHops', self.maxHopsspinBox.value())
self.mydb.setConfig('option_maxJumpDistance', self.maxJumpDistSpinBox.value())
self.mydb.setConfig('option_maxDist', self.maxDistSpinBox.value())
self.mydb.setConfig('option_maxSearchRange', self.searchRangeSpinBox.value())
self.mydb.setConfig('option_minStock', self.minStockSpinBox.value())
self.mydb.setConfig('option_maxStarDist', self.maxStartDistSpinBox.value())
self.mydb.setConfig('option_minTradeProfit', self.minProfitSpinBox.value())
self.mydb.setConfig('option_searchLimit', self.searchLimitOption.currentIndex())
self.mydb.setConfig('option_mhr_showOptions', self.showOptions.isChecked())
self.mydb.setConfig('option_mhr_forceMaxHops', self.forceMaxHops.isChecked())
self.mydb.setConfig('option_mhr_onlyLpadsize', self.onlyLpadsize.isChecked())
def startRouteSearch(self):
self.unsetActiveRoutePointer()
self.main.lockDB()
starttime = timeit.default_timer()
self.route.setOption("startSystem", self.locationlineEdit.text())
self.route.setOption("tradingHops", self.maxHopsspinBox.value())
self.route.setOption("maxJumpDistance", self.maxJumpDistSpinBox.value())
self.route.setOption("maxDist", self.maxDistSpinBox.value())
self.route.setOption("maxSearchRange", self.searchRangeSpinBox.value())
self.route.setOption("minStock", self.minStockSpinBox.value())
self.route.setOption("maxStarDist", self.maxStartDistSpinBox.value())
self.route.setOption("maxAge", self.maxAgeSpinBox.value())
self.route.setOption("minTradeProfit", self.minProfitSpinBox.value())
if self.onlyLpadsize.isChecked():
self.route.setOption("padsize", ["L"])
else:
self.route.setOption("padsize", None)
self.route.calcDefaultOptions()
forceHops = None
if self.forceMaxHops.isChecked():
forceHops = self.maxHopsspinBox.value()
self.route.forceHops = forceHops
self.route.limitCalc(self.searchLimitOption.currentIndex()) # options (normal, fast, nice, slow, all)
self.route.calcRoute()
# self.route.printList()
self.routeModel = RouteTreeModel(self.route, None, forceHops)
QtCore.QObject.connect(self.routeModel, QtCore.SIGNAL('layoutAboutToBeChanged()'), self.routeModellayoutAboutToBeChanged)
QtCore.QObject.connect(self.routeModel, QtCore.SIGNAL('layoutChanged()'), self.routeModellayoutChanged)
QtCore.QObject.connect(self.routeModel, QtCore.SIGNAL('modelAboutToBeReset()'), self.routeModelmodelAboutToBeReset)
QtCore.QObject.connect(self.routeModel, QtCore.SIGNAL('modelReset()'), self.routeModemodelReset)
self.listView.setModel(self.routeModel)
# routeModel.layoutChanged.emit()
self.listView.sortByColumn(2, QtCore.Qt.SortOrder.DescendingOrder)
self.listView.hideColumn(1)
self.listView.show()
self.main.setStatusBar("Route Calculated (%ss) %d routes found" % (round(timeit.default_timer() - starttime, 2), len(self.route.deals)))
self.main.unlockDB()
self.triggerLocationChanged()
def routeModelmodelAboutToBeReset(self):
if _debug:
print("routeModelmodelAboutToBeReset")
def routeModemodelReset(self):
if _debug:
print("routeModelmodelAboutToBeReset")
def enabelSorting(self):
self.listView.setSortingEnabled(True)
self.enabelSortingTimer = None
def routeModellayoutAboutToBeChanged(self):
if _debug:
print("routeModellayoutAboutToBeChanged")
self.autoUpdateLocationTimer.stop()
self.layoutLock = True
def routeModellayoutChanged(self):
if _debug:
print("routeModellayoutChanged")
for rid in range(0, self.listView.model().rowCount(QtCore.QModelIndex())):
# rid item count
for cid in range(0, self.listView.model().rowCount(self.listView.model().index(rid, 0))):
# cid child item count
self.listView.setFirstColumnSpanned(cid, self.listView.model().index(rid, 0), True)
self.listView.expandToDepth(1)
# for i in range(0, 7):
# self.listView.resizeColumnToContents(i)
self.layoutLock = None
self.triggerLocationChanged()
self.autoUpdateLocationTimer.start()
def createTimer(self):
self.autoUpdateLocationTimer = QtCore.QTimer()
self.autoUpdateLocationTimer.start(1000 * 60)
self.autoUpdateLocationTimer.timeout.connect(self.updateLocation)
self.timer_setNextRouteHopToClipbord = QtCore.QTimer()
self.timer_setNextRouteHopToClipbord.start(1000 * 60)
self.timer_setNextRouteHopToClipbord.timeout.connect(self.setNextRouteHopToClipbord)
self.timer_setNextRouteHopToClipbord.stop()
def updateLocation(self):
if self.autoUpdateLocation.isChecked():
self.autoUpdateLocationTimer.stop()
location = self.main.location.getLocation()
if not location:
print("stop update location")
self.autoUpdateLocation.setChecked(False)
return
self.locationlineEdit.setText(location)
self.autoUpdateLocationTimer.start()
else:
print("stop update location timer")
self.autoUpdateLocationTimer.stop()
def triggerLocationChanged(self):
if _debug:
print("triggerLocationChanged")
if self.route.locked or self.layoutLock:
return
self.updateConnectedDealsFromToWindow()
self.setLocationColors()
def setLocationColors(self):
if _debug:
print("setLocationColors")
location = self.locationlineEdit.text()
if self.route.locked or self.layoutLock:
return
if not self.listView.model() or not self.listView.model().rowCount():
return
hopID = self.getCurrentHopFromActiveRoute() # only to fill deal["lastHop"]
if location and self.listView.model():
for rid in range(0, self.listView.model().rowCount(QtCore.QModelIndex())):
if self.layoutLock:
return
guiRroute = self.listView.model().index(rid, 0).internalPointer()
hopID = -1
for cid in range(0, guiRroute.childCount()):
child = guiRroute.child(cid)
# print(child)
if isinstance(child, RouteTreeHopItem):
hopID += 1
deal = child.parent().getInternalRoutePointer()
if self.route.getSystemA(deal, hopID).lower() == location.lower():
if deal["activeRoute"]:
child.setBGColor(QtGui.QColor(0, 255, 0, 128))
else:
child.setBGColor(QtGui.QColor(255, 255, 128, 255))
elif deal["activeRoute"] and hopID == deal["lastHop"]:
child.setBGColor(QtGui.QColor(0, 255, 0, 64))
else:
child.setBGColor(None)
self.listView.dataChanged(self.listView.model().index(0, 0), self.listView.model().index(self.listView.model().rowCount(QtCore.QModelIndex()), 0))
def createActions(self):
self.markFakeItemAct = QtGui.QAction("Set Item as Fake", self,
statusTip="Set not existing items as Fake and filter it on next search", triggered=self.markFakeItem)
self.markIgnorePriceTempAct = QtGui.QAction("Ignore Item temporarily", self,
statusTip="ignored items are hidden until application restart", triggered=self.markIgnorePriceTemp)
self.markIgnorePriceBTempAct = QtGui.QAction("Ignore Item (On Target Station) temporarily", self,
statusTip="ignored items are hidden until application restart", triggered=self.markIgnorePriceBTemp)
self.clipbordRouteHelperAct = QtGui.QAction("Start clipboard Route Helper", self, checkable=True,
statusTip="Start a helper job to set automatly the next routehop to clipboard", triggered=self.clipbordRouteHelper)
self.addRouteHopAsTargetSystemInDealsFromToFinderAct = QtGui.QAction("Set as To in (Deals From To Finder 1)", self,
statusTip="Set System/Station as To in Deals Finder", triggered=self.addRouteHopAsTargetSystemInDealsFromToFinder)
self.addRouteHopAsFromSystemInDealsFromToFinderAct = QtGui.QAction("Set as From in (Deals From To Finder 1)", self,
statusTip="Set System/Station as From in Deals Finder", triggered=self.addRouteHopAsFromSystemInDealsFromToFinder)
self.connectToDealsFromToWindowsAct = QtGui.QAction("Connect Route to (Deals From To Finder 1)", self,
statusTip="Update (Deals From To Finder 1) with current Route position", triggered=self.connectToDealsFromToWindows)
self.disconnectFromDealsFromToWindowAct = QtGui.QAction("Disconnect (Deals From To Finder 1)", self,
statusTip="Disconnect From (Deals From To Finder 1) window", triggered=self.disconnectFromDealsFromToWindow)
self.copyAct = QtGui.QAction("Copy", self, triggered=self.guitools.copyToClipboard, shortcut=QtGui.QKeySequence.Copy)
self.saveSelectedRouteAct = QtGui.QAction("Bookmark Route", self,
statusTip="save a bookmark", triggered=self.saveSelectedRoute)
def setActiveRoutePointer(self):
indexes = self.listView.selectionModel().selectedIndexes()
if isinstance(indexes[0].internalPointer(), RouteTreeItem):
if self.activeRoutePointer:
self.activeRoutePointer["activeRoute"] = None
self.activeRoutePointer = indexes[0].internalPointer().getInternalRoutePointer()
self.activeRoutePointer["activeRoute"] = True
def unsetActiveRoutePointer(self):
if self.activeRoutePointer:
self.activeRoutePointer["activeRoute"] = None
self.activeRoutePointer = None
def clipbordRouteHelper(self):
indexes = self.listView.selectionModel().selectedIndexes()
if self.activeRoutePointer and self.timer_setNextRouteHopToClipbord.isActive() and self.activeRoutePointer == indexes[0].internalPointer().getInternalRoutePointer():
self.clipbordRouteHelperAct.setChecked(False)
self.timer_setNextRouteHopToClipbord.stop()
return
self.setActiveRoutePointer()
self.timer_setNextRouteHopToClipbord.start()
self.clipbordRouteHelperAct.setChecked(True)
self.setNextRouteHopToClipbord(init=True)
self.triggerLocationChanged()
def setNextRouteHopToClipbord(self, init=None):
''' helper to set next route hop to clipboard '''
if _debug:
print("setNextRouteHopToClipbord")
if not self.activeRoutePointer:
return
clipbordText = self.main.clipboard.text()
if init:
self.lastClipboardEntry = None
elif self.lastClipboardEntry != clipbordText:
# stop timer and job do other tool use the clipbord
print("setNextRouteHopToClipbord stop job")
self.timer_setNextRouteHopToClipbord.stop()
self.clipbordRouteHelperAct.setChecked(False)
return
hopID = self.getCurrentHopFromActiveRoute()
if hopID is not None:
systemA = self.route.getSystemB(self.activeRoutePointer, hopID)
if systemA != clipbordText:
systemB = self.route.getSystemB(self.activeRoutePointer, hopID)
self.main.clipboard.setText(systemB)
self.lastClipboardEntry = systemB
print("setNextRouteHopToClipbord1 set clipboard to", systemB)
elif not self.lastClipboardEntry:
# not in route? set the first hop to clipboard
system = self.route.getSystemA(self.activeRoutePointer, 0)
if system:
self.main.clipboard.setText(system)
self.lastClipboardEntry = system
print("setNextRouteHopToClipbord2 set clipboard to", system)
self.timer_setNextRouteHopToClipbord.start()
def markFakeItem(self):
route, hopID = self.getSelectedRouteHopID()
priceID = self.route.getPriceID(route, hopID)
if priceID:
msgBox = QtGui.QMessageBox(QtGui.QMessageBox.Warning,
"Warning", "Warning: fake items are ignored everywhere and no longer displayed",
QtGui.QMessageBox.NoButton, self)
msgBox.addButton("Save as Facke", QtGui.QMessageBox.AcceptRole)
msgBox.addButton("Cancel", QtGui.QMessageBox.RejectRole)
if msgBox.exec_() == QtGui.QMessageBox.AcceptRole:
print("set %s as fakeprice" % priceID)
self.main.lockDB()
self.mydb.setFakePrice(priceID)
self.main.unlockDB()
def testOfFacke(self):
#status = {'newest': newstEntry, 'entrys': entrys, 'item': item, 'list': result}
def test(status):
for entry in status['list']:
if entry['modified'] == status['item']['modified']:
print(entry['count'], status['entrys'])
if entry['count'] < status['entrys'] * 0.5: # < 50% of entrys have the same date
print("warning: < 50% of entrys have the same date")
break
route, hopID = self.getSelectedRouteHopID()
priceID = self.route.getPriceID(route, hopID)
statusA = self.mydb.getItemModifiedStatus(priceID)
priceBID = self.route.getPriceBID(route, hopID)
statusB = self.mydb.getItemModifiedStatus(priceBID)
if not statusA or not statusB:
return
test(statusA)
test(statusB)
print(statusA['item']['StationSell'], statusB['item']['StationBuy'])
if statusA['item']['StationSell'] < statusB['item']['StationBuy'] * 0.5:
print("warning: > 50% profit?")
def markIgnorePriceTemp(self):
route, hopID = self.getSelectedRouteHopID()
priceID = self.route.getPriceID(route, hopID)
if priceID:
msgBox = QtGui.QMessageBox(QtGui.QMessageBox.Warning,
"Warning", "Warning: ignored items are hidden until application restart",
QtGui.QMessageBox.NoButton, self)
msgBox.addButton("Ignore Item", QtGui.QMessageBox.AcceptRole)
msgBox.addButton("Cancel", QtGui.QMessageBox.RejectRole)
if msgBox.exec_() == QtGui.QMessageBox.AcceptRole:
print("set %s as IgnorePriceTemp" % priceID)
self.main.lockDB()
self.mydb.setIgnorePriceTemp(priceID)
self.main.unlockDB()
def markIgnorePriceBTemp(self):
route, hopID = self.getSelectedRouteHopID()
priceID = self.route.getPriceBID(route, hopID)
if priceID:
msgBox = QtGui.QMessageBox(QtGui.QMessageBox.Warning,
"Warning", "Warning: ignored items are hidden until application restart",
QtGui.QMessageBox.NoButton, self)
msgBox.addButton("Ignore Item", QtGui.QMessageBox.AcceptRole)
msgBox.addButton("Cancel", QtGui.QMessageBox.RejectRole)
if msgBox.exec_() == QtGui.QMessageBox.AcceptRole:
print("set %s as IgnorePriceBTemp" % priceID)
self.main.lockDB()
self.mydb.setIgnorePriceTemp(priceID)
self.main.unlockDB()
def getSelectedRouteHopID(self):
if _debug:
print("getSelectedRouteHopID")
indexes = self.listView.selectionModel().selectedIndexes()
if isinstance(indexes[0].internalPointer(), RouteTreeHopItem):
hopID = indexes[0].internalPointer().parent().hopPos(indexes)
route = indexes[0].internalPointer().parent().getInternalRoutePointer()
return (route, hopID)
return (None, None)
def addRouteHopAsTargetSystemInDealsFromToFinder(self):
if _debug:
print("addRouteHopAsTargetSystemInDealsFromToFinder")
route, hopID = self.getSelectedRouteHopID()
if route is None or hopID is None:
return
toStation = self.route.getStationA(route, hopID)
toSystem = self.route.getSystemA(route, hopID)
# TODO: set it only in first Deals window current
if toSystem and toStation:
self.main.dealsFromToWidget[1].toSystem.setText(toSystem)
self.main.dealsFromToWidget[1].toStation.setText(toStation)
def addRouteHopAsFromSystemInDealsFromToFinder(self):
route, hopID = self.getSelectedRouteHopID()
if route is None or hopID is None:
return
station = self.route.getStationA(route, hopID)
system = self.route.getSystemA(route, hopID)
# TODO: set it only in first Deals window current
if system and station:
self.main.dealsFromToWidget[1].fromSystem.setText(system)
self.main.dealsFromToWidget[1].fromStation.setText(station)
def connectToDealsFromToWindows(self):
if _debug:
print("connectToDealsFromToWindows")
if self.connectedDealsFromToWindows:
indexes = self.listView.selectionModel().selectedIndexes()
if self.activeRoutePointer == indexes[0].internalPointer().getInternalRoutePointer():
self.connectedDealsFromToWindows = None
return
if self.main.dealsFromToWidget:
self.setActiveRoutePointer()
self.triggerLocationChanged()
self.connectedDealsFromToWindows = self.main.dealsFromToWidget[1]
self.connectedDealsFromToWindows.autoUpdateLocation.setChecked(False)
self.updateConnectedDealsFromToWindow(init=True)
def disconnectFromDealsFromToWindow(self):
self.connectedDealsFromToWindows = None
def getCurrentHopFromActiveRoute(self):
if _debug:
print("getCurrentHopFromActiveRoute")
if not self.activeRoutePointer:
return
location = self.main.location.getLocation()
hopCount = len(self.activeRoutePointer["path"])
for i in range(0, hopCount + 1):
if not self.activeRoutePointer["lastHop"]:
cid = i
else:
cid = self.activeRoutePointer["lastHop"] + i
if cid > hopCount:
cid = i - self.activeRoutePointer["lastHop"]
systemA = self.route.getSystemA(self.activeRoutePointer, cid)
if systemA == location:
hopID = cid
if hopID > hopCount:
hopID = 0
self.activeRoutePointer["lastHop"] = hopID
return hopID
def updateConnectedDealsFromToWindow(self, init=None):
if _debug:
print("updateConnectedDealsFromToWindow")
if not self.connectedDealsFromToWindows or not self.activeRoutePointer:
return
hopID = self.getCurrentHopFromActiveRoute()
if hopID is None and init:
''' is init and im not inside the route set only the To part from first hop '''
systemA = self.route.getSystemA(self.activeRoutePointer, 0)
stationA = self.route.getStationA(self.activeRoutePointer, 0)
self.connectedDealsFromToWindows.toSystem.setText(systemA)
self.connectedDealsFromToWindows.toStation.setText(stationA)
return
if hopID is None:
return
systemA = self.route.getSystemA(self.activeRoutePointer, hopID)
stationA = self.route.getStationA(self.activeRoutePointer, hopID)
systemB = self.route.getSystemB(self.activeRoutePointer, hopID)
stationB = self.route.getStationB(self.activeRoutePointer, hopID)
self.connectedDealsFromToWindows.fromSystem.setText(systemA)
self.connectedDealsFromToWindows.fromStation.setText(stationA)
self.connectedDealsFromToWindows.toSystem.setText(systemB)
self.connectedDealsFromToWindows.toStation.setText(stationB)
def saveSelectedRoute(self):
indexes = self.listView.selectionModel().selectedIndexes()
route = indexes[0].internalPointer().getInternalRoutePointer()
defName = ""
for i in range(0, self.route.countHops(route)):
systemA = self.route.getSystemA(route, i)
stationA = self.route.getStationA(route, i)
itemName = self.route.getItemName(route, i)
if defName:
defName += " -> "
defName += "%s:%s (%s)" % (systemA, stationA, itemName)
defName = "Deals Route:" + defName
text, ok = QtGui.QInputDialog.getText(self, "Bockmark Name",
"Bockmark Name:", QtGui.QLineEdit.Normal, defName)
if ok and text != '':
routeData = []
for i in range(0, self.route.countHops(route)):
systemAid = self.route.getSystemAid(route, i)
stationAid = self.route.getStationAid(route, i)
itemId = self.route.getItemId(route, i)
routeData.append( {
'SystemID': systemAid,
'StationID': stationAid,
'ItemID': itemId
})
self.main.lockDB()
self.mydb.saveBookmark(text, routeData, 0)
self.main.unlockDB()
|
[
"medi@255.li"
] |
medi@255.li
|
90b8850b0a21353a665b3a4868e12780485007c5
|
b3b353f20f94364bd31e46fec0bc839eb7ac0738
|
/pi1/motorTest.py
|
30240cc23fa03de9bfd7c3373a3a17c8d1f20890
|
[
"MIT"
] |
permissive
|
Rose-Hulman-Rover-Team/Rover-2019-2020
|
4fbfd0b1250fe926d31806b6e287e1b92760a886
|
d75a9086fa733f8a8b5240005bee058737ad82c7
|
refs/heads/master
| 2021-06-17T09:32:21.412169
| 2021-05-28T21:22:58
| 2021-05-28T21:22:58
| 208,160,113
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,973
|
py
|
# Simple demo of of the PCA9685 PWM servo/LED controller library.
# This will move channel 0 from min to max position repeatedly.
# Author: Tony DiCola
# License: Public Domain
from __future__ import division
import time
# Import the PCA9685 module.
import Adafruit_PCA9685
# Uncomment to enable debug output.
#import logging
#logging.basicConfig(level=logging.DEBUG)
# Initialise the PCA9685 using the default address (0x40).
pwm = Adafruit_PCA9685.PCA9685()
# Alternatively specify a different address and/or bus:
#pwm = Adafruit_PCA9685.PCA9685(address=0x41, busnum=2)
# Configure min and max servo pulse lengths
servo_min = 150 # Min pulse length out of 4096
servo_max = 600 # Max pulse length out of 4096
# Helper function to make setting a servo pulse width simpler.
def set_servo_pulse(channel, pulse):
pulse_length = 1000000 # 1,000,000 us per second
pulse_length //= 60 # 60 Hz
print('{0}us per period'.format(pulse_length))
pulse_length //= 4096 # 12 bits of resolution
print('{0}us per bit'.format(pulse_length))
pulse *= 1000
pulse //= pulse_length
pwm.set_pwm(channel, 0, pulse)
# Set frequency to 60hz, good for servos.
pwm.set_pwm_freq(1000)
print('Moving servo on channel 0, press Ctrl-C to quit...')
while True:
# Move servo on channel O between extremes.
#for x in range(0, 4095):
# pwm.set_pwm(1, 0, x)
# time.sleep(.001)
#time.sleep(1)
#pwm.set_pwm(1, 0, 0)
#time.sleep(2)
pwm.set_pwm(1, 0, 4095)
pwm.set_pwm(2, 0, 4095)
pwm.set_pwm(3, 0, 4095)
pwm.set_pwm(4, 0, 4095)
pwm.set_pwm(5, 0, 4095)
pwm.set_pwm(6, 0, 4095)
time.sleep(5)
pwm.set_pwm(1, 0, 0)
pwm.set_pwm(2, 0, 0)
pwm.set_pwm(3, 0, 0)
pwm.set_pwm(4, 0, 0)
pwm.set_pwm(5, 0, 0)
pwm.set_pwm(6, 0, 0)
time.sleep(1)
## time.sleep(1)
## pwm.set_pwm(1, 0, 4095)
## time.sleep(1)
|
[
"chenz16@rose-hulman.edu"
] |
chenz16@rose-hulman.edu
|
0527ac0974bc9e0bb251c33ed09182b31d508867
|
5fefc7b4b3e0022ffa1985bff2944d8b5ce24665
|
/Tsang_sim_archive/test_ls_cen.py
|
961ed1a960c700639ee1dfc23508baa42dac8aae
|
[] |
no_license
|
William-SKC/SLAM_Simulation
|
23284c95b0139b57be40724c1141e52ee47edfd5
|
1ef1594aede469e595ce1339ade6051a9893ace7
|
refs/heads/master
| 2021-01-12T03:39:28.173723
| 2018-07-11T19:36:34
| 2018-07-11T19:36:34
| 78,247,689
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,134
|
py
|
from numpy import matrix
from numpy import linalg as LA
import numpy as np
import robot_team_ls_cen
import sim_env
import math
N = 5 # number of robot
M = 1 # number of landmark
###
iteration = 500
time_end = 2000
sigma_tr_arr = [0] * time_end
sigma_th_tr_arr = [0] * time_end
error_arr = [0] * time_end
for i in range(iteration):
print(i)
initial = matrix([1, 1, 1, 2, 2, 1, -1, -1, 1, 3], dtype=float).T
robots = robot_team_ls_cen.Robot_Team_LS_Cen(initial)
landmarks = [None] * M
for m in range(M):
landmarks[m] = sim_env.Landmark(m, matrix([0.01, 0.02], dtype=float).getT())
for t in range(time_end):
# motion propagation
robots.prop_update()
#robot 0
[dis, phi] = sim_env.relative_measurement(robots.position[0:2], robots.theta[0], landmarks[0].position)
robots.ablt_obsv(0, [dis, phi], landmarks[0])
# robot 2
[dis, phi] = sim_env.relative_measurement(robots.position[4:6], robots.theta[2], robots.position[0:2])
robots.rela_obsv(2, 0, [dis, phi])
[dis, phi] = sim_env.relative_measurement(robots.position[4:6], robots.theta[2], robots.position[2:4])
robots.rela_obsv(2, 1, [dis, phi])
# observation - robot 3
[dis, phi] = sim_env.relative_measurement(robots.position[6:8], robots.theta[3], landmarks[0].position)
robots.ablt_obsv(3, [dis, phi], landmarks[0])
[dis, phi] = sim_env.relative_measurement(robots.position[6:8], robots.theta[3], robots.position[8:10])
robots.rela_obsv(3, 4, [dis, phi])
# real error
s = 0
for j in range(5):
s += pow(robots.s[2*j,0] - robots.position[2*j,0],2) + pow(robots.s[2*j+1,0] - robots.position[2*j+1,0],2)
s = math.sqrt(s*0.2)
error_arr[t] = error_arr[t] + s*(1/float(iteration))
# covariance error
sigma_tr_arr[t] = sigma_tr_arr[t] + math.sqrt(0.2*robots.sigma.trace()[0,0] )*(1/float(iteration))
sigma_th_tr_arr[t] = sigma_th_tr_arr[t] + math.sqrt(0.2*robots.th_sigma.trace()[0,0] )*(1/float(iteration))
file = open('output_ls_cen.txt', 'w')
for t in range(time_end):
file.write( str(sigma_tr_arr[t]) + ' ' + str(sigma_th_tr_arr[t]) + ' ' + str(error_arr[t]) + '\n')
file.close()
|
[
"billyskc@ucla.edu"
] |
billyskc@ucla.edu
|
ce18ad1b15d57f14c990673732248c4a12e960b5
|
a0e777ea7e0d00c061068db132a30a8fa545cc75
|
/FluentPython/insort.py
|
58c686082c39f50d5c8b0b43a9736306a5726539
|
[] |
no_license
|
aadisetyaa/Python-Cookbook
|
87215b64d2d3631d6b18e90a68a09400e7d80919
|
a8df0343a39725312686423296bfd860dbaf70ad
|
refs/heads/master
| 2022-04-08T13:41:27.255352
| 2017-11-27T03:54:29
| 2017-11-27T03:54:29
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 201
|
py
|
import bisect
import random
SIZE = 7
random.seed(1729)
my_list = []
for i in range(SIZE):
new_item = random.randrange(SIZE*2)
bisect.insort(my_list, new_item)
print('%2d ->' % new_item, my_list)
|
[
"wpr101@hotmail.com"
] |
wpr101@hotmail.com
|
59d8e4f5bc64a72352af0319f883401bedcd1567
|
3054445ca866d8054717bd14b9c4f4ef79560540
|
/Rama Myrian/perro.py
|
285d80de13d57527267166e412125aa95604aa5b
|
[] |
no_license
|
javibautista/PrimerRepo
|
7d493db03dd1c5cf1dd1ade899fdd34084b76170
|
990b28b567db488a3141f05ff7fef37b22da72a8
|
refs/heads/master
| 2020-03-25T06:01:54.065521
| 2019-06-23T23:49:59
| 2019-06-23T23:49:59
| 143,479,846
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 415
|
py
|
class Perro:
def __init__(self, posicion):
self.posicion = 0
def caminar(self):
self.posicion += 4
def ladrar(self):
print("GUAU GUAU")
if __name__ == '__main__':
perro = Perro(0)
perro.caminar()
print(perro.posicion)
perro.ladrar()
def pasear_mascota(caminar):
caminar += 5
camina = caminar + perro.posicion
print("La mascota quedo en ", camina)
pasea = pasear_mascota(2)
print(pasea)
|
[
"javibautista333@gmail.com"
] |
javibautista333@gmail.com
|
e73ff28ee191a345f27aada2786db28d6dace4a9
|
661d78ddd1d157a84cb3f25a94b1961ef44fbcbf
|
/hw6/hw6_test.py
|
7324e53313c46d11a30a7aeedbffdffd5abb8707
|
[] |
no_license
|
Jennifer-Shiau/ML2019SPRING
|
7670ffb654565643b751f5f3c6ecde8a6fd3289d
|
0a7ebb5fff24bc2d8da84d895ba3c54e3cc6701e
|
refs/heads/master
| 2022-03-05T22:44:09.758033
| 2019-10-30T06:26:23
| 2019-10-30T06:26:23
| 171,809,904
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,512
|
py
|
import numpy as np
import pandas as pd
import csv
import json
import random
import sys
from keras.models import load_model
import jieba
def load_data(test_x_path):
data = pd.read_csv(test_x_path, header = 0)
data = np.array(data.values)
test_x = data[:, 1]
# test_x.shape = (20000,)
return test_x
def get_seg(x):
thre = 200
seg_list = []
for i in x:
seg = jieba.lcut(i)
if len(seg) > thre:
seg = seg[:thre]
seg_list.append(seg)
return seg_list
def load_test_data(test_x):
x = get_seg(test_x)
max_len = 0
word2idx = json.load(open('word2idx.json'))
# run through each sentence
for i in range(len(x)):
# run through each word
for j in range(len(x[i])):
try:
x[i][j] = word2idx[x[i][j]]
except:
x[i][j] = 0
x[i] = np.array(x[i], dtype = int)
if len(x[i]) > max_len:
max_len = len(x[i])
x_test = np.zeros((len(x), max_len), dtype = int)
for i in range(x_test.shape[0]):
x_test[i][:x[i].shape[0]] = x[i]
return x_test
def ensemble(output_path, x_test):
model1 = load_model('model_2.h5')
model2 = load_model('model_3.h5')
model3 = load_model('model_5.hdf5')
ans1 = model1.predict_classes(x_test)
ans2 = model2.predict_classes(x_test)
ans3 = model3.predict_classes(x_test)
ans = vote(ans1, ans2, ans3)
file = open(output_path, 'w+')
out_file = csv.writer(file, delimiter = ',', lineterminator = '\n')
out_file.writerow(['id', 'label'])
for i in range(len(ans)):
out_file.writerow([i, ans[i]])
file.close()
def vote(ans1, ans2, ans3):
random.seed(0)
ans = np.zeros(ans1.shape)
for i in range(len(ans1)):
if ans1[i] == ans2[i] and ans1[i] == ans3[i]:
ans[i] = ans1[i]
elif ans1[i] == ans2[i]:
ans[i] = ans1[i]
elif ans2[i] == ans3[i]:
ans[i] = ans2[i]
elif ans1[i] == ans3[i]:
ans[i] = ans1[i]
else:
r = random.randint(1, 3)
if r == 1:
ans[i] = ans1[i]
elif r == 2:
ans[i] = ans2[i]
else:
ans[i] = ans3[i]
return ans.astype(int)
if __name__ == '__main__':
jieba.load_userdict(sys.argv[2])
test_x = load_data(sys.argv[1])
x_test = load_test_data(test_x)
ensemble(sys.argv[3], x_test)
|
[
"b05901068@ntu.edu.tw"
] |
b05901068@ntu.edu.tw
|
33db18461299fbbbabfda70980708db958b521a0
|
06ea7950e48945725e7442c4cb4588750e6b6656
|
/app/core/migrations/0005_auto_20210107_1826.py
|
45b3ff01f2dfb7161f374f06d844a09d5c6333ac
|
[] |
no_license
|
AhmedBafadal/ten
|
a0954dec883e03b72439fecdb8a443c92f68be42
|
5cca62a4db84b2f0e6b3c1e253890220fbb2553a
|
refs/heads/main
| 2023-02-10T00:06:12.672524
| 2021-01-08T02:56:17
| 2021-01-08T02:56:17
| 327,774,232
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 378
|
py
|
# Generated by Django 2.1.3 on 2021-01-07 18:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0004_auto_20210107_1818'),
]
operations = [
migrations.AlterField(
model_name='inventory',
name='description',
field=models.TextField(),
),
]
|
[
"a.m.bafadal@gmail.com"
] |
a.m.bafadal@gmail.com
|
fb915ef699daa0ad6453ca4cf0910c8ec5d44441
|
d395cd51965fb98c9956834c40ab00b67196f413
|
/PKUTreeMaker/test/Wcrab/crab3_analysisZZ2.py
|
5f93dc810f63b03a8e79694787c6cd65fa1a80cd
|
[] |
no_license
|
qianminghuang/VBSWA_JESR-94X
|
0c6d81b841bc80b4d03a241e011bcfc832f5e3de
|
bbade3ef61f791f14c954c0f5566a23a50384105
|
refs/heads/master
| 2020-09-10T15:27:42.976213
| 2019-12-04T12:41:52
| 2019-12-04T12:41:52
| 221,738,090
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,487
|
py
|
from WMCore.Configuration import Configuration
config = Configuration()
config.section_("General")
#config.General.requestName = 'ZZ-1'
config.General.requestName = 'ZZ-2'
config.General.transferLogs = True
config.section_("JobType")
config.JobType.pluginName = 'Analysis'
config.JobType.inputFiles = ['Summer16_23Sep2016V4_MC_L1FastJet_AK4PFchs.txt','Summer16_23Sep2016V4_MC_L2Relative_AK4PFchs.txt','Summer16_23Sep2016V4_MC_L3Absolute_AK4PFchs.txt','Summer16_23Sep2016V4_MC_L1FastJet_AK4PFPuppi.txt','Summer16_23Sep2016V4_MC_L2Relative_AK4PFPuppi.txt','Summer16_23Sep2016V4_MC_L3Absolute_AK4PFPuppi.txt']
# Name of the CMSSW configuration file
config.JobType.psetName = 'analysis.py'
config.JobType.allowUndistributedCMSSW = True
config.section_("Data")
#config.Data.inputDataset = '/ZZ_TuneCUETP8M1_13TeV-pythia8/RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6_ext1-v1/MINIAODSIM'
config.Data.inputDataset = '/ZZ_TuneCUETP8M1_13TeV-pythia8/RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1/MINIAODSIM'
config.Data.inputDBS = 'global'
config.Data.splitting = 'FileBased'
config.Data.unitsPerJob = 20
config.Data.totalUnits = -1
config.Data.outLFNDirBase = '/store/group/phys_jetmet/qihuang/'
#config.Data.outLFNDirBase = '/store/user/qihuang/'
config.Data.publication = False
#config.Data.outputDatasetTag = 'ZZ-1'
config.Data.outputDatasetTag = 'ZZ-2'
config.section_("Site")
config.Site.storageSite = 'T2_CH_CERN'
|
[
"qianming.huang@cern.ch"
] |
qianming.huang@cern.ch
|
20d8cf0d76f39ae1bf0ce1a70b5f25df1fad9a8b
|
cb71749d5708c0012f7cffb5a1ebcbce358b407b
|
/split_col+func.py
|
dcb99ddc3b6966b1236018461055a25ccae81db4
|
[] |
no_license
|
mbmarcin/code_examples
|
80928675d30ae1cf1909d9b85fbfb723d353bbec
|
0a62537cd06f2f68263a02c92bca3fcfc9121e78
|
refs/heads/master
| 2023-02-19T12:29:32.876500
| 2021-01-23T21:44:40
| 2021-01-23T21:44:40
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,733
|
py
|
# Given a pandas dataframe containing a pandas series/column of tuples B,
# we want to extract B into B1 and B2 and assign them into separate pandas series
# Method 1: (faster)
# use pd.Series.tolist() method to return a list of tuples
# use pd.DataFrame on the resulting list to turn it into a new pd.DataFrame object, while specifying the original df index
# add to the original df
import pandas as pd
import time
# Put your dataframe here
df = pd.DataFrame({'A':[1,2], 'B':[(1,2), (3,4)]})
print("Original Dataset")
print(df)
start = time.time()
df[['B1','B2']] = pd.DataFrame(df['B'].tolist(),index=df.index)
print("Method 1")
print("Time elapsed :" + str(time.time()-start))
print(df)
# Method 2: (more Pythonic but much slower for larger dataframes)
# use the pd.DataFram.apply method to the column with the pd.Series function
start = time.time()
df[['B1','B2']] = df['B'].apply(pd.Series)
print("Method 2")
print("Time elapsed :" + str(time.time()-start))
print(df)
#EXAMPLE
dta2 = {
'a': [1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3],
'b': [7, 7, 8, 8, 9, 9, 22, 22, 12, 12, 12, 12]
#'c': [45, 34, 12, 45, 56, 67, 78, 34, 23, 34, 45, 23]
}
#
# df = pd.DataFrame(dta)
df2 = pd.DataFrame(dta2)
# change value per group
def first_last(group, col_qty):
"""
:param group: group
:param col_qty: num of col
:return: first and last element df
"""
lst = group.iloc[:, col_qty].to_list()
#return pd.Series([lst[0], lst[len(lst) - 1]])--------> helpfuly
return lst[0], lst[len(lst) - 1]
x = df2.groupby('a').apply(first_last, 1).reset_index()
x[['f', 'e']] = pd.DataFrame(x.iloc[:, 1].tolist(), index=x.index)
print(x)
|
[
"noreply@github.com"
] |
mbmarcin.noreply@github.com
|
4c18ab2948b1020a0de83bc83581060979fd7077
|
1a95d3d1217abae2cf6b2691381945b228a4fe73
|
/utils/prepare_data/split_label.py
|
d331495055725f0d4e33102ec69e369f68413893
|
[] |
no_license
|
fanjuncai/Net
|
38cccb64494536ed396ab2df8bc96b905b85e0e4
|
aa45452ad9d32fce7f79754167dfa79f21629569
|
refs/heads/master
| 2020-09-04T22:10:12.912397
| 2018-06-12T12:37:02
| 2018-06-12T12:37:02
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,075
|
py
|
import os
import numpy as np
import math
import cv2 as cv
path = '/home/north-computer/Text/data/2017/train_image'
gt_path = '/home/north-computer/Text/data/2017/train_gt'
out_path = 're_image'
if not os.path.exists(out_path):
os.makedirs(out_path)
files = os.listdir(path)
files.sort()
#files=files[:100]
for file in files:
_, basename = os.path.split(file)
if basename.lower().split('.')[-1] not in ['jpg', 'png']:
continue
stem, ext = os.path.splitext(basename)
gt_file = os.path.join(gt_path, 'gt_' + stem + '.txt')
img_path = os.path.join(path, file)
print(img_path)
img = cv.imread(img_path)
img_size = img.shape
im_size_min = np.min(img_size[0:2])
im_size_max = np.max(img_size[0:2])
im_scale = float(600) / float(im_size_min)
if np.round(im_scale * im_size_max) > 1200:
im_scale = float(1200) / float(im_size_max)
re_im = cv.resize(img, None, None, fx=im_scale, fy=im_scale, interpolation=cv.INTER_LINEAR)
re_size = re_im.shape
cv.imwrite(os.path.join(out_path, stem) + '.jpg', re_im)
with open(gt_file, 'r') as f:
lines = f.readlines()
for line in lines:
splitted_line = line.strip().lower().split(',')
pt_x = np.zeros((4, 1))
pt_y = np.zeros((4, 1))
pt_x[0, 0] = int(float(splitted_line[0]) / img_size[1] * re_size[1])
pt_y[0, 0] = int(float(splitted_line[1]) / img_size[0] * re_size[0])
pt_x[1, 0] = int(float(splitted_line[2]) / img_size[1] * re_size[1])
pt_y[1, 0] = int(float(splitted_line[3]) / img_size[0] * re_size[0])
pt_x[2, 0] = int(float(splitted_line[4]) / img_size[1] * re_size[1])
pt_y[2, 0] = int(float(splitted_line[5]) / img_size[0] * re_size[0])
pt_x[3, 0] = int(float(splitted_line[6]) / img_size[1] * re_size[1])
pt_y[3, 0] = int(float(splitted_line[7]) / img_size[0] * re_size[0])
ind_x = np.argsort(pt_x, axis=0)
pt_x = pt_x[ind_x]
pt_y = pt_y[ind_x]
if pt_y[0] < pt_y[1]:
pt1 = (pt_x[0], pt_y[0])
pt3 = (pt_x[1], pt_y[1])
else:
pt1 = (pt_x[1], pt_y[1])
pt3 = (pt_x[0], pt_y[0])
if pt_y[2] < pt_y[3]:
pt2 = (pt_x[2], pt_y[2])
pt4 = (pt_x[3], pt_y[3])
else:
pt2 = (pt_x[3], pt_y[3])
pt4 = (pt_x[2], pt_y[2])
xmin = int(min(pt1[0], pt2[0]))
ymin = int(min(pt1[1], pt2[1]))
xmax = int(max(pt2[0], pt4[0]))
ymax = int(max(pt3[1], pt4[1]))
if xmin < 0:
xmin = 0
if xmax > re_size[1] - 1:
xmax = re_size[1] - 1
if ymin < 0:
ymin = 0
if ymax > re_size[0] - 1:
ymax = re_size[0] - 1
width = xmax - xmin
height = ymax - ymin
# reimplement
step = 16.0
x_left = []
x_right = []
x_left.append(xmin)
x_left_start = int(math.ceil(xmin / 16.0) * 16.0)
if x_left_start == xmin:
x_left_start = xmin + 16
for i in np.arange(x_left_start, xmax, 16):
x_left.append(i)
x_left = np.array(x_left)
x_right.append(x_left_start - 1)
for i in range(1, len(x_left) - 1):
x_right.append(x_left[i] + 15)
x_right.append(xmax)
x_right = np.array(x_right)
idx = np.where(x_left == x_right)
x_left = np.delete(x_left, idx, axis=0)
x_right = np.delete(x_right, idx, axis=0)
if not os.path.exists('label_tmp'):
os.makedirs('label_tmp')
with open(os.path.join('label_tmp', stem) + '.txt', 'a') as f:
for i in range(len(x_left)):
f.writelines("text\t")
f.writelines(str(int(x_left[i])))
f.writelines("\t")
f.writelines(str(int(ymin)))
f.writelines("\t")
f.writelines(str(int(x_right[i])))
f.writelines("\t")
f.writelines(str(int(ymax)))
f.writelines("\n")
|
[
"2289331373@qq.com"
] |
2289331373@qq.com
|
58257717c180347561efa5a064b1c55da39fffe1
|
eda5634f00ad384b8179e19c1d7a4fd4dcabdaa1
|
/run.py
|
a84d2605aceb9d918a30bc971cad150984adaf84
|
[] |
no_license
|
somoire/password-locker
|
628d02b8c7288aa86767bc74ff82e2823c18387b
|
01f3ce5d6cdce4e3aff20bc97782e701c57e5067
|
refs/heads/master
| 2020-05-05T10:57:07.959292
| 2019-04-09T08:01:17
| 2019-04-09T08:01:17
| 179,968,063
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,215
|
py
|
#!/usr/bin/env python3.6
import unittest
import random
import string
from user import User
from user import credentials
def create_user(user_name,account_name):
'''
Function to create a new user
'''
new_user = User(user_name,account_name)
return new_user
def create_credential(user_password):
'''
Function to create a new password
'''
new_credential = credentials(user_password)
return new_credential
def save_user(user):
'''
Function to save user
'''
user.save_user()
def save_credential(credentials):
'''
Function to save password
'''
credentials.save_credential()
def del_user(user):
'''
Function to delete user
'''
user.delete_user()
def del_credential(credentials):
'''
Function to delete credential
'''
credentials.delete_credential()
def display_user():
'''
Function to display a user
'''
return User.display_user()
def display_credential():
'''
Function to display a credential
'''
return credentials.display_credentials()
def main():
print("Welcome to your password locker.Please input your name?")
user_name = input()
print(f"Hello {user_name}. what would you like to do?")
print('\n')
while True:
print("run either of this codes according to your preference: ss - Sign-up a new account, dc - display accounts generated, fd -find an account, quit -close the password locker ")
short_code = input().lower()
if short_code == 'ss':
print("New account")
print("-"*10)
print ("user name ....")
user_name = input()
print("account name ...")
account_name = input()
save_user(create_user(user_name,account_name)) # create and save new user.
print("type own-to generate your own password or random-to randomly generate a password")
user_password=input()
if user_password == 'own':
print("enter password")
passwordtype=input()
print("your user name is " + user_name, "for " + account_name,"your password is " + passwordtype)
elif user_password =='random':
def randomStrings(stringLength):
lettersAndDigits = string.ascii_letters + string.digits
return ''.join(random.choice(lettersAndDigits) for i in range(stringLength))
user_password = randomStrings(8)
print("your user name is " + user_name, "for " + account_name,"your password is " + user_password)
save_credential(create_credential(user_password)) # create and save newcredential.
print ('\n')
print(f"New account {user_name} {account_name} {user_password} created")
print ('\n')
elif short_code == 'dc':
if display_user():
print("There you go")
print('\n')
for user in display_user():
print(f"{user.user_name} {user.account_name} .....")
print('\n')
for credentials in display_credential():
print(f"{credentials.user_password} .....")
print('\n')
else:
print('\n')
print("Currently there are no existent accounts.")
print('\n')
elif short_code == 'fd':
print("Key in the account username you want to search for")
search_account = input()
if(search_account):
search_account =(search_account)
print(f"{search_account.user_name} {search_account.account_name}")
print('-' * 20)
print(f"account name.......{search_account.account.name}")
print(f"user name.......{search_account.user_name}")
else:
print("Kindly verify that the account really exists from the user.")
elif short_code == 'quit':
print("Thank you for visiting password locker;-)")
break
else:
print("Kindly use the specified codes to be able to run password locker")
if __name__ == '__main__':
main()
|
[
"rayr30667@gmail.com"
] |
rayr30667@gmail.com
|
994997eb7f427a82eb6de2770c1bf2fb474740c7
|
a67492bfae08b2a2dc486f93fd9b3e5f5da4edaf
|
/lib/bbob_pproc/comp2/pptable2.py
|
4a53b8601b7aea47bd29ef7b90ec11ee71861894
|
[
"Beerware"
] |
permissive
|
Oueee/SOS
|
107f67889580f712dfc3655d0d220fadae3fb011
|
d2c646da4c89b638595c918e5367a15e1a68c768
|
refs/heads/master
| 2021-01-01T03:42:24.586197
| 2016-05-21T15:52:14
| 2016-05-21T15:52:14
| 58,935,277
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 14,613
|
py
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""Rank-sum tests table on "Final Data Points".
That is, for example, using 1/#fevals(ftarget) if ftarget was reached
and -f_final otherwise as input for the rank-sum test, where obviously
the larger the better.
One table per function and dimension.
"""
from __future__ import absolute_import
import os, warnings
import numpy
import matplotlib.pyplot as plt
from bbob_pproc import genericsettings, bestalg, toolsstats
from bbob_pproc.pptex import tableLaTeX, tableLaTeXStar, writeFEvals2, writeFEvalsMaxPrec, writeLabels
from bbob_pproc.toolsstats import significancetest
from pdb import set_trace
targetsOfInterest = (10., 1e-1, 1e-3, 1e-5, 1e-7) # Needs to be sorted
targetf = 1e-8 # value for determining the success ratio
samplesize = genericsettings.simulated_runlength_bootstrap_sample_size
#Get benchmark short infos: put this part in a function?
funInfos = {}
isBenchmarkinfosFound = False
figure_legend = (
r"\ERT\ in number of function evaluations divided by the best \ERT\ measured during " +
r"BBOB-2009 given in the respective first row with the central 80\% range divided by two in brackets for " +
r"different $\Df$ values. \#succ is the number of trials that reached the final " +
r"target $\fopt + 10^{-8}$. " +
r"1:\algorithmAshort\ is \algorithmA\ and 2:\algorithmBshort\ is \algorithmB. " +
r"Bold entries are statistically significantly better compared to the other algorithm, " +
r"with $p=0.05$ or $p=10^{-k}$ where $k\in\{2,3,4,\dots\}$ is the number " +
r"following the $\star$ symbol, with Bonferroni correction of #1. " +
r"A $\downarrow$ indicates the same tested against the best BBOB-2009. ")
infofile = os.path.join(os.path.split(__file__)[0], '..',
'benchmarkshortinfos.txt')
try:
f = open(infofile,'r')
for line in f:
if len(line) == 0 or line.startswith('%') or line.isspace() :
continue
funcId, funcInfo = line[0:-1].split(None,1)
funInfos[int(funcId)] = funcId + ' ' + funcInfo
f.close()
isBenchmarkinfosFound = True
except IOError, (errno, strerror):
print "I/O error(%s): %s" % (errno, strerror)
print 'Could not find file', infofile, \
'Titles in scaling figures will not be displayed.'
def main(dsList0, dsList1, dimsOfInterest, outputdir, info='', verbose=True):
"""One table per dimension, modified to fit in 1 page per table."""
#TODO: method is long, split if possible
dictDim0 = dsList0.dictByDim()
dictDim1 = dsList1.dictByDim()
alg0 = set(i[0] for i in dsList0.dictByAlg().keys()).pop()[0:3]
alg1 = set(i[0] for i in dsList1.dictByAlg().keys()).pop()[0:3]
open(os.path.join(outputdir, 'bbob_pproc_commands.tex'), 'a'
).write(r'\providecommand{\algorithmAshort}{%s}' % writeLabels(alg0) + '\n' +
r'\providecommand{\algorithmBshort}{%s}' % writeLabels(alg1) + '\n')
if info:
info = '_' + info
dims = set.intersection(set(dictDim0.keys()), set(dictDim1.keys()))
if not bestalg.bestalgentries2009:
bestalg.loadBBOB2009()
header = [r'$\Delta f$']
for i in targetsOfInterest:
#header.append(r'\multicolumn{2}{@{}c@{}}{$10^{%d}$}' % (int(numpy.log10(i))))
header.append(r'\multicolumn{2}{@{}c@{}}{1e%+d}' % (int(numpy.log10(i))))
header.append(r'\multicolumn{2}{|@{}r@{}}{\#succ}')
for d in dimsOfInterest: # TODO set as input arguments
table = [header]
extraeol = [r'\hline']
try:
dictFunc0 = dictDim0[d].dictByFunc()
dictFunc1 = dictDim1[d].dictByFunc()
except KeyError:
continue
funcs = set.union(set(dictFunc0.keys()), set(dictFunc1.keys()))
nbtests = len(funcs) * 2. #len(dimsOfInterest)
for f in sorted(funcs):
bestalgentry = bestalg.bestalgentries2009[(d, f)]
curline = [r'${\bf f_{%d}}$' % f]
bestalgdata = bestalgentry.detERT(targetsOfInterest)
bestalgevals, bestalgalgs = bestalgentry.detEvals(targetsOfInterest)
for i in bestalgdata[:-1]:
curline.append(r'\multicolumn{2}{@{}c@{}}{%s}' % writeFEvalsMaxPrec(i, 2))
curline.append(r'\multicolumn{2}{@{}c@{}|}{%s}' % writeFEvalsMaxPrec(bestalgdata[-1], 2))
tmp = bestalgentry.detEvals([targetf])[0][0]
tmp2 = numpy.sum(numpy.isnan(tmp) == False)
curline.append('%d' % (tmp2))
if tmp2 > 0:
curline.append('/%d' % len(tmp))
table.append(curline[:])
extraeol.append('')
rankdata0 = [] # never used
# generate all data from ranksum test
entries = []
ertdata = {}
for nb, dsList in enumerate((dictFunc0, dictFunc1)):
try:
entry = dsList[f][0] # take the first DataSet, there should be only one?
except KeyError:
warnings.warn('data missing for data set ' + str(nb) + ' and function ' + str(f))
print('*** Warning: data missing for data set ' + str(nb) + ' and function ' + str(f) + '***')
continue # TODO: problem here!
ertdata[nb] = entry.detERT(targetsOfInterest)
entries.append(entry)
for _t in ertdata.values():
for _tt in _t:
if _tt is None:
raise ValueError
if len(entries) < 2: # funcion not available for *both* algorithms
continue # TODO: check which one is missing and make sure that what is there is displayed properly in the following
testres0vs1 = significancetest(entries[0], entries[1], targetsOfInterest)
testresbestvs1 = significancetest(bestalgentry, entries[1], targetsOfInterest)
testresbestvs0 = significancetest(bestalgentry, entries[0], targetsOfInterest)
for nb, entry in enumerate(entries):
if nb == 0:
curline = [r'1:\:\algorithmAshort\hspace*{\fill}']
else:
curline = [r'2:\:\algorithmBshort\hspace*{\fill}']
#data = entry.detERT(targetsOfInterest)
dispersion = []
data = []
evals = entry.detEvals(targetsOfInterest)
for i in evals:
succ = (numpy.isnan(i) == False)
tmp = i.copy()
tmp[succ==False] = entry.maxevals[numpy.isnan(i)]
#set_trace()
data.append(toolsstats.sp(tmp, issuccessful=succ)[0])
#if not any(succ):
#set_trace()
if any(succ):
tmp2 = toolsstats.drawSP(tmp[succ], tmp[succ==False],
(10, 50, 90), samplesize)[0]
dispersion.append((tmp2[-1]-tmp2[0])/2.)
else:
dispersion.append(None)
if nb == 0:
assert not isinstance(data, numpy.ndarray)
data0 = data[:] # TODO: check if it is not an array, it's never used anyway?
for i, dati in enumerate(data):
z, p = testres0vs1[i] # TODO: there is something with the sign that I don't get
# assign significance flag, which is the -log10(p)
significance0vs1 = 0
if nb != 0:
z = -z # the test is symmetric
if nbtests * p < 0.05 and z > 0:
significance0vs1 = -int(numpy.ceil(numpy.log10(min([1.0, nbtests * p])))) # this is the larger the more significant
isBold = significance0vs1 > 0
alignment = 'c'
if i == len(data) - 1: # last element
alignment = 'c|'
if numpy.isinf(bestalgdata[i]): # if the 2009 best did not solve the problem
tmp = writeFEvalsMaxPrec(float(dati), 2)
if not numpy.isinf(dati):
tmp = r'\textit{%s}' % (tmp)
if isBold:
tmp = r'\textbf{%s}' % tmp
if dispersion[i] and numpy.isfinite(dispersion[i]):
tmp += r'${\scriptscriptstyle (%s)}$' % writeFEvalsMaxPrec(dispersion[i], 1)
tableentry = (r'\multicolumn{2}{@{}%s@{}}{%s}'
% (alignment, tmp))
else:
# Formatting
tmp = float(dati)/bestalgdata[i]
assert not numpy.isnan(tmp)
isscientific = False
if tmp >= 1000:
isscientific = True
tableentry = writeFEvals2(tmp, 2, isscientific=isscientific)
tableentry = writeFEvalsMaxPrec(tmp, 2)
if numpy.isinf(tmp) and i == len(data)-1:
tableentry = (tableentry
+ r'\textit{%s}' % writeFEvals2(numpy.median(entry.maxevals), 2))
if isBold:
tableentry = r'\textbf{%s}' % tableentry
elif 11 < 3 and significance0vs1 < 0: # cave: negative significance has no meaning anymore
tableentry = r'\textit{%s}' % tableentry
if dispersion[i] and numpy.isfinite(dispersion[i]/bestalgdata[i]):
tableentry += r'${\scriptscriptstyle (%s)}$' % writeFEvalsMaxPrec(dispersion[i]/bestalgdata[i], 1)
tableentry = (r'\multicolumn{2}{@{}%s@{}}{%s}'
% (alignment, tableentry))
elif tableentry.find('e') > -1 or (numpy.isinf(tmp) and i != len(data) - 1):
if isBold:
tableentry = r'\textbf{%s}' % tableentry
elif 11 < 3 and significance0vs1 < 0:
tableentry = r'\textit{%s}' % tableentry
if dispersion[i] and numpy.isfinite(dispersion[i]/bestalgdata[i]):
tableentry += r'${\scriptscriptstyle (%s)}$' % writeFEvalsMaxPrec(dispersion[i]/bestalgdata[i], 1)
tableentry = (r'\multicolumn{2}{@{}%s@{}}{%s}'
% (alignment, tableentry))
else:
tmp = tableentry.split('.', 1)
if isBold:
tmp = list(r'\textbf{%s}' % i for i in tmp)
elif 11 < 3 and significance0vs1 < 0:
tmp = list(r'\textit{%s}' % i for i in tmp)
tableentry = ' & .'.join(tmp)
if len(tmp) == 1:
tableentry += '&'
if dispersion[i] and numpy.isfinite(dispersion[i]/bestalgdata[i]):
tableentry += r'${\scriptscriptstyle (%s)}$' % writeFEvalsMaxPrec(dispersion[i]/bestalgdata[i], 1)
superscript = ''
if nb == 0:
z, p = testresbestvs0[i]
else:
z, p = testresbestvs1[i]
#The conditions are now that ERT < ERT_best
if ((nbtests * p) < 0.05 and dati - bestalgdata[i] < 0.
and z < 0.):
nbstars = -numpy.ceil(numpy.log10(nbtests * p))
#tmp = '\hspace{-.5ex}'.join(nbstars * [r'\star'])
if z > 0:
superscript = r'\uparrow' #* nbstars
else:
superscript = r'\downarrow' #* nbstars
# print z, linebest[i], line1
if nbstars > 1:
superscript += str(int(nbstars))
if superscript or significance0vs1:
s = ''
if significance0vs1 > 0:
s = '\star'
if significance0vs1 > 1:
s += str(significance0vs1)
s = r'$^{' + s + superscript + r'}$'
if tableentry.endswith('}'):
tableentry = tableentry[:-1] + s + r'}'
else:
tableentry += s
curline.append(tableentry)
#curline.append(tableentry)
#if dispersion[i] is None or numpy.isinf(bestalgdata[i]):
#curline.append('')
#else:
#tmp = writeFEvalsMaxPrec(dispersion[i]/bestalgdata[i], 2)
#curline.append('(%s)' % tmp)
tmp = entry.evals[entry.evals[:, 0] <= targetf, 1:]
try:
tmp = tmp[0]
curline.append('%d' % numpy.sum(numpy.isnan(tmp) == False))
except IndexError:
curline.append('%d' % 0)
curline.append('/%d' % entry.nbRuns())
table.append(curline[:])
extraeol.append('')
extraeol[-1] = r'\hline'
extraeol[-1] = ''
outputfile = os.path.join(outputdir, 'pptable2_%02dD%s.tex' % (d, info))
spec = r'@{}c@{}|' + '*{%d}{@{}r@{}@{}l@{}}' % len(targetsOfInterest) + '|@{}r@{}@{}l@{}'
res = r'\providecommand{\algorithmAshort}{%s}' % writeLabels(alg0) + '\n'
res += r'\providecommand{\algorithmBshort}{%s}' % writeLabels(alg1) + '\n'
# open(os.path.join(outputdir, 'bbob_pproc_commands.tex'), 'a').write(res)
#res += tableLaTeXStar(table, width=r'0.45\textwidth', spec=spec,
#extraeol=extraeol)
res += tableLaTeX(table, spec=spec, extraeol=extraeol)
f = open(outputfile, 'w')
f.write(res)
f.close()
if verbose:
print "Table written in %s" % outputfile
|
[
"n.toussaint@etu.unistra.fr"
] |
n.toussaint@etu.unistra.fr
|
927ac19569c4c3feeef69c7929f4b580c5822dd2
|
e1c0e35cf4c92e5b05f7267378a0e733c31a3e40
|
/Math/Sum_of_Multiples.py
|
e5579b94762546262ee5b10435595f0bcde6364e
|
[] |
no_license
|
rahulcode22/Data-structures
|
a2c8e00294e4398983f4acba49fc9ccfe6f4ec86
|
8e5e562c54be46cdf2493e19f4a74c016e62eeb4
|
refs/heads/master
| 2021-01-13T15:09:07.861247
| 2018-04-07T02:43:27
| 2018-04-07T02:43:27
| 79,187,451
| 20
| 9
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 364
|
py
|
'''Given a number a and limit N. Find the sum of multiple of a upto N.'''
#Simple Iterative O(n) Approach
def sumUpto(a,n):
sum_ = 0
i = a
while i <= n:
sum_ += i
i += a
return sum_
print sumUpto(7,49)
#Another O(1) Approach
def sumUpto(a,n):
m = n/a
sum_ = m*(m+1)/2
ans = a*sum_
return ans
print sumUpto(7,49)
|
[
"rahulrock0082@gmail.com"
] |
rahulrock0082@gmail.com
|
438fd8832059fe5b0451726baa1d120d574784c1
|
3a6c82d923bd7caccbb5b62c9b5baf93b1cf49b4
|
/WFS_devel/WFS_class_devel/Parameters.py
|
f675b0669112fed0b2d541273c998162ff377a25
|
[] |
no_license
|
wenh81/vlc_simulator
|
c3a88911db5573de9635e3e8f9f6dbd1a47b681a
|
825a0eab64be709efe161b9a48eb54c4bc5c1bef
|
refs/heads/master
| 2023-04-26T01:21:15.202421
| 2021-05-21T18:54:20
| 2021-05-21T18:54:20
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,947
|
py
|
#Sinalizes for interference between QCs
with_without = "with"
# Wavelenght(um)
wave = 0.633
# Number of Zernike terms
zernike = 20
# Sinalizes for use of defocus term
defocus = 0
# Quantity of microlens
quantity = 4
# Diameter of microlen [um]
diameter = 1000
# focal distance [um]
focal = 200000
# Reflectance
reflect = 0.1
# Radius or edge of QC [um]
cell = 200
# Space between QCs [um]
space = 10
# Effective spot radius [um]
eff = 0.3
# Linearization interval [um]
lin = 0.46
# Absorption coefficient [cm-1]
coefabs = 3345
# QC's inner radius [um]
cent = 0
# QC's material quantum efficience
quant = 0.667
# QC's material quantum efficience of inner radius
quant_inner = 1.0
# Anode's electrons difusion lenght [cm]
lanode = 0.00008768
# Cathode's holes difusion lenght [cm]
lcathode = 0.0293
# Anode's electrons difusion coefficient [cm^2/s]
canode = 2.23
# Cathode's holes difusion coefficient [cm^2/s]
ccathode = 10.76
# Cathode's superficial recombination speed [cm/s]
ranode = 4000
# Anode's superficial recombination speed [cm/s]
rcathode = 70
# Reset period(ms)
reset = 1
# Integration period(ms)
integ = 9
# Pixel model's junction capacitance(pF)
capac = 2
# Base thickness [cm]
bthick = 0.0000300
# Emiter thickness [cm]
ethick = 0.00003
# Pixel model's serie resistance [ohm]
sres = 10
# Pixel model's paralel resistance [ohm]
pres = 100000000000
# Reset pixel lenght(um)
lreset = 1.6
# Reset pixel width(um)
wreset = 3.2
# Buffer pixel lenght(um)
lbuffer = 1.6
# Buffer pixel width(um)
wbuffer = 3.2
# Selector pixel lenght(um)
lsel = 1.6
# Selector pixel widthe(um)
wsel = 3.2
# Charge resistance(Kohm)
charge = 680
# Operation minimum voltage(V)
vmin = 0.5
# Operation maximum voltage(V)
vmax = 2.05
# Transition time step
tran_time_step = 1000
# Sinalizes for the inclusion of interference between QCs
noise_noiseless = "noiseless"
# input optical power (W) for whole WFS matrix
TPS = 1e-4
|
[
"pnabelmonte@gmail.com"
] |
pnabelmonte@gmail.com
|
835ed4c4515af9f0df52405b2f1f0673e9ae8878
|
27ee4bc83a7094abfca59c0cfe3eeca752bfc2fa
|
/prac02/randoms.py
|
6329a1bed00fbfd5dff93b08b8a9662b1fd06604
|
[] |
no_license
|
NANGSENGKHAN/cp1404practicals
|
6c1fe3ad3e402b87f37b97a695b8bcbbf6c5f1f5
|
5e9e1b400a69d27aad340fd6abd99c290c4aabe1
|
refs/heads/master
| 2021-05-22T01:28:54.068687
| 2020-05-26T11:18:33
| 2020-05-26T11:18:33
| 252,907,344
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 818
|
py
|
import random
print(random.randint(5, 20)) # line 1
"""What did you see on line 1?
In line 1, 5 to 20 is an integer.
What was the smallest number you could have seen, what was the largest?
The smallest number is 5 and the largest is 19"""
print(random.randrange(3, 10, 2)) # line 2
"""What did you see on line 2?
In line 2, 3 to 10 is an odd number.
What was the smallest number you could have seen, what was the largest?
The smallest number is 3 and the largest number is 9.
Could line 2 have produced a 4?
No.
"""
print(random.uniform(2.5, 5.5)) # line 3
"""What did you see on line 3?
In line 3, 2.5 and 5.5 is a real number
What was the smallest number you could have seen, what was the largest?
The smallest number is 2.5 and the largest number is infinity near to 5.5.
"""
|
[
"62389440+NANGSENGKHAN@users.noreply.github.com"
] |
62389440+NANGSENGKHAN@users.noreply.github.com
|
4d84e13fb35103abb3193a3f30ef46fa3dc1b855
|
c9b9a120d7c0d05f41d9e88b2cc4b5a6e9e5bf77
|
/DataWrangling/TFRecords/map_char_text_to_tfrecords.py
|
0aec89c12d85c9caff7c6ad1a03800e003a85e16
|
[] |
no_license
|
sjakati98/PixelLinkCharacter
|
a1c5c34f4264639265de78f29897ec4fd44f3d0b
|
2b3d094eb433eabf875cc23a61ed70caab5857f2
|
refs/heads/master
| 2020-04-20T02:50:08.138431
| 2019-11-14T18:15:31
| 2019-11-14T18:15:31
| 168,581,618
| 2
| 0
| null | 2019-11-14T18:15:32
| 2019-01-31T19:15:32
|
Python
|
UTF-8
|
Python
| false
| false
| 4,226
|
py
|
#encoding=utf-8
import numpy as np;
import tensorflow as tf
import util
import os
from dataset_utils import int64_feature, float_feature, bytes_feature, convert_to_example
import sys
sys.path.append('/home/sgkelley/pixel_link')
import config
def cvt_to_tfrecords(output_path , data_path, gt_path):
image_names = util.io.ls(data_path, '.jpg')#[0:10];
print("%d images found in %s"%(len(image_names), data_path));
with tf.python_io.TFRecordWriter(output_path) as tfrecord_writer:
for idx, image_name in enumerate(image_names):
oriented_bboxes = [];
bboxes = []
labels = [];
labels_text = [];
path = util.io.join_path(data_path, image_name);
print("\tconverting image: %d/%d %s"%(idx, len(image_names), image_name));
image_data = tf.gfile.FastGFile(path, 'r').read()
image = util.img.imread(path, rgb = True);
shape = image.shape
h, w = shape[0:2];
h *= 1.0;
w *= 1.0;
image_name = util.str.split(image_name, '.')[0];
gt_name = 'annotation_' + image_name[14:] + '.txt';
gt_filepath = util.io.join_path(gt_path, gt_name);
lines = util.io.read_lines(gt_filepath);
for line in lines:
line = util.str.remove_all(line, '\xef\xbb\xbf')
gt = util.str.split(line, ',');
oriented_box = [int(gt[i]) for i in range(8)];
oriented_box = np.asarray(oriented_box) / ([w, h] * 4);
oriented_bboxes.append(oriented_box);
xs = oriented_box.reshape(4, 2)[:, 0]
ys = oriented_box.reshape(4, 2)[:, 1]
xmin = xs.min()
xmax = xs.max()
ymin = ys.min()
ymax = ys.max()
bboxes.append([xmin, ymin, xmax, ymax])
# might be wrong here, but it doesn't matter because the label is not going to be used in detection
labels_text.append(gt[-1]);
ignored = util.str.contains(gt[-1], '###')
if ignored:
labels.append(config.ignore_label);
else:
labels.append(config.text_label)
example = convert_to_example(image_data, image_name, labels, labels_text, bboxes, oriented_bboxes, shape)
tfrecord_writer.write(example.SerializeToString())
if __name__ == "__main__":
root_dir = util.io.get_absolute_path('/mnt/nfs/work1/elm/sgkelley/shishir/cropped')
train_split_dir = util.io.join_path(root_dir, 'train_split')
test_split_dir = util.io.join_path(root_dir, 'test_split')
os.mkdir(os.path.join(train_split_dir, 'tfrecords'))
os.mkdir(os.path.join(test_split_dir, 'tfrecords'))
training_data_dir = util.io.join_path(train_split_dir, 'images')
output_dir = util.io.join_path(os.path.join(train_split_dir, 'tfrecords'))
annotations_parent_directory = util.io.join_path(train_split_dir, 'annotations')
for annotation_folder in list(filter(lambda folder: os.path.isdir(os.path.join(annotations_parent_directory, folder)), os.listdir(annotations_parent_directory))):
training_gt_dir = util.io.join_path(train_split_dir, 'annotations', annotation_folder)
cvt_to_tfrecords(output_path = util.io.join_path(output_dir, annotation_folder + '_train.tfrecord'), data_path = training_data_dir, gt_path = training_gt_dir)
output_dir = util.io.join_path(os.path.join(train_split_dir, 'tfrecords'))
test_data_dir = util.io.join_path(test_split_dir, 'images')
annotations_parent_directory = util.io.join_path(test_split_dir, 'annotations')
for annotation_folder in list(filter(lambda folder: os.path.isdir(os.path.join(annotations_parent_directory, folder)), os.listdir(annotations_parent_directory))):
test_gt_dir = util.io.join_path(test_split_dir, 'annotations', annotation_folder)
cvt_to_tfrecords(output_path = util.io.join_path(output_dir, annotation_folder + '_test.tfrecord'), data_path = test_data_dir, gt_path = test_gt_dir)
|
[
"shishir.jakati98@gmail.com"
] |
shishir.jakati98@gmail.com
|
a538476fd0732344642771e31ec36381a70890ac
|
0339b0d09502bbb1dbd080214c956ea020a76c1f
|
/Hackerrank/sherlock.py
|
42f7e07265a0092eb761125cbdd2f8fd458d08e9
|
[] |
no_license
|
lamalgopach/codeforces
|
aae785e2b09ac34f3927fb2ceeb5858ccf10656c
|
632dc09ba6bc04d9d22597a183965a9eec0b4607
|
refs/heads/master
| 2021-06-14T04:08:15.857020
| 2021-03-26T01:58:14
| 2021-03-26T01:58:14
| 170,820,683
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 812
|
py
|
"""
Given an array B and must determine an array A. For all i, B[i] >= A[i] >= 1. Select
a series of A[i] such that the sum of the absolute difference of consecutive pairs of A
is maximized. This will be the array's cost.
Input:
- t: number of test cases
- n: length of B
- space-separated integers of B[i]
Output:
Print the maximum sum on a separate line.
"""
def cost(b):
sum_one = 0
sum_num = 0
for i, num in enumerate(b):
if i == 0:
continue
num_to_last = abs(num - b[i - 1])
num_to_one = abs(num - 1)
last_to_one = abs(1 - b[i - 1])
temp = sum_one
sum_one = sum_num + last_to_one
sum_num = max(sum_num + num_to_last, temp + num_to_one)
return max(sum_one, sum_num)
t = int(input())
for i in range(t):
n = int(input())
b = list(map(int, input().split()))
print(cost(b))
|
[
"37968756+lamalgopach@users.noreply.github.com"
] |
37968756+lamalgopach@users.noreply.github.com
|
016945284302b73e1f0f4111554725b781791239
|
ad3b84e710a8a25573a1a58e833bcc53e3093934
|
/odltools/mdsal/tests/test_cli.py
|
ccffb17e120a73b13ec0b8000391a696e06bb7b8
|
[
"Apache-2.0"
] |
permissive
|
shague/odltools
|
a8af0a676882a66e0d00e4a832cec4bb71221cf9
|
13f95f2280cfdc68f61e0adc092a422c77e587b8
|
refs/heads/master
| 2021-01-15T10:57:54.927460
| 2018-06-18T12:36:36
| 2018-06-18T12:36:36
| 99,604,714
| 2
| 4
|
Apache-2.0
| 2018-07-24T15:56:38
| 2017-08-07T17:52:15
|
Python
|
UTF-8
|
Python
| false
| false
| 2,834
|
py
|
# Copyright 2018 Red Hat, Inc. and others. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by 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 logging
import os
import shutil
import unittest
from odltools import logg
from odltools.mdsal.models import model
from odltools.mdsal.models import models
from odltools.mdsal.models.Modules import netvirt_data_models
from odltools.mdsal.tests import Args
@unittest.skip("skipping")
class TestCli(unittest.TestCase):
def setUp(self):
logg.Logger(logging.INFO, logging.DEBUG)
self.args = Args(path="/tmp/testmodels2", pretty_print=True)
def test_get_models(self):
# Ensure odl is running at localhost:8181
# Remove an existing directory
if os.path.exists(self.args.path):
if os.path.islink(self.args.path):
os.unlink(self.args.path)
else:
shutil.rmtree(self.args.path)
# self.args.modules = ["config/network-topology:network-topology/topology/ovsdb:1"]
models.get_models(self.args)
# assert each model has been saved to a file
for res in self.args.modules:
res_split = res.split("/")
store = res_split[0]
model_path = res_split[1]
path_split = model_path.split(":")
module = path_split[0]
name = path_split[1]
filename = model.make_filename(self.args.path, store, module, name)
self.assertTrue(os.path.isfile(filename))
def test_get_all_models(self):
# Ensure odl is running at localhost:8181
# Remove an existing directory
if os.path.exists(self.args.path):
if os.path.islink(self.args.path):
os.unlink(self.args.path)
else:
shutil.rmtree(self.args.path)
models.get_models(self.args)
# assert each model has been saved to a file
for res in netvirt_data_models:
res_split = res.split("/")
store = res_split[0]
model_path = res_split[1]
path_split = model_path.split(":")
module = path_split[0]
name = path_split[1]
filename = model.make_filename(self.args.path, store, module, name)
self.assertTrue(os.path.isfile(filename))
if __name__ == '__main__':
unittest.main()
|
[
"shague@gmail.com"
] |
shague@gmail.com
|
a2936c966636ca9cbb405f2fd922dd31e6cabfcd
|
dbfcf24deb94c6119a507367f52b2745f30dc5df
|
/XML_Extract.py
|
833263a36a1e068a0751a018af32b3aece262c78
|
[] |
no_license
|
Almostdante/Hello2.7
|
71cd310217ea93806983b294382e18bad7366927
|
f6ccea6ee607ef0cd713b1eac2c479c57d19b39a
|
refs/heads/master
| 2021-01-13T14:37:01.680360
| 2016-01-30T06:07:33
| 2016-01-30T06:07:33
| 50,710,688
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 376
|
py
|
import urllib
import xml.etree.ElementTree as ET
#sample_URL = raw_input('Enter location: ')
#counts = ET.fromstring(urllib.urlopen(sample_URL).read()).findall('.//count')
#print 'Retrieving', sample_URL, '\n' 'Retrieved',len(urllib.urlopen(sample_URL).read()),'characters', '\n', "Count:", len(counts), '\n', 'Sum:', sum(int(counts[i].text) for i in range (0, len(counts)))
|
[
"almostdante@gmail.com"
] |
almostdante@gmail.com
|
e2e8ea0a466e23c8e16d87986d7e3b1a609a32af
|
1ec2222b8a189b997af0b54971e61ad9e62297a2
|
/googledrive.py
|
bfdda7602cd9b083c8dc67d91db50d34b64e9b15
|
[] |
no_license
|
kwrd/underwater_measurement_system
|
8f9a97a2a755ba1143b8b4dd01b88e91df68cd72
|
9d401758c5cd68dabc81ec535855ec2dff86baf9
|
refs/heads/master
| 2023-02-27T16:30:44.274198
| 2021-02-03T10:03:40
| 2021-02-03T10:03:40
| 335,579,054
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,383
|
py
|
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# If modifying these scopes, delete the file token.pickle.
# https://developers.google.com/drive/api/v3/about-auth
SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly', 'https://www.googleapis.com/auth/drive.appdata', 'https://www.googleapis.com/auth/drive.file']
def save():
"""Shows basic usage of the Drive v3 API.
Prints the names and ids of the first 10 files the user has access to.
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'config/credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('drive', 'v3', credentials=creds)
# Call the Drive v3 API
results = service.files().list(
pageSize=10, fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])
if not items:
print('No files found.')
else:
print('Files:')
for item in items:
print(u'{0} ({1})'.format(item['name'], item['id']))
file_metadata = {'name': 'sample_writer_row.csv'}
# https://googleapis.github.io/google-api-python-client/docs/epy/googleapiclient.http-module.html
media = MediaFileUpload('sample_writer_row.csv', mimetype='text/csv')
file = service.files().create(body=file_metadata,
media_body=media,
fields='id').execute()
print('File ID: %s' % file.get('id'))
|
[
"robertstoko@gmail.com"
] |
robertstoko@gmail.com
|
7ff65a88ec2461648484bb4576702dc93a63a38f
|
10ce30fad109998ad2b8dcd59d76764cde919a93
|
/cruditor/forms.py
|
b4ad2a08ffffff32b237b4331d3fe24e5deb9f9b
|
[
"BSD-3-Clause"
] |
permissive
|
Francislley/CrudDajndo2017.2
|
282bc6cfe4f80c3a68f38f1b21613ed1e32cd3c9
|
355a442670d28cd91526fd0127b7a01ce733cf2b
|
refs/heads/master
| 2021-09-04T09:07:57.237212
| 2017-09-01T10:36:24
| 2017-09-01T10:36:24
| 117,854,211
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 742
|
py
|
import floppyforms.__future__ as forms
from django.contrib.auth.forms import AuthenticationForm, SetPasswordForm
from django.utils.translation import ugettext_lazy as _
class LoginForm(AuthenticationForm, forms.Form):
username = forms.CharField(max_length=30)
password = forms.CharField(widget=forms.PasswordInput)
class ChangePasswordForm(SetPasswordForm, forms.Form):
new_password1 = forms.CharField(
label=_('New password'), widget=forms.PasswordInput)
new_password2 = forms.CharField(
label=_('New password confirmation'), widget=forms.PasswordInput)
class DeleteConfirmForm(forms.Form):
confirm = forms.BooleanField(
label=_('Are you sure you want to delete this item?'), required=True)
|
[
"steph@rdev.info"
] |
steph@rdev.info
|
5e9b8c17419ceaabe925b977cc19de21d004d025
|
4a9ed707b3b9adffd3e2f98c39040cede7dc0cc8
|
/garage/theano/envs/base.py
|
f99f2c6012914984454187916446df1668e1925a
|
[
"MIT"
] |
permissive
|
flyers/garage
|
f0c568bd850a0770a0f13d6c550318338049a462
|
745dff67d6777b78c5faaf2f2bfafcaf6f71d575
|
refs/heads/master
| 2020-04-15T15:38:42.500998
| 2019-01-29T11:56:29
| 2019-01-29T11:56:29
| 164,802,583
| 0
| 0
|
MIT
| 2019-01-29T12:11:13
| 2019-01-09T06:28:48
|
Python
|
UTF-8
|
Python
| false
| false
| 2,098
|
py
|
"""Wrapper class that converts gym.Env into TheanoEnv."""
from cached_property import cached_property
from gym.spaces import Box as GymBox
from gym.spaces import Dict as GymDict
from gym.spaces import Discrete as GymDiscrete
from gym.spaces import Tuple as GymTuple
from garage.envs import GarageEnv
from garage.envs.env_spec import EnvSpec
from garage.misc.overrides import overrides
from garage.theano.spaces import Box
from garage.theano.spaces import Dict
from garage.theano.spaces import Discrete
from garage.theano.spaces import Tuple
class TheanoEnv(GarageEnv):
"""
Returns a Theano wrapper class for gym.Env.
Args:
env (gym.Env): the env that will be wrapped
"""
def __init__(self, env=None, env_name=""):
super(TheanoEnv, self).__init__(env, env_name)
self.action_space = self._to_garage_space(self.env.action_space)
self.observation_space = self._to_garage_space(
self.env.observation_space)
def _to_garage_space(self, space):
"""
Converts a gym.space to a garage.theano.space.
Returns:
space (garage.theano.spaces)
"""
if isinstance(space, GymBox):
return Box(low=space.low, high=space.high)
elif isinstance(space, GymDict):
return Dict(space.spaces)
elif isinstance(space, GymDiscrete):
return Discrete(space.n)
elif isinstance(space, GymTuple):
return Tuple(list(map(self._to_garage_space, space.spaces)))
else:
raise NotImplementedError
@cached_property
@overrides
def spec(self):
"""
Returns an EnvSpec.
Returns:
spec (garage.envs.EnvSpec)
"""
return EnvSpec(
observation_space=self.observation_space,
action_space=self.action_space)
@cached_property
@overrides
def max_episode_steps(self):
"""
Returns gym.Env's max episode steps.
Returns:
max_episode_steps (int)
"""
return self.env.spec.max_episode_steps
|
[
"noreply@github.com"
] |
flyers.noreply@github.com
|
2191aee5ffad061805676545cbf9cca04c0cf064
|
aa90107cd69b5a64875be76f0bda5b443f024a98
|
/fibonacci_by_bound.py
|
9522012db301bc52fdf752eef7732d2c2734b29a
|
[] |
no_license
|
brahmaduttan/Programming_Lab_Python_TKM
|
9454762c71178d15c6a556d0c2c58ba5a989fe98
|
8dc72fa818cd7d642975abb4e13e5abfb6958eeb
|
refs/heads/main
| 2023-03-26T23:40:52.740934
| 2021-03-17T16:40:06
| 2021-03-17T16:40:06
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 409
|
py
|
def getFibonacci(start,end):
length = end
series = [0,1]
if(length == 1):
print(str([0]))
if(length == 2):
print(str([0,1]))
if(length>=3):
i = 2
while(i<length):
term = series[i-2]+series[i-1]
series.append(term)
i=i+1
filtered = list(filter(lambda x: (x >= start) and (x <= end), series))
return filtered
|
[
"rasikmhd10@gmail.com"
] |
rasikmhd10@gmail.com
|
5d0f4c54f194f751993b9a62e06c4ece90fdc2c3
|
0a351ffd2b59a8de2898555d7c0e28b953e5b0fe
|
/less10_return_statement.py
|
1b9ba168abc2727a05cb89bd0c0426b6484c2f2b
|
[] |
no_license
|
abervit/Python-Base
|
05200f79826286ca2ccdfbfb67f836eb7f3ba839
|
4b1f864b0efbeb2a5c28717c9a3b5c96ccf1275b
|
refs/heads/master
| 2022-11-22T03:29:03.121646
| 2022-11-17T17:10:17
| 2022-11-17T17:10:17
| 210,211,758
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 371
|
py
|
# Return Statement
"""When we want to get some information back from a function - we use 'return' statement"""
def cube(number):
"""after return statement we can't write a code, it won't work"""
return number ** 3, number * number * number
cube(3)
print(cube(3)) # --> (27, 27)
result = cube(4) # stores the value of cube(4)
print(result) # --> (64, 64)
|
[
"vitaliy.kachkovskiy@gmail.com"
] |
vitaliy.kachkovskiy@gmail.com
|
24936bad414d5c96ca59533a1c3ef6da0c72206d
|
5d4d4f5a0237b8584e48bb090e4171d30d0bdf81
|
/yuyu_protocol_export/ProtocolOnline/protocal/export_config.py
|
3f343547c63fde8962469da85817fd3bb4219993
|
[] |
no_license
|
dmxzxy/Love2DCrowdTest
|
b7233d61d42fdab15ba5d6962bff604e07736c0f
|
bbee735cebfcb9820922b17a49575395bce8ab50
|
refs/heads/master
| 2021-01-22T02:21:03.999914
| 2018-02-23T10:35:11
| 2018-02-23T10:35:11
| 92,353,971
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,082
|
py
|
import os
import traceback, sys
from protocal.utils import cmd_call
import zipfile
TOOL_PATH = "D:/workspace/yuyu/program/Tools/ConfigExport"
XLS_PATH = "D:/workspace/yuyu/data/yh_170931_dev(M1)"
VERSION = "1.0"
def do_export(ex_path):
the_export_path = ex_path + '/config'
cmd = 'svn update "%s"'%(XLS_PATH)
cmd_call(cmd)
if not os.path.exists(the_export_path):
os.mkdir(the_export_path)
zip_archive_path = the_export_path + '/archive/'
if not os.path.exists(zip_archive_path):
os.mkdir(zip_archive_path)
cmd = 'cd "%s" && D: && python xls2luas.py %s %s %s'%(TOOL_PATH,XLS_PATH,the_export_path,VERSION)
cmd_call(cmd)
file_zip = zipfile.ZipFile(zip_archive_path+'config_lua.zip','w',zipfile.ZIP_DEFLATED)
startdir = the_export_path + '/lua/'
for dirpath, dirnames, filenames in os.walk(startdir):
for filename in filenames:
tozipfile = os.path.relpath(os.path.join(dirpath,filename), startdir)
file_zip.write(os.path.join(dirpath,filename), tozipfile)
file_zip.close()
|
[
"xiaoyu.zhang@dena.com"
] |
xiaoyu.zhang@dena.com
|
5d248757a078c26aa4bf2e272e4583eb0f63adf8
|
6bfde8bd8fea228f574a7c819ad8a13172e225db
|
/src/chisubmit/tests/common.py
|
f7ef5bbfbd23dbc1a790478bd62637fef8dd9545
|
[] |
no_license
|
pscollins/chisubmit
|
4013bc292153319792a376a3b03a2085292dddc3
|
5fb9422d4e59eee61e4d225d6648d181dcde2de3
|
refs/heads/master
| 2021-01-17T20:25:20.381372
| 2015-04-22T22:10:00
| 2015-04-22T22:10:00
| 34,418,284
| 0
| 0
| null | 2015-04-22T22:00:06
| 2015-04-22T22:00:06
| null |
UTF-8
|
Python
| false
| false
| 22,427
|
py
|
import tempfile
import os
import json
import yaml
import sys
import colorama
import git
import functools
import unittest
import random
import string
import re
import chisubmit.client.session as session
from click.testing import CliRunner
from chisubmit.cli import chisubmit_cmd
from dateutil.parser import parse
from chisubmit.client.session import BadRequestError
colorama.init()
class ChisubmitTestClient(object):
API_PREFIX = "/api/v0/"
def __init__(self, app, user_id, api_key):
self.user_id = user_id
self.api_key = api_key
self.headers = {'content-type': 'application/json'}
if self.api_key is not None:
self.headers["CHISUBMIT-API-KEY"] = self.api_key
self.test_client = session.connect_test(app, api_key)
def get(self, resource):
return self.test_client.get(self.API_PREFIX + resource, headers = self.headers)
def post(self, resource, data):
if isinstance(data, dict):
datastr = json.dumps(data)
elif isinstance(data, basestring):
datastr = data
return self.test_client.post(self.API_PREFIX + resource, data = datastr, headers = self.headers)
def put(self, resource, data):
if isinstance(data, dict):
datastr = json.dumps(data)
elif isinstance(data, basestring):
datastr = data
return self.test_client.put(self.API_PREFIX + resource, data = datastr, headers = self.headers)
def cli_test(func=None, isolated_filesystem = True):
if func is None:
return functools.partial(cli_test, isolated_filesystem = isolated_filesystem)
def new_func(self, *args, **kwargs):
runner = CliRunner()
try:
if isolated_filesystem:
with runner.isolated_filesystem():
func(self, runner, *args, **kwargs)
else:
func(self, runner, *args, **kwargs)
except BadRequestError, bre:
bre.print_errors()
raise
return new_func
class ChisubmitCLITestClient(object):
def __init__(self, user_id, api_key, runner, course = None,
git_credentials = {}, verbose = False):
self.user_id = user_id
self.home_dir = "test-fs/home/%s" % self.user_id
self.conf_dir = "%s/.chisubmit" % (self.home_dir)
self.conf_file = self.conf_dir + "/chisubmit.conf"
self.runner = runner
self.verbose = verbose
self.course = course
git_credentials.update({"Testing" : "testing-credentials"})
os.makedirs(self.home_dir)
os.mkdir(self.conf_dir)
with open(self.conf_file, 'w') as f:
conf = {"api-url": "NONE",
"api-key": api_key,
"git-credentials":
git_credentials
}
yaml.safe_dump(conf, f, default_flow_style=False)
def run(self, subcommands, params = [], course = None, cmd=chisubmit_cmd, catch_exceptions=False, cmd_input = None):
chisubmit_args = ['--testing', '--dir', self.conf_dir, '--conf', self.conf_file]
if course is not None:
chisubmit_args += ['--course', course]
elif self.course is not None:
chisubmit_args += ['--course', self.course]
if subcommands is None:
cmd_args = []
else:
cmd_args = subcommands.split()
cmd_args += params
if self.verbose:
l = []
for ca in cmd_args:
if " " in ca:
l.append('"%s"' % ca)
else:
l.append(ca)
s = ""
s+= colorama.Style.BRIGHT + colorama.Fore.BLUE
s+= "%s$" % self.user_id
s+= colorama.Fore.WHITE
s+= " chisubmit %s" % " ".join(l)
s+= colorama.Style.RESET_ALL
print s
result = self.runner.invoke(cmd, chisubmit_args + cmd_args, catch_exceptions=catch_exceptions, input=cmd_input)
if self.verbose and len(result.output) > 0:
sys.stdout.write(result.output)
sys.stdout.flush()
return result
def create_local_git_repository(self, path):
git_path = "%s/%s" % (self.home_dir, path)
repo = git.Repo.init(git_path)
return repo, git_path
def get_local_git_repository(self, path):
git_path = "%s/%s" % (self.home_dir, path)
repo = git.Repo(git_path)
return repo, git_path
class BaseChisubmitTestCase(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(BaseChisubmitTestCase, self).__init__(*args, **kwargs)
self.git_server_connstr = "server_type=Testing;local_path=./test-fs/server"
self.git_staging_connstr = "server_type=Testing;local_path=./test-fs/staging"
self.git_server_user = None
self.git_staging_user = None
self.git_api_keys = {}
@classmethod
def setUpClass(cls):
from chisubmit.backend.webapp.api import ChisubmitAPIServer
cls.server = ChisubmitAPIServer(debug = True)
cls.db_fd, cls.db_filename = tempfile.mkstemp()
cls.server.connect_sqlite(cls.db_filename)
password_length=random.randint(50,80)
cls.auth_password = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(password_length))
cls.server.set_auth_testing(cls.auth_password)
@classmethod
def tearDownClass(cls):
os.close(cls.db_fd)
os.unlink(cls.db_filename)
def set_git_server_connstr(self, connstr):
self.git_server_connstr = connstr
def set_git_server_user(self, user):
self.git_server_user = user
def set_git_staging_connstr(self, connstr):
self.git_staging_connstr = connstr
def set_git_staging_user(self, user):
self.git_staging_user = user
def add_api_key(self, git_type, apikey):
self.git_api_keys[git_type] = apikey
def get_admin_test_client(self):
return ChisubmitTestClient(self.server.app, "admin", "admin")
def get_test_client(self, user = None):
if user is None:
return ChisubmitTestClient(self.server.app, "anonymous", None)
else:
return ChisubmitTestClient(self.server.app, user["id"], user["api_key"])
def assert_http_code(self, response, expected):
self.assertEquals(response.status_code, expected, "Expected HTTP response code %i, got %i" % (expected, response.status_code))
class ChisubmitTestCase(BaseChisubmitTestCase):
def setUp(self):
self.server.init_db()
self.server.create_admin(api_key="admin")
if hasattr(self, "FIXTURE"):
load_fixture(self.server.db, self.FIXTURE)
def tearDown(self):
self.server.db.session.remove()
self.server.db.drop_all()
class ChisubmitMultiTestCase(BaseChisubmitTestCase):
@classmethod
def setUpClass(cls):
super(ChisubmitMultiTestCase, cls).setUpClass()
cls.server.init_db()
cls.server.create_admin(api_key="admin")
if hasattr(cls, "FIXTURE"):
load_fixture(cls.server.db, cls.FIXTURE)
@classmethod
def tearDownClass(cls):
cls.server.db.session.remove()
cls.server.db.drop_all()
super(ChisubmitMultiTestCase, cls).tearDownClass()
class ChisubmitFixtureTestCase(ChisubmitMultiTestCase):
def test_get_courses(self):
for course in self.FIXTURE["courses"].values():
for instructor in course["instructors"]:
c = self.get_test_client(self.FIXTURE["users"][instructor])
response = c.get("courses")
self.assert_http_code(response, 200)
expected_ncourses = len([c for c in self.FIXTURE["courses"].values()
if instructor in c["instructors"]])
data = json.loads(response.get_data())
self.assertIn("courses", data)
self.assertEquals(len(data["courses"]), expected_ncourses)
def test_get_course(self):
for course in self.FIXTURE["courses"].values():
for instructor in course["instructors"]:
c = self.get_test_client(self.FIXTURE["users"][instructor])
response = c.get("courses/" + course["id"])
self.assert_http_code(response, 200)
data = json.loads(response.get_data())
self.assertIn("course", data)
self.assertEquals(data["course"]["name"], course["name"])
for course1 in self.FIXTURE["courses"].values():
for course2 in self.FIXTURE["courses"].values():
if course1 != course2:
for instructor in course1["instructors"]:
c = self.get_test_client(self.FIXTURE["users"][instructor])
response = c.get("courses/" + course2["id"])
self.assert_http_code(response, 404)
def load_fixture(db, fixture):
from chisubmit.backend.webapp.api.users.models import User
from chisubmit.backend.webapp.api.assignments.models import Assignment
from chisubmit.backend.webapp.api.courses.models import Course,\
CoursesInstructors, CoursesGraders, CoursesStudents
user_objs = {}
for u_id, user in fixture["users"].items():
u = User(first_name=user["first_name"],
last_name=user["last_name"],
id=user["id"],
api_key=user["api_key"])
user_objs[u_id] = u
db.session.add(u)
for c_id, course in fixture["courses"].items():
c = Course(id = course["id"],
name = course["name"])
db.session.add(c)
if course.has_key("instructors"):
for instructor in course["instructors"]:
o = user_objs[instructor]
db.session.add(CoursesInstructors(instructor_id = o.id,
course_id = c.id))
if course.has_key("graders"):
for grader in course["graders"]:
o = user_objs[grader]
db.session.add(CoursesGraders(grader_id = o.id,
course_id = c.id))
if course.has_key("students"):
for student in course["students"]:
o = user_objs[student]
db.session.add(CoursesStudents(student_id = o.id,
course_id = c.id))
if course.has_key("assignments"):
for assignment in course["assignments"].values():
db.session.add(Assignment(id = assignment["id"],
name = assignment["name"],
deadline = parse(assignment["deadline"]),
course_id = c.id))
db.session.commit()
class ChisubmitIntegrationTestCase(ChisubmitTestCase):
def create_user(self, admin_runner, user_id):
from chisubmit.backend.webapp.api.users.models import User
fname = "f_" + user_id
lname = "l_" + user_id
email = user_id + "@example.org"
result = admin_runner.run("admin user add", [user_id, fname, lname, email])
self.assertEquals(result.exit_code, 0)
user = User.from_id(user_id)
self.assertIsNotNone(user)
self.assertEquals(user.id, user_id)
self.assertEquals(user.first_name, fname)
self.assertEquals(user.last_name, lname)
self.assertEquals(user.email, email)
# TODO: We manually set the API key here, since the CLI
# and the server are not completely set up for fetching
# API keys yet.
user.api_key = user_id
self.server.db.session.add(user)
self.server.db.session.commit()
def create_clients(self, runner, course_id, admin_id, instructor_ids, grader_ids, student_ids):
admin = ChisubmitCLITestClient(admin_id, admin_id, runner, git_credentials=self.git_api_keys, verbose = True)
instructors = []
for instructor_id in instructor_ids:
instructors.append(ChisubmitCLITestClient(instructor_id, instructor_id, runner, git_credentials=self.git_api_keys, verbose = True, course = course_id))
graders = []
for grader_id in grader_ids:
graders.append(ChisubmitCLITestClient(grader_id, grader_id, runner, git_credentials=self.git_api_keys, verbose = True, course = course_id))
students = []
for student_id in student_ids:
students.append(ChisubmitCLITestClient(student_id, student_id, runner, git_credentials=self.git_api_keys, verbose = True, course = course_id))
return admin, instructors, graders, students
def create_users(self, admin, user_ids):
for user_id in user_ids:
self.create_user(admin, user_id)
def create_course(self, admin, course_id, course_name):
from chisubmit.backend.webapp.api.courses.models import Course
result = admin.run("admin course add", [course_id, course_name])
self.assertEquals(result.exit_code, 0)
course = Course.from_id(course_id)
self.assertIsNotNone(course)
self.assertEquals(course.name, course_name)
result = admin.run("admin course list")
self.assertEquals(result.exit_code, 0)
self.assertIn(course_id, result.output)
self.assertIn(course_name, result.output)
git_server_connstr = self.git_server_connstr
git_staging_connstr = self.git_staging_connstr
result = admin.run("admin course set-option %s git-server-connstr %s" % (course_id, git_server_connstr))
self.assertEquals(result.exit_code, 0)
result = admin.run("admin course set-option %s git-staging-connstr %s" % (course_id, git_staging_connstr))
self.assertEquals(result.exit_code, 0)
course = Course.from_id(course_id)
self.assertIn("git-server-connstr", course.options)
self.assertIn("git-staging-connstr", course.options)
self.assertEquals(course.options["git-server-connstr"], git_server_connstr)
self.assertEquals(course.options["git-staging-connstr"], git_staging_connstr)
result = admin.run("admin course unsetup-repo %s" % (course_id))
self.assertEquals(result.exit_code, 0)
result = admin.run("admin course setup-repo %s" % (course_id))
self.assertEquals(result.exit_code, 0)
result = admin.run("admin course unsetup-repo %s --staging" % (course_id))
self.assertEquals(result.exit_code, 0)
result = admin.run("admin course setup-repo %s --staging" % (course_id))
self.assertEquals(result.exit_code, 0)
def add_users_to_course(self, admin, course_id, instructors, graders, students):
from chisubmit.backend.webapp.api.courses.models import CoursesStudents
for instructor in instructors:
result = admin.run("admin course add-instructor %s %s" % (course_id, instructor.user_id))
self.assertEquals(result.exit_code, 0)
for grader in graders:
result = admin.run("admin course add-grader %s %s" % (course_id, grader.user_id))
self.assertEquals(result.exit_code, 0)
for student in students:
result = admin.run("admin course add-student %s %s" % (course_id, student.user_id))
self.assertEquals(result.exit_code, 0)
for instructor in instructors:
if self.git_server_user is None:
git_username = "git-" + instructors[0].user_id
else:
git_username = self.git_server_user
result = instructors[0].run("instructor user set-repo-option",
["instructor", instructors[0].user_id, "git-username", git_username])
self.assertEquals(result.exit_code, 0)
for grader in graders:
if self.git_server_user is None:
git_username = "git-" + graders[0].user_id
else:
git_username = self.git_server_user
result = instructors[0].run("instructor user set-repo-option",
["grader", graders[0].user_id, "git-username", git_username])
self.assertEquals(result.exit_code, 0)
result = admin.run("admin course update-repo-access", [course_id])
self.assertEquals(result.exit_code, 0)
result = admin.run("admin course update-repo-access", [course_id, "--staging"])
self.assertEquals(result.exit_code, 0)
for student in students:
if self.git_server_user is None:
git_username = "git-" + student.user_id
else:
git_username = self.git_server_user
result = student.run("student course set-git-username", [git_username])
self.assertEquals(result.exit_code, 0)
course_student = CoursesStudents.query.filter_by(
course_id=course_id).filter_by(
student_id=student.user_id).first()
self.assertIn("git-username", course_student.repo_info)
self.assertEquals(course_student.repo_info["git-username"], git_username)
def create_team_repos(self, admin, course_id, teams, students_team):
team_git_paths = []
team_git_repos = []
team_commits = []
for team, students in zip(teams, students_team):
result = admin.run("admin course team-repo-remove", [course_id, team, "--ignore-non-existing"])
self.assertEquals(result.exit_code, 0)
result = admin.run("admin course team-repo-remove", ["--staging", course_id, team, "--ignore-non-existing"])
self.assertEquals(result.exit_code, 0)
result = admin.run("admin course team-repo-create", [course_id, team, "--public"])
self.assertEquals(result.exit_code, 0)
result = admin.run("admin course team-repo-create", ["--staging", course_id, team, "--public"])
self.assertEquals(result.exit_code, 0)
result = students[0].run("student team repo-check", [team])
self.assertEquals(result.exit_code, 0)
r = re.findall(r"^Repository URL: (.*)$", result.output, flags=re.MULTILINE)
self.assertEquals(len(r), 1, "student team repo-check didn't produce the expected output")
repo_url = r[0]
team_git_repo, team_git_path = students[0].create_local_git_repository(team)
team_remote = team_git_repo.create_remote("origin", repo_url)
team_git_repos.append(team_git_repo)
team_git_paths.append(team_git_path)
commits = []
files = ["foo", "bar", "baz"]
for f in files:
open("%s/%s" % (team_git_path, f), "w").close()
team_git_repo.index.add(files)
team_git_repo.index.commit("First commit of %s" % team)
commits.append(team_git_repo.heads.master.commit)
team_remote.push("master")
f = open("%s/foo" % (team_git_path), "w")
f.write("Hello, team1!")
f.close()
team_git_repo.index.add(["foo"])
team_git_repo.index.commit("Second commit of %s" % team)
commits.append(team_git_repo.heads.master.commit)
team_remote.push("master")
team_commits.append(commits)
for team1, students1 in zip(teams, students_team):
for team2, students2 in zip(teams, students_team):
if team1 != team2:
result = students1[0].run("student team repo-check", [team2])
self.assertNotEquals(result.exit_code, 0)
result = students2[0].run("student team repo-check", [team1])
self.assertNotEquals(result.exit_code, 0)
return team_git_paths, team_git_repos, team_commits
def register_team(self, student_clients, team_name, assignment_id, course_id):
from chisubmit.backend.webapp.api.users.models import User
from chisubmit.backend.webapp.api.teams.models import Team, StudentsTeams
for s in student_clients:
partners = [s2 for s2 in student_clients if s2!=s]
partner_args = []
for p in partners:
partner_args += ["--partner", p.user_id]
s.run("student assignment register",
[ assignment_id, "--team-name", team_name] + partner_args)
s.run("student team show", [team_name])
students_in_team = [User.from_id(s.user_id) for s in student_clients]
ts = Team.find_teams_with_students(course_id, students_in_team)
self.assertGreaterEqual(len(ts), 1)
self.assertIn(team_name, [t.id for t in ts])
team = [t for t in ts if t.id == team_name]
self.assertEqual(len(team), 1)
t = team[0]
self.assertEquals(t.id, team_name)
self.assertListEqual(sorted([s.id for s in students_in_team]),
sorted([s.id for s in t.students]))
for st in t.students_teams:
self.assertEquals(st.status, StudentsTeams.STATUS_CONFIRMED)
|
[
"borja@cs.uchicago.edu"
] |
borja@cs.uchicago.edu
|
14030f6e7871f73633cf3167b5313582beaaa3fe
|
c55ed318cbe079d62def7611948a0358c381ac9b
|
/src/asteroids_agents.py
|
bf1303348213860f05ba5c739377cab870c4f2d0
|
[] |
no_license
|
TheCahyag/asteroids_ai
|
66edb8f65676be6b048248790bd58fc23f39e339
|
2170d3cf7742d6c3f0adae469f9ef24c2df373cd
|
refs/heads/master
| 2022-02-24T20:58:58.951594
| 2019-10-18T06:37:31
| 2019-10-18T06:37:31
| 207,828,040
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,097
|
py
|
import argparse
import random
import gym
from gym import logger
from agents.direction_minimize_agent import DegreeMinimizing
from agents.random_agent import RandomAgent
from agents.distance_minimize_agent import DistanceMinimizing
# Structuring the arguments
parser = argparse.ArgumentParser(description='Main program to run Asteroids using an agent to play. This easily '
'allows switching agents and gives the ability to execute multiple '
'Asteroids runs.\n\n'
'Example: asteroids_agents.py random --runs 5\n\t'
' Run the random agent for 5 games\n'
'Example: asteroids_agents.py shooting\n\t'
' Run the shooting agent for a single game',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog='Programmed by Brandon Bires-Navel (brn5915@rit.edu)')
parser.add_argument('agent', metavar='agent', type=str, choices=['random', 'dis-min', 'deg-min'],
help='Specify the agent you want to use to play Asteroids.... '
'Available Agents: random, dis-min, deg-min')
parser.add_argument('--runs', dest='runs', metavar='N', type=int, nargs=1, default=1,
help='Number of games to play (default: 1)')
parser.add_argument('--seed', dest='seed', metavar='S', type=int, nargs=1, default=random.randint(1, 1000000),
help='Seed to set for the environment (default: random integer)')
if __name__ == '__main__':
logger.set_level(logger.INFO)
env = gym.make('AsteroidsNoFrameskip-v4')
# Select which agent to use based on the command line arguments
agent = None
asteroids_args = parser.parse_args()
agent_arg = asteroids_args.agent
if agent_arg == 'random':
agent = RandomAgent(env.action_space)
elif agent_arg == 'dis-min':
agent = DistanceMinimizing(env.action_space)
elif agent_arg == 'deg-min':
agent = DegreeMinimizing(env.action_space)
seed = asteroids_args.seed if isinstance(asteroids_args.seed, int) else asteroids_args.seed[0]
runs = asteroids_args.runs if isinstance(asteroids_args.runs, int) else asteroids_args.runs[0]
env.seed(seed)
total_runs = 0
total_score = 0
while total_runs < runs:
reward = 0
done = False
score = 0
special_data = {'ale.lives': 3}
ob = env.reset()
i = 0
while not done:
action = agent.act(ob, reward, done)
ob, reward, done, x = env.step(action)
score += reward
# env.render()
i += 1
print(f'Asteroids score [{i}]: {score}')
total_runs += 1
total_score += score
print(f'Average score across {total_runs} runs: {total_score / total_runs}')
# Close the env and write monitor result info to disk
env.close()
|
[
"brandonnavel@outlook.com"
] |
brandonnavel@outlook.com
|
5feb19918e49555e534516f2d8cf4659ad6e859b
|
e05a64a23dcd2c09294690b54ac24d250c5f01af
|
/Gilad And Dennis Projects/Backend/ShopSite/wsgi.py
|
a362fdb3ee7113e3e5c1f5867b740c5592572c1b
|
[] |
no_license
|
yosinovo1/CoronaTime
|
981dad71a163224af32b1b9de1c2e1120a0365bc
|
693409787b3738fb4489ac0b2e25945a07796f4d
|
refs/heads/master
| 2022-12-10T02:49:43.960104
| 2020-07-30T15:33:50
| 2020-07-30T15:33:50
| 250,558,445
| 0
| 1
| null | 2022-12-08T09:28:44
| 2020-03-27T14:38:52
|
JavaScript
|
UTF-8
|
Python
| false
| false
| 393
|
py
|
"""
WSGI config for ShopSite project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ShopSite.settings')
application = get_wsgi_application()
|
[
"denisgerman11@gmail.com"
] |
denisgerman11@gmail.com
|
a42943dfe2d2b8559fa581e341df9f227132462b
|
41298e9f0e3b29f62a52d00723bfb489697f5a14
|
/tests/pgrep/examples/bash.py
|
ef8b81bfe03a09ddae5d98eb6266faf8cce7c4fc
|
[
"Unlicense"
] |
permissive
|
andrewp-as-is/pgrep.py
|
392dcb817a30cb43f9137d7cd36b41e15c2def98
|
7d9eecf3f5a40bd1e8c2bea8d576f12fc9c5e6e8
|
refs/heads/master
| 2021-06-24T22:28:06.875285
| 2020-12-03T21:11:25
| 2020-12-03T21:11:25
| 151,134,453
| 3
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 73
|
py
|
#!/usr/bin/env python
import pgrep
pid = pgrep.pgrep("bash")
print(pid)
|
[
"russianidiot.github@gmail.com"
] |
russianidiot.github@gmail.com
|
ed268c63045a09c40075d568cba27181e86c99ee
|
57d0c4c5805b306c3d434705371196b772bb0fc8
|
/hello.py
|
2dd077c2b2a91bbf43750c8250d3748899772c6a
|
[] |
no_license
|
BushLands/Stepik_web_project
|
c14e0dfc028bcfe736818b6dcc01447818d3d551
|
53dfe17c78bdae5f42bc5e4f023ecc69e56fc61e
|
refs/heads/master
| 2020-11-27T11:00:29.888739
| 2020-02-28T11:50:41
| 2020-02-28T11:50:41
| 229,413,131
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 251
|
py
|
def wsgi_app(environ, start_responce):
headers = [('content-type', 'text/plain')]
query = environ['QUERY_STRING']
body = '\n'.join(query[query.find('?')+1:].split('&').encode('utf-8'))
status = '200 OK'
start_responce(status, headers)
yield body
|
[
"havron7@gmail.com"
] |
havron7@gmail.com
|
27a952463ceaa02cb6db6f5f80cf0c74e6e3d1c2
|
f23572d0c916ed3325480de2daca15d9d16f9186
|
/string/dict_trie.py
|
3875653da5a32507cd7962d9b5e7c1d365e6894f
|
[] |
no_license
|
iCodeIN/data_structures
|
08067aa661ea1dac01c70ac5a3e53f5e146fc82c
|
bbd01fb1785827c64ea28636352c6e0d7c8d62f4
|
refs/heads/master
| 2023-02-21T06:40:05.336522
| 2021-01-22T05:41:27
| 2021-01-22T05:41:27
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,617
|
py
|
class WordDictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
self.trie = {}
def addWord(self, word: str) -> None:
"""
Adds a word into the data structure.
"""
node = self.trie
for ch in word:
if not ch in node:
node[ch] = {}
node = node[ch]
node['$'] = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any letter.
"""
def search_in_node(word, node) -> bool:
for i, ch in enumerate(word):
if not ch in node:
# if the current character is '.'
# check all possible nodes at this level
if ch == '.':
for x in node:
if x != '$' and search_in_node(word[i + 1:], node[x]):
return True
# if no nodes lead to answer
# or the current character != '.'
return False
# if the character is found
# go down to the next level in trie
else:
node = node[ch]
return '$' in node
return search_in_node(word, self.trie)
if __name__=='__main__':
x=WordDictionary()
x.addWord("bad")
x.addWord("mad")
x.addWord("pad")
print(x.search("bad"))
print(x.search(".ad"))
print(x.search("b.."))
|
[
"chosun41"
] |
chosun41
|
dfe29c1001676b28347bcd5be4f668ff6c7b712f
|
e2081f2f873825a3cc8b529614eb784f5cf5e8c5
|
/graphvalidtree1.py
|
bdec503e26bfa97e97d8670789315e093cece028
|
[] |
no_license
|
yilinanyu/Leetcode-with-Python
|
17b454058c673381dbafa5a2a154c4e84b449399
|
a55d2a3e383f858477170effbf8f6454e5dfd218
|
refs/heads/master
| 2021-01-21T04:55:31.025194
| 2016-07-11T20:10:18
| 2016-07-11T20:10:18
| 36,630,923
| 5
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,255
|
py
|
class UnionFind:
def __init__(self, n):
self.count = n
self.father = {}
for i in range(n):
self.father[i] = i
def compressed_find(self, x):
parent = self.father.get(x)
while parent != self.father.get(parent):
parent = self.father.get(parent)
temp = -1
fa = self.father.get(x)
while fa != self.father.get(fa):
temp = self.father.get(fa)
self.father[fa] = parent
fa = temp
return parent
def union(self, x, y):
fa_x = self.compressed_find(x)
fa_y = self.compressed_find(y)
if fa_x != fa_y:
self.father[fa_x] = fa_y
self.count -= 1
return True
else:
return False
class Solution(object):
def validTree(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: bool
"""
if edges == None:
return False
uf = UnionFind(n)
for e in edges:
flag = uf.union(e[0], e[1])
if flag == False:
return False
return uf.count == 1
|
[
"ly783@nyu.edu"
] |
ly783@nyu.edu
|
ee52229a08cf7edc6ccbcdf424f672d78d06cf6b
|
0037517766543c75c9f067666b9225afcc482632
|
/slack_minimizer.py
|
f4a5ebea95c57a882524042b08d0fcd084cd1199
|
[
"Apache-2.0"
] |
permissive
|
b-akshay/marvin
|
9b73917732d88595cc99d03c00dbe6ad76dae5fd
|
5d8d49d3973190c84f442816f949be00a6e64802
|
refs/heads/master
| 2021-06-06T18:51:34.132811
| 2016-10-09T06:22:55
| 2016-10-09T06:22:55
| 59,709,499
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 16,202
|
py
|
import numpy as np
import scipy as sp
import sklearn.metrics
import muffled_utils
import time
class SlackMinimizer(object):
"""
A class that aggregates a given ensemble of specialist classifiers, as in the paper::
"Scalable semi-supervised aggregation of classifiers," Balsubramani and Freund, NIPS 2015.
Attributes:
unlabeled_set: Matrix of unlabeled data. {# examples} rows and {# classifiers} cols.
b_vector: Vector of label correlation bounds for the ensemble classifiers.
weights: Weight vector for the ensemble classifiers.
unlabeled_labels: Vector containing the labels of the unlabeled data.
Used only for diagnostic info, not for learning.
holdout_set: As unlabeled_set, but with the holdout dataset. This dataset
is not used in the minimization. It has often been used to estimate b_vector.
holdout_labels: Vector containing the labels of the holdout data.
validation_set: As unlabeled_set, but with a validation dataset.
This is held out from the entire learning procedure and is used to measure performance.
If not specified, it defaults to holdout_set.
validation_labels: Vector containing the labels of the validation data.
If not specified, it defaults to holdout_labels.
All datasets are assumed to fit in memory. Since the holdout set may have been used to estimate
b_vector, the learned classifier may overfit on it. Comparing holdout performance to validation
performance can be used to detect overfitting.
"""
# TODO(Akshay): Allow unlabeled data to be accessed out of core.
def __init__(self, b_vector, unlabeled_set, holdout_set, holdout_labels,
unlabeled_labels=None, validation_set=None, validation_labels=None,
weights=None, soft_threshold_epsilon=0.0):
self.unlabeled_set = unlabeled_set
self.b_vector = b_vector
self.unlabeled_labels = unlabeled_labels
self.holdout_set = holdout_set
self.holdout_labels = holdout_labels
if validation_set is None:
self.validation_set = holdout_set
self.validation_labels = holdout_labels
else:
self.validation_set = validation_set
self.validation_labels = validation_labels
# By default, initialize weights to a random vector, and scale it so unlabeled data
# have an average score (<x, weights> value) of 1.
if weights is None:
weights = np.random.randn(self.unlabeled_set.shape[1])
scoresunl = self.unlabeled_set.dot(weights)
meanscore = 1.0 / np.mean(np.abs(scoresunl))
self.weights = meanscore * weights
self._scoresunl = meanscore * scoresunl
else:
self.weights = np.array(weights)
self._scoresunl = self.unlabeled_set.dot(self.weights)
# For soft thresholding ([weighted] L1 regularization), can be a scalar or a vector
self._soft_thresh_eps = soft_threshold_epsilon
def calc_grad(self, indices_this_iteration=None):
"""
Calculate gradient of slack function using some subset of unlabeled data.
Args:
indices_this_iteration: list of indices of unlabeled data to use to
estimate the gradient. Defaults to using all unlabeled data.
Returns:
Estimated gradient of the slack function: a vector of floats.
"""
if indices_this_iteration is None:
indices_this_iteration = range(self.unlabeled_set.shape[0])
unl_set = self.unlabeled_set[indices_this_iteration, :]
return -self.b_vector + (1.0/len(indices_this_iteration)) * unl_set.transpose().dot(
self._hallucinate_labels(scores=self._scoresunl[indices_this_iteration]))
def predict(self, dataset, binary_preds=False):
"""
Predict labels on a dataset using current weights over ensemble.
Args:
dataset: Matrix of specialist predictions on data. Dimensions: {# examples} rows,
{# classifiers} columns. E.g. the matrix generated by CompositeFeature.predictions(...).
binary_preds: Optional Boolean, specifies whether the predictions are randomized in {-1,1}.
Returns:
A vector representing the muffled predictions on the dataset, using
the current weight vector (self.weights).
"""
preds = np.clip(dataset.dot(self.weights), -1, 1)
# preds = 2.0*scipy.special.expit(dataset.dot(self.weights)) - 1
if not binary_preds:
return preds
else:
return 2.0 * np.random.binomial(1, 0.5 * (1.0+preds)) - 1.0
def compute_AUC(self, dataset=None, labels=None, binary_preds=False):
""" Compute AUC of the aggregated predictions on a dataset using current weights. """
if dataset is None:
dataset = self.validation_set
labels = self.validation_labels
return sklearn.metrics.roc_auc_score(labels, self.predict(dataset, binary_preds=binary_preds))
def sgd(self, duration, linesearch=True, linesearch_tol=0.00005,
unl_stride_size=0, logging_interval=10):
"""
Run minibatch stochastic gradient descent to minimize the slack function with the unlabeled data.
Args:
duration: int; Number of iterations to run.
linesearch: optional Boolean; True iff line search is to be used to find
the step size, otherwise a step size schedule of t^{-0.5} is used.
linesearch_tol: optional float; Tolerance used to terminate line search procedure.
unl_stride_size: optional int; The number of unlabeled data per minibatch.
Defaults to 0, which indicates that the whole unlabeled set should be
used each minibatch.
logging_interval: optional int; Interval between timesteps on which statistics are computed.
0 indicates to not log at all.
Returns:
List of 6-tuples of floats, giving performance statistics at each iteration.
The first two elements of each tuple give the error and AUC on the unlabeled data,
the next two on the holdout data, and the last two on the validation data.
If labels for any are not available, returns error/AUC of 1.0/0.0.
"""
inittime = time.time()
statauc = []
# Set max step size used to start line search; exponential moving average
# used because step sizes change by several orders of magnitude over a typical run.
EMA_stepsize = 0.2
beta = 0.5 # exponential moving average decay parameter
if unl_stride_size == 0:
unl_stride_size = self.unlabeled_set.shape[0]
time_to_start = 5
for iterct in range(duration):
unl_indices_this_iteration = np.random.choice(
self.unlabeled_set.shape[0], unl_stride_size, replace=False)
grad = self.calc_grad(indices_this_iteration=unl_indices_this_iteration)
# TODO: Can also add an option to use sp.optimize.brent instead of our custom golden section search implementation.
if linesearch:
max_stepsize = 2*EMA_stepsize # Increase each iteration to allow the allowed step size to increase.
stepsize = muffled_utils.golden_section_search(
self._proj_slack_func(-grad), 0, max_stepsize, tol=linesearch_tol)
# stepsize2 = sp.optimize.brent(self._proj_slack_func(-grad), tol=linesearch_tol)
EMA_stepsize = beta*EMA_stepsize + (1-beta)*stepsize
else:
stepsize = 1.0*np.power(iterct + time_to_start, -0.5) # Standard for SGD on convex functions
self.weights += -stepsize * grad
if np.max(self._soft_thresh_eps) == 0.0:
self.weights = np.maximum(self.weights, 0.0) # Project to positive orthant
else: # if we're using L1 regularization instead, do soft thresholding.
wttmp = np.maximum(np.abs(self.weights) - self._soft_thresh_eps, 0.0)
self.weights = np.multiply(wttmp, np.sign(self.weights))
self._scoresunl = self.unlabeled_set.dot(self.weights)
if bool(logging_interval and (iterct%logging_interval == 0)):
preds_unl = np.clip(self._scoresunl, -1, 1)
if self.unlabeled_labels is not None:
alg_loss_unl = 1.0 - muffled_utils.accuracy_calc(self.unlabeled_labels, preds_unl)
alg_auc_unl = sklearn.metrics.roc_auc_score(self.unlabeled_labels, preds_unl)
else:
alg_loss_unl = 1.0
alg_auc_unl = 0.0
preds_out = self.predict(self.holdout_set)
alg_loss_out = 1.0 - muffled_utils.accuracy_calc(self.holdout_labels, preds_out)
alg_auc_out = sklearn.metrics.roc_auc_score(self.holdout_labels, preds_out)
preds_val = self.predict(self.validation_set)
alg_loss_val = 1.0 - muffled_utils.accuracy_calc(self.validation_labels, preds_val)
alg_auc_val = sklearn.metrics.roc_auc_score(self.validation_labels, preds_val)
# vect_preds_out = np.array([[0.5*(1-x), 0.5*(1+x)] for x in logloss_preds_out])
# logloss_out = sklearn.metrics.log_loss(self.holdout_labels, vect_preds_out)
print 'After iteration ' + str(iterct) + ':\t Time = ' + str(time.time() - inittime)
print('Holdout: \t Error = ' + str(alg_loss_out) + '\t AUC: ' + str(alg_auc_out))
print('Validation: \t Error = ' + str(alg_loss_val) + '\t AUC: ' + str(alg_auc_val))
statauc.append(
(alg_loss_unl, alg_auc_unl, alg_loss_out, alg_auc_out, alg_loss_val, alg_auc_val))
return statauc
def _hallucinate_labels(self, scores=None):
"""
Calculate hallucinated labels for dataset using given scores,
which default to current unlabeled scores. Treats borderline labels as clipped,
to avoid problems of zero gradient upon initialization.
We also set labels on hedged examples to zero instead of random fair
binary coin flips, to reduce variance and improve performance.
"""
# TODO(Akshay): Implement different labels for different losses.
if scores is None:
scores = self._scoresunl
ghlabels = np.sign(scores)
ghlabels[np.where(np.abs(scores) < 1)] = 0
# if self.logloss: ghlabels = 2.0*scipy.special.expit(scores) - 1
return ghlabels
def _proj_slack_func(self, search_dir):
"""
Given a line search direction from the current weight vector, returns a function (closure) that
projects the slack function in that direction.
"""
def _toret(alpha):
scores = self._scoresunl + self.unlabeled_set.dot(alpha * search_dir)
return -np.dot(self.b_vector, self.weights + alpha * search_dir) + np.mean(np.maximum(np.abs(scores), 1.0))
return _toret
"""
A basic working example:
(*) Subsamples an amount of labeled and unlabeled data at random from an input file.
(*) Uses 1/4 of the labeled data to train a random forest with 100 trees, and the other 3/4 to estimate
the b_vector over the random forest trees (without deriving specialists).
(*) Minimizes the slack function over the 100 trees.
"""
if __name__ == "__main__":
import time, csv, sys
import composite_feature
from scipy.sparse import csr_matrix
from sklearn.ensemble import RandomForestClassifier
import argparse
parser = argparse.ArgumentParser(
description="""
Minimizes the slack function, given an ensemble of classifiers from which to derive specialists.
Contact: Akshay Balsubramani <abalsubr@ucsd.edu>
""")
parser.add_argument('labeled_file', help='CSV file from which to read data.')
parser.add_argument('total_labels', type=int,
help='Number of labeled data in total (to be divided between training set for the ensemble and holdout for calculating b).')
parser.add_argument('unlabeled_set_size', type=int, help='Number of unlabeled data.')
parser.add_argument('--failure_prob', '-f', type=float, default=0.005,
help='Failure probability for calculating ensemble error bounds (i.e., Wilson intervals for label correlations).')
parser.add_argument('--num_base_classifiers', '-b', type=int, default=20,
help='Number of trees in the random forest.')
parser.add_argument('--num_trials', '-n', type=int, dest='num_MCtrials', default=1,
help='Number of Monte Carlo trials of the experiment to run.')
parser.add_argument('--k', '-k', type=int, default=0,
help="""Approximate number of derived specialists to generate from each base classifier.
More precisely, the best k (by Wilson error bound) are taken, along with the base classifier if it is not already
one of the best k. See CompositeFeature.predictions(...) docs for more details. Defaults to 0.""")
parser.add_argument('--validation_set_size', '-v', type=int, default=1000,
help='Number of validation data.')
parser.add_argument('--sgd_duration', '-d', type=int, default=30,
help='Number of iterations to run the optimization (stochastic gradient descent).')
parser.add_argument('--tree_node_specialists', action='store_true',
help='Use internal nodes of decision trees as specialists.')
args = parser.parse_args()
root = 'muf_ssl'
labeled_set_size = int(args.total_labels*0.25)
holdout_set_size = args.total_labels - labeled_set_size
logname_auc = 'logs/' + root + '_' + str(args.total_labels) + '_tailprob' + str(args.failure_prob) + '_auc.csv'
logname_err = 'logs/' + root + '_' + str(args.total_labels) + '_tailprob' + str(args.failure_prob) + '_err.csv'
inittime = time.time()
with open(logname_auc, 'a') as fo_auc, open(logname_err, 'a') as fo_err:
writer_auc = csv.writer(fo_auc)
writer_err = csv.writer(fo_err)
for mctrial in range(args.num_MCtrials):
print 'Trial ' + str(mctrial) + ':\tTime = ' + str(time.time() - inittime)
(x_train, y_train, x_unl, y_unl, x_out, y_out, x_validate, y_validate) = muffled_utils.read_random_data_from_csv(
args.labeled_file, labeled_set_size, args.unlabeled_set_size, holdout_set_size, args.validation_set_size)
print('Data loaded. \tTime = ' + str(time.time() - inittime))
rf = RandomForestClassifier(n_estimators=args.num_base_classifiers, n_jobs=-1)
rf.fit(x_train, y_train)
print('Random forest trained. \tTime = ' + str(time.time() - inittime))
(b_vector, allfeats_out, allfeats_unl, allfeats_val) = composite_feature.predict_multiple(
rf.estimators_, x_out, x_unl, x_validate, y_out=y_out, k=args.k,
failure_prob=args.failure_prob, from_sklearn_rf=True, use_tree_partition=args.tree_node_specialists)
print ('Featurizing done. \tTime = ' + str(time.time() - inittime))
gradh = SlackMinimizer(
b_vector, allfeats_unl, allfeats_out, y_out, unlabeled_labels=y_unl,
validation_set=allfeats_val, validation_labels=y_validate)
statauc = gradh.sgd(args.sgd_duration, unl_stride_size=0, logging_interval=5)
print 'Final validation AUC:\t ' + str(gradh.compute_AUC())
print 'Random forest AUC:\t ' + str(sklearn.metrics.roc_auc_score(
y_validate, -1.0 + 2*rf.predict_proba(x_validate)[:, 1]))
print len(b_vector), np.sum(gradh.weights)
_, _, _, _, cl_err, cl_auc = zip(*statauc)
# print cl_auc, '\n', cl_err
writer_auc.writerow(cl_auc)
writer_err.writerow(cl_err)
print 'Written to files:\t' + logname_auc + ',\t ' + logname_err
|
[
"abalsubr@ucsd.edu"
] |
abalsubr@ucsd.edu
|
f33620b55e9f14413adbe93137c9136469b009c9
|
a117815a45f6864ef31185551c069211ee63ed95
|
/bot/deactivated_plugins_2/TopicQueuePlugin.py
|
a50e392e65ba5d6832df2648d4e7bc8b8495d774
|
[] |
no_license
|
hheimbuerger/rtbot
|
e6f4e9488febb740725e1d1ec641a3de60264b67
|
5a972b971947ec875e2079696c98802276b943ed
|
refs/heads/master
| 2021-01-16T20:42:24.047256
| 2017-08-24T22:07:43
| 2017-08-24T22:11:23
| 61,387,905
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,506
|
py
|
import collections
import re
class TopicQueuePlugin:
def __init__(self, pluginInterface):
self.pluginInterfaceReference = pluginInterface
self.topicQueue = collections.deque()
def getVersionInformation(self):
return("$Id: BugReplyPlugin.py 260 2006-05-23 22:37:56Z Ksero $")
def onChannelMessage(self, irclib, sender, message):
if(len(message.split()) >= 1):
command = message.split()[0]
if((command == "!push") and (len(message.split()) >= 2)):
topic = message.split(None, 1)[1]
#===============================================================================
# reResult = re.compile("\((.*?)\)^").search(topic.strip())
# if(reResult):
# try:
# users = reResult.group(1).split(", ")
#
# except:
# irclib.sendChannelMessage("One or more of the users are invalid.")
#===============================================================================
self.topicQueue.append(topic)
irclib.sendChannelMessage("The topic '%s' has been queued." % (topic))
elif(command == "!peek"):
if(len(self.topicQueue) > 0):
irclib.sendChannelMessage("The next topic is '%s'." % (self.topicQueue[0]))
else:
irclib.sendChannelMessage("There are no queued topics.")
elif(command == "!listtopics"):
topics
elif(command == "!pop"):
if(len(self.topicQueue) > 0):
irclib.sendChannelMessage("The topic is now '%s'." % (self.topicQueue.popleft()))
else:
irclib.sendChannelMessage("There are no queued topics.")
if __name__ == "__main__":
class PluginInterfaceMock:
def getPlugin(self, name):
return(AuthPluginMock())
class IrcLibMock:
nickname = "RTBot"
def sendPrivateMessage(self, target, text):
print text
def sendChannelMessage(self, text):
print text
def sendChannelEmote(self, text):
print "* %s" % (text)
queue = TopicQueuePlugin(PluginInterfaceMock())
queue.onChannelMessage(IrcLibMock(), "source", "!push abc")
queue.onChannelMessage(IrcLibMock(), "source", "!push def ghi")
queue.onChannelMessage(IrcLibMock(), "source", "!peek")
queue.onChannelMessage(IrcLibMock(), "source", "!pop")
queue.onChannelMessage(IrcLibMock(), "source", "!pop")
queue.onChannelMessage(IrcLibMock(), "source", "!peek")
queue.onChannelMessage(IrcLibMock(), "source", "!pop")
|
[
"henrik@heimbuerger.de"
] |
henrik@heimbuerger.de
|
40dbf366cf65429d225d5fa2c8b3982d35434bfe
|
836d5f7190f6b4503e758c87c71598f18fdfce14
|
/6-İleri-Seviye-Veri-Yapıları/Tuple-Demet-Veri-Tipi.py
|
aff1d7c73e340305fa440ef5d010304b3e2c3e47
|
[] |
no_license
|
S-Oktay-Bicici/PYTHON-PROGRAMMING
|
cf452723fd3e7e8ec2aadc7980208d747c502e9a
|
22e864f89544249d6309d6f4570a4104bf47346b
|
refs/heads/main
| 2021-11-30T00:19:21.158084
| 2021-11-16T15:44:29
| 2021-11-16T15:44:29
| 316,716,147
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,238
|
py
|
demet = ("ocak","şubat",29,"mart")
print(demet)
print(type(demet))
#################################################################
demet = "ocak"
print(type(demet))
demet = "ocak",
print(type(demet))
####################################################################
demet = ("ocak","şubat","mart","nisan","mayıs","haziran",
"temmuz","ağustos","eylül","ekim","kasım","aralık")
print(demet[2])
######################################################################
demet = ("ocak","şubat","mart","nisan","mayıs","haziran",
"temmuz","ağustos","eylül","ekim","kasım","aralık")
print(demet[2:9])
#####################################################################
demet = ("ocak","şubat","mart","nisan","mayıs","haziran",
"temmuz","ağustos","eylül","ekim","kasım","aralık")
print(demet[1:12:3])
#####################################################################
demet = ("ocak","şubat","mart","nisan","mayıs","haziran",
"temmuz","ağustos","eylül","ekim","kasım","aralık")
print(demet[1:])
####################################################################
demet = ("ocak","şubat","mart","nisan","mayıs","haziran",
"temmuz","ağustos","eylül","ekim","kasım","aralık")
print(demet[:2])
########################################################################
demet = ("ocak","şubat","mart","nisan","mayıs","haziran",
"temmuz","ağustos","eylül","ekim","kasım","aralık")
print(demet[::2])
########################################################################
demet = ("ocak","şubat","mart","nisan","mayıs","haziran",
"temmuz","ağustos","eylül","ekim","kasım","aralık")
print(demet[::-1])
######################################################################
demet = ("ocak","şubat","mart","nisan","mayıs","haziran",
"temmuz","ağustos","eylül","ekim","kasım","aralık")
print(demet.index("haziran"))
###################################################################
demet = ("ocak","şubat","mart","nisan","mayıs","haziran",
"temmuz","ağustos","eylül","ekim","kasım","aralık")
print(demet.count("ocak"))
#####################################################################
|
[
"noreply@github.com"
] |
S-Oktay-Bicici.noreply@github.com
|
34a7c58dcf01f9d6380dcda2b8d82b5ea9641155
|
236816235f96479c230bc88de6d9c46357deadcb
|
/13/advent13.py
|
4122d64a02f431b9111e743511464007ab40b9dc
|
[] |
no_license
|
seeming-amusing/advent
|
f59f3f774f19bbcf2fc383da7a1ffbf87cc7a4da
|
6d6ae056d9739729820f4666e6015e877835ba6c
|
refs/heads/master
| 2021-09-01T02:05:47.906949
| 2017-12-24T09:57:05
| 2017-12-24T09:57:05
| 112,764,545
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,209
|
py
|
import sys
import time as t
class Sensor:
def __init__(self, range):
self.range = range
self.position = 1 if range > 0 else 0
self.direction = 1
def __repr__(self):
return "S (pos: " + str(self.position) + ")"
def is_caught(self, time):
if self.range == 0:
return False
return time % (2 * (self.range - 1)) == 0
def readFile():
fileName = sys.argv[1]
with open(fileName) as f:
content = f.readlines()
return content
def extractFirewall():
file = readFile()
firewall = dict()
for line in file:
vals = [int(v) for v in line.rstrip('\n').split(': ')]
firewall[vals[0]] = Sensor(vals[1])
return firewall
def find_severity(firewall):
severity = 0
for i, sensor in firewall.iteritems():
if firewall[i].is_caught(i):
severity += i * firewall[i].range
return severity
def is_caught(firewall, delay):
for i, sensor in firewall.iteritems():
if sensor.is_caught(i + delay):
return True
return False
firewall = extractFirewall()
print find_severity(firewall)
delay = 0
start = t.time()
while is_caught(firewall, delay):
delay += 1
print "Wait " + str(delay) + " ps"
print "Completed in " + str(t.time() - start) + " s"
|
[
"eric.m.lee@deliveryhero.com"
] |
eric.m.lee@deliveryhero.com
|
6ffb883c786a0debe0f2803afb428def4891485b
|
e821cf76df0d3abf618739a81ac9882173df663d
|
/xx.py
|
2be9a43563ca4b8982f1d45aa671d318d4351127
|
[] |
no_license
|
chscls/tenserTest
|
24b0f26428b7d16e4d1b2c60441839f6cf3a558e
|
1e6846c499e0873b30c3c307414b3a50d6bdc302
|
refs/heads/master
| 2020-03-23T19:22:36.969806
| 2018-07-24T00:36:48
| 2018-07-24T00:36:48
| 141,973,106
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 19
|
py
|
1313113131313313131
|
[
"chscls@163.com"
] |
chscls@163.com
|
0baa3ddc9c3e6359d85ca9fc5ec64c54526cffbc
|
0621313c69e79115d39314fcf3c89a62f144c0df
|
/hackathon2017/api/proyectandoapi/api/data_providers/settings.py
|
3ad873c1924dbc5b64ee3aadbff314a7fe1ddd3d
|
[] |
no_license
|
tamaraOrtiz/hackathon2017
|
965aea539403318c4952b4b672d72d785aafe922
|
cd1294b95337852550dbe8b654c26770f2749617
|
refs/heads/master
| 2020-12-02T10:08:16.406986
| 2017-10-17T15:51:06
| 2017-10-17T15:51:24
| 96,693,292
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 10,457
|
py
|
from os import path
from proyectandoapi.settings import *
URL_BASE = "http://geo.stp.gov.py/user/stp/api/v2/sql"
PND_FILE = path.join(BASE_DIR,'api','data_providers','json','pnd.json')
# Estas Unidades de medidas fueron filtradas manualmente, los Ignorados no son mostradas en el cliente
UNIDADES = {'ACTIVIDAD': 'ACTIVIDADES',
'ACTIVIDADES': 'ACTIVIDADES',
'ADJUDICACIONES': 'ADJUDICACIONES',
'AGREGADOS MILITARES': 'AGREGADOS MILITARES',
'ALUMNOS': 'ALUMNOS',
'ALUMNOS CURSANTES': 'ALUMNOS',
'ANIMALES': 'ANIMALES',
'ARANCEL': 'IGNORADOS',
'ASENTAMIENTOS': 'ASENTAMIENTOS',
'ASISTENCIA': 'ASISTENCIA',
'AULAS': 'AULAS',
'BENEFICIARIOS': 'IGNORADOS',
'CANASTA': 'CANASTAS',
'CAPACITACION': 'CAPACITACIONES',
'CASOS': 'CASOS',
'CASOS JUDICIALES': 'CASOS JUDICIALES',
'CAUSAS IMPUTADAS': 'CAUSAS IMPUTADAS',
'CEDULAS DE IDENTIDAD': 'CEDULAS DE IDENTIDAD',
'CENTROS': 'CENTROS',
'CERTIFICADOS': 'CERTIFICADOS',
'COMISIONES': 'COMISIONES',
'COMITÉS': 'COMITÉS',
'COMUNIDAD': 'COMUNIDADES',
'CONTROLES': 'CONTROLES',
'CONVENIOS': 'CONVENIOS',
'COOPERATIVAS': 'COOPERATIVAS',
'CREDITOS':'CREDITOS',
'CUOTAS': 'IGNORADOS',
'CURSOS': 'CURSOS',
'DESPACHOS':'IGNORADOS',
'DETERMINACIONES':'IGNORADOS',
'DIALISIS': 'DIALISIS',
'DISTRITOS':'DISTRITOS',
'DOCENTES': 'DOCENTES',
'DOCUMENTOS': 'IGNORADOS',
'DOSIS ENTREGADAS': 'IGNORADOS',
'EMPRESAS': 'EMPRESAS',
'ENTIDADES': 'ENTIDADES',
'ESCUELAS': 'ESCUELAS',
'ESTABLECIMIENTOS DE SALUD':'ESTABLECIMIENTOS DE SALUD',
'ESTUDIANTE': 'ALUMNOS',
'EVALUACIONES': 'IGNORADOS',
'EVENTOS': 'IGNORADOS',
'FAMILIAS': 'FAMILIAS',
'FERIAS':'IGNORADOS',
'FISCALIZACIONES': 'FISCALIZACIONES',
'GUARANIES': 'IGNORADOS',
'HABILITACIONES': 'HABILITACIONES',
'HECTAREAS': 'HECTAREAS',
'HECTÁREAS':'HECTAREAS',
'HOGARES': 'FAMILIAS',
'HOMBRES': 'HOMBRES',
'HORAS DE AIRE': 'IGNORADOS',
'HORAS DE VUELOS': 'IGNORADOS',
'INFORMES': 'IGNORADOS',
'INFORMES DE AUDITORÍA': 'IGNORADOS',
'INSCRIPCIONES':'IGNORADOS',
'INSTITUCIONES':'IGNORADOS',
'INSUMOS':'IGNORADOS',
'INTERNOS': 'IGNORADOS',
'INTERVENCIONES': 'IGNORADOS',
'INVESTIGACIONES': 'INVESTIGACIONES',
'JORNADAS': 'JORNADAS',
'JUBILADOS': 'JUBILADOS',
'KILOMETROS': 'KILOMETROS',
'KILÓMETROS': 'KILOMETROS',
'KWH':'IGNORADOS',
'LICENCIAS': 'LICENCIAS',
'LITROS':'IGNORADOS',
'LLAMADOS': 'LLAMADOS',
'LOCALES': 'LOCALES',
'LOCALIDADES': 'LOCALIDADES',
'MAPAS': 'MAPAS',
'METRO LINEAL': 'IGNORADOS',
'METROS': 'IGNORADOS',
'METROS CUADRADOS': 'IGNORADOS',
'METROS CUBICOS': 'IGNORADOS',
'MICROPROYECTOS': 'MICROPROYECTOS',
'MUJERES': 'MUJERES',
'NIÑOS/NIÑAS': 'NIÑOS/NIÑAS',
'OBRAS': 'OBRAS',
'OPERACIONES': 'IGNORADOS',
'OPERATIVOS': 'IGNORADOS',
'ORDENES DE TRABAJO': 'IGNORADOS',
'PACIENTES': 'PACIENTES',
'PAGOS': 'IGNORADOS',
'PASAPORTES':'IGNORADOS',
'PERMISOS': 'IGNORADOS',
'PERSONAS': 'PERSONAS',
'PERSONAS ATENDIDAS': 'PERSONAS',
'PLANES': 'IGNORADOS',
'PORCENTAJE': 'IGNORADOS',
'POZOS': 'IGNORADOS',
'PRESTACIONES': 'IGNORADOS',
'PRESTAMOS': 'IGNORADOS',
'PROCEDIMIENTOS': 'IGNORADOS',
'PRODUCTORES': 'PRODUCTORES',
'PROYECTOS': 'PROYECTOS',
'PROYECTOS DE INVESTIGACION': 'PROYECTOS DE INVESTIGACION',
'PUENTES':'PUENTES',
'RECOMENDACIONES': 'IGNORADOS',
'REGISTROS': 'IGNORADOS',
'REPORTES': 'IGNORADOS',
'RESOLUCIONES':'RESOLUCIONES',
'SENTENCIAS DEFINITIVAS': 'IGNORADOS',
'SERVICIOS': 'IGNORADOS',
'SERVICIOS OFRECIDOS': 'IGNORADOS',
'SISTEMAS': 'IGNORADOS',
'SUBSIDIOS': 'IGNORADOS',
'TEXTOS': 'IGNORADOS',
'TONELADAS': 'IGNORADOS',
'TRANSFERENCIAS': 'IGNORADOS',
'UNIDAD': 'IGNORADOS',
'UNIDAD MILITAR': 'UNIDAD MILITAR',
'UNIDADES': 'IGNORADOS',
'USUARIOS': 'USUARIOS',
'VEHICULOS': 'VEHICULOS',
'VERIFICACIONES': 'IGNORADOS',
'VIVIENDAS':'VIVIENDAS',
'VUELOS': 'IGNORADOS'
}
# Define las unidades de medida que son personas
PERSONAS = ['ALUMNOS', 'DOCENTES', 'USUARIOS', 'PERSONAS', 'PACIENTES', 'MUJERES',
'NIÑOS/NIÑAS', 'HOMBRES']
# Relaciona una unidad de medida con un icono
ICONOS = {'ACTIVIDADES': "fa fa-calendar-check-o",
'ADJUDICACIONES': "fa fa-handshake-o",
'AGREGADOS MILITARES': "fa fa-taxi" ,
'ALUMNOS': "fa fa-graduation-cap",
'ANIMALES':"fa fa-paw",
'ASENTAMIENTOS': "fa fa-home",
'ASISTENCIA': "fa fa-handshake-o",
'AULAS': "fa fa-graduation-cap",
'CANASTAS':"fa fa-shopping-basket",
'CAPACITACIONES':"fa fa-graduation-cap",
'CASOS': "fa fa-book",
'CASOS JUDICIALES': "fa fa-book",
'CAUSAS IMPUTADAS': "fa fa-book",
'CEDULAS DE IDENTIDAD': "fa fa-address-card",
'CENTROS': "fa fa-university",
'CERTIFICADOS': "fa fa-newspaper-o",
'COMISIONES': "fa fa-handshake-o",
'COMITÉS':"fa fa-handshake-o",
'COMUNIDADES': "fa fa-users",
'CONTROLES': "fa fa-book",
'CONVENIOS': "fa fa-newspaper-o",
'COOPERATIVAS':"fa fa-university",
'CREDITOS': "fa fa-handshake-o",
'CURSOS': "fa fa-graduation-cap",
'DIALISIS': "fa fa-medkit",
'DISTRITOS':"fa fa-map-marker",
'DOCENTES': "fa fa-graduation-cap",
'EMPRESAS': "fa fa-university",
'ENTIDADES': "fa fa-university",
'ESCUELAS': "fa fa-graduation-cap",
'ESTABLECIMIENTOS DE SALUD': "fa fa-hospital-o",
'FAMILIAS': "fa fa-users",
'FISCALIZACIONES':"fa fa-book",
'HABILITACIONES':"fa fa-address-card",
'HECTAREAS':"fa fa-exchange" ,
'HOMBRES': "fa fa-male",
'IGNORADOS': "",
'INVESTIGACIONES':"fa fa-graduation-cap",
'JORNADAS': "fa fa-graduation-cap",
'JUBILADOS': "fa fa-blind",
'KILOMETROS': "fa fa-exchange" ,
'LICENCIAS': "fa fa-address-card",
'LLAMADOS': "fa fa-volume-control-phone",
'LOCALES':"fa fa-university",
'LOCALIDADES':"fa fa-map-marker",
'MAPAS': "fa fa-map" ,
'MICROPROYECTOS': "fa fa-handshake-o",
'MUJERES':"fa fa-female",
'NIÑOS/NIÑAS': "fa fa-child",
'OBRAS': "fa fa-building-o",
'PACIENTES': "fa fa-wheelchair",
'PERSONAS': "fa fa-users",
'PRODUCTORES':"fa fa-truck",
'PROYECTOS': "fa fa-handshake-o",
'PROYECTOS DE INVESTIGACION': "fa fa-handshake-o",
'PUENTES':"fa fa-building-o",
'RESOLUCIONES': "fa fa-book",
'UNIDAD MILITAR': "fa fa-taxi",
'USUARIOS': "fa fa-users",
'VEHICULOS': "fa fa-car" ,
'VIVIENDAS': "fa fa-home"}
# Define los nombres de los archivos
ACCPRO_FILE = path.join(BASE_DIR,'api','data_providers','json',"acc_prod.json")
TOTALES_PRODUCTOS = path.join(BASE_DIR,'api','data_providers','json',"t_prod.json")
TOTALES_ENTIDADES = path.join(BASE_DIR,'api','data_providers','json',"t_ent.json")
TOTALES_PRODACC = path.join(BASE_DIR,'api','data_providers','json',"t_proacc.json")
AVANCE_FILE = path.join(BASE_DIR,'api','data_providers','json',"avance.json")
LA_FILE = path.join(BASE_DIR,'api','data_providers','json',"la.json")
PROG_FILE = path.join(BASE_DIR,'api','data_providers','json',"pro.json")
LA_PROG_FILE = path.join(BASE_DIR,'api','data_providers','json',"la_pro.json")
LA_MAPA = path.join(BASE_DIR,'api','data_providers','json',"la_mapa.json")
DEST_FILE = path.join(BASE_DIR,'api','data_providers','json',"dest.json")
INST_FILE = path.join(BASE_DIR,'api','data_providers','json',"inst.json")
NIV_FILE = path.join(BASE_DIR,'api','data_providers','json',"niv.json")
ENT_FILE = path.join(BASE_DIR,'api','data_providers','json',"ent.json")
FULLINST_FILE = path.join(BASE_DIR,'api','data_providers','json',"fullinst.json")
|
[
"tamara.tfs@gmail.com"
] |
tamara.tfs@gmail.com
|
d893f81447cffccd57f611c33ea3bf1abef138f4
|
092730e0ab9ca11ea7c729d442eb1864ffef46da
|
/config.py
|
1c2d5cfcce31084d3ea93e07b1fc8120e3f0c5cc
|
[] |
no_license
|
pkulics/clssification4all
|
bde34b286c09829ffa63efd07f334ea4995d2986
|
5dcf1150465db54a22fb0eebfb452648cfcd4b8b
|
refs/heads/master
| 2020-10-02T09:48:12.205019
| 2019-12-13T03:58:30
| 2019-12-13T03:58:30
| 227,750,667
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 627
|
py
|
# 句子长度
SEQ_LENGTH = 20
# 分类类别
NUM_CLASS = 2
# 学习率
LEARNING_RATE = 0.01
# 隐层单元数
HIDDEN_DIM = 300
# 训练轮数
EPOCHS = 100
# 训练batch大小
BATCH_SIZE = 64
# dropout比率
KEEP_PROB = 0.5
# 保存模型路径
SAVE_PATH = "saved_model/"
# 词表路径
WORD_PATH = "data/chars.txt"
# 词向量路径
VEC_PATH = "data/selected_vec.txt"
# 训练集路径
TRAIN_DIR = "data/pingjia/train.txt"
# 测试集路径
TEST_DIR = "data/pingjia/test.txt"
# 验证集路径
VAL_DIR = "data/pingjia/val.txt"
# 隔多少次训练打印一次测试结果
PRINT_PER_BATCH = 100
# 类别
CATEGORY = ['0','1']
|
[
"lics999@126.com"
] |
lics999@126.com
|
784e56a9dbaee37073f8fdb145715f994d3dd23b
|
6c8f3ab5f952d986a17edda582c5a039bf65c632
|
/django/current_time/manage.py
|
d3c6bb5d885435d67ba8dae50bc7e405130103bf
|
[] |
no_license
|
phillipn/coding_bootcamp_projects
|
3d3bd697728dd4502267e0cd2be7a090952029a8
|
278f96df9d256364583654a00fe585d474ea86a1
|
refs/heads/master
| 2021-01-17T17:30:14.607944
| 2017-03-19T18:12:32
| 2017-03-19T18:12:32
| 82,971,619
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 810
|
py
|
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "current_time.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
execute_from_command_line(sys.argv)
|
[
"phillipn101@gmail.com"
] |
phillipn101@gmail.com
|
e2c690c3b7c514541608366bd2c05a1d0074bd84
|
5027dac6f1d8caef4efb343532dcc9fd3eaf5684
|
/wemake_python_styleguide/violations/refactoring.py
|
b2b5f2148489073d379b4a052fbc19800c77265d
|
[
"MIT"
] |
permissive
|
miranda-lin/wemake-python-styleguide
|
a31f81d08aa487fda432f39338f8b1c0ce0e779c
|
673a06431f244291f7a0e57998d86f3d1b3a887c
|
refs/heads/master
| 2020-09-28T08:02:12.409502
| 2019-12-05T08:51:52
| 2019-12-05T08:51:52
| 226,729,049
| 0
| 0
|
MIT
| 2019-12-08T20:45:03
| 2019-12-08T20:45:02
| null |
UTF-8
|
Python
| false
| false
| 27,485
|
py
|
# -*- coding: utf-8 -*-
"""
These checks ensure that you don't have patterns that can be refactored.
There are so many ways of doing the same thing in Python.
Here we collect know patterns that can be rewritten into
much easier or just more pythonic version.
.. currentmodule:: wemake_python_styleguide.violations.refactoring
Summary
-------
.. autosummary::
:nosignatures:
UselessLoopElseViolation
UselessFinallyViolation
SimplifiableIfViolation
UselessReturningElseViolation
NegatedConditionsViolation
NestedTryViolation
UselessLambdaViolation
UselessLenCompareViolation
NotOperatorWithCompareViolation
NestedTernaryViolation
WrongInCompareTypeViolation
UnmergedIsinstanceCallsViolation
WrongIsinstanceWithTupleViolation
ImplicitElifViolation
ImplicitInConditionViolation
OpenWithoutContextManagerViolation
TypeCompareViolation
PointlessStarredViolation
ImplicitEnumerateViolation
ImplicitSumViolation
FalsyConstantCompareViolation
WrongIsCompareViolation
ImplicitPrimitiveViolation
AlmostSwappedViolation
MisrefactoredAssignmentViolation
InCompareWithSingleItemContainerViolation
ImplicitYieldFromViolation
NotATupleArgumentViolation
ImplicitItemsIteratorViolation
ImplicitDictGetViolation
ImplicitNegativeIndexViolation
Refactoring opportunities
-------------------------
.. autoclass:: UselessLoopElseViolation
.. autoclass:: UselessFinallyViolation
.. autoclass:: SimplifiableIfViolation
.. autoclass:: UselessReturningElseViolation
.. autoclass:: NegatedConditionsViolation
.. autoclass:: NestedTryViolation
.. autoclass:: UselessLambdaViolation
.. autoclass:: UselessLenCompareViolation
.. autoclass:: NotOperatorWithCompareViolation
.. autoclass:: NestedTernaryViolation
.. autoclass:: WrongInCompareTypeViolation
.. autoclass:: UnmergedIsinstanceCallsViolation
.. autoclass:: WrongIsinstanceWithTupleViolation
.. autoclass:: ImplicitElifViolation
.. autoclass:: ImplicitInConditionViolation
.. autoclass:: OpenWithoutContextManagerViolation
.. autoclass:: TypeCompareViolation
.. autoclass:: PointlessStarredViolation
.. autoclass:: ImplicitEnumerateViolation
.. autoclass:: ImplicitSumViolation
.. autoclass:: FalsyConstantCompareViolation
.. autoclass:: WrongIsCompareViolation
.. autoclass:: ImplicitPrimitiveViolation
.. autoclass:: AlmostSwappedViolation
.. autoclass:: MisrefactoredAssignmentViolation
.. autoclass:: InCompareWithSingleItemContainerViolation
.. autoclass:: ImplicitYieldFromViolation
.. autoclass:: NotATupleArgumentViolation
.. autoclass:: ImplicitItemsIteratorViolation
.. autoclass:: ImplicitDictGetViolation
.. autoclass:: ImplicitNegativeIndexViolation
"""
from typing_extensions import final
from wemake_python_styleguide.violations.base import (
ASTViolation,
TokenizeViolation,
)
@final
class UselessLoopElseViolation(ASTViolation):
"""
Forbids to use ``else`` without ``break`` in a loop.
We use the same logic for ``for`` and ``while`` loops.
Reasoning:
When there's no ``break`` keyword in loop's body it means
that ``else`` will always be called.
This rule will reduce complexity, improve readability,
and protect from possible errors.
Solution:
Refactor your ``else`` case logic to be inside the loop's body.
Or right after it.
Example::
# Correct:
for letter in 'abc':
if letter == 'b':
break
else:
print('"b" is not found')
for letter in 'abc':
print(letter)
print('always called')
# Wrong:
for letter in 'abc':
print(letter)
else:
print('always called')
.. versionadded:: 0.3.0
.. versionchanged:: 0.11.0
"""
error_template = 'Found `else` in a loop without `break`'
code = 500
previous_codes = {436}
@final
class UselessFinallyViolation(ASTViolation):
"""
Forbids to use ``finally`` in ``try`` block without ``except`` block.
Reasoning:
This rule will reduce complexity and improve readability.
Solution:
Refactor your ``try`` logic.
Replace the ``try-finally`` statement with a ``with`` statement.
Example::
# Correct:
with open("filename") as f:
f.write(...)
# Wrong:
try:
f = open("filename")
f.write(...)
finally:
f.close()
.. versionadded:: 0.3.0
.. versionchanged:: 0.11.0
"""
error_template = 'Found `finally` in `try` block without `except`'
code = 501
previous_codes = {437}
@final
class SimplifiableIfViolation(ASTViolation):
"""
Forbids to have simplifiable ``if`` conditions.
Reasoning:
This complex construction can cause frustration among other developers.
It is longer, more verbose, and more complex.
Solution:
Use ``bool()`` to convert test values to boolean values.
Or just leave it as it is in case
when your test already returns a boolean value.
Use can also use ``not`` keyword to switch boolean values.
Example::
# Correct:
my_bool = bool(some_call())
other_value = 8 if some_call() else None
# Wrong:
my_bool = True if some_call() else False
We only check ``if`` nodes where ``True`` and ``False`` values are used.
We check both ``if`` nodes and ``if`` expressions.
.. versionadded:: 0.7.0
.. versionchanged:: 0.11.0
"""
error_template = 'Found simplifiable `if` condition'
code = 502
previous_codes = {451}
@final
class UselessReturningElseViolation(ASTViolation):
"""
Forbids to use useless ``else`` cases in returning functions.
We check single ``if`` statements that all contain
``return`` or ``raise`` or ``break`` statements with this rule.
We do not check ``if`` statements with ``elif`` cases.
Reasoning:
Using extra ``else`` creates a situation when
the whole node could and should be dropped
without any changes in logic.
So, we prefer to have less code than more code.
Solution:
Remove useless ``else`` case.
Example::
# Correct:
def some_function():
if some_call():
return 'yeap'
return 'nope'
# Wrong:
def some_function():
if some_call():
raise ValueError('yeap')
else:
raise ValueError('nope')
.. versionadded:: 0.7.0
.. versionchanged:: 0.11.0
"""
error_template = 'Found useless returning `else` statement'
code = 503
previous_codes = {457}
@final
class NegatedConditionsViolation(ASTViolation):
"""
Forbids to use negated conditions together with ``else`` clause.
Reasoning:
It easier to read and name regular conditions. Not negated ones.
Solution:
Move actions from the negated ``if`` condition to the ``else``
condition.
Example::
# Correct:
if some == 1:
...
else:
...
if not some:
...
if not some:
...
elif other:
...
# Wrong:
if not some:
...
else:
...
.. versionadded:: 0.8.0
.. versionchanged:: 0.11.0
"""
error_template = 'Found negated condition'
code = 504
previous_codes = {463}
@final
class NestedTryViolation(ASTViolation):
"""
Forbids to use nested ``try`` blocks.
Notice, we check all possible slots for ``try`` block:
1. the ``try`` block itself
2. all ``except`` cases
3. ``else`` case
4. and ``finally`` case
Reasoning:
Nesting ``try`` blocks indicates
that something really bad happens to your logic.
Why does it require two separate exception handlers?
It is a perfect case to refactor your code.
Solution:
Collapse two exception handlers together.
Or create a separate function that will handle this second nested case.
Example::
# Wrong:
try:
try:
...
except SomeException:
...
except SomeOtherException:
...
try:
...
except SomeOtherException:
try:
...
except SomeException:
...
.. versionadded:: 0.8.0
.. versionchanged:: 0.11.0
"""
error_template = 'Found nested `try` block'
code = 505
previous_codes = {464}
@final
class UselessLambdaViolation(ASTViolation):
"""
Forbids to define useless proxy ``lambda`` expressions.
Reasoning:
Sometimes developers tend to overuse ``lambda`` expressions
and they wrap code that can be passed as is, without extra wrapping.
The code without extra ``lambda`` is easier
to read and is more performant.
Solution:
Remove wrapping ``lambda`` declaration, use just the internal function.
Example::
# Correct:
numbers = map(int, ['1', '2'])
# Wrong:
numbers = map(lambda string: int(string), ['1', '2'])
.. versionadded:: 0.10.0
.. versionchanged:: 0.11.0
"""
error_template = 'Found useless lambda declaration'
code = 506
previous_codes = {467}
@final
class UselessLenCompareViolation(ASTViolation):
"""
Forbids to have unpythonic zero-length compare.
Note, that we allow to check arbitrary length, like ``len(arr) == 3``.
Reasoning:
Python's structures like dicts, lists, sets, and tuples
all have ``__bool__`` method to checks their length.
So, there's no point in wrapping them into ``len(...)``
and checking that it is bigger that ``0`` or less then ``1``, etc.
Solution:
Remove extra ``len()`` call.
Example::
# Correct:
if some_array or not other_array or len(third_array) == 1:
...
# Wrong:
if len(some_array) > 0 or len(other_array) < 1:
...
.. versionadded:: 0.10.0
.. versionchanged:: 0.11.0
"""
error_template = 'Found useless `len()` compare'
code = 507
previous_codes = {468}
@final
class NotOperatorWithCompareViolation(ASTViolation):
"""
Forbids to use ``not`` with compare expressions.
Reasoning:
This version of ``not`` operator is unreadable.
Solution:
Refactor the expression without ``not`` operator.
Change the compare signs.
Example::
# Correct:
if x <= 5:
...
# Wrong:
if not x > 5:
...
.. versionadded:: 0.10.0
.. versionchanged:: 0.11.0
"""
error_template = 'Found incorrect `not` with compare usage'
code = 508
previous_codes = {470}
@final
class NestedTernaryViolation(ASTViolation):
"""
Forbids to nest ternary expressions in some places.
Note, that we restrict to nest ternary expressions inside:
- ``if`` conditions
- boolean and binary operations like ``and`` or ``+``
- unary operators
Reasoning:
Nesting ternary in random places can lead to very hard
debug and testing problems.
Solution:
Refactor the ternary expression to be either a new variable,
or nested ``if`` statement, or a new function.
Example::
# Correct:
some = x if cond() else y
# Wrong:
if x if cond() else y:
...
.. versionadded:: 0.10.0
.. versionchanged:: 0.11.0
"""
error_template = 'Found incorrectly nested ternary'
code = 509
previous_codes = {472}
@final
class WrongInCompareTypeViolation(ASTViolation):
"""
Forbids to use ``in`` with static containers except ``set`` nodes.
We enforce people to use sets as a static containers.
You can also use variables, calls, methods, etc.
Dynamic values are not checked.
Reasoning:
Using static ``list``, ``tuple``, or ``dict`` elements
to check that some element is inside the container is a bad practice.
Because we need to iterate all over the container to find the element.
Sets are the best suit for this task.
Moreover, it makes your code consistent.
Solution:
Use ``set`` elements or comprehensions to check that something
is contained in a container.
Example::
# Correct:
print(needle in {'one', 'two'})
# Wrong:
print(needle in ['one', 'two'])
.. versionadded:: 0.10.0
.. versionchanged:: 0.11.0
"""
error_template = 'Found `in` used with a non-set container'
code = 510
previous_codes = {473}
@final
class UnmergedIsinstanceCallsViolation(ASTViolation):
"""
Forbids to multiple ``isinstance`` calls with the same variable.
Reasoning:
The best practice is to use ``isinstance`` with tuple
as the second argument, instead of multiple conditions
joined with ``or``.
Solution:
Use tuple of types as the second argument.
Example::
# Correct:
isinstance(some, (int, float))
# Wrong:
isinstance(some, int) or isinstance(some, float)
See also:
https://docs.python.org/3/library/functions.html#isinstance
.. versionadded:: 0.10.0
.. versionchanged:: 0.11.0
"""
error_template = (
'Found separate `isinstance` calls that can be merged for: {0}'
)
code = 511
previous_codes = {474}
@final
class WrongIsinstanceWithTupleViolation(ASTViolation):
"""
Forbids to multiple ``isinstance`` calls with tuples of a single item.
Reasoning:
There's no need to use tuples with single elements.
You can use single variables or tuples with multiple elements.
Solution:
Use tuples with multiple elements or a single varaible.
Example::
# Correct:
isinstance(some, (int, float))
isisntance(some, int)
# Wrong:
isinstance(some, (int, ))
See: https://docs.python.org/3/library/functions.html#isinstance
.. versionadded:: 0.10.0
.. versionchanged:: 0.11.0
"""
error_template = 'Found `isinstance` call with a single element tuple'
code = 512
previous_codes = {475}
@final
class ImplicitElifViolation(TokenizeViolation):
"""
Forbids to have implicit ``elif`` conditions.
Reasoning:
Nested ``if`` in ``else`` cases are bad
for readability because of the nesting level.
Solution:
Use ``elif`` on the same level.
Example::
# Correct:
if some:
...
elif other:
...
# Wrong:
if some:
...
else:
if other:
...
.. versionadded:: 0.12.0
"""
error_template = 'Found implicit `elif` condition'
code = 513
@final
class ImplicitInConditionViolation(ASTViolation):
"""
Forbids to use multiple equality compare with the same variable name.
Reasoning:
Using double+ equality compare with ``or``
or double+ non-equality compare with ``and``
indicates that you have implicit ``in`` or ``not in`` condition.
It is just hidden from you.
Solution:
Refactor compares to use ``in`` or ``not in`` clauses.
Example::
# Correct:
print(some in {'first', 'second'})
print(some not in {'first', 'second'})
# Wrong:
print(some == 'first' or some == 'second')
print(some != 'first' and some != 'second')
.. versionadded:: 0.10.0
.. versionchanged:: 0.12.0
"""
code = 514
error_template = 'Found implicit `in` condition'
previous_codes = {336}
@final
class OpenWithoutContextManagerViolation(ASTViolation):
"""
Forbids to use ``open()`` with a context manager.
Reasoning:
When you ``open()`` something, you need to close it.
When using a context manager - it is automatically done for you.
When not using it - you might find yourself in a situation
when file is not closed and is not accessable anymore.
Solution:
Refactor ``open()`` call to use ``with``.
Example::
# Correct:
with open(filename) as file_obj:
...
# Wrong:
file_obj = open(filename)
.. versionadded:: 0.12.0
"""
code = 515
error_template = 'Found `open()` used without a context manager'
@final
class TypeCompareViolation(ASTViolation):
"""
Forbids to compare types with ``type()`` function.
Reasoning:
When you compare types with ``type()`` function call
it means that you break polymorphism and dissallow child classes
of a node to work here. That's incorrect.
Solution:
Use ``isinstance`` to compare types.
Example::
# Correct:
print(something, type(something))
# Wrong:
if type(something) == int:
...
.. versionadded:: 0.12.0
"""
code = 516
error_template = 'Found `type()` used to compare types'
@final
class PointlessStarredViolation(ASTViolation):
"""
Forbids to have useless starred expressions.
Reasoning:
Using starred expression with constants is useless.
This piece of code can be rewritten to be flat.
Eg.: ``print(*[1, 2, 3])`` is ``print(1, 2, 3)``.
Solution:
Refactor your code not to use starred expressions
with ``list``, ``dict``, ``tuple``, and ``set`` constants.
Use regular argument passing instead.
Example::
# Correct:
my_list = [1, 2, 3, *other_iterable]
# Wrong:
print(*[1, 2, 3], **{{}})
.. versionadded:: 0.12.0
"""
code = 517
error_template = 'Found pointless starred expression'
@final
class ImplicitEnumerateViolation(ASTViolation):
"""
Forbids to have implicit ``enumerate()`` calls.
Reasoning:
Using ``range(len(...))`` is not pythonic.
Python uses collection iterators, not index-based loops.
Solution:
Use ``enumerate(...)`` instead of ``range(len(...))``.
Example::
# Correct:
for index, person in enumerate(people):
...
# Wrong:
for index in range(len(people)):
...
See also:
https://docs.python.org/3/library/functions.html#enumerate
.. versionadded:: 0.12.0
"""
code = 518
error_template = 'Found implicit `enumerate()` call'
@final
class ImplicitSumViolation(ASTViolation):
"""
Forbids to have implicit ``sum()`` calls.
When summing types different from numbers, you might need to provide
the second argument to the ``sum`` function: ``sum([[1], [2], [3]], [])``
You might also use ``str.join`` to join iterable of strings.
Reasoning:
Using ``for`` loops with ``+=`` assign inside indicates
that you iteratively sum things inside your collection.
That's what ``sum()`` builtin function does.
Solution:
Use ``sum(...)`` instead of a loop with ``+=`` operation.
Example::
# Correct:
sum_result = sum(get_elements())
# Wrong:
sum_result = 0
for to_sum in get_elements():
sum_result += to_sum
See also:
https://docs.python.org/3/library/functions.html#sum
https://docs.python.org/3/library/stdtypes.html#str.join
.. versionadded:: 0.12.0
"""
code = 519
error_template = 'Found implicit `sum()` call'
@final
class FalsyConstantCompareViolation(ASTViolation):
"""
Forbids to compare with explicit falsy constants.
We allow to compare with falsy numbers, strings, booleans, ``None``.
We disallow complex constants like tuple, dicts, and lists.
Reasoning:
When comparing ``something`` with explicit falsy constants
what we really mean is ``not something``.
Solution:
Use ``not`` with your variable.
Fix your data types.
Example::
# Correct:
if not my_check:
...
if some_other is None:
...
if some_num == 0:
...
# Wrong:
if my_check == []:
...
.. versionadded:: 0.12.0
"""
code = 520
error_template = 'Found compare with falsy constant'
@final
class WrongIsCompareViolation(ASTViolation):
"""
Forbids to compare values with constants using ``is`` or ``is not``.
However, we allow to compare with ``None`` and booleans.
Reasoning:
``is`` compares might not do what you want them to do.
Firstly, they check for the same object, not equality.
Secondly, they behave unexpectedly even
with the simple values like ``257``.
Solution:
Use ``==`` to compare with constants.
Example::
# Correct:
if my_check == [1, 2, 3]:
...
# Wrong:
if my_check is [1, 2, 3]:
...
See also:
https://stackoverflow.com/a/33130014/4842742
.. versionadded:: 0.12.0
"""
code = 521
error_template = 'Found wrong `is` compare'
@final
class ImplicitPrimitiveViolation(ASTViolation):
"""
Forbids to use implicit primitives in a form of ``lambda`` functions.
Reasoning:
When you use ``lambda`` that returns a primitive value
and takes no arguments, it means that
you should use a primitive type instead.
Solution:
Replace ``lambda`` with ``int``, ``float``,
``list``, or any other primitive.
Example::
# Correct:
defaultdict(int)
# Wrong:
defaultdict(lambda: 0)
.. versionadded:: 0.13.0
"""
code = 522
error_template = 'Found implicit primitive in a form of `lambda`'
@final
class AlmostSwappedViolation(ASTViolation):
"""
Forbids unpythonic swap variables.
We check for ``a = b; b = a`` sequences.
Reasoning:
This looks like a failed attempt to swap.
Solution:
Use standard way to swap two variables.
Example::
# Correct:
a, b = b, a
# Wrong:
a = b
b = a
temp = a
a = b
b = temp
.. versionadded:: 0.13.0
"""
error_template = 'Found incorrectly swapped variables'
code = 523
@final
class MisrefactoredAssignmentViolation(ASTViolation):
"""
Forbids to use misrefactored self assignment.
Reasoning:
Self assignment does not need to have the same operand
on the left hand side and on the right hand side.
Solution:
Refactor you code to use multiple self assignments or fix your code.
Example::
# Correct:
test += 1
test *= 2
# Wrong:
test += test + 1
See
:py:data:`~wemake_python_styleguide.constants.MATH_APPROXIMATE_CONSTANTS`
for full list of math constants that we check for.
.. versionadded:: 0.13.0
"""
error_template = 'Found self assignment with refactored assignment'
code = 524
@final
class InCompareWithSingleItemContainerViolation(ASTViolation):
"""
Forbids comparisons where ``in`` is compared with single item container.
Reasoning:
``in`` comparison with a container which contains only one item looks
like overhead and unneeded complexity.
Solution:
Refactor your code to use ``==`` instead ``in``.
Example::
# Correct:
a == 's'
# Wrong:
a in {'s'}
.. versionadded:: 0.13.0
"""
error_template = 'Found wrong "in" compare with single item container'
code = 525
@final
class ImplicitYieldFromViolation(ASTViolation):
"""
Forbids to use ``yield`` inside ``for`` loop instead of ``yield from``.
Reasoning:
It is known that ``yield from`` is a semantically identical
to a ``for`` loop with a ``yield`` inside.
But, it is way more readable.
Solution:
Use ``yield from`` some iterable directly
instead iterating over it inside a loop
and ``yield`` it one by one.
Example::
# Correct:
yield from some()
# Wrong:
for item in some():
yield item
.. versionadded:: 0.13.0
"""
error_template = 'Found implicit `yield from` usage'
code = 526
@final
class NotATupleArgumentViolation(ASTViolation):
"""
Forces using tuples as arguments for some functions.
Reasoning:
For some functions, it is better to use tuples instead of another
iterable types (list, sets,...) as arguments.
Solution:
Use tuples as arguments.
Example::
# Correct:
a = frozenset((2,))
# Wrong:
a = frozenset([2])
See
:py:data:`~wemake_python_styleguide.constants.TUPLE_ARGUMENTS_METHODS`
for full list of methods that we check for.
.. versionadded:: 0.13.0
"""
error_template = 'Found not a tuple used as an argument'
code = 527
@final
class ImplicitItemsIteratorViolation(ASTViolation):
"""
Forbids to use implicit ``.items()`` iterator.
Reasoning:
When iterating over collection it is easy to forget
to use ``.items()`` when you need to access both keys and values.
So, when you access the iterable with the key inside a ``for`` loop,
that's a sign to refactor your code.
Solution:
Use ``.items()`` with direct keys and values when you need them.
Example::
# Correct:
for some_key, some_value in collection.items():
print(some_key, some_value)
# Wrong:
for some_key in collection:
print(some_key, collection[some_key])
.. versionadded:: 0.13.0
"""
error_template = 'Found implicit `.items()` usage'
code = 528
@final
class ImplicitDictGetViolation(ASTViolation):
"""
Forbids to use implicit ``.get()`` dict method.
Reasoning:
When using ``in`` with a dict key it is hard to keep the code clean.
It is more convinient to use ``.get()`` and check for ``None`` later.
Solution:
Use ``.get()`` with the key you need.
Check for ``None`` in case you need it,
or just act with the default value of the same type.
Example::
# Correct:
value = collection.get(key)
if value is not None:
print(value)
# Wrong:
if key in collection:
print(collection[key])
.. versionadded:: 0.13.0
"""
error_template = 'Found implicit `.get()` dict usage'
code = 529
@final
class ImplicitNegativeIndexViolation(ASTViolation):
"""
Forbids to use implicit negative indexes.
Reasoning:
There's no need in getting the length of an iterable
and then having a negative offset,
when you can specify negative indexes in the first place.
Solution:
Use negative indexes.
Example::
# Correct:
some_list[-1]
# Wrong:
some_list[len(some_list) - 1]
.. versionadded:: 0.13.0
"""
error_template = 'Found implicit negative index'
code = 530
|
[
"mail@sobolevn.me"
] |
mail@sobolevn.me
|
8434ac74cf6437d09b1477f834bb50b69fa990ee
|
a46d135ba8fd7bd40f0b7d7a96c72be446025719
|
/packages/python/plotly/plotly/validators/mesh3d/colorbar/_xpad.py
|
7820a1942bfa9356738ddc1559e8591237ceef1b
|
[
"MIT"
] |
permissive
|
hugovk/plotly.py
|
5e763fe96f225d964c4fcd1dea79dbefa50b4692
|
cfad7862594b35965c0e000813bd7805e8494a5b
|
refs/heads/master
| 2022-05-10T12:17:38.797994
| 2021-12-21T03:49:19
| 2021-12-21T03:49:19
| 234,146,634
| 0
| 0
|
MIT
| 2020-01-15T18:33:43
| 2020-01-15T18:33:41
| null |
UTF-8
|
Python
| false
| false
| 438
|
py
|
import _plotly_utils.basevalidators
class XpadValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(self, plotly_name="xpad", parent_name="mesh3d.colorbar", **kwargs):
super(XpadValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "colorbars"),
min=kwargs.pop("min", 0),
**kwargs
)
|
[
"noreply@github.com"
] |
hugovk.noreply@github.com
|
c0c36952762518441402ac4632f851c9af287a86
|
0d8b1d5bd8988da99dfb3a20feb0a96367f26f3e
|
/scraper.py
|
942e833f7bd296d085cb70837d37948e08c82993
|
[] |
no_license
|
Arrakark/craigslist_housing
|
2c6add47782258065e1118fcd64d0a0970b31cc3
|
7bbacac7ad70b9636be7571b0f223ab77407fbe0
|
refs/heads/main
| 2023-06-26T11:15:29.308450
| 2021-07-28T08:31:15
| 2021-07-28T08:31:15
| 355,320,181
| 5
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 11,122
|
py
|
from time import sleep
import re
# avoid throttling by not sending too many requests one after the other
from random import randint
from warnings import warn
from time import time
from IPython.core.display import clear_output
import numpy as np
from bs4 import BeautifulSoup
from requests import get
import pandas as pd
from datetime import datetime
import glob
import os
from tinydb import TinyDB, Query
from tinydb.operations import add
# Base URL
# Go to craigslist, set up a search for the apartments you want (price, location, pictures, keywords)
# Then enter the URL here to scrape
base_url = "https://vancouver.craigslist.org/search/apa?query=-shared+-wanted&hasPic=1&search_distance=4.2&postal=v6r3e9&availabilityMode=0&sale_date=all+dates&max_price=4000"
# set scraping delays
# minimum delay in seconds
min_scraping_delay = 5
# maxinum delay in seconds
max_scraping_delay = 15
def get_current_prices(base_url: str, throttle: bool = True) -> pd.DataFrame:
# Scrapes all of the current housing listsings near UBC from Craigslist.
# Returns a Pandas datatable
# May include duplicate listings and listings with a price of $0
# Does not include posts wit hthe keyboards "shared" or "wanted" in the title
# get the first page of housing prices
response = get(base_url)
html_soup = BeautifulSoup(response.text, 'html.parser')
# get the macro-container for the housing posts
posts = html_soup.find_all('li', class_='result-row')
# find the total number of posts to find the limit of the pagination
results_num = html_soup.find('div', class_='search-legend')
# pulled the total count of posts as the upper bound of the pages array
results_total = int(results_num.find('span', class_='totalcount').text)
# each page has 119 posts so each new page is defined as follows: s=120, s=240, s=360, and so on. So we need to step in size 120 in the np.arange function
pages = np.arange(0, results_total+1, 120)
iterations = 0
post_timing = []
post_title_texts = []
bedroom_counts = []
sqfts = []
post_links = []
post_prices = []
for page in pages:
print('Scraping page {}'.format(page))
# get request
response = get(base_url
+ "&s=" # the parameter for defining the page number
+ str(page)) # the page number in the pages array from earlier)
if throttle:
sleep_time = randint(min_scraping_delay, max_scraping_delay)
print('Waiting {} seconds'.format(sleep_time))
sleep(sleep_time)
# throw warning for status codes that are not 200
if response.status_code != 200:
warn('Request: {}; Status code: {}'.format(
requests, response.status_code))
# define the html text
page_html = BeautifulSoup(response.text, 'html.parser')
# define the posts
posts = page_html.find_all('li', class_='result-row')
# extract data item-wise
for post in posts:
if True:
# posting date
# grab the datetime element 0 for date and 1 for time
post_datetime = post.find(
'time', class_='result-date')['datetime']
post_timing.append(post_datetime)
# title text
post_title = post.find('a', class_='result-title hdrlnk')
post_title_text = post_title.text
post_title_texts.append(post_title_text)
# post link
post_link = post_title['href']
post_links.append(post_link)
# removes the \n whitespace from each side, removes the currency symbol, and turns it into an int
post_price = int(post.a.text.strip().replace(
"$", "").replace(',', ''))
post_prices.append(post_price)
if post.find('span', class_='housing') is not None:
# if the first element is accidentally square footage
if 'ft2' in post.find('span', class_='housing').text.split()[0]:
# make bedroom nan
bedroom_count = np.nan
bedroom_counts.append(bedroom_count)
# make sqft the first element
sqft = int(
post.find('span', class_='housing').text.split()[0][:-3])
sqfts.append(sqft)
# if the length of the housing details element is more than 2
elif len(post.find('span', class_='housing').text.split()) > 2:
# therefore element 0 will be bedroom count
bedroom_count = post.find(
'span', class_='housing').text.replace("br", "").split()[0]
bedroom_counts.append(bedroom_count)
# and sqft will be number 3, so set these here and append
sqft = int(
post.find('span', class_='housing').text.split()[2][:-3])
sqfts.append(sqft)
# if there is num bedrooms but no sqft
elif len(post.find('span', class_='housing').text.split()) == 2:
# therefore element 0 will be bedroom count
bedroom_count = post.find(
'span', class_='housing').text.replace("br", "").split()[0]
bedroom_counts.append(bedroom_count)
# and sqft will be number 3, so set these here and append
sqft = np.nan
sqfts.append(sqft)
else:
bedroom_count = np.nan
bedroom_counts.append(bedroom_count)
sqft = np.nan
sqfts.append(sqft)
# if none of those conditions catch, make bedroom nan, this won't be needed
else:
bedroom_count = np.nan
bedroom_counts.append(bedroom_count)
sqft = np.nan
sqfts.append(sqft)
iterations += 1
print("Page " + str(iterations) + " scraped successfully!")
eb_apts = pd.DataFrame({'date_posted': post_timing,
'post_title': post_title_texts,
'number_bedrooms': bedroom_counts,
'sqft': sqfts,
'URL': post_links,
'price': post_prices,
'date_read': datetime.now()})
return eb_apts
def backup_scrape(data: pd.DataFrame):
# Saves Pandas datatable with current datetime in file name
file_name = './backups/{}.csv'.format(datetime.now())
data.to_csv(file_name)
print("Backed up as {}".format(file_name))
def get_latest_backup() -> pd.DataFrame:
# Returns the latest backup done from the backups folder
list_of_files = glob.glob('./backups/*.csv')
latest_file = max(list_of_files, key=os.path.basename)
print('Getting latest backup {}'.format(latest_file))
return pd.read_csv(latest_file)
def clean_data(data: pd.DataFrame) -> pd.DataFrame:
# Cleans scraped data by removing listings with <$500/mo and duplicate URLs and duplicate names
# (not sure how one does duplicate URLs on craigslist but whatever)
# takes in DataTable and returns clean one
eb_apts = data.drop_duplicates(subset='URL')
eb_apts = data.drop_duplicates(subset='post_title')
eb_apts = eb_apts.drop(eb_apts[eb_apts['price'] < 500].index)
eb_apts['number_bedrooms'] = eb_apts['number_bedrooms'].apply(
lambda x: float(x))
from datetime import datetime
eb_apts['date_posted'] = pd.to_datetime(eb_apts['date_posted'])
return eb_apts
def update_listings(scraped_data: pd.DataFrame, throttle: bool = True):
# update the unique listing of apartments in the database
# if listing does not exist, add it to the database for the first time and add it's first price
# if listing does exist, update it's current price
db = TinyDB('./db/listings.json')
listings = db.table('listings')
listing = Query()
for scraped_listing in scraped_data.itertuples():
# for each listing, see if it's in the database
if listings.contains(listing.URL == scraped_listing.URL) == False:
# listing does not exist, add it to unique house listing
page = get_listing_page(scraped_listing.URL)
listings.insert({
'date_posted': str(scraped_listing.date_posted),
'post_title': scraped_listing.post_title,
'number_bedrooms': scraped_listing.number_bedrooms,
'sqft': scraped_listing.sqft,
'URL': scraped_listing.URL,
'page_html': page,
'coordinates': get_gps_coordinates(page),
'snapshots': [{
'timestamp': str(scraped_listing.date_read),
'price': scraped_listing.price
}]
})
# throttle because we are scraping GPS
if throttle:
sleep_time = randint(min_scraping_delay, max_scraping_delay)
sleep(sleep_time)
print("Inserted {} into database".format(
scraped_listing.post_title))
else:
# listing already exists, update it's last-seen time and last price
listings.update(add('snapshots', [{
'timestamp': str(scraped_listing.date_read),
'price': scraped_listing.price
}]),
listing.URL == scraped_listing.URL)
print("Updated price for {} in database".format(
scraped_listing.post_title))
def get_listing_page(url: str) -> str:
# from the URL of a craigslist post, get the listing page
response = get(url)
return response.text
def get_gps_coordinates(page: str) -> dict:
# from the page HTMl content of a craigslist post, attempt to extract the GPS coordinates
# returns dictionary of lat and lng if success, otherwise, empty dict
html_soup = BeautifulSoup(page, 'html.parser')
map_component = html_soup.find('div', {"id": "map"})
if map_component != None:
lat = float(map_component.attrs['data-latitude'])
lng = float(map_component.attrs['data-longitude'])
if lat != None and lng != None:
print("Got GPS coordinates")
return {'lat': lat, 'lng': lng}
else:
print("Could not parse GPS coordinates")
return {}
else:
print("Could not find GPS coordinates")
return {}
if __name__ == "__main__":
scraped_data = get_current_prices(base_url)
#scraped_data = get_latest_backup()
scraped_data = clean_data(scraped_data)
backup_scrape(scraped_data)
update_listings(scraped_data)
|
[
"vlad.pomogaev@gmail.com"
] |
vlad.pomogaev@gmail.com
|
edd08bcc3761d0c614fafb03a5626a68d542cc7b
|
345e2473ba375b2b0150f95dce7317bd11eda7cd
|
/app.py
|
abdc2843e2c84b611177028bf6f0aebc221415cb
|
[] |
no_license
|
Ross-Cockburn96/TestFlaskAPI
|
934911d1f2c557652ec9f9885b0ddf419e15745d
|
496c8fb59ca3392de194f12dbac0088a254bbf50
|
refs/heads/master
| 2021-10-14T08:56:05.820002
| 2019-02-03T15:45:09
| 2019-02-03T15:45:09
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,715
|
py
|
import os
from flask import Flask, request
from flask_restful import Resource, Api, reqparse
from flask_jwt import JWT, jwt_required, current_identity
from resources.user import UserRegister
from security import authenticate, identity
from resources.item import Item, ItemList
from resources.store import Store, StoreList
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get("DATABASE_URL","sqlite:///data.db")
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['PROPAGATE_EXCEPTIONS'] = True
app.secret_key = 'Ross'
api = Api(app)
jwt = JWT(app, authenticate, identity)
items = []
sales = []
class Sale(Resource):
parser2 = reqparse.RequestParser()
parser2.add_argument('item', type=str, required = True, help ="this sale field cannot be left blank")
parser2.add_argument('price', type=int, required = True, help ="this sale field cannot be left blank")
def get(self, name):
print("hello this is a test")
return{"sale" : sales}
def post(self, name):
request_data = Sale.parser2.parse_args()
for key, val in request_data.items():
print(key)
print(val)
sale = {"name" : name, "price" : request_data["price"], "item": request_data['item'] }
sales.append(sale)
return sale, 201
api.add_resource(Sale, "/sale/<string:name>")
api.add_resource(Item, "/item/<string:name>")
api.add_resource(ItemList, "/items")
api.add_resource(UserRegister, "/register")
api.add_resource(Store, "/store/<string:name>")
api.add_resource(StoreList, "/stores")
if __name__ == '__main__':
from db import db
db.init_app(app)
app.run(debug=True) # important to mention debug=True
|
[
"s1424268@ed.ac.uk"
] |
s1424268@ed.ac.uk
|
bc9ab03b12766748c663d9baccc5623ae76a946d
|
8b8639aa8b6bb24bae697640aaee580fe1367bae
|
/tonis_piip_org/settings/base.py
|
ea7d79588d85f12e8d7c8406555c1c471ac40a5e
|
[] |
no_license
|
TonisPiip/tonis_piip_org
|
11155b08701c84a7d3df7f6082930bb797467e70
|
9e569888dfa79b81498cb9496894974ab592ad43
|
refs/heads/master
| 2022-11-11T05:30:24.810591
| 2020-06-28T13:23:04
| 2020-06-28T13:23:04
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 10,373
|
py
|
"""
Django settings for tonis.piip.org project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
import os
from urllib.parse import quote
import environ
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/dev/howto/deployment/checklist/
# Build paths inside the project like this: os.path.join(SITE_ROOT, ...)
SITE_ROOT = os.path.dirname(os.path.dirname(__file__))
# Load env to get settings
ROOT_DIR = environ.Path(SITE_ROOT)
env = environ.Env()
READ_DOT_ENV_FILE = env.bool("DJANGO_READ_DOT_ENV_FILE", default=True)
if READ_DOT_ENV_FILE:
# OS environment variables take precedence over variables from .env
# By default use django.env file from project root directory
env.read_env(str(ROOT_DIR.path("django.env")))
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = env.bool("DJANGO_DEBUG", default=True)
ADMINS = (("Admins", "tonis@eggo.org"),)
MANAGERS = ADMINS
EMAIL_SUBJECT_PREFIX = "[tonis.piip.org] " # subject prefix for managers & admins
SESSION_COOKIE_NAME = "tonis_piip_org_ssid"
INSTALLED_APPS = [
# Local apps
"accounts",
"tonis_piip_org",
# CMS apps
"cms",
"treebeard",
"menus",
"sekizai",
"djangocms_admin_style",
"easy_thumbnails",
"filer",
"mptt",
"djangocms_file",
"djangocms_link",
"djangocms_picture",
"djangocms_text_ckeditor",
# Third-party apps
"django_js_reverse",
"crispy_forms",
"webpack_loader",
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.sites",
"django.contrib.messages",
"django.contrib.staticfiles",
]
MIDDLEWARE = [
"cms.middleware.utils.ApphookReloadMiddleware",
"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",
"django.middleware.locale.LocaleMiddleware",
"cms.middleware.user.CurrentUserMiddleware",
"cms.middleware.page.CurrentPageMiddleware",
"cms.middleware.toolbar.ToolbarMiddleware",
"cms.middleware.language.LanguageCookieMiddleware",
]
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [os.path.join(SITE_ROOT, "templates")],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.contrib.auth.context_processors.auth",
"django.template.context_processors.debug",
"django.template.context_processors.i18n",
"django.template.context_processors.media",
"django.template.context_processors.request",
"django.template.context_processors.static",
"django.template.context_processors.tz",
"django.contrib.messages.context_processors.messages",
"django.template.context_processors.csrf",
"sekizai.context_processors.sekizai",
"cms.context_processors.cms_settings",
"django_settings_export.settings_export",
],
},
},
]
THUMBNAIL_PROCESSORS = (
"filer.thumbnail_processors.scale_and_crop_with_subject_location",
)
CMS_PAGE_CACHE = env.str("DJANGO_CMS_PAGE_CACHE", default=True)
CMS_PLACEHOLDER_CACHE = env.str("DJANGO_CMS_PLACEHOLDER_CACHE", default=True)
CMS_PLUGIN_CACHE = env.str("DJANGO_CMS_PLUGIN_CACHE", default=True)
CMS_TEMPLATES = (("cms_main.html", "Main template"),)
# Database
DATABASES = {
# When using DJANGO_DATABASE_URL, unsafe characters in the url should be encoded.
# See: https://django-environ.readthedocs.io/en/latest/#using-unsafe-characters-in-urls
"default": env.db_url(
"DJANGO_DATABASE_URL",
default="psql://{user}:{password}@{host}:{port}/{name}?sslmode={sslmode}".format(
host=env.str("DJANGO_DATABASE_HOST", default="postgres"),
port=env.int("DJANGO_DATABASE_PORT", default=5432),
name=quote(env.str("DJANGO_DATABASE_NAME", default="tonis_piip_org")),
user=quote(env.str("DJANGO_DATABASE_USER", default="tonis_piip_org")),
password=quote(env.str("DJANGO_DATABASE_PASSWORD", default="tonis_piip_org")),
sslmode=env.str("DJANGO_DATABASE_SSLMODE", "disable"),
),
)
}
# Redis config (used for caching and celery)
REDIS_URL = env.str("DJANGO_REDIS_URL", default="redis://redis:6379/1")
REDIS_CELERY_URL = env.str("DJANGO_REDIS_CELERY_URL", default=REDIS_URL)
# Set your Celerybeat tasks/schedule here
# Rest of Celery configuration lives in celery_settings.py
CELERYBEAT_SCHEDULE = {
"default-task": {
# TODO: Remove the default task after confirming that Celery works.
"task": "tonis_piip_org.tasks.default_task",
"schedule": 5,
},
}
# Caching
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": REDIS_URL,
"OPTIONS": {"CLIENT_CLASS": "django_redis.client.DefaultClient"},
}
}
# Internationalization
LANGUAGE_CODE = "en"
LANGUAGES = (
("en", "English"),
("et", "Eesti keel"),
)
LOCALE_PATHS = ("locale",)
TIME_ZONE = "UTC"
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Media files (user uploaded/site generated)
MEDIA_ROOT = env.str("DJANGO_MEDIA_ROOT", default="/files/media")
MEDIA_URL = env.str("DJANGO_MEDIA_URL", default="/media/")
MEDIAFILES_LOCATION = env.str("DJANGO_MEDIAFILES_LOCATION", default="media")
# In staging/prod we use S3 for file storage engine
AWS_ACCESS_KEY_ID = "<unset>"
AWS_SECRET_ACCESS_KEY = "<unset>"
AWS_STORAGE_BUCKET_NAME = "<unset>"
AWS_DEFAULT_ACL = "public-read"
AWS_IS_GZIPPED = True
AWS_S3_FILE_OVERWRITE = False
AWS_S3_REGION_NAME = "eu-central-1"
AWS_S3_SIGNATURE_VERSION = "s3v4"
# Only set DJANGO_AWS_S3_ENDPOINT_URL if it's defined in environment, fallback to default value in other cases
# Useful for s3 provided by other parties than AWS, like DO.
if env.str("DJANGO_AWS_S3_ENDPOINT_URL", default=""):
AWS_S3_ENDPOINT_URL = env.str("DJANGO_AWS_S3_ENDPOINT_URL")
# Should be True unless using s3 provider that doesn't support it (like DO)
AWS_S3_ENCRYPTION = env.bool("DJANGO_AWS_S3_ENCRYPTION", default=True)
# This helps get around a bug in boto3 (https://github.com/boto/boto3/issues/1644)
# Details in https://github.com/jschneier/django-storages/issues/649
AWS_S3_ADDRESSING_STYLE = "path"
AWS_S3_OBJECT_PARAMETERS = {
"CacheControl": "max-age=1209600", # 2 weeks in seconds
}
# Static files (CSS, JavaScript, images)
STATIC_ROOT = "/files/assets"
STATIC_FILES_ROOT = "app"
STATIC_URL = env.str("DJANGO_STATIC_URL", default="/static/")
STATICFILES_DIRS = (
os.path.join(STATIC_FILES_ROOT, "static"),
os.path.join(STATIC_FILES_ROOT, "webapp", "build"),
)
STATICFILES_FINDERS = (
"django.contrib.staticfiles.finders.FileSystemFinder",
"django.contrib.staticfiles.finders.AppDirectoriesFinder",
)
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env.str("DJANGO_SECRET_KEY", default="dummy key")
AUTH_USER_MODEL = "accounts.User"
# Static site url, used when we need absolute url but lack request object, e.g. in email sending.
SITE_URL = env.str("DJANGO_SITE_URL", default="http://127.0.0.1:8000")
ALLOWED_HOSTS = env.list("DJANGO_ALLOWED_HOSTS", default=[])
SITE_ID = 1
ROOT_URLCONF = "tonis_piip_org.urls"
WSGI_APPLICATION = "tonis_piip_org.wsgi.application"
LOGIN_REDIRECT_URL = "/"
LOGIN_URL = "login"
LOGOUT_REDIRECT_URL = "login"
# Crispy-forms
CRISPY_TEMPLATE_PACK = "bootstrap4"
# Email config
DEFAULT_FROM_EMAIL = "tonis.piip.org <info@tonis.piip.org>"
SERVER_EMAIL = "tonis.piip.org server <server@tonis.piip.org>"
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST = "mailhog"
EMAIL_PORT = 1025
EMAIL_HOST_USER = ""
EMAIL_HOST_PASSWORD = ""
# Base logging config. Logs INFO and higher-level messages to console. Production-specific additions are in
# production.py.
# Notably we modify existing Django loggers to propagate and delegate their logging to the root handler, so that we
# only have to configure the root handler.
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"default": {
"format": "%(asctime)s [%(levelname)s] %(name)s:%(lineno)d %(funcName)s - %(message)s"
},
},
"filters": {"require_debug_false": {"()": "django.utils.log.RequireDebugFalse"}},
"handlers": {"console": {"class": "logging.StreamHandler", "formatter": "default"}},
"loggers": {
"": {"handlers": ["console"], "level": "INFO"},
"django": {"handlers": [], "propagate": True},
"django.request": {"handlers": [], "propagate": True},
"django.security": {"handlers": [], "propagate": True},
},
}
TEST_RUNNER = "django.test.runner.DiscoverRunner"
# Disable a few system checks. Careful with these, only silence what your really really don't need.
# TODO: check if this is right for your project.
SILENCED_SYSTEM_CHECKS = [
"security.W001", # we don't use SecurityMiddleware since security is better applied in nginx config
]
# Default values for sentry
RAVEN_BACKEND_DSN = env.str(
"DJANGO_RAVEN_BACKEND_DSN", default="https://TODO:TODO@sentry.thorgate.eu/TODO"
)
RAVEN_PUBLIC_DSN = env.str(
"DJANGO_RAVEN_PUBLIC_DSN", default="https://TODO@sentry.thorgate.eu/TODO"
)
RAVEN_CONFIG = {"dsn": RAVEN_BACKEND_DSN}
WEBPACK_LOADER = {
"DEFAULT": {
"BUNDLE_DIR_NAME": "",
"STATS_FILE": os.path.join(STATIC_FILES_ROOT, "webapp", "webpack-stats.json"),
}
}
PROJECT_TITLE = "tonis.piip.org"
# All these settings will be made available to javascript app
SETTINGS_EXPORT = [
"DEBUG",
"SITE_URL",
"STATIC_URL",
"RAVEN_PUBLIC_DSN",
"PROJECT_TITLE",
]
# django-js-reverse
JS_REVERSE_JS_VAR_NAME = "reverse"
JS_REVERSE_JS_GLOBAL_OBJECT_NAME = "DJ_CONST"
JS_REVERSE_EXCLUDE_NAMESPACES = ["admin", "djdt"]
|
[
"tonis.piip@gmail.com"
] |
tonis.piip@gmail.com
|
d1f8baf07db8beeae1926ac79ecc73574cef958b
|
d748d2b46d5f043bcf8539c5d809972fc8c1f128
|
/dogehouse/entities.py
|
fde1162b98278bc67acabc0dddf9af4610d8cdee
|
[
"MIT"
] |
permissive
|
absucc/dogehouse.py
|
7ae71c69ecad5782fa9b27266ab7ec5ad5a2c02e
|
9fd9feb7459ad3c47754bfc83f21a97accb94cc0
|
refs/heads/main
| 2023-03-21T21:46:59.631039
| 2021-03-21T20:48:19
| 2021-03-21T20:48:19
| 350,133,089
| 0
| 0
|
MIT
| 2021-03-21T22:13:59
| 2021-03-21T22:13:58
| null |
UTF-8
|
Python
| false
| false
| 5,542
|
py
|
# -*- coding: utf-8 -*-
# MIT License
# Copyright (c) 2021 Arthur
# 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.
from .utils import Repr
from typing import List, Dict
from dateutil.parser import isoparse
class BaseUser(Repr):
def __init__(self, id: str, username: str, displayname: str, avatar_url: str):
self.id = id
self.username = username
self.displayname = displayname
self.avatar_url = avatar_url
self.mention = f"@{username}"
def __str__(self):
return self.username
@staticmethod
def from_dict(data: dict):
"""
Parses a BaseUser object from a dictionary.
Args:
data (dict): The parsed json websocket response.
Returns:
BaseUser: A parsed BaseUser object which contains the data from the dictionary.
"""
return BaseUser(data.get("userId"), data.get("username"), data.get("displayName"), data.get("avatarUrl"))
class User(BaseUser, Repr):
def __init__(self, id: str, username: str, displayname: str, avatar_url: str, bio: str, last_seen: str):
super().__init__(id, username, displayname, avatar_url)
self.bio = bio
self.last_seen = isoparse(last_seen)
def __str__(self):
return self.username
@staticmethod
def from_dict(data: dict):
"""
Parses a User object from a dictionary.
Args:
data (dict): The parsed json websocket response.
Returns:
User: A parsed User object which contains the data from the dictionary.
"""
return User(data.get("id"), data.get("username"), data.get("displayname"), data.get("avatarUrl"), data.get("bio"), data.get("lastOnline"))
class UserPreview(Repr):
def __init__(self, id: str, displayname: str, num_followers: int):
self.id = id
self.displayname = displayname
self.num_followers = num_followers
def __str__(self):
return self.displayname
@staticmethod
def from_dict(data: dict):
"""
Parses a UserPreview object from a dictionary.
Args:
data (dict): The parsed json websocket response.
Returns:
UserPreview: A parsed userpreview object which contains the data from the dictionary.
"""
return UserPreview(data["id"], data["displayName"], data["numFollowers"])
class Room(Repr):
def __init__(self, id: str, creator_id: str, name: str, description: str, created_at: str, is_private: bool, count: int, users: List[UserPreview]):
self.id = id
self.creator_id = creator_id
self.name = name
self.description = description
self.created_at = isoparse(created_at)
self.is_private = is_private
self.count = count
self.users = users
@staticmethod
def from_dict(data: dict):
"""
Parses a Room object from a dictionary.
Args:
data (dict): The parsed json websocket response.
Returns:
Room: A parsed room object which contains the data from the dictionary.
"""
return Room(data["id"], data["creatorId"], data["name"], data["description"], data["inserted_at"], data["isPrivate"], data["numPeopleInside"],
list(map(UserPreview.from_dict, data["peoplePreviewList"])))
class Message(Repr):
def __init__(self, id: str, tokens: List[Dict[str, str]], is_wisper: bool, created_at: str, author: BaseUser):
self.id = id
self.tokens = tokens
self.is_wisper = is_wisper
self.created_at = isoparse(created_at)
self.author = author
self.content = self.__convert_tokens()
def __str__(self):
return self.content
def __convert_tokens(self) -> str:
"""Converts the tokens to a proper message"""
content = []
for token in self.tokens:
if token["t"] == "mention":
content.append(f"@{token['v']}")
else:
content.append(token["v"])
return " ".join(content)
@staticmethod
def from_dict(data: dict):
"""
Parses a Message object from a dictionary.
Args:
data (dict): The parsed json websocket response.
Returns:
Message: A parsed message object which contains the data from the dictionary.
"""
return Message(data["id"], data["tokens"], data["isWhisper"], data["sentAt"], BaseUser.from_dict(data))
|
[
"mail@arthurdw.com"
] |
mail@arthurdw.com
|
16c25deb559d7a5ab960d483c8b7b5eb8b8ef69c
|
3ea2f346f2e38bc0e742b5994e2757bfde9bf7f2
|
/qlearningAgents.py
|
2b1f67e6cffa0c68851a41accb51c48e131d8a0a
|
[] |
no_license
|
Ubastic/PacMan
|
2377a3fca3e8986ab56d06d52f448183c424c047
|
1df7b0576e740e8b288845e819b0c8542bbf396c
|
refs/heads/main
| 2022-12-27T05:03:43.254876
| 2020-10-12T04:07:13
| 2020-10-12T04:07:13
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 8,254
|
py
|
# qlearningAgents.py
# ------------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).
from game import *
from learningAgents import ReinforcementAgent
from featureExtractors import *
import random,util,math
import numpy as np
#import DQNPacman
#from DQNPacman import DQN
import torch
import torch.nn as nn
import torch.nn.functional as func
import torch.optim as optim
class QLearningAgent(ReinforcementAgent):
"""
Q-Learning Agent
Functions you should fill in:
- computeValueFromQValues
- computeActionFromQValues
- getQValue
- getAction
- update
Instance variables you have access to
- self.epsilon (exploration prob)
- self.alpha (learning rate)
- self.discount (discount rate)
Functions you should use
- self.getLegalActions(state)
which returns legal actions for a state
"""
def __init__(self, **args):
"You can initialize Q-values here..."
ReinforcementAgent.__init__(self, **args)
"*** YOUR CODE HERE ***"
self.qvalues = Counter() ##q values start with all zero
self.epsilon = args['epsilon']
self.alpha = args['alpha']
self.discount = args['gamma']
def getQValue(self, state, action):
"""
Returns Q(state,action)
Should return 0.0 if we have never seen a state
or the Q node value otherwise
"""
"*** YOUR CODE HERE ***"
return self.qvalues[(state, action)]
util.raiseNotDefined()
def computeValueFromQValues(self, state):
"""
Returns max_action Q(state,action)
where the max is over legal actions. Note that if
there are no legal actions, which is the case at the
terminal state, you should return a value of 0.0.
"""
"*** YOUR CODE HERE ***"
tempQ = Counter()
for a in self.getLegalActions(state):
tempQ[(state, a)] = self.getQValue(state, a)
if len(list(tempQ)) > 0:
maxPair = tempQ.argMax()
return tempQ[maxPair]
else: return 0
# print(maxPair)
#return tempQ[maxPair]
# util.raiseNotDefined()
def computeActionFromQValues(self, state):
"""
Compute the best action to take in a state. Note that if there
are no legal actions, which is the case at the terminal state,
you should return None.
"""
"*** YOUR CODE HERE ***"
tempQ = Counter()
v = self.computeValueFromQValues(state)
for a in self.getLegalActions(state):
if self.getQValue(state, a) == v:
return a
return None
util.raiseNotDefined()
def getAction(self, state):
"""
Compute the action to take in the current state. With
probability self.epsilon, we should take a random action and
take the best policy action otherwise. Note that if there are
no legal actions, which is the case at the terminal state, you
should choose None as the action.
HINT: You might want to use util.flipCoin(prob)
HINT: To pick randomly from a list, use random.choice(list)
"""
# Pick Action
legalActions = self.getLegalActions(state)
action = None
"*** YOUR CODE HERE ***"
if legalActions == []: return action
if util.flipCoin(self.epsilon): return random.choice(legalActions)
else: return self.computeActionFromQValues(state)
util.raiseNotDefined()
return action
def update(self, state, action, nextState, reward):
"""
The parent class calls this to observe a
state = action => nextState and reward transition.
You should do your Q-Value update here
NOTE: You should never call this function,
it will be called on your behalf
"""
"*** YOUR CODE HERE ***"
#bestAction = self.computeActionFromQValues(nextState)
nextValue = self.computeValueFromQValues(nextState)
qval = self.getQValue(state, action)
self.qvalues[(state, action)] = qval + self.alpha * (reward + self.discount * nextValue - qval)
#util.raiseNotDefined()
def getPolicy(self, state):
return self.computeActionFromQValues(state)
def getValue(self, state):
return self.computeValueFromQValues(state)
class PacmanQAgent(QLearningAgent):
"Exactly the same as QLearningAgent, but with different default parameters"
def __init__(self, epsilon=0.05,gamma=0.8,alpha=0.2, numTraining=0, **args):
"""
These default parameters can be changed from the pacman.py command line.
For example, to change the exploration rate, try:
python pacman.py -p PacmanQLearningAgent -a epsilon=0.1
alpha - learning rate
epsilon - exploration rate
gamma - discount factor
numTraining - number of training episodes, i.e. no learning after these many episodes
"""
args['epsilon'] = epsilon
args['gamma'] = gamma
args['alpha'] = alpha
args['numTraining'] = numTraining
self.index = 0 # This is always Pacman
QLearningAgent.__init__(self, **args)
def getAction(self, state):
"""
Simply calls the getAction method of QLearningAgent and then
informs parent of action for Pacman. Do not change or remove this
method.
"""
action = QLearningAgent.getAction(self,state)
self.doAction(state,action)
return action
class ApproximateQAgent(PacmanQAgent):
"""
ApproximateQLearningAgent
You should only have to overwrite getQValue
and update. All other QLearningAgent functions
should work as is.
"""
def __init__(self, extractor='IdentityExtractor', **args):
self.featExtractor = util.lookup(extractor, globals())()
PacmanQAgent.__init__(self, **args)
self.weights = util.Counter()
# self.qvalues = util.Counter()
def getWeights(self):
return self.weights
def getQValue(self, state, action):
"""
Should return Q(state,action) = w * featureVector
where * is the dotProduct operator
"""
"*** YOUR CODE HERE ***"
return self.getWeights() * self.featExtractor.getFeatures(state, action)
# util.raiseNotDefined()
def update(self, state, action, nextState, reward):
"""
Should update your weights based on transition
"""
"*** YOUR CODE HERE ***"
feats = self.featExtractor.getFeatures(state, action)
diff = reward + self.discount * (self.computeValueFromQValues(nextState)) - self.getQValue(state, action)
featKeys = list(feats)
incfeat = util.Counter()
for k in featKeys:
incfeat[k] = feats[k] * self.alpha * diff
self.weights += incfeat
self.qvalues[(state, action)] = self.getWeights() * self.featExtractor.getFeatures(state, action)
# print("weights: ", self.weights)
# print("state:", state)
#print("action:", action)
#util.raiseNotDefined()
def final(self, state):
"Called at the end of each game."
# call the super-class final method
PacmanQAgent.final(self, state)
# did we finish training?
if self.episodesSoFar == self.numTraining:
# you might want to print your weights here for debugging
"*** YOUR CODE HERE ***"
# print(self.getWeights())
pass
|
[
"noreply@github.com"
] |
Ubastic.noreply@github.com
|
5b1416ac26ffdf9b7c0cc467a06057c5a90b5fad
|
cd4af3cd0d7dc87410085de736ddc8260689da75
|
/gif_gen.py
|
97adb87406c4ab981361203a04f3c63c3550f414
|
[] |
no_license
|
ttruty/AmongUsDiscordBot
|
fb8f125610100909fb6d177678e5f4a5a35a9307
|
4d8e21ad323195261d1870af20df69223c454884
|
refs/heads/master
| 2022-12-26T04:37:29.256649
| 2020-10-11T23:28:25
| 2020-10-11T23:28:25
| 303,231,050
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 747
|
py
|
import os
import random
import giphy_client
from giphy_client.rest import ApiException
from pprint import pprint
GIPHY_KEY = os.environ['GIPHY_KEY']
# Create an instance of the API class
api_instance = giphy_client.DefaultApi()
config = {
'api_key': GIPHY_KEY, # Giphy API Key,
'limit': 20,
'rating': 'r'
}
def get_gif(message):
try:
api_response = api_instance.gifs_search_get(config['api_key'], limit=config['limit'], rating=config['rating'],
q=message)
lst = list(api_response.data)
gif = random.choices(lst)
return gif[0].url
except ApiException as e:
print("Exception when calling DefaultApi->gifs_trending_get: %s\n" % e)
|
[
"ttruty@gmail.com"
] |
ttruty@gmail.com
|
433ebb1663057ded240e28cf383e3dff334b1db9
|
0d894d8b48c7169684f8accd25180211a0ecabdf
|
/heruko.py
|
4d5d79eb08d764ea0e3be9b0803c0b554caae73d
|
[] |
no_license
|
itsdanny58/dojrrp
|
248e8512fbac66507da2e71cf624da002d1289ec
|
f4ac204b69806e2c510e7c692f08d99cb6e84f78
|
refs/heads/master
| 2021-10-10T01:55:10.529330
| 2019-01-06T05:42:30
| 2019-01-06T05:42:30
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 585
|
py
|
import discord
from discord.ext.commands import bot
from discord.ext import commands
import asyncio
import time
import os
Client = discord.Client()
Client = commands.Bot(command_prefix = ".")
@Client.event
async def on_ready():
print("Thanks")
await client.change_presence(game=discord.Game(name="videos"))
@Client.event
async def on_message(message):
if message.content.startswith('.hello'):
msg = 'Hello {0.author.mention} How are you'.format(message)
await client.send_message(message.channel, msg)
client.run(os.getenv('TOKEN'))
|
[
"noreply@github.com"
] |
itsdanny58.noreply@github.com
|
fa070402dffb6777ac4fda53703d2d5d0bb524cf
|
689c695db0ec37d2420fbe24684a1ca0d2d8f297
|
/day_20_1.py
|
d9bf3dc61f3fc56064c8473fc2878fddab878226
|
[] |
no_license
|
moxon6/advent-of-code-2020
|
d2008d5ebe9078d9fd04acffb366859a04ffccb8
|
c17b00c5561ff7089ec0a4c93822c0044a749fdd
|
refs/heads/master
| 2023-02-06T08:45:38.650424
| 2020-12-27T13:54:05
| 2020-12-27T13:54:05
| 320,891,033
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,947
|
py
|
import numpy as np
from collections import namedtuple
Tile = namedtuple('Tile', ['id', 'data'])
def parse_tile_section(tile_sections):
title, *data = tile_sections.splitlines()
tile_id = int(title.strip("Tile :"))
return Tile(
id=tile_id,
data=np.array([list(line) for line in data])
)
def matches_right(arr1, arr2):
return (arr1[:, -1] == arr2[:, 0]).all()
def matches_left(arr1, arr2):
return matches_right(arr2, arr1)
def matches_down(arr1, arr2):
return (arr1[-1, :] == arr2[0, :]).all()
def matches_up(arr1, arr2):
return matches_down(arr2, arr1)
def make_transform(flip, rot):
def op(arr):
if flip:
arr = np.flip(arr, axis=1)
return np.rot90(arr, k=rot)
return op
def transforms(arr):
for flip in [True, False]:
for rot in [0, 1, 2, 3]:
yield make_transform(flip, rot)(arr)
with open("inputs/day20.txt") as f:
tile_sections = f.read().split("\n\n")
tiles = [parse_tile_section(section) for section in tile_sections]
def get_adjacent_tiles(tile):
adjacents = []
for match_direction in [matches_left, matches_right, matches_up, matches_down]:
def get_adjacent_in_direction():
for candidate in tiles:
if (tile is candidate):
continue
for transform in transforms(candidate.data):
if match_direction(tile.data, transform):
return candidate
adjacent = get_adjacent_in_direction()
if adjacent is not None:
adjacents.append(adjacent)
return adjacents
total = 1
adjacents = {
tile.id: get_adjacent_tiles(tile)
for tile in tiles
}
total = np.prod([
tile_id for tile_id, adjacent_tiles in adjacents.items() if len(adjacent_tiles) == 2
])
print(total)
|
[
"moxon6@googlemail.com"
] |
moxon6@googlemail.com
|
8364fbea315acbc88ab8990b88a742bcde2932e4
|
5c55f5753d679deb742406112d8fa1ac0f4a3a45
|
/mysite/polls/tests.py
|
608e5ff35eafe04d082edfe3859d430333d10b59
|
[] |
no_license
|
avoevodin/django_tutorial
|
4fcd4d1c683146c80809ed8f890e621b939553a9
|
cafcae75cac2a5b1d09d0c5c68e687ed6615a7f3
|
refs/heads/master
| 2023-04-07T01:45:19.279078
| 2021-03-22T15:44:04
| 2021-03-22T15:44:04
| 347,059,877
| 1
| 0
| null | 2021-03-22T15:44:05
| 2021-03-12T12:32:57
|
Python
|
UTF-8
|
Python
| false
| false
| 11,682
|
py
|
import datetime
from django.test import TestCase
from django.utils import timezone
from django.urls import reverse
from django.utils.html import escape
from .models import Question, Choice
def create_question(question_text, days):
"""
Create a question with the given 'question_text' and published the
given number of 'days' offset to now (negative for questions published
in the past, positive for questions that have yet to be published).
"""
time = timezone.now() + datetime.timedelta(days=days)
return Question.objects.create(question_text=question_text, pub_date=time)
def create_choice(question, choice_text, votes=0):
return Choice.objects.create(
question=question,
choice_text=choice_text,
votes=votes
)
class QuestionModelTests(TestCase):
def test_was_published_recently_with_future_question(self):
"""
was_published_recently() returns False for questions whose pub_date
is in the future.
"""
time = timezone.now() + datetime.timedelta(days=30)
future_question = Question(pub_date=time)
self.assertIs(future_question.was_published_recently(), False)
def test_was_published_recently_with_old_question(self):
"""
was_published_recently() returns False for questions whose pub_date
is older than one day.
"""
time = timezone.now() - datetime.timedelta(days=1, seconds=1)
old_question = Question(pub_date=time)
self.assertIs(old_question.was_published_recently(), False)
def test_was_published_recently_with_recent_question(self):
"""
was_published_recently() returns True for questions whose pub_date
is within the last day.
"""
time = timezone.now() \
- datetime.timedelta(hours=23, minutes=59, seconds=59)
recent_question = Question(pub_date=time)
self.assertIs(recent_question.was_published_recently(), True)
def test_model_str(self):
test_question = create_question('Test question', days=-5)
self.assertEqual(
test_question.__str__(),
"{}: {}".format(test_question.id, test_question.question_text)
)
def test_model_repr(self):
test_question = create_question('Test question', days=-5)
self.assertEqual(
test_question.__repr__(),
test_question.question_text
)
class ChoiceModelTests(TestCase):
def test_model_str(self):
test_choice = create_choice(
create_question('Test question.', days=-5),
'Choice text.'
)
self.assertEqual(
test_choice.__str__(),
"{}: {} ({})".format(
test_choice.question, test_choice.choice_text,
test_choice.id
))
class QuestionIndexViewTests(TestCase):
def test_no_questions(self):
"""
If no questions exist, an appropriate message is displayed.
"""
response = self.client.get(reverse('polls:index'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, "No polls are available.")
self.assertQuerysetEqual(response.context['latest_question_list'], [])
def test_past_question(self):
"""
Question with a pub_date in the past are displayed on the
index page.
"""
past_question = create_question(question_text="Past question.", days=-30)
create_choice(past_question, 'Choice text.')
response = self.client.get(reverse('polls:index'))
self.assertQuerysetEqual(
response.context['latest_question_list'],
['Past question.']
)
def test_future_question(self):
"""
Questions with a pub_date in the future aren't displayed on the
index page.
"""
future_question = create_question(question_text="Future question.", days=30)
create_choice(future_question, choice_text='Choice text.')
response = self.client.get(reverse('polls:index'))
self.assertContains(response, "No polls are available.")
self.assertQuerysetEqual(response.context['latest_question_list'], [])
def test_future_question_and_past_question(self):
"""
Even if both past and future questions exist, only past questions
are displayed.
"""
past_question = create_question(question_text="Past question.", days=-30)
create_choice(past_question, 'Past question choice.')
future_question = create_question(question_text="Future question.", days=30)
create_choice(future_question, 'Future question choice.')
response = self.client.get(reverse('polls:index'))
self.assertQuerysetEqual(
response.context['latest_question_list'],
['Past question.']
)
def test_two_past_questions(self):
"""
The questions index page may display multiple questions.
"""
past_question_1 = create_question(question_text='Past question 1.', days=-20)
create_choice(past_question_1, 'Past question 1 choice.')
past_question_2 = create_question(question_text='Past question 2.', days=-24)
create_choice(past_question_2, 'Past question 2 choice.')
response = self.client.get(reverse('polls:index'))
self.assertQuerysetEqual(
response.context['latest_question_list'],
['Past question 1.', 'Past question 2.']
)
def test_three_past_questions_one_without_choices(self):
"""
The questions index page may display multiple questions.
There will be only questions with at least one choice.
"""
past_question_1 = create_question(
question_text='Past question 1.',
days=-5
)
create_choice(past_question_1, 'Past question 1 choice.')
past_question_2 = create_question(
question_text='Past question 2.',
days=-6
)
create_choice(past_question_2, 'Past question 2 choice.')
create_question(
question_text='Past question 3.',
days=-7
)
response = self.client.get(reverse('polls:index'))
self.assertQuerysetEqual(
response.context['latest_question_list'],
['Past question 1.', 'Past question 2.']
)
def test_one_past_question_without_choices(self):
"""
If no questions with at least on choice exist,
an appropriate message is displayed.
"""
response = self.client.get(reverse('polls:index'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, "No polls are available.")
self.assertQuerysetEqual(response.context['latest_question_list'], [])
class QuestionDetailViewTests(TestCase):
def test_future_question(self):
"""
The detail view of a question with a pub_date in the future
returns a 404 not found.
"""
future_question = create_question(question_text='Future question.', days=5)
create_choice(future_question, 'Choice text.')
url = reverse('polls:detail', args=(future_question.id,))
response = self.client.get(url)
self.assertEqual(response.status_code, 404)
def test_past_question(self):
"""
The detail view of a question with a pub_date in the past
displays the question's text.
"""
past_question = create_question(question_text='Past Question.', days=-5)
create_choice(past_question, 'Choice text')
url = reverse('polls:detail', args=(past_question.id,))
response = self.client.get(url)
self.assertContains(response, past_question.question_text)
def test_past_question_without_choices(self):
"""
The detail view of a question with a pub_date in the past
but without any choices returns a 404 not found.
"""
past_question = create_question(question_text='Past Question.', days=-5)
url = reverse('polls:detail', args=(past_question.id,))
response = self.client.get(url)
self.assertEqual(response.status_code, 404)
class QuestionResultsViewTests(TestCase):
def test_future_question(self):
"""
The results view of a question with a pub_date in the future
returns a 404 not found.
"""
future_question = create_question(question_text='Future question.', days=5)
create_choice(future_question, 'Choice text.')
url = reverse('polls:results', args=(future_question.id,))
response = self.client.get(url)
self.assertEqual(response.status_code, 404)
def test_past_question(self):
"""
The results view of a question with a pub_date in the past
returns the question vote results
"""
past_question = create_question(question_text='Past question.', days=-5)
create_choice(past_question, 'Choice text')
url = reverse('polls:results', args=(past_question.id,))
response = self.client.get(url)
self.assertContains(response, past_question.question_text)
def test_past_question_without_choices(self):
"""
The results view of a question with a pub_date in the past
but without any choices returns a 404 not found.
"""
past_question = create_question(question_text='Past Question.', days=-5)
url = reverse('polls:results', args=(past_question.id,))
response = self.client.get(url)
self.assertEqual(response.status_code, 404)
class QuestionResultsVotesViewTests(TestCase):
def test_post_vote_for_existed_question(self):
"""
The results view of voted question displays increased
value in the selected choice. Another choices will not
be increased.
"""
choice_1_initial_votes = 10
choice_2_initial_votes = 100
test_question = create_question(question_text='Test question.', days=-5)
test_question_choice_1 = create_choice(
test_question,
choice_text='Test question choice 1.',
votes=choice_1_initial_votes
)
test_question_choice_2 = create_choice(
test_question,
choice_text='Test question choice 2.',
votes=choice_2_initial_votes
)
response = self.client.post(
reverse(
'polls:vote',
args=(test_question.id,)
),
{
'choice': test_question_choice_1.id,
}
)
test_question_choice_1.refresh_from_db()
test_question_choice_2.refresh_from_db()
self.assertRedirects(response, reverse('polls:results', args=(test_question.id,)), status_code=302)
self.assertEqual(response.url, reverse('polls:results', args=(test_question.id,)))
self.assertEqual(choice_1_initial_votes + 1, test_question_choice_1.votes)
self.assertEqual(choice_2_initial_votes, test_question_choice_2.votes)
def test_post_vote_for_not_excited_choice(self):
"""
The results view of voted question displays
'You didn't select a choice.'
"""
test_question = create_question('Test question.', days=-5)
response = self.client.post(
reverse(
'polls:vote',
args=(test_question.id,)
),
{
'choice': 0,
}
)
self.assertContains(response, escape("You didn't select a choice."))
|
[
"avoevodin8888@gmail.com"
] |
avoevodin8888@gmail.com
|
4c73f861c6104b1d38e421440185919342e74b95
|
49e0f4c64b17e456165a98cb52107991bf0d7a48
|
/Material/Day-4/python-cgi/newcgi/checkpost.py
|
56a856c6b21cba3cd9f570fb94085237000b58ed
|
[] |
no_license
|
vzkrish/Python
|
3ab315f5f611d9921d99be3f846d159720853f47
|
192d7d17b99612d213c47c48ee10a6250e38d871
|
refs/heads/master
| 2020-04-07T05:34:29.137697
| 2018-03-07T05:49:33
| 2018-03-07T05:49:33
| 124,172,683
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 373
|
py
|
#! c:\python27\python.exe
print "Content-type:text/html\r\n\r\n"
print '<html>'
print '<form action="/cgi-bin/checkbox.py" method="POST" target="_blank">'
print '<input type="checkbox" name="maths" value="on" /> Maths'
print '<input type="checkbox" name="physics" value="on" /> Physics'
print '<input type="submit" value="Select Subject" />'
print '</form>'
print '</html>'
|
[
"krajubh@gmail.com"
] |
krajubh@gmail.com
|
53e1a51c0286c6ef1201b948532fc3d6c385454f
|
8f15a0736dddc22944c0c8914521d9840514abd8
|
/main.py
|
6387aefe0ccb921cdce21378d90e768a1dfb276c
|
[] |
no_license
|
basic-maths-exercises/numbers-4
|
4ea70c51144d6aadca828792fe0150ddfd9bad44
|
a5be8a5589d42287f20d67e890176c353596723a
|
refs/heads/main
| 2023-03-02T08:03:11.777605
| 2021-02-02T16:22:13
| 2021-02-02T16:22:13
| 316,498,092
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 156
|
py
|
import numpy as np
def getBinary( N ) :
# Your code goes here
for i in range(16) :
print("The binary representation of", i, "is", getBinary(i) )
|
[
"noreply@github.com"
] |
basic-maths-exercises.noreply@github.com
|
7b8bcecabf1e53d27ba468254db1d733c75364cc
|
ad45b7fc2b42b72ad9bd70f27f90577048aadd40
|
/move zeroes.py
|
0d03d661268b43776a6425f38e065c57f6f0db8e
|
[] |
no_license
|
5h4rp/leetcode-practice
|
e333d6496eef365ec3874e47c27b51cc4bc37a54
|
ea8fb61de2c2215ec58e4b95c404c17a2314d880
|
refs/heads/master
| 2023-06-28T18:39:39.888399
| 2021-07-19T21:27:07
| 2021-07-19T21:27:07
| 387,598,309
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 679
|
py
|
# Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
# Example:
# Input: [0,1,0,3,12]
# Output: [1,3,12,0,0]
# Note:
# You must do this in-place without making a copy of the array.
# Minimize the total number of operations.
l = list(map(int, input().split()))
def moveZeroes(nums):
"""
Do not return anything, modify nums in-place instead.
"""
# nums.sort(key=lambda x: 2 if x==0 else 1)
n = len(nums)
nxt = 0
for i in nums:
if i != 0:
nums[nxt] = i
nxt += 1
for j in range(nxt, n):
nums[j] = 0
moveZeroes(l)
print(l)
|
[
"ajayender@live.in"
] |
ajayender@live.in
|
5d4caef210e62617cabc1e940448a65e230b8c8c
|
a3d956e71c3186688c1eb895157810bd821829cd
|
/catkin_ws/src/Onboard-SDK-ROS-3.2/dji_sdk_demo/script/Atmotube/main.py
|
78f421e07d12aeaa4a04c679f5714bea68b98ffb
|
[] |
no_license
|
lipor/MatricePyROS
|
885e09b46637703c031746dd39bdc628c2899669
|
b76b2eab4db49243f892671614512924c9bd74f6
|
refs/heads/master
| 2021-08-28T00:21:15.524791
| 2021-08-10T21:07:25
| 2021-08-10T21:07:25
| 196,454,902
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,135
|
py
|
#!/usr/bin/env python
import rospy
from dji_sdk.dji_drone import DJIDrone
from std_msgs.msg import String
import dji_sdk.msg
import time
import sys
import math
import numpy as np
import datetime
import threading
import atmotube_scanner
import gaussiantest
# A program for retrieving data from an Atmotube air quality sensor (through Bluetooth LE) and GPS data from a DJI Matrice 100 (with ROS), plotting it on a map, and performing a Gaussian Process Regression on the data.
#main.py contains the code to retrieve the GPS data from the ROStopic with a subscriber, as well as write the assembled data to a file. It also spawns the threads that run the Atmotube and the plotter
#Make sure you read the README for further instructions on how to run this properly.
longitude = 0.0
latitude = 0.0
def callback(GPS):
global longitude
global latitude
latitude = GPS.latitude
longitude = GPS.longitude
#Starts up the subscriber. Every time it gets new information in the GlobalPosition topic, it calls the callback.
def listener():
rospy.Subscriber('dji_sdk/global_position', dji_sdk.msg.GlobalPosition, callback)
rospy.spin()
#Essentially just scans for Atmotube data and writes that to the file along with whatever the GPS coordinates are at the time.
def get_data():
global longitude
global latitude
while True:
atmotube = atmotube_scanner.scan()
if atmotube is not None:
write_to_file(latitude, longitude, atmotube[0], atmotube[1], atmotube[2])
atmotube = None
#Self-explanatory, really. Just writes the data to the same file that it made at the beginning of the program.
def write_to_file(latitude, longitude, voc, humidity, temp):
now = datetime.datetime.now()
#f = open('catkin_ws/src/Onboard-SDK-ROS-3.2/dji_sdk_demo/script/Atmotube/data/' + now.strftime("%Y-%m-%d") + '.dat', 'ab+')
f = open('catkin_ws/src/Onboard-SDK-ROS-3.2/dji_sdk_demo/script/Atmotube/data/sample.dat', 'ab+')
data = [[now.isoformat(), latitude, longitude, voc, humidity, temp]]
np.savetxt(f, data,fmt='%s')
f.close()
if __name__ == "__main__":
now = datetime.datetime.now()
#The file that is written to is created here. Its name is just the date. If you want a different file for
#different times/sessions in the same day, you will have to change that.
#The path to the file is also from root, because this file needs to be run with sudo (for reasons explained further in the README. Hint: It's the Atmotube.)
#f = open('catkin_ws/src/Onboard-SDK-ROS-3.2/dji_sdk_demo/script/Atmotube/data/' + now.strftime("%Y-%m-%d") + '.dat', 'a+')
f = open('catkin_ws/src/Onboard-SDK-ROS-3.2/dji_sdk_demo/script/Atmotube/data/sample.dat', 'a+')
f.close()
#Make the plotter thread
plotter = gaussiantest.Plotter()
plotter_thread=threading.Thread(target=plotter.run)
plotter_thread.start()
#Make the atmotube thread
atmotube_thread=threading.Thread(target=get_data)
atmotube_thread.daemon = True
atmotube_thread.start()
drone = DJIDrone()
drone.request_sdk_permission_control()
listener()
|
[
"justinetulip@gmail.com"
] |
justinetulip@gmail.com
|
0b78dcdac58833412c54cbda8d3ec6c9254bdc4e
|
6ebf0d93c77966ecdc0e0db594be614a4ceb3519
|
/bin/deos
|
2ab3571297ca9acf169888b773e6a44bc5ad1e73
|
[
"MIT",
"Apache-2.0",
"BSD-2-Clause",
"BSD-3-Clause"
] |
permissive
|
kvnn/DeOS
|
53a7bb595c26246c1daf00663091749d4e5c7d37
|
d865a3d202e4ae8328ecd1cf4e8b159eda6ed262
|
refs/heads/master
| 2021-01-13T13:41:30.652110
| 2016-12-13T09:24:12
| 2016-12-13T09:24:12
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 688
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
from subprocess import call, check_output
EXEC=lambda x:print('\n%s'%check_output(x.split(' ')))
PRINT=lambda x:print('\n%s\n'%x)
SHELL=lambda x:call(x.split(' '))
CMD={'Δ':'\x1b[32;01mΔ \x1b[0m'}
CMD['down']=lambda:SHELL('make down')
CMD['help']=lambda:PRINT('help')
CMD['ls']=lambda:EXEC('ls')
CMD['clear']=lambda:EXEC('clear')
CMD['vm.ls']=lambda:SHELL('make vm.ls')
CMD['build']=lambda:SHELL('make build')
CMD['test']=lambda:PRINT('test')
CMD['vm']=lambda:SHELL('make vm')
if __name__ == "__main__":
while not((lambda c:1 if c=='quit' else CMD[c]())(raw_input(CMD['Δ']))):
pass
|
[
"noreply@github.com"
] |
kvnn.noreply@github.com
|
|
ef9486bd52fe3268b1678689c22fb5f8354604da
|
aac56d890e5c450b6a6ab15f0427a63cd1637810
|
/wolframalpha.py
|
d45d7a11c3a5f328b019d55e1144b734fc0bb9f8
|
[] |
no_license
|
RitwikGupta/MHacksV
|
d468895c84be5b86896cd39e879c62e99c24a9e5
|
65a2863eba638e1ab40172c110acb6a48d392b88
|
refs/heads/master
| 2021-05-16T02:52:56.390268
| 2017-10-04T21:46:58
| 2017-10-04T21:46:58
| 29,382,054
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 690
|
py
|
import urllib2
import xmltodict
from string import split
statesGlobalVar = ['China']
def query(q, key="PA5U8P-6XX65RA456"):
return urllib2.urlopen('http://api.wolframalpha.com/v2/query?appid=%s&input=%s&format=plaintext' % (key,urllib2.quote(q))).read()
def state_query(group_name, states=statesGlobalVar):
results = {s: xmltodict.parse(query('%s of %s?' % (group_name, s))) for s in states}
results = {s: [p for p in v['queryresult']['pod'] if p['@title'] == 'Result'][0]['subpod']['plaintext'] for s,v in results.items()}
results = {s: float(split(v)[0])*(1000000 if 'million' in v else 1) for s,v in results.items()}
return results
print state_query('population')
|
[
"rmo24@pitt.edu"
] |
rmo24@pitt.edu
|
295cc1d3cf3461a85435bbe482968d67fa518f0e
|
d7331f18dd58c1ee9af63a79ce53fcd6de87d006
|
/Beginner Level/sorted list.py
|
04abbf060ffeb6050a16bfc41bb5583b6454a765
|
[] |
no_license
|
JeevaHariharan/Python-Programming
|
cdef90c31c10d0a670c26f8eb9bf2b5a217f0ece
|
e71c5eee0548430548d4f037aa1b3816fcdc2e30
|
refs/heads/master
| 2021-09-13T10:35:23.876421
| 2018-04-28T10:26:28
| 2018-04-28T10:26:28
| 125,207,625
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 91
|
py
|
n=int(input())
b=[]
for i in range (0,n):
a=int(input())
b.append(a)
b.sort()
print(b)
|
[
"noreply@github.com"
] |
JeevaHariharan.noreply@github.com
|
8e298e3ce6c52bda11234f4b510b5b5dbc48c668
|
c3b69ed405d910eb4783107f65dfe5af509e4f9f
|
/src/simplify_docx/iterators/run.py
|
83d42ae4ed24ceefeed39e81c24678297c7d9a2e
|
[
"LicenseRef-scancode-generic-cla",
"MIT"
] |
permissive
|
microsoft/Simplify-Docx
|
32e992a8313ca20ffe69dd0d32371436ecc4bed1
|
7f41e9195f5eb9e40558d57dc41f325f92a1b3a7
|
refs/heads/master
| 2023-09-01T08:59:34.971626
| 2022-06-13T17:59:06
| 2022-06-13T17:59:06
| 178,740,813
| 160
| 37
|
MIT
| 2022-06-13T17:59:07
| 2019-03-31T20:50:48
|
Python
|
UTF-8
|
Python
| false
| false
| 1,439
|
py
|
"""
Build the iterator for the run elements
"""
from docx.oxml.ns import qn
from .generic import register_iterator
from ..elements import text, simpleTextElement, SymbolChar, empty, contentPart, fldChar
register_iterator(
"CT_R",
TAGS_TO_YIELD={
qn("w:t"): text,
qn("w:sym"): SymbolChar,
qn("w:br"): simpleTextElement,
qn("w:cr"): simpleTextElement,
qn("w:tab"): simpleTextElement,
qn("w:noBreakHyphen"): simpleTextElement,
qn("w:softHyphen"): simpleTextElement,
qn("w:ptab"): simpleTextElement,
qn("w:fldChar"): fldChar,
qn("w:instrText"): empty,
qn("w:dayShort"): empty,
qn("w:monthShort"): empty,
qn("w:yearShort"): empty,
qn("w:dayLong"): empty,
qn("w:monthLong"): empty,
qn("w:yearLong"): empty,
qn("w:contentPart"): contentPart,
qn("w:annotationRef"): empty,
qn("w:footnoteRef"): empty,
qn("w:endnoteRef"): empty,
qn("w:footnoteReference"): empty,
qn("w:endnoteReference"): empty,
qn("w:commentReference"): empty,
qn("w:object"): empty,
qn("w:drawing"): empty,
},
TAGS_TO_IGNORE=[
qn("w:rPr"),
qn("w:delText"),
qn("w:delInstrText"),
qn("w:pgNum"),
qn("w:separator"),
qn("w:continuationSeparator"),
qn("w:ruby"),
qn("w:lastRenderedPageBreak"),
],
)
|
[
"jathorpe@microsoft.com"
] |
jathorpe@microsoft.com
|
23ed161811c076fabbb5ff1db48a45d115ca4d30
|
f9a72c43e0ea5fe08687d0608fcd113e63de2964
|
/368. Largest Divisible Subset.py
|
be5e44d33faac3818b5d64c2cde9fe2e8636e04d
|
[] |
no_license
|
Jingwei4CMU/Leetcode
|
1b82939583e4133442c3f4ae815630fd5999dc5c
|
baa6927a137765e4d7fe2d020863bca6988a1cf7
|
refs/heads/master
| 2020-04-07T22:14:49.266726
| 2019-04-16T23:54:41
| 2019-04-16T23:54:41
| 158,761,244
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,098
|
py
|
class Solution:
def largestDivisibleSubset(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
if len(nums) <= 1:
return nums
nums = sorted(nums)
# print(nums)
maxlen = [1 for i in range(len(nums))]
for i in range(1,len(nums)):
# print('i:',i,nums[i])
for j in range(i):
# print('j:', j,nums[j])
if nums[i] % nums[j] == 0:
if maxlen[j] + 1 > maxlen[i]:
maxlen[i] = maxlen[j] + 1
# print(maxlen)
# print(maxlen)
big = nums[maxlen.index(max(maxlen))]
to_return = []
start = 1
for i in range(len(nums)):
if nums[i] == big:
to_return.append(nums[i])
break
if big%nums[i] == 0:
if maxlen[i] == start:
to_return.append(nums[i])
start += 1
return to_return
nums = [2,3,4,9,8]
print(Solution().largestDivisibleSubset(nums))
|
[
"jingwei4@andrew.cmu.edu"
] |
jingwei4@andrew.cmu.edu
|
ebf006c01946c981bfa6f5883f19c3571f088d2d
|
e3e1890b32cacb7e150e21671616257c3ef42e9a
|
/TelemetryGenerator/main.py
|
6cb87a9b2b58c9b2dfd8c9a8aed07acdcc304323
|
[] |
no_license
|
itaynahum/proj
|
10df64b0ebb63f05d255ab98b983fc91aacaf528
|
64487a6056c6eaedee818df4d6a5ab4fe1afcd93
|
refs/heads/main
| 2023-05-04T20:33:03.487708
| 2021-05-28T13:08:42
| 2021-05-28T13:08:42
| 367,837,569
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 684
|
py
|
from TelemetryGenerator.Utils.Logger import InitLogger
from TelemetryGenerator.Utils.Config import Config
from TelemetryGenerator.Utils.Validator import directory_validator
from TelemetryGenerator.Utils.Runner import Runner
if __name__ == "__main__":
logger = InitLogger()
basic_logger = logger.basic_logger()
basic_logger.info(msg="Started TelemetryGenerator Successfully...")
basic_logger.info(msg="Initialized logger object...")
directory_validator(logger=basic_logger, directories=Config.DIRECTORIES_TO_VALIDATE)
logger = logger.rotating_logger(basic_logger)
runner = Runner(logger=logger, timeout=Config.TIMEOUT_BETWEEN_RUNS)
runner.run()
|
[
"itaynah123@gmail.com"
] |
itaynah123@gmail.com
|
ff38a8f010da123b175d523d3d84c210dda97d3d
|
86f62258c6a98cbd307c8ce705c3d4abc6a4ef11
|
/BigData_BI/BD8/bixi_linear_regressionV2.py
|
e7dd26a1bffe3df0f0d30939f434f487c63971f3
|
[] |
no_license
|
AndresUrregoAngel/CBB
|
59efa3084905bd146c4106d803c2b23194fd5826
|
6a214efd18d9b968d4cab65d0a93c77ed0c7614b
|
refs/heads/master
| 2021-01-01T19:22:12.669772
| 2020-09-25T14:44:06
| 2020-09-25T14:44:06
| 98,571,168
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,225
|
py
|
# _*_ coding: UTF-8 _*_
import pandas as pd
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn import linear_model
from sklearn.utils import column_or_1d
from sklearn import metrics
import numpy as np
df = pd.read_csv('bixi_final.csv',dtype={"user_id": int},low_memory= False,sep=',',encoding = "ISO-8859-1")
df_clNA = df.fillna(0)
#print(df.dtypes)
#print(test.where(df.id == 274680).dropna(thresh=2).head(n=20))
month = df_clNA.mois
month_encoder = preprocessing.LabelEncoder()
month_encoder.fit(month)
mois_formatted = month_encoder.transform(df_clNA['mois'])
jour = df_clNA.jour
jour_encoder = preprocessing.LabelEncoder()
jour_encoder.fit(jour)
jour_formatted = jour_encoder.transform(df_clNA['jour'])
action = df_clNA.action.astype(str)
action_encoder = preprocessing.LabelEncoder()
action_encoder.fit(action)
action_formatted = action_encoder.transform(df_clNA['action'].astype(str))
df_normalized = df_clNA.drop(['mois','jour','action'], axis=1)
df_normalized['mois'] = mois_formatted
df_normalized['jour'] = jour_formatted
df_normalized['action'] = action_formatted
#print(df_normalized.shape)
#print(df_normalized.head())
#print(df_normalized.describe())
y = df_normalized.action
X = df_normalized.drop(['action','id'],axis=1).astype('float64')
print(X.head())
# split training and test
X_train, X_test,y_train,y_test = train_test_split (X,y,test_size=0.25,random_state = 33)
# Apply the scaler
scalerX = StandardScaler().fit(X_train)
scalery = StandardScaler().fit(y_train.reshape(-1,1))
X_train = scalerX.transform(X_train)
y_train = scalery.transform(y_train.reshape(-1,1))
# split the tragets in training/test
X_test = scalerX.transform(X_test)
y_test = scalery.transform(y_test.reshape(-1,1))
# Create model linear regression
clf_sgd = linear_model.SGDRegressor(loss='squared_loss',penalty=None,random_state=42)
# Learning based in the model
clf_sgd.fit(X_train,y_train.ravel())
print("Coefficient de determination:",clf_sgd.score(X_train,y_train))
# Model performance
y_pred = clf_sgd.predict(X_test)
print("Coefficient de determination:{0:.3f}".format(metrics.r2_score(y_test,y_pred)))
|
[
"ingenieroandresangel@gmail.com"
] |
ingenieroandresangel@gmail.com
|
38b0bea0b146ee37a3abdbfd3dc6049cfa25c0a6
|
551b75f52d28c0b5c8944d808a361470e2602654
|
/huaweicloud-sdk-servicestage/huaweicloudsdkservicestage/v2/model/instance_status_view.py
|
f98d61c91c370d3f5da081ed433804c56425b07e
|
[
"Apache-2.0"
] |
permissive
|
wuchen-huawei/huaweicloud-sdk-python-v3
|
9d6597ce8ab666a9a297b3d936aeb85c55cf5877
|
3683d703f4320edb2b8516f36f16d485cff08fc2
|
refs/heads/master
| 2023-05-08T21:32:31.920300
| 2021-05-26T08:54:18
| 2021-05-26T08:54:18
| 370,898,764
| 0
| 0
|
NOASSERTION
| 2021-05-26T03:50:07
| 2021-05-26T03:50:07
| null |
UTF-8
|
Python
| false
| false
| 6,719
|
py
|
# coding: utf-8
import pprint
import re
import six
class InstanceStatusView:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
'status': 'InstanceStatusType',
'available_replica': 'int',
'replica': 'int',
'fail_detail': 'InstanceFailDetail',
'last_job_id': 'str',
'enterprise_project_id': 'str'
}
attribute_map = {
'status': 'status',
'available_replica': 'available_replica',
'replica': 'replica',
'fail_detail': 'fail_detail',
'last_job_id': 'last_job_id',
'enterprise_project_id': 'enterprise_project_id'
}
def __init__(self, status=None, available_replica=None, replica=None, fail_detail=None, last_job_id=None, enterprise_project_id=None):
"""InstanceStatusView - a model defined in huaweicloud sdk"""
self._status = None
self._available_replica = None
self._replica = None
self._fail_detail = None
self._last_job_id = None
self._enterprise_project_id = None
self.discriminator = None
if status is not None:
self.status = status
if available_replica is not None:
self.available_replica = available_replica
if replica is not None:
self.replica = replica
if fail_detail is not None:
self.fail_detail = fail_detail
if last_job_id is not None:
self.last_job_id = last_job_id
if enterprise_project_id is not None:
self.enterprise_project_id = enterprise_project_id
@property
def status(self):
"""Gets the status of this InstanceStatusView.
:return: The status of this InstanceStatusView.
:rtype: InstanceStatusType
"""
return self._status
@status.setter
def status(self, status):
"""Sets the status of this InstanceStatusView.
:param status: The status of this InstanceStatusView.
:type: InstanceStatusType
"""
self._status = status
@property
def available_replica(self):
"""Gets the available_replica of this InstanceStatusView.
正常实例副本数。
:return: The available_replica of this InstanceStatusView.
:rtype: int
"""
return self._available_replica
@available_replica.setter
def available_replica(self, available_replica):
"""Sets the available_replica of this InstanceStatusView.
正常实例副本数。
:param available_replica: The available_replica of this InstanceStatusView.
:type: int
"""
self._available_replica = available_replica
@property
def replica(self):
"""Gets the replica of this InstanceStatusView.
实例副本数。
:return: The replica of this InstanceStatusView.
:rtype: int
"""
return self._replica
@replica.setter
def replica(self, replica):
"""Sets the replica of this InstanceStatusView.
实例副本数。
:param replica: The replica of this InstanceStatusView.
:type: int
"""
self._replica = replica
@property
def fail_detail(self):
"""Gets the fail_detail of this InstanceStatusView.
:return: The fail_detail of this InstanceStatusView.
:rtype: InstanceFailDetail
"""
return self._fail_detail
@fail_detail.setter
def fail_detail(self, fail_detail):
"""Sets the fail_detail of this InstanceStatusView.
:param fail_detail: The fail_detail of this InstanceStatusView.
:type: InstanceFailDetail
"""
self._fail_detail = fail_detail
@property
def last_job_id(self):
"""Gets the last_job_id of this InstanceStatusView.
最近Job ID。
:return: The last_job_id of this InstanceStatusView.
:rtype: str
"""
return self._last_job_id
@last_job_id.setter
def last_job_id(self, last_job_id):
"""Sets the last_job_id of this InstanceStatusView.
最近Job ID。
:param last_job_id: The last_job_id of this InstanceStatusView.
:type: str
"""
self._last_job_id = last_job_id
@property
def enterprise_project_id(self):
"""Gets the enterprise_project_id of this InstanceStatusView.
企业项目ID。
:return: The enterprise_project_id of this InstanceStatusView.
:rtype: str
"""
return self._enterprise_project_id
@enterprise_project_id.setter
def enterprise_project_id(self, enterprise_project_id):
"""Sets the enterprise_project_id of this InstanceStatusView.
企业项目ID。
:param enterprise_project_id: The enterprise_project_id of this InstanceStatusView.
:type: str
"""
self._enterprise_project_id = enterprise_project_id
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
if attr in self.sensitive_list:
result[attr] = "****"
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, InstanceStatusView):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
[
"hwcloudsdk@huawei.com"
] |
hwcloudsdk@huawei.com
|
6bc6edcfb3dcb1ab8eed0ae598148c109e6505c7
|
c76e614c813172115c17a5ecf6828ba3ffb2e40c
|
/core1/migrations/0001_initial.py
|
9c74a35231f3ed42867fc50ca4bee3405d00b121
|
[] |
no_license
|
namanmj/restapi
|
f5ed850cc167ad5157b86ea276d617068da04ce6
|
4863c726a7775d2a885cb951b53dcd8824790956
|
refs/heads/main
| 2023-05-03T05:46:27.401864
| 2021-05-15T18:03:18
| 2021-05-15T18:03:18
| 367,336,576
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,522
|
py
|
# Generated by Django 3.2 on 2021-05-07 17:15
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Building',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=30)),
],
),
migrations.CreateModel(
name='Society',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=30)),
],
),
migrations.CreateModel(
name='Flat',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('flat_no', models.CharField(max_length=30)),
('building', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core1.building')),
('society', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core1.society')),
],
),
migrations.AddField(
model_name='building',
name='society',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core1.society'),
),
]
|
[
"naman.18bcs1103@abes.ac.in"
] |
naman.18bcs1103@abes.ac.in
|
89ddca4933ee0b6bb195fc066824a9b56a447dc3
|
7654f7f7134fb4542a41d4b6766990aa0f4f607f
|
/tutorials/datesntimes/dt_3.py
|
8f08ae066caf5c4836d846fec4888ecc656dd4c0
|
[] |
no_license
|
spelee/python_edu
|
9d76af74ac0c616f84d8d83bb8ea68412629cbc0
|
daaad68f46815b4cfe4beb171db0cc0dd6625040
|
refs/heads/master
| 2020-03-30T15:09:57.532906
| 2020-02-27T00:09:28
| 2020-02-27T00:09:28
| 151,349,770
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,700
|
py
|
import datetime
import pytz # recommended module for timezones
# alternative constructors
# none of the ways below give tz 'aware' datetimes
dt_today = datetime.datetime.today() # current local datetime, tz is None
# gives option to pass a timezone, so not passing a tz makes it equivalent to today()
dt_now = datetime.datetime.now()
# gives utc time, but actually *not* tz aware (i.e. empty tzinfo)
dt_utcnow = datetime.datetime.utcnow()
print(dt_today)
print(dt_now)
print(dt_utcnow)
# recommendation is to work with utc timezone
# left of micro seconds in this example
dt = datetime.datetime(2016, 7, 27, 12, 30, 45, tzinfo=pytz.UTC)
print(dt) # the +00:00 is the tz offset
print(datetime.datetime.now())
# current utc time that is also timezone aware
dt_now = datetime.datetime.now(tz=pytz.UTC)
print(dt_now)
# an alternative way to get current utc time that is also tz aware
dt_utcnow = datetime.datetime.utcnow().replace(tzinfo=pytz.UTC)
print(dt_utcnow)
# now in a different timezone
dt_mtn = dt_utcnow.astimezone(pytz.timezone('US/Mountain'))
print(dt_mtn)
dt_mtn = dt_utcnow.astimezone(pytz.timezone('US/Pacific'))
print(dt_mtn)
print('\n', '='*80, '\n')
# all timezones
for tz in pytz.all_timezones:
break
print(tz)
print('\n', '='*80, '\n')
# localize() converts naive time to local time (i.e. tz aware)
# this method should be used to construct localtimes, rather than passing tzinfo argument to a datetime constructor
dt_mtn = datetime.datetime.now()
print("Naive local time:")
print(dt_mtn)
print()
dt_east = dt_mtn.astimezone(pytz.timezone('US/Eastern'))
print("Converted to tz aware time for different tz:")
print(dt_east)
print()
print("Original local time is still naive:")
print(dt_mtn)
print()
mtn_tz = pytz.timezone('US/Mountain')
dt_mtn = mtn_tz.localize(dt_mtn)
print("Now, local time is tz aware. But note, did not localize to my actual tz.")
print("Localized to Mountain time instead of Pacific.")
print(dt_mtn)
print()
# The following statement no longer seems to be true...
# Can only convert tz if it is a timezone aware (i.e. localized tz)
# And now converting the tz again...
print("Converting tz aware local to new tz, Eastern again. Except now from Mountain time.")
dt_east = dt_mtn.astimezone(pytz.timezone('US/Eastern'))
print(dt_east)
print()
# iso format
print("Printing in ISO format")
print(dt_mtn.isoformat())
print()
# my own format. example...
print("Personalized formatting for datetime")
print(dt_mtn.strftime('%B %d, %Y'))
print()
# parsing date string into datetime obj
print("Parsing string into datetime")
dt_str = 'October 10, 2018'
dt = datetime.datetime.strptime(dt_str, '%B %d, %Y')
print(dt)
print()
|
[
"spelee@gmail.com"
] |
spelee@gmail.com
|
93e8d37ef1da5969876cb667a9ae9f8c823d21b9
|
180f8dd79821f7bc3b374c6fd3841e898a07e7da
|
/Easy/generate_document.py
|
6df48c047cf77f613dd5f39f6066536d5d9a7cb1
|
[] |
no_license
|
dalalsunil1986/Interview-Prep
|
be1382155677bead9667c88ecefaddc43e2d9469
|
595e86f0ff008b8fe534ff1ab4234bb11a3bdf03
|
refs/heads/master
| 2023-03-30T09:39:09.118839
| 2021-03-30T02:09:07
| 2021-03-30T02:09:07
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,261
|
py
|
from collections import Counter
"""
Very simple solution using built in libraries to just count up
occurrences and ensure that we have at least the needed number of chars
in our string to generate the document, based on chars and counts in
the document.
"""
def generateDocument(characters, document):
avail_chars = Counter(characters)
needed_chars = Counter(document)
for needed_char in document:
if avail_chars.get(needed_char, 0) < needed_chars[needed_char]:
return False
return True
"""
Basically the same as sol1 except we use 1 dict (less space) and less time
but asymptotically the same O(m + n)
"""
def generateDocument(characters, document):
char_cts = {}
for char_avail in characters:
char_cts[char_avail] = char_cts.get(char_avail, 0) + 1
for needed_char in document:
# if char isn't in our dict or freq for needed_char = 0 we can't make doc.
if needed_char not in char_cts or not char_cts[needed_char]:
return False
# decrement each time we encounter the char, if it hits 0 and we still
# have that character in the document, we don't have enough of this char to
# create doc.
char_cts[needed_char] -= 1
return True
|
[
"jchopra@seas.upenn.edu"
] |
jchopra@seas.upenn.edu
|
b3b1a60da3c05f3fbbc992bc947f2c48788e42fc
|
9248a1700cf0fad6d7b3e5750acb034e78a37286
|
/fb/audit.py
|
13ad5d11d80a32200cef0fbd5e7806ab2eb05d3f
|
[
"Apache-2.0"
] |
permissive
|
indigos33k3r/Fritbot_Python
|
992314260255294180acc0217968d3cc13a730ad
|
40c26e801952dfe54fad2799949ee684f29d6799
|
refs/heads/master
| 2020-04-13T16:34:03.112310
| 2014-04-16T22:55:26
| 2014-04-16T22:55:26
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 774
|
py
|
import logging, sys
from twisted.python.logfile import DailyLogFile
from twisted.python import log as twistedlogger
from fb.config import cfg
class Auditor(object):
CRITICAL = logging.CRITICAL
ERROR = logging.ERROR
WARNING = logging.WARNING
INFO = logging.INFO
DEBUG = logging.DEBUG
def __init__(self):
try:
logfile = DailyLogFile.fromFullPath(cfg.logging.filename)
except AssertionError:
raise AssertionError("Assertion error attempting to open the log file: {0}. Does the directory exist?".format(cfg.logging.filename))
twistedlogger.startLogging(logfile, setStdout=False)
def msg(self, text, level=INFO):
print text
def auditCommand(self, room, user, command):
pass
def auditResponse(self, room, user, response):
pass
log = Auditor()
|
[
"urthen@gmail.com"
] |
urthen@gmail.com
|
a69b21b4193ae3c1cde954be6583597e7d495bd9
|
2f2cc5bc44f0ff08c1f9888c3dd97ea2d3f3fe0a
|
/EXAMPLES/regex_sub.py
|
db2424c422fd1fef58a058f8075ac90f716c432c
|
[] |
no_license
|
solracq/Python-Training
|
ba33583292863393fab8156d18d48bc511c9f331
|
4c8a29da23b9e483f8e5c30f7ef4a7311a427381
|
refs/heads/master
| 2021-01-21T00:45:04.954824
| 2020-05-04T00:21:35
| 2020-05-04T00:21:35
| 14,281,299
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 287
|
py
|
#!/usr/bin/env python3
import re
fs = "apple banana artichoke cherry date enchilada appetizer"
r = re.compile(r"\b(a[a-z]+)(\s*)") # match words that start with 'a'
print(r.sub('',fs)) # delete matched text
print(r.subn('XXX',fs)) # replace matched text with 'XXX'
|
[
"Solrac@192.168.0.18"
] |
Solrac@192.168.0.18
|
a39a1e6cea4dd37aaaea9a0c0ef62681a2a2aa71
|
fddc60af2bab8c440c91f7096a1d5bee9420d672
|
/venv/Scripts/easy_install-3.8-script.py
|
9e01afb6caf63425cbdf9105a9787dace54fd3c7
|
[] |
no_license
|
lamnhuthoa/Turtle-Race
|
55b9aa98c97ed60372961648efd6507a73c106f9
|
c5b9ecce0c6c4fb807dee9190b03dfb729c4248b
|
refs/heads/master
| 2023-07-25T10:59:20.222685
| 2021-09-03T18:22:39
| 2021-09-03T18:22:39
| 402,862,560
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 471
|
py
|
#!"C:\Users\SONY\Desktop\Python Course\Etch A Sketch\venv\Scripts\python.exe"
# EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==39.1.0','console_scripts','easy_install-3.8'
__requires__ = 'setuptools==39.1.0'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
load_entry_point('setuptools==39.1.0', 'console_scripts', 'easy_install-3.8')()
)
|
[
"hoalamnhut@gmail.com"
] |
hoalamnhut@gmail.com
|
63090d581802e03b77e9c36bac9c1cfea61ff789
|
1c01810b23d8e959605cde200cc82cb3d62899d9
|
/unsam/Clase 4/arboles.py
|
75c3ed101dbcbba79fd467adc4bf7c613dacf3e0
|
[] |
no_license
|
benitez96/unsam
|
a914721a7649092ac8f875866e44af2eb455919e
|
592f98e97672b44b9088938725bdd58a59ea6412
|
refs/heads/main
| 2023-01-13T08:07:17.746091
| 2020-11-05T22:11:43
| 2020-11-05T22:11:43
| 303,542,199
| 0
| 2
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,712
|
py
|
import csv
from collections import Counter
#%%
def leer_parque(nombre_archivo, parque):
'devuelve una lista de arboles en un parque'
arboles = list()
with open(nombre_archivo, encoding='utf8') as f:
rows = csv.reader(f)
headers = next(rows)
for row in rows:
lote = dict(zip(headers, row))
if lote['espacio_ve'] == parque.upper():
lote['altura_tot'] = float(lote['altura_tot'])
arboles.append(lote)
return arboles
#%%
def especies(lista_arboles):
'esta funcion devuelve las especies presentes en un parque'
especies = []
for registro in lista_arboles:
especies.append(registro['nombre_com'])
especies = set(especies)
return especies
#%%
def contar_ejemplares(lista_arboles):
count = Counter()
for registro in lista_arboles:
count.setdefault(registro['nombre_com'], 0)
count[registro['nombre_com']] += 1
return count
#%%
def obtener_alturas(lista_arboles, especie):
alturas = []
for registro in lista_arboles:
if registro['nombre_com'] == especie:
alturas.append(registro['altura_tot'])
return alturas
#return f'Maximo -> {max(alturas)}, Promedio -> {round((sum(alturas)/len(alturas)), 2)}'
#%%
def obtener_inclinaciones(lista_arboles, especie):
inclinaciones = []
for registro in lista_arboles:
if registro['nombre_com'] == especie:
inclinaciones.append(float(registro['inclinacio']))
return inclinaciones
#%%
def especimen_mas_inclinado(lista_arboles):
l_especies = especies(lista_arboles)
l_inclinaciones = []
for e in l_especies:
inc_esp = obtener_inclinaciones(lista_arboles, e)
inc_esp = max(inc_esp)
l_inclinaciones.append((inc_esp, e))
inc_max = max(l_inclinaciones)
return inc_max
#%%
def especie_promedio_mas_inclinada(lista_arboles):
l_especies = especies(lista_arboles)
l_inclinaciones = []
for e in l_especies:
inc_esp = obtener_inclinaciones(lista_arboles, e)
inc_esp = sum(inc_esp)/len(inc_esp)
l_inclinaciones.append((inc_esp, e))
inc_prom = max(l_inclinaciones)
return inc_prom
#%%
def leer_arboles(nombre_archivo):
with open (nombre_archivo, encoding='utf8') as f:
rows = csv.reader(f)
headers = next(rows)
arboleda = [{enc: valor for enc, valor in zip(headers, row)} for row
in rows]
return arboleda
arboleda = leer_arboles('Data/arbolado.csv')
H=[float(arbol['altura_tot']) for arbol in arboleda]
H_jac = [float(arbol['altura_tot']) for arbol in arboleda if
arbol['nombre_com'] == 'Jacarandá']
HyD_jac = [(float(arbol['altura_tot']), float(arbol['diametro'])) for arbol in
arboleda if arbol['nombre_com'] == 'Jacarandá']
#%%
def medidas_de_especies(especies, arboleda):
'''Esta funcion recibe una lista de arboles y una de especies. Devuelve un
diccionario con su nombre(clave) y altura y diametro(valores)'''
diccionario = {especie:[(float(arbol['altura_tot']), float(arbol['diametro']))
for arbol in arboleda if arbol['nombre_com'] == especie] for
especie in especies}
return diccionario
especies = ['Eucalipto', 'Palo borracho rosado', 'Jacarandá']
dicc = medidas_de_especies(especies, arboleda)
#%% plotear altura jacaranda
import os
import matplotlib.pyplot as plt
nombre_archivo = os.path.join('Data', 'arbolado.csv')
arboleda = leer_arboles(nombre_archivo)
altos = [float(arbol['altura_tot']) for arbol in arboleda if
arbol['nombre_com'] == 'Jacarandá']
plt.hist(altos,bins=20)
#%% scatterplot jacaranda h y d
import numpy as np
h = np.array([float(arbol['altura_tot']) for arbol in arboleda if
arbol['nombre_com'] == 'Jacarandá'])
d = np.array([float(arbol['diametro']) for arbol in arboleda if
arbol['nombre_com'] == 'Jacarandá'])
plt.scatter(d, h, c='red', alpha=0.5)
plt.xlabel("diametro (cm)")
plt.ylabel("alto (m)")
plt.title("Relación diámetro-alto para Jacarandás")
#%%
import os
import matplotlib.pyplot as plt
import numpy as np
nombre_archivo = os.path.join('Data', 'arbolado.csv')
arboleda = leer_arboles(nombre_archivo)
especies = ['Eucalipto', 'Palo borracho rosado', 'Jacarandá']
medidas = medidas_de_especies(especies, arboleda)
colores = ['blue', 'green','red']
for i,z in enumerate(medidas):
for h, d in medidas[z]:
plt.scatter(x=d, y=h, alpha=0.4, c=colores[i])
plt.xlabel("diametro (cm)")
plt.ylabel("alto (m)")
#plt.xlim(0,40)
#plt.ylim(0,80)
plt.title(list(medidas.keys())[i])
|
[
"danii-benitez@hotmail.com"
] |
danii-benitez@hotmail.com
|
38339d8f1003dc5740ff2f33c21d904957615df0
|
12355b1f9505281cd22723631a9155312566083d
|
/Automation/Automation_Debpack/improvedir.py
|
82d05b2b4941d0e56a81418a6ec3aac64d399d73
|
[] |
no_license
|
jayanthsagar/portable-vlabs-project
|
ee747ab4f3c52566ad8b9c594416f29f0057ca1e
|
3652f163bd6efe61b587bff2475109764288d530
|
refs/heads/master
| 2020-04-09T09:15:32.351212
| 2015-02-25T05:06:15
| 2015-02-25T05:06:15
| 31,298,117
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 332
|
py
|
import sys
import os
v=sys.argv[1]
for root, dirs, filenames in os.walk(v):
for filename in filenames:
fullpath = os.path.join(root, filename)
filename_split = os.path.splitext(fullpath)
s, fileext = filename_split
i,l=0,len(s)
while i<l:
if s[i]==' ': s=s[0:i]+'_'+s[i+1:]
i+=1
os.rename(fullpath, s + fileext)
|
[
"jayanthsagar.t@gmail.com"
] |
jayanthsagar.t@gmail.com
|
23919b09c33cb9140c8d0a2981d16875d4b98e7e
|
2d395a09a0927c82dc67edc5e924884bc982e4dd
|
/resource/migrations/0002_auto_20211022_1332.py
|
a15ffa8cc834d0654de249a106446a90e9948ee3
|
[] |
no_license
|
Johguxo/hackaton-bbva-2021
|
b87b274e6515a4ba19181ed2efca67b63079078c
|
de515fc60089f0da0ef37d2c248404639f746437
|
refs/heads/master
| 2023-08-19T05:38:56.500277
| 2021-10-24T15:28:19
| 2021-10-24T15:28:19
| 414,044,401
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 917
|
py
|
# Generated by Django 3.2.7 on 2021-10-22 18:32
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('resource', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='file',
name='description',
field=models.TextField(blank=True, default='', null=True),
),
migrations.AddField(
model_name='file',
name='name',
field=models.CharField(default='', max_length=150),
),
migrations.AddField(
model_name='file',
name='url_file',
field=models.URLField(blank=True, null=True),
),
migrations.AlterField(
model_name='file',
name='creation',
field=models.DateField(default=django.utils.timezone.now),
),
]
|
[
"jgonzalesi@uni.pe"
] |
jgonzalesi@uni.pe
|
8af5fce5f8b121061c77f2907d2f7442751ab6d2
|
98b4c86d12903ba7863878ed79523cfeb465a3db
|
/bi_invoice_layout_customization/models/__init__.py
|
829783c8e2492b8291f6900f5e8dcb8109afa689
|
[] |
no_license
|
odoo-modules/dareed
|
4168dc301eeafe8c6ed034a89e49af19e641ac8e
|
2588deb0c0a364bf799846f6c46e38cb1a83d529
|
refs/heads/master
| 2020-07-18T14:58:47.912413
| 2019-09-02T12:58:23
| 2019-09-02T12:58:23
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 151
|
py
|
# -*- coding: utf-8 -*-
from . import account_invoice_inherit
from . import res_partner_inherit
from . import res_company
from . import account_invoice
|
[
"ibrahimqabeell@gmail.com"
] |
ibrahimqabeell@gmail.com
|
4bc88052af9531b9fc985bb173fa8a369612e51f
|
6cf550446a92cc2b77f51632180877a8a6c7fda3
|
/_build/jupyter_execute/lab_notebooks/B04.py
|
6231bd33a1a64ae4211b74788dc2781ad9781a89
|
[] |
no_license
|
zelenkastiot/bio_lab
|
8e6413b2fbf8f573bbfe4ef1e6b8c3d4590fd176
|
a4e8cef347f74f6451274b2867900e65fa309d37
|
refs/heads/main
| 2023-05-10T17:51:49.592662
| 2021-04-20T23:12:12
| 2021-04-20T23:12:12
| 359,972,162
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,710
|
py
|
# 💻 Б4: Yersinia pestis ДНА секвенца
```{admonition} Опис на барање
:class: tip
Да се преземе комплетната ДНА секвенција на Yersinia pestis
(бактерија која ги инфектира белите дробови и предизвикува
пневмонија). До неа се пристапува со употреба на
идентификациониот број **NC_005816** во GeneBank базата
(работете со **SeqIO** објекти, имате детали во
документацијата).
```
Читање на **Genbank** фајл и принтање на секвенцата:
from Bio import SeqIO
record = SeqIO.read("yersinia-pestis-fasta/NC_005816.gb", "genbank")
# print(record)
print(f'Секвенцата: {record.seq[:15]}...{record.seq[-1]}')
print(f'Сите влезови во feature табалета: {len(record.features)}')
print(f'Извор за базата: {record.annotations["source"]}')
**Транскрипција** на прочитаната секвенца:
rna_seq = record.seq.transcribe()
print(f'РНА од секвенцата: {rna_seq[:20]}...{rna_seq[-2]}{rna_seq[-1]}')
**Транслација** на нуклеотидите:
protein_seq = record.seq.translate()
print(f'Протеинска секвенца: {protein_seq[:40]}...{protein_seq[-2]}{protein_seq[-1]}')
**Транслација** на нуклеотидите то првиот стоп кодон и потоа прекинува:
protein_seq_w = record.seq.translate(to_stop=True)
print(f'Протеинска секвенца до прв стоп кодон: {protein_seq_w}')
|
[
"zelenkastiot@gmail.com"
] |
zelenkastiot@gmail.com
|
1e54fa03058fb4fa591d0696e2c0b5f8badf564e
|
8310397dafc1c7b8209821725606cb70ebd15366
|
/dbtest/emp/migrations/0002_auto_20180919_0405.py
|
aa9823a70a863a8d2460100d635c8570a9bcc234
|
[] |
no_license
|
Pkaran26/Download-different-type-of-file-attachments-in-django
|
0233fa4b53a3616cfe15fd43627efdf4ace9f7a4
|
b95c8dabcb78c707a5de56533828740e548c9b21
|
refs/heads/master
| 2020-03-29T00:58:04.063864
| 2018-09-19T00:24:45
| 2018-09-19T00:24:45
| 149,364,652
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 555
|
py
|
# Generated by Django 2.1.1 on 2018-09-18 22:35
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('emp', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='employee',
name='dob',
field=models.DateField(max_length=20),
),
migrations.AlterField(
model_name='employee',
name='join_date',
field=models.DateField(auto_now_add=True),
),
]
|
[
"noreply@github.com"
] |
Pkaran26.noreply@github.com
|
378a3a23ba9b25d34904f847f59c0c6527556a71
|
dd67c85179812aea6fff4fe693f56cb94c58b0f5
|
/polls/migrations/0001_initial.py
|
ca4df1752779d152f03261f48662cd96ebd5694d
|
[] |
no_license
|
amsterdam32/firs_app_votes
|
ad013e98492dc63394b361b9eec9d71a5fd58017
|
89786d4373b3b6a51a3490473cb25abd9913a800
|
refs/heads/master
| 2016-08-12T05:36:19.094347
| 2016-01-15T12:18:31
| 2016-01-15T12:18:31
| 49,647,160
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,229
|
py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-01-14 16:39
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Choice',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('choice_text', models.CharField(max_length=200)),
('votes', models.IntegerField(default=0)),
],
),
migrations.CreateModel(
name='Question',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('question_text', models.CharField(max_length=200)),
('pub_date', models.DateTimeField(verbose_name='date published')),
],
),
migrations.AddField(
model_name='choice',
name='question',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='polls.Question'),
),
]
|
[
"v.postman2014@yandex.com"
] |
v.postman2014@yandex.com
|
b9e98494dc978048f1898ab2c037aa45350f64ce
|
22c060f4be02fbacfa7503f8d2433be9f0454114
|
/venv/bin/wheel
|
973a1d986bf1548c02472c4557724852c8cec08f
|
[] |
no_license
|
doorknob88/cmpe273assignment1
|
3ba2c72614723a69abb8ab3a9cdb62a5fb2456d0
|
600879aaccabcd2153d17c754b0097d4eac93c1f
|
refs/heads/master
| 2021-08-31T04:03:55.841038
| 2017-12-20T09:15:28
| 2017-12-20T09:15:28
| 107,230,741
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 282
|
#!/Users/Dipro/Desktop/SJSU/Fall-17/273-01/Assignment-1/assignment-1/venv/bin/python3.6
# -*- coding: utf-8 -*-
import re
import sys
from wheel.tool import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(main())
|
[
"doorknob88@gmail.com"
] |
doorknob88@gmail.com
|
|
80b9876a49985800a8bd866d146704fac405e374
|
25e8f335313a9d8bfae37ef6d931716c6d9b91b2
|
/AirFleet/AirFleet/asgi.py
|
660b0b4b8e639591c68b7094a69e700ca6354ad1
|
[
"MIT"
] |
permissive
|
fossabot/AirFleet
|
4f854f82465a972483e59f570b56efbb1d3eb8bd
|
f1933bb27129266dcfb7b393622afcb61b4900f8
|
refs/heads/main
| 2023-07-09T18:44:10.312710
| 2021-08-16T18:59:22
| 2021-08-16T18:59:22
| 396,931,977
| 0
| 0
|
MIT
| 2021-08-16T18:59:21
| 2021-08-16T18:59:21
| null |
UTF-8
|
Python
| false
| false
| 393
|
py
|
"""
ASGI config for AirFleet project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'AirFleet.settings')
application = get_asgi_application()
|
[
"pshukla911@gmail.com"
] |
pshukla911@gmail.com
|
c064aa982d26f36d362a8853f239fdc454059b8f
|
53fab060fa262e5d5026e0807d93c75fb81e67b9
|
/gaussiana/ch3_2019_03_15_10_58_42_117187.py
|
d99487bdb36aca329b09cc5c7f5aefc5cc7edc44
|
[] |
no_license
|
gabriellaec/desoft-analise-exercicios
|
b77c6999424c5ce7e44086a12589a0ad43d6adca
|
01940ab0897aa6005764fc220b900e4d6161d36b
|
refs/heads/main
| 2023-01-31T17:19:42.050628
| 2020-12-16T05:21:31
| 2020-12-16T05:21:31
| 306,735,108
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 135
|
py
|
import math
def calcula_gaussiana(x,μ,σ):
f = ( 1.0 / (σ * math.sqrt(2.0*math.pi)) ) * math.exp(-0.5 * ((x - μ)/ σ)**2)
return f
|
[
"you@example.com"
] |
you@example.com
|
bc884dd6ff26f86795874355e8cece32d64a4167
|
1775dcc68f2c0c196b9fb16abae31149b47d5df3
|
/designs/migrations/0002_initial.py
|
bd7b658729d70f11bd713484a65d93023df9f111
|
[] |
no_license
|
jessicastrawford/project-four-backend
|
a5427284f4f2e67e0cd62ed79c8041505d377373
|
da1c26e5aa360b04eae09ea8f641fb579144b76e
|
refs/heads/main
| 2023-08-24T22:29:03.918449
| 2021-10-14T14:45:29
| 2021-10-14T14:45:29
| 404,301,769
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,322
|
py
|
# Generated by Django 3.2.7 on 2021-09-09 18:42
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('designs', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='design',
name='added_by',
field=models.ForeignKey(blank='True', on_delete=django.db.models.deletion.DO_NOTHING, related_name='added_designs', to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='design',
name='saved_by',
field=models.ManyToManyField(blank='True', related_name='saved_designs', to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='comment',
name='design',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='comments', to='designs.design'),
),
migrations.AddField(
model_name='comment',
name='owner',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='comments_made', to=settings.AUTH_USER_MODEL),
),
]
|
[
"jessicastrawford@gmail.com"
] |
jessicastrawford@gmail.com
|
36b4bde74ee055b1e8c0737ab35aac2ac08635e3
|
a30c19795ad4f8ee5d10d1776d63d0eca5497d48
|
/ml_model.py
|
6f8c2ebade828618dca22ee71b4ebf2a7a4eceee
|
[] |
no_license
|
arun1011/ML-Classifiers-Comparison
|
cd78cfd1c4b4eb5eb4959e82b8e5398c99f5e564
|
7d9320f3712911c382c42539b79a6106489c32dc
|
refs/heads/master
| 2021-07-11T20:40:35.109445
| 2021-05-09T06:10:51
| 2021-05-09T06:10:51
| 245,651,072
| 1
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 8,512
|
py
|
import pandas
from sklearn.externals import joblib
import operator
import numpy as np
from pandas.tools.plotting import scatter_matrix
import matplotlib.pyplot as plt
from sklearn import model_selection
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.feature_extraction.text import TfidfVectorizer
from collections import Counter
from sklearn.model_selection import learning_curve
from sklearn.model_selection import ShuffleSplit
######----default name for label is "class"--------#####
def sort_byvalue(dictx):
dicty=sorted(dictx.items(),key=operator.itemgetter(1),reverse=True)
return dicty
def any2list(X):
xlist = []
if type(X) == str: X = [X]; print("txt2vec--->string")
if type(X) == list: xlist = X; print("txt2vec--->list")
if type(X) == np.ndarray:
for i in range(len(X)): xlist.append(X[i][0])
print("txt2vec--->ndarray")
return xlist
def tex2vec(xlist, model_name):
Vectorizer = TfidfVectorizer(min_df=0.001, max_df=1.0, stop_words='english')
X_train_vectors = Vectorizer.fit(xlist)
joblib.dump(Vectorizer, 'models/' + model_name + '_vec.pkl')
X_train_vectors = Vectorizer.transform(xlist)
X_train_vectors = X_train_vectors.toarray()
return X_train_vectors
def get_XY(url, vectorize, features):
dataset = pandas.read_csv(url, names=features); #print(dataset); return
if vectorize==1:
h=list(dataset.columns.values)[0]; #print(h)
dataset[h] = dataset[h].values.astype('U')
array = dataset.values; #print(array[0])
n = len(array[0]); #print("len--->", n)
X = array[:,0:n-1]
Y = array[:,n-1]
return X, Y
def summarize(url, features):
dataset = pandas.read_csv(url, names=features)
#Summarize the Dataset
Summary={}
#Summary['Shape']=dataset.shape
#Summary['Structure']=dataset.head(1)
#Summary['Describe']=dataset.describe()
Summary['Groups']=dataset.groupby('class').size().to_json()
#print(Summary)
#Data Visualization
dataset.plot(kind='box', subplots=True, layout=(2,2), sharex=False, sharey=False); plt.savefig("box.jpg")
dataset.hist(); plt.savefig("hist.jpg")
scatter_matrix(dataset); plt.savefig("scatter.jpg")
return {"summary":Summary, "box":"C:/services.ai/Classifier/box.jpg", "hist":"C:/services.ai/Classifier/hist.jpg", "scatter":"C:/services.ai/Classifier/scatter.jpg"}
def get_models():
models = {}
models['LogR'] = LogisticRegression()
models['LDA'] = LinearDiscriminantAnalysis()
models['KNN'] = KNeighborsClassifier()
models['DTC'] = DecisionTreeClassifier()
models['NBC'] = GaussianNB()
models['SVC'] = SVC()
return models
def compare(url, features, vectorize):
X, Y = get_XY(url, vectorize, features)
if vectorize==1:
xlist = any2list(X)
X = tex2vec(xlist, "compare")
#create validation set
validation_size = 0.20
seed = 7
Xt, Xv, Yt, Yv = model_selection.train_test_split(X, Y, test_size=validation_size, random_state=seed)
#Test options and evaluation metric
scoring = 'accuracy'
models = get_models()
# evaluate each model in turn
results = []
model_names = []
model_list = {}
compare_list = {}
for name, model in models.items():
kfold = model_selection.KFold(n_splits=2, random_state=seed)
cv_results = model_selection.cross_val_score(model, Xt, Yt, cv=kfold, scoring=scoring)
results.append(cv_results)
model_names.append(name)
model_list[model]=cv_results.mean()
cvm = round(cv_results.mean(),2); cvs = round(cv_results.std(),4)
compare_list[name]=[" Mean: "+str(cvm), " Std: "+str(cvs)]
print(name, ':', cvm, cvs)
#print(model_names)
model_dict=sort_byvalue(model_list); #print(model_dict)
final_model=model_dict[0][0]; #print('final_model: ',final_model)
#Compare Algorithms
fig = plt.figure()
fig.suptitle('Algorithm Comparison')
ax = fig.add_subplot(111)
plt.boxplot(results)
ax.set_xticklabels(model_names)
plt.savefig('comparison.jpg')
return [compare_list, "C:/services.ai/Classifier/comparison.jpg", str(final_model)]
def plot_learning_curve(estimator, title, X, y, ylim=None, cv=None,
n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)):
plt.figure()
plt.title(title)
if ylim is not None:
plt.ylim(*ylim)
plt.xlabel("Training examples")
plt.ylabel("Score")
train_sizes, train_scores, test_scores = learning_curve(
estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes)
train_scores_mean = np.mean(train_scores, axis=1)
train_scores_std = np.std(train_scores, axis=1)
test_scores_mean = np.mean(test_scores, axis=1)
test_scores_std = np.std(test_scores, axis=1)
plt.grid()
plt.fill_between(train_sizes, train_scores_mean - train_scores_std,
train_scores_mean + train_scores_std, alpha=0.1,
color="r")
plt.fill_between(train_sizes, test_scores_mean - test_scores_std,
test_scores_mean + test_scores_std, alpha=0.1, color="g")
plt.plot(train_sizes, train_scores_mean, 'o-', color="r",
label="Training score")
plt.plot(train_sizes, test_scores_mean, 'o-', color="g",
label="Cross-validation score")
plt.legend(loc="best")
return plt
def train(url, features, model_key, vectorize, model_name):
model_dict=get_models()
final_model=model_dict[model_key]; #print('final_model--->', final_model)
X, Y = get_XY(url, vectorize, features)
if vectorize==1:
xlist = any2list(X)
X = tex2vec(xlist, model_name)
#print("input-->", X); print("label-->", Y)
#create validation set
tsize = 0.2
Xt, Xv, Yt, Yv = model_selection.train_test_split(X, Y, test_size=tsize, random_state=0)
#print(Xvalidation[0])
## Make predictions on validation dataset
Yt = Yt.reshape(Yt.size, 1); #print(Yt)
print(Xt.shape, Yt.shape);#return
clf=final_model.fit(Xt, Yt)
joblib.dump(clf, 'models/'+model_name+'.pkl'); print("Training Completed")
predictions = clf.predict(Xv); #print(predictions); #print(Xv)
score = accuracy_score(Yv, predictions); print("Score:", score)
#report = classification_report(Yvalidation, predictions)
#matrix = confusion_matrix(Yvalidation, predictions)
#print('Accuracy: ', score); #print(report); print(matrix)
# title = "Learning Curves - "+str(model_key)
# # Cross validation with 2 iterations to get smoother mean test and train
# # score curves, each time with 20% data randomly selected as a validation set.
# cv = ShuffleSplit(n_splits=2, test_size=tsize, random_state=0)
# plot_learning_curve(final_model, title, X, Y, ylim=(0.7, 1.01), cv=cv, n_jobs=4)
# plt.savefig("learning_curve.jpg")
return [round(score,2), "C:/services.ai/Classifier/learning_curve.jpg"]
def predict(url, vectorize, model_name):
model = joblib.load('models/' + model_name + '.pkl')
X, Y = get_XY(url, vectorize, ['desc','temp']); #print(X)
if vectorize==1:
vec = joblib.load('models/' + model_name + '_vec.pkl')
xlist = any2list(X)
X = vec.transform(xlist)
X = X.toarray(); #print(X)
result = model.predict(X); print("Predictions:",result)
#distance_by_class = model.decision_function(x); #confidence of classes
return result
# compare("input/iris.csv",['a','b','c','d','e'],0)
# train("input/iris.csv",['a','b','c','d','e'],"NBC",0,"iris")
# predict("input/iris_test.csv",0,"iris")
# compare("input/hca.csv",['desc','class'],1)
# train("input/hca.csv",['desc','class'],"NBC",1,"hca")
# predict("input/hca_test.csv",1,"hca")
|
[
"noreply@github.com"
] |
arun1011.noreply@github.com
|
316765311ed947f8126d3fd66366e60e5aabd5f0
|
2d9782e06391d5ff98e4d80812580afa4e38e841
|
/app/main/views.py
|
c8e0aab9c6f8f92f6166a6bef793e6931dc7fc83
|
[
"MIT"
] |
permissive
|
JamesMusyoka/PITCH-IP
|
25e4c8aa71a77584190054a53e6a37825c01e032
|
56d9a9e1e30cd702511909d3df9e0ba7f388ef3c
|
refs/heads/master
| 2020-04-21T17:41:35.025345
| 2019-02-14T13:02:23
| 2019-02-14T13:02:23
| 169,744,643
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,440
|
py
|
from flask_login import login_required, current_user
from .forms import PostForm
from .. import db
from flask import Flask,render_template,request,redirect,url_for,abort
from . import main
from ..models import User,Role
# from flask_wtf import FlaskForm
# from wtforms import StringField,PasswordField,BooleanField
# from wtforms.validators import InputRequired,Email,Length
@main.route('/index', methods=['GET', 'POST'])
def home():
form = PostForm()
if form.validate_on_submit():
post = Pitch(body=form.post.data, author=current_user,
category=form.category.data)
db.session.add(post)
db.session.commit()
flash('Your post is now live!')
return redirect(url_for('main.index'))
# posts = Pitch.retrieve_posts(id).all()
return render_template("index.html", title='Home Page', form=form, posts=posts)
@main.route('/')
# @login_required
def index():
title = 'WELCOME TO JAMOPITCH'
# return render_template('index.html')
# # 'test':TestConfig
# # posts = [
# # {
# # 'author': {'username': 'Phanise'}
# # 'body': 'Beautiful day in Holland!'
# # },
# # {
# # 'author': {'username': 'James' },
# # 'body': 'The Original Series was cool'
# # }
# # ]
return render_template('index.html', title = title, index = index)
@main.route('/post/int<int:id>', methods=['GET', 'POST'])
@login_required
def post():
form = PostForm()
if form.validate_on_submit():
post = form.post.data
category = form.category.data
user = current_user
new_pitch = Pitch(body=post, category=category, user=user)
# save pitch
db.session.add(new_pitch)
db.session.commit()
return redirect(url_for('main.explore', uname=user.username))
return render_template('post.html', form=form)
# @main.route('/index.html', methods=['GET', 'POST'])
# # @login_required
# def pitch():
# form = PostForm()
# if form.validate_on_submit():
# # post = form.post.data
# # category = form.category.data
# # user = current_user
# new_pitch = Pitch(body = post,category = category,user = user)
# # save pitch
# db.session.add(new_pitch)
# db.session.commit()
# life = Pitch.query.filter_by(category='index.html')
# # users_post = Pitch.query.filter_by(user_id=id).all()
# return render_template('user_index.html', title = 'title',form=form)
@main.route('/user/<username>')
def profile(uname):
user = User.query.filter_by(username=uname).first()
if user is None:
abort(404)
return render_template("profile/profile.html", user=user)
@main.route('/user/<uname>/update', methods=['GET', 'POST'])
@login_required
def update_profile(username):
user = User.query.filter_by(username=uname).first()
if user is None:
abort(404)
form = UpdateProfile()
if form.validate_on_submit():
user.bio = form.bio.data
db.session.add(user)
db.session.commit()
return redirect(url_for('.profile', uname=user.username))
return render_template('profile/update.html', form=form)
@main.route('/user/<uname>/update/pic', methods=['POST'])
@login_required
def update_pic(uname):
user = User.query.filter_by(username=uname).first()
if 'photo' in request.files:
filename = photos.save(request.files['photo'])
path = f'photos/{filename}'
user.profile_pic_path = path
db.session.commit()
return redirect(url_for('main.profile', uname=uname))
@main.route('/technology.html' ,methods = ['GET','POST'])
def technology():
technology = Pitch.query.filter_by(category = 'Technology').all()
form = CommentForm()
if form.validate_on_submit():
details = form.details.data
user = current_user
new_comment = Comments(details = details,pitch_id=id,user =user)
db.session.add(new_comment)
db.session.commit()
return render_template('technology.html', technology = technology,form=form)
@main.route('/business' ,methods = ['GET','POST'])
def business():
business = Pitch.query.filter_by(category = 'business').all()
form = CommentForm()
if form.validate_on_submit():
details = form.details.data
user = current_user
new_comment = Comments(details = details,pitch_id=id,user =user)
db.session.add(new_comment)
db.session.commit()
return render_template('business.html', business = business,form=form)
@main.route('/pickuplines.html' ,methods = ['GET','POST'])
def pickuplines():
form = CommentForm()
if form.validate_on_submit():
details = form.details.data
user = current_user
new_comment = Comments(details = details,pitch_id=id,user =user)
db.session.add(new_comment)
db.session.commit()
pickuplines = Pitch.query.filter_by(category = 'Pickuplines').all()
if pickuplines is None:
abort(404)
return render_template('pickuplines.html', pickuplines = pickuplines,form=form)
|
[
"jamesmu475@gmail.com"
] |
jamesmu475@gmail.com
|
545b33429f708c172ec7d0784df38f46b5ffb385
|
2fd817893ed972665f0917b7ff8d1427cb59407d
|
/sorting algorithms/Dynamic_KnapsackBlockchain.py
|
9ae024792f694f90631fc53d578d65e746d6e56e
|
[] |
no_license
|
ChuksXD/SDT-Blockchain
|
ce598de666fce422c6317b0f192d0bd00c79b0d0
|
9665ef272dbf51e631306b1cb573e1167c8a8875
|
refs/heads/master
| 2022-12-04T18:02:33.206330
| 2020-09-04T01:05:47
| 2020-09-04T01:05:47
| 161,278,173
| 1
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,495
|
py
|
# A Dynamic Programming based Python Program for the Knapsack Blockchain problem
# Returns the maximum value that can be put in a Block of capacity 1mb
import time
#dynamic programming function obtained from geeksforgeeks
def knapSack(W, wt, val, n):
K = [[0 for x in range(W+1)] for x in range(n+1)]
# Build table K[][] in bottom up manner
for i in range(n+1):
for w in range(W+1):
if i==0 or w==0:
K[i][w] = 0
elif wt[i-1] <= w:
K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w])
else:
K[i][w] = K[i-1][w]
return K[n][W]
#end knapsack function
#start timer
start_time = time.time()
#extract values from mempool data
id = []
fee=[]
size=[]
with open('transactions.txt','r') as f:
for line in f:
id.append(line.split(',')[1])
fee.append(line.split(',')[8])
size.append(line.split(',')[9])
f.close()
# Main Program to test dynamic function
#divide each fee by 10000 to get value in usd
fee = [float(i)/10000 for i in fee]
size = [float(i) for i in size]
#define blocksize in terms of bytes
Blocksize = 1000000
No_of_items = len(fee)
print("Total Value (in dollars) from transactions in the block",knapSack(Blocksize, size, fee, No_of_items))
# time for the algorithm is computed and printed
elapsed_time_secs = time.time() - start_time
msg = "Execution took: %s secs " %elapsed_time_secs
print(msg)
|
[
"noreply@github.com"
] |
ChuksXD.noreply@github.com
|
aa26dec430edca3bd0a142efad6222448eebef37
|
85c231cde886155a72b2bcef10d974e0507005f6
|
/scrapytutorial/venv/Scripts/pyhtmlizer-script.py
|
de7157cc45c278107e49fc0305e6dbd158b74223
|
[] |
no_license
|
liuyu82910/python_project
|
ab720912099160ce0c089ab30ec02453678374ec
|
d97be5e7b81acef68af5836a54ec6b41cd9b1882
|
refs/heads/master
| 2022-12-25T04:05:30.834678
| 2020-08-15T07:11:48
| 2020-08-15T07:11:48
| 278,800,357
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 431
|
py
|
#!D:\pythonprojects\scrapytutorial\venv\Scripts\python.exe
# EASY-INSTALL-ENTRY-SCRIPT: 'Twisted==19.2.1','console_scripts','pyhtmlizer'
__requires__ = 'Twisted==19.2.1'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
load_entry_point('Twisted==19.2.1', 'console_scripts', 'pyhtmlizer')()
)
|
[
"liuyu910@gmail.com"
] |
liuyu910@gmail.com
|
557c51c02717022fc462a767fb4ccd5e908355a6
|
8d110f3bfcb1330aee56dc1323c8f4616ad9a45c
|
/code/serverless_deployment/user_management.py
|
37527826929c2418862fb3bc9bafdd82e55dbfc0
|
[] |
no_license
|
clwatkins/blink
|
6e38c93924165f1a1940cac12006e8540a9c6f8a
|
cf749ba4fd976b141b7b1c267951939809967fed
|
refs/heads/master
| 2020-03-23T03:20:32.994153
| 2018-07-15T12:56:17
| 2018-07-15T12:56:17
| 141,025,357
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 10,329
|
py
|
from api_management import validate_params, generate_user_key, auth_session, session_authoriser, \
APIResponse, APIResponseError, APIResponseUnauthorized, APIResponseSuccess
from config import *
import json
import datetime as dt
import psycopg2
from psycopg2.extras import RealDictCursor
import boto3
DYNAMO_DB = boto3.resource('dynamodb', region_name=AWS_REGION)
USER_TABLE = DYNAMO_DB.Table(USER_TABLE_NAME)
@validate_params(API_USER_EMAIL, API_USER_PASSWORD)
def create_new_user(event_body, context):
f"""
Handles creation of a new user account.
:param event: (Auto) JSON-encoded API Gateway pass-through.
:param {API_USER_EMAIL}: (Req) User identifier
:param {API_USER_PASSWORD}: (Req) HASHED user password that will be directly stored in DB
:param context: (Auto) JSON-encoded API Gateway pass-through. Not used.
:return: temporary session key if successful for future request authentication.
"""
# check for existing user
if "Item" in USER_TABLE.get_item(Key={USER_EMAIL_FIELD: event_body[API_USER_EMAIL]}).keys():
return APIResponse(status_code=409, message="User already exists").send()
# else add a new one
new_user_response = USER_TABLE.put_item(
Item={
USER_EMAIL_FIELD: event_body[API_USER_EMAIL],
USER_PASSWORD_FIELD: event_body[API_USER_PASSWORD],
USER_CREATE_DT_FIELD: int(dt.datetime.strftime(dt.datetime.utcnow(), DT_FORMAT)),
USER_ACCOUNT_TYPE_FIELD: 'email',
USER_ID_FIELD: 'user_' + generate_user_key(USER_KEY_LENGTH),
USER_LAST_ACCESSED_FIELD: int(dt.datetime.strftime(dt.datetime.utcnow(), DT_FORMAT))
}
)
# check that adding user was successful
if new_user_response['ResponseMetadata']['HTTPStatusCode'] == 200:
# if so, log them in
return user_session_login(event_body, context)
else:
return APIResponseError(status_code=500, message="Server error on user addition").send()
@validate_params(API_USER_EMAIL, API_USER_SESSION_KEY, API_USER_AGE, API_USER_GENDER, API_USER_SIZE, API_USER_NAME)
@auth_session()
def set_user_preferences(event_body, context):
f"""
Handles setting of additional user information / preferences.
:param event: (Auto) JSON-encoded API Gateway pass-through.
:param {API_USER_EMAIL}: (Req) User identifier
:param {API_USER_SESSION_KEY}: (Req) Temporary user-specific session key for authentication
:param {API_USER_AGE}: (Req) User age to be stored in DB (empty string if none)
:param {API_USER_GENDER}: (Req) User gender to be stored in DB (M/F/O, empty string if none)
:param {API_USER_SIZE}: (Req) User size ot be stored in DB (S/M/L/etc, empty string if none)
:param {API_USER_NAME}: (Req) Name of user to be displayed (empty string if none)
:param context: (Auto) JSON-encoded API Gateway pass-through. Not used.
:return: User information if update successful
"""
# update user age, size, gender, name
USER_TABLE.update_item(
Key={
API_USER_EMAIL: event_body[API_USER_EMAIL]
},
UpdateExpression=f"""SET {USER_AGE_FIELD} = :user_age, {USER_SIZE_FIELD} = :user_size, {USER_GENDER_FIELD} =
:user_gender, {USER_NAME_FIELD} = :user_name""",
ExpressionAttributeValues={
':user_age': event_body[API_USER_AGE],
':user_size': event_body[API_USER_SIZE],
':user_gender': event_body[API_USER_GENDER],
':user_name': event_body[API_USER_NAME]
})
# return success message, getting fresh user info from database for response
return APIResponseSuccess(message="User preferences updated.",
response_content={"user_info": json.loads(
get_user_preferences(event_body, context)['body'])['user_info']}).send()
@validate_params(API_USER_EMAIL, API_USER_SESSION_KEY)
@auth_session()
def get_user_preferences(event_body, context):
f"""
Handles retrieval of additional user information / preferences on demand.
:param event: (Auto) JSON-encoded API Gateway pass-through.
:param {API_USER_EMAIL}: (Req) User identifier
:param {API_USER_SESSION_KEY}: (Req) Temporary user-specific session key for authentication
:param context: (Auto) JSON-encoded API Gateway pass-through. Not used.
:return: User information if request successful
"""
# get user information
user_info = USER_TABLE.get_item(Key={API_USER_EMAIL: event_body[API_USER_EMAIL]})
# remove sensitive fields that shouldn't be returned
cleaned_user_info = user_info['Item']
cleaned_user_info.pop(USER_SESSION_KEYS_FIELD)
cleaned_user_info.pop(USER_PASSWORD_FIELD)
cleaned_user_info.pop(USER_EMAIL_FIELD)
return APIResponseSuccess(response_content={"user_info": cleaned_user_info}).send()
@validate_params(API_USER_EMAIL, API_USER_SESSION_KEY)
@auth_session()
def get_user_photos(event_body, context):
f"""
Handles retrieval of list of photos a user has posted.
:param event: (Auto) JSON-encoded API Gateway pass-through.
:param {API_USER_EMAIL}: (Req) User identifier
:param {API_USER_SESSION_KEY}: (Req) Temporary user-specific session key for authentication
:param context: (Auto) JSON-encoded API Gateway pass-through. Not used.
:return: Array of photo ids belonging to user if successful, under "user_photos" key
"""
# get user information
user_info = USER_TABLE.get_item(Key={API_USER_EMAIL: event_body[API_USER_EMAIL]})
try:
return APIResponseSuccess(response_content={"user_photos": user_info['Item'][USER_PHOTOS_FIELD]}).send()
except KeyError:
return APIResponseSuccess(message="User has no uploaded photos", response_content={"user_photos": []}).send()
@validate_params(API_USER_EMAIL, API_USER_SESSION_KEY)
@auth_session()
def get_user_likes(event_body, context):
f"""
Handles retrieval of list of photos a user has liked.
:param event: (Auto) JSON-encoded API Gateway pass-through.
:param {API_USER_EMAIL}: (Req) User identifier
:param {API_USER_SESSION_KEY}: (Req) Temporary user-specific session key for authentication
:param context: (Auto) JSON-encoded API Gateway pass-through. Not used.
:return: Array of photo ids that the user has liked if successful, under "user_likes" key
"""
# get user information
user_info = USER_TABLE.get_item(Key={API_USER_EMAIL: event_body[API_USER_EMAIL]})
try:
return APIResponseSuccess(response_content={"user_likes": user_info['Item'][USER_PHOTO_LIKES_FIELD]}).send()
except KeyError:
return APIResponseSuccess(message="User has liked no photos", response_content={"user_likes": []}).send()
@validate_params(API_USER_EMAIL, API_USER_PASSWORD)
def user_session_login(event_body, context):
f"""
Handles user session log-ins, generating temporary session key for further API requests. Keys auto-expire
after a defined period, requiring a new session log in.
:param event: (Auto) JSON-encoded API Gateway pass-through.
:param {API_USER_EMAIL}: (Req) User identifier
:param {API_USER_PASSWORD}: (Req) HASHED user password that will be directly stored in DB
:param context: (Auto) JSON-encoded API Gateway pass-through. Not used.
:return: Temporary session key under "session_key" key if successful
"""
# get stored password for email
db_password_response = USER_TABLE.get_item(
Key={
API_USER_EMAIL: event_body[API_USER_EMAIL]
})
# verify password
try:
db_password = db_password_response['Item'][API_USER_PASSWORD]
except KeyError:
return APIResponseUnauthorized().send()
if event_body[API_USER_PASSWORD] != db_password:
return APIResponseUnauthorized().send()
# get list of current session keys
current_user_data = USER_TABLE.get_item(Key={API_USER_EMAIL: event_body[API_USER_EMAIL]})
try:
session_keys_list = current_user_data['Item'][USER_SESSION_KEYS_FIELD]
except KeyError:
session_keys_list = []
# generate and store session key in user table
new_session_key = generate_user_key(USER_KEY_LENGTH)
session_keys_list.append(new_session_key)
USER_TABLE.update_item(
Key={
API_USER_EMAIL: event_body[API_USER_EMAIL]
},
UpdateExpression=f'SET {USER_SESSION_KEYS_FIELD} = :session_keys_list',
ExpressionAttributeValues={
':session_keys_list': session_keys_list
})
# add login to user login history table
postgres_db = psycopg2.connect(dbname=AWS_POSTGRES_DB, user=AWS_POSTGRES_USER,
password=AWS_POSTGRES_PASSWORD,
host=AWS_POSTGRES_URL)
postgres_db.autocommit = True
postgres_db_cursor = postgres_db.cursor(cursor_factory=RealDictCursor)
postgres_db_cursor.execute(f"""INSERT INTO {LOGIN_HISTORY_TABLE_NAME} ({LOGIN_HISTORY_DT_FIELD},
{LOGIN_HISTORY_USER_FIELD}) VALUES (%(dt)s, %(user)s)""",
{'dt': int(dt.datetime.strftime(dt.datetime.utcnow(), DT_FORMAT)),
'user': event_body[API_USER_EMAIL]})
postgres_db_cursor.close()
postgres_db.close()
return APIResponseSuccess(response_content={"session_key": new_session_key}).send()
@validate_params(API_USER_EMAIL, API_USER_SESSION_KEY)
@auth_session()
def user_session_leave(event_body, context):
f"""
Handles deletion of session key for a particular user if requested (manual ending of session).
:param event: (Auto) JSON-encoded API Gateway pass-through.
:param {API_USER_EMAIL}: (Req) User identifier
:param {API_USER_SESSION_KEY}: (Req) Temporary user-specific session key for authentication
:return: "API key destroyed" message if successful
"""
if session_authoriser(event_body[API_USER_EMAIL], event_body[API_USER_SESSION_KEY], context):
USER_TABLE.update_item(
Key={
API_USER_EMAIL: event_body[API_USER_EMAIL]
},
UpdateExpression=f'REMOVE {USER_SESSION_KEYS_FIELD}'
)
return APIResponseSuccess(message="API key destroyed").send()
else:
return APIResponseUnauthorized().send()
|
[
"chris.watkins93@gmail.com"
] |
chris.watkins93@gmail.com
|
ef4bb7f66cc3f8d6cd20dec99e4b679be3a428d6
|
bc76c5a016dd1517dabb2b0fbe1a6e0902ec7c0c
|
/synoapi/syno_authenticated_api.py
|
cf21a8167250df7d140dbacecfc0b8d3c43662b2
|
[] |
no_license
|
nkuznetsov44/MovieDownloaderBot
|
dd511d33d95757818f7cfe8cba2b55b0cf10cb36
|
23de470bcf8585483553288a7c87081e753e170b
|
refs/heads/master
| 2023-02-20T22:52:36.644217
| 2022-04-26T07:37:55
| 2022-04-26T07:37:55
| 215,633,867
| 1
| 0
| null | 2023-02-16T04:18:53
| 2019-10-16T20:01:47
|
Python
|
UTF-8
|
Python
| false
| false
| 1,684
|
py
|
from synoapi.syno_api_base import SynoApiBase, SynoApiException
from synoapi.syno_auth_api import SynoApiAuth
SESSION_TIMED_OUT_ERROR_CODE = 106
class SynoAuthenticatedApi(SynoApiBase):
def __init__(self, **kwargs):
base_url = kwargs.pop('base_url')
cgi_path = kwargs.pop('cgi_path')
version = kwargs.pop('version')
api = kwargs.pop('api')
session = kwargs.pop('session')
user = kwargs.pop('user')
password = kwargs.pop('password')
super(SynoAuthenticatedApi, self).__init__(base_url, cgi_path, version, api)
self._session = session
self._user = user
self._password = password
self._sid = None
self._auth_api = SynoApiAuth(base_url)
def _do_get_request(self, **params):
return super(SynoAuthenticatedApi, self).get_request(_sid=self._sid, **params)
def _login_and_do_get_request(self, **params):
self._sid = self._auth_api.login(self._session, self._user, self._password)
return self._do_get_request(**params)
def get_request(self, **params):
if not self._sid:
return self._login_and_do_get_request(**params)
try: # already logged in
return self._do_get_request(**params)
except SynoApiException as e:
if e.error_code == SESSION_TIMED_OUT_ERROR_CODE:
self._sid = None
# if session timed out retrying request
return self._login_and_do_get_request(**params)
raise
def logout(self):
if self._sid:
self._auth_api.logout(self._session, self._sid)
|
[
"nkuznetsov44@gmail.com"
] |
nkuznetsov44@gmail.com
|
6d20fc36d3770dc7a999b9578ddef08a1768cf77
|
69a7b07f865b2026aaba6432ed459bc296f607cb
|
/24- 两两交换链表中的节点/__init__.py
|
77d9cd7631b7fb9dc8cda1f40fd518ee4cc6bf3e
|
[] |
no_license
|
BillyChao/leetcode
|
ac94fe2c969475b4e752fcb5a4a9d6e66720370d
|
5f67368e72c376c1299b849e7a92e6d0cbd9ae55
|
refs/heads/master
| 2023-02-21T01:07:29.839823
| 2023-02-16T16:03:35
| 2023-02-16T16:03:35
| 244,396,454
| 5
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 123
|
py
|
# -*- coding: utf-8 -*-
"""
@Time : 2021/2/2 4:21 下午
@Author : mc
@File : __init__.py.py
@Software: PyCharm
"""
|
[
"mengchao@julive.com"
] |
mengchao@julive.com
|
c84d9f3f8c7f29317b3e1753bb23d86a4e1686ff
|
007f0ceed02dff38ef57a1d05c29150984dc4194
|
/test_auto/pages/home.py
|
9a0cf2b0275ba9d944fdde865af1e78214b5ec65
|
[] |
no_license
|
jparedeslopez/rwconnect
|
620c13e8496eecaaa7c4a835edb550d435f037ea
|
9f4acba8247996427d28dbb513f8b12dac368e0e
|
refs/heads/master
| 2022-02-21T15:47:46.615031
| 2019-08-14T08:44:10
| 2019-08-14T08:44:10
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,064
|
py
|
from .base import BasePage
from appium.webdriver.common.mobileby import MobileBy
class HomePage(BasePage):
# ===================
# Inherited Constants
# ===================
driver = None
logger = None
# =========
# Test Data
# =========
MIC_TEXT = "Mic Pringle"
KATE_TEXT = "Kate Bell"
# ========
# Locators
# ========
FRIENDS = (MobileBy.ACCESSIBILITY_ID, "friends")
INFO_BUTTON = (MobileBy.XPATH, '//XCUIElementTypeButton')
MIC = (MobileBy.ACCESSIBILITY_ID, MIC_TEXT)
KATE = (MobileBy.ACCESSIBILITY_ID, KATE_TEXT)
PLUS_BUTTON = (MobileBy.XPATH, '//XCUIElementTypeNavigationBar[@name="RWConnect"]/XCUIElementTypeButton')
# ============
# Page Methods
# ============
def open_info_button(self):
friends_list = self.get_elements(self.FRIENDS)
mic_element = None
for friend in friends_list:
if self.get_elements(locator=self.MIC, base_elem=friend):
mic_element = friend
break
self.get_element(base_elem=mic_element, locator=self.INFO_BUTTON).click()
def open_contact(self):
friends_list = self.get_elements(self.FRIENDS)
mic_element = None
for friend in friends_list:
if self.get_elements(locator=self.MIC, base_elem=friend):
mic_element = friend
break
self.get_element(base_elem=mic_element, locator=self.MIC).click()
def look_for_friend(self):
friends_list = self.get_elements(self.FRIENDS)
for friend in friends_list:
if self.get_elements(locator=self.KATE, base_elem=friend):
return friend
def add_new_contact(self):
self.get_element(HomePage.PLUS_BUTTON).click()
'''
TO DO:
- Names are hardcoded here. In the test page, I should give the test data I want instead.
- open_info_button and open_contact are basically the same. I should write a common function that can be used by
both of them.
'''
|
[
"paredeslopezjavier@hotmail.com"
] |
paredeslopezjavier@hotmail.com
|
e8477548907efa2599f5e177c2bb7420b6860a34
|
082fc9b4b3136278ea1e41da935f649a0520d191
|
/game/control/models.py
|
e0574832f29f4cea45d5f7f859d0e02e1ce311ab
|
[
"MIT"
] |
permissive
|
dcalacci/Interactive_estimation
|
3c4522504bde69b7d92bee8508e68aec246dfca9
|
4b23adc8d06683ade999a9b2f2150dc0592b2cfc
|
refs/heads/master
| 2021-01-12T12:38:14.894641
| 2016-10-12T03:18:17
| 2016-10-12T03:18:17
| 72,585,751
| 0
| 0
| null | 2016-11-01T23:31:03
| 2016-11-01T23:31:02
| null |
UTF-8
|
Python
| false
| false
| 1,248
|
py
|
from django.db import models
from django.conf import settings
# from game.round.models import Round
# Create your models here.
class Control(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, unique=True)
start_time = models.DateTimeField(auto_now_add=True, null=True)
end_time = models.DateTimeField(null=True)
score = models.DecimalField(max_digits=8, decimal_places=4, default=0.00)
instruction = models.BooleanField(default=False)
exist_survey = models.BooleanField(default=False)
check = models.PositiveIntegerField(default=0)
check_done = models.BooleanField(default=False)
def __str__(self):
return self.user.username
class Survey(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
game = models.OneToOneField(Control)
age = models.PositiveSmallIntegerField(null=True)
gender = models.CharField(max_length=10, choices=(('m', 'Male'),
('f', 'Female'),
), blank=True, null=True)
feedback = models.TextField(null=True)
def __str__(self):
return self.user.username
|
[
"adminq80@gmail.com"
] |
adminq80@gmail.com
|
45bacc15b467e45b46fbb4506ce6511ac9254032
|
87e26c2cc73fe500818d4dc5e4bae16c8401237f
|
/config.py
|
9b75936c32b0ce50a279911b441d4a69af3c77d3
|
[] |
no_license
|
wtichentw/xiao-chi-backend
|
ed8ec0d27dc093664ede642ba1829d2412f520d8
|
bd16ed5296f7fc827090135bdad809195fefe8cc
|
refs/heads/master
| 2021-03-30T16:52:43.107147
| 2018-02-12T18:51:50
| 2018-02-12T18:51:50
| 64,310,660
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,471
|
py
|
""" Dir to te images """
image_dir = '/Users/wtichen/Workspace/xiao-chi'
""" Dir to download original Inception v3 model """
raw_model_dir = '/tmp/imagenet'
""" Dir to put cached bottleneck value """
bottleneck_dir = '/tmp/bottleneck'
""" Dir to put training log for tensorboard """
summaries_dir = '/tmp/retrain_logs'
""" Name for retrained model and category label """
output_graph = '/tmp/output_graph.pb'
output_labels = '/tmp/output_labels.txt'
""" final softmax layer name for our category """
final_tensor_name = "final_result"
""" How many training steps to run before ending."""
how_many_training_steps = 40000
""" How large a learning rate to use when training."""
learning_rate = 0.001
""" How often to evaluate the training results."""
eval_step_interval = 10
""" How many images to train on at a time."""
train_batch_size = 100
""" How many images to test on at a time. This"""
""" test set is only used infrequently to verify"""
""" the overall accuracy of the model."""
test_batch_size = 500
""" How many images to use in an evaluation batch."""
validation_batch_size = 100
""" Percentage to split data for validate and test """
testing_percentage = 10
validation_percentage = 10
DATA_URL = 'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz'
BOTTLENECK_TENSOR_NAME = 'pool_3/_reshape:0'
BOTTLENECK_TENSOR_SIZE = 2048
JPEG_DATA_TENSOR_NAME = 'DecodeJpeg/contents:0'
RESIZED_INPUT_TENSOR_NAME = 'ResizeBilinear:0'
|
[
"wtichen.tw@gmail.com"
] |
wtichen.tw@gmail.com
|
c366673f883aedbb4ec1531f61f37c45851a0ed3
|
fc51a42121d41f5db1bb92e5017133e3f981dd3f
|
/CE889ASSIGNMENT_GENTP53602/MCTS.py
|
6302bba4e19caaf441960cf9d88913a607dab2e5
|
[] |
no_license
|
peterlloydgent/ce888labs
|
3c1d097b3cd077cc7bad95928757cbc78566d7c6
|
44ab16ab8c704f4a8eee29e8213636aae0901962
|
refs/heads/master
| 2020-04-16T14:08:03.072165
| 2019-04-25T09:03:16
| 2019-04-25T09:03:16
| 165,655,959
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 17,160
|
py
|
from math import *
import pandas as pd
from sklearn import tree
import numpy as np
import graphviz
import random
class GameState:
""" A state of the game, i.e. the game board. These are the only functions which are
absolutely necessary to implement UCT in any 2-player complete information deterministic
zero-sum game, although they can be enhanced and made quicker, for example by using a
GetRandomMove() function to generate a random move during rollout.
By convention the players are numbered 1 and 2.
"""
def __init__(self):
self.playerJustMoved = 2 # At the root pretend the player just moved is player 2 - player 1 has the first move
def Clone(self):
""" Create a deep clone of this game state.
"""
st = GameState()
st.playerJustMoved = self.playerJustMoved
return st
def DoMove(self, move):
""" Update a state by carrying out the given move.
Must update playerJustMoved.
"""
self.playerJustMoved = 3 - self.playerJustMoved
def GetMoves(self):
""" Get all possible moves from this state.
"""
def GetResult(self, playerjm):
""" Get the game result from the viewpoint of playerjm.
"""
def __repr__(self):
""" Don't need this - but good style.
"""
pass
class NimState:
""" A state of the game Nim. In Nim, players alternately take 1,2 or 3 chips with the
winner being the player to take the last chip.
In Nim any initial state of the form 4n+k for k = 1,2,3 is a win for player 1
(by choosing k) chips.
Any initial state of the form 4n is a win for player 2.
"""
def __init__(self, ch):
self.playerJustMoved = 2 # At the root pretend the player just moved is p2 - p1 has the first move
self.chips = ch
def Clone(self):
""" Create a deep clone of this game state.
"""
st = NimState(self.chips)
st.playerJustMoved = self.playerJustMoved
return st
def DoMove(self, move):
""" Update a state by carrying out the given move.
Must update playerJustMoved.
"""
assert move >= 1 and move <= 3 and move == int(move)
self.chips -= move
self.playerJustMoved = 3 - self.playerJustMoved
def GetMoves(self):
""" Get all possible moves from this state.
"""
return range(1, min([4, self.chips + 1]))
def GetResult(self, playerjm):
""" Get the game result from the viewpoint of playerjm.
"""
assert self.chips == 0
if self.playerJustMoved == playerjm:
return 1.0 # playerjm took the last chip and has won
else:
return 0.0 # playerjm's opponent took the last chip and has won
def __repr__(self):
s = "Chips:" + str(self.chips) + " JustPlayed:" + str(self.playerJustMoved)
return s
class OXOState:
""" A state of the game, i.e. the game board.
Squares in the board are in this arrangement
012
345
678
where 0 = empty, 1 = player 1 (X), 2 = player 2 (O)
"""
def __init__(self):
self.playerJustMoved = 2 # At the root pretend the player just moved is p2 - p1 has the first move
self.board = [0, 0, 0, 0, 0, 0, 0, 0, 0] # 0 = empty, 1 = player 1, 2 = player 2
def Clone(self):
""" Create a deep clone of this game state.
"""
st = OXOState()
st.playerJustMoved = self.playerJustMoved
st.board = self.board[:]
return st
def DoMove(self, move):
""" Update a state by carrying out the given move.
Must update playerToMove.
"""
assert move >= 0 and move <= 8 and move == int(move) and self.board[move] == 0
self.playerJustMoved = 3 - self.playerJustMoved
self.board[move] = self.playerJustMoved
def GetMoves(self):
""" Get all possible moves from this state.
"""
return [i for i in range(9) if self.board[i] == 0]
def GetResult(self, playerjm):
""" Get the game result from the viewpoint of playerjm.
"""
for (x, y, z) in [(0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6)]:
if self.board[x] == self.board[y] == self.board[z]:
if self.board[x] == playerjm:
return 1.0
else:
return 0.0
if self.GetMoves() == []: return 0.5 # draw
assert False # Should not be possible to get here
def __repr__(self):
s = ""
for i in range(9):
s += ".XO"[self.board[i]]
if i % 3 == 2: s += "\n"
return s
class OthelloState:
""" A state of the game of Othello, i.e. the game board.
The board is a 2D array where 0 = empty (.), 1 = player 1 (X), 2 = player 2 (O).
In Othello players alternately place pieces on a square board - each piece played
has to sandwich opponent pieces between the piece played and pieces already on the
board. Sandwiched pieces are flipped.
This implementation modifies the rules to allow variable sized square boards and
terminates the game as soon as the player about to move cannot make a move (whereas
the standard game allows for a pass move).
"""
def __init__(self, sz=8):
self.playerJustMoved = 2 # At the root pretend the player just moved is p2 - p1 has the first move
self.board = [] # 0 = empty, 1 = player 1, 2 = player 2
self.size = sz
assert sz == int(sz) and sz % 2 == 0 # size must be integral and even
for y in range(sz):
self.board.append([0] * sz)
self.board[sz / 2][sz / 2] = self.board[sz / 2 - 1][sz / 2 - 1] = 1
self.board[sz / 2][sz / 2 - 1] = self.board[sz / 2 - 1][sz / 2] = 2
def Clone(self):
""" Create a deep clone of this game state.
"""
st = OthelloState()
st.playerJustMoved = self.playerJustMoved
st.board = [self.board[i][:] for i in range(self.size)]
st.size = self.size
return st
def DoMove(self, move):
""" Update a state by carrying out the given move.
Must update playerToMove.
"""
(x, y) = (move[0], move[1])
assert x == int(x) and y == int(y) and self.IsOnBoard(x, y) and self.board[x][y] == 0
m = self.GetAllSandwichedCounters(x, y)
self.playerJustMoved = 3 - self.playerJustMoved
self.board[x][y] = self.playerJustMoved
for (a, b) in m:
self.board[a][b] = self.playerJustMoved
def GetMoves(self):
""" Get all possible moves from this state.
"""
return [(x, y) for x in range(self.size) for y in range(self.size) if
self.board[x][y] == 0 and self.ExistsSandwichedCounter(x, y)]
def AdjacentToEnemy(self, x, y):
""" Speeds up GetMoves by only considering squares which are adjacent to an enemy-occupied square.
"""
for (dx, dy) in [(0, +1), (+1, +1), (+1, 0), (+1, -1), (0, -1), (-1, -1), (-1, 0), (-1, +1)]:
if self.IsOnBoard(x + dx, y + dy) and self.board[x + dx][y + dy] == self.playerJustMoved:
return True
return False
def AdjacentEnemyDirections(self, x, y):
""" Speeds up GetMoves by only considering squares which are adjacent to an enemy-occupied square.
"""
es = []
for (dx, dy) in [(0, +1), (+1, +1), (+1, 0), (+1, -1), (0, -1), (-1, -1), (-1, 0), (-1, +1)]:
if self.IsOnBoard(x + dx, y + dy) and self.board[x + dx][y + dy] == self.playerJustMoved:
es.append((dx, dy))
return es
def ExistsSandwichedCounter(self, x, y):
""" Does there exist at least one counter which would be flipped if my counter was placed at (x,y)?
"""
for (dx, dy) in self.AdjacentEnemyDirections(x, y):
if len(self.SandwichedCounters(x, y, dx, dy)) > 0:
return True
return False
def GetAllSandwichedCounters(self, x, y):
""" Is (x,y) a possible move (i.e. opponent counters are sandwiched between (x,y) and my counter in some direction)?
"""
sandwiched = []
for (dx, dy) in self.AdjacentEnemyDirections(x, y):
sandwiched.extend(self.SandwichedCounters(x, y, dx, dy))
return sandwiched
def SandwichedCounters(self, x, y, dx, dy):
""" Return the coordinates of all opponent counters sandwiched between (x,y) and my counter.
"""
x += dx
y += dy
sandwiched = []
while self.IsOnBoard(x, y) and self.board[x][y] == self.playerJustMoved:
sandwiched.append((x, y))
x += dx
y += dy
if self.IsOnBoard(x, y) and self.board[x][y] == 3 - self.playerJustMoved:
return sandwiched
else:
return [] # nothing sandwiched
def IsOnBoard(self, x, y):
return x >= 0 and x < self.size and y >= 0 and y < self.size
def GetResult(self, playerjm):
""" Get the game result from the viewpoint of playerjm.
"""
jmcount = len([(x, y) for x in range(self.size) for y in range(self.size) if self.board[x][y] == playerjm])
notjmcount = len(
[(x, y) for x in range(self.size) for y in range(self.size) if self.board[x][y] == 3 - playerjm])
if jmcount > notjmcount:
return 1.0
elif notjmcount > jmcount:
return 0.0
else:
return 0.5 # draw
def __repr__(self):
s = ""
for y in range(self.size - 1, -1, -1):
for x in range(self.size):
s += ".XO"[self.board[x][y]]
s += "\n"
return s
class Node:
""" A node in the game tree. Note wins is always from the viewpoint of playerJustMoved.
Crashes if state not specified.
"""
def __init__(self, move=None, parent=None, state=None):
self.move = move # the move that got us to this node - "None" for the root node
self.parentNode = parent # "None" for the root node
self.childNodes = []
self.wins = 0
self.visits = 0
self.untriedMoves = state.GetMoves() # future child nodes
self.playerJustMoved = state.playerJustMoved # the only part of the state that the Node needs later
def UCTSelectChild(self):
""" Use the UCB1 formula to select a child node. Often a constant UCTK is applied so we have
lambda c: c.wins/c.visits + UCTK * sqrt(2*log(self.visits)/c.visits to vary the amount of
exploration versus exploitation.
"""
s = sorted(self.childNodes, key=lambda c: c.wins / c.visits + sqrt(2 * log(self.visits) / c.visits))[-1]
return s
def AddChild(self, m, s):
""" Remove m from untriedMoves and add a new child node for this move.
Return the added child node
"""
n = Node(move=m, parent=self, state=s)
self.untriedMoves.remove(m)
self.childNodes.append(n)
return n
def Update(self, result):
""" Update this node - one additional visit and result additional wins. result must be from the viewpoint of playerJustmoved.
"""
self.visits += 1
self.wins += result
def __repr__(self):
return "[M:" + str(self.move) + " W/V:" + str(self.wins) + "/" + str(self.visits) + " U:" + str(
self.untriedMoves) + "]"
def TreeToString(self, indent):
s = self.IndentString(indent) + str(self)
for c in self.childNodes:
s += c.TreeToString(indent + 1)
return s
def IndentString(self, indent):
s = "\n"
for i in range(1, indent + 1):
s += "| "
return s
def ChildrenToString(self):
s = ""
for c in self.childNodes:
s += str(c) + "\n"
return s
def UCT(rootstate, itermax, verbose=False):
""" Conduct a UCT search for itermax iterations starting from rootstate.
Return the best move from the rootstate.
Assumes 2 alternating players (player 1 starts), with game results in the range [0.0, 1.0]."""
rootnode = Node(state=rootstate)
for i in range(itermax):
node = rootnode
state = rootstate.Clone()
# Select
while node.untriedMoves == [] and node.childNodes != []: # node is fully expanded and non-terminal
node = node.UCTSelectChild()
state.DoMove(node.move)
# Expand
if node.untriedMoves != []: # if we can expand (i.e. state/node is non-terminal)
m = random.choice(node.untriedMoves)
state.DoMove(m)
node = node.AddChild(m, state) # add child and descend tree
# Rollout - this can often be made orders of magnitude quicker using a state.GetRandomMove() function
while state.GetMoves() != []: # while state is non-terminal
state.DoMove(random.choice(state.GetMoves()))
# DT goes here TODO
# Backpropagate
while node != None: # backpropagate from the expanded node and work back to the root node
node.Update(state.GetResult(
node.playerJustMoved)) # state is terminal. Update node with result from POV of node.playerJustMoved
node = node.parentNode
# Output some information about the tree - can be omitted
if (verbose):
pass
print(rootnode.TreeToString(0))
else:
pass
print(rootnode.ChildrenToString())
return sorted(rootnode.childNodes, key=lambda c: c.visits)[-1].move # return the move that was most visited
def logState(state, move,data_frame):
player = None
if state.playerJustMoved==2:
player = 1
else:
player = 2
player_state_move_endgame = {'player':player}
player_state_move_endgame['0'] = state.board[0]
player_state_move_endgame['1'] = state.board[1]
player_state_move_endgame['2'] = state.board[2]
player_state_move_endgame['3'] = state.board[3]
player_state_move_endgame['4'] = state.board[4]
player_state_move_endgame['5'] = state.board[5]
player_state_move_endgame['6'] = state.board[6]
player_state_move_endgame['7'] = state.board[7]
player_state_move_endgame['8'] = state.board[8]
player_state_move_endgame['best_move'] = str(move)
df = data_frame.append(player_state_move_endgame,sort=False,ignore_index=True)
return df
def updateWinField(data_frame,won):
data_frame['won'] = won
return data_frame
def concat_data_frames(df,data_frame):
frames = [df,data_frame]
return pd.concat(frames)
def UCTPlayGame(data_frame):
""" Play a sample game between two UCT players where each player gets a different number
of UCT iterations (= simulations = tree nodes).
"""
# state = OthelloState(4) # uncomment to play Othello on a square board of the given size
state = OXOState() # uncomment to play OXO
#state = NimState(15) # uncomment to play Nim with the given number of starting chips
df = pd.DataFrame()
while (state.GetMoves() != []):
if state.playerJustMoved == 1:
m = UCT(rootstate=state, itermax=1000, verbose=False) # play with values for itermax and verbose = True
else:
m = UCT(rootstate=state, itermax=100, verbose=False)
df = logState(state, m, df)
state.DoMove(m)
if state.GetResult(state.playerJustMoved) == 1.0:
print("Player " + str(state.playerJustMoved) + " wins!")
df = updateWinField(df,state.playerJustMoved)
return concat_data_frames(df,data_frame)
elif state.GetResult(state.playerJustMoved) == 0.0:
print("Player " + str(3 - state.playerJustMoved) + " wins!")
df = updateWinField(df,str(3-state.playerJustMoved))
return concat_data_frames(df,data_frame)
else:
print("Nobody wins!")
df = updateWinField(df,0)
return concat_data_frames(df,data_frame)
def visualise_tree(trained_tree):
dot_data = tree.export_graphviz(trained_tree,out_file=None)
graph = graphviz.Source(dot_data)
graph.render("oxo")
def trainTree(read_csv):
clf = tree.DecisionTreeClassifier()
slice_training_data = read_csv[["player","0", "1", "2", "3", "4", "5", "6", "7", "8"]]
slice_prediction_data = read_csv[["best_move"]]
clf.fit(slice_training_data,slice_prediction_data)
visualise_tree(clf)
print(read_csv)
if __name__ == "__main__":
""" Play a single game to the end using UCT for both players.
"""
df = pd.DataFrame(columns=["player", "0", "1", "2", "3", "4", "5", "6", "7", "8", "best_move","won"])
for i in range(10):
df = UCTPlayGame(df)
df.to_csv('100games.csv')
#read_csv = pd.read_csv('10000games.csv')
#trainTree(read_csv)
#df = df[["player", "0", "1", "2", "3", "4", "5", "6", "7", "8", "best_move","won"]]
#print(df)
#df.to_csv('10000games.csv')
|
[
"pvtpetey@corneredrats.com"
] |
pvtpetey@corneredrats.com
|
cfa8a4de78572aeeaeaa5e0383e5379a83763ceb
|
3e150786f79b31fe3e8d7f071e9f3c0fca2cba01
|
/users/migrations/0004_auto_20210911_2048.py
|
42340bf2dd4dd973b9783fd6534663d6280442f1
|
[] |
no_license
|
peyzor/ecommerce
|
6f652a0deee17e06abc65b305abfd8b50e5171fd
|
6304bc05d8ec7e502f700416746844d785b72f97
|
refs/heads/main
| 2023-08-01T07:37:38.832974
| 2021-09-16T10:37:09
| 2021-09-16T10:37:09
| 400,048,620
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,766
|
py
|
# Generated by Django 3.2.6 on 2021-09-11 16:18
from django.db import migrations, models
import phonenumber_field.modelfields
class Migration(migrations.Migration):
dependencies = [
('users', '0003_alter_user_phone'),
]
operations = [
migrations.CreateModel(
name='PhoneToken',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('phone', phonenumber_field.modelfields.PhoneNumberField(editable=False, max_length=128, region=None)),
('otp', models.CharField(editable=False, max_length=40)),
('timestamp', models.DateTimeField(auto_now_add=True)),
('attempts', models.IntegerField(default=0)),
('used', models.BooleanField(default=False)),
],
options={
'verbose_name': 'OTP Token',
'verbose_name_plural': 'OTP Tokens',
},
),
migrations.AlterModelOptions(
name='user',
options={'verbose_name': 'user', 'verbose_name_plural': 'users'},
),
migrations.AlterField(
model_name='user',
name='created_time',
field=models.DateTimeField(auto_now_add=True, verbose_name='created time'),
),
migrations.AlterField(
model_name='user',
name='email',
field=models.EmailField(db_index=True, max_length=255, unique=True, verbose_name='email'),
),
migrations.AlterField(
model_name='user',
name='is_active',
field=models.BooleanField(default=True, verbose_name='is active'),
),
migrations.AlterField(
model_name='user',
name='is_staff',
field=models.BooleanField(default=False, verbose_name='is staff'),
),
migrations.AlterField(
model_name='user',
name='is_verified',
field=models.BooleanField(default=False, verbose_name='is verified'),
),
migrations.AlterField(
model_name='user',
name='phone',
field=phonenumber_field.modelfields.PhoneNumberField(blank=True, max_length=128, null=True, region=None, unique=True, verbose_name='phone'),
),
migrations.AlterField(
model_name='user',
name='updated_time',
field=models.DateTimeField(auto_now=True, verbose_name='updated time'),
),
migrations.AlterField(
model_name='user',
name='username',
field=models.CharField(db_index=True, max_length=255, unique=True, verbose_name='username'),
),
]
|
[
"hassani.peyman627@gmail.com"
] |
hassani.peyman627@gmail.com
|
d27922c492196bf5d7b77ed969e497a8e0ed8be7
|
4fdc3d76d594d437b7ac73e22c7c003713500284
|
/simple_execise/1_two_sum.py
|
2c34325fa2824ea3d0376c9b9b5dfb2b60894083
|
[] |
no_license
|
grb2015/leetcode
|
7b48758e4f0e8c7675520fe1eff64f27f1f3aced
|
847564dd0958768bf10ba91a99aa5363e7b6b15b
|
refs/heads/master
| 2021-06-04T09:13:37.038274
| 2021-01-28T06:13:50
| 2021-01-28T06:13:50
| 144,024,122
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,653
|
py
|
'''
# breif : https://leetcode-cn.com/problems/two-sum/
# history : guo created 20210125
# detail :
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
你可以按任意顺序返回答案。
示例 1:
输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
示例 2:
输入:nums = [3,2,4], target = 6
输出:[1,2]
示例 3:
输入:nums = [3,3], target = 6
输出:[0,1]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
# note :
'''
class Solution(object):
def twoSum(self, nums, target):
for i in range(0,len(nums)):
for j in range(i+1,len(nums)):
if nums[i] + nums[j] == target:
return i,j
if __name__ == '__main__':
# test 1
nums1 = [2,7,11,15]
target1 = 9
s1 = Solution()
print(s1.twoSum(nums1,target1))
# test2
nums1 = [3,2,4]
target1 = 6
s1 = Solution()
print(s1.twoSum(nums1,target1))
# test3
nums1 = [3,3]
target1 = 6
s1 = Solution()
print(s1.twoSum(nums1,target1))
|
[
"949409706@qq.com"
] |
949409706@qq.com
|
e6894af4b61b2ad80571c1c70ecb7f9674a55e2f
|
aeb3181db976cc8b091b19a478b10d0682e7ef9c
|
/layer/gatlayer.py
|
c0529961a078397ab38ee66562c6ff57b71e8799
|
[] |
no_license
|
sidney1994/Graph4CNER
|
a677ec14504d991698a2416bb73f2b3ebf44615e
|
9c365e3f6de2fbc01c1d8a4d738f889a5af18740
|
refs/heads/master
| 2020-08-09T10:12:10.995536
| 2019-09-19T08:30:44
| 2019-09-19T08:30:44
| 214,066,049
| 0
| 0
| null | 2019-10-10T02:14:52
| 2019-10-10T02:14:52
| null |
UTF-8
|
Python
| false
| false
| 3,075
|
py
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class GraphAttentionLayer(nn.Module):
def __init__(self, in_features, out_features, dropout, alpha, concat=True):
super(GraphAttentionLayer, self).__init__()
self.dropout = dropout
self.in_features = in_features
self.out_features = out_features
self.alpha = alpha
self.concat = concat
self.W = nn.Linear(in_features, out_features, bias=False)
# self.W = nn.Parameter(torch.zeros(size=(in_features, out_features)))
nn.init.xavier_uniform_(self.W.weight, gain=1.414)
# self.a = nn.Parameter(torch.zeros(size=(2*out_features, 1)))
self.a1 = nn.Parameter(torch.zeros(size=(out_features, 1)))
self.a2 = nn.Parameter(torch.zeros(size=(out_features, 1)))
nn.init.xavier_uniform_(self.a1.data, gain=1.414)
nn.init.xavier_uniform_(self.a2.data, gain=1.414)
self.leakyrelu = nn.LeakyReLU(self.alpha)
def forward(self, input, adj):
h = self.W(input)
# [batch_size, N, out_features]
batch_size, N, _ = h.size()
middle_result1 = torch.matmul(h, self.a1).expand(-1, -1, N)
middle_result2 = torch.matmul(h, self.a2).expand(-1, -1, N).transpose(1, 2)
e = self.leakyrelu(middle_result1 + middle_result2)
attention = e.masked_fill(adj == 0, -1e9)
attention = F.softmax(attention, dim=2)
attention = F.dropout(attention, self.dropout, training=self.training)
h_prime = torch.matmul(attention, h)
if self.concat:
return F.elu(h_prime)
else:
return h_prime
def __repr__(self):
return self.__class__.__name__ + ' (' + str(self.in_features) + ' -> ' + str(self.out_features) + ')'
class GAT(nn.Module):
def __init__(self, nfeat, nhid, nclass, dropout, alpha, nheads, layer):
super(GAT, self).__init__()
self.dropout = dropout
self.layer = layer
self.attentions = [GraphAttentionLayer(nfeat, nhid, dropout=dropout, alpha=alpha, concat=True) for _ in range(nheads)]
for i, attention in enumerate(self.attentions):
self.add_module('attention_{}'.format(i), attention)
if self.layer == 2:
self.out_att = GraphAttentionLayer(nhid * nheads, nclass, dropout=dropout, alpha=alpha, concat=False)
def forward(self, x, adj):
x = F.dropout(x, self.dropout, training=self.training)
if self.layer == 2:
x = torch.cat([att(x, adj) for att in self.attentions], dim=2)
x = F.dropout(x, self.dropout, training=self.training)
x = F.elu(self.out_att(x, adj))
return F.log_softmax(x, dim=2)
elif self.layer == 1:
x = torch.stack([att(x, adj) for att in self.attentions], dim=2)
x = x.sum(2)
x = F.dropout(x, self.dropout, training=self.training)
return F.log_softmax(x, dim=2)
else:
pass
|
[
"noreply@github.com"
] |
sidney1994.noreply@github.com
|
c109be8d1bcd425c996f70e61a42f5f07308ac4f
|
7b794521083696aa756f543a7e03183813d90fd1
|
/main.py
|
d45b812dded2b74b5227d484fec1acc84f880881
|
[] |
no_license
|
alexanderfournier/PythonJobScraper
|
47481ad6394ca4712ad90ac92a034b51426dbe12
|
54b20affc55eaaf86a7009a363a503fed56f6d9b
|
refs/heads/master
| 2020-03-11T11:31:13.278480
| 2018-04-17T22:23:50
| 2018-04-17T22:23:50
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,618
|
py
|
from selenium import webdriver
from client import LIClient
from settings import search_keys
import argparse
import time
def parse_command_line_args():
parser = argparse.ArgumentParser(description="""
parse LinkedIn search parameters
""")
parser.add_argument('--username', type=str, required=True,
help="""
enter LI username
""")
parser.add_argument('--password', type=str, required=True,
help="""
enter LI password
""")
parser.add_argument('--keyword', default=search_keys['keywords'], nargs='*',
help="""
enter search keys separated by a single space. If the keyword is more
than one word, wrap the keyword in double quotes.
""")
parser.add_argument('--location', default=search_keys['locations'], nargs='*',
help="""
enter search locations separated by a single space. If the location
search is more than one word, wrap the location in double quotes.
""")
parser.add_argument('--search_radius', type=int, default=search_keys['search_radius'], nargs='?',
help="""
enter a search radius (in miles). Possible values are: 10, 25, 35,
50, 75, 100. Defaults to 50.
""")
parser.add_argument('--results_page', type=int, default=search_keys['page_number'], nargs='?',
help="""
enter a specific results page. If an unexpected error occurs, one can
resume the previous search by entering the results page where they
left off. Defaults to first results page.
""")
parser.add_argument('--date_range', type=str, default=search_keys['date_range'], nargs='?',
help="""
specify a specific date range. Possible values are: All, 1, 2-7, 8-14,
15-30. Defaults to 'All'.
""")
parser.add_argument('--sort_by', type=str, default=search_keys['sort_by'], nargs='?',
help="""
sort results by relevance or date posted. If the input string is not
equal to 'Relevance' (case insensitive), then results will be sorted
by date posted. Defaults to sorting by relevance.
""")
parser.add_argument('--salary_range', type=str, default=search_keys['salary_range'], nargs='?',
help="""
set a minimum salary requirement. Possible input values are:
All, 40+, 60+, 80+, 100+, 120+, 140+, 160+, 180+, 200+. Defaults
to All.
""")
parser.add_argument('--filename', type=str, default=search_keys['filename'], nargs='?',
help="""
specify a filename to which data will be written. Defaults to
'output.txt'
""")
return vars(parser.parse_args())
if __name__ == "__main__":
search_keys = parse_command_line_args()
# initialize selenium webdriver - pass latest chromedriver path to webdriver.Chrome()
driver = webdriver.Chrome('/usr/bin/chromedriver')
driver.get("https://www.linkedin.com/uas/login")
# initialize LinkedIn web client
liclient = LIClient(driver, **search_keys)
liclient.login()
# wait for page load
time.sleep(3)
assert isinstance(search_keys["keyword"], list)
assert isinstance(search_keys["location"], list)
for keyword in search_keys["keyword"]:
for location in search_keys["location"]:
liclient.keyword = keyword
liclient.location = location
liclient.navigate_to_jobs_page()
liclient.enter_search_keys()
liclient.customize_search_results()
liclient.navigate_search_results()
liclient.driver_quit()
|
[
"alexander.fournier@nasm.org"
] |
alexander.fournier@nasm.org
|
59da85c28fc543beaacca4c18d28fb374f7968f4
|
1fa25f2749dcb37aab0141a8b039883bcfeb38ff
|
/python/4-16_字符串正则表达式4/A.py
|
b5553530857e04926cda0df7ed76c39e54727204
|
[] |
no_license
|
fangxi1998/UniversityCode
|
4931d6cccd359b75f32b72b05b99f151407c38fc
|
c2a2f018517c4bceb7b93b3e030e722e8bc0848a
|
refs/heads/master
| 2020-04-15T16:26:19.176553
| 2020-01-31T10:45:47
| 2020-01-31T10:45:47
| 164,836,047
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 42
|
py
|
i = input()
a =i.split(' ')
print(len(a))
|
[
"fangxi1998@126.com"
] |
fangxi1998@126.com
|
3a36dce289adfb9878271e60ea05284808f970de
|
6c395464e855b58f153f57720a9029ebf28016ec
|
/scraping/restAPIs/weatherAPI/hw3-pt2-weather.py
|
bcd75ce312d3fa45e77eb177419e0204952868d0
|
[] |
no_license
|
belisards/lede2021
|
c7ed3204f1929db0e174752eb336098dccbf3da5
|
7d2b1948bc937657db63eb0c2f1bcfa767ef47c8
|
refs/heads/main
| 2023-07-26T01:07:31.639372
| 2021-09-08T21:37:07
| 2021-09-08T21:37:07
| 378,686,042
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,573
|
py
|
# -*- coding: utf-8 -*-
import requests
docs = 'https://www.weatherapi.com/docs/'
print(f'The documentations URL is: {docs}')
weathernow = f'http://api.weatherapi.com/v1/current.json?key={my_key}&q={query}'
rio = requests.get(weathernow.replace('{query}','Rio+de+Janeiro')).json()
temp_c = rio['current']['temp_c']
print(f'In {rio["location"]["name"]} - a city based in {rio["location"]["country"]} - it is {temp_c} C degrees')
feelslike_c = rio['current']['feelslike_c']
if feelslike_c > temp_c:
diff = feelslike_c - temp_c
print(f"It feels {diff} degrees warmer")
if temp_c > feelslike_c:
diff = temp_c - feelslike_c
print(f"It feels {diff} degrees cooler")
heathrow = requests.get(weathernow.replace('{query}','iata:LHR')).json()
print(f'In Heathrow International Airport - it is {heathrow["current"]["temp_c"]} C degrees')
forecasts = f'http://api.weatherapi.com/v1/forecast.json?key={my_key}&q=iata:LHR&days=3'
print(f'The API endpoint for 3 days forecasts of Heathrow Airpoirt with my token is: {forecasts}')
response = requests.get(forecasts).json()['forecast']
print("Here are the dates:")
top_day = {}
total = len(response['forecastday'])
for i in range(total):
date = response["forecastday"][i]["date"]
max_temp_c = response["forecastday"][i]["day"]["maxtemp_c"]
top_day[date] = max_temp_c
print(f'{date} with {max_temp_c} degrees C as max. temp.')
print("This is the day with the highest maximum temperature in this forecast:")
print(sorted(top_day.items(), key=lambda day: day[1], reverse=True)[:1])
|
[
"adrianobf@gmail.com"
] |
adrianobf@gmail.com
|
39133129449d28658c12ecd172107daad41d29c1
|
1bed10351039b1c53508a8d1822f0df22e210695
|
/imperative/python/megengine/serialization.py
|
217c34aebf630cd41952e6242ce7965ced34df87
|
[
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] |
permissive
|
chyelang/MegEngine
|
2a39857c5e0db4845b27d3c9e49f2de97f1d38d7
|
4cb7fa8e28cbe7fd23c000e4657300f1db0726ae
|
refs/heads/master
| 2023-08-19T12:08:27.596823
| 2021-10-13T02:51:04
| 2021-10-13T03:19:30
| 250,149,702
| 0
| 0
|
NOASSERTION
| 2020-03-26T03:14:37
| 2020-03-26T03:14:36
| null |
UTF-8
|
Python
| false
| false
| 3,871
|
py
|
# -*- coding: utf-8 -*-
# MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
#
# Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import pickle
from .device import _valid_device, get_default_device
from .tensor import Tensor
from .utils.max_recursion_limit import max_recursion_limit
def save(obj, f, pickle_module=pickle, pickle_protocol=pickle.HIGHEST_PROTOCOL):
r"""Save an object to disk file.
Args:
obj: object to save. Only ``module`` or ``state_dict`` are allowed.
f: a string of file name or a text file object to which ``obj`` is saved to.
pickle_module: Default: ``pickle``.
pickle_protocol: Default: ``pickle.HIGHEST_PROTOCOL``.
"""
if isinstance(f, str):
with open(f, "wb") as fout:
save(
obj, fout, pickle_module=pickle_module, pickle_protocol=pickle_protocol
)
return
with max_recursion_limit():
assert hasattr(f, "write"), "{} does not support write".format(f)
pickle_module.dump(obj, f, pickle_protocol)
class dmap:
def __init__(self, map_location):
self.map_location = map_location
def __enter__(self):
Tensor.dmap_callback = staticmethod(self.map_location)
return self
def __exit__(self, type, value, traceback):
Tensor.dmap_callback = None
def _get_callable_map_location(map_location):
if map_location is None:
def callable_map_location(state):
return state
elif isinstance(map_location, str):
def callable_map_location(state):
return map_location
elif isinstance(map_location, dict):
for key, value in map_location.items():
# dict key and values can only be "xpux", "cpux", "gpu0", etc.
assert _valid_device(key), "Invalid locator_map key value {}".format(key)
assert _valid_device(value), "Invalid locator_map key value {}".format(
value
)
def callable_map_location(state):
if state[:4] in map_location.keys():
state = map_location[state[:4]]
return state
else:
assert callable(map_location), "map_location should be str, dict or function"
callable_map_location = map_location
return callable_map_location
def load(f, map_location=None, pickle_module=pickle):
r"""Load an object saved with :func:~.megengine.save` from a file.
Args:
f: a string of file name or a text file object from which to load.
map_location: Default: ``None``.
pickle_module: Default: ``pickle``.
Note:
* ``map_location`` defines device mapping. See examples for usage.
* If you will call :func:`~.megengine.set_default_device()`, please do it
before :func:`~.megengine.load()`.
Examples:
.. code-block::
import megengine as mge
# Load tensors to the same device as defined in model.pkl
mge.load('model.pkl')
# Load all tensors to gpu0.
mge.load('model.pkl', map_location='gpu0')
# Load all tensors originally on gpu0 to cpu0
mge.load('model.pkl', map_location={'gpu0':'cpu0'})
# Load all tensors to cpu0
mge.load('model.pkl', map_location=lambda dev: 'cpu0')
"""
if isinstance(f, str):
with open(f, "rb") as fin:
return load(fin, map_location=map_location, pickle_module=pickle_module)
map_location = _get_callable_map_location(map_location) # callable map_location
with dmap(map_location) as dm:
return pickle_module.load(f)
|
[
"megengine@megvii.com"
] |
megengine@megvii.com
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.