index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
14,700 | fd1ecf99dabb3f1472bb830ae9ea8bf92cd0de0f | #!/usr/bin/env python
"""Tool to launch ROS and setup environment variables automagically."""
import argparse
import os
import socket
def get_local_ip():
"""Get local ip address."""
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# doesn't even have to be reachable
sock.connect(('8.8.8.8', 1))
ip = sock.getsockname()[0]
except:
ip = '127.0.0.1'
finally:
sock.close()
return ip
def find_pi_pucks():
"""Get the IP of the ROS master server."""
local_ip = get_local_ip().split(".")
ip_prefix = ".".join(local_ip[:-1])
for ip_suffix in map(str, range(256)):
try:
(hostname, _, __) = socket.gethostbyaddr(ip_prefix + "." + ip_suffix)
except socket.herror:
continue
if "pi-puck" in hostname:
yield hostname, ip_prefix + "." + ip_suffix
def main():
"""Entry point function."""
argument_parser = argparse.ArgumentParser()
argument_parser.add_argument("-s", "--ssh", action="store_true")
parsed_args = argument_parser.parse_args()
pi_pucks = list(find_pi_pucks())
if pi_pucks:
print("Pi-pucks:")
for pi_puck_hostname, pi_puck_ip in pi_pucks:
print(" - " + pi_puck_hostname + ", " + pi_puck_ip)
if parsed_args.ssh:
os.execlp("ssh", "ssh", "pi@" + pi_pucks[0][1])
else:
print("No Pi-pucks found.")
if __name__ == "__main__":
main()
|
14,701 | f152faae7b89e7377902462fa8b04778c29862af | import re
from datetime import datetime, timedelta
from settings import *
import math
from urllib.request import urlopen
from bs4 import BeautifulSoup
from firebase import firebase
METRE_CONVERSION = 0.3048 # to convert from feet to metres
def getTideTimesAndTideHeights():
"""scrapes www.tide-forecast.com to collect current tide information.
returns: 2 lists, first list contains first two tide times for current date,
second list contain first two tide heights for current dates"""
html = urlopen(urlTidesInfo)
soup = BeautifulSoup(html, 'lxml')
# scrape url to gather current tide time and height
tideTimes = soup.find_all("td", "time tide", limit=2)
tideHeightImperial = soup.find_all("span", "imperial", limit=2)
# remove html tags
tideTimes = [t.get_text() for t in tideTimes]
tideHeightImperial = [h.get_text() for h in tideHeightImperial]
# parse string and remove tide height, convert from imperial to metres
tideHeightsFinal = []
for h in tideHeightImperial:
height = float(''.join([i for i in h if i.isdigit() or i == "."]))
height *= METRE_CONVERSION
tideHeightsFinal.append(round(height, 1))
# parse string and remove time, convert to float
tideTimesFinal = []
for t in tideTimes:
time = ''.join([i for i in t if i.isdigit() or i == ":"])
time = convertTimeToFloat(time)
tideTimesFinal.append(time)
return tideTimesFinal, tideHeightsFinal
def getCurrentTideHeight(currentTimeString):
"""estimates current tide height given local time,
input: current time as rounded string (hours:minutes),
output: estimate of tide height"""
# convert time in hours:minutes as string to float
currentTimeFloat = convertTimeToFloat(currentTimeString)
# get current tide time and tide height information
tideTimes, tideHeight = getTideTimesAndTideHeights()
# get high and low tide, and time of first High tide
if tideHeight[0] > tideHeight[1]:
highTideHeight = tideHeight[0]
lowTideHeight = tideHeight[1]
firstHighTideTime = tideTimes[0]
else:
highTideHeight = tideHeight[1]
lowTideHeight = tideHeight[0]
firstHighTideTime = tideTimes[1]
amplitude = (highTideHeight - lowTideHeight) / 2
midway = amplitude + lowTideHeight
timeFromFirstHighTide = currentTimeFloat - firstHighTideTime
currentTideHeight = round(midway + abs(amplitude) * math.cos(0.5 * timeFromFirstHighTide), 1)
return currentTideHeight
def getCompassDirections(windDir):
"""input: str between 0 and 360,
output: compass bearing"""
compassDict = {1:'N', 2:'NNE', 3:'NE', 4:'ENE', 5:'E', 6:'ESE', 7:'SE',
8:'SSE', 9:'S', 10:'SSW', 11:'SW', 12:'WSW', 13:'W',
14:'WNW', 15:'NW', 16:'NNW', 17:'N'}
windDirDegrees = float(windDir)
compassIndex = round(windDirDegrees/22.5) + 1
return compassDict[compassIndex]
def getStarRating(waveHeight, windDir, avgWind, tideHeight):
"""returns a star rating between 0 and 5 for current conditions,
input: waveHeight, windDir, avgWind, tideHeight,
output: starRating (int)"""
starRating = 0
# wave height
if waveHeight > 2:
starRating += 4
elif waveHeight > 1.6:
starRating += 3
elif waveHeight > 1.4:
starRating += 2
elif waveHeight > 1.2:
starRating += 1
# wind direction
if windDir >= 270 or windDir <= 30:
starRating += 1
# wind strength
if avgWind < 15:
starRating += 1
# tide
if tideHeight < 1.2:
starRating += 1
elif tideHeight > 2.2:
starRating = 1
# check upper bound of 5 stars
if starRating > 5:
starRating = 5
elif waveHeight < 1:
starRating = 0
return starRating
def roundTime(dateTimeString):
"""rounds a datetime string to nearest 20 minutes,
input: dateTimeString, output: time as string (hours:minutes)"""
dateTimeObj = datetime.strptime(dateTimeString, '%d/%m/%Y %H:%M:%S')
# round to nearest 20 minute
discard = timedelta(minutes=dateTimeObj.minute % 20)
dateTimeObj -= discard
if discard > timedelta(minutes=10):
dateTimeObj += timedelta(minutes=20)
result = dateTimeObj.strftime('%H:%M')
return result
def convertTimeToFloat(timeString):
"""input: time in hours:minutes
output: time as float"""
currentTimeList = timeString.split(":")
currentTimeFloat = round(
float(currentTimeList[0]) + float(currentTimeList[1]) / 60, 2)
return currentTimeFloat
def parseTweet(tweet):
"""parses tweet from DublinBayBuoy, input: tweet (string),
output: dictionary of parsed tweet"""
# Parse data using re
waterTemp = re.search(r'Water Temp:[0-9].[0-9]|Water Temp:[0-9]', tweet)
waveHeight = re.search(r'Wave Height:[0-9].[0-9]|Wave Height:[0-9]', tweet)
windDirection = re.search(r'Wind Dir:[0-9][0-9][0-9]|Wind Dir:[0-9]|Wind Dir:[0-9]', tweet)
gustDirection = re.search(r'Gust Dir:[0-9][0-9][0-9]|Gust Dir:[0-9]|Gust Dir:[0-9]', tweet)
avgWind = re.search(r'Avg Wind:[0-9][0-9]|Avg Wind:[0-9]', tweet)
gust = re.search(r'Gust:[0-9][0-9]|Gust:[0-9]', tweet)
dateTimeTemp = re.search(r'at .*', tweet)
# convert dateTime to datetimeObject for local db
dateTime = dateTimeTemp.group().split(" ")[1] + " " + dateTimeTemp.group().split(" ")[2]
dateTimeObject = datetime.strptime(dateTime, '%d/%m/%Y %H:%M:%S')
# add time rounded to nearest 20 minutes
roundedTime = roundTime(dateTime)
# add compass direction
windDirect = float(windDirection.group().split(":")[1])
compassDir = getCompassDirections(windDirect)
# add tide height
tideHeight = getCurrentTideHeight(roundedTime)
# add star rating
waveHeight=float(waveHeight.group().split(":")[1])
windDir=float(windDirection.group().split(":")[1])
avgWind=float(avgWind.group().split(":")[1])
starRating = getStarRating(waveHeight, windDir, avgWind, tideHeight)
try:
parsedTweet = dict(waterTemp=float(waterTemp.group().split(":")[1]),
waveHeight=waveHeight,
windDir=windDir,
gustDir=float(gustDirection.group().split(":")[1]),
avgWind=avgWind,
gust=float(gust.group().split(":")[1]),
dateTime=dateTimeObject,
roundedTime=roundedTime,
compassDir=compassDir,
tideHeight=tideHeight,
starRating=starRating)
except Exception as e:
print ("Failed to parse tweet")
return None
return parsedTweet
|
14,702 | 0e44bdc4e4dffea2e2e57615aadd3e3c67c0da03 | #Day059 - json and REST APIs
city = input('Enter your city: ')
myAPI = "http://api.openweathermap.org/data/2.5/weather?q="+city+"&appid=526f48b568ce72f1ccfdc6cff57d7392"
import requests
response = requests.get(myAPI)
weather_data = response.json()
weather_data['cod']
#http://api.openweathermap.org/data/2.5/weather?q=London&appid=526f48b568ce72f1ccfdc6cff57d7392
#call above API in browser
|
14,703 | 8ec6f46ef73aaeba4a57c1bd99ea60c1bdb1a1fb | from django.urls import path
from Trinamic import local_views
app_name = 'Trinamic'
urlpatterns = [
path('test', local_views.index, name='test'),
path('product-center/<int:p_id>/<int:c_id>', local_views.product_center, name='product-center'),
path('item-detail/<int:item_id>', local_views.item_detail, name='item-detail')
]
|
14,704 | 37729ab85578a238df08152f8b84c462b2a09ef7 | # -*- coding: utf-8 -*-
"""
Created on Sat Jan 27 2018
@author: Francesco
"""
# ELABORAZIONE DATI JSON
import json
from pprint import pprint
## carica un oggetto da un file
with open("Domini_min.json") as in_json:
data_json = json.load(in_json)
pprint(data_json["listaDomini"][0]) |
14,705 | 0cceb7835e612ca5859e13476f5eeac74c5b3512 | from odoo import models, fields, api, _
from odoo.exceptions import UserError
class NamaModel(models.Model):
_inherit = 'res.partner'
identity_number = fields.Char(
string="KTP Number"
)
father_name = fields.Char(
string="Father's Name"
)
mother_name = fields.Char(
string="Mother's Name"
)
birth_place = fields.Char(
string = "Birth Place"
)
age = fields.Integer(
string = "Umur",
compute = "_compute_age",
store = True,
readonly = True
)
date_of_birth = fields.Date(
string="Date of Birth"
)
blood_type = fields.Selection(
[("a", "A"),
("b", "B"),
("ab", "AB"),
("o", "O")],
string="Blood Type")
gender = fields.Selection(
[("male", "Male"),
("female", "Female")],
string="Gender"
)
marital_status = fields.Selection(
[("single", "Single"),
("married", "Married"),
("divorce", "Divorce")],
string="Marital Status"
)
@api.depends('date_of_birth')
def _compute_age(self) :
today = fields.Date.today()
difference = 0
for people in self :
if people.date_of_birth :
# if date of birth from a person is exist
if people.date_of_birth.month < today.month :
difference = 0
elif people.date_of_birth.month == today.month :
if people.date_of_birth.day <= today.day :
difference = 0
elif people.date_of_birth.day > today.day :
difference = -1
else :
difference = -1
people.age = today.year - people.date_of_birth.year + difference
else :
# if date of birth is not exist
people.age = -1
|
14,706 | a92346af784d641bdb9212dc0c92e9f7c624b313 | # Generated by Django 3.1.7 on 2021-03-19 21:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('NavigationApp', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='vehicle',
name='id',
field=models.AutoField(primary_key=True, serialize=False),
),
]
|
14,707 | 86b0459e8184b41195c515ce57b0f512f81eda8a | # coding: utf-8
import sys
from setuptools import setup, find_packages
NAME = "wavefront-client"
VERSION = "2.1.0"
# To install the library, run the following
#
# python setup.py install
#
# prerequisite: setuptools
# http://pypi.python.org/pypi/setuptools
REQUIRES = ["urllib3 >= 1.10", "six >= 1.9", "certifi", "python-dateutil"]
setup(
name=NAME,
version=VERSION,
description="Wavefront Public API",
author="Wavefront Support",
author_email="support@wavefront.com",
url="https://github.com/wavefrontHQ/python-client",
keywords=["Swagger", "Wavefront", "API", "Wavefront Public API"],
install_requires=REQUIRES,
packages=find_packages(),
include_package_data=True,
long_description="""\
<p>Wavefront public APIs enable you to interact with Wavefront servers using standard web service API tools. You can use the APIs to automate commonly executed operations such as automatically tagging sources.</p><p>When you make API calls outside the Wavefront UI you must add the header \"Authorization: Bearer &lt;&lt;API-TOKEN&gt;&gt;\" to your HTTP requests.</p><p>For legacy versions of the Wavefront API, see the <a href=\"/api-docs/ui/deprecated\">legacy API documentation</a>.</p>
"""
)
|
14,708 | 74d82b62feeaba00fbe067ac55a9efb4ec1e1bd3 | import pandas
from bokeh.layouts import column
from bokeh.models import ColumnDataSource, RangeTool
from bokeh.plotting import figure, output_file, show
#Reading the HTML data into a Pandas dataframe
df = pandas.read_html("https://coinmarketcap.com/currencies/bitcoin/historical-data/?start=20190220&end=20190320")[0][::-1]
#Converting the Date column to the proper datetime format
#e.g. from "Mar 20, 2019" to "2019-03-20"
df["Date"] = pandas.to_datetime(df["Date"])
#Converting the Date column to a NumPy array
dates = df["Date"].to_numpy(dtype = 'datetime64[D]')
#At the most basic level, a ColumnDataSource is simply a mapping between column names and lists of data.
#The ColumnDataSource takes a data parameter which is a dict,
#with string column names as keys and lists (or arrays) of data values as values.
#If one positional argument is passed in to the ColumnDataSource initializer, it will be taken as data.
#Once the ColumnDataSource has been created, it can be passed into the source parameter of plotting methods
#which allows you to pass a column’s name as a stand in for the data values
#Source: https://bokeh.pydata.org/en/latest/docs/user_guide/data.html#columndatasource
source = ColumnDataSource(data = dict(date = dates, close = list(df['Close**'])))
#Creating a new plot with various optional parameters
p = figure(plot_height = 300, plot_width = 1200, tools = "", toolbar_location = None,
x_axis_type = "datetime", x_axis_location = "above",
background_fill_color = "#efefef", x_range=(dates[12], dates[20]))
#Drawing the line
p.line('date', 'close', source = source)
#Naming the y axis
p.yaxis.axis_label = 'Price'
#Creating a new plot (the once containing the range tool) with various optional parameters
select = figure(title = "Drag the middle and edges of the selection box to change the range above",
plot_height = 130, plot_width = 1200, y_range = p.y_range,
x_axis_type = "datetime", y_axis_type = None,
tools = "", toolbar_location = None, background_fill_color = "#efefef")
#Creating the range tool - setting the default range
range_tool = RangeTool(x_range = p.x_range)
#Setting other optional parameters
range_tool.overlay.fill_color = "navy"
range_tool.overlay.fill_alpha = 0.2
#Drawing the line and setting additional parameters
select.line('date', 'close', source = source)
select.ygrid.grid_line_color = None
select.add_tools(range_tool)
select.toolbar.active_multi = range_tool
#Creating the output HTML file in the current folder
output_file("btc_range.html", title = "Bitcoin Price Chart")
#Displaying the final result
show(column(p, select)) |
14,709 | 04909af7a7f3fc71ea6f172a650d5717f3022bbe |
import names
import pandas as pd
import numpy as np
import base64
import io
'''
Generate random guests list
:parameter
:param n: num - number of guests and length of dtf
:param lst_categories: list - ["family", "friends", "university", ...]
:param n_rules: num - number of restrictions to apply (ex. if 1 then 2 guests can't be sit together)
:return
dtf with guests
'''
def random_data(n=100, lst_categories=["family","friends","work","university","tennis"], n_rules=0):
## basic list
lst_dics = []
for i in range(n):
name = names.get_full_name()
category = np.random.choice(lst_categories) if len(lst_categories) > 0 else np.nan
lst_dics.append({"id":i, "name":name, "category":category, "avoid":np.nan})
dtf = pd.DataFrame(lst_dics)
## add rules
if n_rules > 0:
for i in range(n_rules):
choices = dtf[dtf["avoid"].isna()]["id"]
ids = np.random.choice(choices, size=2)
dtf["avoid"].iloc[ids[0]] = int(ids[1]) if int(ids[1]) != ids[0] else int(ids[1])+1
return dtf
'''
When a file is uploaded it contains "contents", "filename", "date"
:parameter
:param contents: file
:param filename: str
:return
pandas table
'''
def upload_file(contents, filename):
content_type, content_string = contents.split(',')
decoded = base64.b64decode(content_string)
try:
if 'csv' in filename:
return pd.read_csv(io.StringIO(decoded.decode('utf-8')))
elif 'xls' in filename:
return pd.read_excel(io.BytesIO(decoded))
except Exception as e:
print("ERROR:", e)
return 'There was an error processing this file.'
'''
Write excel
:parameter
:param dtf: pandas table
:return
link
'''
def download_file(dtf):
xlsx_io = io.BytesIO()
writer = pd.ExcelWriter(xlsx_io)
dtf.to_excel(writer, index=False)
writer.save()
xlsx_io.seek(0)
media_type = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
data = base64.b64encode(xlsx_io.read()).decode("utf-8")
link = f'data:{media_type};base64,{data}'
return link
|
14,710 | 7ccab455d48a66f7ae21604103982ef58f4aca1f | import subprocess
from Systems.NV import nv_parser
from settings import NV_PATH, NV_BATFISH
from Systems.systems import System
class NVInterface(System):
def __init__(self):
super().__init__()
self.compare_items = [
'Node',
'Network',
'Next_Hop',
'Protocol'
]
def __str__(self):
return 'NV'
@staticmethod
def run(path, adj):
with open(f'{path}nv-compile', 'w') as f:
f.write(f'init-snapshot {path} nv-snapshot\n'
f'get compile doData="false", file="{path}nv-gen", doNodeFaults="false",'
f' singlePrefix="false", doNextHop="true"')
subprocess.call(f'source {NV_BATFISH}/tools/batfish_functions.sh; allinone -cmd {path}nv-compile', shell=True)
with open(f'{path}nv-gen_control.nv') as f:
data = f.read()
data = data.replace('o.ad', 'o.ospfAd')
conv = nv_parser.router_to_nv_node_conversion(data)
with open(f'{path}nv-gen_control.nv', 'w') as f:
f.write(data)
with open(f'{path}nv_result.txt', 'w') as f:
subprocess.call([NV_PATH, '-simulate', '-verbose', f'{path}nv-gen_control.nv'], stdout=f)
with open(f'{path}nv_result.txt') as f:
rt = nv_parser.parse_results(f.read())
return nv_parser.build_rt(rt, conv, adj), None, None
@staticmethod
def transform_rt(df):
df.loc[df['Protocol'] == 'ospfIA', 'Protocol'] = 'ospf'
df.loc[df['Protocol'] == 'ospfE1', 'Protocol'] = 'ospf'
df.loc[df['Protocol'] == 'ospfE2', 'Protocol'] = 'ospf'
return df
|
14,711 | ddbcc6238e3416bc98596c22e857da29fd706e38 | from django.views.generic import TemplateView
from fluent_pages import appsettings
class RobotsTxtView(TemplateView):
"""
Exposing a ``robots.txt`` template in the Django project.
Add this view to the ``urls.py``:
.. code-block:: python
from fluent_pages.views import RobotsTxtView
urlpatterns = [
# ...
url(r'^robots.txt$', RobotsTxtView.as_view()),
]
Naturally, this pattern should not be included
inside :func:`~django.conf.urls.i18n.i18n_patterns` as it should appear at the top level.
A ``robots.txt`` template is included by default, which you have override in your own project.
"""
#: The content_type to return.
content_type = 'text/plain'
#: The template to render. You can override this template.
template_name = 'robots.txt'
def render_to_response(self, context, **response_kwargs):
response_kwargs['content_type'] = self.content_type # standard TemplateView does not offer this!
context['ROOT_URL'] = self.request.build_absolute_uri('/')
context['ROBOTS_TXT_DISALLOW_ALL'] = appsettings.ROBOTS_TXT_DISALLOW_ALL
return super(RobotsTxtView, self).render_to_response(context, **response_kwargs)
|
14,712 | eca658fff2a200e18e135bb43a16f4d443929258 | from flask import jsonify, request, url_for, current_app, abort
from .. import db
from ..models import Endereco, EnderecoSchema, Permissao, Bairro
from . import api
from .errors import forbidden, bad_request2
from sqlalchemy.exc import IntegrityError, OperationalError
from marshmallow.exceptions import ValidationError
from .decorators import permissao_requerida
@api.route('/enderecos/')
@permissao_requerida(Permissao.VER_SERVICOS)
def get_enderecos():
enderecos = Endereco.query.all()
return jsonify({'enderecos': [endereco.to_json() for endereco in enderecos]})
@api.route('/enderecos/<int:id>')
@permissao_requerida(Permissao.VER_SERVICOS)
def get_endereco(id):
endereco = Endereco.query.get_or_404(id)
return jsonify(endereco.to_json())
@api.route('/enderecos/<int:id>/<string:rua>/<string:comp>')
@permissao_requerida(Permissao.CADASTRO_BASICO)
def get_endereco_bairro(id, rua, comp):
bairro = Bairro.query.get_or_404(id)
endereco = Endereco.query.filter_by(rua=rua, complemento=comp, bairro=bairro).first()
try:
return jsonify(endereco.to_json())
except:
return bad_request2("Endereco nao encontrado", "Endereço não encontrado")
@api.route('/enderecos/', methods=['POST'])
@permissao_requerida(Permissao.CADASTRO_BASICO)
def new_endereco():
try:
endereco = EnderecoSchema().load(request.json, session=db.session)
except ValidationError as err:
campo = list(err.messages.keys())[0].lower().capitalize()
valor = list(err.messages.values())[0][0].lower()
mensagem = campo + ' ' + valor
return bad_request2(str(err), mensagem)
try:
db.session.add(endereco)
db.session.commit()
except IntegrityError as err:
return bad_request2(str(err), "Erro ao inserir o endereço")
except OperationalError as err:
msg = err._message().split('"')[1]
return bad_request2(str(err), msg)
return jsonify(endereco.to_json()), 201, \
{'Location':url_for('api.get_endereco', id=endereco.id)}
@api.route('/enderecos/<int:id>', methods=['PUT'])
@permissao_requerida(Permissao.CADASTRO_BASICO)
def edit_endereco(id):
endereco = Endereco.query.get_or_404(id)
endereco.rua = request.json.get('rua', endereco.rua)
endereco.complemento = request.json.get('rua', endereco.complemento)
bairro = request.json.get('bairro', endereco.bairro)
if type(bairro) is dict:
if 'id' in bairro.keys():
bairro = Bairro.query.get(int(bairro['id']))
elif 'descricao' in bairro.keys():
bairro = Bairro.query.filter_by(descricao=bairro['descricao']).first()
else:
return bad_request2("Campos id ou descricao do bairro não foram passados")
if bairro is None:
return bad_request2("Bairro não existente", "Bairro não existente")
endereco.bairro = bairro
db.session.add(endereco)
db.session.commit()
return jsonify(endereco.to_json()), 200
@api.route('/enderecos/<int:id>', methods=['DELETE'])
@permissao_requerida(Permissao.CADASTRO_BASICO)
def delete_endereco(id):
endereco = Endereco.query.get_or_404(id)
db.session.delete(endereco)
db.session.commit()
return jsonify({"mensagem":"Endereço apagado com sucesso"}), 200 |
14,713 | a1b9960618a447041dd74a8a8c09c254b0efebbe | import urllib.request as ur
import matplotlib.pyplot as plt
import urllib.parse
import requests
import json
import datetime
import sys
import os.path
api_url_base = 'https://stat.ripe.net/data/'
def get_country_asn(country_code):
api_url = '{}country-asns/data.json?resource={}&lod=1'.format(api_url_base, country_code)
response = requests.get(api_url)
if response.status_code == 200:
country_asns_json = json.loads(response.content.decode('utf-8'))
country_asns = country_asns_json["data"]["countries"][0]["routed"]
return country_asns
else:
return None
def get_country_neighbours(country_code, country_asns):
country_neighbours={}
for asn in country_asns:
#print("studying: ", asn)
api_url = '{}asn-neighbours/data.json?resource={}'.format(api_url_base, asn)
asn_neighbours_json1 = requests.get(api_url)
if (asn_neighbours_json1.status_code == 200):
asn_neighbours_json = json.loads(asn_neighbours_json1.content.decode('utf-8'))
for neighbour in asn_neighbours_json['data']['neighbours']:
neighbour_asn = str(neighbour['asn'])
neighbour_v4_peers = int(neighbour['v4_peers'])
if (neighbour['type']=='left' and neighbour_asn not in country_asns):
if (neighbour_asn not in country_neighbours):
country_neighbours[neighbour_asn] = neighbour_v4_peers
else:
country_neighbours[neighbour_asn] = country_neighbours[neighbour_asn] + neighbour_v4_peers
print(country_neighbours)
return country_neighbours
if __name__ == "__main__":
with open('countries.json', 'r') as f:
countries = json.load(f)
global_country_neighbours = dict();
for country_code in countries.values():
country_asns = get_country_asn(country_code)
country_neighbours = get_country_neighbours(country_code, country_asns)
global_country_neighbours[country_code] = country_neighbours
print(global_country_neighbours)
with open('inter_transit.json', 'w') as fp:
json.dump(global_country_neighbours, fp)
|
14,714 | 8ab17693bc32b01d899c58726e5db0fe8cbd716c | from learnable_encryption import BlockScramble
import numpy as np
def blockwise_scramble(imgs,key_size = 4):
x_stack = None
for k in range(8):
tmp = None
# x_stack = None
for j in range(8):
key_file = 'key4/'+str(0)+'_.pkl'
bs = BlockScramble( key_file )
out = np.transpose(imgs,(0, 2, 3, 1))
out = out[:,k*4:(k+1)*4,j*4:(j+1)*4,:]
out = bs.Scramble(out.reshape([out.shape[0],4,4,3])).reshape([out.shape[0],4,4,3])
if tmp is None:
tmp = out
else:
tmp = np.concatenate((tmp,out),axis=2)
if x_stack is None:
x_stack = tmp
else:
x_stack = np.concatenate((x_stack,tmp),axis=1)
return x_stack
|
14,715 | de9e199d1616964222d9e0d5d83307a563df076e | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
loans = pd.read_csv('/home/ikezogwo/PycharmProjects/Data-Machine-Learning/frust/online/tree/loan_data.csv')
#print(loans.head())
#print(df.describe())
print loans['purpose'].value_counts()
plt.figure(figsize=(10,6))
loans[loans['credit.policy']==1]['fico'].hist(alpha=0.5,color='blue',
bins=30,label='Credit.Policy=1')
loans[loans['credit.policy']==0]['fico'].hist(alpha=0.5,color='red',
bins=30,label='Credit.Policy=0')
plt.legend()
plt.xlabel('FICO')
#plt.show()
plt.figure(figsize=(10,6))
loans[loans['not.fully.paid']==1]['fico'].hist(alpha=0.5,color='blue',
bins=30,label='not.fully.paid=1')
loans[loans['not.fully.paid']==0]['fico'].hist(alpha=0.5,color='red',
bins=30,label='not.fully.paid=0')
plt.legend()
plt.xlabel('FICO')
#plt.show()
plt.figure(figsize=(11,7))
sns.countplot(x='purpose',hue='not.fully.paid',data=loans,palette='Set1')
#sns.plt.show()
def getting_dummies(loans):
purpose = pd.get_dummies(loans['purpose'], drop_first=True)
df = pd.concat([loans, purpose], axis=1)
return df
train = getting_dummies(loans)
print train.head()
X = train.drop(['not.fully.paid', 'purpose'],axis=1)
y = train['not.fully.paid']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=101)
rfc = RandomForestClassifier(n_estimators=600)
dtc = DecisionTreeClassifier()
rfc.fit(X_train, y_train)
dtc.fit(X_train, y_train)
rfc_pred = rfc.predict(X_test)
dtc_pred = dtc.predict(X_test)
print(classification_report(y_test, rfc_pred))
print(classification_report(y_test, dtc_pred))
print(confusion_matrix(y_test, rfc_pred))
print(confusion_matrix(y_test, dtc_pred))
|
14,716 | 90f7dcf08c643efeb6ce99a0f4c14b6330cb48e6 | def make_keys():
d={}
f=open('words.txt')
t=[]
for line in f:
t=t+line.split()
for element in t:
d[element]=''
return d
print make_keys()
|
14,717 | a2fcaff20b61451ade6da032eab2517cde45629d | #!/usr/bin/python
#--------------------------------------------------------------------------------------------------
#-- systemDivisions
#--------------------------------------------------------------------------------------------------
# Program : systemDivisions
# To Complie : n/a
#
# Purpose :
#
# Called By :
# Calls :
#
# Author : Rusty Myers <rzm102@psu.edu>
# Based Upon :
#
# Note :
#
# Revisions :
# 2016-01-25 <rzm102> Initial Version
#
# Version : 1.0
#--------------------------------------------------------------------------------------------------
import sys, glob, os, re, shutil, argparse, subprocess
import urllib2 as url
import xml.etree.ElementTree as ET
# Names of packages to export
name = "CUSTOM"
# Set signing cert to name of certificate on system
# Print certificates in termianl: security find-identity -v -p codesigning
signing_cert='Developer ID Installer: $ORGNAME ($ORGID)'
# Functions to sort list of packages
# https://stackoverflow.com/questions/4623446/how-do-you-sort-files-numerically
def tryint(s):
try:
return int(s)
except:
return s
def alphanum_key(s):
""" Turn a string into a list of string and number chunks.
"z23a" -> ["z", 23, "a"]
"""
return [ tryint(c) for c in re.split('([0-9]+)', s) ]
def sort_nicely(l):
""" Sort the given list in the way that humans expect.
"""
l.sort(key=alphanum_key)
# Function to sign packages
def signPackage(pkg):
# rename unsigned package so that we can slot the signed package into place
print "signPackage received: "
print pkg
pkg_dir = os.path.dirname( pkg )
pkg_base_name = os.path.basename( pkg )
( pkg_name_no_extension, pkg_extension ) = os.path.splitext( pkg_base_name )
unsigned_pkg_path = os.path.join( pkg_dir, pkg_name_no_extension + "-unsigned" + pkg_extension )
os.rename( os.path.abspath(pkg), os.path.abspath(unsigned_pkg_path) )
command_line_list = [ "/usr/bin/productsign", \
"--sign", \
signing_cert, \
unsigned_pkg_path, \
pkg ]
subprocess.call( command_line_list )
os.remove(unsigned_pkg_path)
# Function to remove 'relocate' tags
# This forces installer to place files in correct location on disk
def derelocatePacakge(distroPath):
# Open Distribution file passed to function
tree = ET.parse(distroPath)
# Get the root of the tree
root = tree.getroot()
# Check each child
for child in root:
# If it's a pkg-ref
if child.tag == "pkg-ref":
# Check each subtag
for subtag in child:
# If it's a relocate tag
if subtag.tag == "relocate":
# Remove the whole child
root.remove(child)
# Remove old Distribution file
os.remove(distroPath)
# Write new Distribution file
tree.write(distroPath)
# Function to load the latest BESAgent Installer
def loadPackages():
# searches for BESAgent installer packages, returns latest version if
# multiple are found
# Store packages in local folder
besPkgs = []
# Look in local folder
source = "./"
# check each file
for filename in sorted(os.listdir(source)):
# join path and filename
p=os.path.join(source, filename)
# check if it's a file
if os.path.isfile(p):
# Check if it matches BESAgent regex
pattern = re.compile(r'^BESAgent-(\d+.\d+.\d+.\d+)-*.*pkg')
match = pattern.search(filename)
# If it matches, add it to the array of all packages
if match:
print("Found: " + str(filename))
besPkgs.append(p)
# If we have more than one package found, notify
if len(besPkgs) > 1:
print "Found more than one package, choosing latest version."
sort_nicely(besPkgs)
# Return the last package found, which should be latest verison
return besPkgs[-1]
# Clean out the modified files
def clean_up(oldfilepath):
# We're done with the default folder, so we can remove it
if os.path.isdir(oldfilepath):
shutil.rmtree(oldfilepath)
# Touch a file - written by mah60
def touch(path):
basedir = os.path.dirname(path)
if not os.path.exists(basedir):
os.makedirs(basedir)
open(path, 'a').close()
# Add command line arguments
parser = argparse.ArgumentParser(description='Build Custom BESAgent Installers.', conflict_handler='resolve')
# Add option for adding band
parser.add_argument('--brand','-b', dest='custom_brand', action="append", type=str,
help='add branding text to the BESAgent pacakge')
# Add option for adding custom settings
parser.add_argument('--settings','-s', dest='custom_settings', action="store_true",
help='add custom settings cfg to the BESAgent pacakge')
# Add option for specific package
parser.add_argument('--package','-p', dest='custom_pkg', action="append", type=str,
help='specify the BESAgent pacakge to use')
# Parse the arguments
args = parser.parse_args()
# Check that we're on OS X
if not sys.platform.startswith('darwin'):
print "This script currently requires it be run on macOS"
exit(2)
# run function to get packages
if args.custom_pkg:
default_package = args.custom_pkg[0]
print default_package[0:-4]
default_folder = default_package[0:-4]
else:
default_package = loadPackages()
# remove .pkg from name
default_folder = default_package[2:-4]
# Make sure our modified package folder exists
modifiedFolder = "ModifiedPackage"
if not os.path.isdir(modifiedFolder):
# Make it if needed
os.mkdir(modifiedFolder)
# Notify user of default package being used
print "Using Package: " + default_package
# Make the path for the modified package destination
modifiedDest = os.path.join(modifiedFolder, default_folder)
# Print path for modified folder
# print "Modified Dest: {0}".format(modifiedDest)
# Delete old files
clean_up(modifiedDest)
# Set path to distribution file
DistroFile = os.path.join(modifiedDest, "Distribution")
print("Copying ModifiedFiles...")
# If the default folder is missing
# Default folder is the BESAgent package expanded,
# with the addition of our ModifiedFiles.
if not os.path.isdir(modifiedDest):
# Expand default pacakge to create the default folder
sys_cmd = "pkgutil --expand " + default_package + " " + modifiedDest
os.system(sys_cmd)
# Update Distribution file to remove relocate tags
derelocatePacakge(DistroFile)
# Set up paths to the Modified Files and their new destination in expanded package
src = "./ModifiedFiles/"
dest = os.path.join(modifiedDest, "besagent.pkg/Scripts/")
# Create array of all of the modified files
src_files = os.listdir(src)
# For each file in the array of all modified files
# print "Dest {0}".format(dest)
for file_name in src_files:
# create path with source path and file name
full_file_name = os.path.join(src, file_name)
# if it's a file, copy it to the default folder
if (os.path.isfile(full_file_name)):
if "clientsettings.cfg" in full_file_name:
if args.custom_settings:
print(" Copying: " + str(file_name))
shutil.copy(full_file_name, dest)
else:
print(" Copying: " + str(file_name))
shutil.copy(full_file_name, dest)
# Make dir for destination packages
finishedFolder = default_folder[0:-10] + "Finished"
if not os.path.isdir(finishedFolder):
os.mkdir(finishedFolder)
# Print out the one we're doing
#print "{0:<40}".format(name)
# Name of temp unit folder
unit_folder = default_folder + "-" + name
# Name of unit package
unit_package = unit_folder + ".pkg"
# Copy modified package folder to temp unit folder
sys_cmd = "cp -R " + modifiedDest + " " + unit_folder
os.system(sys_cmd)
# Echo Unit Name into Brand file if requested
if args.custom_brand:
print("Adding custom branding.")
sys_cmd = "echo \"" + name + "\" > " + os.path.join(unit_folder, "besagent.pkg/Scripts" ,"brand.txt")
os.system(sys_cmd)
# Flatten customized unit folder into final package
sys_cmd = "pkgutil --flatten " + unit_folder + " " + finishedFolder + "/" + unit_package
os.system(sys_cmd)
# Clean out custom folder
clean_up(unit_folder)
# Clean ourselves up
clean_up(modifiedDest)
# Uncomment to sign pacakage before finishing
# signPackage(finishedFolder + "/" + unit_package)
print("Package completed: " + str(unit_package))
|
14,718 | cf918b37e8e80db68b89f5a2316ccc789e35de4c | from __future__ import print_function, division
import sys, json, warnings
import numpy as np
import scipy.optimize
from ..data import Trace
from ..util.data_test import DataTestCase
from ..baseline import float_mode
from .fitmodel import FitModel
from .searchfit import SearchFit
class Psp(FitModel):
"""PSP-like fitting model defined as the product of rising and decaying exponentials.
Parameters
----------
x : array or scalar
Time values
xoffset : scalar
Horizontal shift (positive shifts to the right)
yoffset : scalar
Vertical offset
rise_time : scalar
Time from beginning of psp until peak
decay_tau : scalar
Decay time constant
amp : scalar
The peak value of the psp
rise_power : scalar
Exponent for the rising phase; larger values result in a slower activation
Notes
-----
This model is mathematically similar to the double exponential used in
Exp2 (the only difference being the rising power). However, the parameters
are re-expressed to give more direct control over the rise time and peak value.
This provides a flatter error surface to fit against, avoiding some of the
tradeoff between parameters that Exp2 suffers from.
"""
def __init__(self):
FitModel.__init__(self, self.psp_func, independent_vars=['x'])
@staticmethod
def _psp_inner(x, rise, decay, power):
return (1.0 - np.exp(-x / rise))**power * np.exp(-x / decay)
@staticmethod
def _psp_max_time(rise, decay, rise_power):
"""Return the time from start to peak for a psp with given parameters."""
return rise * np.log(1 + (decay * rise_power / rise))
@staticmethod
def psp_func(x, xoffset, yoffset, rise_time, decay_tau, amp, rise_power):
"""Function approximating a PSP shape.
"""
rise_tau = Psp._compute_rise_tau(rise_time, rise_power, decay_tau)
max_val = Psp._psp_inner(rise_time, rise_tau, decay_tau, rise_power)
xoff = x - xoffset
output = np.empty(xoff.shape, xoff.dtype)
output[:] = yoffset
mask = xoff >= 0
output[mask] = yoffset + (amp / max_val) * Psp._psp_inner(xoff[mask], rise_tau, decay_tau, rise_power)
if not np.all(np.isfinite(output)):
raise ValueError("Parameters are invalid: xoffset=%f, yoffset=%f, rise_tau=%f, decay_tau=%f, amp=%f, rise_power=%f, isfinite(x)=%s" % (xoffset, yoffset, rise_tau, decay_tau, amp, rise_power, np.all(np.isfinite(x))))
return output
@staticmethod
def _compute_rise_tau(rise_time, rise_power, decay_tau):
fn = lambda tr: tr * np.log(1 + (decay_tau * rise_power / tr)) - rise_time
return scipy.optimize.fsolve(fn, (rise_time,))[0]
class StackedPsp(FitModel):
"""A PSP on top of an exponential decay.
Parameters are the same as for Psp, with the addition of *exp_amp* and *exp_tau*,
which describe the baseline exponential decay.
"""
def __init__(self):
FitModel.__init__(self, self.stacked_psp_func, independent_vars=['x'])
@staticmethod
def stacked_psp_func(x, xoffset, yoffset, rise_time, decay_tau, amp, rise_power, exp_amp, exp_tau):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
exp = exp_amp * np.exp(-(x-xoffset) / exp_tau)
return exp + Psp.psp_func(x, xoffset, yoffset, rise_time, decay_tau, amp, rise_power)
class PspTrain(FitModel):
"""A Train of PSPs, all having the same rise/decay kinetics.
"""
def __init__(self, n_psp):
self.n_psp = n_psp
def fn(*args, **kwds):
return self.psp_train_func(n_psp, *args, **kwds)
# fn.argnames and fn.kwargs are used internally by lmfit to override
# its automatic argument detection
fn.argnames = ['x', 'xoffset', 'yoffset', 'rise_time', 'decay_tau', 'rise_power']
fn.kwargs = []
for i in range(n_psp):
fn.argnames.extend(['xoffset%d'%i, 'amp%d'%i])
fn.kwargs.append(('decay_tau_factor%d'%i, None))
FitModel.__init__(self, fn, independent_vars=['x'])
@staticmethod
def psp_train_func(n_psp, x, xoffset, yoffset, rise_time, decay_tau, rise_power, **kwds):
"""Paramters are the same as for the single Psp model, with the exception
that the x offsets and amplitudes of each event must be numbered like
xoffset0, amp0, xoffset1, amp1, etc.
"""
for i in range(n_psp):
xoffi = kwds['xoffset%d'%i]
amp = kwds['amp%d'%i]
tauf = kwds.get('decay_tau_factor%d'%i, 1)
psp = Psp.psp_func(x, xoffset+xoffi, 0, rise_time, decay_tau*tauf, amp, rise_power)
if i == 0:
tot = psp
else:
tot += psp
return tot + yoffset
class Psp2(FitModel):
"""PSP-like fitting model with double-exponential decay.
Shape is computed as the product of a rising exponential and the sum of two decaying exponentials.
Parameters are xoffset, yoffset, slope, and amp.
"""
def __init__(self):
FitModel.__init__(self, self.double_psp_func, independent_vars=['x'])
@staticmethod
def double_psp_func(x, xoffset, yoffset, rise_tau, decay_tau1, decay_tau2, amp1, amp2, rise_power=2.0):
"""Function approximating a PSP shape with double exponential decay.
"""
x = x-xoffset
out = np.zeros(x.shape, x.dtype)
mask = x >= 0
x = x[mask]
rise_exp = (1.0 - np.exp(-x / rise_tau))**rise_power
decay_exp1 = amp1 * np.exp(-x / decay_tau1)
decay_exp2 = amp2 * np.exp(-x / decay_tau2)
out[mask] = riseExp * (decay_exp1 + decay_exp2)
return out
def fit_psp(data, search_window, clamp_mode, sign=0, exp_baseline=True, baseline_like_psp=False, refine=True, init_params=None, fit_kws=None, ui=None):
"""Fit a Trace instance to a StackedPsp model.
This function is a higher-level interface to StackedPsp.fit:
* Makes some assumptions about typical PSP/PSC properties based on the clamp mode
* Uses SearchFit to find a better fit over a wide search window, and to avoid
common local-minimum traps.
Parameters
----------
data : neuroanalysis.data.TSeries instance
Contains data on trace waveform.
search_window : tuple
start, stop range over which to search for PSP onset.
clamp_mode : string
either 'ic' for current clamp or 'vc' for voltage clamp
sign : int
Specifies the sign of the PSP deflection. Must be 1, -1, or 0.
exp_baseline : bool
If True, then the pre-response baseline is fit to an exponential decay.
This is useful when the PSP follows close after another PSP or action potential.
baseline_like_psp : bool
If True, then the baseline exponential tau and psp decay tau are forced to be equal,
and their amplitudes are forced to have the same sign.
This is useful in situations where the baseline has an exponential decay caused by a preceding
PSP of similar shape, such as when fitting one PSP in a train.
refine : bool
If True, then fit in two stages, with the second stage searching over rise/decay.
init_params : dict
Initial parameter guesses
fit_kws : dict
Extra keyword arguments to send to the minimizer
Returns
-------
fit : lmfit.model.ModelResult
Best fit
"""
import pyqtgraph as pg
prof = pg.debug.Profiler(disabled=True, delayed=False)
prof("args: %s %s %s %s %s %s %s %s" % (search_window, clamp_mode, sign, exp_baseline, baseline_like_psp, refine, init_params, fit_kws))
if ui is not None:
ui.clear()
ui.console.setStack()
ui.plt1.plot(data.time_values, data.data)
ui.plt1.addLine(x=search_window[0], pen=0.3)
ui.plt1.addLine(x=search_window[1], pen=0.3)
prof('plot')
if fit_kws is None:
fit_kws = {}
if init_params is None:
init_params = {}
method = 'leastsq'
fit_kws.setdefault('maxfev', 500)
# good fit, slow
# method = 'Nelder-Mead'
# fit_kws.setdefault('options', {
# 'maxiter': 300,
# # 'disp': True,
# })
# good fit
# method = 'Powell'
# fit_kws.setdefault('options', {'maxfev': 200, 'disp': True})
# bad fit
# method = 'CG'
# fit_kws.setdefault('options', {'maxiter': 100, 'disp': True})
# method = 'L-BFGS-B'
# fit_kws.setdefault('options', {'maxiter': 100, 'disp': True})
# take some measurements to help constrain fit
data_min = data.data.min()
data_max = data.data.max()
data_mean = data.mean()
baseline_mode = float_mode(data.time_slice(None, search_window[0]).data)
# set initial conditions depending on whether in voltage or current clamp
# note that sign of these will automatically be set later on based on the
# the *sign* input
if clamp_mode == 'ic':
amp_init = init_params.get('amp', .2e-3)
amp_max = min(100e-3, 3 * (data_max-data_min))
rise_time_init = init_params.get('rise_time', 5e-3)
decay_tau_init = init_params.get('decay_tau', 50e-3)
exp_tau_init = init_params.get('exp_tau', 50e-3)
exp_amp_max = 100e-3
elif clamp_mode == 'vc':
amp_init = init_params.get('amp', 20e-12)
amp_max = min(500e-12, 3 * (data_max-data_min))
rise_time_init = init_params.get('rise_time', 1e-3)
decay_tau_init = init_params.get('decay_tau', 4e-3)
exp_tau_init = init_params.get('exp_tau', 4e-3)
exp_amp_max = 10e-9
else:
raise ValueError('clamp_mode must be "ic" or "vc"')
# Set up amplitude initial values and boundaries depending on whether *sign* are positive or negative
if sign == -1:
amp = (-amp_init, -amp_max, 0)
elif sign == 1:
amp = (amp_init, 0, amp_max)
elif sign == 0:
amp = (0, -amp_max, amp_max)
else:
raise ValueError('sign must be 1, -1, or 0')
# initial condition, lower boundary, upper boundary
base_params = {
'yoffset': (init_params.get('yoffset', baseline_mode), data_min, data_max),
'rise_time': (rise_time_init, rise_time_init/10., rise_time_init*10.),
'decay_tau': (decay_tau_init, decay_tau_init/10., decay_tau_init*10.),
'rise_power': (2, 'fixed'),
'amp': amp,
}
# specify fitting function and set up conditions
psp = StackedPsp()
if exp_baseline:
if baseline_like_psp:
exp_min = 0 if sign == 1 else -exp_amp_max
exp_max = 0 if sign == -1 else exp_amp_max
base_params['exp_tau'] = 'decay_tau'
else:
exp_min = -exp_amp_max
exp_max = exp_amp_max
base_params['exp_tau'] = (exp_tau_init, exp_tau_init / 10., exp_tau_init * 20.)
base_params['exp_amp'] = (0.01 * sign * amp_init, exp_min, exp_max)
else:
base_params.update({'exp_amp': (0, 'fixed'), 'exp_tau': (1, 'fixed')})
# print(clamp_mode, base_params, sign, amp_init)
# if weight is None: #use default weighting
# weight = np.ones(len(y))
# else: #works if there is a value specified in weight
# if len(weight) != len(y):
# raise Exception('the weight and array vectors are not the same length')
# fit_kws['weights'] = weight
# Round 1: coarse fit
# Coarse search xoffset
n_xoffset_chunks = max(1, int((search_window[1] - search_window[0]) / 1e-3))
xoffset_chunks = np.linspace(search_window[0], search_window[1], n_xoffset_chunks+1)
xoffset = [{'xoffset': ((a+b)/2., a, b)} for a,b in zip(xoffset_chunks[:-1], xoffset_chunks[1:])]
prof('prep for coarse fit')
# Find best coarse fit
search = SearchFit(psp, [xoffset], params=base_params, x=data.time_values, data=data.data, fit_kws=fit_kws, method=method)
for i,result in enumerate(search.iter_fit()):
pass
# prof(' coarse fit iteration %d/%d: %s %s' % (i, len(search), result['param_index'], result['params']))
fit = search.best_result.best_values
prof("coarse fit done (%d iter)" % len(search))
if ui is not None:
br = search.best_result
ui.plt1.plot(data.time_values, br.best_fit, pen=(0, 255, 0, 100))
if not refine:
return search.best_result
# Round 2: fine fit
# Fine search xoffset
fine_search_window = (max(search_window[0], fit['xoffset']-1e-3), min(search_window[1], fit['xoffset']+1e-3))
n_xoffset_chunks = max(1, int((fine_search_window[1] - fine_search_window[0]) / .2e-3))
xoffset_chunks = np.linspace(fine_search_window[0], fine_search_window[1], n_xoffset_chunks + 1)
xoffset = [{'xoffset': ((a+b)/2., a, b)} for a,b in zip(xoffset_chunks[:-1], xoffset_chunks[1:])]
# Search amp / rise time / decay tau to avoid traps
rise_time_inits = base_params['rise_time'][0] * 1.2**np.arange(-1,6)
rise_time = [{'rise_time': (x,) + base_params['rise_time'][1:]} for x in rise_time_inits]
decay_tau_inits = base_params['decay_tau'][0] * 2.0**np.arange(-1,2)
decay_tau = [{'decay_tau': (x,) + base_params['decay_tau'][1:]} for x in decay_tau_inits]
search_params = [
rise_time,
decay_tau,
xoffset,
]
# if 'fixed' not in base_params['exp_amp']:
# exp_amp_inits = [0, amp_init*0.01, amp_init]
# exp_amp = [{'exp_amp': (x,) + base_params['exp_amp'][1:]} for x in exp_amp_inits]
# search_params.append(exp_amp)
# if no sign was specified, search from both sides
if sign == 0:
amp = [{'amp': (amp_init, -amp_max, amp_max)}, {'amp': (-amp_init, -amp_max, amp_max)}]
search_params.append(amp)
prof("prepare for fine fit %r" % base_params)
# Find best fit
search = SearchFit(psp, search_params, params=base_params, x=data.time_values, data=data.data, fit_kws=fit_kws, method=method)
for i,result in enumerate(search.iter_fit()):
pass
prof(' fine fit iteration %d/%d: %s %s' % (i, len(search), result['param_index'], result['params']))
fit = search.best_result
prof('fine fit done (%d iter)' % len(search))
return fit
class PspFitTestCase(DataTestCase):
def __init__(self):
DataTestCase.__init__(self, PspFitTestCase.fit_psp)
@staticmethod
def fit_psp(**kwds):
result = fit_psp(**kwds)
# for storing / comparing fit results, we need to return a dict instead of ModelResult
ret = result.best_values.copy()
ret['nrmse'] = result.nrmse()
return ret
@property
def name(self):
meta = self.meta
return "%0.3f_%s_%s_%s_%s" % (meta['expt_id'], meta['sweep_id'], meta['pre_cell_id'], meta['post_cell_id'], meta['pulse_n'])
def _old_load_file(self, file_path):
test_data = json.load(open(file_path))
self._input_args = {
'data': Trace(data=np.array(test_data['input']['data']), dt=test_data['input']['dt']),
'xoffset': (14e-3, -float('inf'), float('inf')),
'weight': np.array(test_data['input']['weight']),
'sign': test_data['input']['amp_sign'],
'stacked': test_data['input']['stacked'],
}
self._expected_result = test_data['out']['best_values']
self._meta = {}
self._loaded_file_path = file_path
def load_file(self, file_path):
DataTestCase.load_file(self, file_path)
xoff = self._input_args.pop('xoffset', None)
if xoff is not None:
self._input_args['search_window'] = xoff[1:]
|
14,719 | 46246203684cefe976b065f835593f35bdfb48b7 | from multiprocessing import Process
import time
#一种直接使用多进程函数的方法
def f(name):
time.sleep(1)
print('hello',name,time.ctime())
if __name__ == '__main__':
p_list = []
for i in range(5):
p = Process(target=f,args=('xiaoming',))
p_list.append(p)
p.start()
#for p in p_list:
#p.join()
print('我是主进程')
#还有另外一种使用类方式的多进程方法
|
14,720 | 33834044bf04ef70d8910672348711dd73aceaa3 | # # 路由的功能
# # 伪静态实现
# # 正则版路由
# # 增删改查系
# # 日志相关系
# import urllib
# # url编码
# result = urllib.parse.quote("http://www.test.com/wd=逸鹏说道")
# print(result)
# # url解码
# new_result = urllib.parse.unquote(result)
# print(new_result)
# # 把键值对编码为url查询字符串
# result = urllib.parse.urlencode({"wd": "逸鹏说道"})
# print(result)
# # url解码
# new_result = urllib.parse.unquote(result)
# print(new_result)
# # 正文编码
# input_str = "<script>aleter('x xx x');</script>"
# # 正文解码
# # ---
# # logging
import logging
# # 1.控制台输出
# # 默认是 logging.WARNING
# # asctime:时间,文件名:filename,行号:lineno,级别:levelname,消息:message
# logging.basicConfig(level=logging.INFO,format="%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
# logging.debug("debug logging")
# logging.info("info logging")
# logging.warning("warning logging")
# logging.error("error logging")
# logging.critical("critical logging")
# 2.文件写入
import time
logging.basicConfig(level=logging.INFO,filename=f"{time.strftime('%Y-%m-%d',time.localtime())}.log",filemode="a+",format="%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
logging.debug("debug logging")
logging.info("info logging")
logging.warning("warning logging")
logging.error("error logging")
logging.critical("critical logging")
|
14,721 | bb6b6b2efbbbcf50f5a5cd71e3f9c2529fef0fc6 | import json
from ui import qtx
class Settings:
'''Class that looks like a normal dictionary, but is persistent.
The persistence is backed by registry via QSettings service.
Attention: known deviations from normal dict behavior:
* saving tuples will return a list.
'''
def __init__(self, app_identity):
'''Creates new persistent settings object for the application.
'''
self._engine = qtx.QSettings('innodata.com', app_identity)
def get(self, key, default=None):
if key in self:
return _from_string(self._engine.value(key))
return default
def setdefault(self, key, default=None):
if key not in self:
self[key] = default
return self[key]
def clear(self):
self._engine.clear()
def keys(self):
return self._engine.allKeys()
def values(self):
return [self[key] for key in self.keys()]
def items(self):
return zip(self.keys(), self.values())
def update(self, *av, **kav):
if av:
if kav:
raise ValueError('use only keyword arguments or only positional argument, not both')
if len(av) != 1:
raise ValueError('only one positional argument is expected')
items = av[0]
if type(items) is dict:
items = items.items()
else:
items = kav.items()
for k, v in items:
self[k] = v
def __getitem__(self, key):
if key not in self:
raise KeyError(key)
return self.get(key)
def __setitem__(self, key, value):
if type(key) is not str or not key:
raise ValueError('invalid key - must be non-empty string')
self._engine.setValue(key, _as_string(value))
def __delitem__(self, key):
if key not in self:
raise KeyError(key)
self._engine.remove(key)
def __contains__(self, key):
return self._engine.contains(key)
def __iter__(self):
return iter(self.keys())
def sync(self):
self._engine.sync()
def _as_string(obj):
if obj is None or type(obj) in (int, bytes):
return obj
return json.dumps(obj)
def _from_string(obj):
if obj is None or type(obj) in (int, bytes):
return obj
return json.loads(obj)
|
14,722 | 1a23032a41d3ce1ad5480fb9879942bf16751314 | # -*- coding: utf-8 -*-
from Cluster import Cluster
class KMedias:
def __init__(self, datos, headers):
self.datos = datos
self.headers = headers
def armarCluster(self, cantCluster, repeticiones):
self.Kclusters = cantCluster
self.repeticiones = repeticiones
#lista de clusters, cada sub-indice tendra el cluster generado
self.clusters = []
print "armando clusters: \n"
for i in range(0, self.repeticiones):
#hago un nuevo cluster
cluster = Cluster(self.datos, self.headers, self.Kclusters)
#le digo q se ponga puntos al azar
cluster.repartirPuntos()
#le digo que se encuentre sus centroides
cluster.calcular()
#lo guardo en la lista de clusters
self.clusters.append(cluster)
#ahora busco el mejor de los clusters en base a su silueta
self.buscarMejor()
self.imprimirMejorCluster()
def buscarMejor(self):
mejorSilueta = self.clusters[0].getSilueta()
mejorCluster = self.clusters[0]
for i in range(0, self.repeticiones):
silueta = self.clusters[i].getSilueta()
if(silueta < mejorSilueta):
mejorSilueta = silueta
mejorCluster = self.clusters[i]
self.mejorCluster = mejorCluster
def imprimirMejorCluster(self):
#print " El mejor cluster es: \n"
#print self.mejorCluster
print "no hay mejor cluster por que no comparo siluetas"
|
14,723 | 27226ea0f0eca96ab4e3f8876e8feded50c7eba0 | from typing import List
class RotateImage:
"""
Problem: Rotate Image (#48)
Problem Description:
Given n x n 2D matrix, rotate the image by 90 degrees (clockwise)
Must rotate the image in-place (do not allocate another 2D matrix)
Key Insights:
1. Rotate values counter clockwise, ex left col to top col
2. Save value in top call to topLeft for each iteration
Steps:
1. Use l, r, top, bottom pointers and move with +/- i
2. Save values in top row top left cell in each iteration
3. Rotate values counter clockwise
a. left col to top row
b. bottom row to left col
c. right col to bottom row
d. topLeft to right col
4. Increment l pointer, decrement r pointer
5. Do this rotation r - l times (n - 1)
Time Complexity:
O(n^2) time: Traverse every cell
O(1) space: Only create topLeft variable to store value from top row
"""
def rotate(self, matrix: List[List[int]]) -> None:
l, r = 0, len(matrix) - 1
while l < r:
top, bottom = l, r
for i in range(r - l):
topLeft = matrix[top][l + i]
matrix[top][l + i] = matrix[bottom - i][l]
matrix[bottom - i][l] = matrix[bottom][r - i]
matrix[bottom][r - i] = matrix[top + i][r]
matrix[top + i][r] = topLeft
l += 1
r -= 1
|
14,724 | 3c8907eda8b61bc8bdaccf5102f0de837aa484f2 | {
'includes':[
'../common/common.gypi',
],
'targets': [
{
'target_name': 'tizen_download',
'type': 'loadable_module',
'sources': [
'download_api.js',
'download_extension.cc',
'download_extension.h',
'download_instance.cc',
'download_instance.h',
'download_instance_desktop.cc',
'download_instance_tizen.cc',
'download_utils.h',
'../common/virtual_fs.cc',
'../common/virtual_fs.h',
],
'conditions': [
['tizen == 1', {
'includes': [
'../common/pkg-config.gypi',
],
'variables': {
'packages': [
'capi-appfw-application',
'capi-web-url-download',
]
},
}],
],
},
],
}
|
14,725 | dff4298ae886c8d2b9aa2481a88426201a93399d | a=int(input())
summer=0
while a>0:
s=a%10
summer=summer+s
a=a//10
summer=str(summer)
t=summer[::-1]
if t==summer:
print("YES")
else:
print("NO")
|
14,726 | d21fd4117f70040800939401bc4d020d97c224cc | """
-------------
Dropdown menu
-------------
Usually used in tables to add actions for rows.
"""
# 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.
from pom import ui
from selenium.webdriver.common.by import By
@ui.register_ui(
button_toggle=ui.Button(By.CSS_SELECTOR, '.dropdown-toggle'),
item_default=ui.UI(By.CSS_SELECTOR,
'button:nth-of-type(1), a:nth-of-type(1)'),
item_delete=ui.UI(By.CSS_SELECTOR, '[id$="action_delete"]'),
item_edit=ui.UI(By.CSS_SELECTOR, '[id$="action_edit"]'))
class DropdownMenu(ui.Block):
"""Dropdown menu."""
def __init__(self, *args, **kwgs):
"""Constructor.
It has predefined selector.
"""
super(DropdownMenu, self).__init__(*args, **kwgs)
self.locator = By.CSS_SELECTOR, '.btn-group'
|
14,727 | 9768b857da88ff8d45ae7960851a2e8beb684c5d | import json
from PyInquirer import prompt, Separator # type: ignore
import requests
from apihandler import APIHandler
from move import Move
class Pokemon():
"""
A class to represent a Pokemon
Attributes:
id: int
Pokedex ID of the pokemon
name: str
Name of the pokemon
types: tuple
The type(s) that the pokemon belongs to
weight: int
The weight of the pokemon in hectograms
height: int
The height of the pokemon in decimetres
abilities: dict
The abilities of the pokemon
move_list: list
The list of moves the pokemon is able to learn
move_set: list
The list of moves the pokemon has learnt as Move objects
Methods:
from_json(cls, data: dict)
Creates a Pokemon object from a json dictionary
from_response(cls, api_handler: APIHandler, response: requests.models.Response)
Creates a Pokemon object from a Response object
view_pokemon(self, team_name: str, team_choice: str)
Displays the Pokemon object's information
get_pokemon_options(self, mode: str)
Gets the options to use in Pokemon.pokemon_menu()
get_pokemon_move_slots_options(self, mode: str)
Gets the move slot options to use in Pokemon.pokemon_menu()
pokemon_menu(self, mode: str)
Displays the menu for the Pokemon screen
select_pokemon(api_handler: APIHandler)
Displays the input field for the user to select and view a pokemon list or search for a pokemon
view_pokemon_list(view_list: str, number: int, response: requests.models.Response)
Displays the list of pokemon from the generation given by the user's input
confirm_pokemon()
Get confirmation to add the pokemon to the currently selected pokemon slot
"""
def __init__(self, id: int, name: str, types: tuple, weight: int, height: int,
abilities: dict, move_list: list, move_set: list) -> None:
"""
Sets the required attributes for the Pokemon object
Parameters:
id: int
Pokedex ID of the pokemon
name: str
Name of the pokemon
types: tuple
The type(s) that the pokemon belongs to
weight: int
The weight of the pokemon in hectograms
height: int
The height of the pokemon in decimetres
abilities: dict
The abilities of the pokemon
move_list: list
The list of moves the pokemon is able to learn
move_set: list
The list of moves the pokemon has learnt as Move objects
"""
self.id: int = id
self.name: str = name
self.types: tuple = types
self.weight: int = weight
self.height: int = height
self.abilities: dict = abilities
self.move_list: list = move_list
self.move_set: list = move_set
@classmethod
def from_json(cls, data: dict) -> "Pokemon":
"""
Creates a Pokemon object from a json dictionary
Parameters:
data: dict
Dictionary containing attribute, value pairs from the applications saved json data
Returns:
Pokemon object
"""
moves: list = list(map(Move.from_json, data["move_set"]))
return cls(data["id"], data["name"], data["types"], data["weight"],
data["height"], data["abilities"], data["move_list"], moves)
@classmethod
def from_response(cls, api_handler: APIHandler, response: requests.models.Response) -> "Pokemon":
"""
Creates a Pokemon object from a Response object,
additional api calls are required to fetch ability effect information
Parameters:
api_handler: APIHandler
The APIHandler object used to make api calls
response: requests.models.Response
Response object from APIHandler.get_pokemon()
Returns:
Pokemon object
"""
api_data: dict = json.loads(response.text)
id: int = api_data["id"]
name: str = api_data["name"].capitalize()
types: tuple = tuple([type["type"]["name"].capitalize() for type in api_data["types"]])
weight: int = api_data["weight"]
height: int = api_data["height"]
abilities: dict = {}
for ability in api_data["abilities"]:
r: dict = json.loads(api_handler.get_ability(ability["ability"]["name"]).text)
for effect_entry in r["effect_entries"]:
if effect_entry["language"]["name"] == "en":
abilities[ability["ability"]["name"].capitalize()] = effect_entry["effect"].replace("\n", " ").replace(" ", " ")
move_list: list = [move["move"]["name"].capitalize() for move in api_data["moves"]]
default_move: list = ["None", 0, 0, 0, "None", 0, "None"]
if len(move_list) < 4:
move_set: list = [Move(*default_move) for i in range(len(move_list))]
else:
move_set = [Move(*default_move) for i in range(4)]
return cls(id, name, types, weight, height, abilities, move_list, move_set)
def view_pokemon(self, team_name: str, team_choice: str) -> None:
"""
Displays the Pokemon object's information
Parameters:
team_name: str
The name attribute of the currently selected Team
team_choice: str
The team slot number of the currently selected Pokemon
Returns:
None
"""
print(f"\n\u001b[1m\u001b[4mTeam\u001b[0m: \u001b[7m {team_name} \u001b[0m")
print(f"\n\u001b[4mPokémon Slot #{int(team_choice)}\u001b[0m\n\n")
print(f"\u001b[1mName\u001b[0m: {self.name}")
print(f"\u001b[1mPokédex ID:\u001b[0m {self.id}\n")
print(f"\u001b[1mHeight\u001b[0m: {self.height} decimetres")
print(f"\u001b[1mWeight\u001b[0m: {self.weight} hectograms\n")
if len(self.types) == 2:
print(f"\u001b[1mTypes\u001b[0m: {self.types[0]}")
print(f" {self.types[1]}")
else:
print(f"\u001b[1mType\u001b[0m: {self.types[0]}")
print("")
print("\u001b[1mAbilities\u001b[0m:")
if len(self.abilities) > 0:
for ability in self.abilities:
print(f" - \u001b[4m{ability}\u001b[0m:")
print(f" {self.abilities[ability]}")
else:
print(" This Pokémon has no abilities.")
print("")
print("\u001b[1mCurrent Move Set\u001b[0m:")
if len(self.move_set) > 0:
for move in self.move_set:
print(f" - {move.name}")
else:
print(" This Pokémon cannot learn any moves.")
print("\n")
def get_pokemon_options(self, mode: str) -> list:
"""
Gets the options to use in Pokemon.pokemon_menu()
Parameters:
mode: str
The currently running mode of the application
Returns:
List of menu options to display in Pokemon.pokemon_menu()
"""
options: list = [
"Change Pokémon",
None,
"Back to team view"
]
if mode == "online":
if self.name == "None":
options[1] = {"name": "Change moves",
"disabled": "Cannot change moves on an empty pokémon slot"}
else:
options[1] = "Change moves"
return options
else:
empty_move_set: bool = True
for move in self.move_set:
if move.name != "None":
empty_move_set = False
if self.name == "None":
options[1] = {"name": "View moves",
"disabled": "Cannot view moves on an empty pokémon slot"}
elif empty_move_set:
options[1] = {"name": "View moves",
"disabled": "This Pokémon does not have any moves saved"}
else:
options[1] = "View moves"
return options[1:]
def get_pokemon_move_slots_options(self, mode: str) -> list:
"""
Gets the move slot options to use in Pokemon.pokemon_menu()
Parameters:
mode: str
The currently running mode of the application
Returns:
List of move slot options to display in Pokemon.pokemon_menu()
"""
if mode == "online":
pokemon_move_slots = [
"Slot 1 - " + (self.move_set[0].name if self.move_set[0].name != "None" else "Empty"),
"Slot 2 - " + (self.move_set[1].name if self.move_set[1].name != "None" else "Empty"),
"Slot 3 - " + (self.move_set[2].name if self.move_set[2].name != "None" else "Empty"),
"Slot 4 - " + (self.move_set[3].name if self.move_set[3].name != "None" else "Empty")
]
else:
pokemon_move_slots = []
for i in range(len(self.move_set)):
if self.move_set[i].name != "None":
pokemon_move_slots.append(f"Slot {i + 1} - {self.move_set[i].name}")
else:
pokemon_move_slots.append({"name": f"Slot {i + 1} - Empty",
"disabled": "There is no move saved to this slot"})
return pokemon_move_slots
def pokemon_menu(self, mode: str) -> str:
"""
Displays the menu for the Pokemon screen
Parameters:
mode: str
The currently running mode of the application
Returns:
String of the user's input from the PyInquirer prompts
"""
pokemon_options: list = [
{
"type": "list",
"name": "pokemon_menu",
"message": "What would you like to do with this pokémon slot?",
"choices": self.get_pokemon_options(mode)
}
]
while True:
pokemon_option: str = prompt(pokemon_options)["pokemon_menu"]
if pokemon_option not in pokemon_options[0]["choices"]:
print("Can't select a disabled option, please try again.\n")
else:
break
if pokemon_option == "Change moves" or pokemon_option == "View moves":
select_pokemon_move: list = [
{
"type": "list",
"name": "select_pokemon_move",
"message": "Which move slot would you like to select?",
"choices": self.get_pokemon_move_slots_options(mode)
}
]
while True:
pokemon_move_option: str = prompt(select_pokemon_move)["select_pokemon_move"]
if pokemon_move_option not in select_pokemon_move[0]["choices"]:
print("Can't select a disabled option, please try again.\n")
else:
break
return pokemon_move_option[5]
else:
return pokemon_option
@staticmethod
def select_pokemon(api_handler: APIHandler) -> str:
"""
Displays the input field for the user to select and view a pokemon list or search for a pokemon
Parameters:
api_handler: APIHandler
The APIHandler object used to make api calls
Returns:
String of the users input from the PyInquirer prompts
"""
print("\nIf you are unsure of what Pokémon you would like to search for, select a Pokémon generation to view the list of Pokémon "
"from that generation.\n\nOnce you know what Pokémon you would like to search for, select the Search option and enter the "
"Pokémon's name or Pokédex number. If the Pokémon you are searching for has different forms, enter the Pokémon's name "
"followed by -<form> where <form> is the Pokémon's form you are interested in, some generation lists will show examples.\n")
select_pokemon_options: list = [
{
"type": "list",
"name": "select_pokemon_option",
"message": "What would you like to do?",
"choices": [
Separator("-= View Pokémon list for: =-"),
"Generation 1",
"Generation 2",
"Generation 3",
"Generation 4",
"Generation 5",
"Generation 6",
"Generation 7",
"Generation 8",
Separator("-= Search for a Pokémon =-"),
"Search"
]
}
]
selection: str = prompt(select_pokemon_options)["select_pokemon_option"]
if selection == "Search":
search_pokemon: list = [
{
"type": "input",
"name": "search_pokemon",
"message": "What is the name or Pokédex # you would like to search for?",
"validate": lambda val: api_handler.get_pokemon(val.lower().strip(" ")).status_code != 404 or # noqa: W504
"Pokémon not found, please check you have input the correct name/number"
}
]
return prompt(search_pokemon)["search_pokemon"].lower().strip(" ")
else:
return selection
@staticmethod
def view_pokemon_list(view_list: str, number: int, response: requests.models.Response) -> None:
"""
Displays the list of pokemon from the generation given by the user's input
Parameters:
view_list: str
The user's input string from Pokemon.pokemon_menu()
number: int
The Pokedex number of the first pokemon in this generational list
response: requests.models.Response
Response object from APIHandler.get_pokemon() using a query string
Returns:
None
"""
api_data: dict = json.loads(response.text)
pokemon_list: list = []
for result in api_data["results"]:
pokemon_list.append(f" #{number} {result['name'].capitalize()} ")
number += 1
while len(pokemon_list) % 5 != 0:
pokemon_list.append("")
print(f"\u001b[1m\u001b[4m{view_list} Pokémon\u001b[0m:\n")
for a, b, c, d, e in zip(pokemon_list[::5], pokemon_list[1::5], pokemon_list[2::5], pokemon_list[3::5], pokemon_list[4::5]):
print("{:<27}{:<27}{:<27}{:<27}{:<27}".format(a, b, c, d, e))
@staticmethod
def confirm_pokemon() -> str:
"""
Get confirmation to add the pokemon to the currently selected pokemon slot
Returns:
String of the users input from the PyInquirer prompt
"""
confirm_pokemon: list = [
{
"type": "list",
"name": "confirm_pokemon",
"message": "Add this Pokémon to your team?",
"choices": [
"Add Pokémon",
"Search for another Pokémon"
]
}
]
return prompt(confirm_pokemon)["confirm_pokemon"]
|
14,728 | d4544ee7e6fb92e4a15bcc9416f04725eb2d658a | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 31 10:46:24 2022
@author: baptistelafoux
"""
import cv2
import numpy as np
import matplotlib.pyplot as plt
from scipy.ndimage import zoom, gaussian_filter
from utils.graphic import get_moviename_from_dataset
from utils.loader import dataloader
plt.close('all')
path_timeserie = 'cleaned/3_VarLight/2022-01-06/1/trajectory.nc'
ds = dataloader(path_timeserie)
movie_path = get_moviename_from_dataset(ds, noBG=False)
cap = cv2.VideoCapture(movie_path)
t = 41 * 60 * 5
t = int(t)
N = 30
_, frame_ini = cap.read()
stack = frame_ini[None, ...]
np.zeros_like(frame_ini)[None, ...]
for i, t in enumerate(range(t-N, t, 1)):
cap.set(cv2.CAP_PROP_POS_FRAMES, t-1)
_, frame = cap.read()
stack = np.append(stack, frame[None,...], axis=0)
stack = stack[1:]
fig, ax = plt.subplots(figsize=(15, 9))
final = stack.min(axis=0).astype(np.uint8)
cv2.normalize(final, final, 0, 255, cv2.NORM_MINMAX)
final = cv2.cvtColor(final, cv2.COLOR_BGR2GRAY)
final = gaussian_filter(zoom(final, 4) , sigma=0.8)
plt.imsave('output/pcfocus.png', 255 - final, cmap='Greys', dpi=300)
ax.axis('off') |
14,729 | 7997a37ee5716ad0cd7e6c4030f4b66a5045a092 | import unittest
import numpy as np
import pandas as pd
import scipy.stats
import sklearn.metrics
import subprocess
import os
import wot.ot
class TestOT(unittest.TestCase):
"""Tests for `wot` package."""
def test_same_distribution(self):
# test same distributions, diagonals along transport map should be equal
m1 = np.random.rand(2, 3)
m2 = m1
result = wot.ot.transport_stable(np.ones(m1.shape[0]),
np.ones(m2.shape[0]),
sklearn.metrics.pairwise.pairwise_distances(
m1, Y=m2, metric='sqeuclidean'), 1, 1,
0.1, 250, np.ones(m1.shape[0]))
self.assertEqual(result[0, 0], result[1, 1])
self.assertEqual(result[0, 1], result[1, 0])
def test_growth_rate(self):
# as growth rate goes up, sum of mass goes up
m1 = np.random.rand(2, 3)
m2 = np.random.rand(4, 3)
g = [1, 2, 3]
cost_matrix = sklearn.metrics.pairwise.pairwise_distances(m1, Y=m2,
metric='sqeuclidean')
last = -1
for i in range(len(g)):
result = wot.ot.transport_stable(np.ones(m1.shape[0]),
np.ones(m2.shape[0]), cost_matrix, 1,
1, 0.1, 250,
np.ones(m1.shape[0]) * g[i])
sum = np.sum(result)
self.assertTrue(sum > last)
last = sum
def test_epsilon(self):
# as epsilon goes up, entropy goes up
m1 = np.random.rand(2, 3)
m2 = np.random.rand(4, 3)
e = [0.01, 0.1, 1]
cost_matrix = sklearn.metrics.pairwise.pairwise_distances(m1, Y=m2,
metric='sqeuclidean')
last = -1
for i in range(len(e)):
result = wot.ot.transport_stable(np.ones(m1.shape[0]),
np.ones(m2.shape[0]), cost_matrix, 1,
1, e[i], 250,
np.ones(m1.shape[0]))
sum = np.sum([scipy.stats.entropy(r) for r in result])
self.assertTrue(sum > last)
last = sum
def test_transport_maps_by_time(self):
clusters = pd.DataFrame([1, 1, 2, 3, 1, 1, 2, 1],
index=['a', 'b', 'c', 'd', 'e', 'f', 'g',
'h'])
map1 = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]],
index=[1, 2, 3], columns=[1, 2, 3])
map2 = pd.DataFrame([[10, 11, 12], [13, 14, 15], [16, 17, 18]],
index=[1, 2, 3], columns=[1, 2, 3])
# weighted average across time
cluster_weights_by_time = [[0.4, 0.5, 0], [0.6, 0.5, 1]]
result = wot.ot.transport_maps_by_time([map1, map2],
cluster_weights_by_time)
pd.testing.assert_frame_equal(
result,
pd.DataFrame(
[[6.4, 6.5, 12.0],
[9.4, 9.5, 15.0],
[12.4, 12.5, 18.0],
],
index=[1, 2, 3], columns=[1, 2, 3]))
def test_get_weights_intersection(self):
clusters = pd.DataFrame([1, 1, 2, 3, 1, 1, 2, 1],
index=['a', 'b', 'c', 'd', 'e', 'f', 'g',
'h'], columns=['cluster'])
map1 = pd.DataFrame(index=['x', 'y', 'z'], columns=['a', 'b', 'c'])
# note f, g, h are not present in map2
map2 = pd.DataFrame(index=['a', 'b', 'c'], columns=['d', 'e'])
# weighted average across time
grouped_by_cluster = clusters.groupby(clusters.columns[0], axis=0)
cluster_ids = list(grouped_by_cluster.groups.keys())
all_cell_ids = set()
column_cell_ids_by_time = []
for transport_map in [map1, map2]:
all_cell_ids.update(transport_map.columns)
column_cell_ids_by_time.append(transport_map.columns)
all_cell_ids.update(transport_map.index)
result = wot.ot.get_weights(all_cell_ids, column_cell_ids_by_time,
grouped_by_cluster, cluster_ids)
self.assertTrue(
np.array_equal(result['cluster_weights_by_time'],
[[2 / 3, 1 / 1, 0 / 1], [1 / 3, 0 / 1, 1 / 1]]))
self.assertTrue(
np.array_equal(result['cluster_size'],
[3, 1, 1]))
def test_get_weights(self):
clusters = pd.DataFrame([1, 1, 2, 3, 1, 1, 2, 1],
index=['a', 'b', 'c', 'd', 'e', 'f', 'g',
'h'], columns=['cluster'])
map1 = pd.DataFrame(index=['x', 'y', 'z'], columns=['a', 'b', 'c'])
map2 = pd.DataFrame(index=['a', 'b', 'c'], columns=['d', 'e',
'f', 'g', 'h'])
# weighted average across time
grouped_by_cluster = clusters.groupby(clusters.columns[0], axis=0)
cluster_ids = list(grouped_by_cluster.groups.keys())
all_cell_ids = set()
column_cell_ids_by_time = []
for transport_map in [map1, map2]:
all_cell_ids.update(transport_map.columns)
column_cell_ids_by_time.append(transport_map.columns)
all_cell_ids.update(transport_map.index)
result = wot.ot.get_weights(all_cell_ids, column_cell_ids_by_time,
grouped_by_cluster, cluster_ids)
self.assertTrue(
np.array_equal(result['cluster_weights_by_time'],
[[2 / 5, 1 / 2, 0 / 1], [3 / 5, 1 / 2, 1 / 1]]))
self.assertTrue(
np.array_equal(result['cluster_size'],
[5, 2, 1]))
def test_transport_map_by_cluster(self):
row_ids = ['a', 'b', 'c']
column_ids = ['d', 'e', 'f', 'g', 'h'];
clusters = pd.DataFrame([3, 1, 2, 3, 1, 1, 2, 3],
index=['a', 'b', 'c', 'd', 'e', 'f', 'g',
'h'])
grouped_by_cluster = clusters.groupby(clusters.columns[0], axis=0)
cluster_ids = [1, 2, 3]
transport_map = pd.DataFrame(
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]],
index=row_ids,
columns=column_ids)
# sum mass by cluster
result = wot.ot.transport_map_by_cluster(transport_map, grouped_by_cluster,
cluster_ids)
pd.testing.assert_frame_equal(
result,
pd.DataFrame(
[[15, 9, 16],
[25, 14, 26],
[5, 4, 6]
],
index=cluster_ids, columns=cluster_ids))
def test_growth_scores(self):
scores = wot.ot.compute_growth_scores(np.array([-0.399883307]),
np.array([0.006853961]))
np.testing.assert_allclose(np.array([0.705444456674597]),
scores,
atol=0.000001)
def test_ot_commmand_line(self):
subprocess.call(args=['python', os.path.abspath('../bin/optimal_transport'),
'--matrix',
os.path.abspath(
'../finalInput/dmap_2i_normalized.txt'),
'--cell_growth_rates', os.path.abspath(
'../paper/growth_rates.txt'),
'--cell_days', os.path.abspath(
'../paper/days.txt'),
'--day_pairs', os.path.abspath(
'../paper/pairs_2i.txt'),
'--prefix', 'mytest',
'--verbose',
'--compress'],
cwd=os.getcwd(),
stderr=subprocess.STDOUT)
timepoints = [0, 2, 4, 6, 8, 9, 10, 11, 12, 16]
for timepoint in range(0, len(timepoints) - 1):
my_transport = pd.read_table(
'mytest_' + str(
timepoints[timepoint]) + '_' + str(
timepoints[timepoint + 1]) +
'.txt.gz', index_col=0)
# precomputed_transport_map = np.load(
# '../paper/transport_maps/2i/npy/lineage.day-' + str(
# timepoints[timepoint + 1]) + '.npy')
precomputed_transport_map = precomputed_transport_map = \
pd.read_table(
'../paper/transport_maps/2i/lineage.day-' + str(
timepoints[timepoint + 1]) +
'.txt', index_col=0)
pd.testing.assert_index_equal(left=my_transport.index,
right=precomputed_transport_map.index,
check_names=False)
pd.testing.assert_index_equal(left=my_transport.columns,
right=precomputed_transport_map.columns,
check_names=False)
total = 0
count = 0
for i in range(my_transport.shape[0]):
for j in range(my_transport.shape[1]):
diff = abs(precomputed_transport_map.values[i,
j] -
my_transport.values[
i, j])
total += diff
if diff > 0.000001:
count += 1
print('lineage_' + str(
timepoints[timepoint]) + '_' + str(
timepoints[timepoint + 1]))
print('total diff: ' + str(total))
print('pre total: ' + str(precomputed_transport_map.sum().sum()))
print('my total: ' + str(my_transport.sum().sum()))
print('count: ' + str(count) + '/' + str(
my_transport.shape[0] * my_transport.shape[1]))
def test_trajectory(self):
transport_maps = list()
ncells = [4, 2, 5, 6, 3]
for i in range(0, len(ncells) - 1):
transport_map = pd.read_csv('inputs/transport_maps/t' + str(i) +
'_t' + str(i + 1) + '.csv',
index_col=0)
self.assertTrue(transport_map.shape[0] == ncells[i])
self.assertTrue(transport_map.shape[1] == ncells[i + 1])
transport_maps.append({'transport_map': transport_map,
't_minus_1': i, 't': i + 1})
trajectory_id = ['c4-t3']
result = wot.ot.trajectory(trajectory_id, transport_maps, 3, False)
ancestors = result['ancestors']
# not messing up already computed ancestors
ids = ['c1-t2', 'c2-t2',
'c3-t2', 'c4-t2',
'c5-t2']
pd.testing.assert_frame_equal(
ancestors[ancestors.index.isin(ids)],
pd.DataFrame(
{trajectory_id[0]: [5, 4, 3, 2, 1]},
index=ids), check_names=False)
# t1
ids = ['c1-t1']
pd.testing.assert_frame_equal(
ancestors[ancestors.index.isin(ids)],
pd.DataFrame(
{trajectory_id[0]: [50]},
index=ids), check_names=False)
# t0
ids = ['c3-t0']
pd.testing.assert_frame_equal(
ancestors[ancestors.index.isin(ids)],
pd.DataFrame(
{trajectory_id[0]: [1175]},
index=ids), check_names=False)
trajectory_id = ['c1-t1']
result = wot.ot.trajectory(trajectory_id, transport_maps, 1, False)
descendants = result['descendants']
# t3
ids = ['c1-t3', 'c2-t3', 'c3-t3', 'c4-t3', 'c5-t3', 'c6-t3']
pd.testing.assert_frame_equal(
descendants[descendants.index.isin(ids)],
pd.DataFrame(
{trajectory_id[0]: [90, 190, 290, 50, 390, 490]},
index=ids), check_names=False)
# t4
ids = ['c3-t4']
pd.testing.assert_frame_equal(
descendants[descendants.index.isin(ids)],
pd.DataFrame(
{trajectory_id[0]: [25450]},
index=ids), check_names=False)
def test_ot_known_output(self):
gene_expression = pd.read_table('../paper/2i_dmap_20.txt',
index_col=0) # cells on rows,
# diffusion components on columns
growth_scores = pd.read_table('../paper/growth_scores.txt',
index_col=0, header=None,
names=['id', 'growth_score'])
days = pd.read_table(
'../paper/days.txt', header=None,
index_col=0, names=['id', 'days'])
gene_expression = gene_expression.join(growth_scores).join(days)
growth_score_field_name = growth_scores.columns[0]
day_field_name = days.columns[0]
group_by_day = gene_expression.groupby(day_field_name)
timepoints = list(group_by_day.groups.keys())
timepoints.sort()
self.assertTrue(timepoints[0] == 0)
max_transport_fraction = 0.4
min_transport_fraction = 0.05
min_growth_fit = 0.9
l0_max = 100
lambda1 = 1
lambda2 = 1
epsilon = 0.1
growth_ratio = 2.5
scaling_iter = 250
expected_lambda_t0_t2 = 1.5
expected_epsilon_t0_t2 = \
0.01015255979947704383092865754179001669399440288543701171875
for i in range(0, len(timepoints) - 1):
m1 = group_by_day.get_group(timepoints[i])
m2 = group_by_day.get_group(timepoints[i + 1])
delta_t = timepoints[i + 1] - timepoints[i]
cost_matrix = sklearn.metrics.pairwise.pairwise_distances(
m1.drop([day_field_name, growth_score_field_name], axis=1),
Y=m2.drop([day_field_name, growth_score_field_name], axis=1),
metric='sqeuclidean')
cost_matrix = cost_matrix / np.median(cost_matrix)
growth_rate = m1.growth_score.values
result = wot.ot.optimal_transport(cost_matrix, growth_rate,
delta_days=delta_t,
max_transport_fraction=max_transport_fraction,
min_transport_fraction=min_transport_fraction,
min_growth_fit=min_growth_fit,
l0_max=l0_max, lambda1=lambda1,
lambda2=lambda2, epsilon=epsilon,
growth_ratio=growth_ratio,
scaling_iter=scaling_iter)
if i == 0:
self.assertTrue(result['epsilon'] == expected_epsilon_t0_t2)
self.assertTrue(result['lambda1'] == expected_lambda_t0_t2)
self.assertTrue(result['lambda2'] == expected_lambda_t0_t2)
transport = pd.DataFrame(result['transport'], index=m1.index,
columns=m2.index)
precomputed_transport_map = pd.read_table(
'../paper/transport_maps/lineage_' + str(timepoints[i])
+ '_' + str(timepoints[i + 1]) + '.txt', index_col=0)
pd.testing.assert_index_equal(left=transport.index,
right=precomputed_transport_map.index,
check_names=False)
pd.testing.assert_index_equal(left=transport.columns,
right=precomputed_transport_map.columns,
check_names=False)
np.testing.assert_allclose(transport.values,
precomputed_transport_map.values,
atol=0.0004)
if __name__ == '__main__':
unittest.main()
|
14,730 | 6c92e05e5729074f0f5c15751edcd2ad075c8a52 | # L=[23,45,66,77,22,21,24,22], sort it in descending order. No lib should be used.
L=[23,45,66,77,22,21,24,22]
for i in range(len(L)-1):
for j in range(i+1,len(L)):
if L[i]<L[j]:
temp = L[i]
L[i] = L[j]
L[j] = temp
print(L) |
14,731 | a06330b9fb47412abd14a0b2a85b3582dafcb469 | class human:
fp='priti'
def __init__(self,eyes,foot):
self.e=eyes
self.f=foot
def details(self,name,bldgroup):
self.n=name
self.b=bldgroup
def display(self):
print("human eyes=",self.e)
print("human foot=",self.f)
print("human name=",self.n)
print("human bnloodgroupo=",self.b)
def is_fp(cls):
print("this is under=",cls.fp)
return cls.fp
class woman(human):
def __init__(self,eyes,foot):
super().__init__(eyes,foot)
def disp(self,name,bldgroup):
self.n=name
self.b=bldgroup
print("woman eyes=",self.e)
print("woman foot=",self.f)
print("woman name=",self.n)
print("woman bloodgroup=",self.b)
hu=human(2,2)
hu.details("ziyaulhaq","o+")
hu.display()
wo=woman(2,2)
wo.disp("snhivangi","a+")
print(human.fp)
print(Mobile.is_fp(Mobile))
|
14,732 | e6f04a28a921110d9ccc4791fb14ad69846c2476 | import array
import hashlib
import csv
from progressbar.bar import ProgressBar
from Crypto.Hash import SHA256
class PrecursorUsb:
def __init__(self, dev):
self.dev = dev
self.RDSR = 0x05
self.RDSCUR = 0x2B
self.RDID = 0x9F
self.WREN = 0x06
self.WRDI = 0x04
self.SE4B = 0x21
self.BE4B = 0xDC
self.PP4B = 0x12
self.registers = {}
self.regions = {}
self.gitrev = ''
def halt(self):
if 'vexriscv_debug' in self.regions:
self.poke(int(self.regions['vexriscv_debug'][0], 0), 0x00020000)
elif 'reboot_cpu_hold_reset' in self.registers:
self.poke(self.register('reboot_cpu_hold_reset'), 1)
else:
print("Can't find reset CSR. Try updating to the latest version of this program")
def unhalt(self):
if 'vexriscv_debug' in self.regions:
self.poke(int(self.regions['vexriscv_debug'][0], 0), 0x02000000)
elif 'reboot_cpu_hold_reset' in self.registers:
self.poke(self.register('reboot_cpu_hold_reset'), 0)
else:
print("Can't find reset CSR. Try updating to the latest version of this program")
def register(self, name):
return int(self.registers[name], 0)
def peek(self, addr, display=False):
_dummy_s = '\x00'.encode('utf-8')
data = array.array('B', _dummy_s * 4)
numread = self.dev.ctrl_transfer(bmRequestType=(0x80 | 0x43), bRequest=0,
wValue=(addr & 0xffff), wIndex=((addr >> 16) & 0xffff),
data_or_wLength=data, timeout=500)
read_data = int.from_bytes(data.tobytes(), byteorder='little', signed=False)
if display == True:
print("0x{:08x}".format(read_data))
return read_data
def poke(self, addr, wdata, check=False, display=False):
if check == True:
_dummy_s = '\x00'.encode('utf-8')
data = array.array('B', _dummy_s * 4)
numread = self.dev.ctrl_transfer(bmRequestType=(0x80 | 0x43), bRequest=0,
wValue=(addr & 0xffff), wIndex=((addr >> 16) & 0xffff),
data_or_wLength=data, timeout=500)
read_data = int.from_bytes(data.tobytes(), byteorder='little', signed=False)
print("before poke: 0x{:08x}".format(read_data))
data = array.array('B', wdata.to_bytes(4, 'little'))
numwritten = self.dev.ctrl_transfer(bmRequestType=(0x00 | 0x43), bRequest=0,
wValue=(addr & 0xffff), wIndex=((addr >> 16) & 0xffff),
data_or_wLength=data, timeout=500)
if check == True:
_dummy_s = '\x00'.encode('utf-8')
data = array.array('B', _dummy_s * 4)
numread = self.dev.ctrl_transfer(bmRequestType=(0x80 | 0x43), bRequest=0,
wValue=(addr & 0xffff), wIndex=((addr >> 16) & 0xffff),
data_or_wLength=data, timeout=500)
read_data = int.from_bytes(data.tobytes(), byteorder='little', signed=False)
print("after poke: 0x{:08x}".format(read_data))
if display == True:
print("wrote 0x{:08x} to 0x{:08x}".format(wdata, addr))
def burst_read(self, addr, len):
_dummy_s = '\x00'.encode('utf-8')
maxlen = 4096
ret = bytearray()
packet_count = len // maxlen
if (len % maxlen) != 0:
packet_count += 1
for pkt_num in range(packet_count):
cur_addr = addr + pkt_num * maxlen
if pkt_num == packet_count - 1:
if len % maxlen != 0:
bufsize = len % maxlen
else:
bufsize = maxlen
else:
bufsize = maxlen
data = array.array('B', _dummy_s * bufsize)
numread = self.dev.ctrl_transfer(bmRequestType=(0x80 | 0x43), bRequest=0,
wValue=(cur_addr & 0xffff), wIndex=((cur_addr >> 16) & 0xffff),
data_or_wLength=data, timeout=500)
if numread != bufsize:
print("Burst read error: {} bytes requested, {} bytes read at 0x{:08x}".format(bufsize, numread, cur_addr))
exit(1)
ret = ret + data
return ret
def burst_write(self, addr, data):
if len(data) == 0:
return
# the actual "addr" doesn't matter for a burst_write, because it's specified
# as an argument to the flash_pp4b command. We lock out access to the base of
# SPINOR because it's part of the gateware, so, we pick a "safe" address to
# write to instead. The page write responder will aggregate any write data
# to anywhere in the SPINOR address range.
writebuf_addr = 0x2098_0000 # the current start address of the kernel, for example
maxlen = 4096
packet_count = len(data) // maxlen
if (len(data) % maxlen) != 0:
packet_count += 1
for pkt_num in range(packet_count):
cur_addr = addr + pkt_num * maxlen
if pkt_num == packet_count - 1:
if len(data) % maxlen != 0:
bufsize = len(data) % maxlen
else:
bufsize = maxlen
else:
bufsize = maxlen
wdata = array.array('B', data[(pkt_num * maxlen):(pkt_num * maxlen) + bufsize])
numwritten = self.dev.ctrl_transfer(bmRequestType=(0x00 | 0x43), bRequest=0,
# note use of writebuf_addr instead of cur_addr -> see comment above about the quirk of write addressing
wValue=(writebuf_addr & 0xffff), wIndex=((writebuf_addr >> 16) & 0xffff),
data_or_wLength=wdata, timeout=500)
if numwritten != bufsize:
print("Burst write error: {} bytes requested, {} bytes written at 0x{:08x}".format(bufsize, numwritten, cur_addr))
exit(1)
def ping_wdt(self):
self.poke(self.register('wdt_watchdog'), 1, display=False)
self.poke(self.register('wdt_watchdog'), 1, display=False)
def spinor_command_value(self, exec=0, lock_reads=0, cmd_code=0, dummy_cycles=0, data_words=0, has_arg=0):
return ((exec & 1) << 1 |
(lock_reads & 1) << 24 |
(cmd_code & 0xff) << 2 |
(dummy_cycles & 0x1f) << 11 |
(data_words & 0xff) << 16 |
(has_arg & 1) << 10
)
def flash_rdsr(self, lock_reads):
self.poke(self.register('spinor_cmd_arg'), 0)
self.poke(self.register('spinor_command'),
self.spinor_command_value(exec=1, lock_reads=lock_reads, cmd_code=self.RDSR, dummy_cycles=4, data_words=1, has_arg=1)
)
return self.peek(self.register('spinor_cmd_rbk_data'), display=False)
def flash_rdscur(self):
self.poke(self.register('spinor_cmd_arg'), 0)
self.poke(self.register('spinor_command'),
self.spinor_command_value(exec=1, lock_reads=1, cmd_code=self.RDSCUR, dummy_cycles=4, data_words=1, has_arg=1)
)
return self.peek(self.register('spinor_cmd_rbk_data'), display=False)
def flash_rdid(self, offset):
self.poke(self.register('spinor_cmd_arg'), 0)
self.poke(self.register('spinor_command'),
self.spinor_command_value(exec=1, cmd_code=self.RDID, dummy_cycles=4, data_words=offset, has_arg=1)
)
return self.peek(self.register('spinor_cmd_rbk_data'), display=False)
def flash_wren(self):
self.poke(self.register('spinor_cmd_arg'), 0)
self.poke(self.register('spinor_command'),
self.spinor_command_value(exec=1, lock_reads=1, cmd_code=self.WREN)
)
def flash_wrdi(self):
self.poke(self.register('spinor_cmd_arg'), 0)
self.poke(self.register('spinor_command'),
self.spinor_command_value(exec=1, lock_reads=1, cmd_code=self.WRDI)
)
def flash_se4b(self, sector_address):
self.poke(self.register('spinor_cmd_arg'), sector_address)
self.poke(self.register('spinor_command'),
self.spinor_command_value(exec=1, lock_reads=1, cmd_code=self.SE4B, has_arg=1)
)
def flash_be4b(self, block_address):
self.poke(self.register('spinor_cmd_arg'), block_address)
self.poke(self.register('spinor_command'),
self.spinor_command_value(exec=1, lock_reads=1, cmd_code=self.BE4B, has_arg=1)
)
def flash_pp4b(self, address, data_bytes):
self.poke(self.register('spinor_cmd_arg'), address)
self.poke(self.register('spinor_command'),
self.spinor_command_value(exec=1, lock_reads=1, cmd_code=self.PP4B, has_arg=1, data_words=(data_bytes//2))
)
def load_csrs(self, fname=None):
LOC_CSRCSV = 0x20277000 # this address shouldn't change because it's how we figure out our version number
# CSR extraction:
# dd if=soc_csr.bin of=csr_data_0.9.6.bin skip=2524 count=32 bs=1024
if fname == None:
csr_data = self.burst_read(LOC_CSRCSV, 0x8000)
else:
with open(fname, "rb") as f:
csr_data = f.read(0x8000)
hasher = hashlib.sha512()
hasher.update(csr_data[:0x7FC0])
digest = hasher.digest()
if digest != csr_data[0x7fc0:]:
print("Could not find a valid csr.csv descriptor on the device, aborting!")
exit(1)
csr_len = int.from_bytes(csr_data[:4], 'little')
csr_extracted = csr_data[4:4+csr_len]
decoded = csr_extracted.decode('utf-8')
# strip comments
stripped = []
for line in decoded.split('\n'):
if line.startswith('#') == False:
stripped.append(line)
# create database
csr_db = csv.reader(stripped)
for row in csr_db:
if len(row) > 1:
if 'csr_register' in row[0]:
self.registers[row[1]] = row[2]
if 'memory_region' in row[0]:
self.regions[row[1]] = [row[2], row[3]]
if 'git_rev' in row[0]:
self.gitrev = row[1]
print("Using SoC {} registers".format(self.gitrev))
def erase_region(self, addr, length):
# ID code check
code = self.flash_rdid(1)
print("ID code bytes 1-2: 0x{:08x}".format(code))
if code != 0x8080c2c2:
print("ID code mismatch")
exit(1)
code = self.flash_rdid(2)
print("ID code bytes 2-3: 0x{:08x}".format(code))
if code != 0x3b3b8080:
print("ID code mismatch")
exit(1)
# block erase
progress = ProgressBar(min_value=0, max_value=length, prefix='Erasing ').start()
erased = 0
while erased < length:
self.ping_wdt()
if (length - erased >= 65536) and ((addr & 0xFFFF) == 0):
blocksize = 65536
else:
blocksize = 4096
while True:
self.flash_wren()
status = self.flash_rdsr(1)
if status & 0x02 != 0:
break
if blocksize == 4096:
self.flash_se4b(addr + erased)
else:
self.flash_be4b(addr + erased)
erased += blocksize
while (self.flash_rdsr(1) & 0x01) != 0:
pass
result = self.flash_rdscur()
if result & 0x60 != 0:
print("E_FAIL/P_FAIL set on erase, programming may fail, but trying anyways...")
if self.flash_rdsr(1) & 0x02 != 0:
self.flash_wrdi()
while (self.flash_rdsr(1) & 0x02) != 0:
pass
if erased < length:
progress.update(erased)
progress.finish()
print("Erase finished")
# addr is relative to the base of FLASH (not absolute)
def flash_program(self, addr, data, verify=True):
flash_region = int(self.regions['spiflash'][0], 0)
flash_len = int(self.regions['spiflash'][1], 0)
if (addr + len(data) > flash_len):
print("Write data out of bounds! Aborting.")
exit(1)
# ID code check
code = self.flash_rdid(1)
print("ID code bytes 1-2: 0x{:08x}".format(code))
if code != 0x8080c2c2:
print("ID code mismatch")
exit(1)
code = self.flash_rdid(2)
print("ID code bytes 2-3: 0x{:08x}".format(code))
if code != 0x3b3b8080:
print("ID code mismatch")
exit(1)
# block erase
progress = ProgressBar(min_value=0, max_value=len(data), prefix='Erasing ').start()
erased = 0
while erased < len(data):
self.ping_wdt()
if (len(data) - erased >= 65536) and ((addr & 0xFFFF) == 0):
blocksize = 65536
else:
blocksize = 4096
while True:
self.flash_wren()
status = self.flash_rdsr(1)
if status & 0x02 != 0:
break
if blocksize == 4096:
self.flash_se4b(addr + erased)
else:
self.flash_be4b(addr + erased)
erased += blocksize
while (self.flash_rdsr(1) & 0x01) != 0:
pass
result = self.flash_rdscur()
if result & 0x60 != 0:
print("E_FAIL/P_FAIL set on erase, programming may fail, but trying anyways...")
if self.flash_rdsr(1) & 0x02 != 0:
self.flash_wrdi()
while (self.flash_rdsr(1) & 0x02) != 0:
pass
if erased < len(data):
progress.update(erased)
progress.finish()
print("Erase finished")
# program
# pad out to the nearest word length
if len(data) % 4 != 0:
data += bytearray([0xff] * (4 - (len(data) % 4)))
written = 0
progress = ProgressBar(min_value=0, max_value=len(data), prefix='Writing ').start()
while written < len(data):
self.ping_wdt()
if len(data) - written > 256:
chunklen = 256
else:
chunklen = len(data) - written
while True:
self.flash_wren()
status = self.flash_rdsr(1)
if status & 0x02 != 0:
break
self.burst_write(self.register('spinor_wdata'), data[written:(written+chunklen)])
self.flash_pp4b(addr + written, chunklen)
written += chunklen
if written < len(data):
progress.update(written)
progress.finish()
print("Write finished")
if self.flash_rdsr(1) & 0x02 != 0:
self.flash_wrdi()
while (self.flash_rdsr(1) & 0x02) != 0:
pass
# dummy reads to clear the "read lock" bit
self.flash_rdsr(0)
# verify
self.ping_wdt()
if verify:
print("Performing readback for verification...")
self.ping_wdt()
rbk_data = self.burst_read(addr + flash_region, len(data))
if rbk_data != data:
errs = 0
err_thresh = 64
for i in range(0, len(rbk_data)):
if rbk_data[i] != data[i]:
if errs < err_thresh:
print("Error at 0x{:x}: {:x}->{:x}".format(i, data[i], rbk_data[i]))
errs += 1
if errs == err_thresh:
print("Too many errors, stopping print...")
print("Errors were found in verification, programming failed")
print("Total byte errors: {}".format(errs))
exit(1)
else:
print("Verification passed.")
else:
print("Skipped verification at user request")
self.ping_wdt()
|
14,733 | 5987d6cd40e4f586cc0d66a6e36958c764eb0a17 | def findLengthOfLCIS(nums: list) -> int:
if not nums:
return 0
count = 1
result = 0
for i in range(1, len(nums)):
if nums[i] > nums[i - 1]:
count += 1
else:
result = max(result, count)
count = 1
return max(result, count)
if __name__ == "__main__":
print(findLengthOfLCIS([])) |
14,734 | de5e8ff40325c08dbf869ead1073a84c86ae261f | def question_5(first_name, last_name):
return(print("My full name is " + first_name + " " + last_name))
|
14,735 | 0720391e108eee2ac3d99af6c31e80cf58b14542 | from django.db import models
# Create your models here.
class Mineral(models.Model):
UNIT_TYPE = (
('mg', 'miligram'),
('μg', 'mikrogram'),
)
mineral_name = models.CharField(max_length=150)
mineral_symbol = models.CharField(max_length=50)
mineral_unit = models.CharField(max_length=10, choices=UNIT_TYPE)
mineral_recomended_consuption = models.DecimalField(max_digits=7, decimal_places=3)
def __str__(self):
return f'{self.mineral_name} [{self.mineral_unit}]'
class Meta:
verbose_name = 'Minerał'
verbose_name_plural = 'Minerały' |
14,736 | 376aa91efd798eb4c853fbc40123e3c7ff2496ad | a=list()
n=input()
b=input()
for i in range(0,int(n)):
d=input()
a.append(d)
a=''.join(a)
print(a)
if b in a:
print("Yes")
else:
print("No")
|
14,737 | 56d0be39d170bf26875544f3bf618cac043e5981 | import numpy as np
import random
class Graph:
def __init__(self, numVertices, maxEdgeWeight=100,edgeProb=None, avgNumEdges=None, noEdges=False):
self.numVertices = numVertices
self.maxEdgeWeight = maxEdgeWeight
self.E = [[] for i in range(self.numVertices)]
#Create Graph with no Edges
if noEdges:
return
# Ensure graph is connected
for i in range(numVertices):
edgeWeight = random.randint(1, self.maxEdgeWeight)
neighbour = (i+1) % self.numVertices
self.AddEdge((i,neighbour,edgeWeight))
self.edgeProb = edgeProb
self.avgNumEdges = avgNumEdges
if(self.avgNumEdges != None):
self.avgNumEdges -= 2 # number of extra edges needed
numEdgeSelect = range(2 * self.avgNumEdges) # Number of edges will be sample from int range(inclusive) 0 to 2*(avgNumEdges-2), thus on average there will be avgNumEdges
for i in range(self.numVertices):
edgeSelect = np.random.rand(self.numVertices)
edgeSelect[i] = 0.0
for w in self.E[i]:
edgeSelect[w[0]] = 0.0 # remove edges already present from possible choice
numEdges = np.random.choice(numEdgeSelect) + 1# include edges added initially, the random variable we are sampling is X+2
numEdges = max(numEdges - len(self.E[i]), 0)
edgeSelectArgSort = np.argsort(-edgeSelect)[:numEdges] #pick top numEdge values to decide the target vertices
for w in edgeSelectArgSort:
edgeWeight = random.randint(1, self.maxEdgeWeight)
self.AddEdge((i,w,edgeWeight))
elif(self.edgeProb != None):
for i in range(self.numVertices - 2):
# Consider every edge only once to ensure correct probability of picking
for j in range(i+2,self.numVertices):
# Considers all vertices from i+2 to numVertices - 1 (i+1 is already connected). Also for i == 0 the last vertex is ignored
if(np.random.random() <= self.edgeProb and not (j == self.numVertices - 1 and i==0)):
edgeWeight = random.randint(1, self.maxEdgeWeight)
self.AddEdge((i,j,edgeWeight))
else:
raise Exception("Requires Either average number of edges per vertex or percentage of edges")
def AddEdge(self, edge):
if(edge[0] < 0 or edge[0] >= self.numVertices or edge[1] < 0 or edge[1] >= self.numVertices):
raise Exception("Trying to add edge for vertices that don't exist")
self.E[edge[0]].append((edge[1],edge[2]))
self.E[edge[1]].append((edge[0],edge[2]))
class HeapNode:
def __init__(self, key, weight):
self.key = key
self.weight = weight
class MaxHeap:
def __init__(self):
self.heapElements = []
self.numElements = 0
def Top(self):
return self.heapElements[0]
def Delete(self, i, heapIndex=[]):
if(i >= self.numElements):
raise Exception("Cannot delete element outside of range of Heap")
self.heapElements[i].weight, self.heapElements[self.numElements - 1].weight = self.heapElements[self.numElements - 1].weight, self.heapElements[i].weight # Swap i'th value with last value
if(len(heapIndex) > 0):
#swap heap index values
heapIndex[self.heapElements[i].key], heapIndex[self.heapElements[self.numElements - 1].key] = heapIndex[self.heapElements[self.numElements - 1].key], heapIndex[self.heapElements[i].key]
self.heapElements.pop()
self.numElements -= 1
if(self.numElements == i):
return
parent = (i-1)//2
while(i > 0 and self.heapElements[i].weight > self.heapElements[parent].weight):
self.heapElements[i], self.heapElements[parent] = self.heapElements[parent], self.heapElements[i]
if(len(heapIndex) > 0):
#swap heap index values
heapIndex[self.heapElements[i].key], heapIndex[self.heapElements[parent].key] = heapIndex[self.heapElements[parent].key], heapIndex[self.heapElements[i].key]
i = parent
parent = (i-1)//2
while(2*i + 1 < self.numElements):
maxInd = i
if(self.heapElements[maxInd].weight < self.heapElements[2*i + 1].weight):
maxInd = 2*i + 1
if(2*i + 2 < self.numElements and self.heapElements[maxInd].weight< self.heapElements[2*i + 2].weight):
maxInd = 2*i + 2
if(maxInd == i):
break
else:
self.heapElements[i].weight, self.heapElements[maxInd].weight = self.heapElements[maxInd].weight, self.heapElements[i].weight
if(len(heapIndex) > 0):
#swap heap index values
heapIndex[self.heapElements[i].key], heapIndex[self.heapElements[maxInd].key] = heapIndex[self.heapElements[maxInd].key], heapIndex[self.heapElements[i].key]
i = maxInd
def Insert(self, val, heapIndex = []):
self.heapElements.append(val)
self.numElements += 1
i = self.numElements - 1
if(len(heapIndex) > 0):
heapIndex[val.key] = i
parent = (i-1)//2
while(i > 0 and self.heapElements[i].weight > self.heapElements[parent].weight):
self.heapElements[i], self.heapElements[parent] = self.heapElements[parent], self.heapElements[i]
if(len(heapIndex) > 0):
heapIndex[self.heapElements[i].key], heapIndex[self.heapElements[parent].key] = heapIndex[self.heapElements[parent].key], heapIndex[self.heapElements[i].key]
i = parent
parent = (i-1)//2
class UnionFind:
def __init__(self, numVertices):
self.numVertices = numVertices
self.parent = np.zeros(self.numVertices, dtype=int)
self.rank = np.zeros(self.numVertices ,dtype=int)
def Union(self, i, j):
parent_i = self.Find(i)
parent_j = self.Find(j)
if(self.rank[parent_i] > self.rank[parent_j]):
self.parent[parent_j] = parent_i
elif(self.rank[parent_j] > self.rank[parent_i]):
self.parent[parent_i] = parent_j
else:
self.parent[parent_i] = parent_j
self.rank[parent_j] += 1
def Find(self, i):
if(self.parent[i] != i and self.parent[i] != 0):
self.parent[i] = self.Find(self.parent[i])
return self.parent[i]
def MakeSet(self, i):
self.parent[i] = i
self.rank[i] = 1
def HeapSort(arr):
H = MaxHeap()
for val in arr:
H.Insert(val)
sortedArr = []
for i in range(len(arr)):
sortedArr.append(H.Top())
H.Delete(0)
return sortedArr
UNSEEN = 0
FRINGE = 1
INTREE = 2
def MBWDjikstraNoHeap(G, s, t):
status = np.zeros(G.numVertices, dtype=int)
bandwidth = np.zeros(G.numVertices, dtype=int)
parent = np.array([ -1 for i in range(G.numVertices)])
status[s] = INTREE
numFringes = 0
for w,wt in G.E[s]:
status[w] = FRINGE
bandwidth[w] = wt
parent[w] = s
numFringes += 1
while(numFringes > 0):
maxVal = -1
maxIndex = -1
numFringes -= 1
for i in range(G.numVertices):
if(status[i] == FRINGE and maxVal < bandwidth[i]):
maxVal = bandwidth[i]
maxIndex = i
status[maxIndex] = INTREE
for w,wt in G.E[maxIndex]:
if status[w] == UNSEEN:
status[w] = FRINGE
parent[w] = maxIndex
bandwidth[w] = min(bandwidth[maxIndex], wt)
numFringes += 1
elif status[w] == FRINGE:
if(bandwidth[w] < min(bandwidth[maxIndex], wt)):
parent[w] = maxIndex
bandwidth[w] = min(bandwidth[maxIndex], wt)
return bandwidth, parent
def MBWDjikstraHeap(G, s, t):
status = np.zeros(G.numVertices, dtype=int)
bandwidth = np.zeros(G.numVertices, dtype=int)
parent = np.array([ -1 for i in range(G.numVertices)])
heapIndex = np.array([ -1 for i in range(G.numVertices)])
status[s] = INTREE
fringeHeap = MaxHeap()
for w,wt in G.E[s]:
status[w] = FRINGE
bandwidth[w] = wt
parent[w] = s
fringeHeap.Insert(HeapNode(w,bandwidth[w]),heapIndex=heapIndex)
while(fringeHeap.numElements > 0):
maxVal = fringeHeap.Top()
maxIndex = maxVal.key
status[maxIndex] = INTREE
fringeHeap.Delete(0, heapIndex=heapIndex)
for w,wt in G.E[maxIndex]:
if status[w] == UNSEEN:
status[w] = FRINGE
parent[w] = maxIndex
bandwidth[w] = min(bandwidth[maxIndex], wt)
fringeHeap.Insert(HeapNode(w,bandwidth[w]),heapIndex=heapIndex)
elif status[w] == FRINGE:
if(bandwidth[w] < min(bandwidth[maxIndex], wt)):
parent[w] = maxIndex
bandwidth[w] = min(bandwidth[maxIndex], wt)
fringeHeap.Delete(heapIndex[w], heapIndex=heapIndex)
fringeHeap.Insert(HeapNode(w,bandwidth[w]),heapIndex=heapIndex)
return bandwidth, parent
def MBWinTree(G, s, t): # DFS -> Works since no more than one path between two vertices in Tree
status = np.zeros(G.numVertices, dtype=int)
bandwidth = np.zeros(G.numVertices, dtype=int)
parent = np.array([ -1 for i in range(G.numVertices)])
vertexStack = [] #Using stack for iterative form of DFS
status[s] = 1
for w,wt in G.E[s]:
vertexStack.append(w)
bandwidth[w] = wt
status[w] = 1
parent[w] = s
while(len(vertexStack) > 0):
v = vertexStack[-1] # Top of stack
vertexStack.pop()
for w,wt in G.E[v]:
if(status[w] != 1):
vertexStack.append(w)
bandwidth[w] = min(bandwidth[v], wt)
status[w] = 1
parent[w] = v
return bandwidth, parent
def MBWKruskal(G, s, t):
edgeList = []
subTrees = UnionFind(G.numVertices)
maxSpanTree = Graph(G.numVertices,noEdges=True) #Graph with no edges on init
bandwidth = np.zeros(G.numVertices)
for i in range(G.numVertices):
for w,wt in G.E[i]:
if(w>i): # Ensure only unique edges considered
edgeList.append(HeapNode(key=[i,w],weight=wt))
edgeList = HeapSort(edgeList)
for edge in edgeList:
if(subTrees.Find(edge.key[0]) == 0):
subTrees.MakeSet(edge.key[0])
if(subTrees.Find(edge.key[1]) == 0):
subTrees.MakeSet(edge.key[1])
if(subTrees.Find(edge.key[0]) != subTrees.Find(edge.key[1])):
maxSpanTree.AddEdge((edge.key[0],edge.key[1],edge.weight))
subTrees.Union(edge.key[0],edge.key[1])
# return MBW path in maxSpanTree
return MBWinTree(maxSpanTree, s, t)
|
14,738 | a676cab9a3a281c2f453d9e457bda81f66262e10 | from setuptools import find_packages, setup
setup(
name='src',
packages=find_packages(),
version='0.1.0',
description='find some suspicious behaviours of trader.',
author='chirag',
license='',
)
|
14,739 | 71e4bbd70f3e7145e0758b595c4ceff6b1edfd76 | from keras.models import model_from_json
import numpy
import os
# SECTION 1 - Load the model
# By now all of this should be pretty clear for you.
# Still, check out the relevant Keras manual entry
# https://keras.io/models/about-keras-models/
json_file = open('model.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)
loaded_model.load_weights("model.h5")
print("Loaded model from disk")
# SECTION 2 - Run the model on the dataset
# Once you see how the output is, youc an adjust it
# so that it gives the same output as you get from
# your training function.
loaded_model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
score = loaded_model.evaluate(X, Y, verbose=0)
print("%s: %.2f%%" % (loaded_model.metrics_names[1], score[1]*100))
# That's it, it is a simple as that!
|
14,740 | 5b186229922b0d6399707781537ac6d875894350 | from django.contrib import admin
from .models import UrlShort
admin.site.register(UrlShort)
|
14,741 | 80e0bccb2cfa7cbc4c6aabc1dfa37e43f97d49b6 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import cv2
import argparse
import json
import os
import random
import sys
import numpy as np
import tensorflow as tf
import numpy as np
#print(path+'/fisr.png')
batch_size = 128
num_of_classes=3
image_size=28
validate_data=3000
# The following defines a simple CovNet Model.
def SVHN_net_v0(x_):
with tf.variable_scope("CNN"):
conv1 = tf.layers.conv2d(
inputs=x_,
filters=32, # number of filters
kernel_size=[5, 5],
padding="same",
activation=tf.nn.relu)
pool1 = tf.layers.max_pooling2d(inputs=conv1,pool_size=[2, 2], strides=2) # convolution stride
conv2 = tf.layers.conv2d(
inputs=pool1,
filters=32, # number of filters
kernel_size=[5, 5],
padding="same",
activation=tf.nn.relu)
pool2 = tf.layers.max_pooling2d(inputs=conv2,
pool_size=[2, 2],
strides=2) # convolution stride
pool_flat = tf.contrib.layers.flatten(pool2, scope='pool2flat')
dense = tf.layers.dense(inputs=pool_flat, units=500, activation=tf.nn.relu)
logits = tf.layers.dense(inputs=dense, units=num_of_classes)
return logits
def apply_classification_loss(model_function):
with tf.Graph().as_default() as g:
with tf.device("/cpu:0"): # use gpu:0 if on GPU
x_ = tf.placeholder(tf.float32, [None, image_size, image_size,1],name='x')
y_ = tf.placeholder(tf.int32, [None],name='y')
y_logits = model_function(x_)
y_dict = dict(labels=y_, logits=y_logits)
losses = tf.nn.sparse_softmax_cross_entropy_with_logits(**y_dict)
cross_entropy_loss = tf.reduce_mean(losses)
trainer = tf.train.AdamOptimizer(learning_rate=0.001)
train_op = trainer.minimize(cross_entropy_loss)
y_pred = tf.argmax(tf.nn.softmax(y_logits), axis=1)
correct_prediction = tf.equal(tf.cast(y_pred, tf.int32), y_)
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
model_dict = {'graph': g, 'inputs': [x_, y_], 'train_op': train_op,
'accuracy': accuracy, 'loss': cross_entropy_loss}
return model_dict
def get_data(x,y,i):
start=i*batch_size
end=start+batch_size
if (end>x.shape[0]):
end=x.shape[0]
#print("start is ",start)
#print("end is ",end)
x_batch_data=x[start:end,:,:,:]
y_batch_data=y[start:end]
return x_batch_data,y_batch_data
def train_model(model_dict, x_data,y_data,x_test,y_test ,epoch_n, print_every):
with model_dict['graph'].as_default(), tf.Session() as sess:
saver = tf.train.Saver()
#print("variables are",tf.trainable_variables())
sess.run(tf.global_variables_initializer())
batch_num=int(np.ceil(x_data.shape[0]/batch_size))
for epoch_i in range(epoch_n):
for iter_i in range(batch_num):
x_placeholder=model_dict['inputs'][0]
y_placeholder=model_dict['inputs'][1]
#train_feed_dict = dict(zip(model_dict['inputs'], data_batch))
[x_batch_data,y_batch_data]=get_data(x_data,y_data,iter_i)
sess.run(model_dict['train_op'], feed_dict={x_placeholder:x_batch_data,y_placeholder:y_batch_data})
if (iter_i%200==0):
to_compute = [model_dict['loss'], model_dict['accuracy']]
loss,accuracy=sess.run(to_compute, feed_dict={x_placeholder:x_test,y_placeholder:y_test})
print(iter_i,"/",batch_num,"loss:",loss," accuracy:",accuracy)
saver.save(sess, "./saved_sess/model.ckpt")
def load_data():
axe_data=np.load('axe.npy')
cat_data=np.load('cat.npy')
apple_data=np.load('apple.npy')
#labels are 0-axe 1-cat 2-apple
axe_labels=np.zeros(axe_data.shape[0])*0
cat_labels=np.ones(cat_data.shape[0])*1
apple_labels=np.ones(apple_data.shape[0])*2
#connect all data for randomization
data_d=np.concatenate((axe_data,cat_data,apple_data))
data_l=np.concatenate((axe_labels,cat_labels,apple_labels))
data_l=np.expand_dims(data_l,1)
data_all=np.concatenate((data_d,data_l),axis=1)
data_all=np.random.permutation(data_all)
x_data=data_all[:,0:-1]
y_data=data_all[:,-1]
num_img=x_data.shape[0]
data_img=np.reshape(x_data,[num_img,image_size,image_size])
data_train=data_img[validate_data:,:,:]
data_train=np.expand_dims(data_train,3)
labels_train=y_data[validate_data:]
data_test=data_img[:validate_data:,:,:]
data_test=np.expand_dims(data_test,3)
labels_test=y_data[:validate_data]
return data_train,labels_train,data_test,labels_test
[x_data,y_data,x_test,y_test]=load_data()
print("----------_#$%------")
print(x_data.shape)
print(y_data.shape)
print(x_test.shape)
print(y_test.shape)
model_dict = apply_classification_loss(SVHN_net_v0)
train_model(model_dict, x_data,y_data,x_test,y_test ,epoch_n=1, print_every=20)
|
14,742 | 92fd7c33bbb6b5c8438f57a7decdc8aa3ecc257e | from OpenGLCffi.GL import params
@params(api='gl', prms=['mode', 'indirect', 'drawcount', 'maxdrawcount', 'stride'])
def glMultiDrawArraysIndirectCountARB(mode, indirect, drawcount, maxdrawcount, stride):
pass
@params(api='gl', prms=['mode', 'type', 'indirect', 'drawcount', 'maxdrawcount', 'stride'])
def glMultiDrawElementsIndirectCountARB(mode, type, indirect, drawcount, maxdrawcount, stride):
pass
|
14,743 | 9b60a1554c8c839323e72c729fa50a7711a7e7a8 | #from number_recognition import *
import random
import math
import numpy as np
import jsonpickle
import atexit
import json
import keyboard
from tkinter import Tk,Canvas, font
with open("./save_net.json") as f:
print("Starting importing net...")
net = jsonpickle.decode(f.read())
print("Import net complete")
matrix = [0]*(28*28)
border, spacement = 50, 20
def erase_all(evt):
global matrix
matrix = [0]*(28*28)
draw_table()
def click(evt):
global border, spacement, matrix
circle = [[ 0, 0, 0, 0, 0],
[ 0, 0, 0.5, 0, 0],
[ 0, 0.5, 1, 0.5, 0],
[ 0, 0, 0.5, 0, 0],
[ 0, 0, 0, 0, 0 ]]
x_block = (evt.x - border) // spacement
y_block = (evt.y - border) // spacement
for x in range(-2,3):
for y in range(-2,3):
if 0 <= x_block-x < 28 and 0 <= y_block-y < 28:
matrix[(y_block-y)*28+x_block-x] += circle[x+2][y+2]
matrix[(y_block - y) * 28 + x_block - x] = min(matrix[(y_block-y)*28+x_block-x],1)
draw_table()
def draw_table():
global border, spacement, matrix, net
guess = net.calculateResult(matrix)
confidence = max(guess)
guess = guess.index(confidence)
canvas.delete("all")
for i in range(29):
canvas.create_line(border + i*spacement, border, border+i*spacement, border+28*spacement,width=2,fill="black")
canvas.create_line(border, border + i * spacement, border + 28 * spacement, border + i * spacement, width=2,fill="black")
for x in range(28):
for y in range(28):
background=matrix[y * 28 + x]
if background == 0:
continue
background = "#"+str(round((1-background)*255))*3
canvas.create_rectangle(border+x*spacement,border+y*spacement,border+(x+1)*spacement,border+(y+1)*spacement, fill=background)
Font = font.Font(size=10)
canvas.create_text(350,border*2+28*spacement,text=str(guess)+" Confidence: "+str(round(confidence*100))+"%", font=Font)
taille = 700
Fenetre = Tk()
Fenetre.geometry(str(taille)+"x"+str(taille))
canvas = Canvas(Fenetre,width=taille,height=taille,borderwidth=0,highlightthickness=0,bg="lightgray")
canvas.pack()
Fenetre.bind("<B1-Motion>",click)
Fenetre.bind("<Button-1>",click)
Fenetre.bind("<KeyPress-space>",erase_all)
Fenetre.after(100,draw_table)
Fenetre.mainloop()
|
14,744 | fdc1df77b6903164db1616bfaf7cfc14ce890936 | # -*- coding: utf-8 -*-
"""
Created on Sun Sep 20 12:15:56 2020
@author: 426-2019级-1
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
df = pd.read_excel("predict_mor.xlsx")
mor = df['MOR_PREDICT']
'''
画图观察是否为平稳序列
plt.figure(figsize=(10,6))
plt.plot(df.index,mor)
plt.show() #看上去不平稳
'''
'''
一阶差分
'''
def timestamp(h,m,s,gap,num):
for i in range(num):
s = s+1 if i%2 == 0 else s
s+=gap
m+=int(s/60)
h+=int(m/60)
s = s%60
m = m%60
return "2016-04-14 %s:%s:%s"%(
str(h) if h>=10 else '0'+str(h),
str(m) if m>=10 else '0'+str(m),
str(s) if s>=10 else '0'+str(s),
)
time = df['date']
mor_d1 = np.diff(mor)
#mor_d2 = np.diff(mor_d1)
#plt.plot(mor)
##plt.title("高速公路MOR估算时序图",fontsize=30)
#plt.xlabel("时间序列",fontsize=25)
#plt.ylabel("MOR(m)")
#plt.show() #一阶差分 大致稳定
'''
plt.figure()
plt.plot(range(len(mor_d1)),mor_d1)
plt.title("一阶差分",fontsize=30 )
plt.xlabel("时间序列",fontsize=25)
plt.ylabel("MOR一阶差分值",fontsize=25)
plt.figure()
plt.plot(range(len(mor_d2)),mor_d2)
plt.title("二阶差分",fontsize=30)
plt.xlabel("时间序列",fontsize=25)
plt.ylabel("MOR二阶差分值",fontsize=25)
'''
#from statsmodels.tsa.stattools import adfuller
#adf = adfuller(mor)
#print(adf)
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
'''
plot_acf(mor_d1)
plt.xlabel("p",fontsize=25)
plt.title("自相关图",fontsize=30)
plot_pacf(mor_d1)
plt.xlabel("q",fontsize=25)
plt.title("偏自相关",fontsize=30)
'''
'''
(-9.482240734386155,
3.845143230413058e-16,
2, 95, {'1%': -3.5011373281819504, '5%': -2.8924800524857854,
'10%': -2.5832749307479226}, 522.7009913785289)
时序信号自身adf为-9.4822 均小于三种置信度 因此可以认作平稳信号
'''
#使用ARIMA去拟合原始数据,使用ARMA去拟合一阶差分数据 这里就使用ARMA模型
train = mor[0:80]
test = mor[80:-1]
from statsmodels.tsa.arima_model import ARIMA
model = ARIMA(train,order = (15,1,1)) #p,q来自于上面 d为几阶差分后可认作为平稳信号
result = model.fit()
'''
残差检验
resid = result.resid
from statsmodels.graphics.api import qqplot
qqplot(resid,line = 'q',fit = True)
plt.show() #qq图上 红线为正态分布 即红线 结果可以看出散点图大致符合该趋势 因此信号为白噪声
'''
plt.figure()
pred = result.predict(start=1,end=len(mor)+200,typ='levels')
x=100
for i in range(100,len(pred)):
if pred[i] >= 220:
x = i
break
plt.xticks([0,98],['公路截图开始时间\n'+time[0],'公路截图结束时间\n2016-04-14 07:39:11'])
plt.plot(range(len(pred)),[220]*len(pred),linestyle = '--')
plt.plot(range(len(mor)),mor,c='r')
plt.plot(range(len(pred)),pred,c='g')
plt.title('ARIMA模型预测MOR以及计算估计所得MOR',fontsize=30)
plt.annotate('预测大雾消散时间:\n%s'%timestamp(6,31,8,41,x), xy=(x, pred[x]), xycoords='data', xytext=(-100, -100),
textcoords='offset points', fontsize=20,arrowprops=dict(arrowstyle='->', connectionstyle="arc3,rad=.2")
)
sum_abs = 0
for i in range(79,99):
sum_abs = abs(pred[i]-mor[i])/pred[i]
print(sum_abs/20)
plt.tick_params(labelsize=20)
plt.legend(['期望的mor','计算估计的mor','模型预测的mor'],fontsize=25)
plt.xlabel('时间序列',fontsize=25)
plt.ylabel('MOR(m)',fontsize=25)
plt.show()
|
14,745 | 9088af991ca128e85550708cbddddf45af963d56 | # -*- coding:utf-8 -*-
import socket
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('www.bilibili.com', 80))
s.send(b'GET /HTTP/1.1\r\nHost:www.bilibili.com\r\nConnection:close\r\n\r\n')
buffer=[]
while True:
d=s.recv(1024)
if d:
buffer.append(d)
else:
break
data=b''.join(buffer)
s.close()
header, html = data.split(b'\r\n\r\n', 1)
print(header.decode('utf-8'))
# 把接收的数据写入文件:
with open('sina.html', 'wb') as f:
f.write(html) |
14,746 | a77ed31a71760f495bdfed54cbe1295c506714c3 | from pyspark.sql.functions import *
import csv
from pyspark.sql.types import *
from pyspark.sql.functions import *
from pyspark import SparkContext
from pyspark.sql import HiveContext
from pyspark.sql.functions import *
from pyspark.sql.functions import udf
from pyspark.sql.types import BooleanType
from pyspark.sql import Row
import csv
from pyspark.sql import SQLContext
def parseCSV(idx, part):
if idx==0:
part.next()
for p in csv.reader(part):
if p[14] < p[23]:
if p[0] == '2014':
yield Row(YEAR = p[0],
MONTH = int(p[2]),
ORIGIN=p[14],
ORIGIN_AIRPORT_ID = p[11],
DEST = p[23],
DEST_AIRPORT_ID = p[20],
ROUTE = (p[14],p[23]))
elif p[0] == '2015':
yield Row(YEAR = p[0],
MONTH = int(p[2])+12,
ORIGIN=p[14],
ORIGIN_AIRPORT_ID = p[11],
DEST = p[23],
DEST_AIRPORT_ID = p[20],
ROUTE = (p[14],p[23]))
elif p[0] == '2016':
yield Row(YEAR = p[0],
MONTH = int(p[2])+24,
ORIGIN=p[14],
ORIGIN_AIRPORT_ID = p[11],
DEST = p[23],
DEST_AIRPORT_ID = p[20],
ROUTE = (p[14],p[23]))
else:
pass
else:
if p[0] == '2014':
yield Row(YEAR = p[0],
MONTH = int(p[2]),
ORIGIN=p[23],
ORIGIN_AIRPORT_ID = p[11],
DEST = p[14],
DEST_AIRPORT_ID = p[20],
ROUTE = (p[23],p[14]))
elif p[0] == '2015':
yield Row(YEAR = p[0],
MONTH = int(p[2])+12,
ORIGIN=p[23],
ORIGIN_AIRPORT_ID = p[11],
DEST = p[14],
DEST_AIRPORT_ID = p[20],
ROUTE = (p[23],p[14]))
elif p[0] == '2016':
yield Row(YEAR = p[0],
MONTH = int(p[2])+24,
ORIGIN=p[23],
ORIGIN_AIRPORT_ID = p[11],
DEST = p[14],
DEST_AIRPORT_ID = p[20],
ROUTE = (p[23],p[14]))
else:
pass
def main(sc):
spark = HiveContext(sc)
sqlContext = HiveContext(sc)
print "holaaaaa"
rows = sc.textFile('../lmf445/Flight_Project/Data/864625436_T_ONTIME_2*.csv').mapPartitionsWithIndex(parseCSV)
df = sqlContext.createDataFrame(rows)
busiest_route_month_pivot = \
df.select('ORIGIN_AIRPORT_ID', 'ROUTE', 'MONTH') \
.groupBy('ROUTE').pivot('MONTH').count()
busiest_route_month_pivot.toPandas().to_csv('Output/MonthlyRoutes.csv')
if __name__ == "__main__":
sc = SparkContext()
main(sc)
# In[ ]: |
14,747 | 31a9533a17422cf19cd4b2880499c0bf8d310df5 | # Generated by Django 2.2.7 on 2019-11-30 04:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sightings', '0009_auto_20191129_0902'),
]
operations = [
migrations.AlterField(
model_name='new_sighting',
name='Latitude',
field=models.DecimalField(blank=True, decimal_places=6, max_digits=8, null=True),
),
migrations.AlterField(
model_name='new_sighting',
name='Longitude',
field=models.DecimalField(blank=True, decimal_places=6, max_digits=8, null=True),
),
]
|
14,748 | 9b152afba43afe835957dcab49d98dd66d3d3e65 | from urllib.request import urlopen
WORD_URL="http://learncodethehardway.org/words.txt"
WORDS=[]
#for word in urlopen(WORD_URL).readlines():
#WORDS.append(str(word.strip(), encoding='utf-8'))
#print(WORDS)
print(b"adjustment\n".strip())
|
14,749 | acfe875629dc508aae710e1da80a9d2d71885217 | class Bread:
def __init__(self):
self.current_price = 0.80
self.id = 'Bread'
self.discount = False
self.price = 0.80
def apply_discount(self, discount):
self.discount = True
return self.price * discount
def __repr__(self):
return f"{self.id} - {self.current_price}€"
|
14,750 | d606013330f22f10c4732da07609b28cf04744a7 | from django.db import models
from django.utils.translation import gettext as _
import uuid
class Breed(models.Model):
class Meta:
verbose_name = _('Breed')
verbose_name_plural = _('Breeds')
title = models.CharField(_('title'), max_length=64,
blank=False, unique=True, null=False)
def __str__(self):
return self.title
class Dog(models.Model):
SEXS = (
('M', _('Male'),),
('F', _('Female'),),
)
class Meta:
verbose_name = _('Dog')
verbose_name_plural = _('Dogs')
nickname = models.CharField(
_('nickname'), max_length=64, blank=True, null=True)
breed = models.ForeignKey(
Breed, blank=False, null=True, on_delete=models.SET_NULL, verbose_name=_('Breed'))
weight = models.FloatField(
_('weight'), blank=False)
height = models.FloatField(
_('Growth at the withers'), blank=False)
date_of_birth = models.DateField(_('Date of birth'), blank=True, null=True)
guardian = models.ForeignKey(
'Guardian', blank=True, on_delete=models.SET_NULL, null=True)
sex = models.CharField(_('Sex'), max_length=1, choices=SEXS)
image = models.ImageField(
_('Photo'), upload_to='dogs_photo', blank=True, null=True)
def __str__(self):
return f'{self.id} | {self.get_nickname}'
@property
def get_nickname(self):
if self.nickname is not None:
return self.nickname
else:
return _("Name not specified")
class Guardian(models.Model):
class Meta:
verbose_name = _('Guardian')
verbose_name_plural = _('Guardians')
first_name = models.CharField(_('First name'), max_length=64, blank=False)
middle_name = models.CharField(
_('Middle name'), max_length=64, blank=True, null=True)
last_name = models.CharField(_('Last name'), max_length=64, blank=False)
phone_number = models.CharField(_('phone'), max_length=16, blank=False)
address = models.CharField(
_('Address'), max_length=255, blank=True, null=True)
def __str__(self):
return f'{self.id} | {self.last_name}'
def dogs_count(self) -> int:
return self.dog_set.all().count()
class Payment(models.Model):
'''Dog donation check'''
uuid = models.UUIDField(
primary_key=True, default=uuid.uuid1, editable=False)
target = models.ForeignKey(
Dog, on_delete=models.CASCADE, verbose_name=_('Target for donation'))
price = models.PositiveIntegerField(blank=False)
date_of_pay = models.DateTimeField(auto_now=True)
is_success = models.BooleanField(blank=False, default=True)
def __str__(self):
return f'Чек №{self.uuid} - {self.date_of_pay} {self.price}'
|
14,751 | 7a38d8535d07c29dde2abf7cabf28527bee48377 | """
objective 3 : two points on two consecutive sections
"""
import overpy
from geopy.geocoders import Nominatim
from method import *
def give_location3(api, nodes, name, addr,lat1,lon1,lat2,lon2):
''' Give the full location
:param nodes: The list of all nodes of the road
:param name: The name of the road
:param addr: The whole loaction of the tree
:return:?
'''
indice_min_1 = find_nearest_section(nodes,lat1,lon1)
indice_min_2 = find_nearest_section(nodes,lat2,lon2)
if indice_min_1 < indice_min_2:
intersection1 = find_intersection(api, nodes, indice_min_1, -1, name)
intersection2 = find_intersection(api, nodes, indice_min_2 + 1, 1, name)
else:
intersection1 = find_intersection(api, nodes, indice_min_2, -1, name)
intersection2 = find_intersection(api, nodes, indice_min_1 + 1, 1, name)
print(
"Sur "
+ name
+ " entre "
+ intersection1
+ " et "
+ intersection2
+ " dans la ville de "
+ addr[-7]
)
if __name__ == "__main__":
api = overpy.Overpass()
# get coords
lat_arbre_1 = 48.897121406
lon_arbre_1 = 2.2479852324
lat_arbre_2 = 48.89627806
lon_arbre_2 = 2.248657510
addr = find_addr(lat_arbre_1, lon_arbre_1)
way = find_way(api, lat_arbre_1, lon_arbre_1, addr)
give_location3(api, way.get_nodes(
resolve_missing=True), way.tags['name'], addr,lat_arbre_1,lon_arbre_1,lat_arbre_2,lon_arbre_2)
|
14,752 | fe23b5790679d3a037e8df0e88fc17966300d448 | from django.shortcuts import render
from django.http import HttpResponse
import pandas as pd
import json
# from django import jsonify
import os
from .models import Greeting
from django.views.decorators.csrf import csrf_protect
import digitaldivide.src.digitaldivide as digitaldivide
# Create your views here.
def index(request):
# return HttpResponse('Hello from Python!')
return render(request, "index.html")
def db(request):
greeting = Greeting()
greeting.save()
greetings = Greeting.objects.all()
return render(request, "db.html", {"greetings": greetings})
def options_landing(request):
return render(request, "options_landing.html")
def get_result(request):
# output_dump = digitaldivide.src.digitaldivideutil.digitaldividefunc()
global data
path = 'digitaldivide/dat/household-internet-data.csv'
data = pd.read_csv(path)
# filter here
hset = digitaldivide.HouseholdSet(data).sample()
global h
# print(hset)
(rowindex, h) = next(hset.iterrows())
print('>>')
# print(h)
house = digitaldivide.Household(h)
output_dump='<br>'
output_dump += ''' Selected household ''' + str(house.unit_id) + ''' has the following characteristics: <br>
Plan: (Mbps down/up)'''+ str(house.advertised_rate_down)+" "+ str(house.advertised_rate_up)
output_dump +='''<br>House ISP '''+str(house.isp)
output_dump += '''<br> House Technology '''+str(house.technology)
output_dump += '''<br>House State '''+str(house.state)
output_dump +='''<br>Estimated price per month: $'''+str(house.monthly_charge)
output_dump+= '''<br>Upload rate (kbps) '''+str(house.rate_up_kbps)
output_dump+='''<br>Download rate (kbps) '''+ str(house.rate_down_kbps)
output_dump += '''<br>Round-trip delay (ms) '''+ str(house.latency_ms)
output_dump +='''<br>Uplink jitter (ms) '''+ str(house.jitter_up_ms)
output_dump +='''<br>Downlink jitter (ms) '''+ str(house.jitter_down_ms)
output_dump +='''<br>Packet loss (%%) '''+str(house.loss)
output_dump += '<br><br><br>'
# output_dump += str(house.netem_template_up("192.168.0.1")).split()
return render(
request,
'houseset.html',
{
'output_dump': output_dump
}
)
@csrf_protect
def house_id(request):
output_dump = ''
if request.method == 'POST':
houseSet = request.POST['txtHouseSetQty']
state = request.POST['txtState']
tech = request.POST['txtTechnology']
isp = request.POST['txtIsp']
pricemin = request.POST['txtPriceMin']
pricemax = request.POST['txtPriceMax']
houseSet = int(houseSet)
if state == 'Any':
state = ['IL', 'NY', 'CA', 'KS', 'OH', 'CO', 'PA', 'NJ', 'OK', 'TX', 'AZ',
'GA', 'MA', 'KY', 'MD', 'NC', 'TN', 'WI', 'IA', 'NH', 'UT', 'IN',
'MI', 'HI', 'WV', 'FL', 'OR', 'WA', 'AR', 'DE', 'MN', 'VT', 'VA',
'ME', 'MT', 'CT', 'DC', 'MO', 'AL', 'NV', 'NE', 'SC', 'RI', 'LA',
'MS', 'NM', 'ID', 'WY', 'SD', 'ND']
else:
state = [state]
if tech == 'Any':
tech = ['CABLE', 'DSL', 'FIBER', 'SATELLITE']
else:
tech=[tech]
if isp == 'Any':
isp = ['Comcast', 'Time Warner Cable', 'Cox', 'Mediacom', 'Brighthouse',
'Charter', 'Cablevision', 'CenturyLink', 'AT&T', 'Windstream',
'Frontier', 'Verizon', 'Wildblue/ViaSat', 'Hughes']
else:
isp=[isp]
pricemin = float(pricemin)
pricemax = float(pricemax)
else:
houseSet = "1"
state = ['IL', 'NY', 'CA', 'KS', 'OH', 'CO', 'PA', 'NJ', 'OK', 'TX', 'AZ',
'GA', 'MA', 'KY', 'MD', 'NC', 'TN', 'WI', 'IA', 'NH', 'UT', 'IN',
'MI', 'HI', 'WV', 'FL', 'OR', 'WA', 'AR', 'DE', 'MN', 'VT', 'VA',
'ME', 'MT', 'CT', 'DC', 'MO', 'AL', 'NV', 'NE', 'SC', 'RI', 'LA',
'MS', 'NM', 'ID', 'WY', 'SD', 'ND']
tech = ['CABLE', 'DSL', 'FIBER', 'SATELLITE']
isp = ['Comcast', 'Time Warner Cable', 'Cox', 'Mediacom', 'Brighthouse',
'Charter', 'Cablevision', 'CenturyLink', 'AT&T', 'Windstream',
'Frontier', 'Verizon', 'Wildblue/ViaSat', 'Hughes']
pricemin = "0"
pricemax = "300"
path = 'digitaldivide/dat/household-internet-data.csv'
# data = pd.read_csv("household-internet-data.csv")
global data
data = pd.read_csv(path)
# print("size of data")
# print(data.shape)
# print(tech)
data = data.loc[data['technology'].isin(tech)]
# print("size of sieved data")
# print(data.shape)
if data.shape == (0, 0):
output_dump = 'NO RELEVANT SAMPLE , change technology'
return render(
request,
'houseset.html',
{
'output_dump': output_dump
}
)
data = data.loc[data['isp'].isin(isp)]
if data.shape == (0, 0):
output_dump = 'NO RELEVANT SAMPLE , change ISP'
return render(
request,
'houseset.html',
{
'output_dump': output_dump
}
)
data = data.loc[data['state'].isin(state)]
if data.shape == (0, 0):
output_dump = 'NO RELEVANT SAMPLE , change State'
return render(
request,
'houseset.html',
{
'output_dump': output_dump
}
)
data = data.loc[data['monthly.charge'] > float(pricemin)]
if data.shape == (0, 0):
output_dump = 'NO RELEVANT SAMPLE, change monthly minimum price'
return render(
request,
'houseset.html',
{
'output_dump': output_dump
}
)
data = data.loc[data['monthly.charge'] < float(pricemax)]
if data.shape == (0, 0):
output_dump = 'NO RELEVANT SAMPLE, change maximum monthly price'
return render(
request,
'houseset.html',
{
'output_dump': output_dump
}
)
# filter here
for i in range(int(houseSet)):
if i > 0:
data = data.loc[data['unit_id'] != str(house.unit_id)]
if data.shape == (0, 0):
output_dump = 'NO RELEVANT SAMPLE, less samples for these specs'
return render(
request,
'houseset.html',
{
'output_dump': output_dump
}
)
try:
print(data.shape)
# hset = digitaldivide.HouseholdSet(data).sample()
hset = digitaldivide.HouseholdSet(data).sample()
except:
output_dump = 'NO RELEVANT SAMPLE'
return render(
request,
'houseset.html',
{
'output_dump': output_dump
}
)
print(hset)
global h
(rowindex, h) = next(hset.iterrows())
house = digitaldivide.Household(h)
output_dump+='<br>'
output_dump += ''' Selected household ''' + str(house.unit_id) + ''' has the following characteristics: <br>
Plan: (Mbps down/up)'''+ str(house.advertised_rate_down)+" "+ str(house.advertised_rate_up)
output_dump +='''<br>House ISP '''+str(house.isp)
output_dump += '''<br> House Technology '''+str(house.technology)
output_dump += '''<br>House State '''+str(house.state)
output_dump +='''<br>Estimated price per month: $'''+str(house.monthly_charge)
output_dump+= '''<br>Upload rate (kbps) '''+str(house.rate_up_kbps)
output_dump+='''<br>Download rate (kbps) '''+ str(house.rate_down_kbps)
output_dump += '''<br>Round-trip delay (ms) '''+ str(house.latency_ms)
output_dump +='''<br>Uplink jitter (ms) '''+ str(house.jitter_up_ms)
output_dump +='''<br>Downlink jitter (ms) '''+ str(house.jitter_down_ms)
output_dump +='''<br>Packet loss (%%) '''+str(house.loss)
output_dump += '<br><br><br>'+str(house)
# output_dump += str(house.netem_template_up("192.168.0.1")).split()
return render(
request,
'houseset.html',
{
'output_dump': output_dump
}
)
def get_json(request):
global h
global hset
global data
hset = digitaldivide.HouseholdSet(data).sample()
(rowindex, h) = next(hset.iterrows())
house = digitaldivide.Household(h)
j_response_house = digitaldivide.Household.json_template(house)
# return HttpResponse(json.dumps(j_response_house), content_type="application/json", )
response = HttpResponse(j_response_house, content_type='application/json')
response['Content-Disposition'] = 'attachment; filename="foo.json"'
return response
# return jsonify(name='j_dump.json', data=j_response_house)
def get_rspec(request):
global h
global hset
global data
hset = digitaldivide.HouseholdSet(data).sample()
(rowindex, h) = next(hset.iterrows())
house = digitaldivide.Household(h)
r_response_house = digitaldivide.Household.json_template(house)
# return HttpResponse(json.dumps(j_response_house), content_type="application/json", )
response = HttpResponse(r_response_house, content_type='application/xml')
response['Content-Disposition'] = 'attachment; filename="foo.xml"'
return response
def get_netem(request):
global h
global hset
global data
house = digitaldivide.Household(h)
output_dump = ''' Netem template down <br>'''
output_dump += str(house.netem_template_down("0.0.0.0"))
# output_dump += digitaldivide.Household.netem_template_down('192.168.0.1')
output_dump += ''' Netem template up <br>'''
output_dump += str(house.netem_template_up("0.0.0.0"))
# output_dump += digitaldivide.Household.netem_template_up('192.168.0.1')
output_dump = '<br><br><br>'
output_dump += ''' Selected household ''' + str(house.unit_id) + ''' has the following characteristics: <br>
Plan: (Mbps down/up)''' + str(house.advertised_rate_down) + " " + str(house.advertised_rate_up)
output_dump += '''<br>House ISP ''' + str(house.isp)
output_dump += '''<br> House Technology ''' + str(house.technology)
output_dump += '''<br>House State ''' + str(house.state)
output_dump += '''<br>Estimated price per month: $''' + str(house.monthly_charge)
output_dump += '''<br>Upload rate (kbps) ''' + str(house.rate_up_kbps)
output_dump += '''<br>Download rate (kbps) ''' + str(house.rate_down_kbps)
output_dump += '''<br>Round-trip delay (ms) ''' + str(house.latency_ms)
output_dump += '''<br>Uplink jitter (ms) ''' + str(house.jitter_up_ms)
output_dump += '''<br>Downlink jitter (ms) ''' + str(house.jitter_down_ms)
output_dump += '''<br>Packet loss (%%) ''' + str(house.loss)
output_dump += '<br><br><br>'
return render(
request,
'houseset.html',
{
'output_dump': output_dump
}
) |
14,753 | 9e7a9d8c68f3d1fd7862b00659e3cd669fa07da8 | import ffmpeg
vid = ffmpeg.probe("man_running.mp4")
print(vid["streams"])
metadata = vid["streams"][0]
print(metadata)
print(metadata["r_frame_rate"]) |
14,754 | a15283d6ae2f6da67d9471955b8cf8fb7068401a | # 1 - Import library
import sys
sys.path.insert(0, '/storage/home/django_learn/pygame/src')
import os
import math
from random import random, randint
import imgaud
import core
import time
import pygame
from pygame.locals import *
from src import core
class SpaceAdv(core.SpaceAdvCore):
def menu(self):
positionsText = self.font.render("{}".format('New Game'), True, (0,0,0))
textRect = positionsText.get_rect()
textRect.topright=[935,5]
self.screen.blit(positionsText, textRect)
def main(self):
while self.running:
if self.old_time < int(time.time()):
self.old_time = int(time.time())
self.time += 1000
self.badtimer -= 1
# 5 - clear the screen before drawing it again
self.screen.fill(0)
# 6 - draw the screen elements
self.draw_background()
# 6.1 - Set player position and rotation
self.playerpos[0] += self.speed[0]
self.playerpos[1] += self.speed[1]
position = pygame.mouse.get_pos()
angle = math.atan2(position[1] - (self.playerpos[1] + 32),position[0] - (self.playerpos[0] + 26))
playerRot = pygame.transform.rotate(imgaud.player, 360-angle*57.29)
move = self.get_move_pos(position, angle, playerRot)
if move[0] >= self.width - 80 or move[0] <= 20:
self.speed[0] = 0
if move[1] >= self.height- 80 or move[1] <= 20:
self.speed[1] = 0
playerpos1 = (move[0], move[1])
self.screen.blit(playerRot, playerpos1)
# Draw position of ship
positionsText = self.font.render("({}, {})".format(move[0], move[1]), True, (0,0,0))
textRect = positionsText.get_rect()
textRect.topright=[935,5]
self.screen.blit(positionsText, textRect)
# 6.2 - Draw arrows
self.draw_arrows()
# 6.3 - Draw badgers
if self.badtimer == 0:
tmp = {
"pos": [randint(50,800), 0],
"img": imgaud.badguyimg1[randint(0,3)]
}
self.badguys.append(tmp)
self.badtimer = 100 - (self.badtimer1 * 2)
if self.badtimer1 >= 35:
self.badtimer1 = 35
else:
self.badtimer1 += 5
index = 0
for badguy in self.badguys:
if badguy['pos'][1] < -750:
self.badguys.pop(index)
badguy['pos'][1] += 10
# 6.3.1 - Attack castle
badrect = pygame.Rect(badguy['img'].get_rect())
badrect.top = badguy['pos'][1]
badrect.left = badguy['pos'][0]
if badrect.top > 750:
self.healthvalue -= randint(5,20)
self.badguys.pop(index)
imgaud.hit.play()
#6.3.2 - Check for collisions
index1 = 0
for bullet in self.arrows:
bullrect = pygame.Rect(imgaud.arrow.get_rect())
bullrect.left = bullet[1]
bullrect.top = bullet[2]
if badrect.colliderect(bullrect):
self.acc[0]+=1
self.badguys.pop(index)
self.arrows.pop(index1)
#sound
imgaud.enemy.play()
tmp = {
"pos": badguy['pos'],
"img": imgaud.deadimg1[randint(0,2)]
}
self.screen.blit(imgaud.explode, badguy['pos'])
self.deads.append(tmp)
index1 += 1
# 6.3.3 - Next bad guy
index += 1
for dead in self.deads:
self.screen.blit(dead['img'], dead['pos'])
for badguy in self.badguys:
self.screen.blit(badguy['img'], badguy['pos'])
# 6.4 - Draw clock
survivedText = self.font.render(str(int((self.time_left - self.time) / 60000)) + ":" + str(round((self.time_left - self.time) / 1000 % 60)).zfill(2), True, (0,0,0))
textRect = survivedText.get_rect()
textRect.topright = [635,5]
self.screen.blit(survivedText, textRect)
# 6.5 - Draw health bar
self.screen.blit(imgaud.healthbar, (5,5))
for health1 in range(self.healthvalue):
self.screen.blit(imgaud.health, (health1+8,8))
# 7 - update the screen
pygame.display.flip()
# 8 - loop through the events
for event in pygame.event.get():
# check if the event is the X button
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w or event.key==pygame.K_UP:
self.keys['up'] = True
elif event.key == pygame.K_a or event.key==pygame.K_LEFT:
self.keys['left'] = True
elif event.key == pygame.K_s or event.key==pygame.K_DOWN:
self.keys['down'] = True
elif event.key == pygame.K_d or event.key==pygame.K_RIGHT:
self.keys['right'] = True
elif event.key == pygame.K_r:
self.keys['reset'] = True
if event.type == pygame.KEYUP:
if event.key==pygame.K_w or event.key==pygame.K_UP:
self.keys['up'] = False
elif event.key==pygame.K_a or event.key==pygame.K_LEFT:
self.keys['left'] = False
elif event.key==pygame.K_s or event.key==pygame.K_DOWN:
self.keys['down'] = False
elif event.key==pygame.K_d or event.key==pygame.K_RIGHT:
self.keys['right'] = False
elif event.key==pygame.K_r:
self.keys['reset'] = False
if event.type == pygame.MOUSEBUTTONDOWN:
position = pygame.mouse.get_pos()
self.acc[1] += 1
self.arrows.append([math.atan2(position[1] - (playerpos1[1] + 32),position[0] - (playerpos1[0] + 26)), playerpos1[0] + 32, playerpos1[1] + 32])
imgaud.shoot.play()
if event.type==pygame.QUIT:
# if it is quit the game
pygame.quit()
exit(0)
# 9 - Move player
if self.keys['up']:
self.speed[1] -= 0.1
elif self.keys['down']:
self.speed[1] += 0.1
if self.keys['left']:
self.speed[0] -= 0.1
elif self.keys['right']:
self.speed[0] += 0.1
if self.keys['reset']:
return self.reset()
self.results()
while not self.running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit(0)
pygame.display.flip()
pygame.init()
game = SpaceAdv()
# game.menu()
game.main()
|
14,755 | 407c5672f72a0a591bd66a4e75dbeb0eb4f3a4ce | import datetime
class Test:
def __init__(self, testid):
self.__testid = testid
self.__questions = []
self.__noofq = 0
self.__maxmarks = 0
self.__level = None
self.__date = datetime.datetime.now()
def DesignTest(self):
testid = input("Test id: ")
self.__testid = testid
while True:
level = input("Level?(A,S,G) :")
if level.upper() in ['A','S','G']:
self.__level = level
break
else:
print("error input")
qno = 0
totalmarks = 0
print("set question to 'x' to stop adding questions")
while qno < 10:
text = input("question: ")
if text == 'x':
break
answer = input("answer: ")
topic = input("topic: ")
marks = input("marks: ")
totalmarks += int(marks)
self.__maxmarks = totalmarks
qid = self.__testid + str(qno)
newQ = Question()
newQ.SetQuestion(qid, text, answer, marks, topic)
self.__questions.append(newQ)
qno += 1
def PrintTest(self):
for question in self.__questions:
print(question.GetQuestion())
def PrintAnswers(self):
for question in self.__questions:
print(question.GetAnswer())
class Question:
def __init__(self):
self.__questionid = None
self.__questiontext = None
self.__answer = None
self.__marks = None
self.__topic = None
def SetQuestion(self, ID, text, answer, marks, topic):
self.__questionid = ID
self.__questiontext = text
self.__answer = answer
self.__marks = marks
self.__topic = topic
def GetQuestion(self):
return self.__questiontext
def GetMarks(self):
return self.__marks
def GetTopic(self):
return self.__topic
def GetAnswer(self):
return self.__answer
newtest = Test("OOP")
newtest.DesignTest()
newtest.PrintTest()
newtest.PrintAnswers()
|
14,756 | 5bd95b5c96338b070ae50d046c29d29f084a6b57 | from featurehub.tests.util import EPSILON
from featurehub.modeling.scorers import ndcg_score, rmsle_score
from featurehub.modeling.scorers import ndcg_scorer, rmsle_scorer
from featurehub.modeling.automl import ndcg_autoscorer, rmsle_autoscorer
import numpy as np
def test_ndcg():
y_true = np.array([1,0,2])
y_pred1 = np.array([[0.15, 0.55, 0.2], [0.7, 0.2, 0.1], [0.06, 0.04, 0.9]])
score1 = ndcg_score(y_true, y_pred1, k=2)
assert score1 == 1.0
y_pred2 = np.array([[.9, 0.5, 0.8], [0.7, 0.2, 0.1], [0.06, 0.04, 0.9]])
score2 = ndcg_score(y_true, y_pred2, k=2)
assert np.abs(score2 - 0.666666) < EPSILON
# 0.5 0.5 1./np.log2(3)
y_pred3 = np.array([[.9, 0.5, 0.8], [0.1, 0.7, 0.2], [0.04, 0.9, 0.06]])
score3 = ndcg_score(y_true, y_pred3, k=3)
assert np.abs(score3 - 0.543643) < EPSILON
def test_rmsle():
pass
|
14,757 | ccaa76129cdbdc67952ab8b858aff997e93b1eeb | from ._Actions import *
from ._SetControlMode import *
|
14,758 | 6c60bc48907dac1cf6ec5076d26ec1b786d85b0f | # Generated by Django 3.2.6 on 2021-08-28 03:26
import aseb.core.db.fields
import aseb.core.db.utils
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.db.models.functions.datetime
import django_editorjs_fields.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name="Company",
fields=[
(
"id",
models.BigAutoField(
auto_created=True, primary_key=True, serialize=False, verbose_name="ID"
),
),
(
"created_at",
models.DateTimeField(
default=django.db.models.functions.datetime.Now, editable=False
),
),
("modified_at", models.DateTimeField(auto_now=True)),
("removed_at", models.DateTimeField(blank=True, editable=False, null=True)),
("title", models.CharField(max_length=100)),
("slug", models.SlugField(unique=True)),
("seo_title", models.CharField(blank=True, max_length=70)),
("seo_description", models.CharField(blank=True, max_length=300)),
(
"main_image",
models.ImageField(
blank=True,
null=True,
upload_to=aseb.core.db.utils.UploadToFunction(
"{model_name}/{obj.pk}/{filename}.{ext}"
),
),
),
("content", django_editorjs_fields.fields.EditorJsJSONField(blank=True, null=True)),
(
"visibility",
models.CharField(
blank=True,
choices=[("public", "Public"), ("open", "Open"), ("private", "Private")],
default="open",
max_length=10,
null=True,
),
),
("headline", models.CharField(blank=True, max_length=140)),
("presentation", models.TextField(blank=True)),
("contact", aseb.core.db.fields.PropertiesField(blank=True, default=dict)),
("display_name", models.CharField(max_length=140)),
(
"size",
models.IntegerField(
blank=True,
choices=[
(1, "1 - 4 employees"),
(2, "5 - 9 employees"),
(3, "10 - 19 employees"),
(4, "20 - 49 employees"),
(5, "50 - 99 employees"),
(6, "100 - 249 employees"),
(7, "250 - 499 employees"),
(8, "500 - 999 employees"),
(9, "1,000+ employees"),
],
null=True,
),
),
(
"created_by",
models.ForeignKey(
blank=True,
editable=False,
null=True,
on_delete=django.db.models.deletion.CASCADE,
related_name="+",
to=settings.AUTH_USER_MODEL,
),
),
(
"modified_by",
models.ForeignKey(
blank=True,
editable=False,
null=True,
on_delete=django.db.models.deletion.CASCADE,
related_name="+",
to=settings.AUTH_USER_MODEL,
),
),
(
"removed_by",
models.ForeignKey(
blank=True,
editable=False,
null=True,
on_delete=django.db.models.deletion.CASCADE,
related_name="+",
to=settings.AUTH_USER_MODEL,
),
),
],
options={
"verbose_name_plural": "companies",
},
),
migrations.CreateModel(
name="Topic",
fields=[
(
"id",
models.BigAutoField(
auto_created=True, primary_key=True, serialize=False, verbose_name="ID"
),
),
(
"created_at",
models.DateTimeField(
default=django.db.models.functions.datetime.Now, editable=False
),
),
("modified_at", models.DateTimeField(auto_now=True)),
("removed_at", models.DateTimeField(blank=True, editable=False, null=True)),
("name", models.CharField(db_index=True, max_length=250, unique=True)),
("emoji", aseb.core.db.fields.EmojiChooseField(blank=True, max_length=3)),
(
"created_by",
models.ForeignKey(
blank=True,
editable=False,
null=True,
on_delete=django.db.models.deletion.CASCADE,
related_name="+",
to=settings.AUTH_USER_MODEL,
),
),
(
"modified_by",
models.ForeignKey(
blank=True,
editable=False,
null=True,
on_delete=django.db.models.deletion.CASCADE,
related_name="+",
to=settings.AUTH_USER_MODEL,
),
),
(
"removed_by",
models.ForeignKey(
blank=True,
editable=False,
null=True,
on_delete=django.db.models.deletion.CASCADE,
related_name="+",
to=settings.AUTH_USER_MODEL,
),
),
(
"sibling",
models.ManyToManyField(
blank=True,
related_name="_organization_topic_sibling_+",
to="organization.Topic",
),
),
],
options={
"ordering": ("name",),
},
),
migrations.CreateModel(
name="Member",
fields=[
(
"id",
models.BigAutoField(
auto_created=True, primary_key=True, serialize=False, verbose_name="ID"
),
),
(
"created_at",
models.DateTimeField(
default=django.db.models.functions.datetime.Now, editable=False
),
),
("modified_at", models.DateTimeField(auto_now=True)),
("removed_at", models.DateTimeField(blank=True, editable=False, null=True)),
("title", models.CharField(max_length=100)),
("slug", models.SlugField(unique=True)),
("seo_title", models.CharField(blank=True, max_length=70)),
("seo_description", models.CharField(blank=True, max_length=300)),
(
"main_image",
models.ImageField(
blank=True,
null=True,
upload_to=aseb.core.db.utils.UploadToFunction(
"{model_name}/{obj.pk}/{filename}.{ext}"
),
),
),
("content", django_editorjs_fields.fields.EditorJsJSONField(blank=True, null=True)),
("display_name", models.CharField(blank=True, max_length=140)),
(
"visibility",
models.CharField(
blank=True,
choices=[("public", "Public"), ("open", "Open"), ("private", "Private")],
default="open",
max_length=10,
null=True,
),
),
("headline", models.CharField(blank=True, max_length=140)),
("presentation", models.TextField(blank=True)),
("contact", aseb.core.db.fields.PropertiesField(blank=True, default=dict)),
("first_name", models.CharField(max_length=140)),
("last_name", models.CharField(max_length=140)),
("birthday", models.DateField(blank=True, null=True)),
(
"type",
models.CharField(
choices=[("member", "Member"), ("partner", "Partner")], max_length=20
),
),
(
"position",
models.CharField(
blank=True,
choices=[
("president", "President"),
("advisor", "Advisor"),
("boardMember", "Board Member"),
],
max_length=20,
null=True,
),
),
("partner_since", models.DateField(blank=True, null=True)),
("activated_at", models.DateField(blank=True, null=True)),
("expires_at", models.DateField(blank=True, null=True)),
("mentor_since", models.DateTimeField(blank=True, null=True)),
("mentor_presentation", models.TextField(blank=True)),
(
"company",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="members",
to="organization.company",
),
),
(
"created_by",
models.ForeignKey(
blank=True,
editable=False,
null=True,
on_delete=django.db.models.deletion.CASCADE,
related_name="+",
to=settings.AUTH_USER_MODEL,
),
),
(
"login",
models.OneToOneField(
blank=True,
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="membership",
to=settings.AUTH_USER_MODEL,
),
),
(
"mentor_topics",
models.ManyToManyField(
blank=True,
related_name="_organization_member_mentor_topics_+",
to="organization.Topic",
),
),
(
"modified_by",
models.ForeignKey(
blank=True,
editable=False,
null=True,
on_delete=django.db.models.deletion.CASCADE,
related_name="+",
to=settings.AUTH_USER_MODEL,
),
),
(
"nominated_by",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="nominated_members",
to="organization.member",
),
),
(
"removed_by",
models.ForeignKey(
blank=True,
editable=False,
null=True,
on_delete=django.db.models.deletion.CASCADE,
related_name="+",
to=settings.AUTH_USER_MODEL,
),
),
(
"topics",
models.ManyToManyField(
blank=True,
related_name="_organization_member_topics_+",
to="organization.Topic",
),
),
],
options={
"abstract": False,
},
),
migrations.AddField(
model_name="company",
name="topics",
field=models.ManyToManyField(
blank=True, related_name="_organization_company_topics_+", to="organization.Topic"
),
),
]
|
14,759 | 7395de8434cbd2f7447c62574644093c3f6b3b23 | import pretty_midi
from scipy.io import wavfile
import numpy as np
class ChordiumException(Exception):
pass
class IDontKnowThatChord(ChordiumException):
pass
def f64le_to_s32le(data):
shifted = data * (2 ** 31 - 1) # Data ranges from -1.0 to 1.0
ints = shifted.astype(np.int32)
return ints
def chord_name_to_note_name(chord: str):
if chord == "C":
return ["C4", "E4", "G4"]
else:
raise IDontKnowThatChord(f'idk that chord "{chord}" yet.')
def chord_to_wav(chord: str):
pm = pretty_midi.PrettyMIDI()
violin_program = pretty_midi.instrument_name_to_program("Violin")
violin = pretty_midi.Instrument(program=violin_program)
for note_name in chord_name_to_note_name(chord):
note_number = pretty_midi.note_name_to_number(note_name)
note = pretty_midi.Note(velocity=100, pitch=note_number, start=0, end=0.5)
violin.notes.append(note)
pm.instruments.append(violin)
audio_data = pm.fluidsynth()
wavfile.write("hoge.wav", 44100, f64le_to_s32le(audio_data))
if __name__ == "__main__":
chord_to_wav("C") |
14,760 | aee54c333e563b9fbeb4df9af093e94fc56d37c3 | import math
class Knot:
def __init__(self, kn_id, x, y, kn_type, angleSupport, k=[0, 0, 0], pointload=[0, 0, 0]):
self.id = kn_id
self.x_ = x
self.y_ = y
self.pointLoad_ = pointload
self.type = kn_type
self.angle = math.degrees(angleSupport) # in degree
self.coupled_el = [] # connected elements, stores IDs
self.k = k # spring stiffness
def __repr__(self):
return str(self.id)
def __str__(self):
# TODO What is k, do I need to add this to the plot
out_str = ""
out_str += "id: " + str(self.id)
out_str += "\ttype: " + str(self.type)
out_str += "\n\tx: " + str(self.x_)
out_str += "\ty: " + str(self.y_)
out_str += "\tangle: " + str(self.angle)
out_str += "\n\tpointload: " + str(self.pointLoad_)
if self.is_spring():
out_str += "\n\tSpring stiffness: "
out_str += "k_x: {}\t k_y: {}\t mom: {}".format(self.k[0], self.k[1], self.k[2])
if self.coupled_el:
out_str += "\n\tconnected elements: "
for el in self.coupled_el:
out_str += "\t" + str(el) + ","
return out_str
def set_pointload(self, f_hori, f_verti, moment):
self.pointLoad_ = [f_hori, f_verti, moment]
def reset_pointload(self):
self.pointLoad_ = [0, 0, 0]
def add_pointload(self, n, q, mom):
self.pointLoad_ = [self.pointLoad_[0] + n, self.pointLoad_[1] + q, self.pointLoad_[2] + mom]
def set_spring_stiffness(self, k_x, k_y, k_mom):
self.k = [k_x, k_y, k_mom]
def add_spring_stiffness(self, k_x, k_y, k_mom):
self.k = [self.k[0] + k_x, self.k[1] + k_y, self.k[2] + k_mom]
def is_spring(self):
for el in self.k:
if el != 0:
return True
return False
def has_pointload(self):
for el in self.pointLoad_:
if el != 0:
return True
return False
def add_coupled_el(self, el_to_add):
"""
Adds a connected element to the list of connected elements
:param el_to_add: id of the element being coupled. Can be one int or list of ints
"""
if isinstance(el_to_add, list):
self.coupled_el.extend(el_to_add)
else:
self.coupled_el.append(el_to_add)
def delete_coupled_el(self, el_to_del):
"""
Deletes coupled element from list of coupled elements
:param el_to_del: id of the element that needs to be deleted
"""
try:
self.coupled_el.remove(el_to_del)
except ValueError:
print("element is not in list")
def get_knot_id(knot):
return knot.id
|
14,761 | 485fe3cfc6cd31971cee7c837fc2980cc443578c | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 30 23:15:33 2019
@author: marco
Nome: Marcos Vinicius Timoteo Nunes Matricula: 16.2.8388
Disciplina: Aprendizagem de Maquina
Professor: Luiz Carlos Bambirra
Obs: Lembrar de comentar DO TREINAMENTO PARA BAIXO, PARA RODAR
Depois disso, pode descomentar e rodar novamente o codigo inteiro
"""
from sklearn.cluster import KMeans
#from sklearn import KNN
from itertools import combinations
import pandas as pd
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from sklearn import svm
from sklearn.metrics import classification_report, confusion_matrix,accuracy_score
#Leitura da base de dados
dataBase = pd.read_table('arquivoTreino.data',delimiter=',', header=None)
#Separando os classificadores da base de dados
targets = dataBase.iloc[:,10:11]
classifier = KNeighborsClassifier(n_neighbors=5)
#Separando a base de dados dos classificadores
dataBaseAtual = dataBase.iloc[:,1:10]
#aux = dataBase.iloc[:,9:10]
clf = svm.SVC(gamma=0.001,C=100.)
# Separando os valores de classificacção para teste e treino
saida_Treino = targets.iloc[0:np.int(np.floor(len(targets)*0.7)),:]
saida_Teste = targets.iloc[0:np.int(np.floor(len(targets)*0.3)),:]
ListaDeCombinacoes= list()
vetAcuracia =list()
NumCombinacoes = 0
for i in range(0,9):
ListaDePossibilidades = list(combinations(dataBaseAtual.columns,i))
for x in ListaDePossibilidades:
dataAux = pd.DataFrame()
# Pegando o numero de combinações
ListaDeCombinacoes.append(x)
for y in x:
# Concatenando os valores da dataBaseAtual
# nas colunas no dataAux(dataFrame) de acordo
# com os indices do dataBaseAtual
dataAux = pd.concat([dataAux, dataBaseAtual[y]], axis=1)
# Pegando o numero de combinações
NumCombinacoes+=1
# Separando base de teste dos valores do dataAux
teste = dataAux.iloc[0:np.int(np.floor(len(dataAux)*0.3)),:]
# Separando a base de treino dos valores do dataAUX
treino =dataAux.iloc[0:np.int(np.floor(len(dataAux)*0.7)),:]
print(dataAux)
#
# Treinando o algoritmo (COMENTAR DAQUI PRA BAIXO PARA RODAR
#DA PRIMEIRA VEZ, depois pode rodar o codigo inteiro)
classifier.fit(treino, saida_Treino)
# Classificando os dados de teste
Pred = classifier.predict(teste)
# Adicionando no vetor de acuracia o calculo das acuracias das
# de atributos combinações
vetAcuracia.append(accuracy_score(saida_Teste, Pred))
# Pegando a melhor acuracia
MAXpred = max(vetAcuracia)
# Pegando o menor valor de acuracia
MINpred = min(vetAcuracia)
# Pegando a lista de combinacoes
print(vetAcuracia)
print('Maior valor de acuracia', MAXpred)
print('Menor valor de acuracia', MINpred)
print('A melhor combinacao é:',ListaDeCombinacoes[vetAcuracia.index(MAXpred)])
print('A segunda melhor é:',ListaDeCombinacoes[vetAcuracia.index(MAXpred)-1])
print('A terceira melhor é:',ListaDeCombinacoes[vetAcuracia.index(MAXpred)-2])
print('A quarta combinacao é:',ListaDeCombinacoes[vetAcuracia.index(MAXpred)-3])
print('A pior combinacao é:',ListaDeCombinacoes[vetAcuracia.index(MINpred)])
|
14,762 | c8a0488d22ab0178add20e4877362a74d5ba21d6 | import numpy as np
import cv2
import threading
import Object
import StopLine
from model import NeuralNetwork
class CollectTrainingData(object):
def __init__(self, client, steer):
self.client = client
self.steer = steer
self.stopline = StopLine.Stop()
self.dect = Object.Object_Detection(self.steer)
# model create
self.model = NeuralNetwork()
self.model.load_model(path = 'model_data/video_model_1.h5')
def collect(self):
print("Start video stream")
stream_bytes = b' '
while True :
stream_bytes += self.client.recv(1024)
first = stream_bytes.find(b'\xff\xd8')
last = stream_bytes.find(b'\xff\xd9')
if first != -1 and last != -1:
try:
jpg = stream_bytes[first:last + 2]
stream_bytes = stream_bytes[last + 2:]
image = cv2.imdecode(np.frombuffer(jpg, dtype=np.uint8), cv2.IMREAD_GRAYSCALE)
rgb = cv2.imdecode(np.frombuffer(jpg, dtype=np.uint8), cv2.IMREAD_COLOR)
rgb2 = rgb.copy()
roi = image[120:240, :]
roi2 = rgb2[120:240, :] #for line roi
cv2.imshow('Origin', rgb)
cv2.imshow('GRAY', image)
cv2.imshow('roi', roi)
# reshape the roi image into a vector
image_array = np.reshape(roi, (-1, 120, 320, 1))
# neural network makes prediction
self.steer.Set_Line(self.model.predict(image_array))
self.steer.Set_Stopline(self.stopline.GetStopLine(roi2))
self.dect.Detection(rgb)
self.steer.Control()
except:
continue
if cv2.waitKey(1) & 0xFF == ord('q'):
break
|
14,763 | 1b536837235b5598d71ef64ef055f323900320b5 | import os
from ..applescript import osascript
ITERM = os.path.join(os.path.dirname(__file__), "iterm.applescript")
ITERM_BRACKETED = os.path.join(os.path.dirname(__file__), "iterm_bracketed.applescript")
def send_to_iterm(cmd, bracketed=False, commit=True):
if bracketed:
osascript(ITERM_BRACKETED, cmd, str(commit))
else:
osascript(ITERM, cmd, str(commit))
|
14,764 | 7409b02753022a523bdd964e1f549fa7b6b6554d | import pygame.font
class Buttom ():
"""Кнопка в игре"""
def __init__(self, pa_settings, screen, msg):
"""Инициализируем кнопку"""
#self.pa_settings = pa_settings
self.screen = screen
self.screen_rect = screen.get_rect()
#Назначение размеров и свойств кнопки
self.width,self.height = 200, 50
self.buttom_color = (0, 255, 0)
self.text_color = (255, 255, 255)
self.font = pygame.font.SysFont(None, 48)
self.msg = msg
#Построение объекта и выравнивание по центру экрана
self.rect = pygame.Rect(0, 0, self.width,self.height)
self.rect.center = self.screen_rect.center
#Сообщение кновки создаётся только один раз
self.prep_msg(msg)
def prep_msg(self,msg):
"""Преобразует msg в прямоугольник и выравнивает текст по центру"""
self.msg_image = self.font.render(msg, True, self.text_color, self.buttom_color)
self.msg_image_rect = self.msg_image.get_rect()
self.msg_image_rect.center = self.rect.center
def draw_buttom(self):
#Отображение пустой кнопки и ввывод сообщения
self.screen.fill(self.buttom_color, self.rect)
self.screen.blit(self.msg_image, self.msg_image_rect) |
14,765 | 77b15ea90cb722fa2a2f606a6935477554ec60d5 | from rest_framework import serializers
from .models import IpAddress
class IpAddressSerializer(serializers.ModelSerializer):
class Meta:
model = IpAddress
fields = '__all__'
read_only_fields = ('ip_address','status',) |
14,766 | 5c98c99f636fbd0447e580862240582df9875a08 | import sys
from db import connect_db
c = connect_db()
cur = c.cursor()
# 2.g
def pop_obmocja(x, y, distance):
cur.execute(
"select sum(population) from naselje where x > {} and y > {} and x < {} and y < {}".format(x - distance,
y - distance,
x + distance,
y + distance))
result = cur.fetchone()
return result[0]
if __name__ == '__main__':
if len(sys.argv) > 1:
_, x, y, distance = sys.argv
pop_obmocja(float(x), float(y), float(distance))
else:
print(pop_obmocja(40, 40, 10))
print(pop_obmocja(40, 40, 20))
|
14,767 | 4599be3b262babffe85eb104207e301948767c19 | def sum_floats(nums):
return (sum([i for i in nums if isinstance(i, float)]))
print(sum_floats(['a',1,'f',3.2,4,3.25])) |
14,768 | e39ff197a9a3a27e9dd66aa9049b517cb0c710ae | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'PackageDistribution'
db.create_table('repo_packagedistribution', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('package', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['repo.Package'])),
('distribution', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['repo.Distribution'])),
('component', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['repo.Component'])),
))
db.send_create_signal('repo', ['PackageDistribution'])
# Adding unique constraint on 'PackageDistribution', fields ['package', 'distribution']
db.create_unique('repo_packagedistribution', ['package_id', 'distribution_id'])
def backwards(self, orm):
# Removing unique constraint on 'PackageDistribution', fields ['package', 'distribution']
db.delete_unique('repo_packagedistribution', ['package_id', 'distribution_id'])
# Deleting model 'PackageDistribution'
db.delete_table('repo_packagedistribution')
models = {
'repo.architecture': {
'Meta': {'ordering': "('name',)", 'object_name': 'Architecture'},
'active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '10'})
},
'repo.component': {
'Meta': {'ordering': "('name',)", 'object_name': 'Component'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '50'})
},
'repo.distribution': {
'Meta': {'ordering': "('name',)", 'object_name': 'Distribution'},
'active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'architectures': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['repo.Architecture']", 'symmetrical': 'False'}),
'components': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['repo.Component']", 'symmetrical': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'repo.package': {
'Meta': {'ordering': "('component__distribution__name', 'component__name', 'name')", 'unique_together': "(('name', 'distribution'),)", 'object_name': 'Package'},
'component': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['repo.Component']"}),
'distribution': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['repo.Distribution']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '1024'})
},
'repo.packagedistribution': {
'Meta': {'unique_together': "(('package', 'distribution'),)", 'object_name': 'PackageDistribution'},
'component': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['repo.Component']"}),
'distribution': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['repo.Distribution']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'package': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['repo.Package']"})
}
}
complete_apps = ['repo']
|
14,769 | 5b5cb02c2ea8dcd994d1e8028c8362f207063ccc | from account import Account
def main():
loop = True
while loop:
i_d = input("Enter your ID, or press ENTER: ")
if i_d == "":
break
elif float(i_d) < 0:
print("Enter a positive number")
else:
break
loop = True
while loop:
balance = input("Enter your bank balance, or press ENTER: ")
if balance == "":
break
elif float(balance) < 0:
print("Enter a positive number")
else:
break
loop = True
while loop:
annual_interest_rate = input("Enter the Annual Interest Rate, or press ENTER: ")
if annual_interest_rate == "":
break
elif float(annual_interest_rate) < 0:
print("Enter a positive number")
elif float(annual_interest_rate) > 10:
print("Enter a percent less than 10")
else:
break
account1 = Account(i_d, balance, annual_interest_rate)
account1.set_id()
account1.set_balance()
account1.set_annual_interest_rate()
play_again = True
while play_again:
account1.get_display()
menu_choice = eval(input("Choose a category: "))
if menu_choice == 1:
account1.get_id()
elif menu_choice == 2:
account1.get_balance_string()
elif menu_choice == 3:
account1.get_annual_interest_rate()
elif menu_choice == 4:
account1.get_monthly_interest_rate()
elif menu_choice == 5:
account1.get_monthly_interest()
elif menu_choice == 6:
loop = True
while loop:
withdraw_money = float(input("Enter the amount you wish to withdraw: "))
if float(withdraw_money) < 0:
print("Enter a valid number that is not negative")
elif withdraw_money > account1.get_balance():
print("That withdrawal exceeds your funds")
else:
break
account1.withdraw(withdraw_money)
elif menu_choice == 7:
loop = True
while loop:
deposit_money = float(input("Enter the amount you wish to deposit: "))
if float(deposit_money) < 0:
print("Enter a valid number that is not negative")
else:
break
account1.deposit(deposit_money)
else:
print("Thanks")
break
main() |
14,770 | 431ea3275d4931af11d0c4197db73cf7f919d31d | import abc
import numpy as np
__all__ = ['ParamView', 'NodeParamView', 'EdgeParamView']
# delegate almost all magic methods to the full array
# (omit in-place ops + a few others like __len__ that we will special
# case)
_delegated_dunders = ['abs', 'add', 'and', 'bool', 'complex',
'contains', 'copy', 'deepcopy', 'divmod', 'eq',
'float', 'floordiv', 'format', 'ge', 'gt',
'index', 'int', 'invert', 'le', 'lshift',
'lt', 'matmul', 'mod', 'mul', 'ne', 'neg', 'or',
'pos', 'pow', 'radd', 'rand', 'rdivmod', 'reduce',
'reduce_ex', 'repr', 'rfloordiv', 'rlshift', 'rmatmul',
'rmod', 'rmul', 'ror', 'rpow', 'rrshift', 'rsub',
'rtruediv', 'rxor', 'sizeof', 'str', 'sub', 'truediv',
'xor']
_delegated_methods = ['T', 'all', 'any', 'argmax', 'argmin', 'choose',
'conj', 'conjugate', 'copy', 'cumprod', 'cumsum',
'diagonal', 'dot', 'dtype', 'flat', 'flatten',
'imag', 'max', 'mean', 'min', 'ndim', 'nonzero',
'prod', 'ravel', 'real', 'repeat', 'reshape',
'round', 'searchsorted', 'sort', 'squeeze', 'std',
'sum', 'tofile', 'tolist', 'tostring', 'trace',
'transpose', 'var']
def delegated_to_numpy(method_name):
def wrapped(self, *args, **kwargs):
arr = self.array
return getattr(arr, method_name)(*args, **kwargs)
return wrapped
class ParamViewMeta(abc.ABCMeta):
def __init__(cls, name, bases, attrs):
super().__init__(name, bases, attrs)
for attr in _delegated_dunders:
attr = f"__{attr}__"
setattr(cls, attr, delegated_to_numpy(attr))
for attr in _delegated_methods:
setattr(cls, attr, delegated_to_numpy(attr))
class ParamView(object, metaclass=ParamViewMeta):
def __init__(self, name, net, default=np.nan):
self._name = name
self._net = net
self._default = default
def __len__(self):
return len(self._net)
def __iter__(self):
yield from self.array
@abc.abstractmethod
def set(self, value):
pass
@abc.abstractmethod
def __getitem__(self, item):
pass
@abc.abstractmethod
def __setitem__(self, item, value):
pass
@property
@abc.abstractmethod
def shape(self):
pass
@property
@abc.abstractmethod
def array(self):
pass
class NodeParamView(ParamView):
def __getitem__(self, item):
def _get(node):
return self._net.nodes[node].get(self._name, self._default)
try:
return _get(item)
except (KeyError, TypeError):
nodes = list(item)
return np.array([_get(node) for node in nodes])
def __setitem__(self, item, value):
def _set(node, value):
self._net.nodes[node][self._name] = value
if item in self._net.nodes:
_set(item, value)
else:
nodes = list(item)
if np.isscalar(value):
for node in nodes:
_set(node, value)
else:
for node, v in zip(nodes, value):
_set(node, v)
def set(self, value):
if np.isscalar(value):
for node in self._net:
self[node] = value
else:
for node, v in zip(self._net.nodes, value):
self[node] = v
@property
def shape(self):
n = len(self)
return (n,)
@property
def array(self):
return np.array([self[node] for node in self._net], dtype=np.float64)
class EdgeParamView(ParamView):
def __getitem__(self, item):
def _get(edge):
return self._net.edges[edge].get(self._name, self._default)
try:
return _get(item)
except (KeyError, TypeError):
edges = list(item)
return np.array([_get(edge) for edge in edges])
def __setitem__(self, item, value):
def _set(edge, value):
self._net.edges[edge][self._name] = value
if item in self._net.edges:
_set(item, value)
else:
edges = list(item)
if np.isscalar(value):
for edge in edges:
_set(edge, value)
else:
for edge, v in zip(edges, value):
_set(edge, v)
def set(self, value):
if np.isscalar(value):
for edge in self._net.edges():
self[edge] = value
else:
nodes = list(self._net)
value = np.array(value).reshape(self.shape)
if not self._net.is_directed() and not np.all(
value == value.T):
raise ValueError(
f"Can't set edge param '{self._name}' with a "
f"non-symmetric matrix when graph is undirected.")
for (i, j), v in np.ndenumerate(value):
node1, node2 = nodes[i], nodes[j]
if self._net.has_edge(node1, node2):
self[node1, node2] = v
@property
def shape(self):
n = len(self)
return (n, n)
@property
def array(self):
# map node to idx
idx = dict((node, i) for i, node in enumerate(self._net))
arr = np.zeros(self.shape)
for u in self._net:
for v in self._net.neighbors(u):
arr[idx[u], idx[v]] = self[u, v]
return arr
|
14,771 | c0050dc9175b70ddeb5e80576890d85f5fbd3a06 | # -*- coding: utf-8 -*-
import scrapy
from scrapy.selector import Selector
from scrapy.http import Request
from usc.items import CourseItem
import re
from urllib.parse import urljoin
class UscsocSpider(scrapy.Spider):
name = 'uscsoc'
allowed_domains = ['web-app.usc.edu', 'web-app.usc', 'usc.edu']
start_urls = ['https://web-app.usc.edu/ws/soc_archive/soc//']
def parse(self, response):
"""
This starts at https://web-app.usc.edu/ws/soc_archive/soc/
and selects each Term (example: Fall 2018)
"""
sel = Selector(response)
terms = sel.xpath('//*[@id="termdata"]//li/a/@href')
# These selectors were found through trial and error.
# http://xpather.com/ is a useful site
terms = terms[2:13]
for t in terms:
item = CourseItem()
url = 'https://web-app.usc.edu/ws/soc_archive/soc/' + t.get().strip()
item['university'] = 'USC'
item['term'] = t.get()[5:-1]
item['code'] = 'USC'
yield Request(url=url,callback=self.parseDepartments,meta={'item':item}, dont_filter=True)
def parseDepartments(self, response):
"""
For each of the terms, it gets the list of
departments inside the Viterbi School of Engineering
"""
sel = Selector(response)
departments = sel.xpath('//li[@data-school="Engineering" and @data-type="department"]/a')
for d in departments:
item = CourseItem(response.request.meta["item"])
item['department'] = d.xpath('span/text()').get()
href = d.xpath('@href').get().strip()
url = urljoin('https://web-app.usc.edu', href)
yield Request(url=url,callback=self.parseCourses,meta={'item':item}, dont_filter=True)
def parseCourses(self, response):
"""
For each of the departments, it gets the list of classes
inside the department. (example: 101-794 in AME)
"""
sel = Selector(response)
courses = sel.xpath('//div[@class="course-info expandable"]')
for c in courses:
item = CourseItem(response.request.meta["item"])
item['code'] += '-' + c.xpath('@id').get().strip()
item['name'] = c.xpath('//a[@class="courselink"]/text()').get().strip()
# everything works up to here #
href = c.xpath('div/h3/a/@href').get()
url = urljoin('https://web-app.usc.edu', href)
yield Request(url=url,callback=self.parseSection,meta={'item':item})
def parseSection(self, response):
"""
For each of the classes, it gets the list of
sections available. Each section has an
instructor, syllabus, and section code
"""
sel = Selector(response)
sections = sel.xpath('//table[@class="sections responsive"]//tr[not(@class="headers")]')
for s in sections:
item = CourseItem(response.request.meta["item"])
item['section'] = s.xpath('@data-section-id').get().strip()
item['instructors'] = s.css('.instructor::text').get()
if item['instructors'] != None:
item['instructors'].strip()
item['instructors'] = [x.strip() for x in re.split(',', item['instructors'])]
item['syllabus'] = s.css('.syllabus a::attr(href)').get()
if item['syllabus'] != None:
item['syllabus'].strip()
return item
"""
Ignore the code below this. I was trying to get
the times, days, and number registered from the class sections
"""
#times = s.xpath('//td[@class="time"]/text()').get().strip()
#times = re.split('-', times)
#starttime = times[0]
#endtime = times[1]
#endt = dt.datetime.strptime(endtime, '%H:%M%p')
# TODO: Check if "am"/"pm" from endt, & if endt hour is greater/less than startt
#startt = dt.datetime.strptime(starttime, '%H:%M')
#days = s.xpath('//td[@class="days"]/text()').get().strip()
#days = re.split(',', days)
#numdays = len(days]
#cap = s.xpath('//td[@class="registered"]//a/text()').get().strip()
#cap = re.split(' of ', cap.strip())
#item['capacity'] = cap[1]
|
14,772 | c21dc5ae6e1fbf0fbb8bab9aefb7394f4a7db79a | from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import f_classif
from sklearn.ensemble import ExtraTreesClassifier
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import math
class Analyser():
def __init__(self, x, y, feature_list, fig_save_dir):
self.x = x
self.y = y
self.feature_list = feature_list
self.fig_save_dir = fig_save_dir
def run_feature_selection(self):
self._select_k_best()
self._extra_trees()
self._get_corr()
def _select_k_best(self):
best_features = SelectKBest(score_func=f_classif, k=20)
fit = best_features.fit(self.x, self.y)
dfscores = pd.DataFrame(fit.scores_)
dfcolumns = pd.DataFrame(self.feature_list)
feature_scores = pd.concat([dfcolumns, dfscores], axis=1)
feature_scores.columns = ['Feature Name', 'Score']
feature_scores.nlargest(40, 'Score').plot.barh(x='Feature Name', y='Score', title='Select K Best', figsize=(20,10))
plt.savefig(self.fig_save_dir.joinpath('kbest.png'))
def _extra_trees(self):
model = ExtraTreesClassifier()
model.fit(self.x, self.y)
feat_importances = pd.Series(model.feature_importances_, index=self.feature_list)
feat_importances.nlargest(40).plot(kind='barh', title='Extra Tree Classifier', figsize=(20,10))
plt.savefig(self.fig_save_dir.joinpath('extra_trees.png'))
def _get_corr(self):
x_df = pd.DataFrame(self.x, columns=self.feature_list)
y_df = pd.DataFrame(self.y, columns=['label'])
df = pd.merge(x_df, y_df, how="outer", left_index=True, right_index=True)
corrmat = df.corr()
corr = corrmat['label'].sort_values(ascending=False)
plt.figure(figsize=(15,15))
corr.plot(kind='barh', title='Correlation', figsize=(20, 20))
plt.savefig(self.fig_save_dir.joinpath('corr.png'))
|
14,773 | babe5235b102e1e9acd0c5768af95fbb55e56406 | from model.project import Project
def test_delete_project(app, config):
old_project_list = app.soap.get_projects_list(config["webadmin"]["username"], config["webadmin"]["password"])
if len(old_project_list) == 0:
app.project.add_new_project('new')
project_to_delete = old_project_list[0]
app.project.delete_project_by_name(project_to_delete.name)
old_project_list.remove(project_to_delete)
new_project_list = app.soap.get_projects_list(config["webadmin"]["username"], config["webadmin"]["password"])
assert sorted(old_project_list, key=Project.id_or_max) == sorted(new_project_list, key=Project.id_or_max) |
14,774 | 2c6c4d1133ea6c4f95f96e3c699ff6f50b4bed27 | import click
# from mne import read_ctf
import contextlib
import sys
from mne import find_layout
from os.path import commonprefix as cprfx
from os.path import split, splitext, exists, join
from os import makedirs
from mne.io import Raw as Raw_fif
from mne.io import read_raw_ctf as Raw_ctf
from scipy.io import savemat
import numpy as np
@contextlib.contextmanager
def nostdout():
# -- Works both in python2 and python3 -- #
try:
from cStringIO import StringIO
except ImportError:
from io import StringIO
# --------------------------------------- #
save_stdout = sys.stdout
sys.stdout = StringIO()
yield
sys.stdout = save_stdout
@click.command()
@click.argument('save_path', type=click.Path())
@click.argument('meg_files', nargs=-1)
@click.option('--flat/--no-flat', default=False)
def cli(meg_files, save_path, flat):
'''Convert fif or ds to .mat format'''
common_prefix = split(cprfx(meg_files))[0] + '/'
for meg_file in meg_files:
# click.echo(meg_file)
base, ext = splitext(meg_file)
new_base = base.replace(common_prefix, '')
if flat:
new_base = new_base.replace('/','_')
# click.echo(new_base)
new_base = join(save_path, new_base)
if ext == '.fif':
with nostdout():
raw = Raw_fif(meg_file, preload=True, add_eeg_ref=False)
elif ext == '.ds':
with nostdout():
raw = Raw_ctf(meg_file, preload=True)
else:
click.echo('ERROR: UNKNOWN FORMAT FOR {}'.format(meg_file))
meg_raw = raw.pick_types(meg=True, ref_meg=False)
data, times = meg_raw[:,:]
ch_names = meg_raw.info['ch_names']
la = find_layout(meg_raw.info)
pos = la.pos[:,:2]
pos_filt = np.array([pos[i,:] for i in range(len(pos)) if la.names[i] in ''.join(raw.info['ch_names'])])
# click.echo(pos)
new_path,_ = split(new_base)
if not exists(new_path):
makedirs(new_path)
savemat(new_base + '.mat', {'data': data, 'times': times, 'chnames': ch_names, 'chxy': pos_filt})
|
14,775 | c667167dfd441292c299f768b45a3c1f33aebdb2 | from .affine import apply_rotation, random_rotation, sample_rotation
from .deformation import random_deformation_field, apply_deformation_field, random_deformation, checkboard3D, checkboard2D
from .generators import xy_augmentation_generator
from .ImageDataGenerator3D import ImageDataGenerator3D
from .sampling import select_image_samples, get_image_samples |
14,776 | 3357e042ed411c0645a4ef2f82d8f3da5e835a1f | from abc import ABC, abstractmethod
from jawa.assemble import assemble
from jawa.cf import ClassFile
from jawa.methods import Method
from jawa.constants import *
from jawa.util.descriptor import method_descriptor
from jawa.util.bytecode import Operand
import six.moves
# See https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.4.8
REF_getField = 1
REF_getStatic = 2
REF_putField = 3
REF_putStatic = 4
REF_invokeVirtual = 5
REF_invokeStatic = 6
REF_invokeSpecial = 7
REF_newInvokeSpecial = 8
REF_invokeInterface = 9
FIELD_REFS = (REF_getField, REF_getStatic, REF_putField, REF_putStatic)
class InvokeDynamicInfo(ABC):
@staticmethod
def create(ins, cf):
assert(ins.mnemonic == "invokedynamic")
if isinstance(ins.operands[0], Operand):
# Hack due to packetinstructions not expanding constants
const = cf.constants[ins.operands[0].value]
else:
const = ins.operands[0]
bootstrap = cf.bootstrap_methods[const.method_attr_index]
method = cf.constants.get(bootstrap.method_ref)
if method.reference.class_.name == "java/lang/invoke/LambdaMetafactory":
return LambdaInvokeDynamicInfo(ins, cf, const)
elif method.reference.class_.name == "java/lang/invoke/StringConcatFactory":
return StringConcatInvokeDynamicInfo(ins, cf, const)
else:
raise Exception("Unknown invokedynamic class: " + method.reference.class_.name.value)
def __init__(self, ins, cf, const):
self._ins = ins
self._cf = cf
self.stored_args = None
@abstractmethod
def __str__():
pass
def apply_to_stack(self, stack):
"""
Used to simulate an invokedynamic instruction. Pops relevant args, and
puts this object (used to simulate the function we return) onto the stack.
"""
assert self.stored_args == None # Should only be called once
num_arguments = len(self.dynamic_desc.args)
if num_arguments > 0:
self.stored_args = stack[-len(self.dynamic_desc.args):]
else:
self.stored_args = []
for _ in six.moves.range(num_arguments):
stack.pop()
stack.append(self)
@abstractmethod
def create_method(self):
pass
class LambdaInvokeDynamicInfo(InvokeDynamicInfo):
"""
Stores information related to an invokedynamic instruction.
"""
def __init__(self, ins, cf, const):
super().__init__(ins, cf, const)
self.generated_cf = None
self.generated_method = None
bootstrap = cf.bootstrap_methods[const.method_attr_index]
method = cf.constants.get(bootstrap.method_ref)
# Make sure this is a reference to LambdaMetafactory.metafactory
assert method.reference_kind == REF_invokeStatic
assert method.reference.class_.name == "java/lang/invoke/LambdaMetafactory"
assert method.reference.name_and_type.name == "metafactory"
assert len(bootstrap.bootstrap_args) == 3 # Num arguments
# It could also be a reference to LambdaMetafactory.altMetafactory.
# This is used for intersection types, which I don't think I've ever seen
# used in the wild, and maybe for some other things. Here's an example:
"""
class Example {
interface A { default int foo() { return 1; } }
interface B { int bar(); }
public Object test() {
return (A & B)() -> 1;
}
}
"""
# See https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.9
# and https://docs.oracle.com/javase/specs/jls/se8/html/jls-9.html#jls-9.8-200-D
# for details. Minecraft doesn't use this, so let's just pretend it doesn't exist.
# Now check the arguments. Note that LambdaMetafactory has some
# arguments automatically filled in. The bootstrap arguments are:
# args[0] is samMethodType, signature of the implemented method
# args[1] is implMethod, the method handle that is used
# args[2] is instantiatedMethodType, narrower signature of the implemented method
# We only really care about the method handle, and just assume that the
# method handle satisfies instantiatedMethodType, and that that also
# satisfies samMethodType. instantiatedMethodType could maybe be used
# to get the type of object created by the returned function, but I'm not
# sure if there's a reason to do that over just looking at the handle.
methodhandle = cf.constants.get(bootstrap.bootstrap_args[1])
self.ref_kind = methodhandle.reference_kind
# instantiatedMethodType does have a use when executing the created
# object, so store it for later.
instantiated = cf.constants.get(bootstrap.bootstrap_args[2])
self.instantiated_desc = method_descriptor(instantiated.descriptor.value)
assert self.ref_kind >= REF_getField and self.ref_kind <= REF_invokeInterface
# Javac does not appear to use REF_getField, REF_getStatic,
# REF_putField, or REF_putStatic, so don't bother handling fields here.
assert self.ref_kind not in FIELD_REFS
self.method_class = methodhandle.reference.class_.name.value
self.method_name = methodhandle.reference.name_and_type.name.value
self.method_desc = method_descriptor(methodhandle.reference.name_and_type.descriptor.value)
if self.ref_kind == REF_newInvokeSpecial:
# https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.4.8-200-C.2
assert self.method_name == "<init>"
else:
# https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.4.8-200-C.1
assert self.method_name not in ("<init>", "<clinit>")
# As for stack changes, consider the following:
"""
public Supplier<String> foo() {
return this::toString;
}
public Function<Object, String> bar() {
return Object::toString;
}
public static Supplier<String> baz(String a, String b, String c) {
return () -> a + b + c;
}
public Supplier<Object> quux() {
return Object::new;
}
"""
# Which disassembles (tidied to remove java.lang and java.util) to:
"""
Constant pool:
#2 = InvokeDynamic #0:#38 // #0:get:(LClassName;)LSupplier;
#3 = InvokeDynamic #1:#41 // #1:apply:()LFunction;
#4 = InvokeDynamic #2:#43 // #2:get:(LString;LString;LString;)LSupplier;
#5 = InvokeDynamic #3:#45 // #3:get:()LSupplier;
public Supplier<String> foo();
Code:
0: aload_0
1: invokedynamic #2, 0
6: areturn
public Function<Object, String> bar();
Code:
0: invokedynamic #3, 0
5: areturn
public static Supplier<String> baz(String, String, String);
Code:
0: aload_0
1: aload_1
2: aload_2
3: invokedynamic #4, 0
8: areturn
public Supplier<java.lang.Object> quux();
Code:
0: invokedynamic #5, 0
5: areturn
private static synthetic String lambda$baz$0(String, String, String);
-snip-
BootstrapMethods:
0: #34 invokestatic -snip- LambdaMetafactory.metafactory -snip-
Method arguments:
#35 ()LObject;
#36 invokevirtual Object.toString:()LString;
#37 ()LString;
1: #34 invokestatic -snip- LambdaMetafactory.metafactory -snip-
Method arguments:
#39 (LObject;)LObject;
#36 invokevirtual Object.toString:()LString;
#40 (LObject;)LString;
2: #34 invokestatic -snip- LambdaMetafactory.metafactory -snip-
Method arguments:
#35 ()LObject;
#42 invokestatic ClassName.lambda$baz$0:(LString;LString;LString;)LString;
#37 ()LString;
3: #34 invokestatic -snip- LambdaMetafactory.metafactory -snip-
Method arguments:
#35 ()LObject;
#44 newinvokespecial Object."<init>":()V
#35 ()LObject;
"""
# Note that both foo and bar have invokevirtual in the method handle,
# but `this` is added to the stack in foo().
# Similarly, baz pushes 3 arguments to the stack. Unfortunately the JVM
# spec doesn't make it super clear how to decide how many items to
# pop from the stack for invokedynamic. My guess, looking at the
# constant pool, is that it's the name_and_type member of InvokeDynamic,
# specifically the descriptor, that determines stack changes.
# https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.10.1.9.invokedynamic
# kinda confirms this without explicitly stating it.
self.dynamic_name = const.name_and_type.name.value
self.dynamic_desc = method_descriptor(const.name_and_type.descriptor.value)
assert self.dynamic_desc.returns.name != "void"
self.implemented_iface = self.dynamic_desc.returns.name
# created_type is the type returned by the function we return.
if self.ref_kind == REF_newInvokeSpecial:
self.created_type = self.method_class
else:
self.created_type = self.method_desc.returns.name
def __str__(self):
# TODO: be closer to Java syntax (using the stored args)
return "%s::%s" % (self.method_class, self.method_name)
def __repr__(self):
return "<%s::%s%s as %s::%s%s>" % (self.method_class, self.method_name, self.method_desc.descriptor, self.implemented_iface, self.dynamic_name, self.instantiated_desc.descriptor)
def create_method(self):
"""
Creates a Method that corresponds to the generated function call.
It will be part of a class that implements the right interface, and will
have the appropriate name and signature.
"""
assert self.stored_args != None
if self.generated_method != None:
return (self.generated_cf, self.generated_method)
class_name = self._cf.this.name.value + "_lambda_" + str(self._ins.pos)
self.generated_cf = ClassFile.create(class_name)
# Jawa doesn't seem to expose this cleanly. Technically we don't need
# to implement the interface because the caller doesn't actually care,
# but it's better to implement it anyways for the future.
# (Due to the hacks below, the interface isn't even implemented properly
# since the method we create has additional parameters and is static.)
iface_const = self.generated_cf.constants.create_class(self.implemented_iface)
self.generated_cf._interfaces.append(iface_const.index)
# HACK: This officially should use instantiated_desc.descriptor,
# but instead use a combination of the stored arguments and the
# instantiated descriptor to make packetinstructions work better
# (otherwise we'd need to generate and load fields in a way that
# packetinstructions understands)
descriptor = "(" + self.dynamic_desc.args_descriptor + \
self.instantiated_desc.args_descriptor + ")" + \
self.instantiated_desc.returns_descriptor
method = self.generated_cf.methods.create(self.dynamic_name,
descriptor, code=True)
self.generated_method = method
# Similar hack: make the method static, so that packetinstructions
# doesn't look for the corresponding instance.
method.access_flags.acc_static = True
# Third hack: the extra arguments are in the local variables/arguments
# list, not on the stack. So we need to move them to the stack.
# (In a real implementation, these would probably be getfield instructions)
# Also, this uses aload for everything, instead of using the appropriate
# instruction for each type.
instructions = []
for i in range(len(method.args)):
instructions.append(("aload", i))
cls_ref = self.generated_cf.constants.create_class(self.method_class)
if self.ref_kind in FIELD_REFS:
# This case is not currently hit, but provided for future use
# (Likely method_name and method_descriptor would no longer be used though)
ref = self.generated_cf.constants.create_field_ref(
self.method_class, self.method_name, self.method_desc.descriptor)
elif self.ref_kind == REF_invokeInterface:
ref = self.generated_cf.constants.create_interface_method_ref(
self.method_class, self.method_name, self.method_desc.descriptor)
# See https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-6.html#jvms-6.5.invokeinterface.notes
# Since the generated classfile only exists for use by burger,
# we don't _really_ need to handle this, other than providing
# some value, but it's not too hard. However, we're not currently
# treating longs and doubles as 2 instead of 1 (which is incorrect,
# but again, doesn't really matter since this is redundant information
# that burger does not use).
count = len(method.args)
else:
ref = self.generated_cf.constants.create_method_ref(
self.method_class, self.method_name, self.method_desc.descriptor)
# See https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-5.html#jvms-5.4.3.5
if self.ref_kind == REF_getField:
instructions.append(("getfield", ref))
elif self.ref_kind == REF_getStatic:
instructions.append(("getstatic", ref))
elif self.ref_kind == REF_putField:
instructions.append(("putfield", ref))
elif self.ref_kind == REF_putStatic:
instructions.append(("putstatic", ref))
elif self.ref_kind == REF_invokeVirtual:
instructions.append(("invokevirtual", ref))
elif self.ref_kind == REF_invokeStatic:
instructions.append(("invokestatic", ref))
elif self.ref_kind == REF_invokeSpecial:
instructions.append(("invokespecial", ref))
elif self.ref_kind == REF_newInvokeSpecial:
instructions.append(("new", cls_ref))
instructions.append(("dup",))
instructions.append(("invokespecial", ref))
elif self.ref_kind == REF_invokeInterface:
instructions.append(("invokeinterface", ref, count, 0))
method.code.assemble(assemble(instructions))
return (self.generated_cf, self.generated_method)
class StringConcatInvokeDynamicInfo(InvokeDynamicInfo):
"""
Java 9+ uses invokedynamic for string concatenation:
https://www.guardsquare.com/blog/string-concatenation-java-9-untangling-invokedynamic
"""
# An example:
"""
public static String foo(int num, int num2) {
return "num=" + num + " and num2=" + num2;
}
"""
# Becomes:
"""
Constant pool:
#7 = InvokeDynamic #0:#8 // #0:makeConcatWithConstants:(II)Ljava/lang/String;
public static java.lang.String foo(int, int);
descriptor: (II)Ljava/lang/String;
flags: (0x0009) ACC_PUBLIC, ACC_STATIC
Code:
stack=2, locals=2, args_size=2
0: iload_0
1: iload_1
2: invokedynamic #7, 0 // InvokeDynamic #0:makeConcatWithConstants:(II)Ljava/lang/String;
7: areturn
LineNumberTable:
line 3: 0
BootstrapMethods:
0: #19 REF_invokeStatic -snip- StringConcatFactory.makeConcatWithConstants -snip-
Method arguments:
#25 num=\u0001 and num2=\u0001
"""
# Note that the format string can have \u0002 in it as well to indicate a constant.
# I haven't seen any cases of \u0002 yet.
def __init__(self, ins, cf, const):
super().__init__(ins, cf, const)
bootstrap = cf.bootstrap_methods[const.method_attr_index]
method = cf.constants.get(bootstrap.method_ref)
# Make sure this is a reference to StringConcatFactory.makeConcatWithConstants
assert method.reference_kind == REF_invokeStatic
assert method.reference.class_.name == "java/lang/invoke/StringConcatFactory"
assert method.reference.name_and_type.name == "makeConcatWithConstants"
assert len(bootstrap.bootstrap_args) == 1 # Num arguments - may change with constants
# Now check the arguments. Note that StringConcatFactory has some
# arguments automatically filled in. The bootstrap arguments are:
# args[0] is recipe, format string
# Further arguments presumably go into the constants varargs array, but I haven't seen this
# (and I'm not sure how you get a constant that can't be converted to a string at compile time)
self.recipe = cf.constants.get(bootstrap.bootstrap_args[0]).string.value
assert '\u0002' not in self.recipe
self.dynamic_name = const.name_and_type.name.value
self.dynamic_desc = method_descriptor(const.name_and_type.descriptor.value)
assert self.dynamic_desc.returns.name == "java/lang/String"
def __str__(self):
recipe = self.recipe.replace("\u0001", "\\u0001").replace("\u0002", "\\u0002")
if (self.stored_args == None):
return "format_concat(\"%s\", ...)" % (recipe,)
else:
return "format_concat(\"%s\", %s)" % (recipe, ", ".join(str(a) for a in self.stored_args))
def create_method(self):
raise NotImplementedError()
def class_from_invokedynamic(ins, cf):
"""
Gets the class type for an invokedynamic instruction that
calls a constructor.
"""
info = InvokeDynamicInfo.create(ins, cf)
assert info.created_type != "void"
return info.created_type
def try_eval_lambda(ins, args, cf):
"""
Attempts to call a lambda function that returns a constant value.
May throw; this code is very hacky.
"""
info = InvokeDynamicInfo.create(ins, cf)
# We only want to deal with lambdas in the same class
assert info.ref_kind == REF_invokeStatic
assert info.method_class == cf.this.name
lambda_method = cf.methods.find_one(name=info.method_name, args=info.method_desc.args_descriptor, returns=info.method_desc.returns_descriptor)
assert lambda_method != None
class Callback(WalkerCallback):
def on_new(self, ins, const):
raise Exception("Illegal new")
def on_invoke(self, ins, const, obj, args):
raise Exception("Illegal invoke")
def on_get_field(self, ins, const, obj):
raise Exception("Illegal getfield")
def on_put_field(self, ins, const, obj, value):
raise Exception("Illegal putfield")
# Set verbose to false because we don't want lots of output if this errors
# (since it is expected to for more complex methods)
return walk_method(cf, lambda_method, Callback(), False, args)
def string_from_invokedymanic(ins, cf):
"""
Gets the recipe string, if this is a string concatenation implemented via invokedynamic.
"""
info = InvokeDynamicInfo.create(ins, cf)
if not isinstance(info, StringConcatInvokeDynamicInfo):
return
return info.recipe
class WalkerCallback(ABC):
"""
Interface for use with walk_method.
Any of the methods may raise StopIteration to signal the end of checking
instructions.
"""
@abstractmethod
def on_new(self, ins, const):
"""
Called for a `new` instruction.
ins: The instruction
const: The constant, a ConstantClass
return value: what to put on the stack
"""
pass
@abstractmethod
def on_invoke(self, ins, const, obj, args):
"""
Called when a method is invoked.
ins: The instruction
const: The constant, either a MethodReference or InterfaceMethodRef
obj: The object being invoked on (or null for a static method)
args: The arguments to the method, popped from the stack
return value: what to put on the stack (for a non-void method)
"""
pass
@abstractmethod
def on_get_field(self, ins, const, obj):
"""
Called for a getfield or getstatic instruction.
ins: The instruction
const: The constant, a FieldReference
obj: The object to get from, or None for a static field
return value: what to put on the stack
"""
pass
@abstractmethod
def on_put_field(self, ins, const, obj, value):
"""
Called for a putfield or putstatic instruction.
ins: The instruction
const: The constant, a FieldReference
obj: The object to store into, or None for a static field
value: The value to assign
"""
pass
def on_invokedynamic(self, ins, const, args):
"""
Called for an invokedynamic instruction.
ins: The instruction
const: The constant, a InvokeDynamic
args: Arguments closed by the created object
return value: what to put on the stack
"""
raise Exception("Unexpected invokedynamic: %s" % str(ins))
def walk_method(cf, method, callback, verbose, input_args=None):
"""
Walks through a method, evaluating instructions and using the callback
for side-effects.
The method is assumed to not have any conditionals, and to only return
at the very end.
"""
assert isinstance(callback, WalkerCallback)
stack = []
locals = {}
cur_index = 0
if not method.access_flags.acc_static:
# TODO: allow specifying this
locals[cur_index] = object()
cur_index += 1
if input_args != None:
assert len(input_args) == len(method.args)
for arg in input_args:
locals[cur_index] = arg
cur_index += 1
else:
for arg in method.args:
locals[cur_index] = object()
cur_index += 1
ins_list = list(method.code.disassemble())
for ins in ins_list[:-1]:
if ins in ("bipush", "sipush"):
stack.append(ins.operands[0].value)
elif ins.mnemonic.startswith("fconst") or ins.mnemonic.startswith("dconst"):
stack.append(float(ins.mnemonic[-1]))
elif ins.mnemonic.startswith("lconst"):
stack.append(int(ins.mnemonic[-1]))
elif ins == "aconst_null":
stack.append(None)
elif ins in ("ldc", "ldc_w", "ldc2_w"):
const = ins.operands[0]
if isinstance(const, ConstantClass):
stack.append("%s.class" % const.name.value)
elif isinstance(const, String):
stack.append(const.string.value)
else:
stack.append(const.value)
elif ins == "new":
const = ins.operands[0]
try:
stack.append(callback.on_new(ins, const))
except StopIteration:
break
elif ins in ("getfield", "getstatic"):
const = ins.operands[0]
if ins.mnemonic != "getstatic":
obj = stack.pop()
else:
obj = None
try:
stack.append(callback.on_get_field(ins, const, obj))
except StopIteration:
break
elif ins in ("putfield", "putstatic"):
const = ins.operands[0]
value = stack.pop()
if ins.mnemonic != "putstatic":
obj = stack.pop()
else:
obj = None
try:
callback.on_put_field(ins, const, obj, value)
except StopIteration:
break
elif ins in ("invokevirtual", "invokespecial", "invokeinterface", "invokestatic"):
const = ins.operands[0]
method_desc = const.name_and_type.descriptor.value
desc = method_descriptor(method_desc)
num_args = len(desc.args)
args = []
for i in six.moves.range(num_args):
args.insert(0, stack.pop())
if ins.mnemonic != "invokestatic":
obj = stack.pop()
else:
obj = None
try:
ret = callback.on_invoke(ins, const, obj, args)
except StopIteration:
break
if desc.returns.name != "void":
stack.append(ret)
elif ins in ("astore", "istore", "lstore", "fstore", "dstore"):
locals[ins.operands[0].value] = stack.pop()
elif ins in ("aload", "iload", "lload", "fload", "dload"):
stack.append(locals[ins.operands[0].value])
elif ins == "dup":
stack.append(stack[-1])
elif ins == "pop":
stack.pop()
elif ins == "anewarray":
stack.append([None] * stack.pop())
elif ins == "newarray":
stack.append([0] * stack.pop())
elif ins in ("aastore", "bastore", "castore", "sastore", "iastore", "lastore", "fastore", "dastore"):
value = stack.pop()
index = stack.pop()
array = stack.pop()
if isinstance(array, list) and isinstance(index, int):
array[index] = value
elif verbose:
print("Failed to execute %s: array %s index %s value %s" % (ins, array, index, value))
elif ins in ("aaload", "baload", "caload", "saload", "iaload", "laload", "faload", "daload"):
index = stack.pop()
array = stack.pop()
if isinstance(array, list) and isinstance(index, int):
stack.push(array[index])
elif verbose:
print("Failed to execute %s: array %s index %s" % (ins, array, index))
elif ins == "invokedynamic":
const = ins.operands[0]
method_desc = const.name_and_type.descriptor.value
desc = method_descriptor(method_desc)
num_args = len(desc.args)
args = []
for i in six.moves.range(num_args):
args.insert(0, stack.pop())
stack.append(callback.on_invokedynamic(ins, ins.operands[0], args))
elif ins == "checkcast":
pass
elif verbose:
print("Unknown instruction %s: stack is %s" % (ins, stack))
last_ins = ins_list[-1]
if last_ins.mnemonic in ("ireturn", "lreturn", "freturn", "dreturn", "areturn"):
# Non-void method returning
return stack.pop()
elif last_ins.mnemonic == "return":
# Void method returning
pass
elif verbose:
print("Unexpected final instruction %s: stack is %s" % (ins, stack))
def get_enum_constants(cf, verbose):
# Gets enum constants declared in the given class.
# Consider the following code:
"""
public enum TestEnum {
FOO(900),
BAR(42) {
@Override
public String toString() {
return "bar";
}
},
BAZ(Integer.getInteger("SomeSystemProperty"));
public static final TestEnum RECOMMENDED_VALUE = BAR;
private TestEnum(int i) {}
}
"""
# which compiles to:
"""
public final class TestEnum extends java.lang.Enum<TestEnum>
minor version: 0
major version: 52
flags: ACC_PUBLIC, ACC_FINAL, ACC_SUPER, ACC_ENUM
{
public static final TestEnum FOO;
descriptor: LTestEnum;
flags: ACC_PUBLIC, ACC_STATIC, ACC_FINAL, ACC_ENUM
public static final TestEnum BAR;
descriptor: LTestEnum;
flags: ACC_PUBLIC, ACC_STATIC, ACC_FINAL, ACC_ENUM
public static final TestEnum BAZ;
descriptor: LTestEnum;
flags: ACC_PUBLIC, ACC_STATIC, ACC_FINAL, ACC_ENUM
public static final TestEnum RECOMMENDED_VALUE;
descriptor: LTestEnum;
flags: ACC_PUBLIC, ACC_STATIC, ACC_FINAL
private static final TestEnum[] $VALUES;
descriptor: [LTestEnum;
flags: ACC_PRIVATE, ACC_STATIC, ACC_FINAL, ACC_SYNTHETIC
public static TestEnum[] values();
// ...
public static TestEnum valueOf(java.lang.String);
// ...
private TestEnum(int);
// ...
static {};
descriptor: ()V
flags: ACC_STATIC
Code:
stack=5, locals=0, args_size=0
// Initializing enum constants:
0: new #5 // class TestEnum
3: dup
4: ldc #8 // String FOO
6: iconst_0
7: sipush 900
10: invokespecial #1 // Method "<init>":(Ljava/lang/String;II)V
13: putstatic #9 // Field FOO:LTestEnum;
16: new #10 // class TestEnum$1
19: dup
20: ldc #11 // String BAR
22: iconst_1
23: bipush 42
25: invokespecial #12 // Method TestEnum$1."<init>":(Ljava/lang/String;II)V
28: putstatic #13 // Field BAR:LTestEnum;
31: new #5 // class TestEnum
34: dup
35: ldc #14 // String BAZ
37: iconst_2
38: ldc #15 // String SomeSystemProperty
40: invokestatic #16 // Method java/lang/Integer.getInteger:(Ljava/lang/String;)Ljava/lang/Integer;
43: invokevirtual #17 // Method java/lang/Integer.intValue:()I
46: invokespecial #1 // Method "<init>":(Ljava/lang/String;II)V
49: putstatic #18 // Field BAZ:LTestEnum;
// Setting up $VALUES
52: iconst_3
53: anewarray #5 // class TestEnum
56: dup
57: iconst_0
58: getstatic #9 // Field FOO:LTestEnum;
61: aastore
62: dup
63: iconst_1
64: getstatic #13 // Field BAR:LTestEnum;
67: aastore
68: dup
69: iconst_2
70: getstatic #18 // Field BAZ:LTestEnum;
73: aastore
74: putstatic #2 // Field $VALUES:[LTestEnum;
// Other user-specified stuff
77: getstatic #13 // Field BAR:LTestEnum;
80: putstatic #19 // Field RECOMMENDED_VALUE:LTestEnum;
83: return
}
"""
# We only care about the enum constants, not other random user stuff
# (such as RECOMMENDED_VALUE) or the $VALUES thing. Fortunately,
# ACC_ENUM helps us with this. It's worth noting that although MC's
# obfuscater gets rid of the field names, it does not get rid of the
# string constant for enum names (which is used by valueOf()), nor
# does it touch ACC_ENUM.
# For this method, we don't care about parameters other than the name.
if not cf.access_flags.acc_enum:
raise Exception(cf.this.name.value + " is not an enum!")
enum_fields = list(cf.fields.find(f=lambda field: field.access_flags.acc_enum))
enum_class = None
enum_name = None
result = {}
for ins in cf.methods.find_one(name="<clinit>").code.disassemble():
if ins == "new" and enum_class is None:
const = ins.operands[0]
enum_class = const.name.value
elif ins in ("ldc", "ldc_w") and enum_name is None:
const = ins.operands[0]
if isinstance(const, String):
enum_name = const.string.value
elif ins == "putstatic":
if enum_class is None or enum_name is None:
if verbose:
print("Ignoring putstatic for %s as enum_class or enum_name is unset" % str(ins))
continue
const = ins.operands[0]
assigned_field = const.name_and_type
if not any(field.name == assigned_field.name and field.descriptor == assigned_field.descriptor for field in enum_fields):
# This could happen with an enum constant that sets a field in
# its constructor, which is unlikely but happens with e.g. this:
"""
enum Foo {
FOO(i = 2);
static int i;
private Foo(int n) {}
}
"""
if verbose:
print("Ignoring putstatic for %s as it is to a field not in enum_fields (%s)" % (str(ins), enum_fields))
continue
result[enum_name] = {
'name': enum_name,
'field': assigned_field.name.value,
'class': enum_class
}
enum_class = None
enum_name = None
if len(result) == len(enum_fields):
break
if verbose and len(result) != len(enum_fields):
print("Did not find assignments to all enum fields - fields are %s and result is %s" % (result, enum_fields))
return result
|
14,777 | 6b59ebd63e104b19ff5624851a99bf554cf4e683 | DE_only = []
LogFC = []
with open('new_DEs_0.05.csv') as DE_tags:
for line in DE_tags:
line = line.split()
DE_only.append(line[0])
LogFC.append(line[1])
DE_logFC = {}
for z in range(0, len(DE_only)):
DE_logFC[DE_only[z]] = LogFC[z]
#there is 12 GO categories
complete = []
GO1 = []
with open('enriched_GO.csv') as enriched:
for line in enriched:
line = line.split('\t')
complete.append(line)
print(complete)
gene_id = []
logfc = []
GO1.append(complete[11])
GO1[0][11] = GO1[0][11].split('|')
for j in range(0, len(GO1[0][11])):
if GO1[0][11][j] in DE_logFC:
gene_id.append(GO1[0][11][j])
logfc.append(DE_logFC[GO1[0][11][j]])
with open('GO:0016787.csv', 'w') as output:
output.write(GO1[0][0]+'\t'+complete[11][1]+'\n')
output.write('gene_id'+'\t'+'LogFC'+'\n')
for k in range(0, len(gene_id)):
output.write(gene_id[k]+'\t'+logfc[k]+'\n')
|
14,778 | 9d2ea4e673c5f1b199e38d7d40eb6e475966e0dd | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 26 15:02:09 2017
@author: anand
"""
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 25 13:27:40 2017
@author: anand
"""
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 25 12:15:50 2017
@author: anand
"""
import numpy as np
import pandas as pd
from bokeh.plotting import figure, show
import collections
import os
from bokeh.io import curdoc
from bokeh.models import Select, DatetimeTickFormatter, ColumnDataSource, BoxSelectTool,LassoSelectTool
from bokeh.layouts import widgetbox, row, gridplot, layout
dir1 = os.path.dirname(__file__)
df = pd.read_csv(os.path.join(dir1,'url.csv'),sep=",")
df = df.fillna(0)
goals = df.columns.values.tolist()
#%%
goals_dict = {'Adventure Sports':[],'Florida':[],'Go Slutty':[],'Colour Hair':[],'Fountain Spa':[],'Road Trip':[]}
[goals_dict[key].append(df[key]) for key in goals_dict]
#%%
TOOLS="pan,wheel_zoom,reset,hover,box_select,lasso_select"
def create_source(g):
data_dict = {}
for i in xrange(len(goals_dict[g][0])):
data_dict['url'+'%s'%i] = [goals_dict[g][0][i]]
# =============================================================================
# if (goals_dict[g][0][i]!= 0):
# data_dict['url'+'%s'%i] = [goals_dict[g][0][i]]
# else:
# continue
# =============================================================================
data_dict = collections.OrderedDict(sorted(data_dict.items()))
return (ColumnDataSource(data_dict))
def create_plot(source):
img_set = []
dff = source.to_df()
for i in xrange(dff.shape[1]):
p = figure(tools=TOOLS,plot_height=400,plot_width=400,x_range=(0,10), y_range=(0,10))
p.image_url(url=dff.columns[i],x=5,y=5,w=10,h=10,anchor='center',source=source)
p.axis.visible=False
img_set.append(p)
return img_set
def function_to_call(attr, old, new):
goal = select.value
src = create_source(goal)
source.data.update(src.data)
print(goal)
#%%
goal = goals[0]
select = Select(options=goals, value=goal, title="Before 30")
source = create_source(goal)
select.on_change('value', function_to_call)
plot = create_plot(source)
#%%
final = []
count = 0
while (count<len(plot)):
temp = []
while(len(temp)<2):
temp.append(plot[count])
count += 1
if (count==len(plot)):
final.append(temp)
break
if (count==len(plot)):
break
final.append(temp)
#%%
grid = gridplot(final)
layout = layout([
[widgetbox(select)],
[grid]])
curdoc().add_root(layout)
# =============================================================================
# lt = row(grid,widgetbox(select))
# show(lt)
# =============================================================================
|
14,779 | eb68d244e256cf15c8a76f44a4ca6a038a6de7fe | # /usr/bin/env python
# -*- coding: UTF-8 -*-
import hashlib
import time
import random
import string
try:
from urllib import quote
except ImportError:
from urllib.parse import quote
import requests
import sys
#reload(sys)
#sys.setdefaultencoding("utf-8")
def get_params(plus_item):
'''请求时间戳(秒级),用于防止请求重放(保证签名5分钟有效)'''
t = time.time()
time_stamp=int(t)
'''请求随机字符串,用于保证签名不可预测'''
nonce_str = ''.join(random.sample(string.ascii_letters + string.digits, 10))
'''应用标志,这里修改成自己的id和key'''
app_id='2111368055'
app_key='FE4koFjlE1dwPvMg'
'''值使用URL编码,URL编码算法用大写字母'''
text1=plus_item
text=quote(text1.encode('utf8')).upper()
'''拼接应用密钥,得到字符串S'''
sign_before='app_id='+app_id+'&nonce_str='+nonce_str+'&text='+text+'&time_stamp='+str(time_stamp)+'&app_key='+app_key
'''计算MD5摘要,得到签名字符串'''
m=hashlib.md5()
m.update(sign_before.encode('UTF-8'))
sign=m.hexdigest()
sign=sign.upper()
params='app_id='+app_id+'&time_stamp='+str(time_stamp)+'&nonce_str='+nonce_str+'&sign='+sign+'&text='+text
return params
def get_content(plus_item):
url = "https://api.ai.qq.com/fcgi-bin/nlp/nlp_textpolar" # API地址
params = get_params(plus_item)#获取请求参数
url=url+'?'+params#请求地址拼接
# print(url)
try:
r = requests.post(url)
allcontents_json = r.json()
return allcontents_json["data"]["polar"],allcontents_json["data"]["confd"],allcontents_json["data"]["text"]
except Exception as e:
print ('a', str(e))
return 0,0,'0'
if __name__ == '__main__':
polar,confd,text=get_content('刚刚在肥城仪阳崇文路上,外卖小哥耳机线把喉割开了,意外无处不在啊,骑电车带耳机真的很危险[尴尬][尴尬][尴尬]')
print('情感倾向:'+ str(polar)+ '\n'+'程度:'+ str(confd)+'\n'+'文本:' + text) |
14,780 | 0f2181981d152ca283e3a843d6688cf2d6da950c | import asyncio
from typing import Dict
import pytest
from pydantic import BaseModel, StrictInt, conint
import hivemind
from hivemind.dht.node import DHTNode
from hivemind.dht.schema import BytesWithPublicKey, SchemaValidator
from hivemind.dht.validation import DHTRecord, RecordValidatorBase
from hivemind.utils.timed_storage import get_dht_time
class SampleSchema(BaseModel):
experiment_name: bytes
n_batches: Dict[bytes, conint(ge=0, strict=True)]
signed_data: Dict[BytesWithPublicKey, bytes]
@pytest.fixture
async def dht_nodes_with_schema():
validator = SchemaValidator(SampleSchema)
alice = await DHTNode.create(record_validator=validator)
bob = await DHTNode.create(record_validator=validator, initial_peers=await alice.get_visible_maddrs())
yield alice, bob
await asyncio.gather(alice.shutdown(), bob.shutdown())
@pytest.mark.forked
@pytest.mark.asyncio
async def test_expecting_regular_value(dht_nodes_with_schema):
alice, bob = dht_nodes_with_schema
# Regular value (bytes) expected
assert await bob.store("experiment_name", b"foo_bar", get_dht_time() + 10)
assert not await bob.store("experiment_name", 666, get_dht_time() + 10)
assert not await bob.store("experiment_name", b"foo_bar", get_dht_time() + 10, subkey=b"subkey")
# Refuse records despite https://pydantic-docs.helpmanual.io/usage/models/#data-conversion
assert not await bob.store("experiment_name", [], get_dht_time() + 10)
assert not await bob.store("experiment_name", [1, 2, 3], get_dht_time() + 10)
for peer in [alice, bob]:
assert (await peer.get("experiment_name", latest=True)).value == b"foo_bar"
@pytest.mark.forked
@pytest.mark.asyncio
async def test_expecting_dictionary(dht_nodes_with_schema):
alice, bob = dht_nodes_with_schema
# Dictionary (bytes -> non-negative int) expected
assert await bob.store("n_batches", 777, get_dht_time() + 10, subkey=b"uid1")
assert await bob.store("n_batches", 778, get_dht_time() + 10, subkey=b"uid2")
assert not await bob.store("n_batches", -666, get_dht_time() + 10, subkey=b"uid3")
assert not await bob.store("n_batches", 666, get_dht_time() + 10)
assert not await bob.store("n_batches", b"not_integer", get_dht_time() + 10, subkey=b"uid1")
assert not await bob.store("n_batches", 666, get_dht_time() + 10, subkey=666)
# Refuse storing a plain dictionary bypassing the DictionaryDHTValue convention
assert not await bob.store("n_batches", {b"uid3": 779}, get_dht_time() + 10)
# Refuse records despite https://pydantic-docs.helpmanual.io/usage/models/#data-conversion
assert not await bob.store("n_batches", 779.5, get_dht_time() + 10, subkey=b"uid3")
assert not await bob.store("n_batches", 779.0, get_dht_time() + 10, subkey=b"uid3")
assert not await bob.store("n_batches", [], get_dht_time() + 10)
assert not await bob.store("n_batches", [(b"uid3", 779)], get_dht_time() + 10)
# Refuse records despite https://github.com/samuelcolvin/pydantic/issues/1268
assert not await bob.store("n_batches", "", get_dht_time() + 10)
for peer in [alice, bob]:
dictionary = (await peer.get("n_batches", latest=True)).value
assert len(dictionary) == 2 and dictionary[b"uid1"].value == 777 and dictionary[b"uid2"].value == 778
@pytest.mark.forked
@pytest.mark.asyncio
async def test_expecting_public_keys(dht_nodes_with_schema):
alice, bob = dht_nodes_with_schema
# Subkeys expected to contain a public key
# (so hivemind.dht.crypto.RSASignatureValidator would require a signature)
assert await bob.store("signed_data", b"foo_bar", get_dht_time() + 10, subkey=b"uid[owner:public-key]")
assert not await bob.store("signed_data", b"foo_bar", get_dht_time() + 10, subkey=b"uid-without-public-key")
for peer in [alice, bob]:
dictionary = (await peer.get("signed_data", latest=True)).value
assert len(dictionary) == 1 and dictionary[b"uid[owner:public-key]"].value == b"foo_bar"
@pytest.mark.forked
@pytest.mark.asyncio
async def test_keys_outside_schema(dht_nodes_with_schema):
class Schema(BaseModel):
some_field: StrictInt
class MergedSchema(BaseModel):
another_field: StrictInt
for allow_extra_keys in [False, True]:
validator = SchemaValidator(Schema, allow_extra_keys=allow_extra_keys)
assert validator.merge_with(SchemaValidator(MergedSchema, allow_extra_keys=False))
alice = await DHTNode.create(record_validator=validator)
bob = await DHTNode.create(record_validator=validator, initial_peers=await alice.get_visible_maddrs())
store_ok = await bob.store("unknown_key", b"foo_bar", get_dht_time() + 10)
assert store_ok == allow_extra_keys
for peer in [alice, bob]:
result = await peer.get("unknown_key", latest=True)
if allow_extra_keys:
assert result.value == b"foo_bar"
else:
assert result is None
@pytest.mark.forked
@pytest.mark.asyncio
async def test_prefix():
class Schema(BaseModel):
field: StrictInt
validator = SchemaValidator(Schema, allow_extra_keys=False, prefix="prefix")
alice = await DHTNode.create(record_validator=validator)
bob = await DHTNode.create(record_validator=validator, initial_peers=await alice.get_visible_maddrs())
assert await bob.store("prefix_field", 777, get_dht_time() + 10)
assert not await bob.store("prefix_field", "string_value", get_dht_time() + 10)
assert not await bob.store("field", 777, get_dht_time() + 10)
for peer in [alice, bob]:
assert (await peer.get("prefix_field", latest=True)).value == 777
assert (await peer.get("field", latest=True)) is None
await asyncio.gather(alice.shutdown(), bob.shutdown())
@pytest.mark.forked
@pytest.mark.asyncio
async def test_merging_schema_validators(dht_nodes_with_schema):
alice, bob = dht_nodes_with_schema
class TrivialValidator(RecordValidatorBase):
def validate(self, record: DHTRecord) -> bool:
return True
second_validator = TrivialValidator()
# Can't merge with the validator of the different type
assert not alice.protocol.record_validator.merge_with(second_validator)
class SecondSchema(BaseModel):
some_field: StrictInt
another_field: str
class ThirdSchema(BaseModel):
another_field: StrictInt # Allow it to be a StrictInt as well
for schema in [SecondSchema, ThirdSchema]:
new_validator = SchemaValidator(schema, allow_extra_keys=False)
for peer in [alice, bob]:
assert peer.protocol.record_validator.merge_with(new_validator)
assert await bob.store("experiment_name", b"foo_bar", get_dht_time() + 10)
assert await bob.store("some_field", 777, get_dht_time() + 10)
assert not await bob.store("some_field", "string_value", get_dht_time() + 10)
assert await bob.store("another_field", 42, get_dht_time() + 10)
assert await bob.store("another_field", "string_value", get_dht_time() + 10)
# Unknown keys are allowed since the first schema is created with allow_extra_keys=True
assert await bob.store("unknown_key", 999, get_dht_time() + 10)
for peer in [alice, bob]:
assert (await peer.get("experiment_name", latest=True)).value == b"foo_bar"
assert (await peer.get("some_field", latest=True)).value == 777
assert (await peer.get("another_field", latest=True)).value == "string_value"
assert (await peer.get("unknown_key", latest=True)).value == 999
@pytest.mark.forked
def test_sending_validator_instance_between_processes():
alice = hivemind.DHT(start=True)
bob = hivemind.DHT(start=True, initial_peers=alice.get_visible_maddrs())
alice.add_validators([SchemaValidator(SampleSchema)])
bob.add_validators([SchemaValidator(SampleSchema)])
assert bob.store("experiment_name", b"foo_bar", get_dht_time() + 10)
assert not bob.store("experiment_name", 777, get_dht_time() + 10)
assert alice.get("experiment_name", latest=True).value == b"foo_bar"
alice.shutdown()
bob.shutdown()
|
14,781 | a0b58f9bc545221cf6e39361ec7d8845c4cc1674 | from time import sleep
from os import system
def SexoVerificacao(x): #! Função que verifica se o valor inserido para sexo é válido
if x not in 'MF':
while True:
if x in 'MF':
break
print('===Entre com um valor válido!===')
sleep(1)
x = str(input('Sexo[M/F]: ')).upper()
return x
def DesejaContinuar(v): #! Função que verifica se o valor de v é válido
v = str(input('Deseja continuar[S/N]? ')).upper()
while True:
if v in 'SN':
break
print(f'ERRO! ENTRE COM UM VALOR VÁLIDO')
sleep(1)
v = str(input('Deseja continuar[S/N]? ')).upper()
return v
def topo(msg): #! Mensagem do topo da tela
print('='*60)
print(f'{msg}'.center(60))
print('='*60)
print()
def menu(num): #!Função para a tela de menu
sleep(1)
system('cls')
topo('MENU PRINCIPAL')
print('[1] NOVO CADASTRO\n[2] EXIBIR TODOS OS CADASTROS\n[3] EXCLUIR UM CADASTRO\n[4] GERAR ARQUIVO COM TODOS OS CADASTROS\n[5] SAIR')
opt = str(input('\nESCOLHA UMA DAS OPÇÕES DO MENU... '))
while True:
if opt in '12345':
break
print('ERRO!!! Entre com um valor válido!')
sleep(1.5)
opt = str(input('\nESCOLHA UMA DAS OPÇÕES DO MENU... '))
ret = int(opt)
return ret
|
14,782 | db0469453899702cabc48adfbdeb2f2a7818f2aa | import time
import random
import math
people = [('Seymour','BOS'),
('Franny','DAL'),
('Zooey','CAK'),
('Walt','MIA'),
('Buddy','ORD'),
('Les','OMA')]
# Laguardia
destination='LGA'
flights={}
for line in file('schedule.txt'):
origin,dest,depart,arrive,price=line.strip().split(',')
flights.setdefault((origin,dest),[])
flights[(origin,dest)].append((depart, arrive, int(price)))
def getminutes(t):
x=time.strptime(t,'%H:%M')
return x[3]*60+x[4]
def printschedule(r):
for d in range(len(r)/2):
name=people[d][0]
origin=people[d][1]
out=flights[(origin,destination)][int(r[d])]
ret=flights[(destination,origin)][int(r[d+1])]
print '%10s%10s %5s-%5s $%3s %5s-%5s $%3s' % (name,origin,
out[0],out[1],out[2],
ret[0],ret[1],ret[2])
def schedulecost(sol):
totalprice = 0
lastestarrival = 0
earliestdep = 24*60
for d in range(len(sol)/2):
origin = people[d][1]
outbound = flights[(origin,destination)][int(sol[d])]
returnf = flights[(destination, origin)][int(sol[d+1])]
totalprice+=outbound[2]
totalprice+=returnf[2]
if lastestarrival < getminutes(outbound[1]) : lastestarrival=getminutes(outbound[1])
if earliestdep > getminutes(returnf[0]) : earliestdep = getminutes(returnf[0])
totalwait=0
for d in range(len(sol)/2):
origin=people[d][1]
outbound = flights[(origin,destination)][int(sol[d])]
returnf = flights[(destination, origin)][int(sol[d+1])]
totalwait+=lastestarrival-getminutes(outbound[1])
totalwait+=getminutes(returnf[0])-earliestdep
if lastestarrival>earliestdep: totalprice+=50
return totalprice+totalwait
def randomoptimize(domain,costf):
best=999999999
bestr=None
for i in range(10000):
r=[random.randint(domain[i][0],domain[i][1]) for i in range(len(
domain))]
cost=costf(r)
if cost<best:
best=cost
bestr=r
return r
def hillclimb(domain,costf):
sol=[random.randint(domain[i][0],domain[i][1]) for i in range(len(domain))]
while 1:
neighbors=[]
for j in range(len(domain)):
if sol[j]>domain[j][0]:
neighbors.append(object) |
14,783 | f61d2424698a9d8567716caaf5459bb2f4196b9a |
import functools
def flatten(r):
items = (flatten(i) if type(i) is list else [i] for i in r)
return functools.reduce(list.__add__, items)
|
14,784 | b19543de2ee286e8de3bdf71d4818407b08b73c1 | from sampleModule import royalty
def nuclearBomb():
return royalty()
|
14,785 | ccb0dc4f2ed4cfa71ad3d7440854076a1acd580c | import numpy as np
import matplotlib.pyplot as plt
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def BatchNormalization(x):
return x - np.mean(x) / np.std(x)
x = np.random.randn(1000,100)
node_num = 100
hidden_layer_size = 5
activations = {}
for i in range(hidden_layer_size):
if i != 0:
x = activations[i-1]
w = np.random.randn(node_num, node_num) / np.sqrt(node_num) #Xavier
a = np.dot(x,w)
b = BatchNormalization(a)
z = sigmoid(b)
activations[i] = z
for i, a in activations.items():
plt.subplot(1, len(activations), i+1)
plt.title(str(i+1) + '-layer')
plt.hist(a.flatten(),30,range=(0,1))
plt.show() |
14,786 | 5cff63671226882ca7cc52c398c999cee6ddbb93 | # Dictionaries
# Create
person = {
'first_name': 'John',
'last_name': 'Doe',
'age': 20
}
person2 = dict(first_name='Sara', last_name='Williams')
print(person, type(person))
print(person2)
# Get value
print(person['first_name'])
print(person.get('last_name'))
# Add
person['phone'] = '555-555-55'
print(person)
# Get keys
print(person.keys())
# Get items
print(person.items())
# Copy
person2 = person.copy()
person2['city'] = 'Boston'
print(person2)
# Remove
del(person['age'])
person.pop('phone')
# Clear
person.clear()
# Get length
print(len(person2))
print(person)
# List of dicts
people = [{'name': 'Martha', 'age': 30}, {'name': 'Kevin', 'age': 25}]
print(people)
print(people[0]['name'])
|
14,787 | e21c4fa1c820a1e67312f04d0c3f671adcbf2a2f | # -*- coding: utf-8 -*-
# C - Average Length
# https://atcoder.jp/contests/abc145/tasks/abc145_c
import itertools
N = int(input())
xy = [list(map(int, input().split())) for _ in range(N)]
p = []
cnt = 0
for v in itertools.permutations(xy, N):
p.append(v)
for i in range(len(p)):
for j in range(N-1):
cnt += ((p[i][j][0] - p[i][j+1][0])**2 + (p[i][j][1] - p[i][j+1][1])**2) ** 0.5
ans = cnt / len(p)
print(ans)
# 21:05 - 21:29(AC)
|
14,788 | 56b0c16e58b9297aea34aa7ba4ba216e275705ac | import logging
ROOT_LOGGER_NAME = 'mamba'
FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
FILE_LEVEL = logging.DEBUG
CONSOLE_LEVEL = logging.INFO
def init(log_filename="tmp.log", console=True, debug=False):
logging.root.name = ROOT_LOGGER_NAME
logging.root.setLevel(logging.DEBUG)
formatter = logging.Formatter(FORMAT)
# console
if console:
ch = logging.StreamHandler()
if debug:
ch.setLevel(FILE_LEVEL)
else:
ch.setLevel(CONSOLE_LEVEL)
ch.setFormatter(formatter)
logging.root.addHandler(ch)
# file
if (isinstance(log_filename, str) or isinstance(log_filename, unicode)) and len(log_filename) > 0:
fh = logging.FileHandler(log_filename, mode='w')
fh.setLevel(FILE_LEVEL)
fh.setFormatter(formatter)
logging.root.addHandler(fh)
logging.root.info("Logging to %s", log_filename)
def get_logger(name):
return logging.root.getChild(name)
if __name__ == '__main__':
init()
l = get_logger('test')
l.error("error!!!")
|
14,789 | 201e023a9c3d96824bd00cf6f651c0f1f6d020e6 | from invoke import task
@task
def tests(c):
c.run("py.test -vvx tests", pty=True)
|
14,790 | 863091c99200ad10d3c311e4b63a5c619ce9157d | import os
import cv2
import argparse
import numpy as np
import tensorflow as tf
import utils.config as cfg
from utils.model_yolo import YOLONet
from utils.timer import Timer
#检测的类Detector
class Detector(object):
def __init__(self, net, weight_file): # Yolo网络
'''
初始化参数和配置模型
'''
self.net = net # 网络
self.weights_file = weight_file # 模型参数文件
self.classes = cfg.CLASSES # PASCAL VOC数据集的20个类别
self.num_class = len(self.classes) # 20
self.image_size = cfg.IMAGE_SIZE # 448
self.cell_size = cfg.CELL_SIZE # 7
self.boxes_per_cell = cfg.BOXES_PER_CELL # 每一个cell预测的框 2
self.threshold = cfg.THRESHOLD # 0.2
self.iou_threshold = cfg.IOU_THRESHOLD # iou阈值 0.5
self.idx1 = self.cell_size * self.cell_size * self.num_class # 7*7*20
self.idx2 = self.idx1 + self.cell_size * self.cell_size * self.boxes_per_cell # 7*7*20 + 7*7*2
self.sess = tf.Session()
self.sess.run(tf.global_variables_initializer()) # 初始化tensorflow中全局变量
print('Restoring weights from: ' + self.weights_file)
self.saver = tf.train.Saver()
self.saver.restore(self.sess, self.weights_file) # 加载模型参数
def draw_result(self, img, result):
'''
根据result,向image上画框,result维度为[number, 6], 每组4个数的含义是(class, x_center, y_center, width, height, confidence)
'''
print("hell")
print(len(result))
for i in range(len(result)):
x = int(result[i][1])
y = int(result[i][2])
w = int(result[i][3] / 2)
h = int(result[i][4] / 2)
cv2.rectangle(img, (x - w, y - h), (x + w, y + h), (0, 255, 0), 2)
cv2.rectangle(img, (x - w, y - h - 20), (x + w, y - h), (125, 125, 125), -1)
lineType = cv2.LINE_AA if cv2.__version__ > '3' else cv2.CV_AA
cv2.putText(
img, result[i][0] + ' : %.2f' % result[i][5],
(x - w + 5, y - h - 7), cv2.FONT_HERSHEY_SIMPLEX, 0.5,
(0, 0, 0), 1, lineType)
def detect(self, img):
'''
处理图像,图像预处理、输入模型检测、
'''
################### 图像预处理 #####################
img_h, img_w, _ = img.shape
inputs = cv2.resize(img, (self.image_size, self.image_size))
inputs = cv2.cvtColor(inputs, cv2.COLOR_BGR2RGB).astype(np.float32)
inputs = (inputs / 255.0) * 2.0 - 1.0
inputs = np.reshape(inputs, (-1, self.image_size, self.image_size, 3)) #reshape,由于模型输入格式为:[batch_size, image_size, image_size, 3]
################### 图像检测 #######################
net_output = self.sess.run(self.net.logits, feed_dict={self.net.images: inputs}) #网络的输出
print("net_output:",net_output.shape) #其维度为[batch_size, 7*7*30]
results = []
for i in range(net_output.shape[0]):
results.append(self.interpret_output(net_output[i]))
result = results[0] # 由于batch_size=1, 所以取结果中的第一个元素
print(len(result))
print("输出result1:", result[0][1])
print("输出result2:", result[0][2])
print("输出result3:", result[0][3])
print("输出result4:", result[0][4])
for i in range(len(result)):
result[i][1] *= (1.0 * img_w / self.image_size) #x_center
result[i][2] *= (1.0 * img_h / self.image_size) #y_center
result[i][3] *= (1.0 * img_w / self.image_size) #width
result[i][4] *= (1.0 * img_h / self.image_size) #height
return result #返回框位置,已经是真实坐标了
def interpret_output(self, output):
'''
进行阈值筛选(筛选的是类别置信度)和进行非极大值抑制
'''
probs = np.zeros((self.cell_size, self.cell_size, self.boxes_per_cell, self.num_class))
#读取output中的预测结果
class_probs = np.reshape( output[0:self.idx1], (self.cell_size, self.cell_size, self.num_class))
scales = np.reshape(output[self.idx1:self.idx2], (self.cell_size, self.cell_size, self.boxes_per_cell))
boxes = np.reshape( output[self.idx2:], (self.cell_size, self.cell_size, self.boxes_per_cell, 4))
#因为网络预测出来的是偏移量,因此要恢复
offset = self.net.offset
boxes[:, :, :, 0] += offset
boxes[:, :, :, 1] += np.transpose(offset, (1, 0, 2))
boxes[:, :, :, :2] = 1.0 * boxes[:, :, :, :2] / self.cell_size # 得到(x_center, y_cwenter)相对于每一张图片的位置比例
boxes[:, :, :, 2:] = np.square(boxes[:, :, :, 2:]) # 得到预测的宽度和高度乘以平方才能得到相对于整张图片的比例
boxes *= self.image_size # 得到相对于原图的坐标框
#计算类别置信度, probs维度为[7, 7, 2, 20]
for i in range(self.boxes_per_cell):
for j in range(self.num_class):
probs[:, :, i, j] = np.multiply(class_probs[:, :, j], scales[:, :, i])
filter_mat_probs = np.array(probs >= self.threshold, dtype='bool') # 如果大于self.threshold,那么其对应的位置为true, 否则为false
filter_mat_boxes = np.nonzero(filter_mat_probs) # 找到为true的地方,false是0
boxes_filtered = boxes[filter_mat_boxes[0],
filter_mat_boxes[1], filter_mat_boxes[2]] # 找到框的位置
probs_filtered = probs[filter_mat_probs] # 找到符合的类别置信度
#若该cell类别置信度大于阈值,则只取类别置信度最大的那个框,一个cell只负责预测一个类别
classes_num_filtered = np.argmax( filter_mat_probs, axis=3)[filter_mat_boxes[0], filter_mat_boxes[1], filter_mat_boxes[2]]
argsort = np.array(np.argsort(probs_filtered))[::-1] #类别置信度排序,降序排列
boxes_filtered = boxes_filtered[argsort] #找到符合条件的框,从大到小排序
probs_filtered = probs_filtered[argsort] #找到符合条件的类别置信度,从大到小排序
classes_num_filtered = classes_num_filtered[argsort] #类别数过滤
#非极大值抑制算法, iou_threshold=0.5
for i in range(len(boxes_filtered)):
if probs_filtered[i] == 0:
continue
for j in range(i + 1, len(boxes_filtered)):
if self.iou(boxes_filtered[i], boxes_filtered[j]) > self.iou_threshold:
probs_filtered[j] = 0.0
filter_iou = np.array(probs_filtered > 0.0, dtype='bool')
boxes_filtered = boxes_filtered[filter_iou] #经过阈值和非极大值抑制之后得到的框
probs_filtered = probs_filtered[filter_iou] #经过阈值和非极大值抑制之后得到的类别置信度
classes_num_filtered = classes_num_filtered[filter_iou] #经过非极大值抑制之后得到的类别,一个cell只负责预测一个类别
result = [] #保存的为(classname, x_center, y_center, width, height, confidence)
for i in range(len(boxes_filtered)):
result.append(
[self.classes[classes_num_filtered[i]],
boxes_filtered[i][0],
boxes_filtered[i][1],
boxes_filtered[i][2],
boxes_filtered[i][3],
probs_filtered[i]])
return result
def iou(self, box1, box2):
'''
计算交叠率,该方法实际上与yoloNet中的一致,也可省去
'''
tb = min(box1[0] + 0.5 * box1[2], box2[0] + 0.5 * box2[2]) - \
max(box1[0] - 0.5 * box1[2], box2[0] - 0.5 * box2[2])
lr = min(box1[1] + 0.5 * box1[3], box2[1] + 0.5 * box2[3]) - \
max(box1[1] - 0.5 * box1[3], box2[1] - 0.5 * box2[3])
inter = 0 if tb < 0 or lr < 0 else tb * lr
return inter / (box1[2] * box1[3] + box2[2] * box2[3] - inter)
def image_detector(self, imname, wait=0):
'''
图像检测,是该类的外部接口
'''
detect_timer = Timer()
image = cv2.imread(imname)
detect_timer.tic() #记录检测开始的时间
result = self.detect(image) #检测
detect_timer.toc() #结束检测开始的时间
print('Average detecting time: {:.3f}s'.format(
detect_timer.average_time))
self.draw_result(image, result)
cv2.imwrite('image1.jpg',image)
#cv2.imshow('Image', image)
#cv2.waitKey(wait)
#Detector的main函数
def main():
parser = argparse.ArgumentParser() #参数解析
parser.add_argument('--weights', default="yolo.ckpt-6500", type=str)
parser.add_argument('--weight_dir', default='weights', type=str)
parser.add_argument('--data_dir', default="dataSet", type=str)
parser.add_argument('--gpu', default='2', type=str)
args = parser.parse_args()
os.environ['CUDA_VISIBLE_DEVICES'] = args.gpu
yolo = YOLONet(False) #定义网络的框架
weight_file = os.path.join(args.data_dir, args.weight_dir, args.weights) #模型文件路径
detector = Detector(yolo, weight_file) #初始化Detector类
# detect from image file
imname = 'testImg/cat.jpg' #测试文件
detector.image_detector(imname)
#main函数
if __name__ == '__main__':
main() #调用main函数
|
14,791 | a1a4550942ab233486742e972ef1e32785b90f34 | import konlpy
from collections import Counter
# 저는 이미 khaiii로 형태소 분석이 끝났기 때문에 불필요 할 것 같습니다.
# 대신에 collections 의 counter 함수를 이용해서 빈도수만 채크
# def get_key(text, ntags=30):
nouns = open("C:/Users/student/Documents/jinahan/형태소분석/코모란/komoran.txt")
#경로에 있는 파일을 저장.
count =Counter(nouns)
# 참고: https://excelsior-cjh.tistory.com/94
return_list=[]
for n,c in count.most_common(20):
temp = {'tag':n,'count':c}
return_list.append(temp)
print(return_list)
# text_file="C:/Users/student/Documents/jinahan/통계분석/sample_file/words.txt"
# #형태소 분석이 끝난 파일
# noun_count = 20
# #빈도수 20개의 명사
# output_file = "C:/Users/student/Documents/jinahan/통계분석/sample_file/count.txt"
# #빈도수 측정
# open_text = open(text_file,'r',-1,"utf-8")
# #파일을 가지고옴.
# text = open_text.read()
# #파일을 읽어들임
# keys = get_key(text, ntags=30)
# open_ouput_file =open(output_file)
# for key in range(keys):
# noun = key['key']
# count = key['count']
# open_ouput_file.write('{} {}\n'.format(noun,count))
# # 결과 저장 , 참고: .forat https://programmers.co.kr/learn/courses/2/lessons/63
# open_ouput_file.close() |
14,792 | d75c7f153dc93a3266af4005eb7215ad719fc6f5 | from django.contrib.auth.models import User
from rest_framework import serializers
from .models import Item, Profile
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
class UserCreateSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
class Meta:
model = User
fields = ['username', 'password', 'first_name', 'last_name', 'email']
def create(self, validated_data):
username = validated_data['username']
password = validated_data['password']
first_name = validated_data['first_name']
last_name = validated_data['last_name']
email = validated_data['email']
new_user = User(username=username, first_name=first_name, last_name=last_name, email=email)
new_user.set_password(password)
new_user.save()
return validated_data
class ItemSerializer(serializers.ModelSerializer):
class Meta:
model = Item
fields = "__all__"
class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
@classmethod
def get_token(cls, user):
token = super().get_token(user)
token['username'] = user.username
return token
class UserSerializer(serializers.ModelSerializer):
items = ItemSerializer(many=True)
class Meta:
model = User
fields = ["id", "username", "items", "first_name", "last_name"]
class ProfileSerializer(serializers.ModelSerializer):
user = UserSerializer()
class Meta:
model = Profile
fields = ['unique_id', 'user'] |
14,793 | 7adfc3e1fff7483e3ebe955fdcacf4c61087f7f6 | # -*- coding: utf-8 -*-
"""
Created on Mon Feb 20 10:15:37 2017
@author: andy
"""
from cyvlfeat import kmeans
import os
import pickle
from numpy import random
import numpy as np
from preprocess_hog_pkl import hog_preprocess
from cyvlfeat.kmeans import kmeans
def get_hog_dictionary(data_path,num_cluster = 1024, data_per_class=5):
assert data_path.split("/")[-2] == 'hog'
data_points = sample(data_path,data_per_class)
centroids = kmeans(data_points,num_cluster,algorithm="ANN",max_num_comparisons=256,verbose=True)
return centroids
def sample(data_path,data_per_class = 5):
#random.seed(1)
subdirs = [x[0] for x in os.walk(data_path,True)]
subdirs.pop(0)
data_points = []
for subdir in subdirs:
imgs = [x[2] for x in os.walk(subdir,True)][0]
num_files = len(imgs)
idx = np.arange(0,num_files)
random.shuffle(idx)
idx = idx[:data_per_class]
for i in idx:
img = imgs[i]
data_point = pickle.load(open(subdir+'/'+img,'rb'))
data_point = hog_preprocess(data_point,need_normalize=True, need_return_shape = False)
data_points.append(data_point)
data_points= np.hstack(data_points)
data_points = data_points.T
data_points = data_points[~np.all(data_points == 0, axis=1)]
return data_points
|
14,794 | 907165ba0fe39c45b4fc1d3be0c2f88a86238279 | import torch
from torch import nn
class WeightSynthesizer(nn.Module):
def __init__(self, num_dims_in, num_dims_out, d=25):
super(WeightSynthesizer, self).__init__()
self.fc1 = nn.Sequential(
nn.Linear(num_dims_in, d),
nn.ReLU()
)
self.fc2 = nn.Sequential(
nn.Linear(d, d*2),
nn.ReLU()
)
self.fc3 = nn.Sequential(
nn.Linear(d*2, d*4),
nn.ReLU()
)
self.fc4 = nn.Sequential(
nn.Linear(d*4, num_dims_out),
nn.Sigmoid()
)
def forward(self, x):
out = self.fc1(x)
out = self.fc2(out)
out = self.fc3(out)
out = self.fc4(out)
return out
|
14,795 | 15852da39205ea53635499015e1c351f693f7e97 | a, b = map(int, input().split())
answer = min(((a - a // 2) - a // 2) * b, ((b - b // 2) - b // 2) * a)
print(answer) |
14,796 | 3a51ccf51daeed9d42b0127c29b90e277724af85 | import mpyq
from heroprotocol import protocol29406
class HeroParser():
def __init__(self, replay_path):
self.replay_path = replay_path
self.archive = mpyq.MPQArchive(replay_path)
# Read the protocol header, this can be read with any protocol
self.contents = self.archive.header['user_data_header']['content']
# header = heroprotocol.protocol29406.decode_replay_header(contents)
self.header = protocol29406.decode_replay_header(self.contents)
# The header's baseBuild determines which protocol to use
self.baseBuild = self.header['m_version']['m_baseBuild']
module = 'heroprotocol.protocol%s' % self.baseBuild
try:
self.protocol = __import__(module, fromlist=['heroprotocol'])
except ImportError as e:
raise TypeError('Unsupported base build: %d' % baseBuild)
def get_protocol_header(self):
"""
Returns a dictionary:
m_useScaledTime = false
m_version
m_baseBuild = 36144
m_minor = 12
m_revision = 0
m_flags = 1
m_major = 0
m_build = 36359
m_type = 2
m_signature = 'Heroes of the Storm replay\x1b11'
m_ngdpRootKey = {}
m_elapsedGameLoops = 19556
m_dataBuildNum = 36359
"""
return self.header
def get_protocol_details(self):
"""
Returns a dictionary:
m_imageFilePath = ''
m_description = ''
m_timeLocalOffset = -252000000000L
m_thumbnail
m_file = 'ReplaysPreviewImage.tga'
m_defaultDifficulty = 7
m_restartAsTransitionMap = False
m_title = 'Tomb of the Spider Queen'
m_campaignIndex = 0
m_modPaths = None
m_cacheHandles = list of hex values
m_timeUTC = 130812119943125997L
m_isBlizzardMap = True
m_mapFileName = ''
m_gameSpeed = 4
m_playerList = complex dict
m_miniSave = False
m_difficulty = ''
"""
contents = self.archive.read_file('replay.details')
return self.protocol.decode_replay_details(contents)
def get_protocol_init_data(self):
"""
Returns dict of 3 complicated dicts
m_syncLobbyState
m_userInitialData = list
m_testAuto = False
m_mount = ''
m_observe = 0
m_teamPreference
m_team = None
m_toonHandle = ''
m_customInterface = False
m_highestLeague = 0
m_clanTag = ''
m_testMap = False
m_clanLogo = None
m_examine = False
m_testType = 0
m_combinedRaceLevels = 0
m_randomSeed = 0
m_racePreference
m_race = None
m_skin = ''
m_hero = ''
m_name = 'BIOCiiDE'
m_lobbyState
m_maxUsers = 10
m_slots = list
m_mount = 'HorseAlmond'
m_rewards = list of longs
m_handicap = 100
m_aiBuild = 0
m_teamId = 0
m_observe = 0
m_control = 2
m_tandemLeaderUserId = None
m_commanderLevel = 0
m_toonHandle = '1-Hero-1-1715249'
m_logoIndex = 0
m_artifacts = list of empty strings
m_commander = ''
m_racePref
m_race = None
m_colorPref
m_color = 3
m_licenses = empty list
m_userId = 0
m_workingSetSlodId = 0
m_skin = ''
m_hero = 'Muradin'
m_difficulty = 7
m_defaultDifficulty = 7
m_isSinglePlayer = False
m_phase = 0
m_hostUserId = None
m_maxObservers = 6
m_defaultAIBuild = 0
m_pickedMapTag = 0
m_randomSeed = 458461899
m_gameDuration = 0
m_gameDescription
m_maxRaces = 3
m_maxTeams = 10
m_hasExtensionMod = False
m_maxColors = 16
m_isBlizzardMap = True
m_gameOptions
m_competitive = True
m_practice = False
m_ranked = True
m_lockTeams = True
m_amm = True
m_battleNet = True
m_fog = 0
m_noVictoryOrDefeat = False
m_heroDuplicatesAllowed = True
m_advanceSharedControl = False
m_cooperative = False
m_clientDebugFlags = 33
m_observers = 0
m_teamsTogether = False
m_randomRaces = False
m_userDifficulty = 0
m_defaultDifficulty = 7
m_isCoopMode = False
m_mapFileName = ''
m_defaultAIBuild = 0
m_gameType = 0
m_randomValue = 458461899
m_maxObservers = 6
m_maxUsers = 10
m_modFileSyncChecksum = 3487869853L
m_mapSizeX = 248
m_maxPlayers = 10
m_cacheHandles = list of hex codes
m_gamespeed = 4
m_maxControls = 1
m_gameCacheName = 'Dflt'
m_mapAuthorName = '1-Hero-1-26'
m_isPremadeFFA = False
m_mapSizeY = 216
m_mapFileSyncChecksum = 408550135L
m_slotDescriptions = list
m_allowedRaces = (3, 4)
m_allowedColors = (16, 1024)
m_allowedAIBUilds = (96, 0)
m_allowedDifficulty = (32, 3456106496L)
m_allowedObserveTypes = (3, 7)
m_allowedControls = (255, huge long number)
"""
contents = self.archive.read_file('replay.initData')
return self.protocol.decode_replay_initdata(contents)
def get_game_events(self):
"""
Returns a list of dictionaries containing most game data
"""
contents = self.archive.read_file('replay.game.events')
return self.protocol.decode_replay_game_events(contents)
def get_messages(self):
"""
Returns generator of dicts
_eventid = 2
_event = 'NNet.Game.SLoadingProgressMessage'
_bits = 56
m_progress = 28L
_gameloop = 0
_userid
m_userid = 4
m_recipient = 1
_eventid = 1
_event = 'NNet.Game.SpingMessage'
_gameloop = 8556
_bits = 96
_userid
m_userid = 9
m_point
y = 469480L
x = 494367L
"""
contents = self.archive.read_file('replay.message.events')
return self.protocol.decode_replay_message_events(contents)
def get_trackers(self):
"""
Returns list of dicts
m_unitTagIndex = 64
m_unitTagRecycle = 1
_eventid = 1
m_controlPlayerId = 0
_event = 'NNet.Replay.Tracker.SUnitBornEvent'
_gameLoop = 0
m_y = 53
m_x = 140
_bits = 384
m_upkeepPlayerId = 12
m_unitTypeName = 'TownWallRadial17L2'
"""
contents = self.archive.read_file('replay.tracker.events')
return self.protocol.decode_replay_tracker_events(contents)
def get_attributes(self):
"""
Returns source, mapNamespace, scopes
source is 0
mapNamespace is 999
scopes is a complicated dictionary
"""
contents = self.archive.read_file('replay.attributes.events')
return self.protocol.decode_replay_attributes_events(contents)
|
14,797 | 2b3c329cdf36b48528e4bfd68256f481622305a4 | #!/usr/bin/env python
########################################
# Mario Rosasco, 2017
########################################
from Model import *
from Visualization import *
from scipy.optimize import minimize
from allensdk.ephys.ephys_features import detect_putative_spikes
import numpy as np
import sys
def main(modelID):
print "Loading parameters for model", modelID
selection=raw_input('Would you like to download NWB data for model? [Y/N] ')
if selection[0] == 'y' or selection[0] == 'Y':
currModel = Model(modelID, cache_stim = True)
if selection[0] == 'n' or selection[0] == 'N':
currModel = Model(modelID, cache_stim = False)
currModel.init_model()
while(True):
print "Initialized biophysical model", modelID
print '''
Please select from the following options:
1 - Run test pulse on model
2 - Fit model parameter to data
3 - Display static neuron model
4 - Visualize model dynamics
5 - Quit
'''
try:
selection=int(raw_input('Please choose an option above: '))
except ValueError:
print "Invalid selection."
continue
# test pulse example
if selection == 1:
# Run the model with a test pulse of the 'long square' type
print "Running model with a long square current injection pulse of 210pA"
output = currModel.long_square(0.21)
currModel.plot_output()
# fit parameter example
elif selection == 2:
if not currModel.bp.cache_stimulus:
print "Current model was not instantiated with NWB data cached. Please reload the current model and cache experimental stimulus data."
continue
print "Fitting somatic sodium conductance for model", modelID, "to experimental data in sweep 41."
print "Please be patient, this may take some time."
# Define which section and which parameter to fit.
# Here we'll fit the somatic sodium conductance.
currModel.set_fit_section('soma', 0)
currModel.set_parameter_to_fit('gbar_NaV')
# Running the model with an NWB pulse as stimulus takes a
# very long time because of the high sampling rate.
# As a computationally-cheaper approximation for stimuli of
# type Long Square pulse, we can rebuild the stimulus with the
# default (lower) sampling rate in h.IClamp
# currModel.run_nwb_pulse(41) # too slow
output = currModel.long_square(0.21)
# Set the experimental reference sweep and set up the variables for the objective function
currModel.set_reference_sweep(ref_index=41)
currModel.set_up_objective(measure='spike frequency')
# Use SciPy's minimize functions to fit the specified parameter
#results = minimize(currModel.objective_function, currModel.theta, method='Nelder-Mead', tol=1e-3)
#results = minimize(currModel.objective_function, currModel.theta, method='Powell', tol=1e-3)
#results = minimize(currModel.objective_function, currModel.theta, method='COBYLA', tol=1e-5)
currModel.gradient_descent(alpha=0.00005, epsilon=0.001, threshold=0.01, max_cycles=1000)
currModel.plot_fit()
output = currModel.long_square(0.21)
currModel.plot_output()
times = np.array(output['t'])/1000
spikes = detect_putative_spikes(np.array(output['v']), times, 0.1, 1.1)
avg_rate = currModel.average_rate_from_delays(times, spikes, 0.1, 1.1)
print "spike rate for theta of", currModel.theta, ":", avg_rate
# static visualization example
elif selection == 3:
run_visualization(currModel)
elif selection == 4:
run_visualization(currModel, show_simulation_dynamics = True)
elif selection == 5:
quit()
else:
print "Invalid selection."
continue
def run_visualization(currModel, show_simulation_dynamics = False):
print "Setting up visualization..."
morphology = currModel.get_reconstruction()
# Prepare model coordinates for uploading to OpenGL.
tempIndices = []
tempVertices = []
n_index = 0
tempX = []
tempY = []
tempZ = []
tempCol = []
if not show_simulation_dynamics:
print '''
Soma - Red
Axon - Green
Dendrites - Blue
Apical Dendrites - Purple'''
# array of colors to denote individual compartment types
compartmentColors=[[0.0,0.0,0.0,0.0], # padding for index convenience
[1.0, 0.0, 0.0, 1.0], #1: soma - red
[0.0, 1.0, 0.0, 1.0], #2: axon - green
[0.0, 0.0, 1.0, 1.0], #3: dendrites - blue
[1.0, 0.0, 1.0, 1.0]] #4: apical dendrites - purple
color_dim = 4
# used to set up section monitoring for visualization of dynamics
compartmentNames=['none', # padding for index convenience
'soma', #1: soma
'axon', #2: axon
'dend', #3: dendrites - blue
'dend'] #4: apical dendrites - purple
sectionIndices=[0,0,0,0,0]
segmentsPerSection = {}
sec_name = ''
# initialize storage arrays for each vertex.
index = 0
n_compartments = len(morphology.compartment_list)
tempX = [0] * n_compartments
tempY = [0] * n_compartments
tempZ = [0] * n_compartments
tempCol = [0] * n_compartments * color_dim
for n in morphology.compartment_list:
# add parent coords
tempX[n['id']] = n['x']
tempY[n['id']] = -n['y']
tempZ[n['id']] = n['z']
# add color data for parent
col_i = 0
offset = n['id']*color_dim
for cval in compartmentColors[n['type']]:
tempCol[offset+col_i] = cval
col_i += 1
# if at a branch point or an end of a section, set up a vector to monitor that segment's voltage
type = compartmentNames[n['type']]
sec_index = sectionIndices[n['type']]
if not (len(morphology.children_of(n)) == 1): #either branch pt or end
sec_name = type + '[' + str(sec_index) + ']'
sectionIndices[n['type']] += 1
currModel.monitor_section_voltage(type, sec_index)
segmentsPerSection[sec_name] = 1
else:
segmentsPerSection[sec_name] += 1
index += 1
for c in morphology.children_of(n):
# add child coods
tempX[c['id']] = c['x']
tempY[c['id']] = -c['y']
tempZ[c['id']] = c['z']
# add index data:
# draw from parent to child, for each child
tempIndices.append(n['id'])
tempIndices.append(c['id'])
index += 1
# add color data for child
col_i = 0
offset = c['id']*color_dim
for cval in compartmentColors[c['type']]:
tempCol[offset+col_i] = cval
col_i += 1
segmentsPerSection[sec_name] += 1
# get ranges for scaling
maxX = max(tempX)
maxY = max(tempY)
maxZ = max(tempZ)
minX = min(tempX)
minY = min(tempY)
minZ = min(tempZ)
xHalfRange = (maxX - minX)/2.0
yHalfRange = (maxY - minY)/2.0
zHalfRange = (maxZ - minZ)/2.0
longestDimLen = max(xHalfRange, yHalfRange, zHalfRange)
# center coords about 0,0,0, with range -1 to 1
tempX = [((((x-minX)*(2*xHalfRange))/(2*xHalfRange)) - xHalfRange)/longestDimLen for x in tempX]
tempY = [((((y-minY)*(2*yHalfRange))/(2*yHalfRange)) - yHalfRange)/longestDimLen for y in tempY]
tempZ = [((((z-minZ)*(2*zHalfRange))/(2*zHalfRange)) - zHalfRange)/longestDimLen for z in tempZ]
# convert everything to a numpy array so OpenGL can use it
indexData = np.array(tempIndices, dtype='uint16')
vertexData = np.array([tempX,tempY,tempZ], dtype='float32')
tempCol = np.array(tempCol, dtype='float32')
vertexData = np.append(vertexData.transpose().flatten(), tempCol)
#################### /Preparing Model Coords
# Set up the Visualization instance
n_vertices = len(tempX)
currVis = Visualization(data=vertexData, indices=indexData, nVert=n_vertices, colorDim=color_dim)
if show_simulation_dynamics:
currModel.run_test_pulse(amp=0.25, delay=20.0, dur=20.0, tstop=60.0)
#currModel.plot_output() # uncomment this line to display the somatic potential over time before the visualization begins
sectionOutput = currModel.section_output
n_segments = n_vertices
# set up looping color change data
all_voltages = []
n_pts = len(sectionOutput['t'])
for t in range(n_pts): # for each timepoint...
for key in sectionOutput.keys(): # for each section...
if key != 't':
for s in range(segmentsPerSection[key]): # for each segment...
all_voltages.append(sectionOutput[key][t]) # ...set up color for segment
all_voltages = np.array(all_voltages, dtype='float32')
all_voltages -= min(all_voltages)
all_voltages /= max(all_voltages)
temp_col = []
n_pts = 0
for v in all_voltages:
temp_col.append(v)
temp_col.append(0.0)
temp_col.append(1.0-v)
temp_col.append(1.0)
n_pts += 1
voltage_col = np.array(temp_col, dtype='float32')
currVis.change_color_loop(voltage_col, n_colors=n_segments, n_timepoints=n_pts, offset=0, rate=0.10)
currVis.run()
if __name__ == '__main__':
if len(sys.argv) == 1: # no model ID passed as argument
modelID = 497233230
else:
try:
modelID=int(sys.argv[1])
except ValueError:
print "Could not interpret model ID. Initializing with example model 497233230"
modelID = 497233230
main(modelID) |
14,798 | 3cc24c98c6c79f35416edee9db58a09198725a02 | import enum
class ItemType(enum.Enum):
BOOK=1
BAG=2
SHOES=3
CLOTHES=4
class ExpenditureType(enum.Enum):
FEES=1
BUYING=2
class DonationPlan(enum.Enum):
ANUALLY=1
SEMI_ANUALLY =2 |
14,799 | 36c8b70376726b47ba2630cdc3c6b35777ed54ec | '''
@author: Dean D'souza
'''
# Loading necessary Libraries
from __future__ import division
import nltk
from nltk.text import Text
from ProjectTokenizer import pToken
from ProjectTagger import pTagger
from nltk.corpus import stopwords
# Loading all text data
txtFile=open('C:/Users/demon/OneDrive/Documents/GitHub/CISC_520-50_FA2016/Project/data/AllText.txt','r')
tempTxt = txtFile.read()
txtFile.close()
# Tokenizing the text
pTok1 = pToken(tempTxt)
# Basic Statistics of the text without removing stopwords
#print("Number of Words : "+str(len(pTok1)))
#print("Number of Unique Words : "+str(len(set(pTok1))))
#print("Lexical Diversity : "+str(len(pTok1)/len(set(pTok1))))
# Basic Statistics after removing stopwords
#pTok2 = [w.lower() for w in pTok1 if w not in stopwords.words('english')]
#print("Number of Words : "+str(len(pTok2)))
#print("Number of Unique Words : "+str(len(set(pTok2))))
#print("Lexical Diversity : "+str(len(pTok2)/len(set(pTok2))))
# Converting to nltk.text.Text form to easily create Frequency Distribution
nText = Text(pTok1)
fdistv = nltk.FreqDist(nText)
vocab = fdistv.keys()
# List of top most tokens
#print(vocab[:50])
# Cummulative Frequency Plot of the top most tokens
#fdistv.plot(50)
#fdistv.plot(50,cumulative=True)
# Collocations (a.k.a. Words occurring together with a frequency considered greater than chance)
#print(nText.collocations())
# Tagging the tokens with Part-of-Speech tag
taggedTok = pTagger(vocab)
tags = []
for tag in taggedTok:
for t2 in tag:
if isinstance(t2, tuple):
tags.append(t2[1])
elif t2 in ['link','punct','UserID','htag','email','emoji','num']:
tags.append(t2)
# Frequency Distribution of tags
fdisttag=nltk.FreqDist(tags)
#fdisttag.tabulate()
# Frequency Distribution Plot of tags
fdisttag.plot(50)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.