content stringlengths 1 1.04M | input_ids listlengths 1 774k | ratio_char_token float64 0.38 22.9 | token_count int64 1 774k |
|---|---|---|---|
import plotly.express as px
from dash import Dash, dcc, html, Input, Output, State, no_update
from pyproj import Transformer
import dash_bootstrap_components as dbc
import pandas as pd
import altair as alt
import os
alt.data_transformers.disable_max_rows()
# ---------------------------------------------------------------------------------------------------#
crime = pd.read_csv("data/processed/crime_clean.csv")
# ---------------------------------------------------------------------------------------------------#
# Dropdown lists for Neighbourhood and crime types
neighbourhood_l = (
crime.loc[crime["NEIGHBOURHOOD"].notna(), "NEIGHBOURHOOD"].unique().tolist()
)
comp = crime.loc[crime["TYPE"].notna(), "TYPE"].unique().tolist()
week_l = crime.loc[crime["day_of_week"].notna(), "day_of_week"].unique().tolist()
# ---------------------------------------------------------------------------------------------------#
# front-end functions
# map-chart
# Pivot table for map-chart plotting
crime_plot = crime.pivot(columns="TYPE", values="LONG")
crime_map = pd.concat((crime, crime_plot), axis=1)
def plot(crime_type, neighbourhood, month_name):
"""
Function that makes the map chart on crime density on the landing page of the dashboard
Parameters:
----------
crime_type: str
types of crime reported in Vancouver
neighbourhood: str
different neighbourhoods in Vancouver
month_name: str
Abbreviated month names from Jan - Dec
Returns:
----------
fig
the html map plot
"""
if month_name == "All":
fig = px.scatter_mapbox(
crime_map.loc[crime_map["NEIGHBOURHOOD"] == neighbourhood],
lat="LAT",
lon=crime_type,
color="TYPE",
title=f"<b>{crime_type} Crime Density in {neighbourhood}<b>",
color_continuous_scale="RdYlGn_r",
center={"lat": 49.246292, "lon": -123.116226},
zoom=11,
mapbox_style="carto-darkmatter",
hover_name="NEIGHBOURHOOD",
)
fig.update_layout(
margin=dict(l=0, r=0, t=30, b=10),
title_font_size=20,
title_xanchor="center",
title_x=0.5,
title_y=0.98,
title_yanchor="top",
title_font_family="Sans-Serif",
title_font_color="white",
plot_bgcolor="#010915",
paper_bgcolor="#010915",
showlegend=False,
)
else:
fig = px.scatter_mapbox(
crime_map.loc[
(crime_map["NEIGHBOURHOOD"] == neighbourhood)
& (crime_map["month_name"] == month_name)
],
lat="LAT",
lon=crime_type,
color="TYPE",
title=f"<b>{crime_type} Crime Density in {neighbourhood}<b>",
color_continuous_scale="RdYlGn_r",
center={"lat": 49.246292, "lon": -123.116226},
zoom=11,
mapbox_style="carto-darkmatter",
hover_name="NEIGHBOURHOOD",
)
fig.update_layout(
margin=dict(l=0, r=0, t=30, b=10),
title_font_size=20,
title_xanchor="center",
title_x=0.5,
title_y=0.97,
title_yanchor="top",
title_font_family="Sans-Serif",
title_font_color="white",
plot_bgcolor="#010915",
paper_bgcolor="#010915",
showlegend=False,
)
return fig.to_html()
# bar-plot function
def plot_altair(crime_category, neighbourhood, crime_type):
"""
Function that makes the bar chart on crime incidences by crime categories
and neighborhoods.
Parameters:
----------
crime_category: {"All", "Violent crimes", "Property crimes", "Vehicle collision"}
category of crimes reported in Vancouver
neighbourhood: str
different neighbourhoods in Vancouver
Returns:
----------
altair chart
"""
# Set the crime type to be highlighted to a separate value in a new column
crime["highlight"] = False
crime.loc[crime["TYPE"] == crime_type, "highlight"] = True
if crime_category == "All":
chart = (
alt.Chart(
crime.loc[crime["NEIGHBOURHOOD"] == neighbourhood],
title=f"Total Reported Cases by Crime Types in {neighbourhood}",
)
.mark_bar()
.encode(
y=alt.Y("TYPE", sort="-x", title="Type of crime"),
x=alt.X(
"count()", title="Number of crime cases", axis=alt.Axis(grid=False)
),
color=alt.Color("highlight", legend=None),
tooltip="count()",
)
.interactive()
.configure(background="#010915")
.configure_axis(
titleFontSize=18, titleColor="#FFFFFF", labelColor="#FFFFFF"
)
.configure_title(fontSize=18, color="#FFFFFF")
# .configure_header(titleColor="#FFFFFF", titleFontSize=14)
.configure_view(strokeWidth=0)
.properties(width=650, height=500)
)
else:
chart = (
alt.Chart(
crime.loc[
(crime["crime_category"] == crime_category)
& (crime["NEIGHBOURHOOD"] == neighbourhood)
],
title=f"{crime_category}: Total Crime Reports by Crime Types in {neighbourhood}",
)
.mark_bar()
.encode(
y=alt.Y("TYPE", sort="-x", title="Crime types"),
x=alt.X(
"count()", title="Number of crime cases", axis=alt.Axis(grid=False)
),
color=alt.Color("highlight", legend=None),
tooltip="count()",
)
.interactive()
.configure(background="#010915")
.configure_axis(
titleFontSize=18, titleColor="#FFFFFF", labelColor="#FFFFFF"
)
.configure_title(fontSize=18, color="#FFFFFF")
.configure_view(strokeWidth=0)
.properties(width=625, height=475)
)
return chart.to_html()
def plot_histogram(weekday, neighbourhood):
"""
Function that makes the bar chart on crime incidences for each crime
category by days of a week and neighborhoods.
Parameters:
----------
weekday: str
including "All" and seven days of a week - "Monday", "Tuesday", etc.
neighbourhood: str
different neighbourhoods in Vancouver
Returns:
----------
altair chart
"""
if weekday == "All":
chart = (
alt.Chart(
crime.loc[crime["NEIGHBOURHOOD"] == neighbourhood],
title=alt.TitleParams(text=f"Total Reported Crimes in {neighbourhood}"),
)
.mark_bar()
.encode(
x=alt.X(
"crime_category",
sort="-y",
title="Crime Category",
axis=alt.Axis(labelAngle=-45),
),
y=alt.Y(
"count()", title="Number of crime cases", axis=alt.Axis(grid=False)
),
tooltip="count()",
)
.interactive()
.configure(background="#010915")
.configure_axis(
titleFontSize=16, titleColor="#FFFFFF", labelColor="#FFFFFF"
)
.configure_title(fontSize=15, color="#FFFFFF")
.configure_view(strokeWidth=0)
.properties(width=250, height=310)
)
else:
chart = (
alt.Chart(
crime.loc[
(crime["NEIGHBOURHOOD"] == neighbourhood)
& (crime["day_of_week"] == weekday)
],
title=alt.TitleParams(
text=f"Total Reported Crimes on {weekday}s in {neighbourhood}"
),
)
.mark_bar()
.encode(
x=alt.X(
"crime_category",
sort="-y",
title="Crime Category",
axis=alt.Axis(labelAngle=-45),
),
y=alt.Y(
"count()", title="Number of crime cases", axis=alt.Axis(grid=False)
),
tooltip="count()",
)
.interactive()
.configure(background="#010915")
.configure_axis(
titleFontSize=16, titleColor="#FFFFFF", labelColor="#FFFFFF"
)
.configure_title(fontSize=15, color="#FFFFFF")
.configure_view(strokeWidth=0)
.properties(width=250, height=310)
)
return chart.to_html()
# ---------------------------------------------------------------------------------------------------#
app = Dash(__name__, meta_tags=[{"name": "viewport", "content": "width=device-width"}])
app.title = "Safe Vancity"
server = app.server
# ---------------------------------------------------------------------------------------------------# create app layout
tab_style = {
"borderBottom": "1px solid #d6d6d6",
"color": "white",
"padding": "6px",
"backgroundColor": "#010915",
# 'fontWeight': 'bold'
}
tab_selected_style = {
"borderTop": "4px solid #d6d6d6",
"borderBottom": "4px solid #d6d6d6",
"borderLeft": "4px solid #d6d6d6",
"borderRight": "4px solid #d6d6d6",
"backgroundColor": "#010915",
"color": "white",
"padding": "6px",
"fontWeight": "bold",
"fontSize": 20,
}
app.layout = html.Div(
[
html.Div(
[
dbc.Button(
"About",
id="simple-toast-toggle",
color="white",
className="mb-3",
n_clicks=0,
style={"position": "fixed", "right": 90},
),
dbc.Toast(
[
html.A(
"GitHub",
href="https://github.com/UBC-MDS/safe_vancity",
style={"color": "orange", "text-decoration": "underline"},
),
html.P(
"The dashboard was created by Arlin Cherian, Victor Francis, Wanying Ye. It is licensed under MIT license. Please visit GitHub for more information.",
style={"color": "white"},
),
html.A(
"Dashboard description",
style={"color": "orange", "text-decoration": "underline"},
),
html.P(
"""This dashboard allows you to see crime incidence in 2021 in Vancouver neighbourhoods. By selecting a neighbourhood from the drop down menu, all the plots in the app will display metrics related to that neighbourhood. The map will display crime density by 'neighbourhood', 'crime type' and by 'month'. You can zoom into the neighbourhood to see specific streets where the crimes have happened. You can use the toggle options on the top right corner of the map to zoom in or out, pan the map and reset axes. The top-right bar plot shows the total reported crimes in a selected neighbourhood by 'day of the week' (default all days). This plot can be filtered using the 'neighbourhood' and 'day of the week' options. Finally, the bottom bar plot shows total reported crimes by crime category in each neighbourhood. Here crime types are grouped by crime categories (Violent, Property and Vehicle Collision). Default view shows the total cases for all crime categories. You can toggle through the tab options. From this plot you can see the top crimes in each neighbourhood in 2021. Some summary stats of overall reported crimes in Vancouver in 2021, total property, violent and vehicle collision crimes are reported at the very top.""",
style={"color": "white"},
),
],
id="simple-toast",
header="About",
icon="primary",
dismissable=True,
is_open=False,
),
],
className="row flex-display",
),
html.Div(
[
html.Div(
[
html.Img(
src=app.get_asset_url("logo-1.jpg"),
id="logo_image",
style={
"height": "60px",
"width": "auto",
"margin-bottom": "10px",
"padding-left": 0,
},
)
],
className="one column",
),
html.Div(
[
html.Div(
[
html.H2(
"Vancouver Crime Incidence Dashboard",
style={
"margin-bottom": "0px",
"color": "white",
"textalign": "right",
},
),
html.H4(
"Incidence for 2021",
style={
"margin-top": "0px",
"color": "white",
"textalign": "right",
},
),
]
)
],
className="six column",
id="title",
),
],
id="header",
className="row flex-display",
style={"margin-bottom": "25px"},
),
html.Div(
[
html.Div(
[
html.H6(
children="Total crimes",
style={"textAlign": "center", "color": "white"},
),
html.P(
f" 32,007",
style={
"textAlign": "center",
"color": "#4C78A8",
"fontSize": 40,
},
),
],
className="card_container three columns",
),
html.Div(
[
html.H6(
children="Total property crimes",
style={"textAlign": "center", "color": "white"},
),
html.P(
f" 21,853",
style={
"textAlign": "center",
"color": "#4C78A8",
"fontSize": 40,
},
),
],
className="card_container three columns",
),
html.Div(
[
html.H6(
children="Total violent crimes",
style={"textAlign": "center", "color": "white"},
),
html.P(
f" 9,114",
style={
"textAlign": "center",
"color": "#4C78A8",
"fontSize": 40,
},
),
],
className="card_container three columns",
),
html.Div(
[
html.H6(
children=" Total vehical collision",
style={"textAlign": "center", "color": "white"},
),
html.P(
f" 1,040",
style={
"textAlign": "center",
"color": "#4C78A8",
"fontSize": 40,
},
),
],
className="card_container three columns",
),
],
className="row flex-display",
style={"margin-bottom": "25px", "margin-top": "25px"},
),
html.Div(
[
html.Div(
[
html.Iframe(
id="map-chart",
style={
"border-width": "0",
"width": "100%",
"height": "475px",
},
srcDoc=plot(
crime_type="Break and Enter Commercial",
neighbourhood="West End",
month_name="All",
),
)
],
className="create_container ten columns",
),
html.Div(
[
html.Iframe(
id="hist",
style={
"border-width": "0",
"width": "400px", # "100%",
"height": "475px",
},
)
],
className="create_container five columns",
),
],
className="row flex-display",
),
html.Div(
[
html.Div(
[
html.Label(
["FILTERS"],
className="fix_label",
style={
"color": "orange",
"textAlign": "center",
"fontSize": 20,
},
),
html.Label(
[
"Select the crime type",
dcc.Dropdown(
id="crime_type",
value="Break and Enter Commercial",
options=[{"label": i, "value": i} for i in comp],
searchable=True,
# placeholder='Select a crime type..',
clearable=False,
className="dcc_compon",
),
],
className="fix_label",
style={"color": "white"},
),
html.Label(
[
"Select the neighborhood",
dcc.Dropdown(
id="neighbourhood",
value="West End",
options=[
{"label": col, "value": col}
for col in neighbourhood_l
],
searchable=True,
# placeholder='Please select...',
clearable=False,
className="dcc_compon",
),
],
className="fix_label",
style={"color": "white"},
),
html.Label(
[
"Select the month",
dcc.Dropdown(
id="month_name",
value="All",
options=[
{"label": col, "value": col}
for col in [
"All",
"Nov",
"Dec",
"Jul",
"Jun",
"Sep",
"Aug",
"Mar",
"Feb",
"Oct",
"May",
"Apr",
"Jan",
]
],
searchable=True,
# placeholder='Please select...',
clearable=False,
className="dcc_compon",
),
],
className="fix_label",
style={"color": "white"},
),
html.Label(
[
"Select the weekday",
dcc.Dropdown(
id="weekday",
value="All",
options=[
{"label": col, "value": col}
for col in [
"All",
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
]
],
searchable=True,
# placeholder='Please select...',
clearable=False,
className="dcc_compon",
),
],
className="fix_label",
style={"color": "white"},
),
html.Label(
["Data Source: "],
className="fix_label",
style={
"color": "orange",
"textAlign": "center",
"margin-top": "80px",
},
),
html.Label(
[
html.A(
"VPD Open Source",
href="https://geodash.vpd.ca/opendata/#",
)
],
className="fix_label",
style={
"color": "white",
"textAlign": "center",
"margin-top": "0px",
},
),
html.Label(
"Last Updated: "
+ str(
pd.to_datetime("now", utc=True)
.tz_convert("US/Pacific")
.strftime("%m/%d/%Y, %H:%M:%S")
),
style={
"color": "orange",
"margin-top": "25px",
"textAlign": "center",
},
),
],
className="create_container three columns",
),
html.Div(
[
dcc.Tabs(
id="crime_category-widget",
value="All",
children=[
dcc.Tab(
label="All",
value="All",
style=tab_style,
selected_style=tab_selected_style,
),
dcc.Tab(
label="Violent crimes",
value="Violent crimes",
style=tab_style,
selected_style=tab_selected_style,
),
dcc.Tab(
label="Property crimes",
value="Property crimes",
style=tab_style,
selected_style=tab_selected_style,
),
dcc.Tab(
label="Vehicle collision",
value="Vehicle collision",
style=tab_style,
selected_style=tab_selected_style,
),
],
),
html.Iframe(
id="histogram",
style={
"border-width": "0",
"width": "100%",
"height": "600px",
},
),
],
className="create_container nine columns",
),
],
className="row flex-display",
),
],
id="mainContainer",
style={"display": "flex", "flex-direction": "column"},
)
# ---------------------------------------------------------------------------------------------------#
# backend
@app.callback(
Output("map-chart", "srcDoc"),
Input("crime_type", "value"),
Input("neighbourhood", "value"),
Input("month_name", "value"),
)
@app.callback(
Output("histogram", "srcDoc"),
Input("crime_category-widget", "value"),
Input("neighbourhood", "value"),
Input("crime_type", "value"),
)
@app.callback(
Output("hist", "srcDoc"),
Input("weekday", "value"),
Input("neighbourhood", "value"),
)
@app.callback(
Output("simple-toast", "is_open"),
[Input("simple-toast-toggle", "n_clicks")],
)
if __name__ == "__main__":
app.run_server(debug=True)
| [
11748,
7110,
306,
13,
42712,
355,
279,
87,
198,
6738,
14470,
1330,
16189,
11,
288,
535,
11,
27711,
11,
23412,
11,
25235,
11,
1812,
11,
645,
62,
19119,
198,
6738,
12972,
1676,
73,
1330,
3602,
16354,
198,
11748,
14470,
62,
18769,
26418,... | 1.577718 | 17,943 |
from django.contrib import admin
from .models import XMPPAccount
from .forms import XMPPAccountForm
admin.site.register(XMPPAccount, XMPPAccountAdmin)
| [
198,
6738,
42625,
14208,
13,
3642,
822,
1330,
13169,
198,
6738,
764,
27530,
1330,
1395,
7378,
4537,
535,
608,
198,
6738,
764,
23914,
1330,
1395,
7378,
4537,
535,
608,
8479,
628,
198,
28482,
13,
15654,
13,
30238,
7,
55,
7378,
4537,
535... | 2.961538 | 52 |
"""
This class runs all tests
"""
import os,sys,time,pytest
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from page_objects.PageFactory import PageFactory
from utils.Option_Parser import Option_Parser
import conf.product_payment_conf as conf
from page_objects.product_object import Product_Object
def test_weather_shopper_form(base_url,browser,browser_version,os_version,os_name,remote_flag,remote_project_name,remote_build_name):
"Run the test"
try:
#Initalize flags for tests summary
expected_pass = 0
actual_pass = -1
#Create a test object
test_obj = PageFactory.get_page_object("Main Page",base_url=base_url)
#2. Setup and register a driver
start_time = int(time.time()) #Set start_time with current time
test_obj.register_driver(remote_flag,os_name,os_version,browser,browser_version,remote_project_name,remote_build_name)
#3. Read the temparature
result_flag=test_obj.get_temprature()
test_obj.write("Temperature is %s"%result_flag)
# print("Temperature is %s"%result_flag)
#4. Select appropriate item and check the screen
if int(result_flag) <= 19:
# print("Temperature is %s"%result_flag)
#print("We will buy moisturiser")
test_obj.click_moisturizers()
is_screen_visible=test_obj.check_redirect_moisturizers()
#print(is_screen_visible)
if is_screen_visible is not None:
test_obj.write("You are on Buy Moisturizer page")
# Select product categories
product_moisturizers_category = conf.product_moisturizers_category
test_obj.write("product categories are %s"%product_moisturizers_category)
# Adding the product categories in the cart
test_obj.add_products(product_moisturizers_category)
# view the added products on the cart
test_obj.click_cart()
# verify you are at cart screen
is_screen_visible=test_obj.check_redirect_cart()
if is_screen_visible is not None:
test_obj.write("You are on cart page")
elif int(result_flag) >=34:
#print("Temperature is %s"%result_flag)
#print("We will buy sunscreens")
test_obj.click_sunscreens()
is_screen_visible=test_obj.check_redirect_sunscreens()
#print(is_screen_visible)
if is_screen_visible is not None:
test_obj.write("You are on Buy Sunscreens page")
# Select product categories
product_sunscreens_category = conf.product_sunscreens_category
test_obj.write("product categories are %s"%product_sunscreens_category)
# Adding the product categories in the cart
test_obj.add_products(product_sunscreens_category)
# view added products on the cart
test_obj.click_cart()
# verify you are cart screen
is_screen_visible=test_obj.check_redirect_cart()
if is_screen_visible is not None:
test_obj.write("You are on cart page")
#Teardown
test_obj.wait(3)
expected_pass = test_obj.result_counter
actual_pass = test_obj.pass_counter
test_obj.teardown()
except Exception as e:
print("Exception when trying to run test:%s"%__file__)
print("Python says:%s"%str(e))
#---START OF SCRIPT
if __name__=='__main__':
print("Start of %s"%__file__)
#Creating an instance of the class
options_obj = Option_Parser()
options = options_obj.get_options()
#Run the test only if the options provided are valid
if options_obj.check_options(options):
test_weather_shopper_form(base_url=options.url,
browser=options.browser,
browser_version=options.browser_version,
os_version=options.os_version,
os_name=options.os_name,
remote_flag=options.remote_flag,
remote_project_name=options.remote_project_name,
remote_build_name=options.remote_build_name)
else:
print('ERROR: Received incorrect comand line input arguments')
print(options_obj.print_usage()) | [
37811,
198,
1212,
1398,
4539,
477,
5254,
198,
37811,
198,
11748,
28686,
11,
17597,
11,
2435,
11,
9078,
9288,
198,
17597,
13,
6978,
13,
33295,
7,
418,
13,
6978,
13,
15908,
3672,
7,
418,
13,
6978,
13,
15908,
3672,
7,
418,
13,
6978,
... | 2.251016 | 1,968 |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import collections
import multiprocessing
import uuid as pyuuid
from gbpservice.nfp.core import common as nfp_common
from gbpservice.nfp.core import log as nfp_logging
from gbpservice.nfp.core import module as nfp_api
from gbpservice.nfp.core import sequencer as nfp_seq
LOG = nfp_logging.getLogger(__name__)
identify = nfp_common.identify
"""Event Types """
SCHEDULE_EVENT = 'schedule_event'
POLL_EVENT = 'poll_event'
STASH_EVENT = 'stash_event'
EVENT_EXPIRED = 'event_expired'
EVENT_GRAPH = 'event_graph'
"""Event Flag """
EVENT_NEW = 'new_event'
EVENT_COMPLETE = 'event_done'
EVENT_ACK = 'event_ack'
"""Sequencer status. """
SequencerEmpty = nfp_seq.SequencerEmpty
SequencerBusy = nfp_seq.SequencerBusy
deque = collections.deque
"""Defines poll descriptor of an event.
Holds all of the polling information of an
event.
"""
"""Defines the descriptor of an event.
Holds the metadata for an event. Useful
for event processing. Not exposed to nfp modules.
"""
"""Defines the event structure.
Nfp modules need to create object of the class
to create an event.
"""
"""Table of event handler's.
Maintains cache of every module's event handlers.
Also, maintains the polling against event_id
which are provided as decorators.
"""
"""Manages the lifecycle of event of a process.
Each process (worker/distributor) is associated
with a event manager. Event manager pulls events
from the pipe, caches it, sequences & dispatches
the events.
"""
| [
2,
220,
220,
220,
49962,
739,
262,
24843,
13789,
11,
10628,
362,
13,
15,
357,
1169,
366,
34156,
15341,
345,
743,
198,
2,
220,
220,
220,
407,
779,
428,
2393,
2845,
287,
11846,
351,
262,
13789,
13,
921,
743,
7330,
198,
2,
220,
220,
... | 3.10119 | 672 |
# Name: FileGlob
import inviwopy as ivw
from inviwopy.properties import FileProperty, FilePatternProperty, ButtonProperty, IntProperty
| [
2,
6530,
25,
9220,
9861,
672,
198,
198,
11748,
800,
14246,
11081,
355,
21628,
86,
198,
6738,
800,
14246,
11081,
13,
48310,
1330,
9220,
21746,
11,
9220,
47546,
21746,
11,
20969,
21746,
11,
2558,
21746,
628
] | 3.805556 | 36 |
# -*- Mode: Python -*-
#
# Author: Sam Rushing <rushing@nightmare.com>
# Copyright 1997 by Sam Rushing
# All Rights Reserved.
#
RCS_ID = '$Id: default_handler.py,v 1.8 2002/08/01 18:15:45 akuchling Exp $'
# standard python modules
import mimetypes
import re
import stat
import string
# medusa modules
import http_date
import http_server
import status_handler
import producers
unquote = http_server.unquote
# This is the 'default' handler. it implements the base set of
# features expected of a simple file-delivering HTTP server. file
# services are provided through a 'filesystem' object, the very same
# one used by the FTP server.
#
# You can replace or modify this handler if you want a non-standard
# HTTP server. You can also derive your own handler classes from
# it.
#
# support for handling POST requests is available in the derived
# class <default_with_post_handler>, defined below.
#
from counter import counter
# HTTP/1.0 doesn't say anything about the "; length=nnnn" addition
# to this header. I suppose its purpose is to avoid the overhead
# of parsing dates...
IF_MODIFIED_SINCE = re.compile (
'If-Modified-Since: ([^;]+)((; length=([0-9]+)$)|$)',
re.IGNORECASE
)
USER_AGENT = re.compile ('User-Agent: (.*)', re.IGNORECASE)
CONTENT_TYPE = re.compile (
r'Content-Type: ([^;]+)((; boundary=([A-Za-z0-9\'\(\)+_,./:=?-]+)$)|$)',
re.IGNORECASE
)
get_header = http_server.get_header
get_header_match = http_server.get_header_match
| [
2,
532,
9,
12,
10363,
25,
11361,
532,
9,
12,
198,
2,
198,
2,
220,
220,
220,
220,
220,
220,
6434,
25,
3409,
371,
8023,
1279,
81,
8023,
31,
3847,
11449,
13,
785,
29,
198,
2,
220,
220,
220,
220,
220,
220,
15069,
8309,
416,
3409,
... | 2.649153 | 590 |
import cv2
import numpy as np
from matplotlib import pyplot as plt
img=cv2.imread("roads.jpg")
img=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
print(img.shape,img.dtype)
height=img.shape[0]
width=img.shape[1]
region_of_interest_vertices=[(0,height),(height/2,width/2),(width,height)]
gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
edge=cv2.Canny(gray,100,200)
cropped_image=roi(edge,np.array([region_of_interest_vertices],np.uint8))
line=cv2.HoughLinesP(cropped_image,1,np.pi/180,60,lines=np.array([]),minLineLength=40,maxLineGap=25)
final=image_with_lines(img,line)
plt.imshow(final)
plt.show()
| [
11748,
269,
85,
17,
198,
11748,
299,
32152,
355,
45941,
198,
6738,
2603,
29487,
8019,
1330,
12972,
29487,
355,
458,
83,
628,
198,
9600,
28,
33967,
17,
13,
320,
961,
7203,
21372,
13,
9479,
4943,
198,
9600,
28,
33967,
17,
13,
33967,
8... | 2.235741 | 263 |
#!/bin/python3
# ccash_python_client - ccash python client
# Copyright (C) 2021 FearlessDoggo21
# see LICENCE for licensing information
from requests import get, post, delete, patch, Response
from .inc import User
class CCash:
'''The CCash client class'''
def close(self, admin: User) -> Response:
'''Safely closes the server and saves its current state.'''
return post(
self.domain + "/admin/shutdown",
timeout=self.timeout,
headers={
"Accept": "*/*",
"Authorization": admin.auth_encode()
}
)
def new_user(self, user: User) -> Response:
'''Creates a new user without an initial balance.'''
return post(
self.domain + "/user/register",
timeout=self.timeout,
headers={"Accept": "*/*"},
json=user.to_dict()
)
def admin_new_user(self, admin: User, user: User,
amount: int) -> Response:
'''Creates a new user with an initial balance.'''
return post(
self.domain + "/admin/user/register",
timeout=self.timeout,
headers={
"Accept": "*/*",
"Authorization": admin.auth_encode()
},
json={"name": user.name, "amount": amount,
"pass": user.passwd}
)
def del_user(self, user: User) -> Response:
'''Deletes a user.'''
return delete(
self.domain + "/user/delete",
timeout=self.timeout,
headers={
"Accept": "*/*",
"Authorization": user.auth_encode()
}
)
def admin_del_user(self, admin: User, name: str) -> Response:
'''Deletes a user via the admin password.'''
return delete(
self.domain + "/admin/user/delete",
timeout=self.timeout,
headers={
"Accept": "*/*",
"Authorization": admin.auth_encode()
},
json={"name": name}
)
def user_exists(self, name: str) -> Response:
'''Confirms if a user exists.'''
return get(
self.domain + f"/user/exists?name={name}",
timeout=self.timeout,
headers={"Accept": "*/*"}
)
def verify_passwd(self, user: User) -> Response:
'''Confirms a users password.
If a `False` value returned, the user may not exist.'''
return post(
self.domain + "/user/verify_password",
timeout=self.timeout,
headers={
"Accept": "*/*",
"Authorization": user.auth_encode()
}
)
def verify_admin(self, admin: User) -> Response:
'''Confirms the admin account.'''
return post(
self.domain + "/admin/verify_account",
timeout=self.timeout,
headers={
"Accept": "*/*",
"Authorization": admin.auth_encode()
}
)
def change_passwd(self, user: User, passwd: str) -> Response:
'''Changes a user password.'''
return patch(
self.domain + "/user/change_password",
timeout=self.timeout,
headers={
"Accept": "*/*",
"Authorization": user.auth_encode()
},
json={"pass": passwd}
)
def admin_change_passwd(self, admin: User, name: str, \
passwd: str) -> Response:
'''Changes a user password via the admin password.'''
return patch(
self.domain + "/admin/user/change_password",
timeout=self.timeout,
headers={
"Accept": "*/*",
"Authorization": admin.auth_encode()
},
json={"name": name, "pass": passwd}
)
def get_bal(self, name: str) -> Response:
'''Gets the balance of a user.
Returns 0 if the user does not exist.'''
return get(
self.domain + f"/user/balance?name={name}",
timeout=self.timeout,
headers={"Accept": "*/*"}
)
def set_bal(self, admin: User, name: str, balance: int) -> \
Response:
'''Sets the balance of a user.'''
return patch(
self.domain + "/admin/set_balance",
timeout=self.timeout,
headers={
"Accept": "*/*",
"Authorization": admin.auth_encode()
},
json={"name": name, "amount": balance}
)
def impact_bal(self, admin: User, name: str, amount: int) -> \
Response:
'''Offsets the balance of a user.'''
return post(
self.domain + "/admin/impact_balance",
timeout=self.timeout,
headers={
"Accept": "*/*",
"Authorization": admin.auth_encode()
},
json={"name": name, "amount": amount}
)
def get_logs(self, user: User) -> Response:
'''Returns the logged transactions of a user.'''
return get(
self.domain + "/user/log",
timeout = self.timeout,
headers={
"Accept": "*/*",
"Authorization": user.auth_encode()
}
)
def send(self, user: User, name: str, amount: str) -> Response:
'''Sends an amount to another user.'''
return post(
self.domain + "/user/transfer",
timeout=self.timeout,
headers={
"Accept": "*/*",
"Authorization": user.auth_encode()
},
json={"name": name, "amount": amount}
)
def prune(self, admin: User, time: int, amount: int) -> Response:
'''Deletes all users older than time and which have less
money than amount.'''
return post(
self.domain + "/admin/prune_users",
timeout=self.timeout,
headers={
"Accept": "*/*",
"Authorization": admin.auth_encode()
},
json={"time": time, "amount": amount}
)
| [
2,
48443,
8800,
14,
29412,
18,
198,
2,
269,
30350,
62,
29412,
62,
16366,
532,
269,
30350,
21015,
5456,
198,
2,
15069,
357,
34,
8,
33448,
16132,
1203,
32942,
2188,
2481,
198,
2,
766,
38559,
18310,
329,
15665,
1321,
198,
198,
6738,
70... | 1.984395 | 3,140 |
# Copyright 2019-2020 QuantumBlack Visual Analytics Limited
#
# 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
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND
# NONINFRINGEMENT. IN NO EVENT WILL THE LICENSOR OR OTHER CONTRIBUTORS
# BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF, OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# The QuantumBlack Visual Analytics Limited ("QuantumBlack") name and logo
# (either separately or in combination, "QuantumBlack Trademarks") are
# trademarks of QuantumBlack. The License does not grant you any right or
# license to the QuantumBlack Trademarks. You may not use the QuantumBlack
# Trademarks or any confusingly similar mark as a trademark for your product,
# or use the QuantumBlack Trademarks in any other manner that might cause
# confusion in the marketplace, including but not limited to in advertising,
# on websites, or on software.
#
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Module of methods to generate random StructureModel and datasets with various properties, for example, continuous data.
Structure generator based on implementation found in: from https://github.com/xunzheng/notears
git hash: 31923cb22517f7bb6420dd0b6ef23ca550702b97
"""
from typing import Dict, Hashable, List, Optional, Tuple, Union
import networkx as nx
import numpy as np
import pandas as pd
from sklearn.gaussian_process.kernels import RBF, Kernel
from causalnex.structure import StructureModel
from causalnex.structure.categorical_variable_mapper import (
VariableFeatureMapper,
validate_schema,
)
# dict mapping distributions names to their functions
__distribution_mapper = {
"gaussian": np.random.normal,
"normal": np.random.normal,
"student-t": np.random.standard_t,
"gumbel": np.random.gumbel,
"exponential": np.random.exponential,
"probit": np.random.normal,
"logit": np.random.logistic,
}
def generate_structure(
num_nodes: int,
degree: float,
graph_type: str = "erdos-renyi",
w_min: float = 0.5,
w_max: float = 0.5,
) -> StructureModel:
"""Simulate random DAG with some expected degree.
Notes:
graph_type (str):
- erdos-renyi: constructs a graph such that the probability of any given edge is degree / (num_nodes - 1)
- barabasi-albert: constructs a scale-free graph from an initial connected graph of (degree / 2) nodes
- full: constructs a fully-connected graph - degree has no effect
Args:
num_nodes: number of nodes
degree: expected node degree, in + out
graph_type (str):
- erdos-renyi: constructs a graph such that the probability of any given edge is degree / (num_nodes - 1)
- barabasi-albert: constructs a scale-free graph from an initial connected graph of (degree / 2) nodes
- full: constructs a fully-connected graph - degree has no effect
w_min (float): min absolute weight of an edge in the graph
w_max (float): max absolute weight of an edge in the graph
Raises:
ValueError: if invalid arguments are provided
Returns:
weighted DAG
"""
if num_nodes < 2:
raise ValueError("DAG must have at least 2 nodes")
w_min, w_max = abs(w_min), abs(w_max)
if w_min > w_max:
raise ValueError(
"Absolute minimum weight must be less than or equal to maximum weight: {} > {}".format(
w_min, w_max
)
)
if graph_type == "erdos-renyi":
p_threshold = float(degree) / (num_nodes - 1)
p_edge = (np.random.rand(num_nodes, num_nodes) < p_threshold).astype(float)
edge_flags = np.tril(p_edge, k=-1)
elif graph_type == "barabasi-albert":
m = int(round(degree / 2))
edge_flags = np.zeros([num_nodes, num_nodes])
bag = [0]
for i in range(1, num_nodes):
dest = np.random.choice(bag, size=m)
for j in dest:
edge_flags[i, j] = 1
bag.append(i)
bag.extend(dest)
elif graph_type == "full": # ignore degree
edge_flags = np.tril(np.ones([num_nodes, num_nodes]), k=-1)
else:
raise ValueError(
"Unknown graph type {t}. ".format(t=graph_type)
+ "Available types are ['erdos-renyi', 'barabasi-albert', 'full']"
)
# randomly permute edges - required because we limited ourselves to lower diagonal previously
perms = np.random.permutation(np.eye(num_nodes, num_nodes))
edge_flags = perms.T.dot(edge_flags).dot(perms)
# random edge weights between w_min, w_max or between -w_min, -w_max
edge_weights = np.random.uniform(low=w_min, high=w_max, size=[num_nodes, num_nodes])
edge_weights[np.random.rand(num_nodes, num_nodes) < 0.5] *= -1
adj_matrix = (edge_flags != 0).astype(float) * edge_weights
graph = StructureModel(adj_matrix)
return graph
def sem_generator(
graph: nx.DiGraph,
schema: Optional[Dict] = None,
default_type: str = "continuous",
noise_std: float = 1.0,
n_samples: int = 1000,
distributions: Dict[str, Union[str, float]] = None,
intercept: bool = True,
seed: int = None,
) -> pd.DataFrame:
"""
Generator for tabular data with mixed variable types from a DAG.
NOTE: the root nodes of the DAG are sampled from a distribution with noise_std=1.0 always.
This is so that increases in the noise_std are in relation to a fixed spread, and therefore
actually have an impact on the fit. Not using this method causes the noise_std to only change
the axis scaling.
Supported variable types: `'binary', 'categorical', 'continuous'`. The number
of categories can be determined using a colon, e.g. `'categorical:5'`
specifies a categorical feature with 5 categories.
Notation: For binary and continuous variables, a ``variable'' refers to a
``node'', a ``feature'' refers to the one-hot column for categorical
variables and is equivalent to a binary or continuous variable.
Args:
graph: A DAG in form of a networkx or StructureModel.
schema: Dictionary with schema for a node/variable, if a node is missing
uses ``default_type``. Format, {node_name: variable type}.
default_type: The default data type for a node/variable not listed
in the schema, or when the schema is empty.
noise_std: The standard deviation of the noise. The binary and
categorical features are created using a latent variable approach.
The noise standard deviation determines how much weight the "mean"
estimate has on the feature value.
n_samples: The number of rows/observations to sample.
distributions:
``continuous'': The type of distribution to use for the noise
of a continuous variable. Options: 'gaussian'/'normal' (alias)
(default), 'student-t', 'exponential', 'gumbel'.
``binary'': The type of distribution to use for the noise
of the latent binary variable. Options: 'probit'/'normal' (alias),
'logit' (default).
``categorical'': The type of distribution to use for the noise
of a latent continuous feature. Options: 'probit'/'normal' (alias),
'logit'/'gumbel' (alias) (default).
``weight'': The type of distribution to use for the linear coefficients.
Options: 'gaussian'/'normal' (alias), 'uniform' (default).
``intercept'': The type of distribution to use for the intercept. For
binary/categorical: this is the mean in the latent space.
Options: 'gaussian'/'normal' (alias), 'uniform' (default).
``count``: The zero-inflation probability as a float.
intercept: Whether to use an intercept for each feature. The intercept
is sampled once and held constant for all rows. For binary or
categorical the intercept determines the class imbalance.
seed: Random State
Returns:
DataFrame with generated features, uses a one-hot coding for
categorical features.
Raises:
ValueError: if the graph is not a DAG.
ValueError: if schema variable type is not in `'binary', 'categorical',
'continuous', 'continuous:X` (for variables with X categories).
ValueError: if distributions['continuous'] is not 'gaussian', 'normal', 'student-t',
'exponential', 'gumbel'.
ValueError: if distributions['binary'] is not 'probit', 'normal', 'logit'.
ValueError: if distributions['categorical'] is not 'probit', 'normal', 'logit', 'gumbel'.
ValueError: if distributions['weight'] is not 'normal' / 'gaussian' (alias), 'uniform'.
ValueError: if distributions['intercept'] is not 'normal' / 'gaussian' (alias), 'uniform'.
ValueError: if distributions['count'], the zero-inflation factor is not a float in [0, 1].
Example:
sm = StructureModel()
sm.add_edges_from([('A', 'C'), ('D', 'C'), ('E', 'D')])
sm.add_nodes_from(['B', 'F'])
schema = {'B': 'binary', 'C': 'categorical:5',
'E': 'binary', 'F': 'continuous'}
df = sem_generator(sm, schema, noise_scale=1,
n_samples=10000,
intercept=True,
)
"""
distributions, var_fte_mapper, x_mat = _init_sem_data_gen(
graph=graph,
schema=schema,
n_samples=n_samples,
default_type=default_type,
distributions=distributions,
seed=seed,
)
# get dependence based on edges in graph (not via adjacency matrix)
w_mat = _create_weight_matrix(
edges_w_weights=graph.edges(data="weight"),
variable_to_indices_dict=var_fte_mapper.var_indices_dict,
weight_distribution=distributions["weight"],
intercept_distribution=distributions["intercept"],
intercept=intercept,
)
# intercept, append ones to the feature matrix
if intercept:
x_mat = np.append(x_mat, np.ones(shape=(n_samples, 1)), axis=1)
intercept_idx = [x_mat.shape[1] - 1]
# if intercept is used, the root nodes have len = 1
root_node_len = 1 if intercept else 0
# loop over sorted features according to ancestry (no parents first)
for j_node in nx.topological_sort(graph):
# all feature indices corresponding to the node/variable
j_idx_list = var_fte_mapper.get_indices(j_node)
# get all parent feature indices for the variable/node
parents_idx = var_fte_mapper.get_indices(list(graph.predecessors(j_node)))
if intercept:
parents_idx += intercept_idx
# if the data is a root node, must initialise the axis separate from noise parameter
root_node = len(parents_idx) <= root_node_len
# continuous variable
if var_fte_mapper.is_var_of_type(j_node, "continuous"):
x_mat[:, j_idx_list[0]] = _add_continuous_noise(
mean=x_mat[:, parents_idx].dot(w_mat[parents_idx, j_idx_list[0]]),
distribution=distributions["continuous"],
noise_std=noise_std,
root_node=root_node,
)
# binary variable
elif var_fte_mapper.is_var_of_type(j_node, "binary"):
x_mat[:, j_idx_list[0]] = _sample_binary_from_latent(
latent_mean=x_mat[:, parents_idx].dot(
w_mat[parents_idx, j_idx_list[0]]
),
distribution=distributions["binary"],
noise_std=noise_std,
root_node=root_node,
)
# count variable
elif var_fte_mapper.is_var_of_type(j_node, "count"):
x_mat[:, j_idx_list[0]] = _sample_count_from_latent(
eta=x_mat[:, parents_idx].dot(w_mat[parents_idx, j_idx_list[0]]),
zero_inflation_pct=distributions["count"],
root_node=root_node,
)
# categorical variable
elif var_fte_mapper.is_var_of_type(j_node, "categorical"):
x_mat[:, j_idx_list] = _sample_categories_from_latent(
latent_mean=x_mat[:, parents_idx].dot(
w_mat[np.ix_(parents_idx, j_idx_list)]
),
distribution=distributions["categorical"],
noise_std=noise_std,
root_node=root_node,
)
return pd.DataFrame(
x_mat[:, :-1] if intercept else x_mat, columns=var_fte_mapper.feature_list
)
def _sample_count_from_latent(
eta: np.ndarray,
root_node: bool,
zero_inflation_pct: float = 0.05,
) -> np.ndarray:
"""
Samples a zero-inflated poisson distribution.
Returns:
Samples from a Poisson distribution.
Raises:
ValueError: Unsupported zero-inflation factor.
"""
if (
not isinstance(zero_inflation_pct, (float, int))
or zero_inflation_pct < 0
or zero_inflation_pct > 1
):
raise ValueError(
"Unsupported zero-inflation factor, distribution['count'] needs to be a float in [0, 1]"
)
n_samples = eta.shape[0]
# add noise manually if root node
# uniform [0, 1] makes sure that the counts are small
if root_node:
eta += np.random.uniform(size=n_samples)
zif = np.random.uniform(size=n_samples) < zero_inflation_pct
count = _sample_poisson(expected_count=_exp_relu(eta))
# inflate the zeros:
count[zif] = 0
return count
def _sample_poisson(expected_count: np.ndarray, max_count: int = 5000) -> np.ndarray:
"""
Samples from a poisson distribution using each element in ``latent_mean``
as the Poisson parameter.
Args:
expected_count: Event rate of the Poisson process, can be of any array
dimension. Defined on (0, infty).
max_count: Bounds the count from above. The count sample is created
with a while loop. This argument is the maximum number of loop
iterations before stopping. Default value should run on most
machines in reasonable amount of time.
Returns:
Sampled count of a Poisson distribution from the given mean.
"""
# use log for numeric stability for large count values
log_cond_intensity = -expected_count
log_intensity_budget = np.copy(log_cond_intensity)
count = np.zeros_like(expected_count)
log_uni = np.log(np.random.uniform(size=expected_count.shape))
mask = log_uni >= log_intensity_budget
while np.any(mask) and count.max() < max_count:
mask = log_uni >= log_intensity_budget
count[mask] += 1
log_cond_intensity[mask] += np.log(expected_count[mask] / count[mask])
log_intensity_budget[mask] = np.logaddexp(
log_intensity_budget[mask], log_cond_intensity[mask]
)
return count
def _create_weight_matrix(
edges_w_weights: List[Tuple],
variable_to_indices_dict: Dict[Hashable, List[int]],
weight_distribution: str,
intercept_distribution: str,
intercept: bool,
) -> np.ndarray:
"""
Creates a weight matrix for a linear SEM model from the edges of a graph.
If the edges are unweighted, samples the weight values from a specified
distribution. Optionally adds an intercept to the weights using a separate
distribution.
"""
n_columns = sum(len(x) for x in variable_to_indices_dict.values())
w_mat = np.zeros(shape=(n_columns + 1 if intercept else n_columns, n_columns))
for node_from, node_to, weight in edges_w_weights:
ix_from = variable_to_indices_dict[node_from]
ix_to = variable_to_indices_dict[node_to]
ix_mask_array = np.ix_(ix_from, ix_to)
# we cannot assign the same weight for each category!
n_weights = len(ix_from) * len(ix_to)
if weight is None:
if weight_distribution == "uniform":
# zero mean, unit variance:
w_mat[ix_mask_array] = np.random.uniform(
-np.sqrt(12) / 2, np.sqrt(12) / 2, size=(len(ix_from), len(ix_to))
)
elif weight_distribution in ("gaussian", "normal"):
w_mat[ix_mask_array] = np.random.normal(
loc=0, scale=1, size=(len(ix_from), len(ix_to))
)
else:
_raise_dist_error(
"weight", intercept_distribution, ["uniform", "gaussian", "normal"]
)
else:
if n_weights == 1:
w_mat[ix_mask_array] = weight
elif n_weights > 1:
# assign weight randomly to a category (through the
# normalization, this affects all categories from or to)
sparse_mask = np.random.uniform(size=(len(ix_from), len(ix_to)))
sparse_mask = (sparse_mask == np.min(sparse_mask)).astype(int)
w_mat[ix_mask_array] = sparse_mask * weight
if intercept:
if intercept_distribution == "uniform":
# zero mean, unit variance:
w_mat[-1, :] = np.random.uniform(
-np.sqrt(12) / 2, np.sqrt(12) / 2, size=[1, n_columns]
)
elif intercept_distribution in ("gaussian", "normal"):
w_mat[-1, :] = np.random.normal(loc=0, scale=1, size=[1, n_columns])
else:
_raise_dist_error(
"intercept", intercept_distribution, ["uniform", "gaussian", "normal"]
)
return w_mat
def nonlinear_sem_generator(
graph: nx.DiGraph,
kernel: Kernel = RBF(1),
schema: Optional[Dict] = None,
default_type: str = "continuous",
noise_std: float = 1.0,
n_samples: int = 1000,
distributions: Dict[str, str] = None,
seed: int = None,
) -> pd.DataFrame:
"""
Generator for non-linear tabular data with mixed variable types from a DAG.
The nonlinearity can be controlled via the ``kernel``. Note that a
``DotProduct`` is equivalent to a linear function (without mean).
Supported variable types: `'binary', 'categorical', 'continuous'`. The number
of categories can be determined using a colon, e.g. `'categorical:5'`
specifies a categorical feature with 5 categories.
Notation: For binary and continuous variables, a ``variable'' refers to a
``node'', a ``feature'' refers to the one-hot column for categorical
variables and is equivalent to a binary or continuous variable.
Args:
graph: A DAG in form of a networkx or StructureModel.
kernel: A kernel from sklearn.gaussian_process.kernels like RBF(1) or
Matern(1) or any combinations thereof. The kernels are used to
create the latent variable for the binary / categorical variables
and are directly used for continuous variables.
schema: Dictionary with schema for a node/variable, if a node is missing
uses ``default_type``. Format, {node_name: variable type}.
default_type: The default data type for a node/variable not listed
in the schema, or when the schema is empty.
noise_std: The standard deviation of the noise. The binary and
categorical features are created using a latent variable approach.
The noise standard deviation determines how much weight the "mean"
estimate has on the feature value.
n_samples: The number of rows/observations to sample.
distributions:
``continuous'': The type of distribution to use for the noise
of a continuous variable. Options: 'gaussian'/'normal' (alias)
(default), 'student-t', 'exponential', 'gumbel'.
``binary'': The type of distribution to use for the noise
of the latent binary variable. Options: 'probit'/'normal' (alias),
'logit' (default).
``categorical'': The type of distribution to use for the noise
of a latent continuous feature. Options: 'probit'/'normal' (alias),
'logit'/'gumbel' (alias) (default).
seed: Random State
Returns:
DataFrame with generated features, uses a one-hot coding for
categorical features.
Raises:
ValueError: if the graph is not a DAG.
ValueError: if schema variable type is not in `'binary', 'categorical',
'continuous', 'continuous:X` (for variables with X categories).
ValueError: if distributions['continuous'] is not 'gaussian', 'normal', 'student-t',
'exponential', 'gumbel'.
ValueError: if distributions['binary'] is not 'probit', 'normal', 'logit'.
ValueError: if distributions['categorical'] is not 'probit', 'normal', 'logit', 'gumbel'.
ValueError: if distributions['count'], the zero-inflation factor is not a float in [0, 1].
Example:
sm = StructureModel()
sm.add_edges_from([('A', 'C'), ('D', 'C'), ('E', 'D')])
sm.add_nodes_from(['B', 'F'])
schema = {'B': 'binary', 'C': 'categorical:5',
'E': 'binary', 'F': 'continuous'}
df = sem_generator(sm, schema, kernel=RBF(1), noise_scale=1,
n_samples=10000)
"""
distributions, var_fte_mapper, x_mat = _init_sem_data_gen(
graph=graph,
schema=schema,
n_samples=n_samples,
default_type=default_type,
distributions=distributions,
seed=seed,
)
# loop over sorted features according to ancestry (no parents first)
for j_node in nx.topological_sort(graph):
# all feature indices corresponding to the node/variable
j_idx_list = var_fte_mapper.get_indices(j_node)
# get all parent feature indices for the variable/node
parents_idx = var_fte_mapper.get_indices(list(graph.predecessors(j_node)))
# if the data is a root node, must initialise the axis separate from noise parameter
root_node = len(parents_idx) <= 0
# continuous variable
if var_fte_mapper.is_var_of_type(j_node, "continuous"):
x_mat[:, j_idx_list[0]] = _add_continuous_noise(
mean=_gp_index(x_mat[:, parents_idx], kernel),
distribution=distributions["continuous"],
noise_std=noise_std,
root_node=root_node,
)
# binary variable
elif var_fte_mapper.is_var_of_type(j_node, "binary"):
x_mat[:, j_idx_list[0]] = _sample_binary_from_latent(
latent_mean=_gp_index(x_mat[:, parents_idx], kernel),
distribution=distributions["binary"],
noise_std=noise_std,
root_node=root_node,
)
# count
if var_fte_mapper.is_var_of_type(j_node, "count"):
x_mat[:, j_idx_list[0]] = _sample_count_from_latent(
eta=_gp_index(x_mat[:, parents_idx], kernel),
zero_inflation_pct=distributions["count"],
root_node=root_node,
)
# categorical variable
elif var_fte_mapper.is_var_of_type(j_node, "categorical"):
x_mat[:, j_idx_list] = _sample_categories_from_latent(
latent_mean=np.concatenate(
[
np.expand_dims(_gp_index(x_mat[:, parents_idx], kernel), axis=1)
for _ in j_idx_list
],
axis=1,
),
distribution=distributions["categorical"],
noise_std=noise_std,
root_node=root_node,
)
return pd.DataFrame(x_mat, columns=var_fte_mapper.feature_list)
def _gp_index(
x: np.ndarray,
kernel: Kernel,
max_chunk_size: int = 100,
) -> np.ndarray:
"""
Sample a Gaussian process using input data.
``f(x) ~ GP(0, K)``
If the number of samples is larger than ``max_chunk_size``, the sampling is
split in sorted batches (first dimension) and sampled using a conditional
multivariate normal.
Args:
x:
kernel:
max_chunk_size:
Returns:
A one-dimensional numpy array with a sample of f(x)
"""
# if we dont have a parent, the input will have no columns
if x.shape[1] == 0:
return np.zeros(shape=(x.shape[0],))
use_batches = x.shape[0] > max_chunk_size
if not use_batches:
y, _ = _unconditional_sample(x, kernel=kernel)
return _scale_y(y)
# if we need batches, we sort according to the first dimension
ix_sort = np.argsort(x, axis=0)[:, 0].squeeze()
reverse_ix = np.argsort(ix_sort).squeeze()
# split into smaller pieces
n_splits = (x.shape[0] // max_chunk_size) + 1
x_splits = np.array_split(x[ix_sort, :], n_splits)
outputs = []
y, cov_mat = _unconditional_sample(x_splits[0], kernel=kernel)
outputs.append(y)
x_old = x_splits[0]
for x_subset in x_splits[1:]:
y, cov_mat = _conditional_sample(
x_new=x_subset,
x_old=x_old,
f_old=outputs[-1],
kernel=kernel,
cov_mat_old=cov_mat,
)
outputs.append(y)
x_old = x_subset
y_all = _scale_y(np.concatenate(outputs))
return y_all[reverse_ix]
def _scale_y(y):
"""Normalize variance to 1."""
return y / y.std()
| [
2,
15069,
13130,
12,
42334,
29082,
9915,
15612,
30437,
15302,
198,
2,
198,
2,
49962,
739,
262,
24843,
13789,
11,
10628,
362,
13,
15,
357,
1169,
366,
34156,
15341,
198,
2,
345,
743,
407,
779,
428,
2393,
2845,
287,
11846,
351,
262,
13... | 2.360404 | 10,996 |
from django.contrib.auth import authenticate
from rest_framework import status
from rest_framework.authtoken.models import Token
from rest_framework.decorators import api_view, permission_classes, throttle_classes, authentication_classes
from rest_framework.response import Response
from rest_framework.throttling import UserRateThrottle
from core.users.serializers.users import UserSerializer
@api_view(['POST'])
@authentication_classes(())
@permission_classes(())
@api_view(['POST'])
@authentication_classes(())
@permission_classes(())
@throttle_classes((UserRateThrottle,))
| [
6738,
42625,
14208,
13,
3642,
822,
13,
18439,
1330,
8323,
5344,
198,
6738,
1334,
62,
30604,
1330,
3722,
198,
6738,
1334,
62,
30604,
13,
18439,
30001,
13,
27530,
1330,
29130,
198,
6738,
1334,
62,
30604,
13,
12501,
273,
2024,
1330,
40391,... | 3.570552 | 163 |
import numpy as np
import math
| [
11748,
299,
32152,
355,
45941,
198,
11748,
10688,
628,
198
] | 3.3 | 10 |
#!/usr/bin/env python
"""wrapper around emcc link step.
This wrapper currently serves the following purposes.
1. Ensures we always link to file with .js extension. The upstream default
it to link to an llvm bitcode file which is never (AFAICT) want to do that.
2. When building with --config=wasm the final output is multiple files, usually
at least one .js and one .wasm file. Since the cc_binary link step only
allows a single output, we must tar up the outputs into a single file.
3. Add quotes around arguments that need them in the response file to work
around a bazel quirk.
"""
from __future__ import print_function
import os
import subprocess
import sys
# Only argument should be @path/to/parameter/file
assert sys.argv[1][0] == '@'
param_filename = sys.argv[1][1:]
param_file_args = [l.strip() for l in open(param_filename, 'r').readlines()]
output_index = param_file_args.index('-o') + 1
orig_output = js_output = param_file_args[output_index]
outdir = os.path.dirname(orig_output)
# google3-only(TODO(b/139440956): Default to False once the bug is fixed)
replace_response_file = any(' ' in a for a in param_file_args)
if not os.path.splitext(orig_output)[1]:
js_output = orig_output + '.js'
param_file_args[output_index] = js_output
replace_response_file = True
# Re-write response file if needed.
if replace_response_file:
new_param_filename = param_filename + '.modified'
with open(new_param_filename, 'w') as f:
for param in param_file_args:
if ' ' in param:
f.write('"%s"' % param)
else:
f.write(param)
f.write('\n')
sys.argv[1] = '@' + new_param_filename
emcc_py = os.path.join(os.environ['EMSCRIPTEN'], 'emcc.py')
rtn = subprocess.call(['python3', emcc_py] + sys.argv[1:])
if rtn != 0:
sys.exit(1)
js_name = os.path.basename(js_output)
base_name = os.path.splitext(js_name)[0]
files = []
extensions = [
'.js',
'.wasm',
'.wasm.map',
'.js.mem',
'.fetch.js',
'.worker.js',
'.data',
'.js.symbols',
'.wasm.debug.wasm'
]
for ext in extensions:
filename = base_name + ext
if os.path.exists(os.path.join(outdir, filename)):
files.append(filename)
wasm_base = os.path.join(outdir, base_name + '.wasm')
if os.path.exists(wasm_base + '.debug.wasm') and os.path.exists(wasm_base):
# If we have a .wasm.debug.wasm file and a .wasm file, we need to rewrite the
# section in the .wasm file that refers to it. The path that's in there
# is the blaze output path; we want it to be just the filename.
llvm_objcopy = os.path.join(
os.environ['EMSCRIPTEN'], 'llvm-bin/llvm-objcopy')
# First, check to make sure the .wasm file has the header that needs to be
# rewritten.
rtn = subprocess.call([
llvm_objcopy,
'--dump-section=external_debug_info=/dev/null',
wasm_base], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if rtn == 0:
# If llvm-objcopy did not return an error, the external_debug_info section
# must exist, so we're good to continue.
# Next we need to convert length of the filename to LEB128.
# Start by converting the length of the filename to a bit string.
bit_string = '{0:b}'.format(len(base_name + '.wasm.debug.wasm'))
# Pad the bit string with 0s so that its length is a multiple of 7.
while len(bit_string) % 7 != 0:
bit_string = '0' + bit_string
# Break up our bit string into chunks of 7.
# We do this backwards because the final format is little-endian.
final_bytes = bytearray()
for i in reversed(range(0, len(bit_string), 7)):
binary_part = bit_string[i:i + 7]
if i != 0:
# Every chunk except the last one needs to be prepended with '1'.
# The length of each chunk is 7, so that one has an implicit '0'.
binary_part = '1' + binary_part
final_bytes.append(int(binary_part, 2))
# Finally, add the actual filename.
final_bytes.extend(base_name + '.wasm.debug.wasm')
# Write our length + filename bytes to a temp file.
with open('debugsection.tmp', 'wb+') as f:
f.write(final_bytes)
f.close()
# First delete the old section.
subprocess.check_call([
llvm_objcopy,
wasm_base,
'--remove-section=external_debug_info'])
# Rewrite section with the new size and filename from the temp file.
subprocess.check_call([
llvm_objcopy,
wasm_base,
'--add-section=external_debug_info=debugsection.tmp'])
# If we have more than one output file then create tarball
if len(files) > 1:
cmd = ['tar', 'cf', 'tmp.tar'] + files
subprocess.check_call(cmd, cwd=outdir)
os.rename(os.path.join(outdir, 'tmp.tar'), orig_output)
elif len(files) == 1:
# Otherwise, if only have a single output than move it to the expected name
if files[0] != os.path.basename(orig_output):
os.rename(os.path.join(outdir, files[0]), orig_output)
else:
print('emcc.py did not appear to output any known files!')
sys.exit(1)
sys.exit(0)
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
198,
37811,
48553,
1088,
795,
535,
2792,
2239,
13,
198,
198,
1212,
29908,
3058,
9179,
262,
1708,
4959,
13,
198,
198,
16,
13,
48221,
942,
356,
1464,
2792,
284,
2393,
351,
764,
8457,
7552,
... | 2.637712 | 1,888 |
import math
import random
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.utils.data
from mighty.monitor.mutual_info.gcmi import micd
from mighty.monitor.mutual_info.kmeans import MutualInfoKMeans
from mighty.monitor.mutual_info.neural_estimation import MINE_Net, MINE_Trainer
from mighty.utils.common import set_seed
from mighty.utils.constants import BATCH_SIZE
from tqdm import trange
def synthesize_log_softmax_data(n_samples=50000, n_classes=10, p_argmax=0.95, onehot=False):
"""
Simulates a typical trained neural network softmax output probabilities.
Parameters
----------
n_samples : int
No. of samples
n_classes : int
No. of unique classes
p_argmax : float
Network accuracy (softmax probability of the correctly predicted class).
onehot : bool
Return as one-hot encoded vectors (True) or a list of class indices (False).
Returns
-------
x_data : torch.FloatTensor
Simulated softmax probabilities of shape (n_samples, n_classes)
y_labels : torch.LongTensor
Ground truth labels (class indices) of shape
* (n_samples,), if `onehot` is False
* (n_samples, n_classes), otherwise
"""
x_data = torch.randn(n_samples, n_classes)
y_labels = x_data.argmax(dim=1)
x_argmax = x_data[range(x_data.shape[0]), y_labels]
softmax_sum = x_data.exp().sum(dim=1) - x_argmax
x_argmax = torch.log(p_argmax * softmax_sum / (1 - p_argmax))
x_data[range(x_data.shape[0]), y_labels] = x_argmax
if onehot:
y_onehot = torch.zeros(y_labels.shape[0], n_classes, dtype=torch.int64)
y_onehot[torch.arange(y_onehot.shape[0]), y_labels] = 1
y_labels = y_onehot
return x_data, y_labels
def test_gcmi():
"""
Test Gaussian-Copula Mutual Information estimator
"""
outputs, labels = synthesize_log_softmax_data(n_samples=20000, n_classes=10, p_argmax=0.99)
print(type(labels))
estimated = micd(outputs.numpy().T, labels.numpy())
print(f"Gaussian-Copula Mutual Information estimate: {estimated:.3f}")
if __name__ == '__main__':
set_seed(26)
# expected estimated value: log2(10) ~ 3.322
test_kmeans()
test_mine()
test_gcmi()
| [
11748,
10688,
198,
11748,
4738,
198,
198,
11748,
2603,
29487,
8019,
13,
9078,
29487,
355,
458,
83,
198,
11748,
299,
32152,
355,
45941,
198,
11748,
28034,
198,
11748,
28034,
13,
26791,
13,
7890,
198,
6738,
18680,
13,
41143,
13,
21973,
72... | 2.465649 | 917 |
# Copyright 1997 - 2018 by IXIA Keysight
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
from ixnetwork_restpy.base import Base
from ixnetwork_restpy.files import Files
class Evc(Base):
"""The Evc class encapsulates a user managed evc node in the ixnetwork hierarchy.
An instance of the class can be obtained by accessing the Evc property from a parent instance.
The internal properties list will be empty when the property is accessed and is populated from the server using the find method.
The internal properties list can be managed by the user by using the add and remove methods.
"""
_SDM_NAME = 'evc'
@property
def BwProfile(self):
"""An instance of the BwProfile class.
Returns:
obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.elmi.uni.evc.bwprofile.bwprofile.BwProfile)
Raises:
NotFoundError: The requested resource does not exist on the server
ServerError: The server has encountered an uncategorized error condition
"""
from ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.elmi.uni.evc.bwprofile.bwprofile import BwProfile
return BwProfile(self)
@property
def CeVlanIdRange(self):
"""An instance of the CeVlanIdRange class.
Returns:
obj(ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.elmi.uni.evc.cevlanidrange.cevlanidrange.CeVlanIdRange)
Raises:
NotFoundError: The requested resource does not exist on the server
ServerError: The server has encountered an uncategorized error condition
"""
from ixnetwork_restpy.testplatform.sessions.ixnetwork.vport.protocols.elmi.uni.evc.cevlanidrange.cevlanidrange import CeVlanIdRange
return CeVlanIdRange(self)
@property
def DefaultEvc(self):
"""If enabled, default EVC bit is set to 1. It indicates that all CE-VLAN IDs that are not specified in this or other CE-VLAN ID/EVC Map IEs are mapped to this EVC. At most one EVC can be identified as a Default EVC on the UNI. The 'Default EVC' bit has significance only if CE-VLAN ID/EVC Map Type is equal to 'Bundling' (see UNI Status information element octet 3). It must be set to 0 when it is not significant. Default is 0.
Returns:
bool
"""
return self._get_attribute('defaultEvc')
@DefaultEvc.setter
@property
def Enabled(self):
"""If enabled, the EVC is in effect.
Returns:
bool
"""
return self._get_attribute('enabled')
@Enabled.setter
@property
def EvcIdentifier(self):
"""It signifies the content of EVC ID. The length is determined by EVC ID Length. Default is 0.
Returns:
str
"""
return self._get_attribute('evcIdentifier')
@EvcIdentifier.setter
@property
def EvcIdentifierLength(self):
"""It signifies one octet and indicates the length of EVC ID content. Default is 1. Min is 1 and Max is 100.
Returns:
number
"""
return self._get_attribute('evcIdentifierLength')
@EvcIdentifierLength.setter
@property
def EvcStatus(self):
"""Default is New and Active.
Returns:
str(notActive|newAndNotActive|active|newAndActive|partiallyActive|newAndPartiallyActive)
"""
return self._get_attribute('evcStatus')
@EvcStatus.setter
@property
def EvcType(self):
"""It is a drop down of Point-to-Point which is 0 and Multipoint-to-Multipoint which is 1. Default is Point-to-Point.
Returns:
str(pointToPoint|multipointToMultipoint)
"""
return self._get_attribute('evcType')
@EvcType.setter
@property
def ReferenceId(self):
"""Default value is 1. Max two octet maximum value, Min 1.
Returns:
number
"""
return self._get_attribute('referenceId')
@ReferenceId.setter
@property
def UntaggedPriorityTagged(self):
"""If enabled, Untagged/Priority Tagged bit is set to 1. It indicates that this EVC Map Entry identifies the CE VLAN ID for Untagged/Priority Service Frames. The 'Untagged/Priority Tagged' bit has significance only if CE-VLAN ID/EVC Map Type is not equal to 'All to one Bundling' (see UNI Status information element octet 3). It must be set to 0 when it is not significant. Default is 0.
Returns:
bool
"""
return self._get_attribute('untaggedPriorityTagged')
@UntaggedPriorityTagged.setter
def add(self, DefaultEvc=None, Enabled=None, EvcIdentifier=None, EvcIdentifierLength=None, EvcStatus=None, EvcType=None, ReferenceId=None, UntaggedPriorityTagged=None):
"""Adds a new evc node on the server and retrieves it in this instance.
Args:
DefaultEvc (bool): If enabled, default EVC bit is set to 1. It indicates that all CE-VLAN IDs that are not specified in this or other CE-VLAN ID/EVC Map IEs are mapped to this EVC. At most one EVC can be identified as a Default EVC on the UNI. The 'Default EVC' bit has significance only if CE-VLAN ID/EVC Map Type is equal to 'Bundling' (see UNI Status information element octet 3). It must be set to 0 when it is not significant. Default is 0.
Enabled (bool): If enabled, the EVC is in effect.
EvcIdentifier (str): It signifies the content of EVC ID. The length is determined by EVC ID Length. Default is 0.
EvcIdentifierLength (number): It signifies one octet and indicates the length of EVC ID content. Default is 1. Min is 1 and Max is 100.
EvcStatus (str(notActive|newAndNotActive|active|newAndActive|partiallyActive|newAndPartiallyActive)): Default is New and Active.
EvcType (str(pointToPoint|multipointToMultipoint)): It is a drop down of Point-to-Point which is 0 and Multipoint-to-Multipoint which is 1. Default is Point-to-Point.
ReferenceId (number): Default value is 1. Max two octet maximum value, Min 1.
UntaggedPriorityTagged (bool): If enabled, Untagged/Priority Tagged bit is set to 1. It indicates that this EVC Map Entry identifies the CE VLAN ID for Untagged/Priority Service Frames. The 'Untagged/Priority Tagged' bit has significance only if CE-VLAN ID/EVC Map Type is not equal to 'All to one Bundling' (see UNI Status information element octet 3). It must be set to 0 when it is not significant. Default is 0.
Returns:
self: This instance with all currently retrieved evc data using find and the newly added evc data available through an iterator or index
Raises:
ServerError: The server has encountered an uncategorized error condition
"""
return self._create(locals())
def remove(self):
"""Deletes all the evc data in this instance from server.
Raises:
NotFoundError: The requested resource does not exist on the server
ServerError: The server has encountered an uncategorized error condition
"""
self._delete()
def find(self, DefaultEvc=None, Enabled=None, EvcIdentifier=None, EvcIdentifierLength=None, EvcStatus=None, EvcType=None, ReferenceId=None, UntaggedPriorityTagged=None):
"""Finds and retrieves evc data from the server.
All named parameters support regex and can be used to selectively retrieve evc data from the server.
By default the find method takes no parameters and will retrieve all evc data from the server.
Args:
DefaultEvc (bool): If enabled, default EVC bit is set to 1. It indicates that all CE-VLAN IDs that are not specified in this or other CE-VLAN ID/EVC Map IEs are mapped to this EVC. At most one EVC can be identified as a Default EVC on the UNI. The 'Default EVC' bit has significance only if CE-VLAN ID/EVC Map Type is equal to 'Bundling' (see UNI Status information element octet 3). It must be set to 0 when it is not significant. Default is 0.
Enabled (bool): If enabled, the EVC is in effect.
EvcIdentifier (str): It signifies the content of EVC ID. The length is determined by EVC ID Length. Default is 0.
EvcIdentifierLength (number): It signifies one octet and indicates the length of EVC ID content. Default is 1. Min is 1 and Max is 100.
EvcStatus (str(notActive|newAndNotActive|active|newAndActive|partiallyActive|newAndPartiallyActive)): Default is New and Active.
EvcType (str(pointToPoint|multipointToMultipoint)): It is a drop down of Point-to-Point which is 0 and Multipoint-to-Multipoint which is 1. Default is Point-to-Point.
ReferenceId (number): Default value is 1. Max two octet maximum value, Min 1.
UntaggedPriorityTagged (bool): If enabled, Untagged/Priority Tagged bit is set to 1. It indicates that this EVC Map Entry identifies the CE VLAN ID for Untagged/Priority Service Frames. The 'Untagged/Priority Tagged' bit has significance only if CE-VLAN ID/EVC Map Type is not equal to 'All to one Bundling' (see UNI Status information element octet 3). It must be set to 0 when it is not significant. Default is 0.
Returns:
self: This instance with matching evc data retrieved from the server available through an iterator or index
Raises:
ServerError: The server has encountered an uncategorized error condition
"""
return self._select(locals())
def read(self, href):
"""Retrieves a single instance of evc data from the server.
Args:
href (str): An href to the instance to be retrieved
Returns:
self: This instance with the evc data from the server available through an iterator or index
Raises:
NotFoundError: The requested resource does not exist on the server
ServerError: The server has encountered an uncategorized error condition
"""
return self._read(href)
| [
201,
198,
2,
15069,
8309,
532,
2864,
416,
22631,
3539,
26363,
432,
201,
198,
2,
201,
198,
2,
2448,
3411,
318,
29376,
7520,
11,
1479,
286,
3877,
11,
284,
597,
1048,
16727,
257,
4866,
201,
198,
2,
286,
428,
3788,
290,
3917,
10314,
3... | 3.109782 | 3,343 |
import numpy as np
import networkx as nx
from tqdm import tqdm
from sklearn.neighbors import kneighbors_graph
from visualization import *
import metis
| [
11748,
299,
32152,
355,
45941,
198,
11748,
3127,
87,
355,
299,
87,
198,
6738,
256,
80,
36020,
1330,
256,
80,
36020,
198,
6738,
1341,
35720,
13,
710,
394,
32289,
1330,
24813,
394,
32289,
62,
34960,
198,
6738,
32704,
1330,
1635,
198,
19... | 3.2 | 50 |
from rest_framework import serializers
from apps.goods.models import SpecificationOption
# 获取规格选项表信息 序列化器 | [
628,
198,
6738,
1334,
62,
30604,
1330,
11389,
11341,
198,
6738,
6725,
13,
11274,
82,
13,
27530,
1330,
18291,
2649,
19722,
628,
198,
2,
5525,
236,
115,
20998,
244,
164,
100,
226,
43718,
120,
34460,
231,
165,
94,
117,
26193,
101,
46479,... | 1.964286 | 56 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2018 The Blueoil Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =============================================================================
import os
import click
from blueoil.cmd.convert import convert as run_convert
from blueoil.cmd.init import ask_questions, save_config
from blueoil.cmd.predict import predict as run_predict
from blueoil.cmd.train import train as run_train
@click.group(invoke_without_command=True)
@click.pass_context
@main.command(help='Generate blueoil config.')
@click.option(
'-o',
'--output',
help='Path of generated configuration file.',
required=False,
)
@main.command(help='Run training.')
@click.option(
'-c',
'--config',
help='Path of config file.',
required=True,
)
@click.option(
'-e',
'--experiment_id',
help='ID of this training.',
default=None,
required=False,
)
@main.command(help='Convert trained model to binary files.')
@click.option(
'-e',
'--experiment_id',
help='ID of this experiment.',
required=True,
)
@click.option(
'-p',
'--checkpoint',
help='Checkpoint name. e.g. save.ckpt-10001',
default=None,
)
@click.option(
'-t',
'--template',
help='Path of output template directory.',
envvar='OUTPUT_TEMPLATE_DIR',
default=None,
)
@click.option(
"--image_size",
nargs=2,
type=click.Tuple([int, int]),
help="input image size height and width. if these are not provided, it restores from saved experiment config."
"e.g --image_size 320 320",
default=(None, None),
)
@click.option(
"--project_name",
help="project name which generated by convert",
default=None,
)
@main.command(help='Predict by using trained model.')
@click.option(
'-i',
'--input',
help='Directory containing predicted images.',
required=True,
)
@click.option(
'-o',
'--output',
help='Directory to output prediction result.',
required=True,
)
@click.option(
'-e',
'--experiment_id',
help='ID of this experiment.',
required=True,
)
@click.option(
'-p',
'--checkpoint',
help='Checkpoint name. e.g. save.ckpt-10001',
default=None,
)
@click.option(
"--save_images/--no_save_images",
help="Flag of saving images. Default is True.",
default=True,
)
if __name__ == '__main__':
main()
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
198,
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
2,
15069,
2864,
383,
4518,
9437,
46665,
13,
1439,
6923,
33876,
13,
198,
2,
198,
2,
49962,
739,
262,
24843,
13789,
11,... | 2.804243 | 1,037 |
# schema.py
# Copyright (C) 2005-2017 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Compatibility namespace for sqlalchemy.sql.schema and related.
"""
from typing import TYPE_CHECKING
from .sql.base import SchemaVisitor
from .sql.ddl import _CreateDropBase
from .sql.ddl import _DDLCompiles
from .sql.ddl import _DropView
from .sql.ddl import AddConstraint
from .sql.ddl import CreateColumn
from .sql.ddl import CreateIndex
from .sql.ddl import CreateSchema
from .sql.ddl import CreateSequence
from .sql.ddl import CreateTable
from .sql.ddl import DDL
from .sql.ddl import DDLBase
from .sql.ddl import DDLElement
from .sql.ddl import DropColumnComment
from .sql.ddl import DropConstraint
from .sql.ddl import DropIndex
from .sql.ddl import DropSchema
from .sql.ddl import DropSequence
from .sql.ddl import DropTable
from .sql.ddl import DropTableComment
from .sql.ddl import SetColumnComment
from .sql.ddl import SetTableComment
from .sql.ddl import sort_tables
from .sql.ddl import sort_tables_and_constraints
if TYPE_CHECKING:
from .sql.naming import conv
from .sql.schema import _get_table_key
from .sql.schema import BLANK_SCHEMA
from .sql.schema import CheckConstraint
from .sql.schema import Column
from .sql.schema import ColumnCollectionConstraint
from .sql.schema import ColumnCollectionMixin
from .sql.schema import ColumnDefault
from .sql.schema import Constraint
from .sql.schema import DefaultClause
from .sql.schema import DefaultGenerator
from .sql.schema import FetchedValue
from .sql.schema import ForeignKey
from .sql.schema import ForeignKeyConstraint
from .sql.schema import Index
from .sql.schema import MetaData
from .sql.schema import PassiveDefault
from .sql.schema import PrimaryKeyConstraint
from .sql.schema import SchemaItem
from .sql.schema import Sequence
from .sql.schema import Table
from .sql.schema import ThreadLocalMetaData
from .sql.schema import UniqueConstraint
| [
2,
32815,
13,
9078,
198,
2,
15069,
357,
34,
8,
5075,
12,
5539,
262,
16363,
2348,
26599,
7035,
290,
20420,
198,
2,
1279,
3826,
37195,
20673,
2393,
29,
198,
2,
198,
2,
770,
8265,
318,
636,
286,
16363,
2348,
26599,
290,
318,
2716,
73... | 3.058405 | 702 |
from soxs.instrument import instrument_simulator
from soxs.events import write_image, make_exposure_map
from soxs.utils import mylog
import numpy as np
from astropy.io import fits, ascii
from astropy.table import Table
def make_mosaic_events(pointing_list, input_source, out_prefix, exp_time,
instrument, overwrite=False, instr_bkgnd=True,
foreground=True, ptsrc_bkgnd=True, bkgnd_file=None,
no_dither=False, dither_params=None, subpixel_res=False,
aimpt_shift=None, prng=None):
"""
Observe a source from many different pointings.
Parameters
----------
pointing_list : list of tuples or str
Either a list of tuples or a two-column ASCII table, containing
RA and Dec pointings for each mock observation.
input_source : string
The path to the SIMPUT catalog file which contains the input
source(s).
out_prefix : string
The prefix for the event files which will be generated.
exp_time : float, (value, unit) tuple, or :class:`~astropy.units.Quantity`
The exposure time in seconds.
instrument : string
The name of the instrument to use, which picks an instrument
specification from the instrument registry.
overwrite : boolean, optional
Whether or not to overwrite an existing file with the same name.
Default: False
instr_bkgnd : boolean, optional
Whether or not to include the instrumental/particle background.
Default: True
foreground : boolean, optional
Whether or not to include the local foreground.
Default: True
ptsrc_bkgnd : boolean, optional
Whether or not to include the point-source background.
Default: True
bkgnd_file : string, optional
If set, backgrounds will be loaded from this file and not generated
on the fly. Default: None
no_dither : boolean, optional
If True, turn off dithering entirely. Default: False
dither_params : array-like of floats, optional
The parameters to use to control the size and period of the dither
pattern. The first two numbers are the dither amplitude in x and y
detector coordinates in arcseconds, and the second two numbers are
the dither period in x and y detector coordinates in seconds.
Default: [8.0, 8.0, 1000.0, 707.0].
subpixel_res: boolean, optional
If True, event positions are not randomized within the pixels
within which they are detected. Default: False
aimpt_shift : array-like, optional
A two-float array-like object which shifts the aimpoint on the
detector from the nominal position. Units are in arcseconds.
Default: None, which results in no shift from the nominal aimpoint.
prng : :class:`~numpy.random.RandomState` object, integer, or None
A pseudo-random number generator. Typically will only
be specified if you have a reason to generate the same
set of random numbers, such as for a test. Default is None,
which sets the seed based on the system time.
"""
if isinstance(pointing_list, str):
t = ascii.read(pointing_list, format='commented_header', guess=False,
header_start=0, delimiter="\t")
elif not isinstance(pointing_list, Table):
t = Table(np.array(pointing_list), names=["ra", "dec"])
out_list = []
for i, row in enumerate(t):
out_file = f"{out_prefix}_{i}_evt.fits"
out_list.append(out_file)
instrument_simulator(input_source, out_file, exp_time, instrument,
(row["ra"], row["dec"]), overwrite=overwrite,
instr_bkgnd=instr_bkgnd, foreground=foreground,
ptsrc_bkgnd=ptsrc_bkgnd, bkgnd_file=bkgnd_file,
no_dither=no_dither, dither_params=dither_params,
subpixel_res=subpixel_res, aimpt_shift=aimpt_shift,
prng=prng)
t["evtfile"] = out_list
outfile = f"{out_prefix}_event_mosaic.dat"
mylog.info(f"Writing mosaic information to {outfile}.")
t.write(outfile, overwrite=overwrite, delimiter="\t",
format='ascii.commented_header')
return outfile
def make_mosaic_image(evtfile_list, image_file, emin=None, emax=None,
reblock=1, use_expmap=False, expmap_energy=None,
expmap_weights=None, normalize=True, nhistx=16,
nhisty=16, overwrite=False):
"""
Make a single FITS image from a grid of observations. Optionally,
an exposure map can be computed and a flux image may be generated.
Parameters
----------
evtfile_list : filename
The ASCII table produced by :meth:`~soxs.grid.observe_grid_source`
containing the information about the event files and their
locations on the sky.
image_file : filename
The name of the FITS image file to be written. This name will
also be used for the exposure map and flux files if they are
written.
emin : float, (value, unit) tuple, or :class:`~astropy.units.Quantity`, optional
The minimum energy of the photons to put in the image, in keV.
emax : float, (value, unit) tuple, or :class:`~astropy.units.Quantity`, optional
The maximum energy of the photons to put in the image, in keV.
reblock : integer, optional
Supply an integer power of 2 here to make an exposure map
with a different binning. Default: 1
use_expmap : boolean, optional
Whether or not to use (and potentially generate) an exposure map
and a flux map. Default: False
expmap_energy : float, (value, unit) tuple, or :class:`~astropy.units.Quantity`, or NumPy array, optional
The energy in keV to use when computing the exposure map, or
a set of energies to be used with the *weights* parameter. If
providing a set, it must be in keV.
expmap_weights : array-like, optional
The weights to use with a set of energies given in the
*energy* parameter. Used to create a more accurate exposure
map weighted by a range of energies. Default: None
overwrite : boolean, optional
Whether or not to overwrite an existing file with the same name.
Default: False
"""
try:
from reproject.mosaicking import find_optimal_celestial_wcs, \
reproject_and_coadd
from reproject import reproject_interp
except ImportError:
raise ImportError("The mosaic functionality of SOXS requires the "
"'reproject' package to be installed!")
t = ascii.read(evtfile_list, format='commented_header',
guess=False, header_start=0, delimiter="\t")
files = []
for row in t:
evt_file = row["evtfile"]
img_file = evt_file.replace("evt", "img")
if use_expmap:
emap_file = evt_file.replace("evt", "expmap")
make_exposure_map(evt_file, emap_file, energy=expmap_energy,
weights=expmap_weights, normalize=normalize,
overwrite=overwrite, reblock=reblock,
nhistx=nhistx, nhisty=nhisty)
else:
emap_file = None
write_image(evt_file, img_file, emin=emin, emax=emax,
overwrite=overwrite, reblock=reblock)
files.append([img_file, emap_file])
img_hdus = [fits.open(fns[0], memmap=True)[0] for fns in files]
wcs_out, shape_out = find_optimal_celestial_wcs(img_hdus)
img, footprint = reproject_and_coadd(img_hdus, wcs_out, shape_out=shape_out,
reproject_function=reproject_interp,
combine_function='sum')
hdu = fits.PrimaryHDU(img, header=wcs_out.to_header())
hdu.writeto(image_file, overwrite=overwrite)
if use_expmap:
if expmap_energy is None:
raise RuntimeError("The 'expmap_energy' argument must be set if "
"making a mosaicked exposure map!")
emap_hdus = [fits.open(fns[1], memmap=True)[1] for fns in files]
emap, footprint = reproject_and_coadd(
emap_hdus, wcs_out, shape_out=shape_out,
reproject_function=reproject_interp, combine_function='sum')
hdu = fits.PrimaryHDU(emap, header=wcs_out.to_header())
expmap_file = image_file.replace("fits", "expmap")
hdu.writeto(expmap_file, overwrite=overwrite)
with np.errstate(invalid='ignore', divide='ignore'):
flux = img / emap
flux[np.isinf(flux)] = 0.0
flux = np.nan_to_num(flux)
flux[flux < 0.0] = 0.0
hdu = fits.PrimaryHDU(flux, header=wcs_out.to_header())
flux_file = image_file.replace("fits", "flux")
hdu.writeto(flux_file, overwrite=overwrite)
| [
6738,
523,
34223,
13,
259,
43872,
1330,
8875,
62,
14323,
8927,
198,
6738,
523,
34223,
13,
31534,
1330,
3551,
62,
9060,
11,
787,
62,
1069,
26205,
62,
8899,
198,
6738,
523,
34223,
13,
26791,
1330,
616,
6404,
198,
11748,
299,
32152,
355,... | 2.378193 | 3,797 |
import sys
import click
from ghutil.showing import print_json
API_ENDPOINT = 'https://api.github.com'
| [
11748,
25064,
198,
11748,
3904,
198,
6738,
220,
220,
24997,
22602,
13,
1477,
7855,
1330,
3601,
62,
17752,
198,
198,
17614,
62,
1677,
6322,
46,
12394,
796,
705,
5450,
1378,
15042,
13,
12567,
13,
785,
6,
198
] | 2.837838 | 37 |
import sys
from python_qt_binding.QtCore import Qt, QMetaType, QDataStream, QVariant, pyqtSignal
from python_qt_binding import loadUi
from rqt_gui_py.plugin import Plugin
from python_qt_binding.QtWidgets import QWidget, QTreeWidget, QTreeWidgetItem,QListWidgetItem, \
QSlider, QGroupBox, QVBoxLayout, QLabel, QLineEdit, QListWidget, QAbstractItemView, QFileDialog, QDoubleSpinBox, QMessageBox, \
QInputDialog, QShortcut
from python_qt_binding.QtGui import QDoubleValidator, QKeySequence, QPixmap, QTransform
from status_msg import StatusMsg
from quarter_field import QuarterField, RobotInformation
| [
11748,
25064,
198,
6738,
21015,
62,
39568,
62,
30786,
13,
48,
83,
14055,
1330,
33734,
11,
1195,
48526,
6030,
11,
1195,
6601,
12124,
11,
1195,
23907,
415,
11,
12972,
39568,
11712,
282,
198,
6738,
21015,
62,
39568,
62,
30786,
1330,
3440,
... | 3.075377 | 199 |
# Zulip, Inc's internal git plugin configuration.
# The plugin and example config are under api/integrations/
# Leaving all the instructions out of this file to avoid having to
# sync them as we update the comments.
if False: from typing import Dict, Optional, Text
ZULIP_USER = "commit-bot@zulip.com"
ZULIP_API_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
# commit_notice_destination() lets you customize where commit notices
# are sent to.
#
# It takes the following arguments:
# * repo = the name of the git repository
# * branch = the name of the branch that was pushed to
# * commit = the commit id
#
# Returns a dictionary encoding the stream and subject to send the
# notification to (or None to send no notification, e.g. for ).
#
# The default code below will send every commit pushed to "master" to
# * stream "commits"
# * topic "master"
# And similarly for branch "test-post-receive" (for use when testing).
# Modify this function to change how commits are displayed; the most
# common customization is to include a link to the commit in your
# graphical repository viewer, e.g.
#
# return '!avatar(%s) [%s](https://example.com/commits/%s)\n' % (author, subject, commit_id)
ZULIP_API_PATH = "/home/zulip/zulip/api"
ZULIP_SITE = "https://zulip.com"
| [
2,
1168,
377,
541,
11,
3457,
338,
5387,
17606,
13877,
8398,
13,
198,
2,
383,
13877,
290,
1672,
4566,
389,
739,
40391,
14,
18908,
9143,
14,
198,
198,
2,
38068,
477,
262,
7729,
503,
286,
428,
2393,
284,
3368,
1719,
284,
198,
2,
1751... | 3.379679 | 374 |
"""Define the Blueprint for the Link Service"""
from flask import Blueprint, request, jsonify, redirect
from werkzeug.exceptions import BadRequest, InternalServerError, NotFound
from flask_cors import cross_origin
# Controller
from abitly.services.link.controller import (validate_request_body,
get_generated_url,
get_original_url)
link = Blueprint('link', __name__, url_prefix='/link')
@link.route('/', methods=['POST', 'OPTIONS'])
@cross_origin(origin='*', headers=['Origin', 'X-Requested-With',
'Content-Type',
'Accept',
'Authorization'])
def create_link():
"""Verifies if the original_url is already stored:
- If not, creates a new generated_url and saves the original_url.
- If yes, just returns the previously generated_url.
Returns
-------
response : Response
JSON response.
Raises
------
exception : HTTPException
One of the HTTPExceptions.
"""
try:
# Validates the json format of the request
original_url = validate_request_body(request.get_json())
# Gets the saved generated_url or creates a new one
generated_url = get_generated_url(original_url)
return jsonify(statusCode=201, status='Created',
generatedUrl=generated_url,
originalUrl=original_url
), 201
except (BadRequest, InternalServerError) as error:
raise error
@link.route('/<url>')
| [
37811,
7469,
500,
262,
39932,
329,
262,
7502,
4809,
37811,
198,
198,
6738,
42903,
1330,
39932,
11,
2581,
11,
33918,
1958,
11,
18941,
198,
6738,
266,
9587,
2736,
1018,
13,
1069,
11755,
1330,
7772,
18453,
11,
18628,
10697,
12331,
11,
1892... | 2.291492 | 717 |
import os
def detect_cpus():
'''Detects the number of CPUs on a system. Cribbed from pp.'''
# Linux, Unix and MacOS:
if hasattr(os, "sysconf"):
if "SC_NPROCESSORS_ONLN" in os.sysconf_names:
# Linux & Unix:
ncpus = int_or_zero(os.sysconf("SC_NPROCESSORS_ONLN"))
else:
# OSX:
ncpus = int_or_zero(os.popen2("sysctl -n hw.ncpu")[1].read())
# Windows:
if "NUMBER_OF_PROCESSORS" in os.environ:
ncpus = int_or_zero(os.environ["NUMBER_OF_PROCESSORS"])
if ncpus > 0:
return ncpus
return 1 # Default
| [
11748,
28686,
198,
198,
4299,
4886,
62,
13155,
385,
33529,
198,
220,
220,
220,
705,
7061,
47504,
82,
262,
1271,
286,
32340,
319,
257,
1080,
13,
327,
822,
3077,
422,
9788,
2637,
7061,
198,
220,
220,
220,
1303,
7020,
11,
33501,
290,
4... | 1.944805 | 308 |
# !/usr/bin/env python
# -*- coding: UTF-8 -*-
import pprint
from base import BaseObject
from base import FileIO
class GraphNodeDefGenerator(BaseObject):
""" Build GitHub Node Definition for Graphviz """
def __init__(self,
stylesheet_path: str,
is_debug: bool = True):
"""
Created:
31-Dec-2019
craig.trim@ibm.com
* refactored out of 'node-builder'
https://github.ibm.com/GTS-CDO/unstructured-analytics/issues/1681#issuecomment-16877187
* renamed from 'node-line-generator'
https://github.ibm.com/GTS-CDO/unstructured-analytics/issues/1681#issuecomment-16877277
:param is_debug:
if True increase log output at DEBUG level
"""
BaseObject.__init__(self, __name__)
self._is_debug = is_debug
self._config = FileIO.file_to_yaml_by_relative_path(stylesheet_path)
@staticmethod
def _cleanse_node_label(node_label: str) -> str:
"""
Purpose:
Provide generic node label cleaning for Graphviz
:param node_label:
a node label
:return:
a cleansed node label
"""
node_label = node_label.replace('"', '') # GIT-1651-16811213
return node_label
def process(self,
node_id: str,
node_type: str,
node_label: str,
comment: str,
**kwargs) -> list:
"""
:param node_id:
the Unique Node identifier
:param node_type:
the type of Node
e.g., 'issue', 'commit', 'pull-request'
:param node_label:
the display label for the Node
:param comment:
a docstring comment for GraphViz
:return:
the lines necessary to render a Graphviz Node
"""
node_type = node_type.lower().strip()
def _node_style() -> dict:
"""
:return:
the Node Styling block from the Graphviz Stylesheet definition
"""
for a_style in self._config['nodes']:
for style in a_style:
if style.lower().strip() == node_type:
return a_style[style]
self.logger.warning('\n'.join([
f"Node Style Not Found (name={node_type})",
pprint.pformat(self._config['nodes'])]))
raise ValueError
d_node_style = _node_style()
lines = [
f"# {comment}",
f"{node_id}",
"["]
explicit_keys = d_node_style.keys()
explicit_keys = [key for key in explicit_keys if key not in kwargs]
explicit_keys = [key for key in explicit_keys if _is_valid_key(key)]
for k in explicit_keys: # explicit styles via stylesheet
value = d_node_style[k]
lines.append(f"\t{k}=\"{value}\"")
kwarg_keys = kwargs.keys()
kwarg_keys = [key for key in kwarg_keys if _is_valid_key(key)]
for k in kwarg_keys: # dynamic styles via param
value = kwargs[k]
lines.append(f"\t{k}=\"{value}\"")
lines.append(f"\tlabel=\"{label()}\"")
lines.append("]\n")
return lines
| [
2,
5145,
14,
14629,
14,
8800,
14,
24330,
21015,
198,
2,
532,
9,
12,
19617,
25,
41002,
12,
23,
532,
9,
12,
628,
198,
11748,
279,
4798,
198,
198,
6738,
2779,
1330,
7308,
10267,
198,
6738,
2779,
1330,
9220,
9399,
628,
198,
4871,
2968... | 1.986913 | 1,681 |
# -*- coding: utf-8 -*-
import io
import logging
from azure.storage.blob import BlobClient
from azure.core.exceptions import ResourceNotFoundError
DEFAULT_BUFFER_SIZE = 4 * 1024 ** 2
WHENCE_START = 0
WHENCE_CURRENT = 1
WHENCE_END = 2
WHENCE_CHOICES = (WHENCE_START, WHENCE_CURRENT, WHENCE_END)
logger = logging.getLogger(__name__)
class _Reader:
"""Read an Azure Blob Storage file."""
class Blob(io.BufferedIOBase):
"""Reads bytes from Azure Blob Storage"""
def __init__(
self,
client: BlobClient,
concurrency: int,
buffer_size: int = DEFAULT_BUFFER_SIZE,
) -> None:
"""Reads bytes from Azure Blob Storage
:param azure.storage.blob.BlobClient client:
:param int concurrency
:optional int buffer_size: how much of the stream to store in memory
:raises azure.core.exceptions.ResourceNotFoundError: Raised when the blob to read from does not exist.
"""
self.client = client
if self.client.exists() is False:
raise ResourceNotFoundError(f"blob {self.client.blob_name} not found in {self.client.container_name}")
# Acquire a lease on the blob, so that it can not be modified or deleted while we stream it
# The duration is set to 15 seconds, so if the process were to halt mid-way, the lease will automatically expire
self._blob_lease = self.client.acquire_lease(lease_duration=15)
try:
self.size = self.client.get_blob_properties()["size"]
except KeyError:
self.size = 0
self._reader = _Reader(self.client, self.size, concurrency)
self._position = 0
self._buffer = _Buffer(buffer_size)
# Override some methods from io.IOBase.
def close(self) -> None:
"""Release the blob lease, flush and close this stream."""
self._blob_lease.release()
self._blob_lease = None
self.client = None
self._reader = None
# io.BufferedIOBase methods.
def seek(self, offset: int, whence: int = WHENCE_START) -> int:
"""Seek to the specified position.
:param int offset: The offset in bytes.
:param int whence: Where the offset is from.
Returns the position after seeking."""
logger.debug(f"seeking to offset: {offset} whence: {whence}")
if whence not in WHENCE_CHOICES:
raise ValueError(f"invalid whence {whence}, expected one of {WHENCE_CHOICES}")
if whence == WHENCE_START:
new_position = offset
elif whence == WHENCE_CURRENT:
new_position = self._position + offset
else:
new_position = self.size + offset
self._position = new_position
self._reader.seek(new_position)
logger.debug(f"current_pos: {self._position}")
self._buffer.empty()
return self._position
def tell(self) -> int:
"""Return the current position within the file."""
return self._position
def read(self, size: int) -> bytes:
"""Read up to size bytes from the object and return them."""
if size == 0:
return b""
# Return unused data first
if len(self._buffer) >= size:
return self._read_from_buffer(size)
if self._position == self.size:
return self._read_from_buffer()
self._fill_buffer()
return self._read_from_buffer(size)
# Internal methods.
def _read_from_buffer(self, size: int = -1) -> bytes:
"""Remove at most size bytes from our buffer and return them."""
logger.debug(f"reading {size} bytes from {len(self._buffer)} byte-long buffer")
size = size if size >= 0 else len(self._buffer)
part = self._buffer.read(size)
self._position += len(part)
# logger.debug(f'part: {part}')
return part
# Allows usage in a `with` statement
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
198,
11748,
33245,
198,
11748,
18931,
198,
198,
6738,
35560,
495,
13,
35350,
13,
2436,
672,
1330,
1086,
672,
11792,
198,
6738,
35560,
495,
13,
7295,
13,
1069,
11755,
133... | 2.489186 | 1,572 |
# Copyright 2021-2022 Toyota Research Institute. All rights reserved.
import numpy as np
from dgp.agents.base_agent import AgentSnapshotList
from dgp.annotations.ontology import BoundingBoxOntology
from dgp.constants import FEATURE_TYPE_ID_TO_KEY
from dgp.utils.structures.bounding_box_2d import BoundingBox2D
class AgentSnapshot2DList(AgentSnapshotList):
"""Container for 2D agent list.
Parameters
----------
ontology: BoundingBoxOntology
Ontology for 2D bounding box tasks.
TODO : Add support for BoundingBox2DAnnotationList.
boxlist: list[BoundingBox2D]
List of BoundingBox2D objects. See `utils/structures/bounding_box_2d`
for more details.
"""
@classmethod
def load(cls, agent_snapshots_pb2, ontology, feature_ontology_table):
"""Loads agent snapshot list from proto into a canonical format for consumption in __getitem__ function in
BaseDataset.
Format/data structure for agent types will vary based on task.
Parameters
----------
agent_snapshots_pb2: dgp.proto.agent.AgentsSlice.agent_snapshots or dgp.proto.agent.AgentTrack.agent_snapshots
A proto message holding list of agent snapshot.
ontology: Ontology
Ontology for given agent.
feature_ontology_table: dict, default: None
A dictionary mapping feature type key(s) to Ontology(s), i.e.:
{
"agent_2d": AgentFeatureOntology[<ontology_sha>],
"agent_3d": AgentFeatureOntology[<ontology_sha>]
}
Returns
-------
AgentSnapshot2DList
Agent Snapshot list object instantiated from proto object.
"""
boxlist = []
for agent_snapshot_2d in agent_snapshots_pb2:
feature_type = agent_snapshot_2d.agent_snapshot_2D.feature_type
feature_ontology = feature_ontology_table[FEATURE_TYPE_ID_TO_KEY[feature_type]]
boxlist.append(
BoundingBox2D(
box=np.float32([
agent_snapshot_2d.agent_snapshot_2D.box.x, agent_snapshot_2d.agent_snapshot_2D.box.y,
agent_snapshot_2d.agent_snapshot_2D.box.w, agent_snapshot_2d.agent_snapshot_2D.box.h
]),
class_id=ontology.class_id_to_contiguous_id[agent_snapshot_2d.agent_snapshots_2D.class_id],
instance_id=agent_snapshot_2d.agent_snapshot_2D.instance_id,
color=ontology.colormap[agent_snapshot_2d.agent_snapshot_2D.class_id],
attributes=dict([(feature_ontology.id_to_name[feature_id], feature)
for feature_id, feature in enumerate(agent_snapshot_2d.agent_snapshot_2D.features)]
),
)
)
return cls(ontology, boxlist)
def __getitem__(self, index):
"""Return a single 3D bounding box"""
return self.boxlist[index]
def render(self):
"""TODO: Batch rendering function for bounding boxes."""
@property
def class_ids(self):
"""Return class ID for each box, with ontology applied:
0 is background, class IDs mapped to a contiguous set.
"""
return np.int64([box.class_id for box in self.boxlist])
@property
def attributes(self):
"""Return a list of dictionaries of attribute name to value."""
return [box.attributes for box in self.boxlist]
@property
| [
2,
15069,
33448,
12,
1238,
1828,
20182,
4992,
5136,
13,
220,
1439,
2489,
10395,
13,
198,
198,
11748,
299,
32152,
355,
45941,
198,
198,
6738,
288,
31197,
13,
49638,
13,
8692,
62,
25781,
1330,
15906,
43826,
9442,
8053,
198,
6738,
288,
3... | 2.233291 | 1,586 |
#!/usr/bin/env python
import _init_paths
import numpy as np
import cv2
import os
import sys
import time
import argparse
import heapq
import random
import csv
import glob
from utils.timer import Timer
from shutil import copyfile
#def add_path(path):
# if path not in sys.path:
# sys.path.insert(0, path)
#caffe_dir = '/home/ivskaikai/Deep_Learning_Framework/caffe'
#python_path=os.path.join(caffe_dir,'python')
#add_path(python_path)
import caffe
import numpy as np
import matplotlib.pyplot as plt
import time
caffe.set_mode_gpu()
def video_list_to_blob(videos):
"""Convert a list of videos into a network input.
Assumes videos are already prepared (means subtracted, BGR order, ...).
"""
shape = videos[0].shape
num_videos = len(videos)
blob = np.zeros((num_videos, shape[0], shape[1], shape[2], shape[3]),
dtype=np.float32)
for i in xrange(num_videos):
blob[i] = videos[i]
# Move channels (axis 3) to axis 1
# Axis order will become: (batch elem, channel, length, height, width)
channel_swap = (0, 3, 4, 1, 2)
blob = blob.transpose(channel_swap)
return blob
def _get_image_blob(im):
"""Converts an image into a network input.
Arguments:
im (ndarray): a color image in BGR order
Returns:
blob (ndarray): a data blob holding an image pyramid
im_scale_factors (list): list of image scales (relative to im) used
in the image pyramid
"""
im_orig = im.astype(np.float32, copy=True)
for i in range(im_orig.shape[-1]):
img = im_orig[:,:,:,i]
img -= [ 90, 98, 102]
im_orig[:,:,:,i] = img
processed_ims = []
processed_ims.append(im_orig)
# Create a blob to hold the input images
blob = video_list_to_blob(processed_ims)
return blob
def _get_blobs(im):
"""Convert an image and RoIs within that image into network inputs."""
blobs = {'data' : None, 'rois' : None}
blobs['data']= _get_image_blob(im)
return blobs
def demo(net, image_name,iteration):
"""Detect object classes in an image using pre-computed object proposals."""
cap = cv2.VideoCapture(image_name)
CONF_THRESH = args.heat
count = 0
total_time = 0
width = 720
height = 480
CNNwidth = 112
CNNheight = 112
length = 16
image_queue = np.zeros((CNNheight, CNNwidth,3,length), dtype=np.float32)
for idx,path in enumerate(task.split('/')[1:-1]):
if idx == 0:
out_name = path
else:
out_name += '-'+path
out_path = 'test_video'
if not os.path.exists(out_path):
os.makedirs(out_path)
for path in image_name.split('/')[1:-1]:
out_path += '/'+path
if not os.path.exists(out_path):
os.makedirs(out_path)
fourcc = cv2.VideoWriter_fourcc(*'MP4V')
video_name = image_name.split('/')[-1]
capSize = (width, height)
out = cv2.VideoWriter(os.path.join(out_path,video_name+'_'+out_name+'_'+iteration+'_'+dataset+'_'+str(CONF_THRESH)+'.mov'),fourcc, cap.get(5), capSize)
while(cap.isOpened()):
ret, frame = cap.read()
if ret:
frame = cv2.resize(frame, (width, height), interpolation = cv2.INTER_LINEAR)
#frame = cv2.flip(frame,-1)
_t = {'im_preproc': Timer(), 'im_net' : Timer(), 'im_postproc': Timer(), 'misc' : Timer()}
timer = Timer()
timer.tic()
_frame = cv2.resize(frame, (CNNwidth, CNNheight), interpolation = cv2.INTER_LINEAR)
if count == 0:
for i in range(length):
image_queue[:,:,:,i] = _frame
else:
image_queue[:,:,:,:length-1] = image_queue[:,:,:,1:]
image_queue[:,:,:,length-1] = _frame
_t['im_preproc'].tic()
blobs = _get_blobs(image_queue)
net.blobs['data'].reshape(*(blobs['data'].shape))
net.blobs['data'].data[...] = blobs['data']
_t['im_preproc'].toc()
_t['im_net'].tic()
blobs_out = net.forward()
_t['im_net'].toc()
#prob = blobs_out['prob']
#################################
#if 'convcls' in net.blobs:
# _t['im_postproc'].tic()
# top1_map = net.blobs['convcls'].data[0,prob[0].argmax(),0,:,:]
# #fcact = net.params['fcact'][0].data
#
# #top1_map = fcact[1,:].reshape((-1,1,1)) * top1_map
#
# #top1_map = np.sum(top1_map,axis=0)
# top1_map = top1_map.reshape((1,top1_map.shape[0],top1_map.shape[1]))
#
# top1_map = top1_map.transpose((1,2,0))
# top1_map = cv2.resize(top1_map,(width, height),interpolation=cv2.INTER_CUBIC)
# max_n = np.amax(top1_map)
# min_n = np.amin(top1_map)
# top1_map = top1_map*(-120/(max_n-min_n))+(120*max_n/(max_n-min_n))
# matrix = np.zeros((height,width,3),dtype=np.uint8)
# #for index_y in range(CNNheight):
# # for index_x in range(CNNwidth):
# # matrix[index_y][index_x][0] = int(top1_map[index_y][index_x])
# # matrix[index_y][index_x][1] = 255*0.7
# # matrix[index_y][index_x][2] = 255*0.7
# matrix[:,:,0] = top1_map[:,:]
# matrix[:,:,1] = 255
# matrix[:,:,2] = 255
#
# bgrimg = cv2.cvtColor(matrix, cv2.COLOR_HSV2BGR)
# #cv2.imshow('heat map',bgrimg)
# frame = cv2.addWeighted(frame,0.7,bgrimg,0.3,0)
# _t['im_postproc'].toc()
if 'convheatmap' in net.blobs:
_t['im_postproc'].tic()
top1_map = net.blobs['convheatmap'].data[0,0,0,:,:]
if np.max(top1_map) > args.heat:
top1_map = top1_map.reshape((1,top1_map.shape[0],top1_map.shape[1]))
top1_map = top1_map.transpose((1,2,0))
top1_map = cv2.resize(top1_map,(width, height),interpolation=cv2.INTER_CUBIC)
max_n = np.amax(top1_map)
min_n = np.amin(top1_map)
top1_map = top1_map*(-120/(max_n-min_n))+(120*max_n/(max_n-min_n))
matrix = np.zeros((height,width,3),dtype=np.uint8)
matrix[:,:,0] = top1_map[:,:]
matrix[:,:,1] = 255
matrix[:,:,2] = 255
else:
matrix = np.zeros((height,width,3),dtype=np.uint8)
matrix[:,:,0] = 120
matrix[:,:,1] = 255
matrix[:,:,2] = 255
#for index_y in range(CNNheight):
# for index_x in range(CNNwidth):
# matrix[index_y][index_x][0] = int(top1_map[index_y][index_x])
# matrix[index_y][index_x][1] = 255*0.7
# matrix[index_y][index_x][2] = 255*0.7
#if prob[0].argmax()!=0:
# matrix[:,:,0] = top1_map[:,:]
# matrix[:,:,1] = 255
# matrix[:,:,2] = 255
#else:
# matrix[:,:,0] = 120
# matrix[:,:,1] = 255
# matrix[:,:,2] = 255
bgrimg = cv2.cvtColor(matrix, cv2.COLOR_HSV2BGR)
#cv2.imshow('heat map',bgrimg)
frame = cv2.addWeighted(frame,0.7,bgrimg,0.3,0)
_t['im_postproc'].toc()
#######################################
frameshape = frame.shape
#print prob[0].argmax()
#print prob[0].max()
print 'im_detect: net {:.3f}s preproc {:.3f}s postproc {:.3f}s misc {:.3f}s' \
.format(_t['im_net'].average_time,
_t['im_preproc'].average_time, _t['im_postproc'].average_time,
_t['misc'].average_time)
#if prob[0].argmax() == 1:
# cv2.circle(frame,(int(frameshape[1]*0.7),int(frameshape[0]*0.2)), 10, (0,0,255), -1)
#elif prob[0].argmax() == 2:
# cv2.circle(frame,(int(frameshape[1]*0.3),int(frameshape[0]*0.2)), 10, (0,0,255), -1)
#else:
# cv2.circle(frame,(int(frameshape[1]*0.5),int(frameshape[0]*0.2)), 10, (0,255,0), -1)
timer.toc()
total_time += timer.total_time
out.write(frame)
if args.show == 1:
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
count += 1
#Calculate frame per second
print 1 / (total_time / count)
def parse_args():
"""Parse input arguments."""
parser = argparse.ArgumentParser(description='Faster R-CNN demo')
parser.add_argument('--def', dest='prototxt',
help='prototxt file defining the network',
default=None, type=str)
parser.add_argument('--net', dest='caffemodel',
help='model to test',
default=None, type=str)
parser.add_argument('--video', dest='video', help='video',
default='video/FILE2171.mp4', type=str)
parser.add_argument('--heat', dest='heat', help='heat',
default=5, type=float)
parser.add_argument('--show', dest='show', help='show',
default=1, type=int)
args = parser.parse_args()
return args
if __name__ == '__main__':
args = parse_args()
iteration = args.caffemodel.split('/')[-1].split('_')[-1].split('.')[0]
dataset = args.caffemodel.split('/')[-2]
task=args.prototxt
prototxt = args.prototxt
caffemodel = args.caffemodel
net = caffe.Net(prototxt, caffemodel, caffe.TEST)
video = args.video
demo(net,video,iteration)
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
198,
11748,
4808,
15003,
62,
6978,
82,
198,
11748,
299,
32152,
355,
45941,
198,
11748,
269,
85,
17,
198,
11748,
28686,
198,
11748,
25064,
198,
11748,
640,
198,
11748,
1822,
29572,
198,
11748,... | 1.819805 | 5,655 |
from loguru import logger
from flexget import entry, plugin
from flexget.components.emby.api_emby import EmbyApi, EmbyAuth
from flexget.components.emby.emby_util import SCHEMA_SERVER, get_field_map
from flexget.event import event
logger = logger.bind(name='emby_lookup')
class EmbyLookup:
"""
Preforms Emby Lookup
Example:
emby_lookup:
host: http://localhost:8096
username: <username>
apikey: <apikey>
return_host: wan
"""
auth = {}
schema = {**SCHEMA_SERVER}
@entry.register_lazy_lookup('emby_lookup')
# Run after series and metainfo series and imdb
@plugin.priority(110)
@property
def movie_identifier(self):
"""Returns the plugin main identifier type"""
return 'emby_movie_id'
@property
def series_identifier(self):
"""Returns the plugin main identifier type"""
return 'emby_serie_id'
@event('plugin.register')
| [
6738,
2604,
14717,
1330,
49706,
198,
198,
6738,
7059,
1136,
1330,
5726,
11,
13877,
198,
6738,
7059,
1136,
13,
5589,
3906,
13,
368,
1525,
13,
15042,
62,
368,
1525,
1330,
2295,
1525,
32,
14415,
11,
2295,
1525,
30515,
198,
6738,
7059,
11... | 2.435768 | 397 |
print(" 12! ", fattoriale(12))
print(" 18! ", fattoriale(18))
print(" 33! ", fattoriale(33))
| [
201,
198,
4798,
7203,
1105,
0,
33172,
277,
1078,
5132,
68,
7,
1065,
4008,
201,
198,
4798,
7203,
1248,
0,
33172,
277,
1078,
5132,
68,
7,
1507,
4008,
201,
198,
4798,
7203,
4747,
0,
33172,
277,
1078,
5132,
68,
7,
2091,
4008,
201,
198... | 2.227273 | 44 |
import rpy2.rinterface as rinterface
import rpy2.robjects.conversion as conversion
import rpy2.robjects as ro
import rpy2_arrow.pyarrow_rarrow as pyr
import rpy2_arrow.r6b as r6b_ar
import rpy2_R6.r6b as r6b
import pyarrow
import pytest
@pytest.mark.xfail
@pytest.mark.parametrize(
'pyarrow_constructor,pyr_py2r',
[
(pyarrow.array, pyr.pyarrow_to_r_array),
(pyarrow.chunked_array, pyr.pyarrow_to_r_chunkedarray)
]
)
| [
11748,
374,
9078,
17,
13,
81,
39994,
355,
374,
39994,
198,
11748,
374,
9078,
17,
13,
22609,
752,
82,
13,
1102,
9641,
355,
11315,
198,
11748,
374,
9078,
17,
13,
22609,
752,
82,
355,
686,
198,
11748,
374,
9078,
17,
62,
6018,
13,
907... | 2.186275 | 204 |
#!/usr/bin/env python3
from setuptools import setup
if __name__ == "__main__":
setup()
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
18,
198,
198,
6738,
900,
37623,
10141,
1330,
9058,
198,
198,
361,
11593,
3672,
834,
6624,
366,
834,
12417,
834,
1298,
198,
220,
220,
220,
9058,
3419,
198
] | 2.583333 | 36 |
import matplotlib.pyplot as plt
import numpy as np
import spikewarp as sw
def cluster_pair_plots(meta_dict, dh):
"""
Function for plotting meta analyses of cluster pair analyses
"""
data_to_plot = [meta_dict['quadruplet']['proportion_of_pairwise_conj_trials_by_single_unit_ENOUGH_QUAD_CONJ'], meta_dict['all_clusters']['proportion_of_pairwise_conj_trials_by_single_unit_ALL']]
sw.normal_histo_plot(data_to_plot, dh.state_corr_meta_stats + 'proportion_of_pairwise_conj_trials_by_single_unit_ENOUGH_QUAD_CONJ_FOR_TEST_AND_ALL', bins=20, histo_range=[0.0, 1.0], x_axis_left_buffer=0.01, x_axis_label="Proportion", y_axis_label="Frequency", custom_x_tick_locators=[1.0, 0.2], custom_y_tick_locators=[5, 5], alpha=0.78, labels=['Quadruplets', "All"])
data_to_plot = [meta_dict['quadruplet']['proportion_of_pairwise_conj_trials_by_single_unit_ENOUGH_QUAD_CONJ'], meta_dict['quadruplet']['proportion_of_pairwise_conj_trials_by_single_unit_ENOUGH_QUAD_CONJ_CORR']]
sw.normal_histo_plot(data_to_plot, dh.state_corr_meta_stats + 'proportion_of_pairwise_conj_trials_by_single_unit_ENOUGH_QUAD_CONJ_ENOUGH_QUAD_CONJ_FOR_TEST_AND_CORR', bins=20, histo_range=[0.0, 1.0], x_axis_left_buffer=0.01, x_axis_label="Proportion", y_axis_label="Frequency", custom_x_tick_locators=[1.0, 0.2], custom_y_tick_locators=[5, 5], alpha=0.78, labels=['Quadruplets enough conj for test', 'Quadruplets enough conj for test corr'])
############## EXPLAINED VARIANCE ##############
# TRIPLETS
exp_var_ratios = np.asarray(meta_dict['triplet']['explained_variance_ratio_by_PCA_component'])
if (exp_var_ratios != []):
plt.figure()
plt.scatter(exp_var_ratios[:, 0], exp_var_ratios[:, 1])
plt.gca().set_xlim([0.0, 1.0]); plt.gca().set_ylim([0.0, 1.0])
plt.savefig(dh.pca_explained_var_meta_stats + 'exp_var_ratios_triplets_pca_comp_0_and_1.pdf')
plt.close()
plt.figure()
plt.bar(['1st', '2nd', '3rd'], np.mean(exp_var_ratios, axis=0))
plt.savefig(dh.pca_explained_var_meta_stats + 'mean_exp_var_ratios_triplets.pdf')
plt.close()
# QUADRUPLETS
exp_var_ratios = np.asarray(meta_dict['quadruplet']['explained_variance_ratio_by_PCA_component'])
if (exp_var_ratios != []):
plt.figure()
plt.scatter(exp_var_ratios[:, 0], exp_var_ratios[:, 1])
plt.gca().set_xlim([0.0, 1.0]); plt.gca().set_ylim([0.0, 1.0])
plt.savefig(dh.pca_explained_var_meta_stats + 'exp_var_ratios_quadruplets_pca_comp_0_and_1.pdf')
plt.close()
plt.figure()
plt.scatter(exp_var_ratios[:, 2], exp_var_ratios[:, 3])
plt.gca().set_xlim([0.0, 1.0]); plt.gca().set_ylim([0.0, 1.0])
plt.savefig(dh.pca_explained_var_meta_stats + 'exp_var_ratios_quadruplets_pca_comp_2_and_3.pdf')
plt.close()
plt.figure()
plt.bar(['1st', '2nd', '3rd', '4th'], np.mean(exp_var_ratios, axis=0))
plt.gca().set_xlabel('PCA component'); plt.gca().set_ylabel('Proportion of\nexplained variance');
plt.savefig(dh.pca_explained_var_meta_stats + 'mean_exp_var_ratios_quadruplets.pdf')
plt.close()
############## STATE CORR ##############
sw.normal_histo_plot([meta_dict['quadruplet']['cluster_pairs_state_corr_pvals']], dh.state_corr_meta_stats + 'cluster_pairs_state_corr_pvals', bins=20, histo_range=[0.0, 1.0], x_axis_left_buffer=0.01, x_axis_label="$p value$", y_axis_label="Frequency", custom_x_tick_locators=[1.0, 0.2], custom_y_tick_locators=[5, 5], alpha=0.78)
sw.normal_histo_plot([np.asarray(meta_dict['quadruplet']['cluster_pairs_state_corr_rvals'])[np.argwhere(np.asarray(meta_dict['quadruplet']['cluster_pairs_state_corr_pvals']) < 0.05).flatten()]], dh.state_corr_meta_stats + 'cluster_pairs_state_corr_rvals_quadruplets', bins=40, histo_range=[-1.0, 1.0], x_axis_left_buffer=0.01, x_axis_label="$r$", y_axis_label="Frequency", custom_x_tick_locators=[1.0, 0.2], custom_y_tick_locators=[5, 5], alpha=0.78)
sw.normal_histo_plot([np.asarray(meta_dict['quadruplet']['cluster_pairs_state_corr_r2vals'])[np.argwhere(np.asarray(meta_dict['quadruplet']['cluster_pairs_state_corr_pvals']) < 0.05).flatten()]], dh.state_corr_meta_stats + 'cluster_pairs_state_corr_r2vals_quadruplets', bins=20, histo_range=[0.0, 1.0], x_axis_left_buffer=0.01, x_axis_label="$r^2$", y_axis_label="Frequency", custom_x_tick_locators=[1.0, 0.2], custom_y_tick_locators=[5, 5], alpha=0.78)
############## DIFFERENCES PREDICTION AND CORR ##############
sw.normal_histo_plot([meta_dict['quadruplet']['difference_prediction_from_state_pvalues']], dh.diff_corr_meta_stats + 'difference_prediction_from_state_pvalues', bins=20, histo_range=[0.0, 1.0], x_axis_left_buffer=0.01, x_axis_label="$p value$", y_axis_label="Frequency", custom_x_tick_locators=[1.0, 0.2], custom_y_tick_locators=[5, 5], alpha=0.78)
sw.normal_histo_plot([np.asarray(meta_dict['quadruplet']['difference_prediction_from_state_rvalues'])[np.argwhere(np.asarray(meta_dict['quadruplet']['difference_prediction_from_state_pvalues']) < 0.05).flatten()]], dh.diff_corr_meta_stats + 'difference_prediction_from_state_rvalues', bins=40, histo_range=[-1.0, 1.0], x_axis_left_buffer=0.01, x_axis_label="$r$", y_axis_label="Frequency", custom_x_tick_locators=[1.0, 0.2], custom_y_tick_locators=[5, 5], alpha=0.78)
sw.normal_histo_plot([np.asarray(meta_dict['quadruplet']['difference_prediction_from_state_rsquared_values'])[np.argwhere(np.asarray(meta_dict['quadruplet']['difference_prediction_from_state_pvalues']) < 0.05).flatten()]], dh.diff_corr_meta_stats + 'difference_prediction_from_state_rsquared_values', bins=20, histo_range=[0.0, 1.0], x_axis_left_buffer=0.01, x_axis_label="$r^2$", y_axis_label="Frequency", custom_x_tick_locators=[1.0, 0.2], custom_y_tick_locators=[5, 5], alpha=0.78)
############## SINGLE UNIT PREDICTION AND CORR ##############
# Already p-value thresholded
sw.normal_histo_plot([meta_dict['quadruplet']['sch_single_unit_prediction_from_state_pvalues']], dh.state_corr_meta_stats + 'sch_single_unit_prediction_from_state_pvalues', bins=20, histo_range=[0.0, 1.0], x_axis_left_buffer=0.01, x_axis_label="$p value$", y_axis_label="Frequency", custom_x_tick_locators=[1.0, 0.2], custom_y_tick_locators=[100, 100], alpha=0.78)
sw.normal_histo_plot([np.asarray(meta_dict['quadruplet']['sch_single_unit_prediction_from_state_rvalues'])], dh.state_corr_meta_stats + 'sch_single_unit_prediction_from_state_rvalues', bins=40, histo_range=[-1.0, 1.0], x_axis_left_buffer=0.01, x_axis_label="$r$", y_axis_label="Frequency", custom_x_tick_locators=[1.0, 0.2], custom_y_tick_locators=[5, 5], alpha=0.78)
sw.normal_histo_plot([np.asarray(meta_dict['quadruplet']['sch_single_unit_prediction_from_state_rsquared_values'])], dh.state_corr_meta_stats + 'sch_single_unit_prediction_from_state_rsquared_values', bins=20, histo_range=[0.0, 1.0], x_axis_left_buffer=0.01, x_axis_label="$r^2$", y_axis_label="Frequency", custom_x_tick_locators=[1.0, 0.2], custom_y_tick_locators=[5, 5], alpha=0.78)
scatter_point_color_groups = ['tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple', 'tab:brown', 'tab:pink', 'tab:gray', 'tab:olive', 'tab:cyan']
sw.plot_fa_comparison([meta_dict['quadruplet']['difference_prediction_from_state_cluster_orig_sds']],
[meta_dict['quadruplet']['difference_prediction_from_state_state_predic_error_sds']],
dh.diff_corr_meta_stats + "_ClusterSD_vs_StatePredicErrorSD",
y_equals_x_max=30,
optional_y_max=30,
scatter_point_color_groups=scatter_point_color_groups)
sw.plot_fa_comparison([meta_dict['quadruplet']['difference_prediction_from_state_FA_predicted_sds']],
[meta_dict['quadruplet']['difference_prediction_from_state_state_predic_error_sds']],
dh.diff_corr_meta_stats + "_FAPredicSD_vs_StatePredicErrorSD",
y_equals_x_max=14,
optional_y_max=14,
scatter_point_color_groups=scatter_point_color_groups)
sw.plot_fa_comparison([meta_dict['quadruplet']['difference_prediction_from_state_conj_orig_sds']],
[meta_dict['quadruplet']['difference_prediction_from_state_state_predic_error_sds']],
dh.diff_corr_meta_stats + "_ConjSD_vs_StatePredicErrorSD",
y_equals_x_max=25,
optional_y_max=25,
scatter_point_color_groups=scatter_point_color_groups)
sw.plot_fa_comparison([meta_dict['quadruplet']['sch_single_unit_prediction_from_state_cluster_orig_sds']],
[meta_dict['quadruplet']['sch_single_unit_prediction_from_state_state_predic_error_sds']],
dh.state_corr_meta_stats + "_ClusterSD_vs_StatePredicErrorSD",
y_equals_x_max=30,
optional_y_max=30,
scatter_point_color_groups=scatter_point_color_groups)
sw.plot_fa_comparison([meta_dict['quadruplet']['sch_single_unit_prediction_from_state_FA_predicted_sds']],
[meta_dict['quadruplet']['sch_single_unit_prediction_from_state_state_predic_error_sds']],
dh.state_corr_meta_stats + "_FAPredicSD_vs_StatePredicErrorSD",
y_equals_x_max=14,
optional_y_max=14,
scatter_point_color_groups=scatter_point_color_groups)
sw.plot_fa_comparison([meta_dict['quadruplet']['sch_single_unit_prediction_from_state_conj_orig_sds']],
[meta_dict['quadruplet']['sch_single_unit_prediction_from_state_state_predic_error_sds']],
dh.state_corr_meta_stats + "_ConjSD_vs_StatePredicErrorSD",
y_equals_x_max=25,
optional_y_max=25,
scatter_point_color_groups=scatter_point_color_groups)
| [
11748,
2603,
29487,
8019,
13,
9078,
29487,
355,
458,
83,
198,
11748,
299,
32152,
355,
45941,
198,
198,
11748,
20240,
86,
5117,
355,
1509,
198,
198,
4299,
13946,
62,
24874,
62,
489,
1747,
7,
28961,
62,
11600,
11,
34590,
2599,
628,
197,... | 2.266976 | 4,094 |
# -*- coding: utf-8 -*-
import scrapy
import re
import json
import urllib.parse
import datetime
import random
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
11748,
15881,
88,
198,
11748,
302,
198,
11748,
33918,
198,
11748,
2956,
297,
571,
13,
29572,
198,
11748,
4818,
8079,
198,
11748,
4738,
628,
198
] | 2.871795 | 39 |
"""
Eigendecomposition
Eigenvalues and eigenvectors are easy to find with Python and NumPy. Remember,
an eigenvector of a square matrix A is a nozero vector v such that multiplication by A
alters only the scale of v
Av=λv
The scalar λ is known as the eigenvalue corresponding to this eigenvector.
"""
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.cm as cm
# find the eigenvalues and eigenvectors for a simple square matrix
A = np.diag(np.arange(1, 4))
"""
[[1 0 0]
[0 2 0]
[0 0 3]]
"""
eigenvalues, eigenvectors = np.linalg.eig(A)
"""
Eigenvalue's: [1. 2. 3.]
Eigenvectors:[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
"""
# the eigenvalue w[i] corresponds to the eigenvector v[:, i]
print('Eigenvalue: {}'.format(eigenvalues[1]))
print('Eigenvector: {}'.format(eigenvectors[:, 1]))
"""
Eigenvalue: 2.0
Eigenvector: [0. 1. 0.]
"""
# verify eigendecomposition - should return original matrix
matrix = np.matmul(np.diag(eigenvalues), np.linalg.inv(eigenvectors))
output = np.matmul(eigenvectors, matrix).astype(np.int)
"""
[[1 0 0]
[0 2 0]
[0 0 3]]
"""
# plot the eigenvectors
origin = [0,0,0]
fig = plt.figure(figsize=(18,10))
fig.suptitle('Effects of Eigenvalues and Eigenvectors')
ax1 = fig.add_subplot(121, projection='3d')
ax1.quiver(origin, origin, origin, eigenvectors[0, :], eigenvectors[1, :], eigenvectors[2, :], color = 'k')
ax1.set_xlim([-3, 3])
ax1.set_ylim([-3, 3])
ax1.set_zlim([-3, 3])
ax1.set_xlabel('X axis')
ax1.set_ylabel('Y axis')
ax1.set_zlabel('Z axis')
ax1.view_init(15, 30)
ax1.set_title("Before Multiplication")
# multiply original matrix by eigenvectors
new_eig = np.matmul(A, eigenvectors)
ax2 = plt.subplot(122, projection='3d')
# plot the new vectors
ax2.quiver(origin, origin, origin, new_eig[0, :], new_eig[1, :], new_eig[2, :], color = 'k')
# plot the eigenvalues for each vector (the amount the vector should be scaled by)
ax2.plot((eigenvalues[0]*eigenvectors[0]), (eigenvalues[1]*eigenvectors[1]), (eigenvalues[2]*eigenvectors[2]), 'rX')
ax2.set_title("After Multiplication")
ax2.set_xlim([-3, 3])
ax2.set_ylim([-3, 3])
ax2.set_zlim([-3, 3])
ax2.set_xlabel('X axis')
ax2.set_ylabel('Y axis')
ax2.set_zlabel('Z axis')
ax2.view_init(15, 30)
# check the png file for plot
plt.savefig('eigen_vectors.png')
plt.close(fig)
| [
37811,
198,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
412,
328,
437,
721,
296,
9150,
198,
36,
9324,
27160,
290,
304,
9324,
303,
5217,
389,
2562,
284,
1064,
... | 2.294957 | 1,051 |
from torch_geometric.nn import MessagePassing
from .. import BaseModel, register_model
from cogdl.utils import spmm, remove_self_loops
from copy import copy
from ogb.graphproppred.mol_encoder import BondEncoder, AtomEncoder
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch_sparse
from torch_sparse import SparseTensor, coalesce
from torch_geometric.nn import global_mean_pool, global_max_pool, global_add_pool
def make_multihop_edges(data, k):
"""
Adds edges corresponding to distances up to k to a data object.
:param data: torch_geometric.data object, in coo format
(ie an edge (i, j) with label v is stored with an arbitrary index u as:
edge_index[0, u] = i, edge_index[1, u]=j, edge_attr[u]=v)
:return: a new data object with new fields, multihop_edge_index and distance.
distance[u] contains values from 1 to k corresponding to the distance between
multihop_edge_index[0, u] and multihop_edge_index[1, u]
"""
data = copy(data)
N = data.num_nodes
E = data.num_edges
if E == 0:
data.multihop_edge_index = torch.empty_like(data.edge_index)
data.distance = torch.empty_like(data.multihop_edge_index[0])
return data
# Get the distance 0
multihop_edge_index = torch.arange(0, N, dtype=data.edge_index[0].dtype, device=data.x.device)
distance = torch.zeros_like(multihop_edge_index)
multihop_edge_index = multihop_edge_index.unsqueeze(0).repeat(2, 1)
# mei: Tensor [2,N]
# Get the distance 1
ei = torch.stack(data.edge_index, dim=0) # ei: Tensor [2,E]
multihop_edge_index = torch.cat((multihop_edge_index, ei), dim=1)
distance = torch.cat((distance, torch.ones_like(data.edge_index[0])), dim=0)
A = SparseTensor(
row=data.edge_index[0],
col=data.edge_index[1],
value=torch.ones_like(data.edge_index[0]).float(),
sparse_sizes=(N, N),
is_sorted=False,
)
Ad = A # A to the power d
# Get larger distances
for d in range(2, k + 1):
Ad = torch_sparse.matmul(Ad, A)
row, col, v = Ad.coo()
d_edge_index = torch.stack((row, col))
d_edge_attr = torch.empty_like(row).fill_(d)
multihop_edge_index = torch.cat((multihop_edge_index, d_edge_index), dim=1)
distance = torch.cat((distance, d_edge_attr), dim=0)
# remove dupicate, keep only shortest distance
multihop_edge_index, distance = coalesce(multihop_edge_index, distance, N, N, op="min")
data.multihop_edge_index = multihop_edge_index
data.distance = distance
return data
@register_model("gine")
class Gine(BaseModel):
"""
https://arxiv.org/abs/2011.15069 \n
"""
@staticmethod
@classmethod
| [
6738,
28034,
62,
469,
16996,
13,
20471,
1330,
16000,
14478,
278,
198,
6738,
11485,
1330,
7308,
17633,
11,
7881,
62,
19849,
198,
6738,
43072,
25404,
13,
26791,
1330,
599,
3020,
11,
4781,
62,
944,
62,
5439,
2840,
198,
6738,
4866,
1330,
... | 2.461815 | 1,113 |
import midiout
import sequence
import noteMsg
import util
import random
# 在这里设置传入的mid路径
# midifile = r'E:\Minecraft1.11\.minecraft\saves\DEMO 4-4 Hack - old\data\functions\Toilet Story 4(black remix 262278 notes) .mid'
midifile = r'./mid/彩虹猫-Part.mid'
tickRate = 28.0
noteRoot = 66
lineWidth= 8
# 常用指令暴露出来
from util import setblock
from util import fallingBlock
from util import noteParticle
from fallingEntity import FallingBlock
FB = FallingBlock() # 伪单例模式使用 FallingBlock
NB = midiout.NoteBlock()
seq = sequence.Seq()
# def getPos(tick, note, velocity, channel, xfix=0.25, zfix=1.0, x=0.0, y=0.0, z=0.0):
# _x,_y,_z = 0.5,16.05,13.5+88
# _x += tick*xfix + x
# _z += -note*zfix + z
# _y += y + (channel)*2.0
# return _x,_y,_z
#
BuildList = {}
if __name__ == '__main__':
msgList = noteMsg.MsgList()
msgList.load(midifile, tickRate)
for item in msgList:
tick = item.tick
rsTick = int(tick/2)
for msg in item.msgs.msgs:
# 设置乐器
if msg.velocity == -2:
# seq.findByTick(tick).addCmd(midiout.setprogram(msg.channel, msg.program))
pass
# 设置控制
elif msg.velocity == -3:
# seq.findByTick(tick).addCmd(midiout.controlchange(msg.channel, msg.control, msg.value))
pass
# 弯轮音
elif msg.velocity == -1:
# seq.findByTick(tick).addCmd(midiout.pitchwheel(msg.channel, msg.pitch))
pass
# 音符 具备长度、若是弯轮音在 msg.move 中会提供移动值
elif msg.velocity > 0:
sTick = tick
eTick = tick+msg.length
channel = msg.channel
note = msg.note
velocity= msg.velocity
# 按下
if not BuildList.__contains__(rsTick):
BuildList[rsTick] = []
BuildList[rsTick].append(msg.note)
else:
BuildList[rsTick].append(msg.note)
lastRsTick = rsTick
#
# print(f'c:{msg.channel}, n:{msg.note}, v:{msg.velocity}')
# seq.findByTick(tick).addCmd(util.log(f't:{tick}, c:{msg.channel}, n:{msg.note}, v:{msg.velocity}'))
# seq.findByTick(sTick).addCmd(NB.toPlaySoundCmd(msg.note, msg.velocity))
# # 弹起
# seq.findByTick(eTick).addCmd(midiout.toCmd(msg.channel, msg.note, 0))
print(BuildList)
print(lastRsTick)
for i in range(0, lastRsTick+1):
if BuildList.__contains__(i):
cmd = getNoteBlocksCmd(i, BuildList[i])
seq.findByTick(i).addCmd(cmd)
else:
cmd = getNoteBlocksCmd(i, [])
seq.findByTick(i).addCmd(cmd)
seq.makeCmd(log=True) | [
11748,
3095,
72,
448,
198,
11748,
8379,
198,
11748,
3465,
50108,
198,
11748,
7736,
198,
11748,
4738,
198,
198,
2,
10263,
250,
101,
32573,
247,
34932,
234,
164,
106,
122,
163,
121,
106,
27670,
254,
17739,
98,
21410,
13602,
164,
115,
10... | 1.918258 | 1,309 |
import os, sys, configparser, platform
if platform.architecture()[0] == "64bit":
libdir = 'third_party/lib64'
else:
libdir = 'third_party/lib'
sys.path.insert(0, os.path.join(os.path.dirname(__file__), libdir))
os.environ['PATH'] = os.environ['PATH'] + ";."
from ctypes import windll
| [
11748,
28686,
11,
25064,
11,
4566,
48610,
11,
3859,
201,
198,
201,
198,
361,
3859,
13,
998,
5712,
495,
3419,
58,
15,
60,
6624,
366,
2414,
2545,
1298,
201,
198,
220,
220,
220,
9195,
15908,
796,
705,
17089,
62,
10608,
14,
8019,
2414,
... | 2.435484 | 124 |
from depccg.tree import Tree
from depccg.utils import normalize, denormalize
def auto_of(tree: Tree) -> str:
"""tree string in auto format commonly used in English CCGBank.
Args:
tree (Tree): tree object
Returns:
str: tree string in the auto format
"""
return rec(tree)
def auto_flattened_of(tree: Tree) -> str:
"""tree string in flattened version of auto format.
This is mainly used for evaluation only.
Args:
tree (Tree): tree object
Returns:
str: tree string in the flattened auto format
"""
return f'###\n{rec(tree)}\n'
def auto_extended_of(tree: Tree) -> str:
"""tree string in extended version of auto format, used by C&C.
Args:
tree (Tree): tree object
Returns:
str: tree string in the extended auto format
"""
return rec(tree)
| [
6738,
1207,
535,
70,
13,
21048,
1330,
12200,
198,
6738,
1207,
535,
70,
13,
26791,
1330,
3487,
1096,
11,
2853,
6636,
1096,
628,
198,
4299,
8295,
62,
1659,
7,
21048,
25,
12200,
8,
4613,
965,
25,
198,
220,
220,
220,
37227,
21048,
4731,... | 2.710692 | 318 |
import pypsa, numpy as np, pandas as pd
from pypsa.linopt import get_var, linexpr, join_exprs, define_constraints
from vresutils.costdata import annuity
import logging
logger = logging.getLogger(__name__)
# Suppress logging of the slack bus choices
pypsa.pf.logger.setLevel(logging.WARNING)
from vresutils.benchmark import memory_logger
# from https://github.com/PyPSA/pypsa-eur-sec/blob/93eb86eec87d34832ebc061697e289eabb38c105/scripts/solve_network.py
override_component_attrs = pypsa.descriptors.Dict({k : v.copy() for k,v in pypsa.components.component_attrs.items()})
override_component_attrs["Link"].loc["bus2"] = ["string",np.nan,np.nan,"2nd bus","Input (optional)"]
override_component_attrs["Link"].loc["bus3"] = ["string",np.nan,np.nan,"3rd bus","Input (optional)"]
override_component_attrs["Link"].loc["bus4"] = ["string",np.nan,np.nan,"4th bus","Input (optional)"]
override_component_attrs["Link"].loc["efficiency2"] = ["static or series","per unit",1.,"2nd bus efficiency","Input (optional)"]
override_component_attrs["Link"].loc["efficiency3"] = ["static or series","per unit",1.,"3rd bus efficiency","Input (optional)"]
override_component_attrs["Link"].loc["efficiency4"] = ["static or series","per unit",1.,"4th bus efficiency","Input (optional)"]
override_component_attrs["Link"].loc["p2"] = ["series","MW",0.,"2nd bus output","Output"]
override_component_attrs["Link"].loc["p3"] = ["series","MW",0.,"3rd bus output","Output"]
override_component_attrs["Link"].loc["p4"] = ["series","MW",0.,"4th bus output","Output"]
# TODO checkout PyPSA-Eur script
def add_ci(n):
"""Add C&I at its own node"""
#first deal with global policy environment
gl_policy = snakemake.config['global']
if gl_policy['policy_type'] == "co2 cap":
co2_cap = gl_policy['co2_share']*gl_policy['co2_baseline']
print("Setting global CO2 cap to ",co2_cap)
n.global_constraints.at["CO2Limit","constant"] = co2_cap
elif gl_policy['policy_type'] == "co2 price":
n.global_constraints.drop("CO2Limit",
inplace=True)
print("Setting CO2 price to",gl_policy['co2_price'])
for carrier in ["coal", "oil", "gas"]:
n.generators.at[f"EU {carrier}","marginal_cost"] += gl_policy['co2_price']*costs.at[carrier, 'CO2 intensity']
#local C&I properties
ci = snakemake.config['ci']
name = ci['name']
node = ci['node']
load = ci['load']
n.add("Bus",
name)
n.add("Link",
name + " export",
bus0=name,
bus1=node,
marginal_cost=1, #to stop link being used to destroy energy
p_nom=1e6)
n.add("Link",
name + " import",
bus0=node,
bus1=name,
marginal_cost=1, #to stop link being used to destroy energy
p_nom=1e6)
#baseload clean energy generator
if "green hydrogen OCGT" in ci["clean_techs"]:
n.add("Generator",
name + " green hydrogen OCGT",
carrier="green hydrogen OCGT",
bus=name,
p_nom_extendable=True,
capital_cost=costs.at['OCGT', 'fixed'],
marginal_cost=costs.at['OCGT', 'VOM'] + snakemake.config['costs']['price_green_hydrogen']/0.033/costs.at['OCGT', 'efficiency']) #hydrogen cost in EUR/kg, 0.033 MWhLHV/kg
#RES generator
for carrier in ["onwind","solar"]:
if carrier not in ci["clean_techs"]:
continue
gen_template = node + " " + carrier
n.add("Generator",
f"{name} {carrier}",
carrier=carrier,
bus=name,
p_nom_extendable=True,
p_max_pu=n.generators_t.p_max_pu[gen_template],
capital_cost=n.generators.at[gen_template,"capital_cost"],
marginal_cost=n.generators.at[gen_template,"marginal_cost"])
n.add("Load",
name + " load",
carrier=name,
bus=name,
p_set=pd.Series(load,index=n.snapshots))
if "battery" in ci["storage_techs"]:
n.add("Bus",
f"{name} battery",
carrier="battery"
)
n.add("Store",
f"{name} battery",
bus=f"{name} battery",
e_cyclic=True,
e_nom_extendable=True,
carrier="battery",
capital_cost=n.stores.at[f"{node} battery", "capital_cost"],
lifetime=n.stores.at[f"{node} battery", "lifetime"]
)
n.add("Link",
f"{name} battery charger",
bus0=name,
bus1=f"{name} battery",
carrier="battery charger",
efficiency=n.links.at[f"{node} battery charger", "efficiency"],
capital_cost=n.links.at[f"{node} battery charger", "capital_cost"],
p_nom_extendable=True,
lifetime=n.links.at[f"{node} battery charger", "lifetime"]
)
n.add("Link",
f"{name} battery discharger",
bus0=f"{name} battery",
bus1=name,
carrier="battery discharger",
efficiency=n.links.at[f"{node} battery discharger", "efficiency"],
marginal_cost=n.links.at[f"{node} battery discharger", "marginal_cost"],
p_nom_extendable=True,
lifetime=n.links.at[f"{node} battery discharger", "lifetime"]
)
if "hydrogen" in ci["storage_techs"]:
n.add("Bus",
f"{name} H2",
carrier="H2"
)
n.add("Store",
f"{name} H2 Store",
bus=f"{name} H2",
e_cyclic=True,
e_nom_extendable=True,
carrier="H2 Store",
capital_cost=n.stores.at[f"{node} H2 Store", "capital_cost"],
lifetime=n.stores.at[f"{node} H2 Store", "lifetime"]
)
n.add("Link",
f"{name} H2 Electrolysis",
bus0=name,
bus1=f"{name} H2",
carrier="H2 Electrolysis",
efficiency=n.links.at[f"{node} H2 Electrolysis", "efficiency"],
capital_cost=n.links.at[f"{node} H2 Electrolysis", "capital_cost"],
p_nom_extendable=True,
lifetime=n.links.at[f"{node} H2 Electrolysis", "lifetime"]
)
n.add("Link",
f"{name} H2 Fuel Cell",
bus0=f"{name} H2",
bus1=name,
carrier="H2 Fuel Cell",
efficiency=n.links.at[f"{node} H2 Fuel Cell", "efficiency"],
capital_cost=n.links.at[f"{node} H2 Fuel Cell", "capital_cost"],
p_nom_extendable=True,
lifetime=n.links.at[f"{node} H2 Fuel Cell", "lifetime"]
)
if __name__ == "__main__":
# Detect running outside of snakemake and mock snakemake for testing
if 'snakemake' not in globals():
from vresutils.snakemake import MockSnakemake, Dict
snakemake = MockSnakemake(
path='',
wildcards=dict(policy='co2120-trans-storage-wind1040-sola510-nuclNone-lCCSNone',parameter="0"),
output=dict(network="results/test/0after.nc"),
log=dict(solver="results/test/log_0after.log")
)
import yaml
with open('config.yaml') as f:
snakemake.config = yaml.load(f)
n = pypsa.Network(snakemake.input.network,
override_component_attrs=override_component_attrs)
policy = snakemake.wildcards.policy[:3]
penetration = float(snakemake.wildcards.policy[3:])/100
print(f"solving network for policy {policy} and penetration {penetration}")
Nyears = 1 # years in simulation
costs = prepare_costs(snakemake.input.costs,
snakemake.config['costs']['USD2013_to_EUR2013'],
snakemake.config['costs']['discountrate'],
Nyears,
snakemake.config['costs']['lifetime'])
with memory_logger(filename=getattr(snakemake.log, 'memory', None), interval=30.) as mem:
strip_network(n)
add_ci(n)
solve_network(n, policy, penetration)
n.export_to_netcdf(snakemake.output.network)
logger.info("Maximum memory usage: {}".format(mem.mem_usage))
| [
198,
11748,
12972,
862,
64,
11,
299,
32152,
355,
45941,
11,
19798,
292,
355,
279,
67,
198,
6738,
12972,
862,
64,
13,
2815,
8738,
1330,
651,
62,
7785,
11,
1627,
87,
1050,
11,
4654,
62,
31937,
82,
11,
8160,
62,
1102,
2536,
6003,
198... | 2.045833 | 4,080 |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class DiagnosticsProfile(Model):
"""Specifies the boot diagnostic settings state. <br><br>Minimum api-version:
2015-06-15.
:param boot_diagnostics: Boot Diagnostics is a debugging feature which
allows you to view Console Output and Screenshot to diagnose VM status.
<br><br> You can easily view the output of your console log. <br><br>
Azure also enables you to see a screenshot of the VM from the hypervisor.
:type boot_diagnostics:
~azure.mgmt.compute.v2019_03_01.models.BootDiagnostics
"""
_attribute_map = {
'boot_diagnostics': {'key': 'bootDiagnostics', 'type': 'BootDiagnostics'},
}
| [
2,
19617,
28,
40477,
12,
23,
198,
2,
16529,
35937,
198,
2,
15069,
357,
66,
8,
5413,
10501,
13,
1439,
2489,
10395,
13,
198,
2,
49962,
739,
262,
17168,
13789,
13,
4091,
13789,
13,
14116,
287,
262,
1628,
6808,
329,
198,
2,
5964,
1321... | 3.677215 | 316 |
from django.core.cache import cache
from django.contrib.contenttypes.models import ContentType
from biblepaycentral.emailalert.models import EMailAlert
def emailalert_exist(content_type_id, object_id, user):
""" Checks if a specific object is in the email alert list. This
function is called a lot, so we work with a cached list of the email alerts """
# first we need to get OR create the email alert list for one user
cached_list = cache.get('emailalert_cache__' + str(user.pk))
if cached_list is None:
alerts = EMailAlert.objects.filter(user=user)
cached_list = []
for alert in alerts:
cached_list.append([alert.content_type_id, alert.object_id])
cache.set('emailalert_cache__' + str(user.pk), cached_list, 300)
# we return true if the requested object is in the alert list for this user
for entry in cached_list:
if str(entry[0]) == str(content_type_id) and str(entry[1]) == str(object_id):
return True
return False
| [
6738,
42625,
14208,
13,
7295,
13,
23870,
1330,
12940,
201,
198,
6738,
42625,
14208,
13,
3642,
822,
13,
11299,
19199,
13,
27530,
1330,
14041,
6030,
201,
198,
6738,
41169,
15577,
31463,
13,
12888,
44598,
13,
27530,
1330,
17228,
603,
36420,
... | 2.596618 | 414 |
from __future__ import unicode_literals
from django.apps import AppConfig
| [
6738,
11593,
37443,
834,
1330,
28000,
1098,
62,
17201,
874,
198,
198,
6738,
42625,
14208,
13,
18211,
1330,
2034,
16934,
198
] | 3.571429 | 21 |
from __future__ import print_function
import tensorflow as tf
import numpy as np
def conv_pass(
fmaps_in,
kernel_size,
num_fmaps,
activation="relu",
name="conv_pass",
fov=(1, 1, 1),
voxel_size=(1, 1, 1),
prefix="",
):
"""Create a convolution pass::
f_in --> f_1 --> ... --> f_n
where each ``-->`` is a convolution followed by a (non-linear) activation
function and ``n`` ``num_repetitions``. Each convolution will decrease the
size of the feature maps by ``kernel_size-1``.
Args:
f_in:
The input tensor of shape ``(batch_size, channels, depth, height, width)``.
kernel_size:
List of sizes of kernels. Length determines number of convolutional layers.
Kernel size forwarded to tf.layers.conv3d.
num_fmaps:
The number of feature maps to produce with each convolution.
activation:
Which activation to use after a convolution. Accepts the name of any
tensorflow activation function (e.g., ``relu`` for ``tf.nn.relu``).
name:
Base name for the conv layer.
fov:
Field of view of fmaps_in, in physical units.
voxel_size:
Size of a voxel in the input data, in physical units.
"""
fmaps = fmaps_in
if activation is not None:
activation = getattr(tf.nn, activation)
for i, ks in enumerate(kernel_size):
fov = tuple(f + (k - 1) * vs for f, k, vs in zip(fov, ks, voxel_size))
print(
prefix,
"fov:",
fov,
"voxsize:",
voxel_size,
"anisotropy:",
(fov[0]) / float(fov[1]),
)
fmaps = tf.layers.conv3d(
inputs=fmaps,
filters=num_fmaps,
kernel_size=ks,
padding="valid",
data_format="channels_first",
activation=activation,
name=name + "_%i" % i,
)
return fmaps, fov
def crop_zyx(fmaps_in, shape):
"""Crop only the spacial dimensions to match shape.
Args:
fmaps_in:
The input tensor.
shape:
A list (not a tensor) with the requested shape [_, _, z, y, x].
"""
in_shape = fmaps_in.get_shape().as_list()
offset = [
0, # batch
0, # channel
(in_shape[2] - shape[2]) // 2, # z
(in_shape[3] - shape[3]) // 2, # y
(in_shape[4] - shape[4]) // 2, # x
]
size = [in_shape[0], in_shape[1], shape[2], shape[3], shape[4]]
fmaps = tf.slice(fmaps_in, offset, size)
return fmaps
| [
6738,
11593,
37443,
834,
1330,
3601,
62,
8818,
198,
11748,
11192,
273,
11125,
355,
48700,
198,
11748,
299,
32152,
355,
45941,
198,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
220,
2... | 2.050847 | 1,298 |
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
with open('requirements.txt') as f:
install_requires = f.read().strip().split('\n')
# get version from __version__ variable in dernetz/__init__.py
from dernetz import __version__ as version
setup(
name='dernetz',
version=version,
description='Customise ERP For Energy Broker',
author='Tech Innovators',
author_email='techinnovatorssurat@gmail.com',
packages=find_packages(),
zip_safe=False,
include_package_data=True,
install_requires=install_requires
)
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
6738,
900,
37623,
10141,
1330,
9058,
11,
1064,
62,
43789,
198,
198,
4480,
1280,
10786,
8897,
18883,
13,
14116,
11537,
355,
277,
25,
198,
197,
17350,
62,
47911,
796,
277,... | 2.988827 | 179 |
from sqlalchemy import Integer, DateTime, String, Column, Boolean, Time
from database import Base
| [
6738,
44161,
282,
26599,
1330,
34142,
11,
7536,
7575,
11,
10903,
11,
29201,
11,
41146,
11,
3862,
198,
6738,
6831,
1330,
7308,
198
] | 4.26087 | 23 |
#############################################################################################
## Author: Tung Son Tran
## Modified after C.Baziotis et. al.,
#############################################################################################
import json
import os
import sys
import argparse
sys.path.append('.')
sys.path.append('..')
sys.path.append('../../')
sys.path.append('../../../')
from collections import defaultdict
from config import BASE_PATH, EXPS_PATH
from model.task1.baseline_models import train_ei_reg, train_ei_oc, train_v_reg, train_v_oc
from modules.sklearn.models import nbow_model, bow_model, eval_reg, eval_mclf
from utils.load_embeddings import load_word_vectors
from utils.nlp import twitter_preprocess
help_reg="""
(Required) Choose one of the following schemes for task EI-reg, V-reg
SGDR (Stochastic Gradient Descent Regressor)
SVR (Support Vector Regressor)
RFR (Random Forest Regressor)
"""
help_clf="""
(Required) Choose one of the following schemes for task EI-oc, V-oc
LoR (Logistic Regressor)
SVC (Support Vector Classifier)
"""
help_task="""
(Optional) Run a specific subtask. Suitable for demo
EI_reg
EI_oc
V_reg
V_oc
"""
help_finetune="""
(Optional) Enable tuning if set to "true". Requires lots of training time
"""
help_baseline="""
(Optional) Run the baseline model if set to "true". Faster but worse performance
"""
# Arguments parsing
parser = argparse.ArgumentParser(description='test',
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('--clf', help=help_clf)
parser.add_argument('--reg', help=help_reg)
parser.add_argument('--task', help=help_task)
parser.add_argument('--finetune', help=help_finetune)
parser.add_argument('--baseline', help=help_baseline)
args = parser.parse_args()
print(args)
if args.clf is None and args.reg is None:
raise ValueError("Please specify classification and regression algorithms!")
# Load embeddings
emb_files = [
("word2vec_300_6_concatened.txt", 310)
]
embeddings = {}
for e, d in emb_files:
file = os.path.join(BASE_PATH, "embeddings", e)
word2idx, idx2word, weights = load_word_vectors(file, d)
embeddings[e.split(".")[0]] = (weights, word2idx)
# Models config
if args.clf is not None:
bow_clf = bow_model(args.clf)
nbow_clf = {"nbow_{}".format(name): nbow_model(args.clf, e, w2i)
for name, (e, w2i) in embeddings.items()}
if args.reg is not None:
bow_reg = bow_model(args.reg)
nbow_reg = {"nbow_{}".format(name): nbow_model(args.reg, e, w2i)
for name, (e, w2i) in embeddings.items()}
# Preprocess
preprocessor = twitter_preprocess()
results = defaultdict(dict)
# ###########################################################################
# # 1. Task EI-reg: Detecting Emotion Intensity (regression)
# ###########################################################################
if args.task == 'EI_reg':
for emotion in ["joy", "sadness", "fear", "anger"]:
task = "EI-reg:{}".format(emotion)
if args.baseline == 'true':
print("Running task {}-{} using baseline model".format(args.task,emotion))
dev, gold = train_ei_reg(emotion=emotion,
model=bow_reg,
algorithm=args.reg,
evaluation=eval_reg,
finetune=args.finetune,
baseline=args.baseline,
preprocessor=preprocessor)
results[task]["bow"] = {"dev": dev, "gold": gold}
else:
print("Running task {}-{} using NN model".format(args.task,emotion))
for name, model in nbow_reg.items():
dev, gold = train_ei_reg(emotion=emotion,
model=model,
algorithm=args.reg,
evaluation=eval_reg,
finetune=args.finetune,
baseline=args.baseline,
preprocessor=preprocessor)
results[task][name] = {"dev": dev, "gold": gold}
###########################################################################
# 2. Task V-reg: Detecting Valence or Sentiment Intensity (regression)
###########################################################################
elif args.task == 'V_reg':
task = "V-reg"
if args.baseline == 'true':
print("Running task {} using baseline model".format(args.task))
dev, gold = train_v_reg(model=bow_reg,
algorithm=args.reg,
evaluation=eval_reg,
finetune=args.finetune,
baseline=args.baseline,
preprocessor=preprocessor)
results[task]["bow"] = {"dev": dev, "gold": gold}
else:
print("Running task {} using NN model".format(args.task))
for name, model in nbow_reg.items():
dev, gold = train_v_reg(model=model,
algorithm=args.reg,
evaluation=eval_reg,
finetune=args.finetune,
baseline=args.baseline,
preprocessor=preprocessor)
results[task][name] = {"dev": dev, "gold": gold}
###########################################################################
# 3. Task EI-oc: Detecting Emotion Intensity (ordinal classification)
###########################################################################
elif args.task == 'EI_oc':
for emotion in ["joy", "sadness", "fear", "anger"]:
task = "EI-oc:{}".format(emotion)
if args.baseline == 'true':
print("Running task {}-{} using baseline model".format(args.task,emotion))
dev, gold = train_ei_oc(emotion=emotion,
model=bow_clf,
algorithm=args.clf,
evaluation=eval_reg,
finetune=args.finetune,
baseline=args.baseline,
preprocessor=preprocessor)
results[task]["bow"] = {"dev": dev, "gold": gold}
else:
print("Running task {}-{} using NN model".format(args.task,emotion))
for name, model in nbow_clf.items():
dev, gold = train_ei_oc(emotion=emotion,
model=model,
algorithm=args.clf,
evaluation=eval_reg,
finetune=args.finetune,
baseline=args.baseline,
preprocessor=preprocessor)
results[task][name] = {"dev": dev, "gold": gold}
##########################################################################
# 4. Task V-oc: Detecting Valence (ordinal classification)
##########################################################################
elif args.task == 'V_oc':
task = "V-oc"
if args.baseline == 'true':
print("Running task {} using baseline model".format(args.task))
dev, gold = train_v_oc(model=bow_clf,
algorithm=args.clf,
evaluation=eval_reg,
finetune=args.finetune,
baseline=args.baseline,
preprocessor=preprocessor)
results[task]["bow"] = {"dev": dev, "gold": gold}
else:
print("Running task {} using NN model".format(args.task))
for name, model in nbow_clf.items():
dev, gold = train_v_oc(model=model,
algorithm=args.clf,
evaluation=eval_reg,
finetune=args.finetune,
baseline=args.baseline,
preprocessor=preprocessor)
results[task][name] = {"dev": dev, "gold": gold}
##########################################################################
with open(os.path.join(EXPS_PATH, "Text Mining Project.json"), 'w') as f:
json.dump(results, f)
| [
29113,
29113,
14468,
7804,
4242,
2,
198,
2235,
6434,
25,
309,
2150,
6295,
833,
272,
198,
2235,
40499,
706,
327,
13,
33,
1031,
5151,
271,
2123,
13,
435,
1539,
198,
29113,
29113,
14468,
7804,
4242,
2,
220,
198,
198,
11748,
33918,
198,
... | 2.105874 | 4,052 |
import torch
import transformers
import transformers.models as tlm
from ignite.handlers import ModelCheckpoint
from transformers import AutoModelForSequenceClassification
from typing import Dict, Callable
from thermostat.utils import Configurable
| [
11748,
28034,
198,
11748,
6121,
364,
198,
11748,
6121,
364,
13,
27530,
355,
256,
75,
76,
198,
6738,
44794,
13,
4993,
8116,
1330,
9104,
9787,
4122,
198,
6738,
6121,
364,
1330,
11160,
17633,
1890,
44015,
594,
9487,
2649,
198,
6738,
19720,... | 4.183333 | 60 |
# -*- coding: utf-8 -*-
import types
from functools import update_wrapper
from .relations.wrapper import Wrapper
from .builder import Builder
from ..query import QueryBuilder
from .relations import (
HasOne, HasMany, HasManyThrough,
BelongsTo, BelongsToMany,
MorphOne, MorphMany, MorphTo, MorphToMany
)
class scope(classmethod):
"""
Decorator to add local scopes.
"""
# Relations decorators
class relation:
"""
Base relation decorator
"""
relation_class = None
class has_one(relation):
"""
Has One relationship decorator
"""
relation_class = HasOne
class morph_one(relation):
"""
Morph One relationship decorator
"""
relation_class = MorphOne
class belongs_to(relation):
"""
Belongs to relationship decorator
"""
relation_class = BelongsTo
class morph_to(relation):
"""
Morph To relationship decorator
"""
relation_class = MorphTo
class has_many(relation):
"""
Has Many relationship decorator
"""
relation_class = HasMany
class has_many_through(relation):
"""
Has Many Through relationship decorator
"""
relation_class = HasManyThrough
class morph_many(relation):
"""
Morph Many relationship decorator
"""
relation_class = MorphMany
class belongs_to_many(relation):
"""
Belongs To Many relationship decorator
"""
relation_class = BelongsToMany
class morph_to_many(relation):
"""
Morph To Many relationship decorator
"""
relation_class = MorphToMany
class morphed_by_many(relation):
"""
Morphed By Many relationship decorator
"""
relation_class = MorphToMany
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
198,
11748,
3858,
198,
6738,
1257,
310,
10141,
1330,
4296,
62,
48553,
198,
6738,
764,
39468,
13,
48553,
1330,
27323,
2848,
198,
6738,
764,
38272,
1330,
35869,
198,
6738,
... | 2.966783 | 572 |
"""Create a database Client for managing connections & executing queries."""
from typing import Union
from .async_client import AsyncClient
from .sync_client import SyncClient
Client = Union[AsyncClient, SyncClient]
| [
37811,
16447,
257,
6831,
20985,
329,
11149,
8787,
1222,
23710,
20743,
526,
15931,
198,
198,
6738,
19720,
1330,
4479,
198,
198,
6738,
764,
292,
13361,
62,
16366,
1330,
1081,
13361,
11792,
198,
6738,
764,
27261,
62,
16366,
1330,
35908,
1179... | 4.132075 | 53 |
""" Errors raised by service classes
"""
import json
class ServiceError(Exception):
"""Errors raised from services"""
def json_body(self):
"""Parse the response body
Returns the json dict or an empty dict if it fails
"""
try:
return json.loads(self.response_text)
except json.decoder.JSONDecodeError:
return {}
class InvalidDataError(ServiceError): # pragma: no coverage
"""Error when the service returns a 400 Bad request received"""
class AuthenticationError(ServiceError): # pragma: no coverage
"""Error when the service returns a 401 Unauthorized"""
class PaymentRequiredError(ServiceError): # pragma: no coverage
"""Error when the service returns a 402 Forbidden"""
class AuthorizationError(ServiceError): # pragma: no coverage
"""Error when the service returns a 403 Forbidden"""
class NotFoundError(ServiceError): # pragma: no coverage
"""Error when the service returns a 404 Not found"""
class ConflictError(ServiceError): # pragma: no coverage
"""Error when the service returns a 409 Conflict"""
class InternalServerError(ServiceError): # pragma: no coverage
"""Error when the service returns a 500 Not found"""
class UnexpectedError(ServiceError): # pragma: no coverage
"""Error raised when the service returns an unexpected status code"""
| [
37811,
44225,
4376,
416,
2139,
6097,
198,
37811,
198,
198,
11748,
33918,
628,
198,
4871,
4809,
12331,
7,
16922,
2599,
198,
220,
220,
220,
37227,
9139,
5965,
4376,
422,
2594,
37811,
628,
220,
220,
220,
825,
33918,
62,
2618,
7,
944,
259... | 3.431762 | 403 |
import numpy as np
from gtda.utils.validation import check_diagrams
from scipy import stats
from scipy.sparse import linalg
import warnings
class ExtractPTS:
""" Extracts Topological Persistence Signatures from Persistence Diagrams as
in the following paper:
Som, A., Thopalli, K., Ramamurthy, K.N., Venkataraman, V., Shukla, A. and
Turaga, P., Perturbation Robust Representations of Topological Persistence
Diagrams.
https://arxiv.org/pdf/1807.10400.pdf
Adapted from the official repository:
https://github.com/anirudhsom/Perturbed-Topological-Signature
A set of Perturbed PDs is created by applying Gaussian noise on the initial
PD with transformed axis. The Perturbed PDs are then converted to 2D PDFs by
fitting a Gaussian kernel function at each point in the PD, normalizing the
2D surface and discretizing the surface over a `x1` x `x2` grid. The 2D PDFs
are then mapped to the Grassmanian manifold. The largest singular vectors
are extracted using SVD.
Parameters
----------
n_perturbations : int, optional, default: ``40``
The number of perturbations extracted from the initial PD.
max_displacement : float, optional, default: ``0.05``
The displacement done to the points from the initial PD.
x1 : int, optional, default: ``50``
Number of lines for the discretization of the PDF.
x2 : int, optional, default: ``50``
Number of columns for the discretization of the PDF.
sigma : float, optional, default: ``0.04``
The standard deviation (bandwidth parameter) for the Gaussian used to
convert the Perturbed PDs to PDFs.
subspace_dimension : int, optional, default: ``10``
Subspace dimension for the Grassmann manifold.
tries : int, optional, default: ``50``
How many times to try again if the transformation fails.
"""
def fit(self, X, y=None):
""" Does nothing, returns an unchanged estimator.
This method is here to implement the usual scikit-learn API and hence
work in pipelines.
Parameters
----------
X : ndarray of shape (n_samples, n_features, 3)
Input data. Array of persistence diagrams, each a collection of
triples [b, d, q] representing persistent topological features
through their birth (b), death (d) and homology dimension (q).
y : None
There is no need for a target in a transformer, yet the pipeline
API requires this parameter.
Returns
-------
self : object
"""
check_diagrams(X)
self.__is_fitted = True
return self
def transform(self, X, y=None):
""" Transforms a PDs into PTS representations.
Parameters
----------
X : ndarray of shape (n_samples, n_features, 3)
Input data. Array of persistence diagrams, each a collection of
triples [b, d, q] representing persistent topological features
through their birth (b), death (d) and homology dimension (q).
We assume that the PDs are normalized. The normalization scheme
in the official implementation is PD_norm = PD/max(PD).
y : None
There is no need for a target in a transformer, yet the pipeline
API requires this parameter.
Returns
-------
pts_repr : ndarray of shape
(n_samples, n_features, `subspace_dimension`)
PTS features.
"""
Xs = check_diagrams(X, copy=True)
pts_list = []
n_pds = Xs.shape[0]
for pd in Xs:
perturbed_pds = self.make_perturbation(pd)
pdfs = self.make_pdfs(perturbed_pds)
while self.subspace_dimension >= len(pdfs) and self.tries > 0:
perturbed_pds = self.make_perturbation(pd)
pdfs = self.make_pdfs(perturbed_pds)
self.tries -= 1
else:
if self.subspace_dimension >= len(pdfs):
raise ValueError("Cannot extract PTS. Please try again")
manifold_point = self.map_to_manifold(pdfs)
manifold_point = np.expand_dims(manifold_point, axis=0)
pts_list.append(manifold_point)
pts_repr = np.concatenate(pts_list, axis=0)
return pts_repr
def make_perturbation(self, X):
""" Perturbs a single PD and returns a list size `n_perturbations` + 1
PDs.
Parameters
----------
X : ndarray of shape (n_features, 3)
Input data. Array of persistence diagrams, each a collection of
triples [b, d, q] representing persistent topological features
through their birth (b), death (d) and homology dimension (q).
We assume that the PDs are normalized. The normalization scheme
in the official implementation is PD_norm = PD/max(PD).
Returns
-------
perturbed_pds : list with `n_perturbations` + 1 PDs of shape
(n_features, 3)
"""
Xs = X.copy()
# We expect a single PD
if len(Xs.shape) > 2:
Xs = np.squeeze(Xs, axis=0)
n_points = X.shape[0]
perturbed_pds = []
# Transform the axes of the PD: (b, d) -> ( (b+d)/2, d-b )
b = 0.5 * (Xs[:, :1] + Xs[:, 1:2])
d = Xs[:, 1:2] - Xs[:, :1]
h = np.squeeze(Xs[:, 2:3], axis=1)
Xs[:, :1] = b
Xs[:, 1:2] = d
# Append the unperturbed PD to the list
perturbed_pds.append(Xs)
# Create randomly perturbed PDs
random_pert_b = np.random.random((n_points, self.n_perturbations))
random_pert_d = np.random.random((n_points, self.n_perturbations))
random_pert_b = random_pert_b * 2 * self.max_displacement
random_pert_d = random_pert_d * 2 * self.max_displacement
random_pert_b = random_pert_b - self.max_displacement
random_pert_d = random_pert_d - self.max_displacement
b_perturbed = b + random_pert_b
d_perturbed = d + random_pert_d
for i in range(self.n_perturbations):
b_i = b_perturbed[:, i]
d_i = d_perturbed[:, i]
h_i = h.copy()
# Remove entries with negative birth
b_i = b_i[np.where(b_i >= 0)]
d_i = d_i[np.where(b_i >= 0)]
h_i = h_i[np.where(b_i >= 0)]
# Remove entries with negative death
b_i = b_i[np.where(d_i >= 0)]
d_i = d_i[np.where(d_i >= 0)]
h_i = h_i[np.where(d_i >= 0)]
# Remove entries with birth >= 1
b_i = b_i[np.where(b_i <= 1)]
d_i = d_i[np.where(b_i <= 1)]
h_i = h_i[np.where(b_i <= 1)]
# Remove entries with death >= 1
b_i = b_i[np.where(d_i <= 1)]
d_i = d_i[np.where(d_i <= 1)]
h_i = h_i[np.where(d_i <= 1)]
perturbed_pd = np.column_stack((b_i, d_i, h_i))
perturbed_pds.append(perturbed_pd)
return perturbed_pds
def make_pdfs(self, perturbed_pds):
""" Converts the Perturbed PDs to 2D surfaces using a Gaussian kernel
function and discretizes into a `x1` x `x2` grid.
Parameters
----------
perturbed_pds : list of `n_perturbations` + 1 PDs of shape
(n_features, 3).
Returns
-------
pdfs : list of `n_perturbations` + 1 discretized PDFs of shape
((`x1`+1) * (`x2`+1),).
"""
pdfs = []
x1 = np.arange(0, 1.01, 1 / self.x1)
x2 = np.arange(0, 1.01, 1 / self.x2)
X1, X2 = np.meshgrid(x1, x2)
positions = np.vstack([X1.ravel(), X2.ravel()])
heatmap = np.zeros((self.x1 + 1, self.x2 + 1))
# print('-'*20)
for idx, pd in enumerate(perturbed_pds):
# print('idx:', idx)
pd_t = pd[:, :2].T.copy()
try:
# If the PD has few points, the following problem occurs:
# try-catch wrapper for the following cases:
# 1. pd_t is singular
# 2. positions matrix is not positive definite
# 3. positions is null
# The pipeline should not be affected due to the SVD.
# Issue: It will crash if the number of vectors extracted is
# less than `subspace_dimension`
kernel = stats.gaussian_kde(pd_t, self.sigma)
transformed = kernel(positions)
Z = np.reshape(transformed.T, X1.shape)
heatmap = heatmap + Z
pdf = heatmap.reshape((X1.shape[0] * X2.shape[1]))
except Exception as e:
# warnings.warn(f"{e}") # we check at the end if we could get a minimum of subspace_dimension pdfs
continue
pdf = pdf / np.sum(pdf)
pdfs.append(pdf)
return pdfs
def map_to_manifold(self, pdfs):
""" Converts the Perturbed PDs to 2D surfaces using a Gaussian kernel
function and discretizes into a `x1` x `x2` grid.
Parameters
----------
pdfs : list of `n_perturbations` + 1 discretized PDFs of shape
((`x1`+1) * (`x2`+1),).
Returns
-------
U : PTS representation of shape
((`x1`+1) * (`x2`+1), subspace_dimension).
Contains the largest `subspace_dimension` orthonormal singular
vectors.
"""
column_pdfs = np.column_stack(pdfs)
U, _, _ = linalg.svds(column_pdfs, k=self.subspace_dimension)
return U | [
11748,
299,
32152,
355,
45941,
198,
6738,
308,
83,
6814,
13,
26791,
13,
12102,
341,
1330,
2198,
62,
10989,
6713,
82,
198,
6738,
629,
541,
88,
1330,
9756,
198,
6738,
629,
541,
88,
13,
82,
29572,
1330,
300,
1292,
70,
198,
11748,
14601... | 2.14509 | 4,542 |
import click
from redspot.build import build
from redspot.run import run
@click.group()
cli.add_command(run.cli, name="run")
cli.add_command(build.cli, name="build")
if __name__ == "__main__":
cli()
| [
11748,
3904,
198,
198,
6738,
2266,
20485,
13,
11249,
1330,
1382,
198,
6738,
2266,
20485,
13,
5143,
1330,
1057,
628,
198,
31,
12976,
13,
8094,
3419,
628,
198,
44506,
13,
2860,
62,
21812,
7,
5143,
13,
44506,
11,
1438,
2625,
5143,
4943,
... | 2.714286 | 77 |
import bpy
from bpy.props import *
from bpy.types import Node, NodeSocket
from arm.logicnode.arm_nodes import *
class SeparateColorNode(Node, ArmLogicTreeNode):
'''Separate color node'''
bl_idname = 'LNSeparateColorNode'
bl_label = 'Separate RGB'
bl_icon = 'CURVE_PATH'
add_node(SeparateColorNode, category='Value')
| [
11748,
275,
9078,
198,
6738,
275,
9078,
13,
1676,
862,
1330,
1635,
198,
6738,
275,
9078,
13,
19199,
1330,
19081,
11,
19081,
39105,
198,
6738,
3211,
13,
6404,
291,
17440,
13,
1670,
62,
77,
4147,
1330,
1635,
198,
198,
4871,
8621,
30748,... | 2.650794 | 126 |
import sys, cctk
import pandas as pd
from asciichartpy import plot
#### This is a script to monitor the output of Orca files.
#### In contrast to ``analyze_orca.py``, this script analyzes only one file!
#### Usage: ``python monitor_orca.py path/to/output.out``
#### Corin Wagen and Eugene Kwan, 2019
filename = sys.argv[1]
print(f"\n\033[3mreading {filename}:\033[0m")
output_file = cctk.OrcaFile.read_file(filename)
if isinstance(output_file, list):
output_file = output_file[-1]
print(f"{output_file.successful_terminations} successful terminations")
print(f"{output_file.num_imaginaries()} imaginary frequencies")
if output_file.num_imaginaries():
freqs = [f"{f:.1f} cm-1" for f in output_file.imaginaries()]
for f in freqs:
print(f"\t{f}")
print("\n\033[3manalysis:\033[0m")
print(f"{len(output_file.ensemble)} iterations completed")
property_names = ["scf_iterations", "energy", "rms_step", "rms_gradient", "S**2"]
properties = output_file.ensemble[:,property_names]
if len(output_file.ensemble) == 1:
properties = [properties]
df = pd.DataFrame(properties, columns=property_names).fillna(0)
df["rel_energy"] = (df.energy - df.energy.min()) * 627.509469
print("\n\033[1mENERGY (kcal/mol):\033[0m")
print(plot(df["rel_energy"], {"height": 12, "format": " {:8.2f} "}))
print("\n\033[1mRMS GRADIENT:\033[0m")
print(plot(df["rms_gradient"], {"height": 12, "format": " {:8.6f} "}))
print("\n\033[1mRMS STEP:\033[0m")
print(plot(df["rms_step"], {"height": 12, "format": " {:8.6f} "}))
if df["S**2"][0] is not None:
print("\n\033[1mSPIN EXPECTATION VALUE:\033[0m")
print(plot(df["S**2"], {"height": 12, "format": " {:8.6f} "}))
| [
11748,
25064,
11,
269,
310,
74,
198,
11748,
19798,
292,
355,
279,
67,
198,
6738,
355,
979,
488,
433,
9078,
1330,
7110,
198,
198,
4242,
770,
318,
257,
4226,
284,
5671,
262,
5072,
286,
1471,
6888,
3696,
13,
220,
198,
4242,
554,
6273,
... | 2.477037 | 675 |
#!/usr/bin/python
# This file is part of python-evtx.
#
# Copyright 2012, 2013 Willi Ballenthin william.ballenthin@mandiant.com>
# while at Mandiant <http://www.mandiant.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import re
import itertools
import base64
from BinaryParser import Block
from BinaryParser import hex_dump
from BinaryParser import ParseException
from BinaryParser import memoize
node_dispatch_table = [] # updated at end of file
node_readable_tokens = [] # updated at end of file
class SuppressConditionalSubstitution(Exception):
"""
This exception is to be thrown to indicate that a conditional
substitution evaluated to NULL, and the parent element should
be suppressed. This exception should be caught at the first
opportunity, and must not propagate far up the call chain.
Strategy:
AttributeNode catches this, .xml() --> ""
StartOpenElementNode catches this for each child, ensures
there's at least one useful value. Or, .xml() --> ""
"""
class UnexpectedStateException(ParseException):
"""
UnexpectedStateException is an exception to be thrown when the parser
encounters an unexpected value or state. This probably means there
is a bug in the parser, but could stem from a corrupted input file.
"""
class EndOfStreamNode(BXmlNode):
"""
The binary XML node for the system token 0x00.
This is the "end of stream" token. It may never actually
be instantiated here.
"""
class OpenStartElementNode(BXmlNode):
"""
The binary XML node for the system token 0x01.
This is the "open start element" token.
"""
@memoize
@memoize
@memoize
class CloseStartElementNode(BXmlNode):
"""
The binary XML node for the system token 0x02.
This is the "close start element" token.
"""
class CloseEmptyElementNode(BXmlNode):
"""
The binary XML node for the system token 0x03.
"""
class CloseElementNode(BXmlNode):
"""
The binary XML node for the system token 0x04.
This is the "close element" token.
"""
def get_variant_value(buf, offset, chunk, parent, type_, length=None):
"""
@return A VariantType subclass instance found in the given
buffer and offset.
"""
types = {
0x00: NullTypeNode,
0x01: WstringTypeNode,
0x02: StringTypeNode,
0x03: SignedByteTypeNode,
0x04: UnsignedByteTypeNode,
0x05: SignedWordTypeNode,
0x06: UnsignedWordTypeNode,
0x07: SignedDwordTypeNode,
0x08: UnsignedDwordTypeNode,
0x09: SignedQwordTypeNode,
0x0A: UnsignedQwordTypeNode,
0x0B: FloatTypeNode,
0x0C: DoubleTypeNode,
0x0D: BooleanTypeNode,
0x0E: BinaryTypeNode,
0x0F: GuidTypeNode,
0x10: SizeTypeNode,
0x11: FiletimeTypeNode,
0x12: SystemtimeTypeNode,
0x13: SIDTypeNode,
0x14: Hex32TypeNode,
0x15: Hex64TypeNode,
0x21: BXmlTypeNode,
0x81: WstringArrayTypeNode,
}
try:
TypeClass = types[type_]
except IndexError:
raise NotImplementedError("Type %s not implemented" % (type_))
return TypeClass(buf, offset, chunk, parent, length=length)
class ValueNode(BXmlNode):
"""
The binary XML node for the system token 0x05.
This is the "value" token.
"""
class AttributeNode(BXmlNode):
"""
The binary XML node for the system token 0x06.
This is the "attribute" token.
"""
def attribute_name(self):
"""
@return A NameNode instance that contains the attribute name.
"""
return self._chunk.strings()[self.string_offset()]
def attribute_value(self):
"""
@return A BXmlNode instance that is one of (ValueNode,
ConditionalSubstitutionNode, NormalSubstitutionNode).
"""
return self.children()[0]
@memoize
class CDataSectionNode(BXmlNode):
"""
The binary XML node for the system token 0x07.
This is the "CDATA section" system token.
"""
class EntityReferenceNode(BXmlNode):
"""
The binary XML node for the system token 0x09.
This is an entity reference node. That is, something that represents
a non-XML character, eg. & --> &.
TODO(wb): this is untested.
"""
class ProcessingInstructionTargetNode(BXmlNode):
"""
The binary XML node for the system token 0x0A.
TODO(wb): untested.
"""
class ProcessingInstructionDataNode(BXmlNode):
"""
The binary XML node for the system token 0x0B.
TODO(wb): untested.
"""
class TemplateInstanceNode(BXmlNode):
"""
The binary XML node for the system token 0x0C.
"""
@memoize
class NormalSubstitutionNode(BXmlNode):
"""
The binary XML node for the system token 0x0D.
This is a "normal substitution" token.
"""
class ConditionalSubstitutionNode(BXmlNode):
"""
The binary XML node for the system token 0x0E.
"""
class StreamStartNode(BXmlNode):
"""
The binary XML node for the system token 0x0F.
This is the "start of stream" token.
"""
class RootNode(BXmlNode):
"""
The binary XML node for the Root node.
"""
@memoize
def children(self):
"""
@return The template instances which make up this node.
"""
return self._children(end_tokens=[SYSTEM_TOKENS.EndOfStreamToken])
def tag_and_children_length(self):
"""
@return The length of the tag of this element, and the children.
This does not take into account the substitutions that may be
at the end of this element.
"""
children_length = 0
for child in self.children():
children_length += child.length()
return self.tag_length() + children_length
@memoize
def fast_substitutions(self):
"""
Get the list of elements that are the
the substitutions for this root node.
Each element is one of:
str
int
float
RootNode
@rtype: list
"""
sub_decl = []
sub_def = []
ofs = self.tag_and_children_length()
sub_count = self.unpack_dword(ofs)
ofs += 4
for _ in xrange(sub_count):
size = self.unpack_word(ofs)
type_ = self.unpack_byte(ofs + 0x2)
sub_decl.append((size, type_))
ofs += 4
for (size, type_) in sub_decl:
#[0] = parse_null_type_node,
if type_ == 0x0:
value = None
sub_def.append(value)
#[1] = parse_wstring_type_node,
elif type_ == 0x1:
s = self.unpack_wstring(ofs, size / 2).rstrip("\x00")
value = s.replace("<", ">").replace(">", "<")
sub_def.append(value)
#[2] = parse_string_type_node,
elif type_ == 0x2:
s = self.unpack_string(ofs, size)
value = s.decode("utf8").rstrip("\x00")
value = value.replace("<", ">")
value = value.replace(">", "<")
sub_def.append(value)
#[3] = parse_signed_byte_type_node,
elif type_ == 0x3:
sub_def.append(self.unpack_int8(ofs))
#[4] = parse_unsigned_byte_type_node,
elif type_ == 0x4:
sub_def.append(self.unpack_byte(ofs))
#[5] = parse_signed_word_type_node,
elif type_ == 0x5:
sub_def.append(self.unpack_int16(ofs))
#[6] = parse_unsigned_word_type_node,
elif type_ == 0x6:
sub_def.append(self.unpack_word(ofs))
#[7] = parse_signed_dword_type_node,
elif type_ == 0x7:
sub_def.append(self.unpack_int32(ofs))
#[8] = parse_unsigned_dword_type_node,
elif type_ == 0x8:
sub_def.append(self.unpack_dword(ofs))
#[9] = parse_signed_qword_type_node,
elif type_ == 0x9:
sub_def.append(self.unpack_int64(ofs))
#[10] = parse_unsigned_qword_type_node,
elif type_ == 0xA:
sub_def.append(self.unpack_qword(ofs))
#[11] = parse_float_type_node,
elif type_ == 0xB:
sub_def.append(self.unpack_float(ofs))
#[12] = parse_double_type_node,
elif type_ == 0xC:
sub_def.append(self.unpack_double(ofs))
#[13] = parse_boolean_type_node,
elif type_ == 0xD:
sub_def.append(str(self.unpack_word(ofs) > 1))
#[14] = parse_binary_type_node,
elif type_ == 0xE:
sub_def.append(base64.b64encode(self.unpack_binary(ofs, size)))
#[15] = parse_guid_type_node,
elif type_ == 0xF:
sub_def.append(self.unpack_guid(ofs))
#[16] = parse_size_type_node,
elif type_ == 0x10:
if size == 0x4:
sub_def.append(self.unpack_dword(ofs))
elif size == 0x8:
sub_def.append(self.unpack_qword(ofs))
else:
raise UnexpectedStateException("Unexpected size for SizeTypeNode: %s" % hex(size))
#[17] = parse_filetime_type_node,
elif type_ == 0x11:
sub_def.append(self.unpack_filetime(ofs))
#[18] = parse_systemtime_type_node,
elif type_ == 0x12:
sub_def.append(self.unpack_systemtime(ofs))
#[19] = parse_sid_type_node, -- SIDTypeNode, 0x13
elif type_ == 0x13:
version = self.unpack_byte(ofs)
num_elements = self.unpack_byte(ofs + 1)
id_high = self.unpack_dword_be(ofs + 2)
id_low = self.unpack_word_be(ofs + 6)
value = "S-%d-%d" % (version, (id_high << 16) ^ id_low)
for i in xrange(num_elements):
val = self.unpack_dword(ofs + 8 + (4 * i))
value += "-%d" % val
sub_def.append(value)
#[20] = parse_hex32_type_node, -- Hex32TypeNoe, 0x14
elif type_ == 0x14:
value = "0x"
for c in self.unpack_binary(ofs, size)[::-1]:
value += "%02x" % ord(c)
sub_def.append(value)
#[21] = parse_hex64_type_node, -- Hex64TypeNode, 0x15
elif type_ == 0x15:
value = "0x"
for c in self.unpack_binary(ofs, size)[::-1]:
value += "%02x" % ord(c)
sub_def.append(value)
#[33] = parse_bxml_type_node, -- BXmlTypeNode, 0x21
elif type_ == 0x21:
sub_def.append(RootNode(self._buf, self.offset() + ofs,
self._chunk, self))
#[129] = TODO, -- WstringArrayTypeNode, 0x81
elif type_ == 0x81:
bin = self.unpack_binary(ofs, size)
acc = []
while len(bin) > 0:
match = re.search("((?:[^\x00].)+)", bin)
if match:
frag = match.group()
acc.append("<string>")
acc.append(frag.decode("utf16"))
acc.append("</string>\n")
bin = bin[len(frag) + 2:]
if len(bin) == 0:
break
frag = re.search("(\x00*)", bin).group()
if len(frag) % 2 == 0:
for _ in xrange(len(frag) // 2):
acc.append("<string></string>\n")
else:
raise ParseException("Error parsing uneven substring of NULLs")
bin = bin[len(frag):]
sub_def.append("".join(acc))
else:
raise "Unexpected type encountered: %s" % hex(type_)
ofs += size
return sub_def
@memoize
def substitutions(self):
"""
@return A list of VariantTypeNode subclass instances that
contain the substitutions for this root node.
"""
sub_decl = []
sub_def = []
ofs = self.tag_and_children_length()
sub_count = self.unpack_dword(ofs)
ofs += 4
for _ in xrange(sub_count):
size = self.unpack_word(ofs)
type_ = self.unpack_byte(ofs + 0x2)
sub_decl.append((size, type_))
ofs += 4
for (size, type_) in sub_decl:
val = get_variant_value(self._buf, self.offset() + ofs,
self._chunk, self, type_, length=size)
if abs(size - val.length()) > 4:
# TODO(wb): This is a hack, so I'm sorry.
# But, we are not passing around a 'length' field,
# so we have to depend on the structure of each
# variant type. It seems some BXmlTypeNode sizes
# are not exact. Hopefully, this is just alignment.
# So, that's what we compensate for here.
raise ParseException("Invalid substitution value size")
sub_def.append(val)
ofs += size
return sub_def
@memoize
class VariantTypeNode(BXmlNode):
"""
"""
class NullTypeNode(object): # but satisfies the contract of VariantTypeNode, BXmlNode, but not Block
"""
Variant type 0x00.
"""
class WstringTypeNode(VariantTypeNode):
"""
Variant ttype 0x01.
"""
class StringTypeNode(VariantTypeNode):
"""
Variant type 0x02.
"""
class SignedByteTypeNode(VariantTypeNode):
"""
Variant type 0x03.
"""
class UnsignedByteTypeNode(VariantTypeNode):
"""
Variant type 0x04.
"""
class SignedWordTypeNode(VariantTypeNode):
"""
Variant type 0x05.
"""
class UnsignedWordTypeNode(VariantTypeNode):
"""
Variant type 0x06.
"""
class SignedDwordTypeNode(VariantTypeNode):
"""
Variant type 0x07.
"""
class UnsignedDwordTypeNode(VariantTypeNode):
"""
Variant type 0x08.
"""
class SignedQwordTypeNode(VariantTypeNode):
"""
Variant type 0x09.
"""
class UnsignedQwordTypeNode(VariantTypeNode):
"""
Variant type 0x0A.
"""
class FloatTypeNode(VariantTypeNode):
"""
Variant type 0x0B.
"""
class DoubleTypeNode(VariantTypeNode):
"""
Variant type 0x0C.
"""
class BooleanTypeNode(VariantTypeNode):
"""
Variant type 0x0D.
"""
class BinaryTypeNode(VariantTypeNode):
"""
Variant type 0x0E.
String/XML representation is Base64 encoded.
"""
class GuidTypeNode(VariantTypeNode):
"""
Variant type 0x0F.
"""
class SizeTypeNode(VariantTypeNode):
"""
Variant type 0x10.
Note: Assuming sizeof(size_t) == 0x8.
"""
class FiletimeTypeNode(VariantTypeNode):
"""
Variant type 0x11.
"""
class SystemtimeTypeNode(VariantTypeNode):
"""
Variant type 0x12.
"""
class SIDTypeNode(VariantTypeNode):
"""
Variant type 0x13.
"""
@memoize
@memoize
class Hex32TypeNode(VariantTypeNode):
"""
Variant type 0x14.
"""
class Hex64TypeNode(VariantTypeNode):
"""
Variant type 0x15.
"""
class BXmlTypeNode(VariantTypeNode):
"""
Variant type 0x21.
"""
class WstringArrayTypeNode(VariantTypeNode):
"""
Variant ttype 0x81.
"""
node_dispatch_table = [
EndOfStreamNode,
OpenStartElementNode,
CloseStartElementNode,
CloseEmptyElementNode,
CloseElementNode,
ValueNode,
AttributeNode,
CDataSectionNode,
None,
EntityReferenceNode,
ProcessingInstructionTargetNode,
ProcessingInstructionDataNode,
TemplateInstanceNode,
NormalSubstitutionNode,
ConditionalSubstitutionNode,
StreamStartNode,
]
node_readable_tokens = [
"End of Stream",
"Open Start Element",
"Close Start Element",
"Close Empty Element",
"Close Element",
"Value",
"Attribute",
"unknown",
"unknown",
"unknown",
"unknown",
"unknown",
"TemplateInstanceNode",
"Normal Substitution",
"Conditional Substitution",
"Start of Stream",
]
| [
2,
48443,
14629,
14,
8800,
14,
29412,
198,
2,
220,
220,
220,
770,
2393,
318,
636,
286,
21015,
12,
1990,
17602,
13,
198,
2,
198,
2,
220,
220,
15069,
2321,
11,
2211,
2561,
72,
6932,
7944,
259,
481,
1789,
13,
1894,
7944,
259,
31,
2... | 2.110437 | 8,077 |
"""add licensed works layer
Revision ID: 369150228f9d
Revises: 603d93ba52ea
Create Date: 2020-08-10 02:52:28.638544
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '369150228f9d'
down_revision = '603d93ba52ea'
branch_labels = None
depends_on = None
| [
37811,
2860,
11971,
2499,
7679,
198,
198,
18009,
1166,
4522,
25,
45620,
8628,
23815,
69,
24,
67,
198,
18009,
2696,
25,
718,
3070,
67,
6052,
7012,
4309,
18213,
198,
16447,
7536,
25,
12131,
12,
2919,
12,
940,
7816,
25,
4309,
25,
2078,
... | 2.605042 | 119 |
# encoding: utf-8
"""
主函数
"""
import numpy as np
import tensorflow as tf
from AlexNet import training_graph as tg, args_manager as am, input_local_data as ild, caffe_classes
import cv2
session = tf.InteractiveSession()
# --------------------------------- build a graph ---------------------------
args = am.ArgumentManager(session, skip_layer=[])
input_data = ild.InputLocalData(train_file_dir='train_data/',
test_file_dir='test_data/', num_class=1000, num_epochs=3)
# 训练和测试用的批量本地数据
img_batch, lab_batch = input_data.get_batches(resize_w=227, resize_h=227,
batch_size=3, capacity=20)
# 识别 demo 用到的少许数据
test_data_list = input_data.get_test_img_list()
graph = tg.TrainingGraph(keep_prob=1, class_num=1000)
choice = input('\nwant to train/test or recognition ?\n train/test - 1\n recognition - 2\n')
if choice is '1':
# 批量训练本地数据用这个图,注意是在 bvlc_alexnet.npy 参数的基础上训练
train_step, logits, acc = graph.build_graph(img_batch=img_batch, lab_batch=lab_batch)
else:
# 识别 demo 用这个图
img_ph = tf.placeholder(shape=[1, 227, 227, 3], dtype=tf.float32)
_, test_logits, _ = graph.build_graph(img_ph, None)
test_softmax = tf.nn.softmax(test_logits)
# --------------------------------- init all variables -------------------------------
# ys = input("attention!!!\ninit the variables from ?\n 'model_sava/'-1\n alexNet-2\n no-n\n")
# switch = {
# 'n': args.init_all(),
# '1': args.restore(),
# '2': args.load_initial_weights(),
# }
# switch.get(ys)
if choice is '1':
args.initial_from_bvlc_alexnet()
else:
args.restore()
# --------------------------------- calculate the graph ------------------------------
if choice is '1':
"""
批量训练和测试本地数据,采用 TensorFlow 多线程,文件队列
详见 https://blog.csdn.net/dcrmg/article/details/79780331
"""
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=session, coord=coord)
try:
for step in np.arange(2):
print("training step: %d" % step)
if coord.should_stop():
break
train_step.run()
print("accuracy: {}\n".format(acc.eval()))
# Save the variables to disk.
args.save()
except tf.errors.OutOfRangeError:
print("Done!!!")
finally:
coord.request_stop()
coord.join(threads)
else:
"""
图像识别的 demo
"""
for i, img in enumerate(test_data_list):
# 标准化,这里不建议使用 tf.image.per_image_standardization ,因为它得到的是 tensor 对象,
# 将其完美转化为 ndarray 对象需要在 sess 里运行.
test = cv2.resize(img.astype(np.float32), (227, 227))
# img_mean = np.array([104, 117, 124], np.float32)
# test = test - img_mean # 去均值
img_arr = test.reshape([1, 227, 227, 3])
# 应用 argmax 找到向量中最大概率值的下标
maxx = np.argmax(session.run(test_softmax, feed_dict={img_ph: img_arr}))
# 通过下标从字符串中取得物体名称
res = caffe_classes.class_names[maxx]
print('the result is {} {} '.format(maxx, res))
font = cv2.FONT_HERSHEY_SIMPLEX
# 绘制
cv2.putText(img, res, (int(img.shape[0] / 3), int(img.shape[1] / 3)), font, 1, (0, 255, 0), 2)
cv2.imshow("demo", img)
cv2.waitKey(5000)
| [
2,
21004,
25,
3384,
69,
12,
23,
198,
37811,
198,
10310,
119,
49035,
121,
46763,
108,
198,
37811,
198,
11748,
299,
32152,
355,
45941,
198,
11748,
11192,
273,
11125,
355,
48700,
198,
6738,
4422,
7934,
1330,
3047,
62,
34960,
355,
256,
70... | 1.891672 | 1,717 |
""" RoleManager tests """
from django.apps import apps
from django.test import TestCase
from improved_permissions.exceptions import ImproperlyConfigured, NotAllowed
from improved_permissions.roles import ALL_MODELS, Role, RoleManager
from testapp1 import roles
class RoleTest(TestCase):
""" Role class tests """
def test_incorrect_implementations(self):
""" test for exceptions """
# Trying to instantiate.
with self.assertRaises(ImproperlyConfigured):
Role()
# Trying to use the methods on the abstract class.
with self.assertRaises(ImproperlyConfigured):
Role.get_class_name()
# Trying to register another class but using
# the same name.
with self.assertRaises(ImproperlyConfigured):
RoleManager.register_role(Advisor)
# Trying to access the inherit mode of a
# role class using inherit=False.
with self.assertRaises(NotAllowed):
roles.Advisor.get_inherit_mode()
# Check if the role class using ALL_MODELS
# actually get all models by your method.
models_list = roles.Coordenator.get_models()
self.assertEqual(models_list, apps.get_models())
| [
37811,
20934,
13511,
5254,
37227,
198,
6738,
42625,
14208,
13,
18211,
1330,
6725,
198,
6738,
42625,
14208,
13,
9288,
1330,
6208,
20448,
198,
198,
6738,
6596,
62,
525,
8481,
13,
1069,
11755,
1330,
12205,
525,
306,
16934,
1522,
11,
1892,
... | 2.684096 | 459 |
from Algorithims import Algorithms
import time
import threading
import random
| [
6738,
978,
7727,
12078,
1330,
978,
7727,
907,
198,
11748,
640,
198,
11748,
4704,
278,
198,
11748,
4738,
628
] | 4.157895 | 19 |
# This file is executed on every boot (including wake-boot from deepsleep)
import esp
esp.osdebug(None)
#import webrepl
#webrepl.start()
| [
2,
770,
2393,
318,
10945,
319,
790,
6297,
357,
8201,
7765,
12,
18769,
422,
2769,
42832,
8,
201,
198,
11748,
15024,
201,
198,
9774,
13,
418,
24442,
7,
14202,
8,
201,
198,
2,
11748,
3992,
35666,
201,
198,
2,
732,
4679,
489,
13,
9688... | 3.021277 | 47 |
# Exercício Python 26: Faça um programa que calcule a soma entre todos os números que são múltiplos de três e que se encontram no intervalo de 1 até 500.
soma = 0
for i in range(1, 501):
if i % 2 != 0 and i % 3 == 0:
soma += i
print(soma) | [
2,
1475,
2798,
8836,
66,
952,
11361,
2608,
25,
18350,
50041,
23781,
1430,
64,
8358,
2386,
23172,
257,
3870,
64,
920,
260,
284,
37427,
28686,
299,
21356,
647,
418,
8358,
264,
28749,
285,
21356,
2528,
24705,
418,
390,
491,
25792,
82,
30... | 2.321101 | 109 |
# -*- coding: utf-8 -*-
from bleak import BleakClient
from toio_API.characteristics import (
Battery,
Button,
Configuration,
Lamp,
MagneticSensor,
MotionSensor,
Motor,
Reader,
Sound,
)
class Toio:
"""The toio cube to control.
For more information, please refer to https://toio.github.io/toio-spec/docs/ble_communication_overview.
Args:
address (str, optional): Bluetooth device address of toio in small letter.
- Defaults to None.
name (str, optional): Name of toio.
- Defaults to None.
"""
@property
@property
@property
@property
@property
@property
@property
@property
@property
@property
@property
@property
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
198,
6738,
30942,
1330,
17175,
461,
11792,
198,
6738,
284,
952,
62,
17614,
13,
22769,
3969,
1330,
357,
198,
220,
220,
220,
23490,
11,
198,
220,
220,
220,
20969,
11,
19... | 2.506536 | 306 |
from django.test import TestCase
from django.core.urlresolvers import reverse
from wagtail.tests.utils import WagtailTestUtils
from django.test.utils import override_settings
from wagtail.tests.models import Advert, AlphaSnippet, ZuluSnippet
from wagtail.wagtailsnippets.models import register_snippet, SNIPPET_MODELS
from wagtail.wagtailsnippets.views.snippets import (
get_snippet_edit_handler
)
from wagtail.wagtailsnippets.edit_handlers import SnippetChooserPanel
from wagtail.wagtailcore.models import Page
| [
6738,
42625,
14208,
13,
9288,
1330,
6208,
20448,
198,
6738,
42625,
14208,
13,
7295,
13,
6371,
411,
349,
690,
1330,
9575,
198,
198,
6738,
266,
363,
13199,
13,
41989,
13,
26791,
1330,
21309,
13199,
14402,
18274,
4487,
198,
6738,
42625,
14... | 2.960674 | 178 |
#!/usr/bin/env python
import rospy
import json
import contextlib
import time
from std_msgs.msg import *
from motivational_component.msg import *
from motivational_component.srv import *
import signal
import sys
try:
from sensor_msgs.msg import BatteryState
except ImportError:
SIMULATION = True
else:
SIMULATION = False
import datetime as dt
if __name__ == '__main__':
MotivationnalComponent()
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
198,
198,
11748,
686,
2777,
88,
198,
11748,
33918,
198,
11748,
4732,
8019,
198,
11748,
640,
198,
6738,
14367,
62,
907,
14542,
13,
19662,
1330,
1635,
198,
6738,
49066,
62,
42895,
13,
19662,
... | 3.058824 | 136 |
import torch
import os, sys
from multiprocessing import Process, Manager
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), 'submodels', 'SoftConciseNormalForm')))
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), 'submodels', 'RegexGenerator')))
from collections import Counter
from submodels.RegexGenerator.batch import *
import submodels.SCNF.synthesizer
from submodels.SCNF.parsetree import *
import submodels.SCNF.synthesizer_snort
from submodels.SCNF.util_snort import *
from seq2seq.dataset.dataset import Vocabulary
from submodels.SCNF.examples import Examples
from rpni import synthesis as rpni_synthesis
| [
11748,
28034,
198,
198,
11748,
28686,
11,
25064,
198,
6738,
18540,
305,
919,
278,
1330,
10854,
11,
9142,
198,
198,
17597,
13,
6978,
13,
33295,
7,
418,
13,
6978,
13,
397,
2777,
776,
7,
418,
13,
6978,
13,
22179,
7,
418,
13,
6978,
13... | 2.929825 | 228 |
import joblib
import sys
from sklearn.tree import DecisionTreeClassifier
# print("Hello World")
model=joblib.load("model.h5")
result=model.predict([[float(sys.argv[1]),float(sys.argv[2]),float(sys.argv[3]),float(sys.argv[4]),float(sys.argv[5]),float(sys.argv[6]),float(sys.argv[7])]])
result=result[0]
if result==1:
print("Tomato")
elif result==2:
print("Potato")
elif result==3:
print("Soyabean")
elif result==4:
print("Strawberry")
elif result==5:
print("Bell Pepper")
elif result==6:
print("Raspberry")
elif result==7:
print("Peach")
elif result==8:
print("Grapes")
elif result==9:
print("Orange")
elif result==10:
print("Corn")
elif result==11:
print("Cherry") | [
11748,
1693,
8019,
198,
11748,
25064,
198,
6738,
1341,
35720,
13,
21048,
1330,
26423,
27660,
9487,
7483,
198,
2,
3601,
7203,
15496,
2159,
4943,
198,
19849,
28,
21858,
8019,
13,
2220,
7203,
19849,
13,
71,
20,
4943,
198,
20274,
28,
19849,... | 2.4 | 295 |
# coding=utf8
import lldb
from lldbsuite.test.lldbtest import *
import lldbsuite.test.lldbutil as lldbutil
from lldbsuite.test.decorators import *
| [
2,
19617,
28,
40477,
23,
198,
11748,
32660,
9945,
198,
6738,
32660,
67,
1443,
84,
578,
13,
9288,
13,
297,
9945,
9288,
1330,
1635,
198,
11748,
32660,
67,
1443,
84,
578,
13,
9288,
13,
297,
67,
4360,
346,
355,
32660,
67,
4360,
346,
1... | 2.508475 | 59 |
password="pbkdf2(1000,20,sha512)$a3a3bce6673b9c58$b1659a51cdaac695c2cea3435527a5d08515c3d1"
| [
28712,
2625,
40842,
74,
7568,
17,
7,
12825,
11,
1238,
11,
26270,
25836,
8,
3,
64,
18,
64,
18,
65,
344,
2791,
4790,
65,
24,
66,
3365,
3,
65,
1433,
3270,
64,
4349,
66,
6814,
330,
37381,
66,
17,
344,
64,
2682,
28567,
1983,
64,
20... | 1.672727 | 55 |
"""
Cache for storing and retrieving routing information in a pod.
"""
from grow.routing import router
FILE_ROUTES_CACHE = 'routescache.json'
class RoutesCache(object):
"""Routes cache for caching routing data in a pod."""
KEY_CONCRETE = 'concrete'
KEY_DYNAMIC = 'dynamic'
KEY_NONE = '__None__'
@classmethod
@staticmethod
def add(self, key, value, options=None, concrete=False, env=None):
"""Add a new item to the cache or overwrite an existing value."""
if env is None:
env = self.KEY_NONE
cache_key = self._cache_key(concrete)
if env not in self._cache[cache_key]:
self._cache[cache_key][env] = {}
cache = self._cache[cache_key][env]
cache_value = {
'value': value,
'options': options,
}
if not self._is_dirty and (key not in cache or cache[key] != cache_value):
self._is_dirty = True
cache[key] = cache_value
def export(self, concrete=None):
"""Returns the raw cache data."""
if concrete is None:
return {
'version': 1,
self.KEY_CONCRETE: self._export_cache(self._cache[self.KEY_CONCRETE]),
self.KEY_DYNAMIC: self._export_cache(self._cache[self.KEY_DYNAMIC]),
}
return self._export_cache(self._cache[self._cache_key(concrete)])
def from_data(self, data):
"""Set the cache from data."""
# Check for version changes in the data format.
version = data.get('version')
if not version or version < 1:
return
for super_key in [self.KEY_DYNAMIC, self.KEY_CONCRETE]:
if super_key in data:
concrete = super_key == self.KEY_CONCRETE
for env, env_data in data[super_key].items():
for key, item in env_data.items():
self.add(
key,
router.RouteInfo.from_data(**item['value']),
options=item['options'], concrete=concrete,
env=env)
def get(self, key, concrete=False, env=None):
"""Retrieve the value from the cache."""
if env is None:
env = self.KEY_NONE
return self._cache[self._cache_key(concrete)].get(env, {}).get(key, None)
@property
def is_dirty(self):
"""Have the contents of the object cache been modified?"""
return self._is_dirty
def mark_clean(self):
"""Mark that the object cache is clean."""
self._is_dirty = False
def raw(self, concrete=None, env=None):
"""Returns the raw cache data."""
if concrete is None:
return self._cache
if env is None:
env = self.KEY_NONE
return self._cache[self._cache_key(concrete)].get(env, {})
def remove(self, key, concrete=False, env=None):
"""Removes a single element from the cache."""
if env is None:
env = self.KEY_NONE
self._is_dirty = True
return self._cache[self._cache_key(concrete)].get(env, {}).pop(key, None)
def reset(self):
"""Reset the internal cache object."""
self._cache = {
self.KEY_CONCRETE: {},
self.KEY_DYNAMIC: {},
}
self._is_dirty = False
| [
37811,
198,
30562,
329,
23069,
290,
50122,
28166,
1321,
287,
257,
24573,
13,
198,
37811,
198,
198,
6738,
1663,
13,
81,
13660,
1330,
20264,
628,
198,
25664,
62,
49,
12425,
1546,
62,
34,
2246,
13909,
796,
705,
81,
448,
3798,
4891,
13,
... | 2.141952 | 1,578 |
#coding=utf-8
import os
import sys
sys.path.insert(0, os.path.abspath('src'))
| [
2,
66,
7656,
28,
40477,
12,
23,
198,
198,
11748,
28686,
198,
11748,
25064,
198,
198,
17597,
13,
6978,
13,
28463,
7,
15,
11,
28686,
13,
6978,
13,
397,
2777,
776,
10786,
10677,
6,
4008,
198
] | 2.222222 | 36 |
# Solution of;
# Project Euler Problem 668: Square root smooth Numbers
# https://projecteuler.net/problem=668
#
# A positive integer is called square root smooth if all of its prime factors
# are strictly less than its square root. Including the number $1$, there are
# $29$ square root smooth numbers not exceeding $100$. How many square root
# smooth numbers are there not exceeding $10\,000\,000\,000$?
#
# by lcsm29 http://github.com/lcsm29/project-euler
import timed
if __name__ == '__main__':
n = 1000
i = 10000
prob_id = 668
timed.caller(dummy, n, i, prob_id)
| [
2,
28186,
286,
26,
198,
2,
4935,
412,
18173,
20647,
718,
3104,
25,
9276,
6808,
7209,
27797,
198,
2,
3740,
1378,
16302,
68,
18173,
13,
3262,
14,
45573,
28,
35809,
198,
2,
220,
198,
2,
317,
3967,
18253,
318,
1444,
6616,
6808,
7209,
... | 3.046392 | 194 |
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
import re
DIAL_PARAMETERS = ("reason", "text_or_audio")
@csrf_exempt
| [
6738,
42625,
14208,
13,
19509,
23779,
1330,
8543,
198,
6738,
42625,
14208,
13,
33571,
13,
12501,
273,
2024,
13,
6359,
41871,
1330,
269,
27891,
69,
62,
42679,
198,
11748,
302,
198,
198,
35,
12576,
62,
27082,
2390,
2767,
4877,
796,
5855,
... | 2.775862 | 58 |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from vilya.libs.template import st
from vilya.models.sshkey import SSHKey
_q_exports = []
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
198,
6738,
11593,
37443,
834,
1330,
4112,
62,
11748,
198,
198,
6738,
410,
813,
64,
13,
8019,
82,
13,
28243,
1330,
336,
198,
6738,
410,
813,
64,
13,
27530,
13,
45824,
... | 2.633333 | 60 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import logging
import time
import sys
from pgoapi import PGoApi
from pgoapi.utilities import f2i, get_cellid
from . import config
from .models import parse_map
log = logging.getLogger(__name__)
TIMESTAMP = '\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000'
REQ_SLEEP = 1
failed_consecutive = 0
api = PGoApi()
| [
2,
48443,
14629,
14,
8800,
14,
29412,
198,
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
198,
11748,
18931,
198,
11748,
640,
198,
11748,
25064,
198,
6738,
279,
2188,
15042,
1330,
350,
5247,
32,
14415,
198,
6738,
279... | 2.33526 | 173 |
from __future__ import print_function, unicode_literals
import sys
import os
import screed
if __name__ == '__main__':
main()
| [
6738,
11593,
37443,
834,
1330,
3601,
62,
8818,
11,
28000,
1098,
62,
17201,
874,
198,
198,
11748,
25064,
198,
11748,
28686,
198,
198,
11748,
629,
15977,
198,
198,
361,
11593,
3672,
834,
6624,
705,
834,
12417,
834,
10354,
198,
220,
220,
... | 2.933333 | 45 |
import numpy as np
import joblib
import pandas as pd
import statsmodels.formula.api as smf
{% include 'load_data.py' %}
| [
11748,
299,
32152,
355,
45941,
198,
11748,
1693,
8019,
198,
11748,
19798,
292,
355,
279,
67,
198,
11748,
9756,
27530,
13,
687,
4712,
13,
15042,
355,
895,
69,
628,
198,
90,
4,
2291,
705,
2220,
62,
7890,
13,
9078,
6,
4064,
92,
628
] | 2.860465 | 43 |
import numpy as np
import cv2
import pyautogui | [
11748,
299,
32152,
355,
45941,
198,
11748,
269,
85,
17,
198,
11748,
12972,
2306,
519,
9019
] | 2.875 | 16 |
from pyuploadcare.client import Uploadcare
from pyuploadcare.ucare_cli.commands.helpers import (
_list,
bool_or_none,
int_or_none,
)
| [
6738,
12972,
25850,
6651,
13,
16366,
1330,
36803,
6651,
198,
6738,
12972,
25850,
6651,
13,
1229,
533,
62,
44506,
13,
9503,
1746,
13,
16794,
364,
1330,
357,
198,
220,
220,
220,
4808,
4868,
11,
198,
220,
220,
220,
20512,
62,
273,
62,
... | 2.534483 | 58 |
import json
import datetime
from collections import defaultdict
from django.shortcuts import render, get_object_or_404, redirect
from django.http import HttpResponseBadRequest, Http404, HttpResponse, QueryDict
from django.contrib import messages
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.db.models import Count, Q
from vanilla import ListView, DetailView, UpdateView, CreateView, GenericView
import vobject
from schedule.models import *
from schedule.forms import *
| [
11748,
33918,
198,
11748,
4818,
8079,
198,
6738,
17268,
1330,
4277,
11600,
198,
6738,
42625,
14208,
13,
19509,
23779,
1330,
8543,
11,
651,
62,
15252,
62,
273,
62,
26429,
11,
18941,
198,
6738,
42625,
14208,
13,
4023,
1330,
367,
29281,
31... | 3.845588 | 136 |
import numpy as np
def linear_parts(num_atoms, num_threads):
"""Linear partitions
Parameters
----------
num_atoms: int
The number of data points
num_threads: int
The number of partitions to split
Returns
-------
array: indices of start and end
"""
parts = np.linspace(0, num_atoms, min(num_threads, num_atoms) + 1)
parts = np.ceil(parts).astype(int)
return parts
def nested_parts(num_atoms, num_threads, descend=False):
"""Nested partitions
Parameters
----------
num_atoms: int
The number of data points
num_threads: int
The number of partitions to split
descent: bool, (default False)
If True, the size of partitions are decreasing
Returns
-------
array: indices of start and end
"""
parts = [0]
num_threads = min(num_threads, num_atoms)
for num in range(num_threads):
part = 1 + 4 * (parts[-1] ** 2 + parts[-1] + num_atoms * (num_atoms + 1.) / num_threads)
part = 0.5 * (-1 + np.sqrt(part))
parts.append(part)
if descend:
# Computational decreases as index increases
parts = np.cumsum(np.diff(parts)[::-1])
parts = np.append(np.array([0]), parts)
parts = np.round(parts).astype(int)
return parts | [
11748,
299,
32152,
355,
45941,
628,
198,
4299,
14174,
62,
42632,
7,
22510,
62,
265,
3150,
11,
997,
62,
16663,
82,
2599,
198,
220,
220,
220,
37227,
14993,
451,
43869,
628,
220,
220,
220,
40117,
198,
220,
220,
220,
24200,
438,
198,
22... | 2.434701 | 536 |
# -*- coding: utf-8 -*-
igrok1 = 0
igrok2 = 0
win = 0
draw = 0
lose = 0
list_choises = ['Камень', 'Ножницы', 'Бумага']
print("(Камень - 1, Ножницы - 2, Бумага - 3) Игрок 1, введите ваш номер:")
igrok1 = verify(igrok1, 1)
igrok2 = verify(igrok2, 2)
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
328,
305,
74,
16,
796,
657,
198,
328,
305,
74,
17,
796,
657,
198,
5404,
796,
657,
198,
19334,
796,
657,
198,
75,
577,
796,
657,
198,
4868,
62,
6679,
2696,
796,
372... | 1.422857 | 175 |
"""
Generate randomized circuits for Quantum Volume analysis.
Example run:
python RandomCircuits.py -n 5 -d 5
"""
import sys
import math
import time
import argparse
import numpy as np
from scipy.linalg import qr
from scipy.linalg import det
from qiskit import QuantumProgram
from qiskit.mapper import two_qubit_kak
if sys.version_info < (3,0):
raise Exception("Please use Python version 3 or greater.")
def random_SU(n):
"""Return an n x n Haar distributed unitary matrix.
Return numpy array.
"""
X = (np.random.randn(n, n) + 1j*np.random.randn(n, n))
Q, R = qr(X) # Q is a unitary matrix
Q /= pow(det(Q), 1/n) # make Q a special unitary
return Q
def build_model_circuits(name, n, depth, num_circ=1):
"""Create a quantum program containing model circuits.
The model circuits consist of layers of Haar random
elements of SU(4) applied between corresponding pairs
of qubits in a random bipartition.
name = leading name of circuits
n = number of qubits
depth = ideal depth of each model circuit (over SU(4))
num_circ = number of model circuits to construct
Return a quantum program.
"""
qp = QuantumProgram()
q = qp.create_quantum_register("q", n)
c = qp.create_classical_register("c", n)
# Create measurement subcircuit
meas = qp.create_circuit("meas", [q], [c])
for j in range(n):
meas.measure(q[j], c[j])
# For each sample number, build the model circuits
for i in range(num_circ):
# Initialize empty circuit Ci without measurement
circuit_i = qp.create_circuit("%s_%d" % (name, i), [q], [c])
# For each layer
for j in range(depth):
# Generate uniformly random permutation Pj of [0...n-1]
perm = np.random.permutation(n)
# For each pair p in Pj, generate Haar random SU(4)
# Decompose each SU(4) into CNOT + SU(2) and add to Ci
for k in range(math.floor(n/2)):
qubits = [int(perm[2*k]), int(perm[2*k+1])]
SU = random_SU(4)
for gate in two_qubit_kak(SU):
i0 = qubits[gate["args"][0]]
if gate["name"] == "cx":
i1 = qubits[gate["args"][1]]
circuit_i.cx(q[i0], q[i1])
elif gate["name"] == "u1":
circuit_i.u1(gate["params"][2], q[i0])
elif gate["name"] == "u2":
circuit_i.u2(gate["params"][1], gate["params"][2],
q[i0])
elif gate["name"] == "u3":
circuit_i.u3(gate["params"][0], gate["params"][1],
gate["params"][2], q[i0])
elif gate["name"] == "id":
pass # do nothing
# circuit_i.barrier(q) # barriers between layers
circuit_i.barrier(q) # barrier before measurement
# Create circuit with final measurement
qp.add_circuit("%s_%d_meas" % (name, i), circuit_i + meas)
return qp
if __name__ == "__main__":
main()
| [
37811,
198,
8645,
378,
23925,
24907,
329,
29082,
14701,
3781,
13,
198,
198,
16281,
1057,
25,
198,
220,
21015,
14534,
31560,
15379,
13,
9078,
532,
77,
642,
532,
67,
642,
198,
37811,
198,
198,
11748,
25064,
198,
11748,
10688,
198,
11748,
... | 2.100863 | 1,507 |
from floodsystem.geo import rivers_by_station_number
from floodsystem.stationdata import build_station_list
if __name__ == "__main__":
print("*** Task 1D: CUED Part IA Flood Warning System ***")
run() | [
6738,
6947,
10057,
13,
469,
78,
1330,
18180,
62,
1525,
62,
17529,
62,
17618,
198,
6738,
6947,
10057,
13,
17529,
7890,
1330,
1382,
62,
17529,
62,
4868,
198,
198,
361,
11593,
3672,
834,
6624,
366,
834,
12417,
834,
1298,
198,
220,
220,
... | 3.215385 | 65 |
import mock
from collections import defaultdict
from searx.engines import fdroid
from searx.testing import SearxTestCase
| [
11748,
15290,
198,
6738,
17268,
1330,
4277,
11600,
198,
6738,
9622,
87,
13,
1516,
1127,
1330,
277,
67,
3882,
198,
6738,
9622,
87,
13,
33407,
1330,
42016,
87,
14402,
20448,
628
] | 3.935484 | 31 |
import os, shutil
import json
from xml.etree import ElementTree as ET
from GeometrA.src.File.Project import Project
| [
11748,
28686,
11,
4423,
346,
198,
11748,
33918,
198,
198,
6738,
35555,
13,
316,
631,
1330,
11703,
27660,
355,
12152,
198,
198,
6738,
2269,
908,
81,
32,
13,
10677,
13,
8979,
13,
16775,
1330,
4935,
628
] | 3.305556 | 36 |
from __future__ import division
import torch
import torch.nn as nn
import torch.nn.functional as F
from utils import norm_col_init, weights_init
# class agentNET(torch.nn.Module):
# def __init__(self, num_inputs = 1, num_outputs = 6):
# super(agentNET, self).__init__()
#
# self.conv1 = nn.Conv1d(num_inputs, 16, 3, stride=1, padding=1)
# self.conv2 = nn.Conv1d(16, 16, 2, stride=1)
# self.conv3 = nn.Conv1d(16, 8, 2, stride=1)
#
# self.lstm = nn.LSTMCell(32, 20)
# self.fc1 = nn.Linear(20, 10)
#
# self.critic_linear = nn.Linear(10, 1)
# self.actor_linear = nn.Linear(10, num_outputs)
#
# self.apply(weights_init)
# self.actor_linear.weight.data = norm_col_init(
# self.actor_linear.weight.data, 0.01)
# self.actor_linear.bias.data.fill_(0)
#
# self.critic_linear.weight.data = norm_col_init(
# self.critic_linear.weight.data, 1.0)
# self.critic_linear.bias.data.fill_(0)
#
# self.fc1.weight.data = norm_col_init(
# self.fc1.weight.data, 1.0)
# self.fc1.bias.data.fill_(0)
#
# self.lstm.bias_ih.data.fill_(0)
# self.lstm.bias_hh.data.fill_(0)
#
# self.train()
#
# def forward(self, inputs):
# inputs, (hx, cx) = inputs
# x = F.elu(self.conv1(inputs))
# x = F.elu(self.conv2(x))
# x = F.elu(self.conv3(x))
#
# x = x.view(x.size(0), -1)
#
# hx, cx = self.lstm(x, (hx, cx))
#
# x = F.elu(self.fc1(hx))
#
# return self.critic_linear(x), self.actor_linear(x), (hx, cx) | [
6738,
11593,
37443,
834,
1330,
7297,
198,
11748,
28034,
198,
11748,
28034,
13,
20471,
355,
299,
77,
198,
11748,
28034,
13,
20471,
13,
45124,
355,
376,
198,
6738,
3384,
4487,
1330,
2593,
62,
4033,
62,
15003,
11,
19590,
62,
15003,
198,
... | 1.827119 | 885 |
from . import process_gtex
| [
6738,
764,
1330,
1429,
62,
70,
16886,
198
] | 3.375 | 8 |
import logging
from typing import Dict, Optional
from bs4 import BeautifulSoup, NavigableString
from documental import Document
from documental.html import (
BareLink,
Figure,
Heading,
Image,
Images,
Link,
UnorderedList,
Style,
StyledText,
)
from documental.text import Text
from .url import absolute_url, is_url
styles: Dict[str, Style] = {
"b": Style.Bold,
"i": Style.Italics,
"del": Style.Strikethrough,
"ins": Style.Underlined,
"em": Style.Emphasis,
"u": Style.Misspelled,
"small": Style.Small,
}
| [
11748,
18931,
198,
6738,
19720,
1330,
360,
713,
11,
32233,
198,
198,
6738,
275,
82,
19,
1330,
23762,
50,
10486,
11,
13244,
328,
540,
10100,
198,
198,
6738,
3188,
282,
1330,
16854,
198,
6738,
3188,
282,
13,
6494,
1330,
357,
198,
220,
... | 2.526316 | 228 |
"""
Created on Wed Jul 22 22:27:09 2020
@author: wallissoncarvalho
"""
from nasadap import Nasa, parse_nasa_catalog
import json
# Parameters Definition
credentials = json.loads(open(".earthdata_credentials").read())
product_summary = {'mission': 'gpm', 'product': '3IMERGHH', 'version': 6, 'dataset_type': 'precipitationCal'}
dates = {'from': None, 'to': None}
# Coordinates Definition
coordinates = {'min_lat': -33, 'max_lat': 3, 'min_lon': -72, 'max_lon': -35}
# Getting the Initial and Final dates
min_max = parse_nasa_catalog(product_summary['mission'], product_summary['product'], product_summary['version'],
min_max=True)
# Dates definition
dates['from'] = min_max.from_date.to_list()[0].strftime("%Y-%m-%d")
dates['to'] = min_max.to_date.to_list()[-1].strftime("%Y-%m-%d")
# Accessing Nasa Available Products
nasa_access = Nasa(credentials['username'], credentials['password'], product_summary['mission'], cache_dir=r'prod_data')
# Downloading Data
dataset = nasa_access.get_data(product_summary['product'], product_summary['version'], product_summary['dataset_type'],
dates['from'], dates['to'], coordinates['min_lat'], coordinates['max_lat'],
coordinates['min_lon'], coordinates['max_lon'])
nasa_access.close()
| [
37811,
198,
41972,
319,
3300,
5979,
2534,
2534,
25,
1983,
25,
2931,
12131,
198,
31,
9800,
25,
3355,
30927,
7718,
2100,
8873,
198,
37811,
198,
198,
6738,
25221,
324,
499,
1330,
48673,
11,
21136,
62,
77,
15462,
62,
9246,
11794,
198,
117... | 2.549133 | 519 |
if __name__ == "__main__":
with open("params.txt", "w") as param_file:
N_list = [0]
# N_list = [16, 64]
# N_list = [128, 256, 512, 1024, 2048, 4096]
L_list = [16, 20, 24, 28]
p_list = {}
p_list[0] = [0.19, 0.195, 0.2, 0.205, 0.21]
p_list[16] = [0.028, 0.029, 0.03, 0.031, 0.032]
p_list[64] = [0.019, 0.02, 0.021, 0.022, 0.023]
p_list[128] = [0.016, 0.017, 0.018, 0.019, 0.02]
p_list[256] = [0.015, 0.016, 0.017, 0.018, 0.019]
p_list[512] = [0.014, 0.015, 0.016, 0.017, 0.018]
p_list[1024] = [0.013, 0.014, 0.015, 0.016, 0.017]
p_list[2048] = [0.013, 0.014, 0.015, 0.016, 0.017]
p_list[4096] = [0.013, 0.014, 0.015, 0.016, 0.017]
runs = 1000
i = 0
for N in N_list:
for L in L_list:
for p in p_list[N]:
param_file.write("{} {} {} {} {}\n".format(
i, N, L, p, runs))
i += 1
| [
361,
11593,
3672,
834,
6624,
366,
834,
12417,
834,
1298,
201,
198,
220,
220,
220,
351,
1280,
7203,
37266,
13,
14116,
1600,
366,
86,
4943,
355,
5772,
62,
7753,
25,
201,
198,
220,
220,
220,
220,
220,
220,
220,
399,
62,
4868,
796,
68... | 1.577744 | 656 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 1 08:40:54 2020
@author: james
A script for making a corner plot of a tested galaxy using the trained CAE.
"""
# =============================================================================
# Import relevant packages
# =============================================================================
import corner
import numpy as np
import matplotlib.pyplot as plt
import multiprocessing as mp
import torch
from tqdm import tqdm
import sys
sys.path.append("../utils/")
from model_int import CAE
from functions import return_cube
from rcparams import rcparams
rcparams()
# =============================================================================
# Setup paths
# =============================================================================
model_path = '/path/to/saved/models/'
image_path = '/path/to/save/images/'
# =============================================================================
# Load the model
# =============================================================================
model = CAE()
model.load_state_dict(torch.load(model_path+'semantic_AE_KinMS_ONLY.pt'))
model = model.cpu()
model.train(False)
model.apply(apply_dropout)
print("Model cast to CPU")
# =============================================================================
# Create the test data
# =============================================================================
index = np.array([1])
num_cores = 14
pool = mp.Pool(num_cores,maxtasksperchild=100)
results = list(pool.imap(return_cube,index))
pool.close()
batch = np.array([r[0] for r in results])
target = np.array([r[1:] for r in results])
batch = torch.tensor(batch).to(torch.float)
batch[batch!=batch]=0
target = torch.tensor(target).to(torch.float)
pos = target[:,0]
ah = target[:,-2]*32
a = target[:,-3]*32
mom0s, mom1s = batch[:,0,:,:].unsqueeze(1), batch[:,1,:,:].unsqueeze(1)
print("Test data created")
# =============================================================================
# Run the testing procedure
# =============================================================================
predictions = []
errors = []
temp_pred = []
for _ in tqdm(range(10000)):
prediction1 = model.test_encode(mom0s,mom1s,pos)
prediction1 = prediction1.detach().numpy()
temp_pred.append(prediction1)
temp_pred = np.vstack(temp_pred)
mean_pred = np.mean(temp_pred,0)
predictions.append(mean_pred)
errors.append(np.sum(np.abs(temp_pred-mean_pred[None,:]),0)/len(temp_pred))
p = temp_pred
p = p[:,1:]
p[:,0] = np.rad2deg(p[:,0])
p[:,1] *= 32
p[:,2] *= 32
_labels = ['i ($^{\circ}$)','$r_{scale}$ ($\prime\prime$)','$r_{turn}$ ($\prime\prime$)','$V_{max} \, sin(i) \, (km\,s^{-1})$']
# =============================================================================
# Make the corner plot
# =============================================================================
figure = corner.corner(p,bins=20, labels=_labels)
plt.tight_layout()
plt.savefig(image_path + 'corner_single.pdf')
# =============================================================================
# End of script
# =============================================================================
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
18,
198,
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
198,
37811,
198,
41972,
319,
2892,
7653,
220,
352,
8487,
25,
1821,
25,
4051,
12131,
198,
198,
31,
9800,
25,
474,
1047,... | 3.577009 | 896 |
# Authors: Gael Varoquaux <gael.varoquaux@normalesup.org>
# Justin Vincent
# Lars Buitinck
# License: BSD 3 clause
import numpy as np
from nose.tools import assert_equal
from numpy.testing import (assert_almost_equal,
assert_array_almost_equal)
from sklearn.utils.fixes import divide, expit
| [
2,
46665,
25,
39652,
569,
12022,
421,
14644,
1279,
70,
3010,
13,
7785,
22696,
14644,
31,
27237,
2040,
929,
13,
2398,
29,
198,
2,
220,
220,
220,
220,
220,
220,
220,
220,
220,
10799,
18653,
198,
2,
220,
220,
220,
220,
220,
220,
220,... | 2.41844 | 141 |
# -*- coding: utf-8 -*-
from sys import version_info
if version_info[0] > 2 or version_info[1] >= 7:
from collections import OrderedDict
else:
from ._py24_ordereddict import OrderedDict # noqa
| [
2,
532,
9,
12,
19617,
25,
3384,
69,
12,
23,
532,
9,
12,
201,
198,
6738,
25064,
1330,
2196,
62,
10951,
201,
198,
201,
198,
361,
2196,
62,
10951,
58,
15,
60,
1875,
362,
393,
2196,
62,
10951,
58,
16,
60,
18189,
767,
25,
201,
198,... | 2.53012 | 83 |
import pandas as pd
AMZ_data = pd.read_csv('AMZ_data_resample_gps.csv')
print(len(AMZ_data.lat)) | [
11748,
19798,
292,
355,
279,
67,
201,
198,
201,
198,
2390,
57,
62,
7890,
796,
279,
67,
13,
961,
62,
40664,
10786,
2390,
57,
62,
7890,
62,
411,
1403,
62,
70,
862,
13,
40664,
11537,
201,
198,
201,
198,
4798,
7,
11925,
7,
2390,
57,... | 2.04 | 50 |
import os, sys
import zipfile
import numpy as np
import spacekit
from spacekit.transformer import Transformer
from spacekit.builder import Builder
if __name__ == '__main__':
import spacekit
prep = Prep()
prep.unzip('/exoTrain.csv.zip', '/exoTest.csv.zip')
X_train, X_test, y_train, y_test = prep.split_data('/exoTrain.csv', '/exoTest.csv')
X_train, X_test = prep.scale_data(X_train, X_test)
X_train, X_test = prep.add_filter(X_train, X_test)
learning_rate, epochs = main(sys.argv)
launch = Launch(X_train, X_test, y_train, y_test, learning_rate, epochs)
cnn = launch.deploy()
history = launch.takeoff(cnn)
| [
11748,
28686,
11,
25064,
198,
11748,
19974,
7753,
198,
11748,
299,
32152,
355,
45941,
198,
11748,
2272,
15813,
198,
6738,
2272,
15813,
13,
7645,
16354,
1330,
3602,
16354,
198,
6738,
2272,
15813,
13,
38272,
1330,
35869,
198,
198,
361,
1159... | 2.509653 | 259 |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
identicon.py
identicon python implementation.
by Shin Adachi <shn@glucose.jp>
= usage =
== commandline ==
>>> python identicon.py [code]
== python ==
>>> import identicon
>>> identicon.render_identicon(code, size)
Return a PIL Image class instance which have generated identicon image.
```size``` specifies `patch size`. Generated image size is 3 * ```size```.
"""
# g
# PIL Modules
import Image
import ImageDraw
import ImagePath
import ImageColor
__all__ = ['render_identicon', 'IdenticonRendererBase']
class Matrix2D(list):
"""Matrix for Patch rotation"""
@classmethod
@classmethod
"""
# need `import math`
@classmethod
def rotate(kls, theta, pivot=None):
c = math.cos(theta)
s = math.sin(theta)
matR = kls([c, -s, 0., s, c, 0., 0., 0., 1.])
if not pivot:
return matR
return kls.translate(-pivot[0], -pivot[1]) * matR *
kls.translate(*pivot)
"""
@classmethod
class DonRenderer(IdenticonRendererBase):
"""
Don Park's implementation of identicon
see : http://www.docuverse.com/blog/donpark/2007/01/19/identicon-updated-and-source-released
"""
PATH_SET = [
[(0, 0), (4, 0), (4, 4), (0, 4)], # 0
[(0, 0), (4, 0), (0, 4)],
[(2, 0), (4, 4), (0, 4)],
[(0, 0), (2, 0), (2, 4), (0, 4)],
[(2, 0), (4, 2), (2, 4), (0, 2)], # 4
[(0, 0), (4, 2), (4, 4), (2, 4)],
[(2, 0), (4, 4), (2, 4), (3, 2), (1, 2), (2, 4), (0, 4)],
[(0, 0), (4, 2), (2, 4)],
[(1, 1), (3, 1), (3, 3), (1, 3)], # 8
[(2, 0), (4, 0), (0, 4), (0, 2), (2, 2)],
[(0, 0), (2, 0), (2, 2), (0, 2)],
[(0, 2), (4, 2), (2, 4)],
[(2, 2), (4, 4), (0, 4)],
[(2, 0), (2, 2), (0, 2)],
[(0, 0), (2, 0), (0, 2)],
[]] # 15
MIDDLE_PATCH_SET = [0, 4, 8, 15]
# modify path set
for idx in xrange(len(PATH_SET)):
if PATH_SET[idx]:
p = map(lambda vec: (vec[0] / 4.0, vec[1] / 4.0), PATH_SET[idx])
PATH_SET[idx] = p + p[:1]
if __name__ == '__main__':
import sys
if len(sys.argv) < 2:
print 'usage: python identicon.py [CODE]....'
raise SystemExit
for code in sys.argv[1:]:
if code.startswith('0x') or code.startswith('0X'):
code = int(code[2:], 16)
elif code.startswith('0'):
code = int(code[1:], 8)
else:
code = int(code)
icon = render_identicon(code, 24)
icon.save('%08x.png' % code, 'PNG')
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
198,
2,
532,
9,
12,
19617,
25,
40477,
12,
23,
532,
9,
12,
198,
37811,
198,
738,
4749,
13,
9078,
198,
738,
4749,
21015,
7822,
13,
198,
1525,
11466,
1215,
14299,
1279,
1477,
77,
31,
4743,... | 1.915169 | 1,391 |
import math
import numpy as np
import cv2
import tensorflow as tf
import gc
from PIL import Image, ImageFile
| [
11748,
10688,
198,
11748,
299,
32152,
355,
45941,
198,
11748,
269,
85,
17,
198,
11748,
11192,
273,
11125,
355,
48700,
198,
11748,
308,
66,
198,
6738,
350,
4146,
1330,
7412,
11,
7412,
8979,
628
] | 3.235294 | 34 |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Run BERT on SQuAD."""
from __future__ import absolute_import, division, print_function
import argparse
import logging
import os
import random
import sys
from io import open
import numpy as np
import torch
from torch.utils.data import (DataLoader, RandomSampler, SequentialSampler,
TensorDataset)
from torch.utils.data.distributed import DistributedSampler
from tqdm import tqdm, trange
from tensorboardX import SummaryWriter
from pytorch_pretrained_bert.file_utils import WEIGHTS_NAME, CONFIG_NAME
from pytorch_pretrained_bert.modeling import BertForQuestionAnswering
from pytorch_pretrained_bert.optimization import BertAdam, WarmupLinearSchedule
from pytorch_pretrained_bert.tokenization import BertTokenizer
from run_squad_dataset_utils import read_squad_examples, convert_examples_to_features, RawResult, write_predictions
if sys.version_info[0] == 2:
import cPickle as pickle
else:
import pickle
logger = logging.getLogger(__name__)
if __name__ == "__main__":
main()
| [
2,
19617,
28,
40477,
12,
23,
198,
2,
15069,
2864,
383,
3012,
9552,
15417,
4816,
46665,
290,
383,
12905,
2667,
32388,
3457,
13,
1074,
13,
198,
2,
15069,
357,
66,
8,
2864,
11,
15127,
23929,
44680,
6234,
13,
220,
1439,
2489,
10395,
13,... | 3.277358 | 530 |
#!/usr/bin/env python
#
# Splits a big trace file of multiple top level functions into separate traces
# for each function.
#
# This is useful for breaking up an accelerator into smaller blocks, where each
# block might call multiple other functions.
#
# Author: Sam Xi
import argparse
import gzip
import os
import io
import re
import time
LABELMAP_START = "%%%% LABEL MAP START %%%%"
LABELMAP_END = "%%%% LABEL MAP END %%%%"
RET_OP = 1
def split_trace(trace_fname):
""" Splits a dynamic trace of multiple functions into individual traces. """
top_level_funcs = [] # f.strip() for f in top_level_funcs]
sub_trace_files = {} #dict((func, gzip.open("%s.gz" % func, "wb")) for func in top_level_funcs)
labelmap = ""
curr_func = ""
print "Starting time:", time.ctime()
with gzip.open(trace_fname, "rb") as gz_file:
with io.BufferedReader(gz_file) as main_trace:
# Just look for and write the labelmap, if it exists.
for line in strip(main_trace):
if line == LABELMAP_START:
labelmap = parse_labelmap(main_trace)
break
break
# Now process the remainder of the trace.
for line in strip(main_trace):
components = line.split(",")
if components[0] == "entry":
func_name = components[1]
if not func_name in top_level_funcs:
top_level_funcs.append(func_name)
sub_trace_files[func_name] = io.BufferedWriter(gzip.open("%s.gz" % func_name, "wb"))
sub_trace_files[func_name].write(labelmap)
print "Found top level function", func_name
else:
print "Copying function", func_name
copy_function(main_trace, line, func_name, sub_trace_files[func_name])
for f in sub_trace_files.itervalues():
f.close()
print "Ending time:", time.ctime()
if __name__ == "__main__":
main()
| [
2,
48443,
14629,
14,
8800,
14,
24330,
21015,
198,
2,
198,
2,
13341,
896,
257,
1263,
12854,
2393,
286,
3294,
1353,
1241,
5499,
656,
4553,
20675,
198,
2,
329,
1123,
2163,
13,
198,
2,
198,
2,
770,
318,
4465,
329,
7163,
510,
281,
4421... | 2.535957 | 737 |