code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
# currScenRecQuery = """
# SELECT * from 'pla_scenario_values_new2' where rid='{rId}' and qno='{qNo}'
# """.format(rId=1, qNo=2)
# currScenRec = db.fetch_results(currScenRecQuery, single_row=True)
#
# updateBetaAttrQuery = """
# UPDATE 'pla_scenario_values_new2' SET 'beta_sde' = '{beta_sde}',
# 'beta_tts' = '{beta_tts}', 'beta_rp' = '{beta_rp}', 'beta_sdl' = '{beta_sdl}'
# WHERE 'pla_scenario_values_new2'.'rid' = {rId} AND 'pla_scenario_values_new2'.'qno' = '{num}';
# """.format(beta_sde=1, beta_tts=2, beta_rp=3, beta_sdl=4, rId=5, num=6)
# db.execute(updateBetaAttrQuery)
################### make query to fetch data ################
## start mysql service manually if failed (run->services.msc->mysql (right click) ->start)
id = 'a0be48f6b592ebcbd536f6a615be005f2066335665973d868907bd32706fe81c'
acc = 21
query = """
SELECT * from `testtest_mysql1` where id='{id}' and accuracy='{acc}'
""".format(id=id, acc=acc)
## two methods
## use db.py
import db
results = db.fetch_results('cuebiq201911', query)
print (results)
## use directly
import pymysql as mysql
dbconnect = mysql.connect(host='localhost', database='cuebiq201911', user='root', password='<PASSWORD>')
dbcursor = dbconnect.cursor()
dbcursor.execute(query)
results = dbcursor.fetchall() # is a duple of duples
[list(item) for item in results] # turn into a list of lists
dbcursor.close()
dbconnect.close()
############################ creat database ####################
import pymysql as mysql
dbconnect = mysql.connect(host='localhost', user='root', password='<PASSWORD>')
dbcursor = dbconnect.cursor()
dbcursor.execute("CREATE DATABASE cuebiq201801to03;") #SHOW DATABASES; USE cuebiq201911; #
dbconnect.commit() # commit before close; if commit, return None, else, return result
dbcursor.close()
dbconnect.close()
################### creat table and load csv ################
## creat table: two method: 1) use db.py; 2) use directly
query1 = """
CREATE TABLE {table} (
row_i INT NOT NULL AUTO_INCREMENT, unix_time INT NOT NULL, id VARCHAR(255) NOT NULL, type TINYINT NOT NULL,
latitude FLOAT NOT NULL, longitude FLOAT NOT NULL, accuracy SMALLINT NOT NULL, timezone SMALLINT NOT NULL,
PRIMARY KEY (row_i), INDEX id (id))
""".format(table='upzip') # '{table}' return error
db.execute('cuebiq201801to03', query1)
## load csv: cannot use db.py because of the reason specified below
## Make sure to have autocommit turned on. To upload files, you need to set the local_infile parameter to 1.
usedatabase = 'cuebiq201801to03'
usetable = 'upzip'
dbconnect = mysql.connect(host='localhost', database=usedatabase, user='root', password='<PASSWORD>', autocommit=True, local_infile=1)
dbcursor = dbconnect.cursor()
import os
filedaylist = os.listdir('E:\\cuebiq_psrc_2019\\sorted')
filedaylist = [fileday for fileday in filedaylist if fileday.startswith('unzip20') and fileday <= 'unzip20180331.csv']
for filename in filedaylist:
infilepath = 'E:/cuebiq_psrc_2019/sorted/' + filename #'E:/cuebiq_psrc_2019/sorted/testtest_mysql.csv'
print (infilepath)
query2 = """
LOAD DATA LOCAL INFILE '{infilepath}' INTO TABLE {totable}
FIELDS TERMINATED BY '\\t'
LINES TERMINATED BY '\\n'
(unix_time, id, type, latitude, longitude, accuracy, timezone);
""".format(infilepath=infilepath, totable=usetable) # {infilepath} return error
# db.execute('cuebiq201911', query2) # Error: InternalError(1148, u'The used command is not allowed with this MySQL version')
dbcursor.execute(query2)
dbconnect.commit()
dbcursor.close()
dbconnect.close()
| [
"os.listdir",
"pymysql.connect",
"db.fetch_results",
"db.execute"
] | [((1141, 1180), 'db.fetch_results', 'db.fetch_results', (['"""cuebiq201911"""', 'query'], {}), "('cuebiq201911', query)\n", (1157, 1180), False, 'import db\n'), ((1255, 1351), 'pymysql.connect', 'mysql.connect', ([], {'host': '"""localhost"""', 'database': '"""cuebiq201911"""', 'user': '"""root"""', 'password': '"""<PASSWORD>"""'}), "(host='localhost', database='cuebiq201911', user='root',\n password='<PASSWORD>')\n", (1268, 1351), True, 'import pymysql as mysql\n'), ((1665, 1732), 'pymysql.connect', 'mysql.connect', ([], {'host': '"""localhost"""', 'user': '"""root"""', 'password': '"""<PASSWORD>"""'}), "(host='localhost', user='root', password='<PASSWORD>')\n", (1678, 1732), True, 'import pymysql as mysql\n'), ((2513, 2551), 'db.execute', 'db.execute', (['"""cuebiq201801to03"""', 'query1'], {}), "('cuebiq201801to03', query1)\n", (2523, 2551), False, 'import db\n'), ((2800, 2927), 'pymysql.connect', 'mysql.connect', ([], {'host': '"""localhost"""', 'database': 'usedatabase', 'user': '"""root"""', 'password': '"""<PASSWORD>"""', 'autocommit': '(True)', 'local_infile': '(1)'}), "(host='localhost', database=usedatabase, user='root', password\n ='<PASSWORD>', autocommit=True, local_infile=1)\n", (2813, 2927), True, 'import pymysql as mysql\n'), ((2982, 3024), 'os.listdir', 'os.listdir', (['"""E:\\\\cuebiq_psrc_2019\\\\sorted"""'], {}), "('E:\\\\cuebiq_psrc_2019\\\\sorted')\n", (2992, 3024), False, 'import os\n')] |
# -*- coding: utf-8 -*-
'''
VKGroups
Copyright © 2010-2018 HeaTTheatR
Для предложений и вопросов:
<<EMAIL>>
Данный файл распространяется по услолвиям той же лицензии,
что и фреймворк Kivy.
'''
from jnius import autoclass, PythonJavaClass, java_method, cast
from android.runnable import run_on_ui_thread
Toast = autoclass('android.widget.Toast')
context = autoclass('org.kivy.android.PythonActivity').mActivity
@run_on_ui_thread
def toast(text, length_long=False):
duration = Toast.LENGTH_LONG if length_long else Toast.LENGTH_SHORT
String = autoclass('java.lang.String')
c = cast('java.lang.CharSequence', String(text))
t = Toast.makeText(context, c, duration)
t.show()
| [
"jnius.autoclass"
] | [((318, 351), 'jnius.autoclass', 'autoclass', (['"""android.widget.Toast"""'], {}), "('android.widget.Toast')\n", (327, 351), False, 'from jnius import autoclass, PythonJavaClass, java_method, cast\n'), ((362, 406), 'jnius.autoclass', 'autoclass', (['"""org.kivy.android.PythonActivity"""'], {}), "('org.kivy.android.PythonActivity')\n", (371, 406), False, 'from jnius import autoclass, PythonJavaClass, java_method, cast\n'), ((557, 586), 'jnius.autoclass', 'autoclass', (['"""java.lang.String"""'], {}), "('java.lang.String')\n", (566, 586), False, 'from jnius import autoclass, PythonJavaClass, java_method, cast\n')] |
# Copyright 2020 Adap GmbH. 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.
# ==============================================================================
"""Federating: Fast and Slow."""
import statistics
from typing import Callable, Dict, List, Optional, Tuple, cast
import numpy as np
from flower.client_manager import ClientManager
from flower.client_proxy import ClientProxy
from flower.typing import EvaluateRes, FitIns, FitRes, Weights
from .aggregate import aggregate, weighted_loss_avg
from .fedavg import FedAvg
from .parameter import parameters_to_weights, weights_to_parameters
class FastAndSlow(FedAvg):
"""Strategy implementation which alternates between fast and slow rounds."""
# pylint: disable-msg=too-many-arguments,too-many-instance-attributes
def __init__(
self,
fraction_fit: float = 0.1,
fraction_eval: float = 0.1,
min_fit_clients: int = 1,
min_eval_clients: int = 1,
min_available_clients: int = 1,
eval_fn: Optional[Callable[[Weights], Optional[Tuple[float, float]]]] = None,
min_completion_rate_fit: float = 0.5,
min_completion_rate_evaluate: float = 0.5,
on_fit_config_fn: Optional[Callable[[int], Dict[str, str]]] = None,
on_evaluate_config_fn: Optional[Callable[[int], Dict[str, str]]] = None,
r_fast: int = 1,
r_slow: int = 1,
t_fast: int = 10,
t_slow: int = 10,
) -> None:
super().__init__(
fraction_fit=fraction_fit,
fraction_eval=fraction_eval,
min_fit_clients=min_fit_clients,
min_eval_clients=min_eval_clients,
min_available_clients=min_available_clients,
eval_fn=eval_fn,
on_fit_config_fn=on_fit_config_fn,
on_evaluate_config_fn=on_evaluate_config_fn,
)
self.min_completion_rate_fit = min_completion_rate_fit
self.min_completion_rate_evaluate = min_completion_rate_evaluate
self.r_fast = r_fast
self.r_slow = r_slow
self.t_fast = t_fast
self.t_slow = t_slow
self.contributions: Dict[str, List[Tuple[int, float]]] = {}
# pylint: disable-msg=too-many-locals
def on_configure_fit(
self, rnd: int, weights: Weights, client_manager: ClientManager
) -> List[Tuple[ClientProxy, FitIns]]:
"""Configure the next round of training."""
# Block until `min_num_clients` are available
sample_size, min_num_clients = self.num_fit_clients(
client_manager.num_available()
)
success = client_manager.wait_for(num_clients=min_num_clients, timeout=60)
if not success:
# Do not continue if not enough clients are available
return []
# Prepare parameters and config
parameters = weights_to_parameters(weights)
config = {}
if self.on_fit_config_fn is not None:
# Use custom fit config function if provided
config = self.on_fit_config_fn(rnd)
use_fast_timeout = is_fast_round(rnd, self.r_fast, self.r_slow)
config["timeout"] = str(self.t_fast if use_fast_timeout else self.t_slow)
fit_ins = (parameters, config)
# Get all clients and gather their contributions
all_clients: Dict[str, ClientProxy] = client_manager.all()
cid_idx: Dict[int, str] = {}
logits: List[float] = []
for idx, (cid, _) in enumerate(all_clients.items()):
cid_idx[idx] = cid
penalty = 0.0
if cid in self.contributions.keys():
contribs: List[Tuple[int, float]] = self.contributions[cid]
penalty = statistics.mean([c for _, c in contribs])
# `p` should be:
# - High for clients which have never been picked before
# - Medium for clients which have contributed, but not used their entire budget
# - Low (but not 0) for clients which have been picked and used their budget
logits.append(1.1 - penalty)
# Sample clients
indices = np.arange(len(all_clients.keys()))
probs = softmax(np.array(logits))
idxs = np.random.choice(indices, size=sample_size, replace=False, p=probs)
clients = [all_clients[cid_idx[idx]] for idx in idxs]
# Return client/config pairs
return [(client, fit_ins) for client in clients]
def on_aggregate_fit(
self,
rnd: int,
results: List[Tuple[ClientProxy, FitRes]],
failures: List[BaseException],
) -> Optional[Weights]:
"""Aggregate fit results using weighted average."""
if not results:
return None
# Check if enough results are available
completion_rate = len(results) / (len(results) + len(failures))
if completion_rate < self.min_completion_rate_fit:
# Not enough results for aggregation
return None
# Convert results
weights_results = [
(parameters_to_weights(parameters), num_examples)
for client, (parameters, num_examples, _) in results
]
weights_prime = aggregate(weights_results)
# Track contributions to the global model
for client, fit_res in results:
cid = client.cid
contribution: Tuple[int, float] = (rnd, fit_res[1] / fit_res[2])
if cid not in self.contributions.keys():
self.contributions[cid] = []
self.contributions[cid].append(contribution)
return weights_prime
def on_aggregate_evaluate(
self,
rnd: int,
results: List[Tuple[ClientProxy, EvaluateRes]],
failures: List[BaseException],
) -> Optional[float]:
"""Aggregate evaluation losses using weighted average."""
if not results:
return None
# Check if enough results are available
completion_rate = len(results) / (len(results) + len(failures))
if completion_rate < self.min_completion_rate_evaluate:
# Not enough results for aggregation
return None
return weighted_loss_avg([evaluate_res for _, evaluate_res in results])
def is_fast_round(rnd: int, r_fast: int, r_slow: int) -> bool:
"""Determine if the round is fast or slow."""
remainder = rnd % (r_fast + r_slow)
return remainder - r_fast < 0
def softmax(logits: np.ndarray) -> np.ndarray:
"""Compute softmax."""
e_x = np.exp(logits - np.max(logits))
return cast(np.ndarray, e_x / e_x.sum(axis=0))
| [
"numpy.random.choice",
"numpy.array",
"statistics.mean",
"numpy.max"
] | [((4713, 4780), 'numpy.random.choice', 'np.random.choice', (['indices'], {'size': 'sample_size', 'replace': '(False)', 'p': 'probs'}), '(indices, size=sample_size, replace=False, p=probs)\n', (4729, 4780), True, 'import numpy as np\n'), ((4680, 4696), 'numpy.array', 'np.array', (['logits'], {}), '(logits)\n', (4688, 4696), True, 'import numpy as np\n'), ((7030, 7044), 'numpy.max', 'np.max', (['logits'], {}), '(logits)\n', (7036, 7044), True, 'import numpy as np\n'), ((4209, 4250), 'statistics.mean', 'statistics.mean', (['[c for _, c in contribs]'], {}), '([c for _, c in contribs])\n', (4224, 4250), False, 'import statistics\n')] |
import tensorflow as tf
A = tf.constant([4], tf.int32, name='A')
B = tf.constant([4], tf.int32, name='B')
C = tf.constant([4], tf.int32, name='C')
x = tf.placeholder(tf.int32, name='x')
with tf.name_scope("Equation_1"):
AX2_1 = tf.multiply(A, tf.pow(x,2), name='AX2_1')
Bx = tf.multiply(B, tf.pow(x,2), name='Bx')
# Cx = tf.add_n(C, tf.pow(x,2), name='Cx')
y1 = tf.add_n([AX2_1, Bx, C], name="y1")
with tf.name_scope("Equation_1"):
AX2_2 = tf.multiply(A, tf.pow(x,2), name='AX2_2')
Bx2 = tf.multiply(B, tf.pow(x,2), name='Bx2')
# Cx = tf.add_n(C, tf.pow(x,2), name='Cx')
y2 = tf.add_n([AX2_1, Bx, C], name="y2")
with tf.name_scope("Result"):
y = y1 + y2
with tf.Session() as sess:
print(sess.run(y,feed_dict={x:[10]}))
writer =tf.summary.FileWriter('./m3_example7', sess.graph)
writer.close()
| [
"tensorflow.pow",
"tensorflow.Session",
"tensorflow.placeholder",
"tensorflow.add_n",
"tensorflow.name_scope",
"tensorflow.constant",
"tensorflow.summary.FileWriter"
] | [((29, 65), 'tensorflow.constant', 'tf.constant', (['[4]', 'tf.int32'], {'name': '"""A"""'}), "([4], tf.int32, name='A')\n", (40, 65), True, 'import tensorflow as tf\n'), ((70, 106), 'tensorflow.constant', 'tf.constant', (['[4]', 'tf.int32'], {'name': '"""B"""'}), "([4], tf.int32, name='B')\n", (81, 106), True, 'import tensorflow as tf\n'), ((111, 147), 'tensorflow.constant', 'tf.constant', (['[4]', 'tf.int32'], {'name': '"""C"""'}), "([4], tf.int32, name='C')\n", (122, 147), True, 'import tensorflow as tf\n'), ((153, 187), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'name': '"""x"""'}), "(tf.int32, name='x')\n", (167, 187), True, 'import tensorflow as tf\n'), ((194, 221), 'tensorflow.name_scope', 'tf.name_scope', (['"""Equation_1"""'], {}), "('Equation_1')\n", (207, 221), True, 'import tensorflow as tf\n'), ((382, 417), 'tensorflow.add_n', 'tf.add_n', (['[AX2_1, Bx, C]'], {'name': '"""y1"""'}), "([AX2_1, Bx, C], name='y1')\n", (390, 417), True, 'import tensorflow as tf\n'), ((424, 451), 'tensorflow.name_scope', 'tf.name_scope', (['"""Equation_1"""'], {}), "('Equation_1')\n", (437, 451), True, 'import tensorflow as tf\n'), ((614, 649), 'tensorflow.add_n', 'tf.add_n', (['[AX2_1, Bx, C]'], {'name': '"""y2"""'}), "([AX2_1, Bx, C], name='y2')\n", (622, 649), True, 'import tensorflow as tf\n'), ((656, 679), 'tensorflow.name_scope', 'tf.name_scope', (['"""Result"""'], {}), "('Result')\n", (669, 679), True, 'import tensorflow as tf\n'), ((703, 715), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (713, 715), True, 'import tensorflow as tf\n'), ((779, 829), 'tensorflow.summary.FileWriter', 'tf.summary.FileWriter', (['"""./m3_example7"""', 'sess.graph'], {}), "('./m3_example7', sess.graph)\n", (800, 829), True, 'import tensorflow as tf\n'), ((250, 262), 'tensorflow.pow', 'tf.pow', (['x', '(2)'], {}), '(x, 2)\n', (256, 262), True, 'import tensorflow as tf\n'), ((301, 313), 'tensorflow.pow', 'tf.pow', (['x', '(2)'], {}), '(x, 2)\n', (307, 313), True, 'import tensorflow as tf\n'), ((480, 492), 'tensorflow.pow', 'tf.pow', (['x', '(2)'], {}), '(x, 2)\n', (486, 492), True, 'import tensorflow as tf\n'), ((532, 544), 'tensorflow.pow', 'tf.pow', (['x', '(2)'], {}), '(x, 2)\n', (538, 544), True, 'import tensorflow as tf\n')] |
import os
class Config():
SECRET_KEY = os.environ.get('FLASK_SECRET_KEY', 'f&k*n@kfa_H*tf^$)')
SSL_DISABLE = False
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
SQLALCHEMY_RECORD_QUERIES = True
SQLALCHEMY_TRACK_MODIFICATIONS = False
FLASKY_SLOW_DB_QUERY_TIME = 0.5
FLASKY_PER_PAGE = 10
CKEDITOR_SERVE_LOCAL = True
CKEDITOR_HEIGHT = 400
CKEDITOR_ENABLE_CODESNIPPET = True
CKEDITOR_FILE_UPLOADER = 'main.upload'
@staticmethod
def init__app(app):
pass
class DevelopmentConfig(Config):
DEBUG = True
SQLALCHEMY_DATABASE_URI = ('mysql+pymysql://root:123456@localhost:3306'
'/flask_dev?charset=utf8mb4')
class ProductionConfig(Config):
DEBUG = False
SQLALCHEMY_DATABASE_URI = ('mysql+pymysql://root:123456@localhost:3306'
'/flask_pro?charset=utf8mb4')
config = {
'default': ProductionConfig,
'development': DevelopmentConfig,
'production': ProductionConfig
}
| [
"os.environ.get"
] | [((45, 100), 'os.environ.get', 'os.environ.get', (['"""FLASK_SECRET_KEY"""', '"""f&k*n@kfa_H*tf^$)"""'], {}), "('FLASK_SECRET_KEY', 'f&k*n@kfa_H*tf^$)')\n", (59, 100), False, 'import os\n')] |
import random
class Thing:
"""
This represents any physical object that can appear in an Environment.
"""
def is_alive(self):
"""Things that are 'alive' should return true."""
return hasattr(self, 'alive') and self.alive
def show_state(self):
"""Display the agent's internal state. Subclasses should override."""
print("I don't know how to show_state.")
class Agent(Thing):
"""
An Agent is a subclass of Thing
"""
def __init__(self, program=None):
self.alive = True
self.performance = 0
self.program = program
def can_grab(self, thing):
"""Return True if this agent can grab this thing.
Override for appropriate subclasses of Agent and Thing."""
return False
def TableDrivenAgentProgram(table):
"""
[Figure 2.7]
This agent selects an action based on the percept sequence.
It is practical only for tiny domains.
To customize it, provide as table a dictionary of all
{percept_sequence:action} pairs.
"""
percepts = []
def program(percept):
action =None
"""
Write your code here
"""
return action
return program
loc_A, loc_B = (0, 0), (1, 0) # The two locations for the Vacuum world
def TableDrivenVacuumAgent():
"""
Tabular approach towards vacuum world
"""
table = {((loc_A, 'Clean'),): 'Right',
((loc_A, 'Dirty'),): 'Suck',
((loc_B, 'Clean'),): 'Left',
((loc_B, 'Dirty'),): 'Suck',
((loc_A, 'Dirty'), (loc_A, 'Clean')): 'Right',
((loc_A, 'Clean'), (loc_B, 'Dirty')): 'Suck',
((loc_B, 'Clean'), (loc_A, 'Dirty')): 'Suck',
((loc_B, 'Dirty'), (loc_B, 'Clean')): 'Left',
((loc_A, 'Dirty'), (loc_A, 'Clean'), (loc_B, 'Dirty')): 'Suck',
((loc_B, 'Dirty'), (loc_B, 'Clean'), (loc_A, 'Dirty')): 'Suck'}
return Agent(TableDrivenAgentProgram(table))
class Environment:
"""Abstract class representing an Environment. 'Real' Environment classes
inherit from this. Your Environment will typically need to implement:
percept: Define the percept that an agent sees.
execute_action: Define the effects of executing an action.
Also update the agent.performance slot.
The environment keeps a list of .things and .agents (which is a subset
of .things). Each agent has a .performance slot, initialized to 0.
Each thing has a .location slot, even though some environments may not
need this."""
def __init__(self):
self.things = []
self.agents = []
def percept(self, agent):
"""Return the percept that the agent sees at this point. (Implement this.)"""
raise NotImplementedError
def execute_action(self, agent, action):
"""Change the world to reflect this action. (Implement this.)"""
raise NotImplementedError
def default_location(self, thing):
"""Default location to place a new thing with unspecified location."""
return None
def is_done(self):
"""By default, we're done when we can't find a live agent."""
return not any(agent.is_alive() for agent in self.agents)
def step(self):
"""Run the environment for one time step. If the
actions and exogenous changes are independent, this method will
do. If there are interactions between them, you'll need to
override this method."""
if not self.is_done():
actions = []
for agent in self.agents:
if agent.alive:
actions.append(agent.program(self.percept(agent)))
else:
actions.append("")
for (agent, action) in zip(self.agents, actions):
self.execute_action(agent, action)
def run(self, steps=1000):
"""Run the Environment for given number of time steps."""
for step in range(steps):
if self.is_done():
return
self.step()
def add_thing(self, thing, location=None):
"""Add a thing to the environment, setting its location. For
convenience, if thing is an agent program we make a new agent
for it. (Shouldn't need to override this.)"""
if not isinstance(thing, Thing):
thing = Agent(thing)
if thing in self.things:
print("Can't add the same thing twice")
else:
thing.location = location if location is not None else self.default_location(thing)
self.things.append(thing)
if isinstance(thing, Agent):
thing.performance = 0
self.agents.append(thing)
def delete_thing(self, thing):
"""Remove a thing from the environment."""
try:
self.things.remove(thing)
except ValueError as e:
print(e)
print(" in Environment delete_thing")
print(" Thing to be removed: {} at {}".format(thing, thing.location))
print(" from list: {}".format([(thing, thing.location) for thing in self.things]))
if thing in self.agents:
self.agents.remove(thing)
class TrivialVacuumEnvironment(Environment):
"""This environment has two locations, A and B. Each can be Dirty
or Clean. The agent perceives its location and the location's
status. This serves as an example of how to implement a simple
Environment."""
def __init__(self):
super().__init__()
self.status = {loc_A: random.choice(['Clean', 'Dirty']),
loc_B: random.choice(['Clean', 'Dirty'])}
def thing_classes(self):
return [ TableDrivenVacuumAgent]
def percept(self, agent):
"""Returns the agent's location, and the location status (Dirty/Clean)."""
return agent.location, self.status[agent.location]
def execute_action(self, agent, action):
"""Change agent's location and/or location's status; track performance.
Score 10 for each dirt cleaned; -1 for each move."""
"""
Write your code here
"""
def default_location(self, thing):
"""Agents start in either location at random."""
return random.choice([loc_A, loc_B])
if __name__ == "__main__":
agent = TableDrivenVacuumAgent()
environment = TrivialVacuumEnvironment()
environment.add_thing(agent)
print(environment.status)
environment.run()
print(agent.performance)
| [
"random.choice"
] | [((6333, 6362), 'random.choice', 'random.choice', (['[loc_A, loc_B]'], {}), '([loc_A, loc_B])\n', (6346, 6362), False, 'import random\n'), ((5636, 5669), 'random.choice', 'random.choice', (["['Clean', 'Dirty']"], {}), "(['Clean', 'Dirty'])\n", (5649, 5669), False, 'import random\n'), ((5701, 5734), 'random.choice', 'random.choice', (["['Clean', 'Dirty']"], {}), "(['Clean', 'Dirty'])\n", (5714, 5734), False, 'import random\n')] |
# -*- coding: utf-8 -*-
"""
tests.tests_models.test_water_container
~~~~~~~~~~~~~~~~~~~
This script contains tests for the WaterContainer model.
"""
from pytest import fixture, mark, raises
from src.exceptions import CoffeeMachineException
from src.exceptions import NotEnoughWater
from src.models.container import WaterContainer
from src.utils import Mililiters
@fixture
def create_water_container(request) -> WaterContainer:
"""Create WaterContainer object for testing."""
try:
_container_capacity = request.param
except AttributeError:
_container_capacity = TestWaterContainer.capacity_default
_container = WaterContainer(capacity=_container_capacity)
return _container
class TestWaterContainer:
capacity_default: Mililiters = 1000
@mark.parametrize(
('create_water_container', 'water_volume', 'expectation'),
[(100, 200, raises(NotEnoughWater)),
(0, 1, raises(NotEnoughWater))],
indirect=['create_water_container']
)
def test_fill_level_raise_not_enough_water(self,
create_water_container: WaterContainer,
water_volume: Mililiters,
expectation: CoffeeMachineException) -> None:
"""Test an edge case, when there is not enough water to get from the WaterContainer"""
with expectation:
create_water_container.get_water(volume=water_volume)
| [
"src.models.container.WaterContainer",
"pytest.raises"
] | [((646, 690), 'src.models.container.WaterContainer', 'WaterContainer', ([], {'capacity': '_container_capacity'}), '(capacity=_container_capacity)\n', (660, 690), False, 'from src.models.container import WaterContainer\n'), ((893, 915), 'pytest.raises', 'raises', (['NotEnoughWater'], {}), '(NotEnoughWater)\n', (899, 915), False, 'from pytest import fixture, mark, raises\n'), ((934, 956), 'pytest.raises', 'raises', (['NotEnoughWater'], {}), '(NotEnoughWater)\n', (940, 956), False, 'from pytest import fixture, mark, raises\n')] |
from quicksectx import IntervalTree, Interval
import unittest
tree = IntervalTree()
tree.add(0, 3, 100)
tree.add(5, 8, 110)
tree.add(6, 10, 120)
tree.add(8, 9, 130)
tree.add(15, 23, 140)
tree.add(19, 20, 150)
tree.add(17, 19, 160)
tree.add(26, 26, 160)
tree.add(25, 30, 160)
tree.add(16, 21, 160)
print(tree.search(3,15))
print(tree.pretty_print())
print('\n\n---\n\n\n')
tree = IntervalTree()
tree.add(0, 3, 100)
tree.add(5, 8, 110)
tree.add(6, 10, 120)
tree.add(8, 9, 130)
tree.add(15, 23, 140)
tree.add(16, 21, 160)
tree.add(17, 19, 160)
tree.add(19, 20, 150)
tree.add(25, 30, 160)
tree.add(26, 26, 160)
tree.add(27, 28, 160)
tree.add(27, 28, 160)
tree.add(27, 28, 160)
print(tree.pretty_print())
class MyTestCase(unittest.TestCase):
def test_1(self):
tree = IntervalTree()
tree.add(1, 3, 100)
tree.add(3, 7, 110)
tree.add(2, 5, 120)
tree.add(4, 6, 130)
print(tree.pretty_print())
print(tree.find(Interval(2, 5)))
tree.remove(Interval(2, 5))
print(tree.find(Interval(2, 5)))
print(tree.pretty_print())
self.assertEqual(True, True)
if __name__ == '__main__':
unittest.main()
print(Interval(1, 2).__reduce__())
| [
"unittest.main",
"quicksectx.IntervalTree",
"quicksectx.Interval"
] | [((70, 84), 'quicksectx.IntervalTree', 'IntervalTree', ([], {}), '()\n', (82, 84), False, 'from quicksectx import IntervalTree, Interval\n'), ((380, 394), 'quicksectx.IntervalTree', 'IntervalTree', ([], {}), '()\n', (392, 394), False, 'from quicksectx import IntervalTree, Interval\n'), ((1161, 1176), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1174, 1176), False, 'import unittest\n'), ((776, 790), 'quicksectx.IntervalTree', 'IntervalTree', ([], {}), '()\n', (788, 790), False, 'from quicksectx import IntervalTree, Interval\n'), ((999, 1013), 'quicksectx.Interval', 'Interval', (['(2)', '(5)'], {}), '(2, 5)\n', (1007, 1013), False, 'from quicksectx import IntervalTree, Interval\n'), ((1183, 1197), 'quicksectx.Interval', 'Interval', (['(1)', '(2)'], {}), '(1, 2)\n', (1191, 1197), False, 'from quicksectx import IntervalTree, Interval\n'), ((962, 976), 'quicksectx.Interval', 'Interval', (['(2)', '(5)'], {}), '(2, 5)\n', (970, 976), False, 'from quicksectx import IntervalTree, Interval\n'), ((1039, 1053), 'quicksectx.Interval', 'Interval', (['(2)', '(5)'], {}), '(2, 5)\n', (1047, 1053), False, 'from quicksectx import IntervalTree, Interval\n')] |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# author arrti
from ss_admin import app
if __name__ == '__main__':
app.run()
| [
"ss_admin.app.run"
] | [((116, 125), 'ss_admin.app.run', 'app.run', ([], {}), '()\n', (123, 125), False, 'from ss_admin import app\n')] |
# Maximum Gap Problem
# http://www.zrzahid.com/the-%E2%80%A9maximum%E2%80%A9-gap%E2%80%A9-problem-%E2%80%A9pigeonhole-%E2%80%A9principle%E2%80%A9/
# http://cgm.cs.mcgill.ca/~godfried/teaching/dm-reading-assignments/Maximum-Gap-Problem.pdf
# https://stackoverflow.com/questions/10262937/array-maximum-difference-algorithm-that-runs-in-on
import sys
from math import floor
def maxGapin(arr):
n = len(arr)
if(n<2):
return 0
minn,maxx = min(arr),max(arr)
bucketMaxima = [sys.maxsize for i in range(n-1)]
bucketMinima = [-sys.maxsize for i in range(n-1)]
delta = (maxx-minn)/(n-1)
#populate the buckets
for i in arr:
if(i==maxx or i==minn):
continue
bIndex = floor((i-minn)/delta)
if(bucketMaxima[bIndex] == -1*sys.maxsize):
bucketMaxima[bIndex] = i
else:
bucketMaxima[bIndex] = max(bucketMaxima[bIndex], i)
#similarly for bucketMinima
if(bucketMinima[bIndex] == sys.maxsize):
bucketMinima[bIndex] = i
else:
bucketMinima[bIndex] = min(bucketMinima[bIndex], i)
#find the max gap
print(bucketMaxima,"\n",bucketMinima)
print(maxx,minn)
prev = minn
maxGap = 0
#following pigeonhole principle to empty bucket
for i in range(n-1):
if(bucketMinima[i]==sys.maxsize):
continue
maxGap = max(maxGap, bucketMinima[i]-prev)
prev = bucketMaxima[i]
return max(maxGap, maxx-prev)
#print(maxGapin([5, 3, 1, 8, 9, 2, 4]))
print(maxGapin([6,44,99,-50,8,1])) | [
"math.floor"
] | [((689, 714), 'math.floor', 'floor', (['((i - minn) / delta)'], {}), '((i - minn) / delta)\n', (694, 714), False, 'from math import floor\n')] |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
from .__misc__ import __version__, __data_version__
from maro.utils.utils import deploy, check_deployment_status
if not check_deployment_status():
deploy()
| [
"maro.utils.utils.deploy",
"maro.utils.utils.check_deployment_status"
] | [((196, 221), 'maro.utils.utils.check_deployment_status', 'check_deployment_status', ([], {}), '()\n', (219, 221), False, 'from maro.utils.utils import deploy, check_deployment_status\n'), ((227, 235), 'maro.utils.utils.deploy', 'deploy', ([], {}), '()\n', (233, 235), False, 'from maro.utils.utils import deploy, check_deployment_status\n')] |
# -*- coding: UTF-8 -*-
"""
@author: <NAME>
@file : settings.py
@time : 2021/09/10 09:20
@desc :
"""
import configparser
import os
import PySimpleGUI as sg
LANGUAGE_DEF = '中文/英文'
LANGUAGE_NAME_KEY_MAP = {
'中文/英文': 'ch',
'繁体中文': 'ch_tra',
'日语': 'japan',
'韩语': 'korean',
'法语': 'french',
'德语': 'german',
}
LANGUAGE_KEY_NAME_MAP = {v: k for k, v in LANGUAGE_NAME_KEY_MAP.items()}
MODE_DEF = '快速'
MODE_NAME_KEY_MAP = {
'快速': 'fast',
'精准': 'accurate',
}
MODE_KEY_NAME_MAP = {v: k for k, v in MODE_NAME_KEY_MAP.items()}
def set_language_mode(config_file):
language_def, mode_def = parse_config(config_file)
sg.theme('LightBrown12')
window = sg.Window(title='字幕提取器',
layout=[
[sg.Text('选择视频字幕的语言:'), sg.DropDown(values=list(LANGUAGE_NAME_KEY_MAP.keys()), size=(30, 20), pad=(0, 20),
key='-LANGUAGE-', readonly=True, default_value=language_def)],
[sg.Text('选择识别模式:'), sg.DropDown(values=list(MODE_NAME_KEY_MAP.keys()), size=(30, 20), pad=(0, 20),
key='-MODE-', readonly=True, default_value=mode_def)],
[sg.OK(), sg.Cancel()]
])
event, values = window.read()
if event == 'OK':
# 设置模型语言配置
language = None
mode = None
language_str = values['-LANGUAGE-']
print('选择语言:', language_str)
if language_str in LANGUAGE_NAME_KEY_MAP:
language = LANGUAGE_NAME_KEY_MAP[language_str]
# 设置模型语言配置
mode_str = values['-MODE-']
print('选择模式:', mode_str)
if mode_str in MODE_NAME_KEY_MAP:
mode = MODE_NAME_KEY_MAP[mode_str]
set_config(config_file, language, mode)
window.close()
return event
def set_config(config_file, language_code, mode):
# 写入配置文件
with open(config_file, mode='w') as f:
f.write('[DEFAULT]\n')
f.write(f'Language = {language_code}\n')
f.write(f'Mode = {mode}\n')
def parse_config(config_file):
if not os.path.exists(config_file):
return LANGUAGE_DEF, MODE_DEF
config = configparser.ConfigParser()
config.read(config_file)
language = config['DEFAULT']['Language']
mode = config['DEFAULT']['Mode']
language_def = LANGUAGE_KEY_NAME_MAP[language] if language in LANGUAGE_KEY_NAME_MAP else LANGUAGE_DEF
mode_def = MODE_KEY_NAME_MAP[mode] if mode in MODE_KEY_NAME_MAP else MODE_DEF
return language_def, mode_def
| [
"os.path.exists",
"configparser.ConfigParser",
"PySimpleGUI.Cancel",
"PySimpleGUI.Text",
"PySimpleGUI.theme",
"PySimpleGUI.OK"
] | [((706, 730), 'PySimpleGUI.theme', 'sg.theme', (['"""LightBrown12"""'], {}), "('LightBrown12')\n", (714, 730), True, 'import PySimpleGUI as sg\n'), ((2297, 2324), 'configparser.ConfigParser', 'configparser.ConfigParser', ([], {}), '()\n', (2322, 2324), False, 'import configparser\n'), ((2217, 2244), 'os.path.exists', 'os.path.exists', (['config_file'], {}), '(config_file)\n', (2231, 2244), False, 'import os\n'), ((829, 850), 'PySimpleGUI.Text', 'sg.Text', (['"""选择视频字幕的语言:"""'], {}), "('选择视频字幕的语言:')\n", (836, 850), True, 'import PySimpleGUI as sg\n'), ((1089, 1107), 'PySimpleGUI.Text', 'sg.Text', (['"""选择识别模式:"""'], {}), "('选择识别模式:')\n", (1096, 1107), True, 'import PySimpleGUI as sg\n'), ((1331, 1338), 'PySimpleGUI.OK', 'sg.OK', ([], {}), '()\n', (1336, 1338), True, 'import PySimpleGUI as sg\n'), ((1340, 1351), 'PySimpleGUI.Cancel', 'sg.Cancel', ([], {}), '()\n', (1349, 1351), True, 'import PySimpleGUI as sg\n')] |
# Generated by Django 3.1.1 on 2020-09-13 05:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('log_reg_app', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='user',
name='password',
field=models.CharField(default=None, max_length=255),
),
]
| [
"django.db.models.CharField"
] | [((327, 373), 'django.db.models.CharField', 'models.CharField', ([], {'default': 'None', 'max_length': '(255)'}), '(default=None, max_length=255)\n', (343, 373), False, 'from django.db import migrations, models\n')] |
import math
class Prime:
is_debug = True
prime_list = []
max_ind = 0
max_keep = 0
prev_no = 0
seq_list = []
inter_list = []
def __init__(self, limit):
self.max_keep = round(math.sqrt(limit) / math.log(math.sqrt(limit), math.e) * 1.5)
def get(self, index):
return self.prime_list[index] if (index < self.max_ind - 1) else self.prime_list[self.max_ind - 1]
def getlast(self):
return self.prime_list[len(self.prime_list) - 1]
def size(self):
return self.max_ind
def add(self, p):
self.prime_list.append(p)
self.max_ind = self.max_ind + 1
def generate_results(self, inter, end_no):
self.output_sequence(self.prev_no, end_no)
self.output_interval(inter)
self.prev_no = end_no
self.free_up()
def output_interval(self, inter):
if inter % pow(10, len(str(inter)) - 1) == 0:
s = self.df_string(inter) + "|" + str(self.max_ind) + "|" + str(self.prime_list[len(self.prime_list) - 1])
self.inter_list.append(s)
if self.is_debug: print("[In:]" + s)
def output_sequence(self, begin_no, end_no):
for i in range(len(str(begin_no)) - 1, len(str(end_no))):
for j in range(1, 10):
seq = j * pow(10, i)
if seq < begin_no: continue
if seq >= end_no: return
l = self.prime_list[len(self.prime_list) - 1 - (end_no - seq)]
s = self.df_string(seq) + "|" + str(l)
self.seq_list.append(s)
if self.is_debug: print("==>[No:]" + s)
def free_up(self):
if self.max_ind > self.max_keep:
del self.prime_list[self.max_keep:len(self.prime_list)]
def df_string(self, l):
s = str(l)
if l % 1_0000_0000_0000 == 0:
s = s[:-12] + "万亿"
elif l % 1_0000_0000 == 0:
s = s[:-8] + "亿"
elif l % 1_0000 == 0:
s = s[:-4] + "万"
return s
def print_table(self):
print("## 素数区间表")
print("区间|个数|最大值")
print("---|---|---")
for s in self.inter_list: print(s)
print("## 素数序列表")
print("序号|数值")
print("---|---")
for s in self.seq_list: print(s)
| [
"math.sqrt"
] | [((216, 232), 'math.sqrt', 'math.sqrt', (['limit'], {}), '(limit)\n', (225, 232), False, 'import math\n'), ((244, 260), 'math.sqrt', 'math.sqrt', (['limit'], {}), '(limit)\n', (253, 260), False, 'import math\n')] |
import pandas as pd
import numpy as np
import re
from FeatureExtraction import *
from CrossValidation import *
import warnings
from Preprocessing import *
from collections import Counter
import seaborn as sns
import matplotlib.pyplot as plt
warnings.filterwarnings(action = 'ignore')
#read train file
train=pd.read_csv('Data/train.csv')
#read test file
test=pd.read_csv('Data/test.csv')
#combine train and test file to clean data
df = pd.concat([train, test], ignore_index=True)
#count most frequent word in frame
most_word=Counter(" ".join(df["text"]).split()).most_common(20)
#plot word
x=[]
y=[]
for name,count in most_word[:20]:
x.append(name)
y.append(count)
sns.barplot(x=x,y=y)
plt.savefig('frequent_words.png')
plt.show()
#clean text
df=clean(df)
clean_messages = []
for message in df['text']:
clean_messages.append(text_to_wordlist(
message, remove_stopwords=True, return_list=False))
clean_message = []
for message in clean_messages:
clean_message.append(abb(message))
lemmanization = []
for message in clean_message:
lemmanization.append(lemma(message))
stemming=[]
for message in lemmanization:
stemming.append(stem(message))
#convert text to vector using bag of words method
data_features,data_features_name=BagOfWords(stemming)
#data features convert data frame
data=pd.DataFrame(data_features,columns=data_features_name)
#remove text column from data frame
df.pop('text')
#index start from 0
df = df.reset_index(drop=True)
df=pd.concat([data,df],axis=1)
train = df.loc[df['Class'].notna()]
test = df.loc[df['Class'].isna()]
test.pop('Class')
predictors=train.drop(['Class','id1'],axis=1)
target=train['Class']
| [
"matplotlib.pyplot.savefig",
"pandas.read_csv",
"pandas.DataFrame",
"seaborn.barplot",
"pandas.concat",
"warnings.filterwarnings",
"matplotlib.pyplot.show"
] | [((241, 281), 'warnings.filterwarnings', 'warnings.filterwarnings', ([], {'action': '"""ignore"""'}), "(action='ignore')\n", (264, 281), False, 'import warnings\n'), ((308, 337), 'pandas.read_csv', 'pd.read_csv', (['"""Data/train.csv"""'], {}), "('Data/train.csv')\n", (319, 337), True, 'import pandas as pd\n'), ((360, 388), 'pandas.read_csv', 'pd.read_csv', (['"""Data/test.csv"""'], {}), "('Data/test.csv')\n", (371, 388), True, 'import pandas as pd\n'), ((439, 482), 'pandas.concat', 'pd.concat', (['[train, test]'], {'ignore_index': '(True)'}), '([train, test], ignore_index=True)\n', (448, 482), True, 'import pandas as pd\n'), ((675, 696), 'seaborn.barplot', 'sns.barplot', ([], {'x': 'x', 'y': 'y'}), '(x=x, y=y)\n', (686, 696), True, 'import seaborn as sns\n'), ((696, 729), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""frequent_words.png"""'], {}), "('frequent_words.png')\n", (707, 729), True, 'import matplotlib.pyplot as plt\n'), ((730, 740), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (738, 740), True, 'import matplotlib.pyplot as plt\n'), ((1335, 1390), 'pandas.DataFrame', 'pd.DataFrame', (['data_features'], {'columns': 'data_features_name'}), '(data_features, columns=data_features_name)\n', (1347, 1390), True, 'import pandas as pd\n'), ((1498, 1527), 'pandas.concat', 'pd.concat', (['[data, df]'], {'axis': '(1)'}), '([data, df], axis=1)\n', (1507, 1527), True, 'import pandas as pd\n')] |
#to run this script once per day (auto-update the washingtonpost data from GitHub) add this to crontab:
# 0 12 * * * python /Users/quran/Dropbox/MusicArtProjects/endsSentenceFunction/data/download.py
import os
import urllib
fullfilename = os.path.join('/Users/quran/Dropbox/MusicArtProjects/endsSentenceFunction/data', 'fatal-police-shootings-data.csv')
csvData = urllib.URLopener()
csvData.retrieve("https://raw.githubusercontent.com/washingtonpost/data-police-shootings/master/fatal-police-shootings-data.csv", fullfilename)
| [
"urllib.URLopener",
"os.path.join"
] | [((240, 358), 'os.path.join', 'os.path.join', (['"""/Users/quran/Dropbox/MusicArtProjects/endsSentenceFunction/data"""', '"""fatal-police-shootings-data.csv"""'], {}), "('/Users/quran/Dropbox/MusicArtProjects/endsSentenceFunction/data',\n 'fatal-police-shootings-data.csv')\n", (252, 358), False, 'import os\n'), ((365, 383), 'urllib.URLopener', 'urllib.URLopener', ([], {}), '()\n', (381, 383), False, 'import urllib\n')] |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Event',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('approved', models.BooleanField(default=False)),
('title', models.CharField(max_length=100)),
('isonline', models.BooleanField(default=False, verbose_name='Online event')),
('city', models.CharField(max_length=50, blank=True)),
('state', models.CharField(max_length=50, blank=True)),
('training', models.BooleanField(default=False)),
('startdate', models.DateField(verbose_name='Start date')),
('enddate', models.DateField(verbose_name='End date')),
('summary', models.TextField(help_text='A short introduction (shown on the events listing page)')),
('details', models.TextField(help_text='Complete event description')),
('country', models.ForeignKey(blank=True, to='core.Country', null=True, on_delete=models.CASCADE)),
('language', models.ForeignKey(default='eng', blank=True, to='core.Language', help_text='Primary language for event. When multiple languages, specify this in the event description', null=True, on_delete=models.CASCADE)),
('org', models.ForeignKey(verbose_name='Organisation', to='core.Organisation', help_text='If no organisations are listed, please check the <a href="/account/orglist/">organisation list</a> and contact the organisation manager or <a href="mailto:<EMAIL>"><EMAIL></a> if none are listed.', on_delete=models.CASCADE)),
],
options={
'ordering': ('-startdate', '-enddate'),
},
),
]
| [
"django.db.models.DateField",
"django.db.models.TextField",
"django.db.models.ForeignKey",
"django.db.models.BooleanField",
"django.db.models.AutoField",
"django.db.models.CharField"
] | [((331, 424), 'django.db.models.AutoField', 'models.AutoField', ([], {'verbose_name': '"""ID"""', 'serialize': '(False)', 'auto_created': '(True)', 'primary_key': '(True)'}), "(verbose_name='ID', serialize=False, auto_created=True,\n primary_key=True)\n", (347, 424), False, 'from django.db import migrations, models\n'), ((452, 486), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (471, 486), False, 'from django.db import migrations, models\n'), ((515, 547), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)'}), '(max_length=100)\n', (531, 547), False, 'from django.db import migrations, models\n'), ((579, 642), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)', 'verbose_name': '"""Online event"""'}), "(default=False, verbose_name='Online event')\n", (598, 642), False, 'from django.db import migrations, models\n'), ((670, 713), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(50)', 'blank': '(True)'}), '(max_length=50, blank=True)\n', (686, 713), False, 'from django.db import migrations, models\n'), ((742, 785), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(50)', 'blank': '(True)'}), '(max_length=50, blank=True)\n', (758, 785), False, 'from django.db import migrations, models\n'), ((817, 851), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (836, 851), False, 'from django.db import migrations, models\n'), ((884, 927), 'django.db.models.DateField', 'models.DateField', ([], {'verbose_name': '"""Start date"""'}), "(verbose_name='Start date')\n", (900, 927), False, 'from django.db import migrations, models\n'), ((958, 999), 'django.db.models.DateField', 'models.DateField', ([], {'verbose_name': '"""End date"""'}), "(verbose_name='End date')\n", (974, 999), False, 'from django.db import migrations, models\n'), ((1030, 1120), 'django.db.models.TextField', 'models.TextField', ([], {'help_text': '"""A short introduction (shown on the events listing page)"""'}), "(help_text=\n 'A short introduction (shown on the events listing page)')\n", (1046, 1120), False, 'from django.db import migrations, models\n'), ((1146, 1202), 'django.db.models.TextField', 'models.TextField', ([], {'help_text': '"""Complete event description"""'}), "(help_text='Complete event description')\n", (1162, 1202), False, 'from django.db import migrations, models\n'), ((1233, 1323), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'blank': '(True)', 'to': '"""core.Country"""', 'null': '(True)', 'on_delete': 'models.CASCADE'}), "(blank=True, to='core.Country', null=True, on_delete=\n models.CASCADE)\n", (1250, 1323), False, 'from django.db import migrations, models\n'), ((1350, 1565), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'default': '"""eng"""', 'blank': '(True)', 'to': '"""core.Language"""', 'help_text': '"""Primary language for event. When multiple languages, specify this in the event description"""', 'null': '(True)', 'on_delete': 'models.CASCADE'}), "(default='eng', blank=True, to='core.Language', help_text=\n 'Primary language for event. When multiple languages, specify this in the event description'\n , null=True, on_delete=models.CASCADE)\n", (1367, 1565), False, 'from django.db import migrations, models\n'), ((1582, 1901), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'verbose_name': '"""Organisation"""', 'to': '"""core.Organisation"""', 'help_text': '"""If no organisations are listed, please check the <a href="/account/orglist/">organisation list</a> and contact the organisation manager or <a href="mailto:<EMAIL>"><EMAIL></a> if none are listed."""', 'on_delete': 'models.CASCADE'}), '(verbose_name=\'Organisation\', to=\'core.Organisation\',\n help_text=\n \'If no organisations are listed, please check the <a href="/account/orglist/">organisation list</a> and contact the organisation manager or <a href="mailto:<EMAIL>"><EMAIL></a> if none are listed.\'\n , on_delete=models.CASCADE)\n', (1599, 1901), False, 'from django.db import migrations, models\n')] |
################################################################################
#
# Select a
#
# Author(s): <NAME>
################################################################################
import pathlib
import random
from typing import Union, List
from enum import Enum
import torch as t
from torchaudio.backend.sox_io_backend import save
from .debug import BatchDebugInfo, DebugWriter
from .base import AudioDataSample, Preprocessor
from ...util.torch import debug_tensor_content
################################################################################
# implementation of the selector
class AudioChunkDebugWriter(DebugWriter):
def __init__(self, sample_rate: int):
self.sample_rate = sample_rate
def write(self, tensor: t.Tensor, save_dir: pathlib.Path, idx: int):
debug_tensor_content(
tensor, f"{idx:03d}_randomly_selected_audio_chunk", save_dir
)
save(
str(save_dir / f"{idx:03d}_randomly_selected_audio_chunk.wav"),
tensor,
self.sample_rate,
)
class SelectionStrategy(str, Enum):
start = "start"
end = "end"
random = "random"
random_contiguous = "random_contiguous"
contiguous = "contiguous"
class AudioChunkSelector(Preprocessor):
def __init__(
self,
selection_strategy: SelectionStrategy,
desired_chunk_length_sec: float,
sample_rate: int = 16000,
yield_all_contiguous: bool = False,
):
"""
Randomly select a subsample of a audio tensor where the last dimension
contains the audio observations
:param selection_strategy: how to select the subsample
:param desired_chunk_length_sec: the desired length of the subsample in seconds
:param sample_rate: the sample rate of the audio
"""
super().__init__()
if selection_strategy == SelectionStrategy.start:
self.fn = self._start_select
elif selection_strategy == SelectionStrategy.end:
self.fn = self._end_select
elif selection_strategy == SelectionStrategy.random:
self.fn = self._random_select
elif selection_strategy == SelectionStrategy.random_contiguous:
self.fn = self._random_contiguous_select
elif selection_strategy == SelectionStrategy.contiguous:
self.fn = self._contiguous_select
else:
raise ValueError(f"unknown selection strategy {selection_strategy}")
self.chunk_size = round(sample_rate * desired_chunk_length_sec)
self.sample_rate = sample_rate
self.yield_all_contiguous = yield_all_contiguous
def process(
self, sample: AudioDataSample
) -> Union[AudioDataSample, List[AudioDataSample]]:
chunked_wavs = [c for c in self.fn(sample.audio)]
if len(chunked_wavs) == 1:
sample.audio = chunked_wavs[0]
sample.audio_length_frames = chunked_wavs[0].shape[-1]
if sample.debug_info is not None:
sample.debug_info.pipeline_progress.append(
(sample.audio, self.init_debug_writer())
)
return sample
elif len(chunked_wavs) > 1:
samples = []
for idx, selected_wav in enumerate(chunked_wavs):
new_network_input = selected_wav
if sample.debug_info is not None:
new_side_info = BatchDebugInfo(
original_tensor=sample.debug_info.original_tensor,
pipeline_progress=list(sample.debug_info.pipeline_progress)
+ [(new_network_input, self.init_debug_writer())],
meta=sample.debug_info.meta,
)
else:
new_side_info = None
new_sample = AudioDataSample(
key=sample.key + f"/chunk{idx}",
audio=new_network_input,
sample_rate=sample.sample_rate,
ground_truth_container=sample.ground_truth_container,
debug_info=new_side_info,
audio_length_frames=new_network_input.shape[-1],
)
samples.append(new_sample)
return samples
else:
raise ValueError("unable to select at least one chunk")
def init_debug_writer(self):
return AudioChunkDebugWriter(self.sample_rate)
def _start_select(self, wav_tensor: t.Tensor):
yield wav_tensor[..., : self.chunk_size]
def _end_select(self, wav_tensor: t.Tensor):
yield wav_tensor[..., -self.chunk_size :]
def _random_select(self, wav_tensor: t.Tensor):
num_samples = wav_tensor.shape[-1]
if self.chunk_size > num_samples:
yield wav_tensor[..., :]
else:
start = random.randint(0, num_samples - self.chunk_size - 1)
end = start + self.chunk_size
yield wav_tensor[..., start:end]
def _random_contiguous_select(self, wav_tensor: t.Tensor):
num_samples = wav_tensor.shape[-1]
num_possible_chunks = num_samples // self.chunk_size
selected_chunk = random.randint(0, num_possible_chunks - 1)
start = selected_chunk * self.chunk_size
end = start + self.chunk_size
yield wav_tensor[..., start:end]
def _contiguous_select(self, wav_tensor: t.Tensor):
num_samples = wav_tensor.shape[-1]
num_possible_chunks = num_samples // self.chunk_size
for selected_chunk in range(num_possible_chunks):
start = selected_chunk * self.chunk_size
end = start + self.chunk_size
yield wav_tensor[..., start:end]
| [
"random.randint"
] | [((5239, 5281), 'random.randint', 'random.randint', (['(0)', '(num_possible_chunks - 1)'], {}), '(0, num_possible_chunks - 1)\n', (5253, 5281), False, 'import random\n'), ((4905, 4957), 'random.randint', 'random.randint', (['(0)', '(num_samples - self.chunk_size - 1)'], {}), '(0, num_samples - self.chunk_size - 1)\n', (4919, 4957), False, 'import random\n')] |
# Copyright (c) 2021 Graphcore Ltd. All rights reserved.
import copy
import inspect
import torch
# Do not import any poptorch.* here: it will break the poptorch module
from . import _impl
from ._logging import logger
class ArgsParser:
class Args:
def __init__(self):
self._args = []
self.first_none = None
def clone(self):
clone = ArgsParser.Args()
clone._args = copy.copy(self._args) # pylint: disable=protected-access
clone.first_none = self.first_none
return clone
def _forEach(self, data, fn):
if isinstance(data, (tuple, list)):
return type(data)(self._forEach(d, fn) for d in data)
if isinstance(data, dict):
return {
key: self._forEach(value, fn)
for key, value in data.items()
}
return fn(data)
def _forEachMatched(self, data, condition, doOnTrue, conditionMatches):
if isinstance(data, (tuple, list)):
return type(data)(self._forEachMatched(
d, condition, doOnTrue, conditionMatches) for d in data)
if isinstance(data, dict):
return {
key: self._forEachMatched(value, condition, doOnTrue,
conditionMatches)
for key, value in data.items()
}
if condition(data):
conditionMatches.setTrue()
return doOnTrue(data)
return data
def forEachMatchedAtLeastOnce(self, condition, doOnTrue=None):
class ConditionMatches:
def __init__(self):
self._matches = False
def __bool__(self):
return self._matches
def setTrue(self):
self._matches = True
matches = ConditionMatches()
self._args = self._forEachMatched(self._args, condition, doOnTrue,
matches)
return bool(matches)
def forEach(self, fn):
self._args = self._forEach(self._args, fn)
def asTuple(self):
return tuple(self._args)
def __init__(self, model):
# Combine args and kwargs:
if isinstance(model, _impl.OptimizerWrapper):
sig = inspect.signature(model.model.forward)
else:
sig = inspect.signature(model.forward)
self._has_variadic_arguments = any([
p.kind in [p.VAR_POSITIONAL, p.VAR_KEYWORD]
for p in sig.parameters.values()
])
self._varnames = list(sig.parameters.keys())
self._defaults = [p.default for p in sig.parameters.values()]
self._warned_not_contiguous_input = False
def __call__(self, args, kwargs, fast_path=False):
"""Checks the inputs are of a supported type. Inputs must be
tensors or tuples/lists of tensors. Will convert list to tuples
as we can't natively support lists in the JIT.
"""
in_tensors = ArgsParser.Args()
assert self._has_variadic_arguments or len(args) + len(kwargs) <= len(
self._varnames), ("Too many arguments provided: expected %s (%d) "
"but got %d") % (self._varnames,
len(self._varnames),
len(args) + len(kwargs))
first_optional = len(self._varnames) - len(self._defaults)
none_passed = []
# Make sure all the arguments provided are allowed.
for k in kwargs.keys():
assert k in self._varnames, (
f"{k} is not a valid parameter."
f"Allowed values are {self._varnames}")
for i, name in enumerate(self._varnames):
if i < len(args):
has_list = self._errorOnDictReturnTrueIfList(args[i], name, [])
# Non fast path for compilation, fast path for executing.
if not fast_path:
if has_list:
logger.warning(
"Lists as inputs only have partial support, they "
"can be accessed but full Python functionality is "
"not enabled. Consider changing input to tuple.")
data = self._convertLists(args[i])
in_tensors._args.append(data)
else:
in_tensors._args.append(args[i])
assert name not in kwargs, ("Parameter %s was passed more "
"than once") % name
elif name in kwargs:
assert not none_passed, (
"Torch doesn't support passing tensors (%s)"
" after the following parameters have defaulted to None."
" %s") % (name, ", ".join(none_passed))
has_list = self._errorOnDictReturnTrueIfList(
kwargs[name], name, [])
# Non fast path for compilation, fast path for executing.
if not fast_path:
if has_list:
logger.warning(
"Lists as inputs only have partial support, they "
"can be accessed but full Python functionality is "
"not enabled. Consider changing input to tuple.")
kwargs[name] = self._convertLists(kwargs[name])
in_tensors._args.append(kwargs[name])
else:
assert i >= first_optional, ("Mandatory parameter %s "
"missing") % name
value = self._defaults[i - first_optional]
if value is None:
if in_tensors.first_none is None:
in_tensors.first_none = i
none_passed.append("%s (%d)" % (name, i))
if not none_passed:
in_tensors._args.append(value)
if in_tensors.first_none is None:
in_tensors.first_none = len(self._varnames)
# filter-out trailing None arguments when they default to None
# Extending this to any argument set to its default value has
# proven problematic - the trace may be computed with fewer
# inputs than intended.
for i in reversed(range(len(in_tensors._args))):
if in_tensors._args[i] is not None:
break
if self._defaults[i] is not None:
break
in_tensors._args.pop()
if in_tensors.first_none == i:
in_tensors.first_none = None
# assert we are not passing None parameters to avoid a cryptic error
assert None not in in_tensors._args, \
"'None' may not be passed as explicit model argument. It may " + \
"only be used as default initialiser"
if in_tensors.forEachMatchedAtLeastOnce(
condition=lambda t: isinstance(t, torch.Tensor
) and not t.is_contiguous(),
doOnTrue=lambda t: t.contiguous()):
if not self._warned_not_contiguous_input:
logger.warning("At least one input tensor is not contiguous: "
"non-contiguous tensors will be converted.")
self._warned_not_contiguous_input = True
return in_tensors
def _convertLists(self, input):
if isinstance(input, (tuple, list)):
new_tuple = []
for _, data in enumerate(input):
new_tuple.append(self._convertLists(data))
return tuple(new_tuple)
return input
def _errorOnDictReturnTrueIfList(self, data, arg_name, stack_list):
has_list = False
if isinstance(data, (tuple, list)):
for idx, d in enumerate(data):
stack_list.append(idx)
has_list &= self._errorOnDictReturnTrueIfList(
d, arg_name, stack_list)
stack_list.pop()
if isinstance(data, list):
has_list = True
if isinstance(data, (dict)):
stack_list = [str(s) for s in stack_list]
end_msg = arg_name
if stack_list:
end_msg += "[" + "][".join(stack_list) + "]"
end_msg += " = " + str(data)
if isinstance(data, dict):
raise TypeError(
"Dictionaries are not supported as input arguments,"
" including when nested in tuples.\nReceived dict " + end_msg)
return has_list
| [
"copy.copy",
"inspect.signature"
] | [((435, 456), 'copy.copy', 'copy.copy', (['self._args'], {}), '(self._args)\n', (444, 456), False, 'import copy\n'), ((2444, 2482), 'inspect.signature', 'inspect.signature', (['model.model.forward'], {}), '(model.model.forward)\n', (2461, 2482), False, 'import inspect\n'), ((2515, 2547), 'inspect.signature', 'inspect.signature', (['model.forward'], {}), '(model.forward)\n', (2532, 2547), False, 'import inspect\n')] |
from unicodedata import name
from django.shortcuts import render
def home_view(request):
return render(request, 'home.html')
def contact_view(request):
return render(request, 'contact.html')
def skills_view(request):
return render(request, 'skills.html')
def experience_view(request):
return render(request, 'experience.html')
| [
"django.shortcuts.render"
] | [((106, 134), 'django.shortcuts.render', 'render', (['request', '"""home.html"""'], {}), "(request, 'home.html')\n", (112, 134), False, 'from django.shortcuts import render\n'), ((178, 209), 'django.shortcuts.render', 'render', (['request', '"""contact.html"""'], {}), "(request, 'contact.html')\n", (184, 209), False, 'from django.shortcuts import render\n'), ((252, 282), 'django.shortcuts.render', 'render', (['request', '"""skills.html"""'], {}), "(request, 'skills.html')\n", (258, 282), False, 'from django.shortcuts import render\n'), ((329, 363), 'django.shortcuts.render', 'render', (['request', '"""experience.html"""'], {}), "(request, 'experience.html')\n", (335, 363), False, 'from django.shortcuts import render\n')] |
import sys
import tkinter
import functools
def getwin():
window = tkinter.Tk()
globals()['window_data'] = window
return window
def close():
globals()['window_data'].destroy()
def popup():
import argoncraft
win = getwin()
win.title('ArgonCraft - Settings')
win.config(bg=argoncraft.gettheme()['bg'])
ram_var = tkinter.StringVar(value=open('logs/ram.txt').read())
ram_input = tkinter.Entry(win,
fg=argoncraft.gettheme()['fg'],
bg=argoncraft.gettheme()['light'],
font=(argoncraft.gettheme()['font'], 14),
relief='flat',
)
ram_input.pack()
go = tkinter.Button(win,
fg=argoncraft.gettheme()['fg'],
bg=argoncraft.gettheme()['bg'],
text='Save',
font=(argoncraft.gettheme()['font'], 14),
relief='flat',
command=functools.partial(argoncraft.setram, ram_input.get()),
activebackground=argoncraft.gettheme()['light'],
activeforeground=argoncraft.gettheme()['fg']
)
go.pack()
win.mainloop()
| [
"argoncraft.gettheme",
"tkinter.Tk"
] | [((71, 83), 'tkinter.Tk', 'tkinter.Tk', ([], {}), '()\n', (81, 83), False, 'import tkinter\n'), ((306, 327), 'argoncraft.gettheme', 'argoncraft.gettheme', ([], {}), '()\n', (325, 327), False, 'import argoncraft\n'), ((450, 471), 'argoncraft.gettheme', 'argoncraft.gettheme', ([], {}), '()\n', (469, 471), False, 'import argoncraft\n'), ((490, 511), 'argoncraft.gettheme', 'argoncraft.gettheme', ([], {}), '()\n', (509, 511), False, 'import argoncraft\n'), ((667, 688), 'argoncraft.gettheme', 'argoncraft.gettheme', ([], {}), '()\n', (686, 688), False, 'import argoncraft\n'), ((707, 728), 'argoncraft.gettheme', 'argoncraft.gettheme', ([], {}), '()\n', (726, 728), False, 'import argoncraft\n'), ((926, 947), 'argoncraft.gettheme', 'argoncraft.gettheme', ([], {}), '()\n', (945, 947), False, 'import argoncraft\n'), ((983, 1004), 'argoncraft.gettheme', 'argoncraft.gettheme', ([], {}), '()\n', (1002, 1004), False, 'import argoncraft\n'), ((536, 557), 'argoncraft.gettheme', 'argoncraft.gettheme', ([], {}), '()\n', (555, 557), False, 'import argoncraft\n'), ((771, 792), 'argoncraft.gettheme', 'argoncraft.gettheme', ([], {}), '()\n', (790, 792), False, 'import argoncraft\n')] |
import time
import board
import pulseio
import adafruit_irremote
import neopixel
# Configure treasure information
TREASURE_ID = 1
TRANSMIT_DELAY = 15
# Create NeoPixel object to indicate status
pixels = neopixel.NeoPixel(board.NEOPIXEL, 10)
# Create a 'pulseio' output, to send infrared signals on the IR transmitter @ 38KHz
pwm = pulseio.PWMOut(board.IR_TX, frequency=38000, duty_cycle=2 ** 15)
pulseout = pulseio.PulseOut(pwm)
# Create an encoder that will take numbers and turn them into IR pulses
encoder = adafruit_irremote.GenericTransmit(header=[9500, 4500], one=[550, 550], zero=[550, 1700], trail=0)
while True:
pixels.fill(0xC0392B) #match color from hunter code
encoder.transmit(pulseout, [TREASURE_ID]*4)
time.sleep(0.25)
pixels.fill(0)
time.sleep(TRANSMIT_DELAY) | [
"pulseio.PulseOut",
"adafruit_irremote.GenericTransmit",
"time.sleep",
"pulseio.PWMOut",
"neopixel.NeoPixel"
] | [((205, 242), 'neopixel.NeoPixel', 'neopixel.NeoPixel', (['board.NEOPIXEL', '(10)'], {}), '(board.NEOPIXEL, 10)\n', (222, 242), False, 'import neopixel\n'), ((334, 398), 'pulseio.PWMOut', 'pulseio.PWMOut', (['board.IR_TX'], {'frequency': '(38000)', 'duty_cycle': '(2 ** 15)'}), '(board.IR_TX, frequency=38000, duty_cycle=2 ** 15)\n', (348, 398), False, 'import pulseio\n'), ((410, 431), 'pulseio.PulseOut', 'pulseio.PulseOut', (['pwm'], {}), '(pwm)\n', (426, 431), False, 'import pulseio\n'), ((515, 617), 'adafruit_irremote.GenericTransmit', 'adafruit_irremote.GenericTransmit', ([], {'header': '[9500, 4500]', 'one': '[550, 550]', 'zero': '[550, 1700]', 'trail': '(0)'}), '(header=[9500, 4500], one=[550, 550], zero\n =[550, 1700], trail=0)\n', (548, 617), False, 'import adafruit_irremote\n'), ((734, 750), 'time.sleep', 'time.sleep', (['(0.25)'], {}), '(0.25)\n', (744, 750), False, 'import time\n'), ((774, 800), 'time.sleep', 'time.sleep', (['TRANSMIT_DELAY'], {}), '(TRANSMIT_DELAY)\n', (784, 800), False, 'import time\n')] |
from django.conf.urls import patterns, url
urlpatterns = patterns(
'apps.zblog.views',
url(r'^$', 'index', name='index'),
url(r'^(?P<id>\d+)/(?P<slug>[\w_-]+)', 'detail', name='detail'),
url(r'^archives', 'archives', name='archives'),
url(r'^tag/(?P<tag_name>.+)', 'tag', name='tag'),
url(r'^category/(?P<category_name>.+)', 'category', name='category'),
url(r'^page/(?P<page_num>\d+)', 'page', name='page'),
)
| [
"django.conf.urls.url"
] | [((100, 132), 'django.conf.urls.url', 'url', (['"""^$"""', '"""index"""'], {'name': '"""index"""'}), "('^$', 'index', name='index')\n", (103, 132), False, 'from django.conf.urls import patterns, url\n'), ((140, 204), 'django.conf.urls.url', 'url', (['"""^(?P<id>\\\\d+)/(?P<slug>[\\\\w_-]+)"""', '"""detail"""'], {'name': '"""detail"""'}), "('^(?P<id>\\\\d+)/(?P<slug>[\\\\w_-]+)', 'detail', name='detail')\n", (143, 204), False, 'from django.conf.urls import patterns, url\n'), ((210, 255), 'django.conf.urls.url', 'url', (['"""^archives"""', '"""archives"""'], {'name': '"""archives"""'}), "('^archives', 'archives', name='archives')\n", (213, 255), False, 'from django.conf.urls import patterns, url\n'), ((263, 310), 'django.conf.urls.url', 'url', (['"""^tag/(?P<tag_name>.+)"""', '"""tag"""'], {'name': '"""tag"""'}), "('^tag/(?P<tag_name>.+)', 'tag', name='tag')\n", (266, 310), False, 'from django.conf.urls import patterns, url\n'), ((318, 385), 'django.conf.urls.url', 'url', (['"""^category/(?P<category_name>.+)"""', '"""category"""'], {'name': '"""category"""'}), "('^category/(?P<category_name>.+)', 'category', name='category')\n", (321, 385), False, 'from django.conf.urls import patterns, url\n'), ((393, 445), 'django.conf.urls.url', 'url', (['"""^page/(?P<page_num>\\\\d+)"""', '"""page"""'], {'name': '"""page"""'}), "('^page/(?P<page_num>\\\\d+)', 'page', name='page')\n", (396, 445), False, 'from django.conf.urls import patterns, url\n')] |
from clients.rabbitmq_client import RabbitMQClient
import json
from settings import APP_QUEUE
if __name__ == "__main__":
rabbit_mq = RabbitMQClient()
payload = {
"component": "DOBIE",
"message": {
"tasks": [
{
"label": "95671c903a5b97a9",
"jobDescription": "memcached, win32, pig, rdf, linear programming"
}
]
}
}
# data = """SELECT ?subject ?predicate ?object
# WHERE {
# ?subject ?predicate ?object
# }
# LIMIT 100000"""
# payload = {
# "component": "QE",
# "message": {
# "query": payload
# }
# }
rabbit_mq.producer(queue=APP_QUEUE, message=json.dumps(payload))
| [
"json.dumps",
"clients.rabbitmq_client.RabbitMQClient"
] | [((139, 155), 'clients.rabbitmq_client.RabbitMQClient', 'RabbitMQClient', ([], {}), '()\n', (153, 155), False, 'from clients.rabbitmq_client import RabbitMQClient\n'), ((736, 755), 'json.dumps', 'json.dumps', (['payload'], {}), '(payload)\n', (746, 755), False, 'import json\n')] |
import xlrd
import xlwt
import os
class XlsReader:
def __init__(self, file: str):
self.file_path = file
def read_data(self, n:int = 0):
try:
wb = xlrd.open_workbook(self.file_path)
sheet = wb.sheet_by_index(0)
result_list = []
for nr in range(n, sheet.nrows):
row = sheet.row(nr)
cells = []
for cell in row:
cell = str(cell).replace("'", "").split(":")
cells.append((cell[0], ":".join(cell[1:])))
result_list.append(cells)
return result_list
except Exception:
return None
class XlsWriter:
def __init__(self, file: str):
if os.path.exists(file):
os.remove(file)
self.file_path = file
self.sheets = []
self.tables = []
self.wb = xlwt.Workbook()
def add_sheet(self, text, table: list):
header_font = xlwt.Font()
header_font.bold = True
header_style = xlwt.XFStyle()
header_style.font = header_font
ws = self.wb.add_sheet(text)
if len(table) > 0:
for c in range(len(table[0])):
ws.write(0, c, table[0][c], header_style)
if len(table) > 1:
for r in range(1, len(table)):
for c in range(len(table[r])):
ws.write(r, c, table[r][c])
def save(self):
self.wb.save(self.file_path)
| [
"os.path.exists",
"xlwt.Workbook",
"xlwt.XFStyle",
"xlrd.open_workbook",
"xlwt.Font",
"os.remove"
] | [((748, 768), 'os.path.exists', 'os.path.exists', (['file'], {}), '(file)\n', (762, 768), False, 'import os\n'), ((896, 911), 'xlwt.Workbook', 'xlwt.Workbook', ([], {}), '()\n', (909, 911), False, 'import xlwt\n'), ((979, 990), 'xlwt.Font', 'xlwt.Font', ([], {}), '()\n', (988, 990), False, 'import xlwt\n'), ((1047, 1061), 'xlwt.XFStyle', 'xlwt.XFStyle', ([], {}), '()\n', (1059, 1061), False, 'import xlwt\n'), ((185, 219), 'xlrd.open_workbook', 'xlrd.open_workbook', (['self.file_path'], {}), '(self.file_path)\n', (203, 219), False, 'import xlrd\n'), ((782, 797), 'os.remove', 'os.remove', (['file'], {}), '(file)\n', (791, 797), False, 'import os\n')] |
from subprocess import Popen, PIPE
import sys
import os
def osascript(scpt):
p = Popen(['osascript', '-'], stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate(scpt.encode('utf-8'))
return stdout, stderr
def openTab():
script = f"""
tell application "System Events"
tell process "Terminal" to keystroke "t" using command down
end
tell application "Terminal"
activate
do script with command "cd {os.getcwd()}" in window 1
end tell
"""
stdout, stderr = osascript(script)
if stderr:
sys.stderr.write('Error in Applescript: {}\n'.format(stderr)) | [
"subprocess.Popen",
"os.getcwd"
] | [((87, 150), 'subprocess.Popen', 'Popen', (["['osascript', '-']"], {'stdin': 'PIPE', 'stdout': 'PIPE', 'stderr': 'PIPE'}), "(['osascript', '-'], stdin=PIPE, stdout=PIPE, stderr=PIPE)\n", (92, 150), False, 'from subprocess import Popen, PIPE\n'), ((530, 541), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (539, 541), False, 'import os\n')] |
# Generated by Django 3.0.6 on 2020-05-22 08:33
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import usuarios.managers
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0011_update_proxy_permissions'),
('cuestionarios', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')),
('email_colegio', models.EmailField(blank=True, max_length=254, verbose_name='email address colegio')),
('username', models.CharField(blank=True, max_length=255, unique=True)),
('nombre', models.CharField(blank=True, max_length=30, verbose_name='nombre')),
('apellidos', models.CharField(blank=True, max_length=60, verbose_name='apellidos')),
('date_joined', models.DateTimeField(auto_now_add=True, verbose_name='date joined')),
('alias', models.CharField(blank=True, max_length=30)),
('DNI', models.CharField(blank=True, max_length=10)),
('colegio', models.CharField(max_length=100, null=True)),
('is_staff', models.BooleanField(default=False)),
('validado', models.BooleanField(default=False)),
('is_active', models.BooleanField(default=True)),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
],
options={
'abstract': False,
},
managers=[
('objects', usuarios.managers.UserManager()),
],
),
migrations.CreateModel(
name='User_test',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('test', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='cuestionarios.Test')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'unique_together': {('user', 'test')},
},
),
migrations.AddField(
model_name='user',
name='test',
field=models.ManyToManyField(related_name='tests', through='usuarios.User_test', to='cuestionarios.Test'),
),
migrations.AddField(
model_name='user',
name='user_permissions',
field=models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions'),
),
]
| [
"django.db.models.EmailField",
"django.db.models.ForeignKey",
"django.db.models.ManyToManyField",
"django.db.models.BooleanField",
"django.db.models.AutoField",
"django.db.models.DateTimeField",
"django.db.models.CharField"
] | [((3112, 3215), 'django.db.models.ManyToManyField', 'models.ManyToManyField', ([], {'related_name': '"""tests"""', 'through': '"""usuarios.User_test"""', 'to': '"""cuestionarios.Test"""'}), "(related_name='tests', through='usuarios.User_test',\n to='cuestionarios.Test')\n", (3134, 3215), False, 'from django.db import migrations, models\n'), ((3339, 3543), 'django.db.models.ManyToManyField', 'models.ManyToManyField', ([], {'blank': '(True)', 'help_text': '"""Specific permissions for this user."""', 'related_name': '"""user_set"""', 'related_query_name': '"""user"""', 'to': '"""auth.Permission"""', 'verbose_name': '"""user permissions"""'}), "(blank=True, help_text=\n 'Specific permissions for this user.', related_name='user_set',\n related_query_name='user', to='auth.Permission', verbose_name=\n 'user permissions')\n", (3361, 3543), False, 'from django.db import migrations, models\n'), ((485, 578), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (501, 578), False, 'from django.db import migrations, models\n'), ((606, 663), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(128)', 'verbose_name': '"""password"""'}), "(max_length=128, verbose_name='password')\n", (622, 663), False, 'from django.db import migrations, models\n'), ((697, 767), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'blank': '(True)', 'null': '(True)', 'verbose_name': '"""last login"""'}), "(blank=True, null=True, verbose_name='last login')\n", (717, 767), False, 'from django.db import migrations, models\n'), ((803, 974), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)', 'help_text': '"""Designates that this user has all permissions without explicitly assigning them."""', 'verbose_name': '"""superuser status"""'}), "(default=False, help_text=\n 'Designates that this user has all permissions without explicitly assigning them.'\n , verbose_name='superuser status')\n", (822, 974), False, 'from django.db import migrations, models\n'), ((993, 1068), 'django.db.models.EmailField', 'models.EmailField', ([], {'blank': '(True)', 'max_length': '(254)', 'verbose_name': '"""email address"""'}), "(blank=True, max_length=254, verbose_name='email address')\n", (1010, 1068), False, 'from django.db import migrations, models\n'), ((1105, 1193), 'django.db.models.EmailField', 'models.EmailField', ([], {'blank': '(True)', 'max_length': '(254)', 'verbose_name': '"""email address colegio"""'}), "(blank=True, max_length=254, verbose_name=\n 'email address colegio')\n", (1122, 1193), False, 'from django.db import migrations, models\n'), ((1220, 1277), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(255)', 'unique': '(True)'}), '(blank=True, max_length=255, unique=True)\n', (1236, 1277), False, 'from django.db import migrations, models\n'), ((1307, 1373), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(30)', 'verbose_name': '"""nombre"""'}), "(blank=True, max_length=30, verbose_name='nombre')\n", (1323, 1373), False, 'from django.db import migrations, models\n'), ((1406, 1475), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(60)', 'verbose_name': '"""apellidos"""'}), "(blank=True, max_length=60, verbose_name='apellidos')\n", (1422, 1475), False, 'from django.db import migrations, models\n'), ((1510, 1577), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)', 'verbose_name': '"""date joined"""'}), "(auto_now_add=True, verbose_name='date joined')\n", (1530, 1577), False, 'from django.db import migrations, models\n'), ((1606, 1649), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(30)'}), '(blank=True, max_length=30)\n', (1622, 1649), False, 'from django.db import migrations, models\n'), ((1676, 1719), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(10)'}), '(blank=True, max_length=10)\n', (1692, 1719), False, 'from django.db import migrations, models\n'), ((1750, 1793), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)', 'null': '(True)'}), '(max_length=100, null=True)\n', (1766, 1793), False, 'from django.db import migrations, models\n'), ((1825, 1859), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (1844, 1859), False, 'from django.db import migrations, models\n'), ((1891, 1925), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (1910, 1925), False, 'from django.db import migrations, models\n'), ((1958, 1991), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(True)'}), '(default=True)\n', (1977, 1991), False, 'from django.db import migrations, models\n'), ((2021, 2272), 'django.db.models.ManyToManyField', 'models.ManyToManyField', ([], {'blank': '(True)', 'help_text': '"""The groups this user belongs to. A user will get all permissions granted to each of their groups."""', 'related_name': '"""user_set"""', 'related_query_name': '"""user"""', 'to': '"""auth.Group"""', 'verbose_name': '"""groups"""'}), "(blank=True, help_text=\n 'The groups this user belongs to. A user will get all permissions granted to each of their groups.'\n , related_name='user_set', related_query_name='user', to='auth.Group',\n verbose_name='groups')\n", (2043, 2272), False, 'from django.db import migrations, models\n'), ((2565, 2658), 'django.db.models.AutoField', 'models.AutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (2581, 2658), False, 'from django.db import migrations, models\n'), ((2682, 2774), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'django.db.models.deletion.CASCADE', 'to': '"""cuestionarios.Test"""'}), "(on_delete=django.db.models.deletion.CASCADE, to=\n 'cuestionarios.Test')\n", (2699, 2774), False, 'from django.db import migrations, models\n'), ((2797, 2893), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'django.db.models.deletion.CASCADE', 'to': 'settings.AUTH_USER_MODEL'}), '(on_delete=django.db.models.deletion.CASCADE, to=settings.\n AUTH_USER_MODEL)\n', (2814, 2893), False, 'from django.db import migrations, models\n')] |
from flask import Flask, render_template, jsonify
from flask_cors import CORS
from makeSentence import makeSentence
app = Flask(__name__)
CORS(app)
@app.route("/")
def index():
return render_template("index.html", sentence=makeSentence())
@app.route("/api")
def api():
return jsonify(sentence=makeSentence())
if __name__ == "__main__":
app.debug = True
app.env = "DEV"
app.run()
| [
"makeSentence.makeSentence",
"flask_cors.CORS",
"flask.Flask"
] | [((123, 138), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (128, 138), False, 'from flask import Flask, render_template, jsonify\n'), ((139, 148), 'flask_cors.CORS', 'CORS', (['app'], {}), '(app)\n', (143, 148), False, 'from flask_cors import CORS\n'), ((230, 244), 'makeSentence.makeSentence', 'makeSentence', ([], {}), '()\n', (242, 244), False, 'from makeSentence import makeSentence\n'), ((306, 320), 'makeSentence.makeSentence', 'makeSentence', ([], {}), '()\n', (318, 320), False, 'from makeSentence import makeSentence\n')] |
import pickle
import random
import cv2 as cv
import numpy as np
import torch
from torch.utils.data import Dataset
from torchvision import transforms
from config import pickle_file, num_workers
from utils import align_face
# Data augmentation and normalization for training
# Just normalization for validation
data_transforms = {
'train': transforms.Compose([
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
# transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
]),
'val': transforms.Compose([
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
# transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])
]),
}
class ArcFaceDataset(Dataset):
def __init__(self, split):
with open(pickle_file, 'rb') as file:
data = pickle.load(file)
samples = data['samples']
num_samples = len(samples)
num_train = num_samples
if split == 'train':
self.samples = samples[:num_train]
self.transformer = data_transforms['train']
def __getitem__(self, i):
sample = self.samples[i]
full_path = sample['full_path']
landmarks = sample['landmarks']
try:
img = align_face(full_path, landmarks)
except Exception:
print('full_path: ' + full_path)
raise
img = transforms.ToPILImage()(img)
img = self.transformer(img)
class_id = sample['class_id']
return img, class_id
def __len__(self):
return len(self.samples)
def shuffle(self):
np.random.shuffle(self.samples)
def show_align():
with open(pickle_file, 'rb') as file:
data = pickle.load(file)
samples = random.sample(data['samples'], 10)
for i, sample in enumerate(samples):
full_path = sample['full_path']
landmarks = sample['landmarks']
raw = cv.imread(full_path)
raw = cv.resize(raw, (224, 224))
img = align_face(full_path, landmarks)
filename = 'images/{}_raw.jpg'.format(i)
cv.imwrite(filename, raw)
filename = 'images/{}_img.jpg'.format(i)
cv.imwrite(filename, img)
if __name__ == "__main__":
train_dataset = ArcFaceDataset('train')
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=256, shuffle=True,
num_workers=num_workers,
pin_memory=True)
print(len(train_dataset))
print(len(train_loader))
| [
"cv2.imwrite",
"random.sample",
"torchvision.transforms.ToPILImage",
"torchvision.transforms.ToTensor",
"pickle.load",
"torchvision.transforms.RandomHorizontalFlip",
"torchvision.transforms.Normalize",
"torch.utils.data.DataLoader",
"cv2.resize",
"cv2.imread",
"utils.align_face",
"numpy.random... | [((1861, 1895), 'random.sample', 'random.sample', (["data['samples']", '(10)'], {}), "(data['samples'], 10)\n", (1874, 1895), False, 'import random\n'), ((2399, 2517), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['train_dataset'], {'batch_size': '(256)', 'shuffle': '(True)', 'num_workers': 'num_workers', 'pin_memory': '(True)'}), '(train_dataset, batch_size=256, shuffle=True,\n num_workers=num_workers, pin_memory=True)\n', (2426, 2517), False, 'import torch\n'), ((1719, 1750), 'numpy.random.shuffle', 'np.random.shuffle', (['self.samples'], {}), '(self.samples)\n', (1736, 1750), True, 'import numpy as np\n'), ((1828, 1845), 'pickle.load', 'pickle.load', (['file'], {}), '(file)\n', (1839, 1845), False, 'import pickle\n'), ((2032, 2052), 'cv2.imread', 'cv.imread', (['full_path'], {}), '(full_path)\n', (2041, 2052), True, 'import cv2 as cv\n'), ((2067, 2093), 'cv2.resize', 'cv.resize', (['raw', '(224, 224)'], {}), '(raw, (224, 224))\n', (2076, 2093), True, 'import cv2 as cv\n'), ((2108, 2140), 'utils.align_face', 'align_face', (['full_path', 'landmarks'], {}), '(full_path, landmarks)\n', (2118, 2140), False, 'from utils import align_face\n'), ((2198, 2223), 'cv2.imwrite', 'cv.imwrite', (['filename', 'raw'], {}), '(filename, raw)\n', (2208, 2223), True, 'import cv2 as cv\n'), ((2281, 2306), 'cv2.imwrite', 'cv.imwrite', (['filename', 'img'], {}), '(filename, img)\n', (2291, 2306), True, 'import cv2 as cv\n'), ((374, 407), 'torchvision.transforms.RandomHorizontalFlip', 'transforms.RandomHorizontalFlip', ([], {}), '()\n', (405, 407), False, 'from torchvision import transforms\n'), ((417, 438), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (436, 438), False, 'from torchvision import transforms\n'), ((448, 514), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['[0.485, 0.456, 0.406]', '[0.229, 0.224, 0.225]'], {}), '([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n', (468, 514), False, 'from torchvision import transforms\n'), ((628, 649), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (647, 649), False, 'from torchvision import transforms\n'), ((659, 725), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['[0.485, 0.456, 0.406]', '[0.229, 0.224, 0.225]'], {}), '([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n', (679, 725), False, 'from torchvision import transforms\n'), ((930, 947), 'pickle.load', 'pickle.load', (['file'], {}), '(file)\n', (941, 947), False, 'import pickle\n'), ((1360, 1392), 'utils.align_face', 'align_face', (['full_path', 'landmarks'], {}), '(full_path, landmarks)\n', (1370, 1392), False, 'from utils import align_face\n'), ((1497, 1520), 'torchvision.transforms.ToPILImage', 'transforms.ToPILImage', ([], {}), '()\n', (1518, 1520), False, 'from torchvision import transforms\n')] |
import multiprocessing as mp
import pandas as pd
import dill
from functools import wraps
__spawn_ctx__ = None
def get_mp_ctx(f):
def with_ctx(*args, **kws):
global __spawn_ctx__
if __spawn_ctx__ is None:
__spawn_ctx__ = mp.get_context('spawn')
return f(*args, mp_ctx=__spawn_ctx__, **kws)
return wraps(f)(with_ctx)
def apply_worker(result_queue, data, offset, chunk_size, f_pickled, kwargs):
# Unpickle the function
f = dill.loads(f_pickled)
# Apply function and store result
chunk = data[offset*chunk_size:(offset+1)*chunk_size]
result_queue.put((offset, chunk.apply(f, **kwargs)))
return True
@get_mp_ctx
def apply(data, f, n_processes=mp.cpu_count(), mp_ctx=None, **kwargs):
"""
parallel version of apply
Parameters
----------
data : Series or DataFrame
the pandas object to apply data on
f : function
the function to apply
n_processes : int (optional)
specify the number of processes to use, otherwise use all
Additional keyword arguments will be passed on to pandas apply operation
Returns
-------
result of apply operation
"""
# Compute chunk size
chunk_size = (len(data)-1) // n_processes + 1
# Pickle function
f_pickled = dill.dumps(f)
# Start workers
result_queue = mp_ctx.Queue()
processes = []
for offset in range(n_processes):
p = mp_ctx.Process(target=apply_worker,
args=(result_queue, data, offset, chunk_size,
f_pickled, kwargs))
p.daemon = True
p.start()
processes.append(p)
# Get results
results = list()
while len(results) < n_processes:
results.append(result_queue.get())
# Wait for all workers to finish
for p in processes:
p.join()
# Close queues
result_queue.close()
# Sort results such that resulting series/dataframe has the same index
# as the original one
results = [y[1] for y in sorted(results, key=lambda x: x[0])]
# Return concated results
return pd.concat(results)
def groupby_apply_worker(result_queue, dataframe, columns, f_pickled,
i_segment, segments):
# Unpickle the function
f = dill.loads(f_pickled)
# Groupby, apply function and return result
result_queue.put(dataframe[segments == i_segment].groupby(
by=columns, sort=False).apply(f))
return True
@get_mp_ctx
def groupby_apply(dataframe, columns, func,
n_processes=mp.cpu_count(), mp_ctx=None):
"""
parallel version of groupby/apply
Parameters
----------
data : Series or DataFrame
the pandas object to apply data on
columns : list or Index
subset of columns to used to group by
func : function
the function pass to apply of the grouper object
n_processes : int (optional)
specify the number of processes to use, otherwise use all
Returns
-------
result of groupby/apply operation
"""
# Pickle function
f_pickled = dill.dumps(func)
# Segmentize rows such that two rows belonging to the same group
# are assigned to the same segment
segments = apply(dataframe[columns],
lambda x: hash(tuple(x.values)) % n_processes,
n_processes=mp.cpu_count(), axis=1)
# Init and start workers
result_queue = mp_ctx.Queue()
processes = []
for iSegment in range(n_processes):
p = mp_ctx.Process(target=groupby_apply_worker,
args=(result_queue, dataframe, columns,
f_pickled, iSegment, segments))
p.daemon = True
p.start()
processes.append(p)
# Get results
results = list()
while len(results) < n_processes:
results.append(result_queue.get())
# Wait for all workers to finish
for p in processes:
p.join()
# Close queues
result_queue.close()
# Return concated results
return pd.concat(results)
| [
"multiprocessing.get_context",
"dill.loads",
"functools.wraps",
"multiprocessing.cpu_count",
"dill.dumps",
"pandas.concat"
] | [((477, 498), 'dill.loads', 'dill.loads', (['f_pickled'], {}), '(f_pickled)\n', (487, 498), False, 'import dill\n'), ((713, 727), 'multiprocessing.cpu_count', 'mp.cpu_count', ([], {}), '()\n', (725, 727), True, 'import multiprocessing as mp\n'), ((1295, 1308), 'dill.dumps', 'dill.dumps', (['f'], {}), '(f)\n', (1305, 1308), False, 'import dill\n'), ((2106, 2124), 'pandas.concat', 'pd.concat', (['results'], {}), '(results)\n', (2115, 2124), True, 'import pandas as pd\n'), ((2280, 2301), 'dill.loads', 'dill.loads', (['f_pickled'], {}), '(f_pickled)\n', (2290, 2301), False, 'import dill\n'), ((2559, 2573), 'multiprocessing.cpu_count', 'mp.cpu_count', ([], {}), '()\n', (2571, 2573), True, 'import multiprocessing as mp\n'), ((3099, 3115), 'dill.dumps', 'dill.dumps', (['func'], {}), '(func)\n', (3109, 3115), False, 'import dill\n'), ((4045, 4063), 'pandas.concat', 'pd.concat', (['results'], {}), '(results)\n', (4054, 4063), True, 'import pandas as pd\n'), ((343, 351), 'functools.wraps', 'wraps', (['f'], {}), '(f)\n', (348, 351), False, 'from functools import wraps\n'), ((255, 278), 'multiprocessing.get_context', 'mp.get_context', (['"""spawn"""'], {}), "('spawn')\n", (269, 278), True, 'import multiprocessing as mp\n'), ((3366, 3380), 'multiprocessing.cpu_count', 'mp.cpu_count', ([], {}), '()\n', (3378, 3380), True, 'import multiprocessing as mp\n')] |
from collections import defaultdict
from typing import List, Any, Tuple, Dict
from util.helpers import solution_timer
from util.input_helper import read_entire_input
data = read_entire_input(2019,6)
def parse(data: List[str]) -> Any:
orbits = defaultdict(list)
orbiting = {}
for row in data:
a,b=row.split(")")
orbits[a].append(b)
orbiting[b] = a
return orbits, orbiting
class Node:
def __init__(self, name, degree=0, parent=None, head=None):
self.name = name
self.degree=degree
self.parent=parent
self.head=self if head is None else head
self.children = []
self.total_degree=0
def add_child(self, name: str):
child = Node(name=name, degree=self.degree+1,parent=self,head=self.head)
self.children.append(child)
self.head.total_degree += child.degree
return child
def __repr__(self):
return f"Node({self.name})"
def build_orbital_tree(orbits: Dict[str,str], parent: Node):
for child_name in orbits[parent.name]:
child = parent.add_child(child_name)
build_orbital_tree(orbits, child)
def path_to_root(orbiting: Dict[str,str], start):
parent = orbiting.get(start, None)
if parent is None:
return start
return parent + ',' + path_to_root(orbiting, parent)
def find_node(root: Node, name: str):
if root.name == name:
return root
else:
for child in root.children:
return find_node(child, name)
def find_first_common_element(A: list, B: list):
for a in A:
if a in B:
return a
@solution_timer(2019,6,1)
def part_one(data: List[str]):
orbits, _ = parse(data)
root_node = Node('COM')
build_orbital_tree(orbits, root_node)
return root_node.total_degree
@solution_timer(2019,6,2)
def part_two(data: List[str]):
_, orbiting = parse(data)
your_orbits = path_to_root(orbiting,'YOU').split(",")
santa_orbits= path_to_root(orbiting,'SAN').split(",")
first_common_element = find_first_common_element(your_orbits, santa_orbits)
return your_orbits.index(first_common_element) + santa_orbits.index(first_common_element)
if __name__ == "__main__":
data = read_entire_input(2019,6)
part_one(data)
part_two(data) | [
"util.input_helper.read_entire_input",
"collections.defaultdict",
"util.helpers.solution_timer"
] | [((174, 200), 'util.input_helper.read_entire_input', 'read_entire_input', (['(2019)', '(6)'], {}), '(2019, 6)\n', (191, 200), False, 'from util.input_helper import read_entire_input\n'), ((1618, 1644), 'util.helpers.solution_timer', 'solution_timer', (['(2019)', '(6)', '(1)'], {}), '(2019, 6, 1)\n', (1632, 1644), False, 'from util.helpers import solution_timer\n'), ((1808, 1834), 'util.helpers.solution_timer', 'solution_timer', (['(2019)', '(6)', '(2)'], {}), '(2019, 6, 2)\n', (1822, 1834), False, 'from util.helpers import solution_timer\n'), ((249, 266), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (260, 266), False, 'from collections import defaultdict\n'), ((2222, 2248), 'util.input_helper.read_entire_input', 'read_entire_input', (['(2019)', '(6)'], {}), '(2019, 6)\n', (2239, 2248), False, 'from util.input_helper import read_entire_input\n')] |
import socket
MAX_PACKET_SIZE = 1024
def start_client(host=socket.gethostname(), port=5000):
# Create socket
client_socket = socket.socket()
# Connect to host and port
client_socket.connect((host, port))
# Enter a message from user
msg = input("Enter a message: ")
while msg.lower().strip() not in ("bye", "quit", "exit"):
# Send message
client_socket.send(msg.encode())
# Get response
resp = client_socket.recv(MAX_PACKET_SIZE).decode()
print("Got as response: {}".format(resp))
msg = input("Enter a message: ")
client_socket.close()
if __name__ == "__main__":
start_client()
| [
"socket.gethostname",
"socket.socket"
] | [((62, 82), 'socket.gethostname', 'socket.gethostname', ([], {}), '()\n', (80, 82), False, 'import socket\n'), ((136, 151), 'socket.socket', 'socket.socket', ([], {}), '()\n', (149, 151), False, 'import socket\n')] |
from math import factorial
def solve(r):
if r == 1:
return 1
elif r == 2:
return 5
elif r == 3:
return 15
fatR = factorial(r)
fatR_m1 = factorial(r-1)
comb_part_one = fatR/(2*factorial(r-2))
comb_part_two = r * (fatR_m1/(2*factorial((r-1)-2)))
arranjo = fatR / (factorial(r-4))
return int(r + (r*(r-1)) + comb_part_one + comb_part_two + (arranjo/12))
if __name__ == '__main__':
while True:
try:
r = int(input())
if r == 0:
break
print(solve(r)%1000007)
except EOFError:
break
| [
"math.factorial"
] | [((155, 167), 'math.factorial', 'factorial', (['r'], {}), '(r)\n', (164, 167), False, 'from math import factorial\n'), ((182, 198), 'math.factorial', 'factorial', (['(r - 1)'], {}), '(r - 1)\n', (191, 198), False, 'from math import factorial\n'), ((321, 337), 'math.factorial', 'factorial', (['(r - 4)'], {}), '(r - 4)\n', (330, 337), False, 'from math import factorial\n'), ((226, 242), 'math.factorial', 'factorial', (['(r - 2)'], {}), '(r - 2)\n', (235, 242), False, 'from math import factorial\n'), ((278, 298), 'math.factorial', 'factorial', (['(r - 1 - 2)'], {}), '(r - 1 - 2)\n', (287, 298), False, 'from math import factorial\n')] |
import unittest
from fxphelper import *
C_TEST_PRECISION = 5
class TestConversion(unittest.TestCase):
def test_conv_unsigned_int(self):
x = 3
y = FXPQNumber(0,5,0, float_value = x)
self.assertAlmostEqual(y.to_float(), x, C_TEST_PRECISION)
def test_conv_signed_int(self):
x = -3
y = FXPQNumber(1,5,0, float_value = x)
self.assertAlmostEqual(y.to_float(), x, C_TEST_PRECISION)
def test_conv_unsigned_float(self):
x = 3.2
y = FXPQNumber(0,4,17, float_value = x)
self.assertAlmostEqual(y.to_float(), x, C_TEST_PRECISION)
def test_conv_signed_float(self):
x = -3.2
y = FXPQNumber(1,4,17, float_value = x)
self.assertAlmostEqual(y.to_float(), x, C_TEST_PRECISION)
def test_conv_cpl_signed_float(self):
x = complex(-3.2, 1.7)
y = FXPQComplex(1,4,17, complex_value = x)
self.assertAlmostEqual(y.to_complex(), x, C_TEST_PRECISION)
if __name__ == '__main__':
unittest.main()
| [
"unittest.main"
] | [((1004, 1019), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1017, 1019), False, 'import unittest\n')] |
from rest_framework import serializers
from django.contrib.auth.models import Permission, ContentType, Group
class GroupPermissionModelSerializer(serializers.ModelSerializer):
class Meta:
model = Group
fields = '__all__'
class PermissionSimpleSerializer(serializers.ModelSerializer):
content_type = serializers.StringRelatedField()
class Meta:
model = Permission
fields = ['id', 'name', 'content_type']
| [
"rest_framework.serializers.StringRelatedField"
] | [((327, 359), 'rest_framework.serializers.StringRelatedField', 'serializers.StringRelatedField', ([], {}), '()\n', (357, 359), False, 'from rest_framework import serializers\n')] |
import FWCore.ParameterSet.Config as cms
# Remove duplicates from the electron list
electronsNoDuplicates = cms.EDFilter("DuplicatedElectronCleaner",
## reco electron input source
electronSource = cms.InputTag("gsfElectrons"),
)
| [
"FWCore.ParameterSet.Config.InputTag"
] | [((207, 235), 'FWCore.ParameterSet.Config.InputTag', 'cms.InputTag', (['"""gsfElectrons"""'], {}), "('gsfElectrons')\n", (219, 235), True, 'import FWCore.ParameterSet.Config as cms\n')] |
import json
import os
class ToolSettings:
def __init__(self, repopath, importFacePoses, DEFAULT_DIR_KEY, RECENT_FILES, RECENT_FILES_MAX):
self.repopath = repopath
self.importFacePoses = importFacePoses
self.DEFAULT_DIR_KEY = DEFAULT_DIR_KEY
self.RECENT_FILES = RECENT_FILES
self.RECENT_FILES_MAX = RECENT_FILES_MAX
@classmethod
def from_json(cls, data):
return cls(**data)
def get():
dirpath, file = os.path.split(__file__)
config_file = directory = dirpath+"\\config.json"
with open(config_file) as config_file:
jsondata = json.load(config_file)
data = ToolSettings.from_json(jsondata)
return data
def save(toolSettings):
dirpath, file = os.path.split(__file__)
config_file = directory = dirpath+"\\config.json"
with open(config_file, "w") as file:
file.write(json.dumps(toolSettings.__dict__,indent=2, sort_keys=True)) | [
"json.load",
"json.dumps",
"os.path.split"
] | [((467, 490), 'os.path.split', 'os.path.split', (['__file__'], {}), '(__file__)\n', (480, 490), False, 'import os\n'), ((745, 768), 'os.path.split', 'os.path.split', (['__file__'], {}), '(__file__)\n', (758, 768), False, 'import os\n'), ((608, 630), 'json.load', 'json.load', (['config_file'], {}), '(config_file)\n', (617, 630), False, 'import json\n'), ((884, 943), 'json.dumps', 'json.dumps', (['toolSettings.__dict__'], {'indent': '(2)', 'sort_keys': '(True)'}), '(toolSettings.__dict__, indent=2, sort_keys=True)\n', (894, 943), False, 'import json\n')] |
import streamlit as st
import pandas as pd
import numpy as np
DISPLAY_TEXT = "Display Text"
DISPLAY_DATA = "Display Data"
DISPLAY_CODE = "Display Code"
DISPLAY_GRAPHS = "Display Graphs"
USE_MEDIA = "Webcam and Microphone"
DRAWABLE_CANVAS = "Drawable Canvas"
INTERACTIVE_DISPLAY = "User interaction"
PROGRESS_AND_STATUS = "Progress and Status"
# Set wide display
st.set_page_config(layout="wide")
# Side Bar
## Create a page dropdown
page = st.sidebar.radio("Choose your page:",
[
DISPLAY_TEXT,
DISPLAY_DATA,
DISPLAY_CODE,
PROGRESS_AND_STATUS,
INTERACTIVE_DISPLAY,
#DISPLAY_GRAPHS,
#DRAWABLE_CANVAS,
#USE_MEDIA,
]
)
## Links
links = [
"* [Streamlit Cheat Sheet](https://share.streamlit.io/daniellewisdl/streamlit-cheat-sheet/app.py)",
"* [Streamlit Gallery](https://streamlit.io/gallery)",
]
st.sidebar.markdown("Links:")
st.sidebar.markdown("\n".join(links))
## Autor
st.sidebar.markdown("Created by [sebastiandres](https://sebastiandres.xyz)")
# Main Page, display according to selection
if page == DISPLAY_TEXT:
from pages import display_text
display_text.display_page(page)
elif page == DISPLAY_DATA:
from pages import display_data
display_data.display_page(page)
elif page == DISPLAY_CODE:
from pages import display_code
display_code.display_page(page)
elif page == DISPLAY_GRAPHS:
from pages import display_graphs
display_graphs.display_page(page)
elif page == USE_MEDIA:
from pages import display_media
display_media.display_page(page)
elif page == DRAWABLE_CANVAS:
from pages import drawable_canvas
drawable_canvas.display_page(page)
elif page == INTERACTIVE_DISPLAY:
from pages import interactive_widgets
interactive_widgets.display_page(page)
elif page == PROGRESS_AND_STATUS:
from pages import progress_and_status
progress_and_status.display_page(page) | [
"pages.progress_and_status.display_page",
"pages.display_text.display_page",
"pages.drawable_canvas.display_page",
"streamlit.sidebar.markdown",
"pages.display_graphs.display_page",
"pages.interactive_widgets.display_page",
"pages.display_data.display_page",
"streamlit.set_page_config",
"pages.displ... | [((364, 397), 'streamlit.set_page_config', 'st.set_page_config', ([], {'layout': '"""wide"""'}), "(layout='wide')\n", (382, 397), True, 'import streamlit as st\n'), ((443, 570), 'streamlit.sidebar.radio', 'st.sidebar.radio', (['"""Choose your page:"""', '[DISPLAY_TEXT, DISPLAY_DATA, DISPLAY_CODE, PROGRESS_AND_STATUS,\n INTERACTIVE_DISPLAY]'], {}), "('Choose your page:', [DISPLAY_TEXT, DISPLAY_DATA,\n DISPLAY_CODE, PROGRESS_AND_STATUS, INTERACTIVE_DISPLAY])\n", (459, 570), True, 'import streamlit as st\n'), ((1128, 1157), 'streamlit.sidebar.markdown', 'st.sidebar.markdown', (['"""Links:"""'], {}), "('Links:')\n", (1147, 1157), True, 'import streamlit as st\n'), ((1207, 1283), 'streamlit.sidebar.markdown', 'st.sidebar.markdown', (['"""Created by [sebastiandres](https://sebastiandres.xyz)"""'], {}), "('Created by [sebastiandres](https://sebastiandres.xyz)')\n", (1226, 1283), True, 'import streamlit as st\n'), ((1394, 1425), 'pages.display_text.display_page', 'display_text.display_page', (['page'], {}), '(page)\n', (1419, 1425), False, 'from pages import display_text\n'), ((1492, 1523), 'pages.display_data.display_page', 'display_data.display_page', (['page'], {}), '(page)\n', (1517, 1523), False, 'from pages import display_data\n'), ((1590, 1621), 'pages.display_code.display_page', 'display_code.display_page', (['page'], {}), '(page)\n', (1615, 1621), False, 'from pages import display_code\n'), ((1692, 1725), 'pages.display_graphs.display_page', 'display_graphs.display_page', (['page'], {}), '(page)\n', (1719, 1725), False, 'from pages import display_graphs\n'), ((1790, 1822), 'pages.display_media.display_page', 'display_media.display_page', (['page'], {}), '(page)\n', (1816, 1822), False, 'from pages import display_media\n'), ((1895, 1929), 'pages.drawable_canvas.display_page', 'drawable_canvas.display_page', (['page'], {}), '(page)\n', (1923, 1929), False, 'from pages import drawable_canvas\n'), ((2010, 2048), 'pages.interactive_widgets.display_page', 'interactive_widgets.display_page', (['page'], {}), '(page)\n', (2042, 2048), False, 'from pages import interactive_widgets\n'), ((2129, 2167), 'pages.progress_and_status.display_page', 'progress_and_status.display_page', (['page'], {}), '(page)\n', (2161, 2167), False, 'from pages import progress_and_status\n')] |
import requests
from bs4 import BeautifulSoup
import re
from datetime import datetime
class PageScrapper:
def __init__(self, server):
self.url = 'https://czech-craft.eu/server/' + server + '/vote/'
def CanVote(self):
page = requests.get(self.url)
if page.status_code != 200:
return -1
soup = BeautifulSoup(page.content, "html.parser")
alerts = soup.findAll("div", {"class": "alert-error"})
if len(alerts) < 1:
return 1
else:
text = alerts[0].text # if you can vote - return time left
only_time = ":".join(re.findall("[0-9]+", text))
result = datetime.strptime(only_time, '%H:%M:%S').time()
return result
| [
"bs4.BeautifulSoup",
"re.findall",
"datetime.datetime.strptime",
"requests.get"
] | [((251, 273), 'requests.get', 'requests.get', (['self.url'], {}), '(self.url)\n', (263, 273), False, 'import requests\n'), ((348, 390), 'bs4.BeautifulSoup', 'BeautifulSoup', (['page.content', '"""html.parser"""'], {}), "(page.content, 'html.parser')\n", (361, 390), False, 'from bs4 import BeautifulSoup\n'), ((624, 650), 're.findall', 're.findall', (['"""[0-9]+"""', 'text'], {}), "('[0-9]+', text)\n", (634, 650), False, 'import re\n'), ((674, 714), 'datetime.datetime.strptime', 'datetime.strptime', (['only_time', '"""%H:%M:%S"""'], {}), "(only_time, '%H:%M:%S')\n", (691, 714), False, 'from datetime import datetime\n')] |
#First we'll import the os module
#This will allow us to create file paths across operating systems
import os
#Module for reading CSV files
import csv
#Set path for file
csvpath = os.path.join("budget_data.csv")
#Open the csv
with open(csvpath) as csvfile:
csvreader = csv.reader(csvfile, delimiter=",")
#Read the header row first (skip this step if there is now header)
csv_header = next(csvreader)
print(f"CSV Header: {csv_header}")
total_profit = 0
List_of_changes =[]
Greatest_Increase = 0
Greatest_Decrease = 0
#Loop through looking for the months then add to counter
month_counter = 0
for row in csvreader:
#Count number of months
month_counter= (month_counter+ 1)
#Calculate Total Profit
total_profit = total_profit + int(row[1])
#Calculate month-to-month change
if month_counter ==1:
previous = int(row[1])
else:
month_to_month_change = int(row[1]) - previous
previous = int(row[1])
List_of_changes.append(month_to_month_change)
#Calculate greatest increase in profits:
if Greatest_Increase < month_to_month_change:
Greatest_Increase = month_to_month_change
Greatest_Increase_Date = str(row[0])
elif Greatest_Decrease > month_to_month_change:
Greatest_Decrease = month_to_month_change
Greatest_Decrease_Date = str(row[0])
print("Financial Analysis")
print("------------------")
print(f"Total Months : {month_counter}")
print(f"Total : ${total_profit}")
print(f"Average Change:{sum(List_of_changes)/ (month_counter-1)}")
print(f"Greatest Increase in Profits : {Greatest_Increase_Date} (${Greatest_Increase})")
print(f"Greatest Decrease in Profits : {Greatest_Decrease_Date} (${Greatest_Decrease})") | [
"os.path.join",
"csv.reader"
] | [((182, 213), 'os.path.join', 'os.path.join', (['"""budget_data.csv"""'], {}), "('budget_data.csv')\n", (194, 213), False, 'import os\n'), ((276, 310), 'csv.reader', 'csv.reader', (['csvfile'], {'delimiter': '""","""'}), "(csvfile, delimiter=',')\n", (286, 310), False, 'import csv\n')] |
#%%
import matplotlib.pyplot as plt
import cv2
import numpy as np
import os
import re
from pathlib import Path
#%%
def find_contours(img):
# img channels assumed to be RGB
img_bw = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
_, thresh = cv2.threshold(img_bw, 0, 255, cv2.THRESH_BINARY_INV)
contours, _ = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
return contours
def mask_leaf_parts(img):
contours = find_contours(img)
# longest contour usually corresponds to the whole leaf (not necessarily always)
i = np.argmax([len(c) for c in contours])
leaf_contour = contours[i]
mask = np.zeros(img.shape[:2], np.uint8)
cv2.fillPoly(mask, pts=[leaf_contour], color=(255, 255, 255))
masked = cv2.bitwise_and(img, img, mask=mask)
return masked
#%%
def get_bounding_boxes(path_masked):
# assumes image is masked
img_orig = cv2.imread(path_masked)
# plt.imshow(img_orig)
img = cv2.cvtColor(img_orig, cv2.COLOR_BGR2RGB)
# plt.imshow(img)
contours = find_contours(img)
# print(len(contours))
contours = contours[1:]
boxes = []
for i, c in enumerate(contours[::-1]):
if (cv2.contourArea(c) > 10000):
boxes.append(cv2.boundingRect(c))
return boxes
def cut(img, bounding_boxes, is_masked=True):
segments = []
for x,y,w,h in bounding_boxes:
img_segmented = img[y:y+h, x:x+w]
if is_masked:
img_segmented = mask_leaf_parts(img_segmented)
segments.append(img_segmented)
return segments
def write(segments, path, img_original, output_path):
filename = Path(path).stem
pathname = os.path.join(output_path, filename)
original_filetype = os.path.splitext(path)[1]
segmented_paths = []
if not os.path.exists(pathname):
os.makedirs(pathname)
# for now, save the original image in the same location as the segments, just for easy checking that the segmentation has gone right
cv2.imwrite(os.path.join(pathname, f"{filename}{original_filetype}"), img_original)
for i, segment in enumerate(segments):
segmented_path = os.path.join(pathname, f"{filename}_{i}.png")
segmented_paths.append(segmented_path)
cv2.imwrite(segmented_path, segment)
return segmented_paths
def segment(path_masked, path_original, output_path):
img_orig_masked = cv2.imread(path_masked)
img_masked = cv2.cvtColor(img_orig_masked, cv2.COLOR_BGR2RGB)
img_orig = cv2.imread(path_original)
img_original = cv2.cvtColor(img_orig, cv2.COLOR_BGR2RGB)
bounding_boxes = get_bounding_boxes(path_masked)
segments_masked = cut(img_masked, bounding_boxes, is_masked=True)
segments_original = cut(img_original, bounding_boxes, is_masked=False)
# TODO: if original image and masked image names will be the same (the separation is done on the folder level for example), the original image will overwrite the segmented masked image
segmented_paths_masked = write(segments_masked, path_masked, img_masked, output_path)
segmented_paths_original = write(segments_original, path_original, img_original, output_path)
return segmented_paths_masked, segmented_paths_original
| [
"cv2.fillPoly",
"os.path.exists",
"cv2.imwrite",
"os.makedirs",
"pathlib.Path",
"cv2.threshold",
"cv2.bitwise_and",
"os.path.join",
"os.path.splitext",
"cv2.contourArea",
"numpy.zeros",
"cv2.cvtColor",
"cv2.findContours",
"cv2.imread",
"cv2.boundingRect"
] | [((191, 228), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_RGB2GRAY'], {}), '(img, cv2.COLOR_RGB2GRAY)\n', (203, 228), False, 'import cv2\n'), ((245, 297), 'cv2.threshold', 'cv2.threshold', (['img_bw', '(0)', '(255)', 'cv2.THRESH_BINARY_INV'], {}), '(img_bw, 0, 255, cv2.THRESH_BINARY_INV)\n', (258, 297), False, 'import cv2\n'), ((316, 380), 'cv2.findContours', 'cv2.findContours', (['thresh', 'cv2.RETR_TREE', 'cv2.CHAIN_APPROX_SIMPLE'], {}), '(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n', (332, 380), False, 'import cv2\n'), ((639, 672), 'numpy.zeros', 'np.zeros', (['img.shape[:2]', 'np.uint8'], {}), '(img.shape[:2], np.uint8)\n', (647, 672), True, 'import numpy as np\n'), ((677, 738), 'cv2.fillPoly', 'cv2.fillPoly', (['mask'], {'pts': '[leaf_contour]', 'color': '(255, 255, 255)'}), '(mask, pts=[leaf_contour], color=(255, 255, 255))\n', (689, 738), False, 'import cv2\n'), ((753, 789), 'cv2.bitwise_and', 'cv2.bitwise_and', (['img', 'img'], {'mask': 'mask'}), '(img, img, mask=mask)\n', (768, 789), False, 'import cv2\n'), ((897, 920), 'cv2.imread', 'cv2.imread', (['path_masked'], {}), '(path_masked)\n', (907, 920), False, 'import cv2\n'), ((958, 999), 'cv2.cvtColor', 'cv2.cvtColor', (['img_orig', 'cv2.COLOR_BGR2RGB'], {}), '(img_orig, cv2.COLOR_BGR2RGB)\n', (970, 999), False, 'import cv2\n'), ((1666, 1701), 'os.path.join', 'os.path.join', (['output_path', 'filename'], {}), '(output_path, filename)\n', (1678, 1701), False, 'import os\n'), ((2387, 2410), 'cv2.imread', 'cv2.imread', (['path_masked'], {}), '(path_masked)\n', (2397, 2410), False, 'import cv2\n'), ((2428, 2476), 'cv2.cvtColor', 'cv2.cvtColor', (['img_orig_masked', 'cv2.COLOR_BGR2RGB'], {}), '(img_orig_masked, cv2.COLOR_BGR2RGB)\n', (2440, 2476), False, 'import cv2\n'), ((2493, 2518), 'cv2.imread', 'cv2.imread', (['path_original'], {}), '(path_original)\n', (2503, 2518), False, 'import cv2\n'), ((2538, 2579), 'cv2.cvtColor', 'cv2.cvtColor', (['img_orig', 'cv2.COLOR_BGR2RGB'], {}), '(img_orig, cv2.COLOR_BGR2RGB)\n', (2550, 2579), False, 'import cv2\n'), ((1635, 1645), 'pathlib.Path', 'Path', (['path'], {}), '(path)\n', (1639, 1645), False, 'from pathlib import Path\n'), ((1727, 1749), 'os.path.splitext', 'os.path.splitext', (['path'], {}), '(path)\n', (1743, 1749), False, 'import os\n'), ((1791, 1815), 'os.path.exists', 'os.path.exists', (['pathname'], {}), '(pathname)\n', (1805, 1815), False, 'import os\n'), ((1825, 1846), 'os.makedirs', 'os.makedirs', (['pathname'], {}), '(pathname)\n', (1836, 1846), False, 'import os\n'), ((2001, 2057), 'os.path.join', 'os.path.join', (['pathname', 'f"""{filename}{original_filetype}"""'], {}), "(pathname, f'{filename}{original_filetype}')\n", (2013, 2057), False, 'import os\n'), ((2142, 2187), 'os.path.join', 'os.path.join', (['pathname', 'f"""{filename}_{i}.png"""'], {}), "(pathname, f'{filename}_{i}.png')\n", (2154, 2187), False, 'import os\n'), ((2243, 2279), 'cv2.imwrite', 'cv2.imwrite', (['segmented_path', 'segment'], {}), '(segmented_path, segment)\n', (2254, 2279), False, 'import cv2\n'), ((1184, 1202), 'cv2.contourArea', 'cv2.contourArea', (['c'], {}), '(c)\n', (1199, 1202), False, 'import cv2\n'), ((1238, 1257), 'cv2.boundingRect', 'cv2.boundingRect', (['c'], {}), '(c)\n', (1254, 1257), False, 'import cv2\n')] |
from tile_calculator.main import parse_args
def test_main():
parser = parse_args(["54", "18", "1", "10"])
assert parser.latitude == 54
assert parser.longitude == 18
assert parser.radius == 1
assert parser.zoom_level == 10
assert not parser.miles
assert not parser.total_only
| [
"tile_calculator.main.parse_args"
] | [((76, 111), 'tile_calculator.main.parse_args', 'parse_args', (["['54', '18', '1', '10']"], {}), "(['54', '18', '1', '10'])\n", (86, 111), False, 'from tile_calculator.main import parse_args\n')] |
#!/usr/bin/env python3
"""
Usage:
run_clust.py (create|run) <path> [options] [--] [<add_args> ...]
Options:
Logging:
--log <level> Level of stdout logging [default: INFO]
--lformat <level> Which formatter to use [default: extended]
Experiments:
--raw Run code inside the 'code_root' folder directly.
(Disables --commit flag)
--commit <hash> Check out this commit [default: HEAD]
(Mutually exclusive with --raw)
"""
from pathlib import Path
from docopt import docopt
import vst
from dervo.snippets import (docopt_loglevel, loglevel_int_to_str, find_exp_path)
from dervo import experiment
def main(args):
# Define proper formatter right away
loglevel_int: int = docopt_loglevel(args.get('--log'))
log = vst.reasonable_logging_setup(loglevel_int, args['--lformat'])
log.info('STDOUT loglevel: {}'.format(loglevel_int_to_str(loglevel_int)))
if args['create']:
# path -> path to experiment
path = find_exp_path(args['<path>'])
co_commit = None if args['--raw'] else args['--commit']
experiment.prepare_cluster_experiment(path, args['<add_args>'], co_commit)
elif args['run']:
# path -> path to workfolder
workfolder_w_commit = Path(args['<path>'])
experiment.run_cluster_experiment(workfolder_w_commit, args['<add_args>'])
else:
raise NotImplementedError()
if __name__ == '__main__':
args = docopt(__doc__)
main(args)
| [
"pathlib.Path",
"vst.reasonable_logging_setup",
"dervo.experiment.run_cluster_experiment",
"dervo.snippets.loglevel_int_to_str",
"dervo.snippets.find_exp_path",
"dervo.experiment.prepare_cluster_experiment",
"docopt.docopt"
] | [((871, 932), 'vst.reasonable_logging_setup', 'vst.reasonable_logging_setup', (['loglevel_int', "args['--lformat']"], {}), "(loglevel_int, args['--lformat'])\n", (899, 932), False, 'import vst\n'), ((1543, 1558), 'docopt.docopt', 'docopt', (['__doc__'], {}), '(__doc__)\n', (1549, 1558), False, 'from docopt import docopt\n'), ((1087, 1116), 'dervo.snippets.find_exp_path', 'find_exp_path', (["args['<path>']"], {}), "(args['<path>'])\n", (1100, 1116), False, 'from dervo.snippets import docopt_loglevel, loglevel_int_to_str, find_exp_path\n'), ((1189, 1263), 'dervo.experiment.prepare_cluster_experiment', 'experiment.prepare_cluster_experiment', (['path', "args['<add_args>']", 'co_commit'], {}), "(path, args['<add_args>'], co_commit)\n", (1226, 1263), False, 'from dervo import experiment\n'), ((975, 1008), 'dervo.snippets.loglevel_int_to_str', 'loglevel_int_to_str', (['loglevel_int'], {}), '(loglevel_int)\n', (994, 1008), False, 'from dervo.snippets import docopt_loglevel, loglevel_int_to_str, find_exp_path\n'), ((1353, 1373), 'pathlib.Path', 'Path', (["args['<path>']"], {}), "(args['<path>'])\n", (1357, 1373), False, 'from pathlib import Path\n'), ((1382, 1456), 'dervo.experiment.run_cluster_experiment', 'experiment.run_cluster_experiment', (['workfolder_w_commit', "args['<add_args>']"], {}), "(workfolder_w_commit, args['<add_args>'])\n", (1415, 1456), False, 'from dervo import experiment\n')] |
from django.contrib.auth.decorators import login_required
from django.contrib.admin.views.decorators import staff_member_required
from django.shortcuts import render, redirect, get_object_or_404
from django.http import Http404
from catalog.models import Paper, Person, Dataset, Venue, Comment, Code
from catalog.models import ReadingGroup, ReadingGroupEntry
from catalog.models import Collection, CollectionEntry
from catalog.forms import (
PaperForm,
DatasetForm,
VenueForm,
CommentForm,
PaperImportForm,
)
from catalog.forms import (
SearchVenuesForm,
SearchPapersForm,
SearchPeopleForm,
SearchDatasetsForm,
SearchCodesForm,
PaperConnectionForm,
)
from django.urls import reverse
from django.http import HttpResponseRedirect
from neomodel import db
from datetime import date
from nltk.corpus import stopwords
from urllib.request import urlopen, Request
from urllib.error import HTTPError, URLError
from bs4 import BeautifulSoup
from django.contrib import messages
from catalog.views.views_codes import _code_find
import re
#
# Paper Views
#
def get_paper_authors(paper):
query = "MATCH (:Paper {title: {paper_title}})<--(a:Person) RETURN a"
results, meta = db.cypher_query(query, dict(paper_title=paper.title))
if len(results) > 0:
authors = [Person.inflate(row[0]) for row in results]
else:
authors = []
# pdb.set_trace()
authors = [
"{}. {}".format(author.first_name[0], author.last_name) for author in authors
]
return authors
def _get_paper_codes(paper):
query = "MATCH (:Paper {title: {paper_title}})<--(c:Code) RETURN c"
results, meta = db.cypher_query(query, dict(paper_title=paper.title))
if len(results) > 0:
codes = [Code.inflate(row[0]) for row in results]
else:
codes = []
# pdb.set_trace()
# authors = ['{}. {}'.format(author.first_name[0], author.last_name) for author in authors]
return codes
def get_paper_venue(paper):
query = "MATCH (:Paper {title: {paper_title}})--(v:Venue) RETURN v"
results, meta = db.cypher_query(query, dict(paper_title=paper.title))
if len(results) == 1: # there should only be one venue associated with a paper
venue = [Venue.inflate(row[0]) for row in results][0]
else:
venue = None
# pdb.set_trace()
if venue is not None:
return "{}, {}".format(venue.name, venue.publication_date)
else:
return ""
def papers(request):
# Retrieve the papers ordered by newest addition to DB first.
# limit to maximum 50 papers until we get pagination to work.
# However, even with pagination, we are going to want to limit
# the number of papers retrieved for speed, especially when the
# the DB grows large.
all_papers = Paper.nodes.order_by("-created")[:50]
# Retrieve all comments about this paper.
all_authors = [", ".join(get_paper_authors(paper)) for paper in all_papers]
all_venues = [get_paper_venue(paper) for paper in all_papers]
papers = list(zip(all_papers, all_authors, all_venues))
message = None
if request.method == "POST":
form = SearchPapersForm(request.POST)
print("Received POST request")
if form.is_valid():
english_stopwords = stopwords.words("english")
paper_title = form.cleaned_data["paper_title"].lower()
paper_title_tokens = [
w for w in paper_title.split(" ") if not w in english_stopwords
]
paper_query = (
"(?i).*" + "+.*".join("(" + w + ")" for w in paper_title_tokens) + "+.*"
)
query = (
"MATCH (p:Paper) WHERE p.title =~ { paper_query } RETURN p LIMIT 25"
)
print("Cypher query string {}".format(query))
results, meta = db.cypher_query(query, dict(paper_query=paper_query))
if len(results) > 0:
print("Found {} matching papers".format(len(results)))
papers = [Paper.inflate(row[0]) for row in results]
return render(request, "paper_results.html", {"papers": papers, "form": form, "message": ""})
else:
message = "No results found. Please try again!"
elif request.method == "GET":
print("Received GET request")
form = SearchPapersForm()
return render(
request,
"papers.html",
{
"papers": papers,
"papers_only": all_papers,
"num_papers": len(Paper.nodes.all()),
"form": form,
"message": message,
},
)
def paper_authors(request, id):
"""Displays the list of authors associated with this paper"""
relationship_ids = []
paper = _get_paper_by_id(id)
print("Retrieved paper with title {}".format(paper.title))
query = "MATCH (p:Paper)<-[r]-(a:Person) WHERE ID(p)={id} RETURN a, ID(r)"
results, meta = db.cypher_query(query, dict(id=id))
if len(results) > 0:
authors = [Person.inflate(row[0]) for row in results]
relationship_ids = [row[1] for row in results]
else:
authors = []
num_authors = len(authors)
print("paper author link ids {}".format(relationship_ids))
print("Found {} authors for paper with id {}".format(len(authors), id))
# for rid in relationship_ids:
delete_urls = [
reverse("paper_remove_author", kwargs={"id": id, "rid": rid})
for rid in relationship_ids
]
print("author remove urls")
print(delete_urls)
authors = zip(authors, delete_urls)
return render(request, "paper_authors.html", {"authors": authors, "paper": paper, "number_of_authors": num_authors})
# should limit access to admin users only!!
@staff_member_required
def paper_remove_author(request, id, rid):
print("Paper id {} and edge id {}".format(id, rid))
# Cypher query to delete edge of type authors with id equal to rid
query = "MATCH ()-[r:authors]-() WHERE ID(r)={id} DELETE r"
results, meta = db.cypher_query(query, dict(id=rid))
# TO DO
# What does this return? How can I make certain that the paper was deleted?
return HttpResponseRedirect(reverse("paper_authors", kwargs={"id": id}))
# should limit access to admin users only!!
@staff_member_required
def paper_delete(request, id):
print("WARNING: Deleting paper id {} and all related edges".format(id))
# Cypher query to delete the paper node
query = "MATCH (p:Paper) WHERE ID(p)={id} DETACH DELETE p"
results, meta = db.cypher_query(query, dict(id=id))
return HttpResponseRedirect(reverse("papers_index"))
def _get_paper_by_id(id):
# Retrieve the paper from the database
query = "MATCH (a) WHERE ID(a)={id} RETURN a"
results, meta = db.cypher_query(query, dict(id=id))
paper = None
if len(results) > 0:
all_papers = [Paper.inflate(row[0]) for row in results]
paper = all_papers[0]
return paper
def paper_detail(request, id):
# Retrieve the paper from the database
query = "MATCH (a) WHERE ID(a)={id} RETURN a"
results, meta = db.cypher_query(query, dict(id=id))
if len(results) > 0:
all_papers = [Paper.inflate(row[0]) for row in results]
paper = all_papers[0]
else: # go back to the paper index page
return render(
request,
"papers.html",
{"papers": Paper.nodes.all(), "num_papers": len(Paper.nodes.all())},
)
# Retrieve the paper's authors
authors = get_paper_authors(paper)
# authors is a list of strings so just concatenate the strings.
authors = ", ".join(authors)
# Retrieve all comments about this paper.
query = "MATCH (:Paper {title: {paper_title}})<--(c:Comment) RETURN c"
results, meta = db.cypher_query(query, dict(paper_title=paper.title))
if len(results) > 0:
comments = [Comment.inflate(row[0]) for row in results]
num_comments = len(comments)
else:
comments = []
num_comments = 0
# Retrieve the code repos that implement the algorithm(s) in this paper
codes = _get_paper_codes(paper)
# Retrieve venue where paper was published.
query = "MATCH (:Paper {title: {paper_title}})-->(v:Venue) RETURN v"
results, meta = db.cypher_query(query, dict(paper_title=paper.title))
if len(results) > 0:
venues = [Venue.inflate(row[0]) for row in results]
venue = venues[0]
else:
venue = None
request.session["last-viewed-paper"] = id
ego_network_json = _get_node_ego_network(paper.id, paper.title)
main_paper_id = paper.id
print("ego_network_json: {}".format(ego_network_json))
return render(
request,
"paper_detail.html",
{
"paper": paper,
"venue": venue,
"authors": authors,
"comments": comments,
"codes": codes,
"num_comments": num_comments,
"ego_network": ego_network_json,
"main_paper_id": main_paper_id,
},
)
def _get_node_ego_network(id, paper_title):
"""
Returns a json formatted string of the nodes ego network
:param id:
:return:
"""
# query for everything that points to the paper
query_all_in = "MATCH (s:Paper {title: {paper_title}}) <-[relationship_type]- (p) RETURN p, " \
"Type(relationship_type) "
# query for everything the paper points to
query_all_out = "MATCH (s:Paper {title: {paper_title}}) -[relationship_type]-> (p) RETURN p, " \
"Type(relationship_type) "
results_all_in, meta = db.cypher_query(query_all_in, dict(paper_title=paper_title))
results_all_out, meta = db.cypher_query(query_all_out, dict(paper_title=paper_title))
print("Results out are: ", results_all_out)
print("Results in are: ", results_all_in)
ego_json = "{{data : {{id: '{}', title: '{}', href: '{}', type: '{}', label: '{}'}} }}".format(
id, paper_title, reverse("paper_detail", kwargs={"id": id}), 'Paper', 'origin'
)
target_papers = []
target_people = []
target_venues = []
target_datasets = []
target_codes = []
# Assort nodes and store them in arrays accordingly
# 'out' refers to being from the paper to the object
if len(results_all_out) > 0:
for row in results_all_out:
new_rela = row[1].replace("_", " ")
for label in row[0].labels:
if label == 'Paper':
target_papers.append([Paper.inflate(row[0]), new_rela, 'out'])
if label == 'Person':
target_people.append([Person.inflate(row[0]), new_rela, 'out'])
if label == 'Venue':
target_venues.append([Venue.inflate(row[0]), new_rela, 'out'])
if label == 'Dataset':
target_datasets.append([Dataset.inflate(row[0]), new_rela, 'out'])
if label == 'Code':
target_codes.append([Code.inflate(row[0]), new_rela, 'out'])
if len(results_all_in) > 0:
for row in results_all_in:
new_rela = row[1].replace("_", " ")
for label in row[0].labels:
if label == 'Paper':
target_papers.append([Paper.inflate(row[0]), new_rela, 'in'])
if label == 'Person':
target_people.append([Person.inflate(row[0]), new_rela, 'in'])
if label == 'Venue':
target_venues.append([Venue.inflate(row[0]), new_rela, 'in'])
if label == 'Dataset':
target_datasets.append([Dataset.inflate(row[0]), new_rela, 'in'])
if label == 'Code':
target_codes.append([Code.inflate(row[0]), new_rela, 'in'])
print("length of connected papers: ", len(target_papers))
print("length of connected people: ", len(target_people))
print("length of connected venues: ", len(target_venues))
print("length of connected datasets: ", len(target_datasets))
print("length of connected codes: ", len(target_codes))
for tp in target_papers:
ego_json += ", {{data : {{id: '{}', title: '{}', href: '{}', type: '{}', label: '{}' }} }}".format(
tp[0].id, tp[0].title, reverse("paper_detail", kwargs={"id": tp[0].id}), 'Paper', tp[1]
)
# '-' distinguishes id e.g. 1-11 to 111 in relationships
if tp[2] == 'out':
ego_json += ",{{data: {{ id: '{}{}{}', label: '{}', source: '{}', target: '{}' }}}}".format(
id, '-', tp[0].id, tp[1], id, tp[0].id
)
if tp[2] == 'in':
ego_json += ",{{data: {{ id: '{}{}{}', label: '{}', source: '{}', target: '{}' }} }}".format(
tp[0].id, "-", id, tp[1], tp[0].id, id
)
for tpc in target_codes:
ego_json += ", {{data : {{id: '{}', title: '{}', href: '{}', type: '{}', label: '{}' }} }}".format(
tpc[0].id, 'Code', reverse("code_detail", kwargs={"id": tpc[0].id}), 'Code', tpc[1]
)
if tpc[2] == 'out':
ego_json += ",{{data: {{ id: '{}{}{}', label: '{}', source: '{}', target: '{}' }}}}".format(
id, '-', tpc[0].id, tpc[1], id, tpc[0].id
)
if tpc[2] == 'in':
ego_json += ",{{data: {{ id: '{}{}{}', label: '{}', source: '{}', target: '{}' }} }}".format(
tpc[0].id, "-", id, tpc[1], tpc[0].id, id
)
for tpv in target_venues:
ego_json += ", {{data : {{id: '{}', title: '{}', href: '{}', type: '{}', label: '{}' }} }}".format(
tpv[0].id, tpv[0].name, reverse("venue_detail", kwargs={"id": tpv[0].id}), 'Venue', tpv[1]
)
if tpv[2] == 'out':
ego_json += ",{{data: {{ id: '{}{}{}', label: '{}', source: '{}', target: '{}' }}}}".format(
id, '-', tpv[0].id, tpv[1], id, tpv[0].id
)
if tpv[2] == 'in':
ego_json += ",{{data: {{ id: '{}{}{}', label: '{}', source: '{}', target: '{}' }} }}".format(
tpv[0].id, "-", id, tpv[1], tpv[0].id, id
)
for tpd in target_datasets:
ego_json += ", {{data : {{id: '{}', title: '{}', href: '{}', type: '{}', label: '{}' }} }}".format(
tpd[0].id, tpd[0].name, reverse("dataset_detail", kwargs={"id": tpd[0].id}), 'Dataset', tpd[1]
)
if tpd[2] == 'out':
ego_json += ",{{data: {{ id: '{}{}{}', label: '{}', source: '{}', target: '{}' }}}}".format(
id, '-', tpd[0].id, tpd[1], id, tpd[0].id
)
if tpd[2] == 'in':
ego_json += ",{{data: {{ id: '{}{}{}', label: '{}', source: '{}', target: '{}' }} }}".format(
tpd[0].id, "-", id, tpd[1], tpd[0].id, id
)
for tpe in target_people:
middleName = ''
# reformat middle name from string "['mn1', 'mn2', ...]" to array ['mn1', 'mn2', ...]
if tpe[0].middle_name != None:
middleNames = tpe[0].middle_name[1:-1].split(', ')
# concatenate middle names to get 'mn1 mn2 ...'
for i in range(len(middleNames)):
middleName = middleName + " " + middleNames[i][1:-1]
ego_json += ", {{data : {{id: '{}', first_name: '{}', middle_name: '{}', last_name: '{}', href: '{}', " \
"type: '{}', " \
"label: '{}'}} }}".format(
tpe[0].id, tpe[0].first_name, middleName, tpe[0].last_name,
reverse("person_detail", kwargs={"id": tpe[0].id}), 'Person', tpe[1]
)
if tpe[2] == 'in':
ego_json += ", {{data : {{id: '{}{}{}', label: '{}', source: '{}', target: '{}' }} }}".format(
tpe[0].id, "-", id, tpe[1], tpe[0].id, id
)
if tpe[2] == 'out':
ego_json += ", {{data : {{id: '{}{}{}', label: '{}', source: '{}', target: '{}' }} }}".format(
id, "-", tpe[0].id, tpe[1], id, tpe[0].id
)
return "[" + ego_json + "]"
def paper_find(request):
message = None
if request.method == "POST":
form = SearchPapersForm(request.POST)
print("Received POST request")
if form.is_valid():
english_stopwords = stopwords.words("english")
paper_title = form.cleaned_data["paper_title"].lower()
paper_title_tokens = [
w for w in paper_title.split(" ") if not w in english_stopwords
]
paper_query = (
"(?i).*" + "+.*".join("(" + w + ")" for w in paper_title_tokens) + "+.*"
)
query = (
"MATCH (p:Paper) WHERE p.title =~ { paper_query } RETURN p LIMIT 25"
)
print("Cypher query string {}".format(query))
results, meta = db.cypher_query(query, dict(paper_query=paper_query))
if len(results) > 0:
print("Found {} matching papers".format(len(results)))
papers = [Paper.inflate(row[0]) for row in results]
return render(request, "papers_index.html", {"papers": papers, "form": form, "message": message})
else:
message = "No results found. Please try again!"
elif request.method == "GET":
print("Received GET request")
form = SearchPapersForm()
return render(request, "papers_index.html", {"form": form, "message": message})
@login_required
def paper_connect_venue(request, id):
if request.method == "POST":
form = SearchVenuesForm(request.POST)
if form.is_valid():
# search the db for the venue
# if venue found, then link with paper and go back to paper view
# if not, ask the user to create a new venue
english_stopwords = stopwords.words("english")
venue_name = form.cleaned_data["venue_name"].lower()
venue_publication_year = form.cleaned_data["venue_publication_year"]
# TO DO: should probably check that data is 4 digits...
venue_name_tokens = [
w for w in venue_name.split(" ") if not w in english_stopwords
]
venue_query = (
"(?i).*" + "+.*".join("(" + w + ")" for w in venue_name_tokens) + "+.*"
)
query = (
"MATCH (v:Venue) WHERE v.publication_date =~ '"
+ venue_publication_year[0:4]
+ ".*' AND v.name =~ { venue_query } RETURN v"
)
results, meta = db.cypher_query(
query,
dict(
venue_publication_year=venue_publication_year[0:4],
venue_query=venue_query,
),
)
if len(results) > 0:
venues = [Venue.inflate(row[0]) for row in results]
print("Found {} venues that match".format(len(venues)))
for v in venues:
print("\t{}".format(v))
if len(results) > 1:
# ask the user to select one of them
return render(
request,
"paper_connect_venue.html",
{
"form": form,
"venues": venues,
"message": "Found more than one matching venues. Please narrow your search",
},
)
else:
venue = venues[0]
print("Selected Venue: {}".format(venue))
# retrieve the paper
query = "MATCH (a) WHERE ID(a)={id} RETURN a"
results, meta = db.cypher_query(query, dict(id=id))
if len(results) > 0:
all_papers = [Paper.inflate(row[0]) for row in results]
paper = all_papers[0]
print("Found paper: {}".format(paper.title))
# check if the paper is connect with a venue; if yes, the remove link to
# venue before adding link to the new venue
query = "MATCH (p:Paper)-[r:was_published_at]->(v:Venue) where id(p)={id} return v"
results, meta = db.cypher_query(query, dict(id=id))
if len(results) > 0:
venues = [Venue.inflate(row[0]) for row in results]
for v in venues:
print("Disconnecting from: {}".format(v))
paper.was_published_at.disconnect(v)
paper.save()
else:
print("Could not find paper!")
# should not get here since we started from the actual paper...but what if we do end up here?
pass # Should raise an exception but for now just pass
# we have a venue and a paper, so connect them.
print("Citation link not found, adding it!")
messages.add_message(request, messages.INFO, "Link to venue added!")
paper.was_published_at.connect(venue)
return redirect("paper_detail", id=paper.id)
else:
# render new Venue form with the searched name as
message = "No matching venues found"
if request.method == "GET":
form = SearchVenuesForm()
message = None
return render(
request,
"paper_connect_venue.html",
{"form": form, "venues": None, "message": message},
)
@login_required
def paper_add_to_collection_selected(request, id, cid):
message = None
print("In paper_add_to_collection_selected")
query = "MATCH (a) WHERE ID(a)={id} RETURN a"
results, meta = db.cypher_query(query, dict(id=id))
if len(results) > 0:
all_papers = [Paper.inflate(row[0]) for row in results]
paper = all_papers[0]
else:
raise Http404
collection = get_object_or_404(Collection, pk=cid)
print("Found collection {}".format(collection))
if collection.owner == request.user:
# check if paper already exists in collection.
paper_in_collection = collection.papers.filter(paper_id=paper.id)
if paper_in_collection:
message = "Paper already exists in collection {}".format(collection.name)
else:
c_entry = CollectionEntry()
c_entry.collection = collection
c_entry.paper_id = id
c_entry.paper_title = paper.title
c_entry.save()
message = "Paper added to collection {}".format(collection.name)
else:
print("collection owner does not match user")
print(message)
messages.add_message(request, messages.INFO, message)
return HttpResponseRedirect(reverse("paper_detail", kwargs={"id": id,}))
@login_required
def paper_add_to_collection(request, id):
print("In paper_add_to_collection")
message = None
# Get all collections that this person has created
collections = Collection.objects.filter(owner=request.user)
print("User has {} collections.".format(len(collections)))
if len(collections) > 0:
collection_urls = [
reverse(
"paper_add_to_collection_selected",
kwargs={"id": id, "cid": collection.id},
)
for collection in collections
]
all_collections = zip(collections, collection_urls)
else:
all_collections = None
return render(
request,
"paper_add_to_collection.html",
{"collections": all_collections, "message": message},
)
@login_required
def paper_add_to_group_selected(request, id, gid):
query = "MATCH (a) WHERE ID(a)={id} RETURN a"
results, meta = db.cypher_query(query, dict(id=id))
if len(results) > 0:
all_papers = [Paper.inflate(row[0]) for row in results]
paper = all_papers[0]
else: # go back to the paper index page
raise Http404
group = get_object_or_404(ReadingGroup, pk=gid)
group_entry = ReadingGroupEntry()
group_entry.reading_group = group
group_entry.proposed_by = request.user
group_entry.paper_id = id
group_entry.paper_title = paper.title
group_entry.save()
return HttpResponseRedirect(reverse("paper_detail", kwargs={"id": id}))
@login_required
def paper_add_to_group(request, id):
message = None
# Get all reading groups that this person has created
# Note: This should be extended to allow user to propose
# papers to group they belong to as well.
# groups = ReadingGroup.objects.filter(owner=request.user.id)
groups = ReadingGroup.objects.all()
group_urls = [
reverse(
"paper_add_to_group_selected",
kwargs={"id": id, "gid": group.id},
)
for group in groups
]
all_groups = zip(groups, group_urls)
return render(
request,
"paper_add_to_group.html",
{"groups": all_groups, "message": message},
)
@login_required
def paper_connect_author_selected(request, id, aid):
query = "MATCH (p:Paper), (a:Person) WHERE ID(p)={id} AND ID(a)={aid} MERGE (a)-[r:authors]->(p) RETURN r"
results, meta = db.cypher_query(query, dict(id=id, aid=aid))
if len(results) > 0:
messages.add_message(request, messages.INFO, "Linked with author.")
else:
messages.add_message(request, messages.INFO, "Link to author failed!")
return HttpResponseRedirect(reverse("paper_detail", kwargs={"id": id}))
@login_required
def paper_connect_author(request, id):
if request.method == "POST":
form = SearchPeopleForm(request.POST)
if form.is_valid():
# search the db for the person
# if the person is found, then link with paper and go back to paper view
# if not, ask the user to create a new person
name = form.cleaned_data["person_name"]
people_found = _person_find(name)
if people_found is not None:
print("Found {} people that match".format(len(people_found)))
for person in people_found:
print(
"\t{} {} {}".format(
person.first_name, person.middle_name, person.last_name
)
)
if len(people_found) > 0:
# for rid in relationship_ids:
author_connect_urls = [
reverse(
"paper_connect_author_selected",
kwargs={"id": id, "aid": person.id},
)
for person in people_found
]
print("author remove urls")
print(author_connect_urls)
authors = zip(people_found, author_connect_urls)
# ask the user to select one of them
return render(
request,
"paper_connect_author.html",
{"form": form, "people": authors, "message": ""},
)
else:
message = "No matching people found"
if request.method == "GET":
form = SearchPeopleForm()
message = None
return render(
request,
"paper_connect_author.html",
{"form": form, "people": None, "message": message},
)
@login_required
def paper_connect_paper_selected(request, id, pid):
query = "MATCH (a) WHERE ID(a)={id} RETURN a"
results, meta = db.cypher_query(query, dict(id=id))
if len(results) > 0:
all_papers = [Paper.inflate(row[0]) for row in results]
paper_source = all_papers[
0
] # since we search by id only one paper should have been returned.
print("Found source paper: {}".format(paper_source.title))
query = "MATCH (a) WHERE ID(a)={id} RETURN a"
results, meta = db.cypher_query(query, dict(id=pid))
if len(results) > 0:
all_papers = [Paper.inflate(row[0]) for row in results]
paper_target = all_papers[
0
] # since we search by id only one paper should have been returned.
print("Found target paper: {}".format(paper_target.title))
# check if the papers are already connected with a cites link; if yes, then
# do nothing. Otherwise, add the link.
query = "MATCH (q:Paper)<-[r]-(p:Paper) where id(p)={source_id} and id(q)={target_id} return p"
results, meta = db.cypher_query(
query,
dict(source_id=id, target_id=pid),
)
if len(results) == 0:
link_type = request.session["link_type"]
# papers are not linked so add the edge
print("Connection link not found, adding it!")
if link_type == 'cites':
paper_source.cites.connect(paper_target)
elif link_type == 'uses':
paper_source.uses.connect(paper_target)
elif link_type == 'extends':
paper_source.extends.connect(paper_target)
messages.add_message(request, messages.INFO, "Connection Added!")
else:
print("Connection link found not adding it!")
messages.add_message(
request, messages.INFO, "Papers are already linked!"
)
else:
print("Could not find paper!")
messages.add_message(
request, messages.INFO, "Could not find paper!"
)
return redirect("paper_detail", id=id)
@login_required
def paper_connect_paper(request, id):
"""
View function for connecting a paper with another paper.
:param request:
:param id:
:return:
"""
message = None
if request.method == "POST":
form = PaperConnectionForm(request.POST)
if form.is_valid():
# search the db for the person
# if the person is found, then link with paper and go back to paper view
# if not, ask the user to create a new person
paper_title_query = form.cleaned_data["paper_title"]
papers_found = _find_paper(paper_title_query)
paper_connected = form.cleaned_data["paper_connection"]
if len(papers_found) > 0: # found more than one matching papers
print("Found {} papers that match".format(len(papers_found)))
for paper in papers_found:
print("\t{}".format(paper.title))
# for rid in relationship_ids:
paper_connect_urls = [
reverse(
"paper_connect_paper_selected",
kwargs={"id": id, "pid": paper.id},
)
for paper in papers_found
]
print("paper connect urls")
print(paper_connect_urls)
papers = zip(papers_found, paper_connect_urls)
request.session["link_type"] = paper_connected
# ask the user to select one of them
return render(
request,
"paper_connect_paper.html",
{"form": form, "papers": papers, "message": ""},
)
# if len(papers_found) > 1:
# return render(
# request,
# "paper_connect_paper.html",
# {
# "form": form,
# "papers": papers_found,
# "message": "Found more than one matching papers. Please narrow your search",
# },
# )
# else:
# paper_target = papers_found[0] # one person found
# print("Selected paper: {}".format(paper.title))
# retrieve the paper
# query = "MATCH (a) WHERE ID(a)={id} RETURN a"
# results, meta = db.cypher_query(query, dict(id=id))
# if len(results) > 0:
# all_papers = [Paper.inflate(row[0]) for row in results]
# paper_source = all_papers[
# 0
# ] # since we search by id only one paper should have been returned.
# print("Found paper: {}".format(paper_source.title))
# # check if the papers are already connected with a cites link; if yes, then
# # do nothing. Otherwise, add the link.
# query = "MATCH (q:Paper)<-[r]-(p:Paper) where id(p)={source_id} and id(q)={target_id} return p"
# results, meta = db.cypher_query(
# query,
# dict(source_id=paper_source.id, target_id=paper_target.id),
# )
# if len(results) == 0:
# # papers are not linked so add the edge
# print("Connection link not found, adding it!")
# if paper_connected == 'cites':
# paper_source.cites.connect(paper_target)
# elif paper_connected == 'uses':
# paper_source.uses.connect(paper_target)
# elif paper_connected == 'extends':
# paper_source.extends.connect(paper_target)
# messages.add_message(request, messages.INFO, "Connection Added!")
# else:
# print("Connection link found not adding it!")
# messages.add_message(
# request, messages.INFO, "Connection Already Exists!"
# )
# else:
# print("Could not find paper!")
# messages.add_message(
# request, messages.INFO, "Could not find paper!"
# )
# return redirect("paper_detail", id=id)
else:
message = "No matching papers found"
if request.method == "GET":
form = PaperConnectionForm()
return render(
request,
"paper_connect_paper.html",
{"form": form, "papers": None, "message": message},
)
@login_required
def paper_connect_dataset(request, id):
"""
View function for connecting a paper with a dataset.
:param request:
:param id:
:return:
"""
if request.method == "POST":
form = SearchDatasetsForm(request.POST)
if form.is_valid():
# search the db for the dataset
# if the dataset is found, then link with paper and go back to paper view
# if not, ask the user to create a new dataset
dataset_query_name = form.cleaned_data["name"]
dataset_query_keywords = form.cleaned_data["keywords"]
datasets_found = _dataset_find(dataset_query_name, dataset_query_keywords)
if len(datasets_found) > 0: # found more than one matching dataset
print("Found {} datasets that match".format(len(datasets_found)))
for dataset in datasets_found:
print("\t{}".format(dataset.name))
if len(datasets_found) > 1:
return render(
request,
"paper_connect_dataset.html",
{
"form": form,
"datasets": datasets_found,
"message": "Found more than one matching datasets. Please narrow your search",
},
)
else:
dataset_target = datasets_found[0] # one person found
print("Selected dataset: {}".format(dataset_target.name))
# retrieve the paper
query = "MATCH (a) WHERE ID(a)={id} RETURN a"
results, meta = db.cypher_query(query, dict(id=id))
if len(results) > 0:
all_papers = [Paper.inflate(row[0]) for row in results]
paper_source = all_papers[
0
] # since we search by id only one paper should have been returned.
print("Found paper: {}".format(paper_source.title))
# check if the papers are already connected with a cites link; if yes, then
# do nothing. Otherwise, add the link.
query = "MATCH (d:Dataset)<-[r:evaluates_on]-(p:Paper) where id(p)={id} and id(d)={dataset_id} return p"
results, meta = db.cypher_query(
query, dict(id=id, dataset_id=dataset_target.id)
)
if len(results) == 0:
# dataset is not linked with paper so add the edge
paper_source.evaluates_on.connect(dataset_target)
messages.add_message(
request, messages.INFO, "Link to dataset added!"
)
else:
messages.add_message(
request, messages.INFO, "Link to dataset already exists!"
)
else:
print("Could not find paper!")
return redirect("paper_detail", id=id)
else:
message = "No matching datasets found"
if request.method == "GET":
form = SearchDatasetsForm()
message = None
return render(
request,
"paper_connect_dataset.html",
{"form": form, "datasets": None, "message": message},
)
@login_required
def paper_connect_code_selected(request, id, cid):
query = "MATCH (p:Paper), (c:Code) WHERE ID(p)={id} AND ID(c)={cid} MERGE (c)-[r:implements]->(p) RETURN r"
results, meta = db.cypher_query(query, dict(id=id, cid=cid))
if len(results) > 0:
messages.add_message(request, messages.INFO, "Linked with code repo.")
else:
messages.add_message(request, messages.INFO, "Link to code repo failed!")
return HttpResponseRedirect(reverse("paper_detail", kwargs={"id": id}))
@login_required
def paper_connect_code(request, id):
"""
View function for connecting a paper with a dataset.
:param request:
:param id:
:return:
"""
message = ""
if request.method == "POST":
form = SearchCodesForm(request.POST)
if form.is_valid():
# search the db for the person
# if the person is found, then link with paper and go back to paper view
# if not, ask the user to create a new person
keywords = form.cleaned_data["keywords"]
codes_found = _code_find(keywords)
if len(codes_found) > 0:
print("Found {} codes that match".format(len(codes_found)))
for code in codes_found:
print("\t{} {}".format(code.website, code.keywords))
if len(codes_found) > 0:
# for rid in relationship_ids:
codes_connect_urls = [
reverse(
"paper_connect_code_selected",
kwargs={"id": id, "cid": code.id},
)
for code in codes_found
]
print(codes_connect_urls)
codes = zip(codes_found, codes_connect_urls)
# ask the user to select one of them
return render(
request,
"paper_connect_code.html",
{"form": form, "codes": codes, "message": ""},
)
else:
message = "No matching codes found"
if request.method == "GET":
form = SearchCodesForm()
message = None
return render(
request,
"paper_connect_code.html",
{"form": form, "codes": None, "message": message},
)
@login_required
def paper_update(request, id):
# retrieve paper by ID
# https://github.com/neo4j-contrib/neomodel/issues/199
query = "MATCH (a) WHERE ID(a)={id} RETURN a"
results, meta = db.cypher_query(query, dict(id=id))
if len(results) > 0:
all_papers = [Paper.inflate(row[0]) for row in results]
paper_inst = all_papers[0]
else:
paper_inst = Paper()
# if this is POST request then process the Form data
if request.method == "POST":
form = PaperForm(request.POST)
if form.is_valid():
paper_inst.title = form.cleaned_data["title"]
paper_inst.abstract = form.cleaned_data["abstract"]
paper_inst.keywords = form.cleaned_data["keywords"]
paper_inst.download_link = form.cleaned_data["download_link"]
paper_inst.save()
return HttpResponseRedirect(reverse("papers_index"))
# GET request
else:
query = "MATCH (a) WHERE ID(a)={id} RETURN a"
results, meta = db.cypher_query(query, dict(id=id))
if len(results) > 0:
all_papers = [Paper.inflate(row[0]) for row in results]
paper_inst = all_papers[0]
else:
paper_inst = Paper()
# paper_inst = Paper()
form = PaperForm(
initial={
"title": paper_inst.title,
"abstract": paper_inst.abstract,
"keywords": paper_inst.keywords,
"download_link": paper_inst.download_link,
}
)
return render(request, "paper_update.html", {"form": form, "paper": paper_inst})
def _find_paper(query_string):
"""
Helper method to query the DB for a paper based on its title.
:param query_string: The query string, e.g., title of paper to search for
:return: <list> List of papers that match the query or empty list if none match.
"""
papers_found = []
english_stopwords = stopwords.words("english")
paper_title = query_string.lower()
paper_title_tokens = [
w for w in paper_title.split(" ") if not w in english_stopwords
]
paper_query = (
"(?i).*" + "+.*".join("(" + w + ")" for w in paper_title_tokens) + "+.*"
)
query = "MATCH (p:Paper) WHERE p.title =~ { paper_query } RETURN p LIMIT 25"
print("Cypher query string {}".format(query))
results, meta = db.cypher_query(query, dict(paper_query=paper_query))
if len(results) > 0:
papers_found = [Paper.inflate(row[0]) for row in results]
return papers_found
def _add_author(author, paper=None):
"""
Adds author to the DB if author does not already exist and links to paper
as author if paper is not None
:param author:
:param paper:
"""
link_with_paper = False
p = None
people_found = _person_find(author, exact_match=True)
author_name = author.strip().split(" ")
if people_found is None: # not in DB
print("Author {} not in DB".format(author))
p = Person()
p.first_name = author_name[0]
if len(author_name) > 2: # has middle name(s)
p.middle_name = author_name[1:-1]
else:
p.middle_name = None
p.last_name = author_name[-1]
#print("**** Person {} ***".format(p))
p.save() # save to DB
link_with_paper = True
elif len(people_found) == 1:
# Exactly one person found. Check if name is an exact match.
p = people_found[0]
# NOTE: The problem with this simple check is that if two people have
# the same name then the wrong person will be linked to the paper.
if p.first_name == author_name[0] and p.last_name == author_name[-1]:
if len(author_name) > 2:
if p.middle_name == author_name[1:-1]:
link_with_paper = True
else:
link_with_paper = True
else:
print("Person with similar but not exactly the same name is already in DB.")
if link_with_paper and paper is not None:
print("Adding authors link to paper {}".format(paper.title[:50]))
# link author with paper
p.authors.connect(paper)
@login_required
def paper_create(request):
user = request.user
print("In paper_create() view.")
message = ""
if request.method == "POST":
print(" POST")
paper = Paper()
paper.created_by = user.id
form = PaperForm(instance=paper, data=request.POST)
if form.is_valid():
# Check if the paper already exists in DB
matching_papers = _find_paper(form.cleaned_data["title"])
if len(matching_papers) > 0: # paper in DB already
message = "Paper already exists in Gnosis!"
return render(
request,
"paper_results.html",
{"papers": matching_papers, "message": message},
)
else: # the paper is not in DB yet.
form.save() # store
# Now, add the authors and link each author to the paper with an "authors"
# type edge.
if request.session.get("from_external", False):
paper_authors = request.session["external_authors"]
for paper_author in reversed(paper_authors.split(",")):
print("Adding author {}".format(paper_author))
_add_author(paper_author, paper)
request.session["from_external"] = False # reset
# go back to paper index page.
# Should this redirect to the page of the new paper just added?
return HttpResponseRedirect(reverse("papers_index"))
else: # GET
print(" GET")
# check if this is a redirect from paper_create_from_url
# if so, then pre-populate the form with the data from external source,
# otherwise start with an empty form.
if request.session.get("from_external", False) is True:
title = request.session["external_title"]
abstract = request.session["external_abstract"]
url = request.session["external_url"]
download_link = request.session["download_link"]
form = PaperForm(
initial={"title": title, "abstract": abstract, "download_link": download_link, "source_link": url}
)
else:
form = PaperForm()
return render(request, "paper_form.html", {"form": form, "message": message})
# the two functions below are used to abstract author names from IEEE
# to abstract the author name from a format of "name":"author_name"
def find_author_from_IEEE_author_info(text):
i = text.find('''"name":''')
start = i + 8
i = i + 8
while text[i] != '''"''':
i = i + 1
author = text[start:i]
return author
# to find the author names as a list
def find_author_list_from_IEEE(bs4obj):
text = bs4obj.get_text()
# to find the string which stores information of authors, which is stored in a
# format of "authors":[{author 1 info},{author 2 info}]
i = text.find('''"authors":[''')
if i == -1:
return []
while text[i] != '[':
i = i + 1
i = i + 1
array_count = 1
bracket_count = 0
bracket_start = 0
author_list = []
while array_count != 0:
if text[i] == '{':
if bracket_count == 0:
bracket_start = i
bracket_count = bracket_count + 1
if text[i] == '}':
bracket_count = bracket_count - 1
if bracket_count == 0:
author_list.append(find_author_from_IEEE_author_info(text[bracket_start:i]))
if text[i] == ']':
array_count = array_count - 1
if text[i] == '[':
array_count = array_count + 1
i = i + 1
return author_list
def get_authors(bs4obj, source_website):
"""
Extract authors from the source website
:param bs4obj, source_website;
:return: None or a string with comma separated author names from first to last name
"""
if source_website == "arxiv":
authorList = bs4obj.findAll("div", {"class": "authors"})
if authorList:
if len(authorList) > 1:
# there should be just one but let's just take the first one
authorList = authorList[0]
# for author in authorList:
# print("type of author {}".format(type(author)))
author_str = authorList[0].get_text()
if author_str.startswith("Authors:"):
author_str = author_str[8:]
return author_str
elif source_website == 'nips':
# authors are found to be list objects , so needs to join them to get the author string
authorList = bs4obj.findAll("li", {"class": "author"})
if authorList:
authorList = [author.text for author in authorList]
author_str = ','.join(authorList)
return author_str
elif source_website == "jmlr":
# in JMLR authors are found in the html tag "i"
authorList = bs4obj.findAll("i")
if authorList:
if len(authorList) >= 1:
author_str = authorList[0].text
return author_str
elif source_website == "ieee":
authorList = find_author_list_from_IEEE(bs4obj)
if authorList:
authorList = [author for author in authorList]
author_str = ','.join(authorList)
return author_str
elif source_website == "acm":
author_str = bs4obj.find("meta", {"name": "citation_authors"})
author_str = str(author_str)
# print("get_authors() downloaded author_str: {}".format(author_str))
start = author_str.find('"')
end = author_str.find('"', start + 1)
author_str = author_str[start + 1:end]
author_str_rev = ""
for n in author_str.split(";"):
if len(author_str_rev) == 0:
author_str_rev = ", ".join(n.split(",")[::-1])
else:
author_str_rev = author_str_rev + "; " + ",".join(n.split(", ")[::-1])
#print("get_authors() author_str_rev: {}".format(author_str_rev))
author_str = author_str_rev.replace(",", "")
author_str = author_str.replace("; ", ",")
#print("get_authors() cleaned author_str: {}".format(author_str))
# names are last, first so reverse to first, last
return author_str
# if source website is not supported or the autherlist is none , return none
return None
def get_title(bs4obj, source_website):
"""
Extract paper title from the source web.
:param bs4obj:
:return:
"""
if source_website == "arxiv":
titleList = bs4obj.findAll("h1", {"class": "title"})
elif source_website == 'nips':
titleList = bs4obj.findAll("title")
elif source_website == "jmlr":
titleList = bs4obj.findAll("h2")
elif source_website == "ieee":
title = bs4obj.find("title").get_text()
i = title.find("- IEEE")
if i != -1:
title = title[0:i]
return title
elif source_website == "acm":
titleList = bs4obj.find("meta", {"name": "citation_title"})
title = str(titleList)
start = title.find('"')
end = title.find('"', start + 1)
title = title[start + 1:end]
if title == "Non":
return None
return title
else:
titleList = []
# check the validity of the abstracted titlelist
if titleList:
if len(titleList) == 0:
return None
else:
if len(titleList) > 1:
print("WARNING: Found more than one title. Returning the first one.")
# return " ".join(titleList[0].get_text().split()[1:])
title_text = titleList[0].get_text()
if title_text.startswith("Title:"):
return title_text[6:]
else:
return title_text
return None
# this function is used to find the abstract for a paper from IEEE
def get_abstract_from_IEEE(bs4obj):
"""
Extract paper abstract from the source website.
:param bs4obj:
:return: abstract
"""
text = bs4obj.get_text()
i = text.find('''"abstract":"''')
start = None
count = 0
abstract = None
if text[i + 12:i + 16] == "true":
i = text.find('''"abstract":"''', i + 16)
start = i + 12
i = start
count = 1
while count != 0:
if text[i] == '''"''':
if text[i + 1] == "," and text[i + 2] == '''"''':
count = 0
i += 1
abstract = text[start:i]
return abstract
# this function is used to find the abstract for a paper from IEEE
def get_abstract_from_ACM(bs4obj):
"""
Extract paper abstract from the source website.
:param bs4obj:
:return: abstract
"""
abstract = bs4obj.find("div", {"style": "display:inline"})
if abstract:
abstract = abstract.get_text()
else:
abstract = bs4obj.find("meta", {"name": "citation_abstract_html_url"})
abstract_url = str(abstract)
start = abstract_url.find('"')
end = abstract_url.find('"', start + 1)
abstract_url = abstract_url[start + 1:end]
if abstract_url == "Non":
return None
abstract_url += "&preflayout=flat"
headers = {"User-Agent": "Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11"}
req = Request(abstract_url, headers=headers)
html = urlopen(req)
bs4obj1 = BeautifulSoup(html,features="html.parser")
abstract = bs4obj1.findAll("div", {"style": "display:inline"})
abstract = abstract[0]
if abstract:
abstract = abstract.get_text()
return abstract
def get_abstract(bs4obj, source_website):
"""
Extract paper abstract from the source website.
:param bs4obj, source_website:
:return:
"""
if source_website == "arxiv":
abstract = bs4obj.find("blockquote", {"class": "abstract"})
if abstract is not None:
abstract = " ".join(abstract.get_text().split(" ")[1:])
elif source_website == 'nips':
abstract = bs4obj.find("p", {"class": "abstract"})
if abstract is not None:
abstract = abstract.get_text()
elif source_website == "jmlr":
abstract = bs4obj.find("p", {"class": "abstract"})
if abstract is not None:
abstract = abstract.get_text()
else:
# for some papers from JMLR , the abstract is stored without a tag,so this will find the abstract
abstract = bs4obj.find("h3")
if abstract is not None:
abstract = abstract.next_sibling
elif source_website == "ieee":
abstract = get_abstract_from_IEEE(bs4obj)
elif source_website == "acm":
abstract = get_abstract_from_ACM(bs4obj)
else:
abstract = None
# want to remove all the leading and ending white space and line breakers in the abstract
if abstract is not None:
abstract = abstract.strip()
if source_website != "arxiv":
abstract = abstract.replace('\r', '').replace('\n', '')
else:
abstract = abstract.replace('\n', ' ')
return abstract
def get_venue(bs4obj):
"""
Extract publication venue from arXiv.org paper page.
:param bs4obj:
:return:
"""
venue = bs4obj.find("td", {"class": "tablecell comments mathjax"})
if venue is not None:
venue = venue.get_text().split(";")[0]
return venue
# this function is used to find the download_link for a paper from IEEE
def get_ddl_from_IEEE(bs4obj):
text = bs4obj.get_text()
# the ddl link is stored in a format of "pdfUrl":"download_link"
i = text.find('''"pdfUrl":"''')
start = i + 10
i = start
count = 1
while count != 0:
if text[i] == '''"''':
count = 0
i += 1
ddl = text[start:i - 1]
ddl = "https://ieeexplore.ieee.org" + ddl
return ddl
def get_download_link(bs4obj, source_website, url):
"""
Extract download link from paper page1
:param bs4obj:
return: download link of paper
"""
if url.endswith("/"):
url = url[:-1]
if source_website == "arxiv":
download_link = url.replace("/abs/", "/pdf/", 1) + ".pdf"
elif source_website == "nips":
download_link = url + ".pdf"
elif source_website == "jmlr":
download_link = bs4obj.find(href=re.compile("pdf"))['href']
print(download_link)
if download_link.startswith("/papers/"):
download_link = "http://www.jmlr.org" + download_link
elif source_website == "ieee":
download_link = get_ddl_from_IEEE(bs4obj)
elif source_website == "acm":
download_link = bs4obj.find("meta", {"name": "citation_pdf_url"})
download_link = str(download_link)
start = download_link.find('"')
end = download_link.find('"', start + 1)
download_link = download_link[start + 1:end]
return download_link
else:
download_link = None
return download_link
def check_valid_paper_type_ieee(bs4obj):
text = bs4obj.get_text()
# the paper type is stored in a format of "xploreDocumentType":"paper_type"
i = text.find('''"xploreDocumentType":"''')
start = i + 22
i = start
count = 1
while count != 0:
if text[i] == '''"''':
count = 0
i += 1
paper_type = text[start:i - 1]
print(paper_type)
if paper_type == "Journals & Magazine":
return True
return False
def get_paper_info(url, source_website):
"""
Extract paper information, title, abstract, and authors, from source website
paper page.
:param url, source_website:
:return:
"""
try:
# html = urlopen("http://pythonscraping.com/pages/page1.html")
url_copy = url
if source_website == "acm":
headers = {"User-Agent": "Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11"}
url = Request(url, headers=headers)
html = urlopen(url)
except HTTPError as e:
print(e)
except URLError as e:
print(e)
print("The server could not be found.")
else:
bs4obj = BeautifulSoup(html,features="html.parser")
if source_website == "ieee":
if check_valid_paper_type_ieee(bs4obj) == False:
return None, None, None, None
if source_website == "acm":
url = ""
if bs4obj.find("a", {"title": "Buy this Book"}) or bs4obj.find("a", {"ACM Magazines"}) \
or bs4obj.find_all("meta", {"name": "citation_conference_title"}):
return None, None, None, None
# Now, we can access individual element in the page
authors = get_authors(bs4obj, source_website)
title = get_title(bs4obj, source_website)
abstract = get_abstract(bs4obj, source_website)
download_link = ""
if authors and title and abstract:
download_link = get_download_link(bs4obj, source_website, url)
if download_link == "Non":
download_link = url_copy
# venue = get_venue(bs4obj)
return title, authors, abstract, download_link
return None, None, None, None
@login_required
def paper_create_from_url(request):
user = request.user
if request.method == "POST":
# create the paper from the extracted data and send to
# paper_form.html asking the user to verify
print("{}".format(request.POST["url"]))
# get the data from arxiv
url = request.POST["url"]
# check if a particular url starts with http , it is important as JMLR does not support https
if url.startswith("http://"):
url = url[7:]
# check if url includes https, and if not add it
if not url.startswith("https://"):
url = "https://" + url
# check whether the url is from a supported website
# from arXiv.org
if url.startswith("https://arxiv.org"):
source_website = "arxiv"
print("source from arXiv")
# from NeurlIPS
elif url.startswith("https://papers.nips.cc/paper"):
source_website = "nips"
print("source from nips")
# for urls of JMLR, they do not support https , so we need to change it to http instead
elif url.startswith("https://www.jmlr.org/papers"):
url = "http://" + url[8:]
source_website = "jmlr"
print("source from jmlr")
# from IEEE
elif url.startswith("https://ieeexplore.ieee.org/document/"):
source_website = "ieee"
print("source from ieee")
# from ACM
elif url.startswith("https://dl.acm.org/"):
source_website = "acm"
print("source from acm")
# return error message if the website is not supported
else:
form = PaperImportForm()
return render(
request,
"paper_form.html",
{"form": form, "message": "Source website is not supported"},
)
# retrieve paper info. If the information cannot be retrieved from remote
# server, then we will return an error message and redirect to paper_form.html.
title, authors, abstract, download_link = get_paper_info(url, source_website)
if title is None or authors is None or abstract is None:
form = PaperImportForm()
return render(
request,
"paper_form.html",
{"form": form, "message": "Invalid source, please try again."},
)
request.session["from_external"] = True
request.session["external_title"] = title
request.session["external_abstract"] = abstract
request.session["external_url"] = url
request.session["download_link"] = download_link
request.session[
"external_authors"
] = authors # comma separate list of author names, first to last name
print("Authors: {}".format(authors))
return HttpResponseRedirect(reverse("paper_create"))
else: # GET
request.session["from_external"] = False
form = PaperImportForm()
return render(request, "paper_form.html", {"form": form})
def _person_find(person_name, exact_match=False):
"""
Searches the DB for a person whose name matches the given name
:param person_name:
:return:
"""
person_name = person_name.lower()
person_name_tokens = [w for w in person_name.split()]
if exact_match:
if len(person_name_tokens) > 2:
query = "MATCH (p:Person) WHERE LOWER(p.last_name) IN { person_tokens } AND LOWER(p.first_name) IN { person_tokens } AND LOWER(p.middle_name) IN { person_tokens } RETURN p LIMIT 20"
else:
query = "MATCH (p:Person) WHERE LOWER(p.last_name) IN { person_tokens } AND LOWER(p.first_name) IN { person_tokens } RETURN p LIMIT 20"
else:
query = "MATCH (p:Person) WHERE LOWER(p.last_name) IN { person_tokens } OR LOWER(p.first_name) IN { person_tokens } OR LOWER(p.middle_name) IN { person_tokens } RETURN p LIMIT 20"
results, meta = db.cypher_query(query, dict(person_tokens=person_name_tokens))
if len(results) > 0:
print("Found {} matching people".format(len(results)))
people = [Person.inflate(row[0]) for row in results]
return people
else:
return None
#
# Dataset Views
#
def datasets(request):
all_datasets = Dataset.nodes.order_by("-publication_date")[:50]
message = None
if request.method == "POST":
form = SearchDatasetsForm(request.POST)
print("Received POST request")
if form.is_valid():
dataset_name = form.cleaned_data["name"].lower()
dataset_keywords = form.cleaned_data[
"keywords"
].lower() # comma separated list
datasets = _dataset_find(dataset_name, dataset_keywords)
if len(datasets) > 0:
return render(
request,
"datasets.html",
{"datasets": datasets, "form": form, "message": ""},
)
else:
message = "No results found. Please try again!"
elif request.method == "GET":
print("Received GET request")
form = SearchDatasetsForm()
return render(
request,
"datasets.html",
{"datasets": all_datasets, "form": form, "message": message},
)
def dataset_detail(request, id):
# Retrieve the paper from the database
query = "MATCH (a) WHERE ID(a)={id} RETURN a"
results, meta = db.cypher_query(query, dict(id=id))
if len(results) > 0:
# There should be only one results because ID should be unique. Here we check that at
# least one result has been returned and take the first result as the correct match.
# Now, it should not happen that len(results) > 1 since IDs are meant to be unique.
# For the MVP we are going to ignore the latter case and just continue but ultimately,
# we should be checking for > 1 and failing gracefully.
all_datasets = [Dataset.inflate(row[0]) for row in results]
dataset = all_datasets[0]
else: # go back to the paper index page
return render(
request,
"datasets.html",
{"datasets": Dataset.nodes.all(), "num_datasets": len(Dataset.nodes.all())},
)
#
# TO DO: Retrieve and list all papers that evaluate on this dataset.
#
request.session["last-viewed-dataset"] = id
return render(request, "dataset_detail.html", {"dataset": dataset})
def _dataset_find(name, keywords):
"""
Helper method for searching Neo4J DB for a dataset.
:param name: Dataset name search query
:param keywords: Dataset keywords search query
:return:
"""
dataset_name_tokens = [w for w in name.split()]
dataset_keywords = [w for w in keywords.split()]
datasets = []
if len(dataset_keywords) > 0 and len(dataset_name_tokens) > 0:
# Search using both the name and the keywords
keyword_query = (
"(?i).*" + "+.*".join("(" + w + ")" for w in dataset_keywords) + "+.*"
)
name_query = (
"(?i).*" + "+.*".join("(" + w + ")" for w in dataset_name_tokens) + "+.*"
)
query = "MATCH (d:Dataset) WHERE d.name =~ { name_query } AND d.keywords =~ { keyword_query} RETURN d LIMIT 25"
results, meta = db.cypher_query(
query, dict(name_query=name_query, keyword_query=keyword_query)
)
if len(results) > 0:
datasets = [Dataset.inflate(row[0]) for row in results]
return datasets
else:
if len(dataset_keywords) > 0:
# only keywords given
dataset_query = (
"(?i).*" + "+.*".join("(" + w + ")" for w in dataset_keywords) + "+.*"
)
query = "MATCH (d:Dataset) WHERE d.keywords =~ { dataset_query } RETURN d LIMIT 25"
else:
# only name or nothing (will still return all datasets if name and
# keywords fields are left empty and sumbit button is pressed.
dataset_query = (
"(?i).*"
+ "+.*".join("(" + w + ")" for w in dataset_name_tokens)
+ "+.*"
)
query = (
"MATCH (d:Dataset) WHERE d.name =~ { dataset_query } RETURN d LIMIT 25"
)
# results, meta = db.cypher_query(query, dict(dataset_query=dataset_query))
results, meta = db.cypher_query(query, dict(dataset_query=dataset_query))
if len(results) > 0:
datasets = [Dataset.inflate(row[0]) for row in results]
return datasets
return datasets # empty list
def dataset_find(request):
"""
Searching for a dataset in the DB.
:param request:
:return:
"""
message = None
if request.method == "POST":
form = SearchDatasetsForm(request.POST)
print("Received POST request")
if form.is_valid():
dataset_name = form.cleaned_data["name"].lower()
dataset_keywords = form.cleaned_data[
"keywords"
].lower() # comma separated list
datasets = _dataset_find(dataset_name, dataset_keywords)
if len(datasets) > 0:
return render(request, "datasets.html", {"datasets": datasets})
else:
message = "No results found. Please try again!"
elif request.method == "GET":
print("Received GET request")
form = SearchDatasetsForm()
return render(request, "dataset_find.html", {"form": form, "message": message})
@login_required
def dataset_create(request):
user = request.user
if request.method == "POST":
dataset = Dataset()
dataset.created_by = user.id
form = DatasetForm(instance=dataset, data=request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse("datasets_index"))
else: # GET
form = DatasetForm()
return render(request, "dataset_form.html", {"form": form})
# should limit access to admin users only!!
@staff_member_required
def dataset_delete(request, id):
print("WARNING: Deleting dataset id {} and all related edges".format(id))
# Cypher query to delete the paper node
query = "MATCH (d:Dataset) WHERE ID(d)={id} DETACH DELETE d"
results, meta = db.cypher_query(query, dict(id=id))
return HttpResponseRedirect(reverse("datasets_index"))
@login_required
def dataset_update(request, id):
# retrieve paper by ID
# https://github.com/neo4j-contrib/neomodel/issues/199
query = "MATCH (a) WHERE ID(a)={id} RETURN a"
results, meta = db.cypher_query(query, dict(id=id))
if len(results) > 0:
datasets = [Dataset.inflate(row[0]) for row in results]
dataset = datasets[0]
else:
dataset = Dataset()
# if this is POST request then process the Form data
if request.method == "POST":
form = DatasetForm(request.POST)
if form.is_valid():
dataset.name = form.cleaned_data["name"]
dataset.keywords = form.cleaned_data["keywords"]
dataset.description = form.cleaned_data["description"]
dataset.publication_date = form.cleaned_data["publication_date"]
dataset.source_type = form.cleaned_data["source_type"]
dataset.website = form.cleaned_data["website"]
dataset.save()
return HttpResponseRedirect(reverse("datasets_index"))
# GET request
else:
query = "MATCH (a) WHERE ID(a)={id} RETURN a"
results, meta = db.cypher_query(query, dict(id=id))
if len(results) > 0:
datasets = [Dataset.inflate(row[0]) for row in results]
dataset = datasets[0]
else:
dataset = Dataset()
form = DatasetForm(
initial={
"name": dataset.name,
"keywords": dataset.keywords,
"description": dataset.description,
"publication_date": dataset.publication_date,
"source_type": dataset.source_type,
"website": dataset.website,
}
)
return render(request, "dataset_update.html", {"form": form, "dataset": dataset})
#
# Venue Views
#
def venues(request):
all_venues = Venue.nodes.order_by("-publication_date")[:50]
message = None
if request.method == "POST":
form = SearchVenuesForm(request.POST)
if form.is_valid():
# search the db for the venue
# if venue found, then link with paper and go back to paper view
# if not, ask the user to create a new venue
english_stopwords = stopwords.words("english")
venue_name = form.cleaned_data["venue_name"].lower()
venue_publication_year = form.cleaned_data["venue_publication_year"]
# TO DO: should probably check that data is 4 digits...
venue_name_tokens = [
w for w in venue_name.split(" ") if not w in english_stopwords
]
venue_query = (
"(?i).*" + "+.*".join("(" + w + ")" for w in venue_name_tokens) + "+.*"
)
query = (
"MATCH (v:Venue) WHERE v.publication_date =~ '"
+ venue_publication_year[0:4]
+ ".*' AND v.name =~ { venue_query } RETURN v"
)
results, meta = db.cypher_query(
query,
dict(
venue_publication_year=venue_publication_year[0:4],
venue_query=venue_query,
),
)
if len(results) > 0:
venues = [Venue.inflate(row[0]) for row in results]
print("Found {} venues that match".format(len(venues)))
return render(request, "venues.html", {"venues": venues, 'form': form, "message": message})
else:
# render new Venue form with the searched name as
message = "No matching venues found"
if request.method == "GET":
form = SearchVenuesForm()
message = None
return render(request, "venues.html", {"venues": all_venues, "form": form, "message": message})
def venue_detail(request, id):
papers_published_at_venue = None
# Retrieve the paper from the database
query = "MATCH (a) WHERE ID(a)={id} RETURN a"
results, meta = db.cypher_query(query, dict(id=id))
if len(results) > 0:
# There should be only one results because ID should be unique. Here we check that at
# least one result has been returned and take the first result as the correct match.
# Now, it should not happen that len(results) > 1 since IDs are meant to be unique.
# For the MVP we are going to ignore the latter case and just continue but ultimately,
# we should be checking for > 1 and failing gracefully.
all_venues = [Venue.inflate(row[0]) for row in results]
venue = all_venues[0]
else: # go back to the venue index page
return render(
request,
"venues.html",
{"venues": Venue.nodes.all(), "num_venues": len(Venue.nodes.all())},
)
#
# TO DO: Retrieve all papers published at this venue and list them
#
query = "MATCH (p:Paper)-[r:was_published_at]->(v:Venue) where id(v)={id} return p"
results, meta = db.cypher_query(query, dict(id=id))
if len(results) > 0:
papers_published_at_venue = [Paper.inflate(row[0]) for row in results]
print("Number of papers published at this venue {}".format(len(papers_published_at_venue)))
for p in papers_published_at_venue:
print("Title: {}".format(p.title))
request.session["last-viewed-venue"] = id
return render(request, "venue_detail.html", {"venue": venue, "papers": papers_published_at_venue})
def venue_find(request):
"""
Search for venue.
:param request:
:return:
"""
if request.method == "POST":
form = SearchVenuesForm(request.POST)
if form.is_valid():
# search the db for the venue
# if venue found, then link with paper and go back to paper view
# if not, ask the user to create a new venue
english_stopwords = stopwords.words("english")
venue_name = form.cleaned_data["venue_name"].lower()
venue_publication_year = form.cleaned_data["venue_publication_year"]
# TO DO: should probably check that data is 4 digits...
venue_name_tokens = [
w for w in venue_name.split(" ") if not w in english_stopwords
]
venue_query = (
"(?i).*" + "+.*".join("(" + w + ")" for w in venue_name_tokens) + "+.*"
)
query = (
"MATCH (v:Venue) WHERE v.publication_date =~ '"
+ venue_publication_year[0:4]
+ ".*' AND v.name =~ { venue_query } RETURN v"
)
results, meta = db.cypher_query(
query,
dict(
venue_publication_year=venue_publication_year[0:4],
venue_query=venue_query,
),
)
if len(results) > 0:
venues = [Venue.inflate(row[0]) for row in results]
print("Found {} venues that match".format(len(venues)))
return render(request, "venues.html", {"venues": venues})
else:
# render new Venue form with the searched name as
message = "No matching venues found"
if request.method == "GET":
form = SearchVenuesForm()
message = None
return render(request, "venue_find.html", {"form": form, "message": message})
@login_required
def venue_create(request):
user = request.user
if request.method == "POST":
venue = Venue()
venue.created_by = user.id
venue.created_by = user.id
form = VenueForm(instance=venue, data=request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse("venues_index"))
else: # GET
form = VenueForm()
return render(request, "venue_form.html", {"form": form})
# should limit access to admin users only!!
@staff_member_required
def venue_delete(request, id):
print("WARNING: Deleting venue id {} and all related edges".format(id))
# Cypher query to delete the paper node
query = "MATCH (v:Venue) WHERE ID(v)={id} DETACH DELETE v"
results, meta = db.cypher_query(query, dict(id=id))
return HttpResponseRedirect(reverse("venues_index"))
@login_required
def venue_update(request, id):
# retrieve paper by ID
# https://github.com/neo4j-contrib/neomodel/issues/199
query = "MATCH (a) WHERE ID(a)={id} RETURN a"
results, meta = db.cypher_query(query, dict(id=id))
if len(results) > 0:
venues = [Venue.inflate(row[0]) for row in results]
venue = venues[0]
else:
venue = Venue()
# if this is POST request then process the Form data
if request.method == "POST":
form = VenueForm(request.POST)
if form.is_valid():
venue.name = form.cleaned_data["name"]
venue.publication_date = form.cleaned_data["publication_date"]
venue.type = form.cleaned_data["type"]
venue.publisher = form.cleaned_data["publisher"]
venue.keywords = form.cleaned_data["keywords"]
venue.peer_reviewed = form.cleaned_data["peer_reviewed"]
venue.website = form.cleaned_data["website"]
venue.save()
return HttpResponseRedirect(reverse("venues_index"))
# GET request
else:
query = "MATCH (a) WHERE ID(a)={id} RETURN a"
results, meta = db.cypher_query(query, dict(id=id))
if len(results) > 0:
venues = [Venue.inflate(row[0]) for row in results]
venue = venues[0]
else:
venue = Venue()
form = VenueForm(
initial={
"name": venue.name,
"type": venue.type,
"publication_date": venue.publication_date,
"publisher": venue.publisher,
"keywords": venue.keywords,
"peer_reviewed": venue.peer_reviewed,
"website": venue.website,
}
)
return render(request, "venue_update.html", {"form": form, "venue": venue})
#
# Comment Views
#
@login_required
def comments(request):
"""
We should only show the list of comments if the user is admin. Otherwise, the user should
be redirected to the home page.
:param request:
:return:
"""
# Only superusers can view all the comments
if request.user.is_superuser:
return render(
request,
"comments.html",
{"comments": Comment.nodes.all(), "num_comments": len(Comment.nodes.all())},
)
else:
# other users are sent back to the paper index
return HttpResponseRedirect(reverse("papers_index"))
@login_required
def comment_detail(request, id):
# Only superusers can view comment details.
if request.user.is_superuser:
return render(request, "comment_detail.html", {"comment": Comment.nodes.all()})
else:
# other users are sent back to the papers index
return HttpResponseRedirect(reverse("papers_index"))
@login_required
def comment_create(request):
user = request.user
# Retrieve paper using paper id
paper_id = request.session["last-viewed-paper"]
query = "MATCH (a) WHERE ID(a)={id} RETURN a"
results, meta = db.cypher_query(query, dict(id=paper_id))
if len(results) > 0:
all_papers = [Paper.inflate(row[0]) for row in results]
paper = all_papers[0]
else: # just send him to the list of papers
HttpResponseRedirect(reverse("papers_index"))
if request.method == "POST":
comment = Comment()
comment.created_by = user.id
comment.author = user.username
form = CommentForm(instance=comment, data=request.POST)
if form.is_valid():
# add link from new comment to paper
form.save()
comment.discusses.connect(paper)
del request.session["last-viewed-paper"]
return redirect("paper_detail", id=paper_id)
else: # GET
form = CommentForm()
return render(request, "comment_form.html", {"form": form})
@login_required
def comment_update(request, id):
# retrieve paper by ID
# https://github.com/neo4j-contrib/neomodel/issues/199
query = "MATCH (a) WHERE ID(a)={id} RETURN a"
results, meta = db.cypher_query(query, dict(id=id))
if len(results) > 0:
comments = [Comment.inflate(row[0]) for row in results]
comment = comments[0]
else:
comment = Comment()
# Retrieve paper using paper id
paper_id = request.session["last-viewed-paper"]
# if this is POST request then process the Form data
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment.text = form.cleaned_data["text"]
# comment.author = form.cleaned_data['author']
comment.save()
# return HttpResponseRedirect(reverse('comments_index'))
del request.session["last-viewed-paper"]
return redirect("paper_detail", id=paper_id)
# GET request
else:
query = "MATCH (a) WHERE ID(a)={id} RETURN a"
results, meta = db.cypher_query(query, dict(id=id))
if len(results) > 0:
comments = [Comment.inflate(row[0]) for row in results]
comment = comments[0]
else:
comment = Comment()
# form = CommentForm(initial={'author': comment.author,
# 'text': comment.text,
# 'publication_date': comment.publication_date,
# }
# )
form = CommentForm(
initial={"text": comment.text, "publication_date": comment.publication_date}
)
return render(request, "comment_update.html", {"form": form, "comment": comment})
#
# Utility Views (admin required)
#
@login_required
def build(request):
try:
d1 = Dataset()
d1.name = "Yelp"
d1.source_type = "N"
d1.save()
v1 = Venue()
v1.name = "Neural Information Processing Systems"
v1.publication_date = date(2017, 12, 15)
v1.type = "C"
v1.publisher = "NIPS Foundation"
v1.keywords = "machine learning, machine learning, computational neuroscience"
v1.website = "https://nips.cc"
v1.peer_reviewed = "Y"
v1.save()
v2 = Venue()
v2.name = "International Conference on Machine Learning"
v2.publication_date = date(2016, 5, 24)
v2.type = "C"
v2.publisher = "International Machine Learning Society (IMLS)"
v2.keywords = "machine learning, computer science"
v2.peer_reviewed = "Y"
v2.website = "https://icml.cc/2016/"
v2.save()
p1 = Paper()
p1.title = "The best paper in the world."
p1.abstract = "Abstract goes here"
p1.keywords = "computer science, machine learning, graphs"
p1.save()
p1.evaluates_on.connect(d1)
p1.was_published_at.connect(v1)
p2 = Paper()
p2.title = "The second best paper in the world."
p2.abstract = "Abstract goes here"
p2.keywords = "statistics, robust methods"
p2.save()
p2.cites.connect(p1)
p2.was_published_at.connect(v2)
p3 = Paper()
p3.title = "I wish I could write a paper with a great title."
p3.abstract = "Abstract goes here"
p3.keywords = "machine learning, neural networks, convolutional neural networks"
p3.save()
p3.cites.connect(p1)
p3.was_published_at.connect(v1)
a1 = Person()
a1.first_name = "Pantelis"
a1.last_name = "Elinas"
a1.save()
a1.authors.connect(p1)
a2 = Person()
a2.first_name = "Ke"
a2.last_name = "Sun"
a2.save()
a2.authors.connect(p1)
a2.authors.connect(p2)
a3 = Person()
a3.first_name = "Bill"
a3.last_name = "Gates"
a3.save()
a3.authors.connect(p3)
a3.advisor_of.connect(a1)
a4 = Person()
a4.first_name = "Steve"
a4.last_name = "Jobs"
a4.save()
a4.authors.connect(p2)
a4.authors.connect(p3)
a4.co_authors_with.connect(a3)
c1 = Comment()
c1.author = "<NAME>"
c1.text = "This paper is flawless"
c1.save()
c1.discusses.connect(p1)
except Exception:
pass
num_papers = len(Paper.nodes.all())
num_people = len(Person.nodes.all())
return render(
request, "build.html", {"num_papers": num_papers, "num_people": num_people}
)
| [
"catalog.forms.PaperForm",
"catalog.forms.SearchDatasetsForm",
"re.compile",
"catalog.models.Comment",
"urllib.request.Request",
"catalog.forms.SearchVenuesForm",
"catalog.forms.PaperConnectionForm",
"catalog.forms.PaperImportForm",
"catalog.models.ReadingGroup.objects.all",
"django.urls.reverse",... | [((5612, 5725), 'django.shortcuts.render', 'render', (['request', '"""paper_authors.html"""', "{'authors': authors, 'paper': paper, 'number_of_authors': num_authors}"], {}), "(request, 'paper_authors.html', {'authors': authors, 'paper': paper,\n 'number_of_authors': num_authors})\n", (5618, 5725), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((8714, 8949), 'django.shortcuts.render', 'render', (['request', '"""paper_detail.html"""', "{'paper': paper, 'venue': venue, 'authors': authors, 'comments': comments,\n 'codes': codes, 'num_comments': num_comments, 'ego_network':\n ego_network_json, 'main_paper_id': main_paper_id}"], {}), "(request, 'paper_detail.html', {'paper': paper, 'venue': venue,\n 'authors': authors, 'comments': comments, 'codes': codes,\n 'num_comments': num_comments, 'ego_network': ego_network_json,\n 'main_paper_id': main_paper_id})\n", (8720, 8949), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((17422, 17494), 'django.shortcuts.render', 'render', (['request', '"""papers_index.html"""', "{'form': form, 'message': message}"], {}), "(request, 'papers_index.html', {'form': form, 'message': message})\n", (17428, 17494), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((21566, 21665), 'django.shortcuts.render', 'render', (['request', '"""paper_connect_venue.html"""', "{'form': form, 'venues': None, 'message': message}"], {}), "(request, 'paper_connect_venue.html', {'form': form, 'venues': None,\n 'message': message})\n", (21572, 21665), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((22111, 22148), 'django.shortcuts.get_object_or_404', 'get_object_or_404', (['Collection'], {'pk': 'cid'}), '(Collection, pk=cid)\n', (22128, 22148), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((22860, 22913), 'django.contrib.messages.add_message', 'messages.add_message', (['request', 'messages.INFO', 'message'], {}), '(request, messages.INFO, message)\n', (22880, 22913), False, 'from django.contrib import messages\n'), ((23185, 23230), 'catalog.models.Collection.objects.filter', 'Collection.objects.filter', ([], {'owner': 'request.user'}), '(owner=request.user)\n', (23210, 23230), False, 'from catalog.models import Collection, CollectionEntry\n'), ((23663, 23768), 'django.shortcuts.render', 'render', (['request', '"""paper_add_to_collection.html"""', "{'collections': all_collections, 'message': message}"], {}), "(request, 'paper_add_to_collection.html', {'collections':\n all_collections, 'message': message})\n", (23669, 23768), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((24171, 24210), 'django.shortcuts.get_object_or_404', 'get_object_or_404', (['ReadingGroup'], {'pk': 'gid'}), '(ReadingGroup, pk=gid)\n', (24188, 24210), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((24229, 24248), 'catalog.models.ReadingGroupEntry', 'ReadingGroupEntry', ([], {}), '()\n', (24246, 24248), False, 'from catalog.models import ReadingGroup, ReadingGroupEntry\n'), ((24826, 24852), 'catalog.models.ReadingGroup.objects.all', 'ReadingGroup.objects.all', ([], {}), '()\n', (24850, 24852), False, 'from catalog.models import ReadingGroup, ReadingGroupEntry\n'), ((25079, 25169), 'django.shortcuts.render', 'render', (['request', '"""paper_add_to_group.html"""', "{'groups': all_groups, 'message': message}"], {}), "(request, 'paper_add_to_group.html', {'groups': all_groups, 'message':\n message})\n", (25085, 25169), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((27537, 27637), 'django.shortcuts.render', 'render', (['request', '"""paper_connect_author.html"""', "{'form': form, 'people': None, 'message': message}"], {}), "(request, 'paper_connect_author.html', {'form': form, 'people': None,\n 'message': message})\n", (27543, 27637), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((29899, 29930), 'django.shortcuts.redirect', 'redirect', (['"""paper_detail"""'], {'id': 'id'}), "('paper_detail', id=id)\n", (29907, 29930), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((34701, 34800), 'django.shortcuts.render', 'render', (['request', '"""paper_connect_paper.html"""', "{'form': form, 'papers': None, 'message': message}"], {}), "(request, 'paper_connect_paper.html', {'form': form, 'papers': None,\n 'message': message})\n", (34707, 34800), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((38179, 38282), 'django.shortcuts.render', 'render', (['request', '"""paper_connect_dataset.html"""', "{'form': form, 'datasets': None, 'message': message}"], {}), "(request, 'paper_connect_dataset.html', {'form': form, 'datasets':\n None, 'message': message})\n", (38185, 38282), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((40584, 40681), 'django.shortcuts.render', 'render', (['request', '"""paper_connect_code.html"""', "{'form': form, 'codes': None, 'message': message}"], {}), "(request, 'paper_connect_code.html', {'form': form, 'codes': None,\n 'message': message})\n", (40590, 40681), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((42268, 42341), 'django.shortcuts.render', 'render', (['request', '"""paper_update.html"""', "{'form': form, 'paper': paper_inst}"], {}), "(request, 'paper_update.html', {'form': form, 'paper': paper_inst})\n", (42274, 42341), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((42667, 42693), 'nltk.corpus.stopwords.words', 'stopwords.words', (['"""english"""'], {}), "('english')\n", (42682, 42693), False, 'from nltk.corpus import stopwords\n'), ((47215, 47285), 'django.shortcuts.render', 'render', (['request', '"""paper_form.html"""', "{'form': form, 'message': message}"], {}), "(request, 'paper_form.html', {'form': form, 'message': message})\n", (47221, 47285), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((63257, 63307), 'django.shortcuts.render', 'render', (['request', '"""paper_form.html"""', "{'form': form}"], {}), "(request, 'paper_form.html', {'form': form})\n", (63263, 63307), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((65439, 65537), 'django.shortcuts.render', 'render', (['request', '"""datasets.html"""', "{'datasets': all_datasets, 'form': form, 'message': message}"], {}), "(request, 'datasets.html', {'datasets': all_datasets, 'form': form,\n 'message': message})\n", (65445, 65537), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((66678, 66738), 'django.shortcuts.render', 'render', (['request', '"""dataset_detail.html"""', "{'dataset': dataset}"], {}), "(request, 'dataset_detail.html', {'dataset': dataset})\n", (66684, 66738), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((69791, 69863), 'django.shortcuts.render', 'render', (['request', '"""dataset_find.html"""', "{'form': form, 'message': message}"], {}), "(request, 'dataset_find.html', {'form': form, 'message': message})\n", (69797, 69863), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((70275, 70327), 'django.shortcuts.render', 'render', (['request', '"""dataset_form.html"""', "{'form': form}"], {}), "(request, 'dataset_form.html', {'form': form})\n", (70281, 70327), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((72472, 72546), 'django.shortcuts.render', 'render', (['request', '"""dataset_update.html"""', "{'form': form, 'dataset': dataset}"], {}), "(request, 'dataset_update.html', {'form': form, 'dataset': dataset})\n", (72478, 72546), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((74470, 74562), 'django.shortcuts.render', 'render', (['request', '"""venues.html"""', "{'venues': all_venues, 'form': form, 'message': message}"], {}), "(request, 'venues.html', {'venues': all_venues, 'form': form,\n 'message': message})\n", (74476, 74562), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((76123, 76218), 'django.shortcuts.render', 'render', (['request', '"""venue_detail.html"""', "{'venue': venue, 'papers': papers_published_at_venue}"], {}), "(request, 'venue_detail.html', {'venue': venue, 'papers':\n papers_published_at_venue})\n", (76129, 76218), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((78077, 78147), 'django.shortcuts.render', 'render', (['request', '"""venue_find.html"""', "{'form': form, 'message': message}"], {}), "(request, 'venue_find.html', {'form': form, 'message': message})\n", (78083, 78147), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((78578, 78628), 'django.shortcuts.render', 'render', (['request', '"""venue_form.html"""', "{'form': form}"], {}), "(request, 'venue_form.html', {'form': form})\n", (78584, 78628), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((80794, 80862), 'django.shortcuts.render', 'render', (['request', '"""venue_update.html"""', "{'form': form, 'venue': venue}"], {}), "(request, 'venue_update.html', {'form': form, 'venue': venue})\n", (80800, 80862), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((82841, 82893), 'django.shortcuts.render', 'render', (['request', '"""comment_form.html"""', "{'form': form}"], {}), "(request, 'comment_form.html', {'form': form})\n", (82847, 82893), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((84599, 84673), 'django.shortcuts.render', 'render', (['request', '"""comment_update.html"""', "{'form': form, 'comment': comment}"], {}), "(request, 'comment_update.html', {'form': form, 'comment': comment})\n", (84605, 84673), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((87406, 87493), 'django.shortcuts.render', 'render', (['request', '"""build.html"""', "{'num_papers': num_papers, 'num_people': num_people}"], {}), "(request, 'build.html', {'num_papers': num_papers, 'num_people':\n num_people})\n", (87412, 87493), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((2791, 2823), 'catalog.models.Paper.nodes.order_by', 'Paper.nodes.order_by', (['"""-created"""'], {}), "('-created')\n", (2811, 2823), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((3150, 3180), 'catalog.forms.SearchPapersForm', 'SearchPapersForm', (['request.POST'], {}), '(request.POST)\n', (3166, 3180), False, 'from catalog.forms import SearchVenuesForm, SearchPapersForm, SearchPeopleForm, SearchDatasetsForm, SearchCodesForm, PaperConnectionForm\n'), ((5400, 5461), 'django.urls.reverse', 'reverse', (['"""paper_remove_author"""'], {'kwargs': "{'id': id, 'rid': rid}"}), "('paper_remove_author', kwargs={'id': id, 'rid': rid})\n", (5407, 5461), False, 'from django.urls import reverse\n'), ((6209, 6252), 'django.urls.reverse', 'reverse', (['"""paper_authors"""'], {'kwargs': "{'id': id}"}), "('paper_authors', kwargs={'id': id})\n", (6216, 6252), False, 'from django.urls import reverse\n'), ((6627, 6650), 'django.urls.reverse', 'reverse', (['"""papers_index"""'], {}), "('papers_index')\n", (6634, 6650), False, 'from django.urls import reverse\n'), ((10023, 10065), 'django.urls.reverse', 'reverse', (['"""paper_detail"""'], {'kwargs': "{'id': id}"}), "('paper_detail', kwargs={'id': id})\n", (10030, 10065), False, 'from django.urls import reverse\n'), ((16185, 16215), 'catalog.forms.SearchPapersForm', 'SearchPapersForm', (['request.POST'], {}), '(request.POST)\n', (16201, 16215), False, 'from catalog.forms import SearchVenuesForm, SearchPapersForm, SearchPeopleForm, SearchDatasetsForm, SearchCodesForm, PaperConnectionForm\n'), ((17599, 17629), 'catalog.forms.SearchVenuesForm', 'SearchVenuesForm', (['request.POST'], {}), '(request.POST)\n', (17615, 17629), False, 'from catalog.forms import SearchVenuesForm, SearchPapersForm, SearchPeopleForm, SearchDatasetsForm, SearchCodesForm, PaperConnectionForm\n'), ((21512, 21530), 'catalog.forms.SearchVenuesForm', 'SearchVenuesForm', ([], {}), '()\n', (21528, 21530), False, 'from catalog.forms import SearchVenuesForm, SearchPapersForm, SearchPeopleForm, SearchDatasetsForm, SearchCodesForm, PaperConnectionForm\n'), ((22947, 22989), 'django.urls.reverse', 'reverse', (['"""paper_detail"""'], {'kwargs': "{'id': id}"}), "('paper_detail', kwargs={'id': id})\n", (22954, 22989), False, 'from django.urls import reverse\n'), ((24458, 24500), 'django.urls.reverse', 'reverse', (['"""paper_detail"""'], {'kwargs': "{'id': id}"}), "('paper_detail', kwargs={'id': id})\n", (24465, 24500), False, 'from django.urls import reverse\n'), ((24881, 24955), 'django.urls.reverse', 'reverse', (['"""paper_add_to_group_selected"""'], {'kwargs': "{'id': id, 'gid': group.id}"}), "('paper_add_to_group_selected', kwargs={'id': id, 'gid': group.id})\n", (24888, 24955), False, 'from django.urls import reverse\n'), ((25478, 25545), 'django.contrib.messages.add_message', 'messages.add_message', (['request', 'messages.INFO', '"""Linked with author."""'], {}), "(request, messages.INFO, 'Linked with author.')\n", (25498, 25545), False, 'from django.contrib import messages\n'), ((25564, 25634), 'django.contrib.messages.add_message', 'messages.add_message', (['request', 'messages.INFO', '"""Link to author failed!"""'], {}), "(request, messages.INFO, 'Link to author failed!')\n", (25584, 25634), False, 'from django.contrib import messages\n'), ((25668, 25710), 'django.urls.reverse', 'reverse', (['"""paper_detail"""'], {'kwargs': "{'id': id}"}), "('paper_detail', kwargs={'id': id})\n", (25675, 25710), False, 'from django.urls import reverse\n'), ((25817, 25847), 'catalog.forms.SearchPeopleForm', 'SearchPeopleForm', (['request.POST'], {}), '(request.POST)\n', (25833, 25847), False, 'from catalog.forms import SearchVenuesForm, SearchPapersForm, SearchPeopleForm, SearchDatasetsForm, SearchCodesForm, PaperConnectionForm\n'), ((27483, 27501), 'catalog.forms.SearchPeopleForm', 'SearchPeopleForm', ([], {}), '()\n', (27499, 27501), False, 'from catalog.forms import SearchVenuesForm, SearchPapersForm, SearchPeopleForm, SearchDatasetsForm, SearchCodesForm, PaperConnectionForm\n'), ((29796, 29865), 'django.contrib.messages.add_message', 'messages.add_message', (['request', 'messages.INFO', '"""Could not find paper!"""'], {}), "(request, messages.INFO, 'Could not find paper!')\n", (29816, 29865), False, 'from django.contrib import messages\n'), ((30178, 30211), 'catalog.forms.PaperConnectionForm', 'PaperConnectionForm', (['request.POST'], {}), '(request.POST)\n', (30197, 30211), False, 'from catalog.forms import SearchVenuesForm, SearchPapersForm, SearchPeopleForm, SearchDatasetsForm, SearchCodesForm, PaperConnectionForm\n'), ((34667, 34688), 'catalog.forms.PaperConnectionForm', 'PaperConnectionForm', ([], {}), '()\n', (34686, 34688), False, 'from catalog.forms import SearchVenuesForm, SearchPapersForm, SearchPeopleForm, SearchDatasetsForm, SearchCodesForm, PaperConnectionForm\n'), ((35056, 35088), 'catalog.forms.SearchDatasetsForm', 'SearchDatasetsForm', (['request.POST'], {}), '(request.POST)\n', (35074, 35088), False, 'from catalog.forms import SearchVenuesForm, SearchPapersForm, SearchPeopleForm, SearchDatasetsForm, SearchCodesForm, PaperConnectionForm\n'), ((38123, 38143), 'catalog.forms.SearchDatasetsForm', 'SearchDatasetsForm', ([], {}), '()\n', (38141, 38143), False, 'from catalog.forms import SearchVenuesForm, SearchPapersForm, SearchPeopleForm, SearchDatasetsForm, SearchCodesForm, PaperConnectionForm\n'), ((38590, 38660), 'django.contrib.messages.add_message', 'messages.add_message', (['request', 'messages.INFO', '"""Linked with code repo."""'], {}), "(request, messages.INFO, 'Linked with code repo.')\n", (38610, 38660), False, 'from django.contrib import messages\n'), ((38679, 38752), 'django.contrib.messages.add_message', 'messages.add_message', (['request', 'messages.INFO', '"""Link to code repo failed!"""'], {}), "(request, messages.INFO, 'Link to code repo failed!')\n", (38699, 38752), False, 'from django.contrib import messages\n'), ((38786, 38828), 'django.urls.reverse', 'reverse', (['"""paper_detail"""'], {'kwargs': "{'id': id}"}), "('paper_detail', kwargs={'id': id})\n", (38793, 38828), False, 'from django.urls import reverse\n'), ((39072, 39101), 'catalog.forms.SearchCodesForm', 'SearchCodesForm', (['request.POST'], {}), '(request.POST)\n', (39087, 39101), False, 'from catalog.forms import SearchVenuesForm, SearchPapersForm, SearchPeopleForm, SearchDatasetsForm, SearchCodesForm, PaperConnectionForm\n'), ((40531, 40548), 'catalog.forms.SearchCodesForm', 'SearchCodesForm', ([], {}), '()\n', (40546, 40548), False, 'from catalog.forms import SearchVenuesForm, SearchPapersForm, SearchPeopleForm, SearchDatasetsForm, SearchCodesForm, PaperConnectionForm\n'), ((41105, 41112), 'catalog.models.Paper', 'Paper', ([], {}), '()\n', (41110, 41112), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((41220, 41243), 'catalog.forms.PaperForm', 'PaperForm', (['request.POST'], {}), '(request.POST)\n', (41229, 41243), False, 'from catalog.forms import PaperForm, DatasetForm, VenueForm, CommentForm, PaperImportForm\n'), ((41999, 42164), 'catalog.forms.PaperForm', 'PaperForm', ([], {'initial': "{'title': paper_inst.title, 'abstract': paper_inst.abstract, 'keywords':\n paper_inst.keywords, 'download_link': paper_inst.download_link}"}), "(initial={'title': paper_inst.title, 'abstract': paper_inst.\n abstract, 'keywords': paper_inst.keywords, 'download_link': paper_inst.\n download_link})\n", (42008, 42164), False, 'from catalog.forms import PaperForm, DatasetForm, VenueForm, CommentForm, PaperImportForm\n'), ((43726, 43734), 'catalog.models.Person', 'Person', ([], {}), '()\n', (43732, 43734), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((45100, 45107), 'catalog.models.Paper', 'Paper', ([], {}), '()\n', (45105, 45107), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((45158, 45202), 'catalog.forms.PaperForm', 'PaperForm', ([], {'instance': 'paper', 'data': 'request.POST'}), '(instance=paper, data=request.POST)\n', (45167, 45202), False, 'from catalog.forms import PaperForm, DatasetForm, VenueForm, CommentForm, PaperImportForm\n'), ((54345, 54383), 'urllib.request.Request', 'Request', (['abstract_url'], {'headers': 'headers'}), '(abstract_url, headers=headers)\n', (54352, 54383), False, 'from urllib.request import urlopen, Request\n'), ((54399, 54411), 'urllib.request.urlopen', 'urlopen', (['req'], {}), '(req)\n', (54406, 54411), False, 'from urllib.request import urlopen, Request\n'), ((54430, 54473), 'bs4.BeautifulSoup', 'BeautifulSoup', (['html'], {'features': '"""html.parser"""'}), "(html, features='html.parser')\n", (54443, 54473), False, 'from bs4 import BeautifulSoup\n'), ((59010, 59022), 'urllib.request.urlopen', 'urlopen', (['url'], {}), '(url)\n', (59017, 59022), False, 'from urllib.request import urlopen, Request\n'), ((59185, 59228), 'bs4.BeautifulSoup', 'BeautifulSoup', (['html'], {'features': '"""html.parser"""'}), "(html, features='html.parser')\n", (59198, 59228), False, 'from bs4 import BeautifulSoup\n'), ((63227, 63244), 'catalog.forms.PaperImportForm', 'PaperImportForm', ([], {}), '()\n', (63242, 63244), False, 'from catalog.forms import PaperForm, DatasetForm, VenueForm, CommentForm, PaperImportForm\n'), ((64543, 64586), 'catalog.models.Dataset.nodes.order_by', 'Dataset.nodes.order_by', (['"""-publication_date"""'], {}), "('-publication_date')\n", (64565, 64586), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((64660, 64692), 'catalog.forms.SearchDatasetsForm', 'SearchDatasetsForm', (['request.POST'], {}), '(request.POST)\n', (64678, 64692), False, 'from catalog.forms import SearchVenuesForm, SearchPapersForm, SearchPeopleForm, SearchDatasetsForm, SearchCodesForm, PaperConnectionForm\n'), ((69120, 69152), 'catalog.forms.SearchDatasetsForm', 'SearchDatasetsForm', (['request.POST'], {}), '(request.POST)\n', (69138, 69152), False, 'from catalog.forms import SearchVenuesForm, SearchPapersForm, SearchPeopleForm, SearchDatasetsForm, SearchCodesForm, PaperConnectionForm\n'), ((69987, 69996), 'catalog.models.Dataset', 'Dataset', ([], {}), '()\n', (69994, 69996), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((70049, 70097), 'catalog.forms.DatasetForm', 'DatasetForm', ([], {'instance': 'dataset', 'data': 'request.POST'}), '(instance=dataset, data=request.POST)\n', (70060, 70097), False, 'from catalog.forms import PaperForm, DatasetForm, VenueForm, CommentForm, PaperImportForm\n'), ((70249, 70262), 'catalog.forms.DatasetForm', 'DatasetForm', ([], {}), '()\n', (70260, 70262), False, 'from catalog.forms import PaperForm, DatasetForm, VenueForm, CommentForm, PaperImportForm\n'), ((70707, 70732), 'django.urls.reverse', 'reverse', (['"""datasets_index"""'], {}), "('datasets_index')\n", (70714, 70732), False, 'from django.urls import reverse\n'), ((71124, 71133), 'catalog.models.Dataset', 'Dataset', ([], {}), '()\n', (71131, 71133), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((71240, 71265), 'catalog.forms.DatasetForm', 'DatasetForm', (['request.POST'], {}), '(request.POST)\n', (71251, 71265), False, 'from catalog.forms import PaperForm, DatasetForm, VenueForm, CommentForm, PaperImportForm\n'), ((72107, 72339), 'catalog.forms.DatasetForm', 'DatasetForm', ([], {'initial': "{'name': dataset.name, 'keywords': dataset.keywords, 'description': dataset\n .description, 'publication_date': dataset.publication_date,\n 'source_type': dataset.source_type, 'website': dataset.website}"}), "(initial={'name': dataset.name, 'keywords': dataset.keywords,\n 'description': dataset.description, 'publication_date': dataset.\n publication_date, 'source_type': dataset.source_type, 'website':\n dataset.website})\n", (72118, 72339), False, 'from catalog.forms import PaperForm, DatasetForm, VenueForm, CommentForm, PaperImportForm\n'), ((72605, 72646), 'catalog.models.Venue.nodes.order_by', 'Venue.nodes.order_by', (['"""-publication_date"""'], {}), "('-publication_date')\n", (72625, 72646), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((72720, 72750), 'catalog.forms.SearchVenuesForm', 'SearchVenuesForm', (['request.POST'], {}), '(request.POST)\n', (72736, 72750), False, 'from catalog.forms import SearchVenuesForm, SearchPapersForm, SearchPeopleForm, SearchDatasetsForm, SearchCodesForm, PaperConnectionForm\n'), ((74416, 74434), 'catalog.forms.SearchVenuesForm', 'SearchVenuesForm', ([], {}), '()\n', (74432, 74434), False, 'from catalog.forms import SearchVenuesForm, SearchPapersForm, SearchPeopleForm, SearchDatasetsForm, SearchCodesForm, PaperConnectionForm\n'), ((76361, 76391), 'catalog.forms.SearchVenuesForm', 'SearchVenuesForm', (['request.POST'], {}), '(request.POST)\n', (76377, 76391), False, 'from catalog.forms import SearchVenuesForm, SearchPapersForm, SearchPeopleForm, SearchDatasetsForm, SearchCodesForm, PaperConnectionForm\n'), ((78023, 78041), 'catalog.forms.SearchVenuesForm', 'SearchVenuesForm', ([], {}), '()\n', (78039, 78041), False, 'from catalog.forms import SearchVenuesForm, SearchPapersForm, SearchPeopleForm, SearchDatasetsForm, SearchCodesForm, PaperConnectionForm\n'), ((78267, 78274), 'catalog.models.Venue', 'Venue', ([], {}), '()\n', (78272, 78274), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((78360, 78404), 'catalog.forms.VenueForm', 'VenueForm', ([], {'instance': 'venue', 'data': 'request.POST'}), '(instance=venue, data=request.POST)\n', (78369, 78404), False, 'from catalog.forms import PaperForm, DatasetForm, VenueForm, CommentForm, PaperImportForm\n'), ((78554, 78565), 'catalog.forms.VenueForm', 'VenueForm', ([], {}), '()\n', (78563, 78565), False, 'from catalog.forms import PaperForm, DatasetForm, VenueForm, CommentForm, PaperImportForm\n'), ((79002, 79025), 'django.urls.reverse', 'reverse', (['"""venues_index"""'], {}), "('venues_index')\n", (79009, 79025), False, 'from django.urls import reverse\n'), ((79405, 79412), 'catalog.models.Venue', 'Venue', ([], {}), '()\n', (79410, 79412), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((79519, 79542), 'catalog.forms.VenueForm', 'VenueForm', (['request.POST'], {}), '(request.POST)\n', (79528, 79542), False, 'from catalog.forms import PaperForm, DatasetForm, VenueForm, CommentForm, PaperImportForm\n'), ((80407, 80646), 'catalog.forms.VenueForm', 'VenueForm', ([], {'initial': "{'name': venue.name, 'type': venue.type, 'publication_date': venue.\n publication_date, 'publisher': venue.publisher, 'keywords': venue.\n keywords, 'peer_reviewed': venue.peer_reviewed, 'website': venue.website}"}), "(initial={'name': venue.name, 'type': venue.type,\n 'publication_date': venue.publication_date, 'publisher': venue.\n publisher, 'keywords': venue.keywords, 'peer_reviewed': venue.\n peer_reviewed, 'website': venue.website})\n", (80416, 80646), False, 'from catalog.forms import PaperForm, DatasetForm, VenueForm, CommentForm, PaperImportForm\n'), ((82377, 82386), 'catalog.models.Comment', 'Comment', ([], {}), '()\n', (82384, 82386), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((82478, 82526), 'catalog.forms.CommentForm', 'CommentForm', ([], {'instance': 'comment', 'data': 'request.POST'}), '(instance=comment, data=request.POST)\n', (82489, 82526), False, 'from catalog.forms import PaperForm, DatasetForm, VenueForm, CommentForm, PaperImportForm\n'), ((82815, 82828), 'catalog.forms.CommentForm', 'CommentForm', ([], {}), '()\n', (82826, 82828), False, 'from catalog.forms import PaperForm, DatasetForm, VenueForm, CommentForm, PaperImportForm\n'), ((83284, 83293), 'catalog.models.Comment', 'Comment', ([], {}), '()\n', (83291, 83293), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((83489, 83514), 'catalog.forms.CommentForm', 'CommentForm', (['request.POST'], {}), '(request.POST)\n', (83500, 83514), False, 'from catalog.forms import PaperForm, DatasetForm, VenueForm, CommentForm, PaperImportForm\n'), ((84475, 84569), 'catalog.forms.CommentForm', 'CommentForm', ([], {'initial': "{'text': comment.text, 'publication_date': comment.publication_date}"}), "(initial={'text': comment.text, 'publication_date': comment.\n publication_date})\n", (84486, 84569), False, 'from catalog.forms import PaperForm, DatasetForm, VenueForm, CommentForm, PaperImportForm\n'), ((84771, 84780), 'catalog.models.Dataset', 'Dataset', ([], {}), '()\n', (84778, 84780), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((84867, 84874), 'catalog.models.Venue', 'Venue', ([], {}), '()\n', (84872, 84874), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((84963, 84981), 'datetime.date', 'date', (['(2017)', '(12)', '(15)'], {}), '(2017, 12, 15)\n', (84967, 84981), False, 'from datetime import date\n'), ((85234, 85241), 'catalog.models.Venue', 'Venue', ([], {}), '()\n', (85239, 85241), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((85337, 85354), 'datetime.date', 'date', (['(2016)', '(5)', '(24)'], {}), '(2016, 5, 24)\n', (85341, 85354), False, 'from datetime import date\n'), ((85615, 85622), 'catalog.models.Paper', 'Paper', ([], {}), '()\n', (85620, 85622), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((85892, 85899), 'catalog.models.Paper', 'Paper', ([], {}), '()\n', (85897, 85899), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((86153, 86160), 'catalog.models.Paper', 'Paper', ([], {}), '()\n', (86158, 86160), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((86465, 86473), 'catalog.models.Person', 'Person', ([], {}), '()\n', (86471, 86473), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((86605, 86613), 'catalog.models.Person', 'Person', ([], {}), '()\n', (86611, 86613), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((86767, 86775), 'catalog.models.Person', 'Person', ([], {}), '()\n', (86773, 86775), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((86936, 86944), 'catalog.models.Person', 'Person', ([], {}), '()\n', (86942, 86944), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((87142, 87151), 'catalog.models.Comment', 'Comment', ([], {}), '()\n', (87149, 87151), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((87334, 87351), 'catalog.models.Paper.nodes.all', 'Paper.nodes.all', ([], {}), '()\n', (87349, 87351), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((87374, 87392), 'catalog.models.Person.nodes.all', 'Person.nodes.all', ([], {}), '()\n', (87390, 87392), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((1313, 1335), 'catalog.models.Person.inflate', 'Person.inflate', (['row[0]'], {}), '(row[0])\n', (1327, 1335), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((1756, 1776), 'catalog.models.Code.inflate', 'Code.inflate', (['row[0]'], {}), '(row[0])\n', (1768, 1776), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((3280, 3306), 'nltk.corpus.stopwords.words', 'stopwords.words', (['"""english"""'], {}), "('english')\n", (3295, 3306), False, 'from nltk.corpus import stopwords\n'), ((4352, 4370), 'catalog.forms.SearchPapersForm', 'SearchPapersForm', ([], {}), '()\n', (4368, 4370), False, 'from catalog.forms import SearchVenuesForm, SearchPapersForm, SearchPeopleForm, SearchDatasetsForm, SearchCodesForm, PaperConnectionForm\n'), ((5037, 5059), 'catalog.models.Person.inflate', 'Person.inflate', (['row[0]'], {}), '(row[0])\n', (5051, 5059), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((6893, 6914), 'catalog.models.Paper.inflate', 'Paper.inflate', (['row[0]'], {}), '(row[0])\n', (6906, 6914), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((7211, 7232), 'catalog.models.Paper.inflate', 'Paper.inflate', (['row[0]'], {}), '(row[0])\n', (7224, 7232), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((7908, 7931), 'catalog.models.Comment.inflate', 'Comment.inflate', (['row[0]'], {}), '(row[0])\n', (7923, 7931), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((8398, 8419), 'catalog.models.Venue.inflate', 'Venue.inflate', (['row[0]'], {}), '(row[0])\n', (8411, 8419), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((12325, 12373), 'django.urls.reverse', 'reverse', (['"""paper_detail"""'], {'kwargs': "{'id': tp[0].id}"}), "('paper_detail', kwargs={'id': tp[0].id})\n", (12332, 12373), False, 'from django.urls import reverse\n'), ((13037, 13085), 'django.urls.reverse', 'reverse', (['"""code_detail"""'], {'kwargs': "{'id': tpc[0].id}"}), "('code_detail', kwargs={'id': tpc[0].id})\n", (13044, 13085), False, 'from django.urls import reverse\n'), ((13698, 13747), 'django.urls.reverse', 'reverse', (['"""venue_detail"""'], {'kwargs': "{'id': tpv[0].id}"}), "('venue_detail', kwargs={'id': tpv[0].id})\n", (13705, 13747), False, 'from django.urls import reverse\n'), ((14363, 14414), 'django.urls.reverse', 'reverse', (['"""dataset_detail"""'], {'kwargs': "{'id': tpd[0].id}"}), "('dataset_detail', kwargs={'id': tpd[0].id})\n", (14370, 14414), False, 'from django.urls import reverse\n'), ((15564, 15614), 'django.urls.reverse', 'reverse', (['"""person_detail"""'], {'kwargs': "{'id': tpe[0].id}"}), "('person_detail', kwargs={'id': tpe[0].id})\n", (15571, 15614), False, 'from django.urls import reverse\n'), ((16315, 16341), 'nltk.corpus.stopwords.words', 'stopwords.words', (['"""english"""'], {}), "('english')\n", (16330, 16341), False, 'from nltk.corpus import stopwords\n'), ((17391, 17409), 'catalog.forms.SearchPapersForm', 'SearchPapersForm', ([], {}), '()\n', (17407, 17409), False, 'from catalog.forms import SearchVenuesForm, SearchPapersForm, SearchPeopleForm, SearchDatasetsForm, SearchCodesForm, PaperConnectionForm\n'), ((17866, 17892), 'nltk.corpus.stopwords.words', 'stopwords.words', (['"""english"""'], {}), "('english')\n", (17881, 17892), False, 'from nltk.corpus import stopwords\n'), ((21989, 22010), 'catalog.models.Paper.inflate', 'Paper.inflate', (['row[0]'], {}), '(row[0])\n', (22002, 22010), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((22526, 22543), 'catalog.models.CollectionEntry', 'CollectionEntry', ([], {}), '()\n', (22541, 22543), False, 'from catalog.models import Collection, CollectionEntry\n'), ((23365, 23453), 'django.urls.reverse', 'reverse', (['"""paper_add_to_collection_selected"""'], {'kwargs': "{'id': id, 'cid': collection.id}"}), "('paper_add_to_collection_selected', kwargs={'id': id, 'cid':\n collection.id})\n", (23372, 23453), False, 'from django.urls import reverse\n'), ((24019, 24040), 'catalog.models.Paper.inflate', 'Paper.inflate', (['row[0]'], {}), '(row[0])\n', (24032, 24040), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((27889, 27910), 'catalog.models.Paper.inflate', 'Paper.inflate', (['row[0]'], {}), '(row[0])\n', (27902, 27910), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((39395, 39415), 'catalog.views.views_codes._code_find', '_code_find', (['keywords'], {}), '(keywords)\n', (39405, 39415), False, 'from catalog.views.views_codes import _code_find\n'), ((40997, 41018), 'catalog.models.Paper.inflate', 'Paper.inflate', (['row[0]'], {}), '(row[0])\n', (41010, 41018), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((41945, 41952), 'catalog.models.Paper', 'Paper', ([], {}), '()\n', (41950, 41952), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((43205, 43226), 'catalog.models.Paper.inflate', 'Paper.inflate', (['row[0]'], {}), '(row[0])\n', (43218, 43226), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((47018, 47131), 'catalog.forms.PaperForm', 'PaperForm', ([], {'initial': "{'title': title, 'abstract': abstract, 'download_link': download_link,\n 'source_link': url}"}), "(initial={'title': title, 'abstract': abstract, 'download_link':\n download_link, 'source_link': url})\n", (47027, 47131), False, 'from catalog.forms import PaperForm, DatasetForm, VenueForm, CommentForm, PaperImportForm\n'), ((47191, 47202), 'catalog.forms.PaperForm', 'PaperForm', ([], {}), '()\n', (47200, 47202), False, 'from catalog.forms import PaperForm, DatasetForm, VenueForm, CommentForm, PaperImportForm\n'), ((58965, 58994), 'urllib.request.Request', 'Request', (['url'], {'headers': 'headers'}), '(url, headers=headers)\n', (58972, 58994), False, 'from urllib.request import urlopen, Request\n'), ((62446, 62463), 'catalog.forms.PaperImportForm', 'PaperImportForm', ([], {}), '()\n', (62461, 62463), False, 'from catalog.forms import PaperForm, DatasetForm, VenueForm, CommentForm, PaperImportForm\n'), ((62483, 62585), 'django.shortcuts.render', 'render', (['request', '"""paper_form.html"""', "{'form': form, 'message': 'Invalid source, please try again.'}"], {}), "(request, 'paper_form.html', {'form': form, 'message':\n 'Invalid source, please try again.'})\n", (62489, 62585), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((63121, 63144), 'django.urls.reverse', 'reverse', (['"""paper_create"""'], {}), "('paper_create')\n", (63128, 63144), False, 'from django.urls import reverse\n'), ((64384, 64406), 'catalog.models.Person.inflate', 'Person.inflate', (['row[0]'], {}), '(row[0])\n', (64398, 64406), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((65406, 65426), 'catalog.forms.SearchDatasetsForm', 'SearchDatasetsForm', ([], {}), '()\n', (65424, 65426), False, 'from catalog.forms import SearchVenuesForm, SearchPapersForm, SearchPeopleForm, SearchDatasetsForm, SearchCodesForm, PaperConnectionForm\n'), ((66236, 66259), 'catalog.models.Dataset.inflate', 'Dataset.inflate', (['row[0]'], {}), '(row[0])\n', (66251, 66259), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((69758, 69778), 'catalog.forms.SearchDatasetsForm', 'SearchDatasetsForm', ([], {}), '()\n', (69776, 69778), False, 'from catalog.forms import SearchVenuesForm, SearchPapersForm, SearchPeopleForm, SearchDatasetsForm, SearchCodesForm, PaperConnectionForm\n'), ((71022, 71045), 'catalog.models.Dataset.inflate', 'Dataset.inflate', (['row[0]'], {}), '(row[0])\n', (71037, 71045), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((72082, 72091), 'catalog.models.Dataset', 'Dataset', ([], {}), '()\n', (72089, 72091), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((72987, 73013), 'nltk.corpus.stopwords.words', 'stopwords.words', (['"""english"""'], {}), "('english')\n", (73002, 73013), False, 'from nltk.corpus import stopwords\n'), ((75263, 75284), 'catalog.models.Venue.inflate', 'Venue.inflate', (['row[0]'], {}), '(row[0])\n', (75276, 75284), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((75832, 75853), 'catalog.models.Paper.inflate', 'Paper.inflate', (['row[0]'], {}), '(row[0])\n', (75845, 75853), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((76628, 76654), 'nltk.corpus.stopwords.words', 'stopwords.words', (['"""english"""'], {}), "('english')\n", (76643, 76654), False, 'from nltk.corpus import stopwords\n'), ((79311, 79332), 'catalog.models.Venue.inflate', 'Venue.inflate', (['row[0]'], {}), '(row[0])\n', (79324, 79332), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((80384, 80391), 'catalog.models.Venue', 'Venue', ([], {}), '()\n', (80389, 80391), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((81458, 81481), 'django.urls.reverse', 'reverse', (['"""papers_index"""'], {}), "('papers_index')\n", (81465, 81481), False, 'from django.urls import reverse\n'), ((81806, 81829), 'django.urls.reverse', 'reverse', (['"""papers_index"""'], {}), "('papers_index')\n", (81813, 81829), False, 'from django.urls import reverse\n'), ((82150, 82171), 'catalog.models.Paper.inflate', 'Paper.inflate', (['row[0]'], {}), '(row[0])\n', (82163, 82171), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((82300, 82323), 'django.urls.reverse', 'reverse', (['"""papers_index"""'], {}), "('papers_index')\n", (82307, 82323), False, 'from django.urls import reverse\n'), ((82745, 82782), 'django.shortcuts.redirect', 'redirect', (['"""paper_detail"""'], {'id': 'paper_id'}), "('paper_detail', id=paper_id)\n", (82753, 82782), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((83182, 83205), 'catalog.models.Comment.inflate', 'Comment.inflate', (['row[0]'], {}), '(row[0])\n', (83197, 83205), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((83823, 83860), 'django.shortcuts.redirect', 'redirect', (['"""paper_detail"""'], {'id': 'paper_id'}), "('paper_detail', id=paper_id)\n", (83831, 83860), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((84171, 84180), 'catalog.models.Comment', 'Comment', ([], {}), '()\n', (84178, 84180), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((2239, 2260), 'catalog.models.Venue.inflate', 'Venue.inflate', (['row[0]'], {}), '(row[0])\n', (2252, 2260), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((4095, 4185), 'django.shortcuts.render', 'render', (['request', '"""paper_results.html"""', "{'papers': papers, 'form': form, 'message': ''}"], {}), "(request, 'paper_results.html', {'papers': papers, 'form': form,\n 'message': ''})\n", (4101, 4185), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((4540, 4557), 'catalog.models.Paper.nodes.all', 'Paper.nodes.all', ([], {}), '()\n', (4555, 4557), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((7422, 7439), 'catalog.models.Paper.nodes.all', 'Paper.nodes.all', ([], {}), '()\n', (7437, 7439), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((17130, 17224), 'django.shortcuts.render', 'render', (['request', '"""papers_index.html"""', "{'papers': papers, 'form': form, 'message': message}"], {}), "(request, 'papers_index.html', {'papers': papers, 'form': form,\n 'message': message})\n", (17136, 17224), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((21143, 21211), 'django.contrib.messages.add_message', 'messages.add_message', (['request', 'messages.INFO', '"""Link to venue added!"""'], {}), "(request, messages.INFO, 'Link to venue added!')\n", (21163, 21211), False, 'from django.contrib import messages\n'), ((21289, 21326), 'django.shortcuts.redirect', 'redirect', (['"""paper_detail"""'], {'id': 'paper.id'}), "('paper_detail', id=paper.id)\n", (21297, 21326), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((28294, 28315), 'catalog.models.Paper.inflate', 'Paper.inflate', (['row[0]'], {}), '(row[0])\n', (28307, 28315), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((29464, 29529), 'django.contrib.messages.add_message', 'messages.add_message', (['request', 'messages.INFO', '"""Connection Added!"""'], {}), "(request, messages.INFO, 'Connection Added!')\n", (29484, 29529), False, 'from django.contrib import messages\n'), ((29626, 29700), 'django.contrib.messages.add_message', 'messages.add_message', (['request', 'messages.INFO', '"""Papers are already linked!"""'], {}), "(request, messages.INFO, 'Papers are already linked!')\n", (29646, 29700), False, 'from django.contrib import messages\n'), ((37969, 38000), 'django.shortcuts.redirect', 'redirect', (['"""paper_detail"""'], {'id': 'id'}), "('paper_detail', id=id)\n", (37977, 38000), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((41603, 41626), 'django.urls.reverse', 'reverse', (['"""papers_index"""'], {}), "('papers_index')\n", (41610, 41626), False, 'from django.urls import reverse\n'), ((41825, 41846), 'catalog.models.Paper.inflate', 'Paper.inflate', (['row[0]'], {}), '(row[0])\n', (41838, 41846), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((45502, 45592), 'django.shortcuts.render', 'render', (['request', '"""paper_results.html"""', "{'papers': matching_papers, 'message': message}"], {}), "(request, 'paper_results.html', {'papers': matching_papers, 'message':\n message})\n", (45508, 45592), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((65072, 65161), 'django.shortcuts.render', 'render', (['request', '"""datasets.html"""', "{'datasets': datasets, 'form': form, 'message': ''}"], {}), "(request, 'datasets.html', {'datasets': datasets, 'form': form,\n 'message': ''})\n", (65078, 65161), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((66457, 66476), 'catalog.models.Dataset.nodes.all', 'Dataset.nodes.all', ([], {}), '()\n', (66474, 66476), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((67747, 67770), 'catalog.models.Dataset.inflate', 'Dataset.inflate', (['row[0]'], {}), '(row[0])\n', (67762, 67770), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((68828, 68851), 'catalog.models.Dataset.inflate', 'Dataset.inflate', (['row[0]'], {}), '(row[0])\n', (68843, 68851), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((69532, 69588), 'django.shortcuts.render', 'render', (['request', '"""datasets.html"""', "{'datasets': datasets}"], {}), "(request, 'datasets.html', {'datasets': datasets})\n", (69538, 69588), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((70190, 70215), 'django.urls.reverse', 'reverse', (['"""datasets_index"""'], {}), "('datasets_index')\n", (70197, 70215), False, 'from django.urls import reverse\n'), ((71746, 71771), 'django.urls.reverse', 'reverse', (['"""datasets_index"""'], {}), "('datasets_index')\n", (71753, 71771), False, 'from django.urls import reverse\n'), ((71968, 71991), 'catalog.models.Dataset.inflate', 'Dataset.inflate', (['row[0]'], {}), '(row[0])\n', (71983, 71991), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((74146, 74234), 'django.shortcuts.render', 'render', (['request', '"""venues.html"""', "{'venues': venues, 'form': form, 'message': message}"], {}), "(request, 'venues.html', {'venues': venues, 'form': form, 'message':\n message})\n", (74152, 74234), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((75474, 75491), 'catalog.models.Venue.nodes.all', 'Venue.nodes.all', ([], {}), '()\n', (75489, 75491), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((77787, 77837), 'django.shortcuts.render', 'render', (['request', '"""venues.html"""', "{'venues': venues}"], {}), "(request, 'venues.html', {'venues': venues})\n", (77793, 77837), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((78497, 78520), 'django.urls.reverse', 'reverse', (['"""venues_index"""'], {}), "('venues_index')\n", (78504, 78520), False, 'from django.urls import reverse\n'), ((80060, 80083), 'django.urls.reverse', 'reverse', (['"""venues_index"""'], {}), "('venues_index')\n", (80067, 80083), False, 'from django.urls import reverse\n'), ((80278, 80299), 'catalog.models.Venue.inflate', 'Venue.inflate', (['row[0]'], {}), '(row[0])\n', (80291, 80299), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((81283, 81302), 'catalog.models.Comment.nodes.all', 'Comment.nodes.all', ([], {}), '()\n', (81300, 81302), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((81682, 81701), 'catalog.models.Comment.nodes.all', 'Comment.nodes.all', ([], {}), '()\n', (81699, 81701), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((84057, 84080), 'catalog.models.Comment.inflate', 'Comment.inflate', (['row[0]'], {}), '(row[0])\n', (84072, 84080), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((4030, 4051), 'catalog.models.Paper.inflate', 'Paper.inflate', (['row[0]'], {}), '(row[0])\n', (4043, 4051), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((7459, 7476), 'catalog.models.Paper.nodes.all', 'Paper.nodes.all', ([], {}), '()\n', (7474, 7476), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((17065, 17086), 'catalog.models.Paper.inflate', 'Paper.inflate', (['row[0]'], {}), '(row[0])\n', (17078, 17086), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((18888, 18909), 'catalog.models.Venue.inflate', 'Venue.inflate', (['row[0]'], {}), '(row[0])\n', (18901, 18909), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((19201, 19363), 'django.shortcuts.render', 'render', (['request', '"""paper_connect_venue.html"""', "{'form': form, 'venues': venues, 'message':\n 'Found more than one matching venues. Please narrow your search'}"], {}), "(request, 'paper_connect_venue.html', {'form': form, 'venues': venues,\n 'message':\n 'Found more than one matching venues. Please narrow your search'})\n", (19207, 19363), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((27174, 27272), 'django.shortcuts.render', 'render', (['request', '"""paper_connect_author.html"""', "{'form': form, 'people': authors, 'message': ''}"], {}), "(request, 'paper_connect_author.html', {'form': form, 'people':\n authors, 'message': ''})\n", (27180, 27272), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((31534, 31630), 'django.shortcuts.render', 'render', (['request', '"""paper_connect_paper.html"""', "{'form': form, 'papers': papers, 'message': ''}"], {}), "(request, 'paper_connect_paper.html', {'form': form, 'papers': papers,\n 'message': ''})\n", (31540, 31630), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((35856, 36032), 'django.shortcuts.render', 'render', (['request', '"""paper_connect_dataset.html"""', "{'form': form, 'datasets': datasets_found, 'message':\n 'Found more than one matching datasets. Please narrow your search'}"], {}), "(request, 'paper_connect_dataset.html', {'form': form, 'datasets':\n datasets_found, 'message':\n 'Found more than one matching datasets. Please narrow your search'})\n", (35862, 36032), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((40228, 40321), 'django.shortcuts.render', 'render', (['request', '"""paper_connect_code.html"""', "{'form': form, 'codes': codes, 'message': ''}"], {}), "(request, 'paper_connect_code.html', {'form': form, 'codes': codes,\n 'message': ''})\n", (40234, 40321), False, 'from django.shortcuts import render, redirect, get_object_or_404\n'), ((46452, 46475), 'django.urls.reverse', 'reverse', (['"""papers_index"""'], {}), "('papers_index')\n", (46459, 46475), False, 'from django.urls import reverse\n'), ((66498, 66517), 'catalog.models.Dataset.nodes.all', 'Dataset.nodes.all', ([], {}), '()\n', (66515, 66517), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((74009, 74030), 'catalog.models.Venue.inflate', 'Venue.inflate', (['row[0]'], {}), '(row[0])\n', (74022, 74030), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((75511, 75528), 'catalog.models.Venue.nodes.all', 'Venue.nodes.all', ([], {}), '()\n', (75526, 75528), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((77650, 77671), 'catalog.models.Venue.inflate', 'Venue.inflate', (['row[0]'], {}), '(row[0])\n', (77663, 77671), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((81324, 81343), 'catalog.models.Comment.nodes.all', 'Comment.nodes.all', ([], {}), '()\n', (81341, 81343), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((19923, 19944), 'catalog.models.Paper.inflate', 'Paper.inflate', (['row[0]'], {}), '(row[0])\n', (19936, 19944), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((26690, 26767), 'django.urls.reverse', 'reverse', (['"""paper_connect_author_selected"""'], {'kwargs': "{'id': id, 'aid': person.id}"}), "('paper_connect_author_selected', kwargs={'id': id, 'aid': person.id})\n", (26697, 26767), False, 'from django.urls import reverse\n'), ((30989, 31064), 'django.urls.reverse', 'reverse', (['"""paper_connect_paper_selected"""'], {'kwargs': "{'id': id, 'pid': paper.id}"}), "('paper_connect_paper_selected', kwargs={'id': id, 'pid': paper.id})\n", (30996, 31064), False, 'from django.urls import reverse\n'), ((36645, 36666), 'catalog.models.Paper.inflate', 'Paper.inflate', (['row[0]'], {}), '(row[0])\n', (36658, 36666), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((37564, 37634), 'django.contrib.messages.add_message', 'messages.add_message', (['request', 'messages.INFO', '"""Link to dataset added!"""'], {}), "(request, messages.INFO, 'Link to dataset added!')\n", (37584, 37634), False, 'from django.contrib import messages\n'), ((37739, 37818), 'django.contrib.messages.add_message', 'messages.add_message', (['request', 'messages.INFO', '"""Link to dataset already exists!"""'], {}), "(request, messages.INFO, 'Link to dataset already exists!')\n", (37759, 37818), False, 'from django.contrib import messages\n'), ((39804, 39877), 'django.urls.reverse', 'reverse', (['"""paper_connect_code_selected"""'], {'kwargs': "{'id': id, 'cid': code.id}"}), "('paper_connect_code_selected', kwargs={'id': id, 'cid': code.id})\n", (39811, 39877), False, 'from django.urls import reverse\n'), ((10557, 10578), 'catalog.models.Paper.inflate', 'Paper.inflate', (['row[0]'], {}), '(row[0])\n', (10570, 10578), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((10678, 10700), 'catalog.models.Person.inflate', 'Person.inflate', (['row[0]'], {}), '(row[0])\n', (10692, 10700), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((10799, 10820), 'catalog.models.Venue.inflate', 'Venue.inflate', (['row[0]'], {}), '(row[0])\n', (10812, 10820), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((10923, 10946), 'catalog.models.Dataset.inflate', 'Dataset.inflate', (['row[0]'], {}), '(row[0])\n', (10938, 10946), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((11043, 11063), 'catalog.models.Code.inflate', 'Code.inflate', (['row[0]'], {}), '(row[0])\n', (11055, 11063), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((11318, 11339), 'catalog.models.Paper.inflate', 'Paper.inflate', (['row[0]'], {}), '(row[0])\n', (11331, 11339), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((11438, 11460), 'catalog.models.Person.inflate', 'Person.inflate', (['row[0]'], {}), '(row[0])\n', (11452, 11460), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((11558, 11579), 'catalog.models.Venue.inflate', 'Venue.inflate', (['row[0]'], {}), '(row[0])\n', (11571, 11579), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((11681, 11704), 'catalog.models.Dataset.inflate', 'Dataset.inflate', (['row[0]'], {}), '(row[0])\n', (11696, 11704), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((11800, 11820), 'catalog.models.Code.inflate', 'Code.inflate', (['row[0]'], {}), '(row[0])\n', (11812, 11820), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((20480, 20501), 'catalog.models.Venue.inflate', 'Venue.inflate', (['row[0]'], {}), '(row[0])\n', (20493, 20501), False, 'from catalog.models import Paper, Person, Dataset, Venue, Comment, Code\n'), ((57385, 57402), 're.compile', 're.compile', (['"""pdf"""'], {}), "('pdf')\n", (57395, 57402), False, 'import re\n'), ((61909, 61926), 'catalog.forms.PaperImportForm', 'PaperImportForm', ([], {}), '()\n', (61924, 61926), False, 'from catalog.forms import PaperForm, DatasetForm, VenueForm, CommentForm, PaperImportForm\n'), ((61946, 62046), 'django.shortcuts.render', 'render', (['request', '"""paper_form.html"""', "{'form': form, 'message': 'Source website is not supported'}"], {}), "(request, 'paper_form.html', {'form': form, 'message':\n 'Source website is not supported'})\n", (61952, 62046), False, 'from django.shortcuts import render, redirect, get_object_or_404\n')] |
import multiprocessing
debug = False
bind = "0.0.0.0:5000"
pidfile = "gunicorn.pid"
workers = multiprocessing.cpu_count()*2 + 1
worker_class = "gevent"
# daemon=True 在docker中不需要daemon运行,反而会导致看不到gunicorn输出而增加排查问题的难度 | [
"multiprocessing.cpu_count"
] | [((94, 121), 'multiprocessing.cpu_count', 'multiprocessing.cpu_count', ([], {}), '()\n', (119, 121), False, 'import multiprocessing\n')] |
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class MicroblogConfig(AppConfig):
name = 'microblog'
verbose_name = _('Blog')
| [
"django.utils.translation.gettext_lazy"
] | [((167, 176), 'django.utils.translation.gettext_lazy', '_', (['"""Blog"""'], {}), "('Blog')\n", (168, 176), True, 'from django.utils.translation import gettext_lazy as _\n')] |
# Copyright 2014 Google Inc. All Rights Reserved.
"""Implements the command for SSHing into an instance."""
import getpass
from googlecloudsdk.calliope import exceptions
from googlecloudsdk.compute.lib import ssh_utils
from googlecloudsdk.compute.lib import utils
class SSH(ssh_utils.BaseSSHCLICommand):
"""SSH into a virtual machine instance."""
@staticmethod
def Args(parser):
ssh_utils.BaseSSHCLICommand.Args(parser)
parser.add_argument(
'--command',
help='A command to run on the virtual machine.')
ssh_flags = parser.add_argument(
'--ssh-flag',
action='append',
help='Additional flags to be passed to ssh.')
ssh_flags.detailed_help = """\
Additional flags to be passed to *ssh(1)*. It is recommended that flags
be passed using an assignment operator and quotes. This flag will
replace occurences of ``%USER%'' and ``%INSTANCE%'' with their
dereferenced values. Example:
$ {command} example-instance --zone us-central1-a --ssh-flag="-vvv" --ssh-flag="-L 80:%INSTANCE%:80"
is equivalent to passing the flags ``--vvv'' and ``-L
80:192.168.3.11:80'' to *ssh(1)* if the external IP address of
'example-instance' is 192.168.3.11.
"""
parser.add_argument(
'--container',
help="""\
The name of a container inside of the virtual machine instance to
connect to. This only applies to virtual machines that are using
a Google container virtual machine image. For more information,
see link:https://developers.google.com/compute/docs/containers[].
""")
user_host = parser.add_argument(
'user_host',
help='Specifies the instance to SSH into.',
metavar='[USER@]INSTANCE')
user_host.detailed_help = """\
Specifies the instance to SSH into.
``USER'' specifies the username with which to SSH. If omitted,
$USER from the environment is selected.
"""
utils.AddZoneFlag(
parser,
resource_type='instance',
operation_type='connect to')
def Run(self, args):
super(SSH, self).Run(args)
parts = args.user_host.split('@')
if len(parts) == 1:
user = getpass.getuser()
instance = parts[0]
elif len(parts) == 2:
user, instance = parts
else:
raise exceptions.ToolException(
'Expected argument of the form [USER@]INSTANCE; received [{0}].'
.format(args.user_host))
instance_ref = self.CreateZonalReference(instance, args.zone)
external_ip_address = self.GetInstanceExternalIpAddress(instance_ref)
ssh_args = [self.ssh_executable]
if not args.plain:
ssh_args.extend(self.GetDefaultFlags())
# Allocates a tty if no command was provided and a container was provided.
if args.container and not args.command:
ssh_args.append('-t')
if args.ssh_flag:
for flag in args.ssh_flag:
dereferenced_flag = (
flag.replace('%USER%', user)
.replace('%INSTANCE%', external_ip_address))
ssh_args.append(dereferenced_flag)
ssh_args.append(ssh_utils.UserHost(user, external_ip_address))
interactive_ssh = False
if args.container:
ssh_args.append('--')
ssh_args.append('container_exec')
ssh_args.append(args.container)
# Runs the given command inside the given container if --command was
# specified, otherwise runs /bin/sh.
if args.command:
ssh_args.append(args.command)
else:
ssh_args.append('/bin/sh')
elif args.command:
ssh_args.append('--')
ssh_args.append(args.command)
else:
interactive_ssh = True
self.ActuallyRun(args, ssh_args, user, external_ip_address,
interactive_ssh=interactive_ssh)
SSH.detailed_help = {
'brief': 'SSH into a virtual machine instance',
'DESCRIPTION': """\
*{command}* is a thin wrapper around the *ssh(1)* command that
takes care of authentication and the translation of the
instance name into an IP address.
This command ensures that the user's public SSH key is present
in the project's metadata. If the user does not have a public
SSH key, one is generated using *ssh-keygen(1)*.
""",
'EXAMPLES': """\
To SSH into 'example-instance' in zone ``us-central1-a'', run:
$ {command} example-instance --zone us-central1-a
You can also run a command on the virtual machine. For
example, to get a snapshot of the guest's process tree, run:
$ {command} example-instance --zone us-central1-a --command "ps -ejH"
If you are using the Google container virtual machine image, you
can SSH into one of your containers with:
$ {command} example-instance --zone us-central1-a --container CONTAINER
""",
}
| [
"getpass.getuser",
"googlecloudsdk.compute.lib.utils.AddZoneFlag",
"googlecloudsdk.compute.lib.ssh_utils.UserHost",
"googlecloudsdk.compute.lib.ssh_utils.BaseSSHCLICommand.Args"
] | [((394, 434), 'googlecloudsdk.compute.lib.ssh_utils.BaseSSHCLICommand.Args', 'ssh_utils.BaseSSHCLICommand.Args', (['parser'], {}), '(parser)\n', (426, 434), False, 'from googlecloudsdk.compute.lib import ssh_utils\n'), ((2033, 2118), 'googlecloudsdk.compute.lib.utils.AddZoneFlag', 'utils.AddZoneFlag', (['parser'], {'resource_type': '"""instance"""', 'operation_type': '"""connect to"""'}), "(parser, resource_type='instance', operation_type='connect to'\n )\n", (2050, 2118), False, 'from googlecloudsdk.compute.lib import utils\n'), ((2269, 2286), 'getpass.getuser', 'getpass.getuser', ([], {}), '()\n', (2284, 2286), False, 'import getpass\n'), ((3179, 3224), 'googlecloudsdk.compute.lib.ssh_utils.UserHost', 'ssh_utils.UserHost', (['user', 'external_ip_address'], {}), '(user, external_ip_address)\n', (3197, 3224), False, 'from googlecloudsdk.compute.lib import ssh_utils\n')] |
from sklearn.preprocessing import scale
import numpy as np
class GradientDescent:
learning_rate = 0.01
max_iter = 2000
scale = False
new_theta = []
def __init__(self, learning_rate=0.01, max_iter=2000, scale=False):
self.learning_rate = learning_rate
self.max_iter = max_iter
self.scale = scale
def fit(self, X, y):
ones = [1] * len(X)
if self.scale:
X = scale(X)
X = np.transpose(np.concatenate((np.array([ones]).reshape(-1, 1), X), axis=1))
zeroes = [0] * X.shape[0]
theta = np.array([zeroes])
for i in range(self.max_iter):
htheta = np.dot(theta, X)
diff_theta = htheta - y.values
partial_derivative_theta = np.dot(diff_theta, np.transpose(X)) / len(y.values)
theta = theta - self.learning_rate * partial_derivative_theta
self.new_theta.append(theta)
def predict(self, X):
if scale:
X = scale(X)
theta0 = self.new_theta[self.max_iter-1][0][0]
thetas = []
for i in range(1, self.new_theta[self.max_iter-1].shape[1]):
thetas.append(self.new_theta[self.max_iter-1][0][i])
predict = theta0 + (thetas * X).sum(axis=1)
return(predict)
def score(self, X, y):
if scale:
X = scale(X)
pred_y = self.predict(X)
mean_y = y.mean()
ess = sum((y - mean_y) ** 2)
rss = sum((y - pred_y) ** 2)
rsquared = 1 - (rss/ess)
return rsquared | [
"numpy.array",
"numpy.dot",
"numpy.transpose",
"sklearn.preprocessing.scale"
] | [((616, 634), 'numpy.array', 'np.array', (['[zeroes]'], {}), '([zeroes])\n', (624, 634), True, 'import numpy as np\n'), ((467, 475), 'sklearn.preprocessing.scale', 'scale', (['X'], {}), '(X)\n', (472, 475), False, 'from sklearn.preprocessing import scale\n'), ((697, 713), 'numpy.dot', 'np.dot', (['theta', 'X'], {}), '(theta, X)\n', (703, 713), True, 'import numpy as np\n'), ((1036, 1044), 'sklearn.preprocessing.scale', 'scale', (['X'], {}), '(X)\n', (1041, 1044), False, 'from sklearn.preprocessing import scale\n'), ((1406, 1414), 'sklearn.preprocessing.scale', 'scale', (['X'], {}), '(X)\n', (1411, 1414), False, 'from sklearn.preprocessing import scale\n'), ((817, 832), 'numpy.transpose', 'np.transpose', (['X'], {}), '(X)\n', (829, 832), True, 'import numpy as np\n'), ((518, 534), 'numpy.array', 'np.array', (['[ones]'], {}), '([ones])\n', (526, 534), True, 'import numpy as np\n')] |
# Copyright (c) 2013 <NAME>
#
# 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.
"""
Provide wrappers for `tabix <http://sourceforge.net/projects/samtools/files/tabix/>`_
Classes
-------
"""
import os
import luigi
import ratatosk.lib.files.input
from ratatosk.job import JobTask, JobWrapperTask
from ratatosk.jobrunner import DefaultShellJobRunner
from ratatosk.utils import rreplace, fullclassname
from ratatosk.log import get_logger
logger = get_logger()
class InputVcfFile(ratatosk.lib.files.input.InputVcfFile):
pass
class TabixJobRunner(DefaultShellJobRunner):
pass
class TabixJobTask(JobTask):
executable = ""
def job_runner(self):
return TabixJobRunner()
def exe(self):
return self.sub_executable
def main(self):
return None
class Bgzip(TabixJobTask):
sub_executable = luigi.Parameter(default="bgzip")
parent_task = luigi.Parameter(default="ratatosk.lib.variation.tabix.InputVcfFile")
suffix = luigi.Parameter(default=".vcf.gz")
options = luigi.Parameter(default=("-f",))
def args(self):
return [self.input()[0]]
# Since this is such a common operation, add the task here
class BgUnzip(TabixJobTask):
sub_executable = luigi.Parameter(default="bgzip")
parent_task = luigi.Parameter(default="ratatosk.lib.variation.tabix.Bgzip")
suffix = luigi.Parameter(default=".vcf")
def opts(self):
retval = list(self.options)
if not "-d" in retval:
retval += ["-d"]
return retval
def args(self):
return [self.input()[0]]
class Tabix(TabixJobTask):
sub_executable = luigi.Parameter(default="tabix")
parent_task = luigi.Parameter(default="ratatosk.lib.variation.tabix.Bgzip")
suffix = luigi.Parameter(default=".vcf.gz.tbi")
def args(self):
return [self.input()[0]]
class IndexedBgzip(JobWrapperTask):
suffix = luigi.Parameter(default=(".vcf.gz", ".vcf.gz.tbi"), is_list=True)
parent_task = luigi.Parameter(default="ratatosk.lib.variation.tabix.Bgzip")
def requires(self):
zipcls = ratatosk.lib.variation.tabix.Bgzip
indexcls = ratatosk.lib.variation.tabix.Tabix
return [zipcls(target=self.source()[0]),
indexcls(target=rreplace(self.source()[0], zipcls().sfx(), indexcls().sfx(), 1),
parent_task=fullclassname(zipcls))]
| [
"ratatosk.log.get_logger",
"luigi.Parameter",
"ratatosk.utils.fullclassname"
] | [((937, 949), 'ratatosk.log.get_logger', 'get_logger', ([], {}), '()\n', (947, 949), False, 'from ratatosk.log import get_logger\n'), ((1332, 1364), 'luigi.Parameter', 'luigi.Parameter', ([], {'default': '"""bgzip"""'}), "(default='bgzip')\n", (1347, 1364), False, 'import luigi\n'), ((1383, 1451), 'luigi.Parameter', 'luigi.Parameter', ([], {'default': '"""ratatosk.lib.variation.tabix.InputVcfFile"""'}), "(default='ratatosk.lib.variation.tabix.InputVcfFile')\n", (1398, 1451), False, 'import luigi\n'), ((1465, 1499), 'luigi.Parameter', 'luigi.Parameter', ([], {'default': '""".vcf.gz"""'}), "(default='.vcf.gz')\n", (1480, 1499), False, 'import luigi\n'), ((1514, 1546), 'luigi.Parameter', 'luigi.Parameter', ([], {'default': "('-f',)"}), "(default=('-f',))\n", (1529, 1546), False, 'import luigi\n'), ((1711, 1743), 'luigi.Parameter', 'luigi.Parameter', ([], {'default': '"""bgzip"""'}), "(default='bgzip')\n", (1726, 1743), False, 'import luigi\n'), ((1762, 1823), 'luigi.Parameter', 'luigi.Parameter', ([], {'default': '"""ratatosk.lib.variation.tabix.Bgzip"""'}), "(default='ratatosk.lib.variation.tabix.Bgzip')\n", (1777, 1823), False, 'import luigi\n'), ((1837, 1868), 'luigi.Parameter', 'luigi.Parameter', ([], {'default': '""".vcf"""'}), "(default='.vcf')\n", (1852, 1868), False, 'import luigi\n'), ((2111, 2143), 'luigi.Parameter', 'luigi.Parameter', ([], {'default': '"""tabix"""'}), "(default='tabix')\n", (2126, 2143), False, 'import luigi\n'), ((2162, 2223), 'luigi.Parameter', 'luigi.Parameter', ([], {'default': '"""ratatosk.lib.variation.tabix.Bgzip"""'}), "(default='ratatosk.lib.variation.tabix.Bgzip')\n", (2177, 2223), False, 'import luigi\n'), ((2237, 2275), 'luigi.Parameter', 'luigi.Parameter', ([], {'default': '""".vcf.gz.tbi"""'}), "(default='.vcf.gz.tbi')\n", (2252, 2275), False, 'import luigi\n'), ((2385, 2450), 'luigi.Parameter', 'luigi.Parameter', ([], {'default': "('.vcf.gz', '.vcf.gz.tbi')", 'is_list': '(True)'}), "(default=('.vcf.gz', '.vcf.gz.tbi'), is_list=True)\n", (2400, 2450), False, 'import luigi\n'), ((2469, 2530), 'luigi.Parameter', 'luigi.Parameter', ([], {'default': '"""ratatosk.lib.variation.tabix.Bgzip"""'}), "(default='ratatosk.lib.variation.tabix.Bgzip')\n", (2484, 2530), False, 'import luigi\n'), ((2860, 2881), 'ratatosk.utils.fullclassname', 'fullclassname', (['zipcls'], {}), '(zipcls)\n', (2873, 2881), False, 'from ratatosk.utils import rreplace, fullclassname\n')] |
import os,sys
import numpy as np
import random
import matplotlib.pyplot as plt
import seaborn as sns
from copy import deepcopy
import math
import torch
import torch.nn as nn
from tqdm import tqdm
from torch._six import inf
import pandas as pd
from PIL import Image
from sklearn.feature_extraction import image
from arguments import get_args
args = get_args()
def gs_cal(t, x, y, criterion, model, sbatch=20):
# Init
param_R = {}
for name, param in model.named_parameters():
if len(param.size()) <= 1:
continue
name = name.split('.')[:-1]
name = '.'.join(name)
param = param.view(param.size(0), -1)
param_R['{}'.format(name)]=torch.zeros((param.size(0)))
# Compute
model.train()
for i in range(0,x.size(0),sbatch):
b=torch.LongTensor(np.arange(i,np.min([i+sbatch,x.size(0)]))).cuda()
images=x[b]
target=y[b]
# Forward and backward
outputs = model.forward(images, True)[t]
cnt = 0
for idx, j in enumerate(model.act):
j = torch.mean(j, dim=0)
if len(j.size())>1:
j = torch.mean(j.view(j.size(0), -1), dim = 1).abs()
model.act[idx] = j
for name, param in model.named_parameters():
if len(param.size()) <= 1 or 'last' in name or 'downsample' in name:
continue
name = name.split('.')[:-1]
name = '.'.join(name)
param_R[name] += model.act[cnt].abs().detach()*sbatch
cnt+=1
with torch.no_grad():
for key in param_R.keys():
param_R[key]=(param_R[key]/x.size(0))
return param_R
def print_model_report(model):
print('-'*100)
print(model)
print('Dimensions =',end=' ')
count=0
for p in model.parameters():
print(p.size(),end=' ')
count+=np.prod(p.size())
print()
print('Num parameters = %s'%(human_format(count)))
print('-'*100)
return count
def human_format(num):
magnitude=0
while abs(num)>=1000:
magnitude+=1
num/=1000.0
return '%.1f%s'%(num,['','K','M','G','T','P'][magnitude])
def print_optimizer_config(optim):
if optim is None:
print(optim)
else:
print(optim,'=',end=' ')
opt=optim.param_groups[0]
for n in opt.keys():
if not n.startswith('param'):
print(n+':',opt[n],end=', ')
print()
return
########################################################################################################################
def copy_model(model):
for module_ in model.net:
if isinstance(module_, ModuleList):
for linear_ in module_:
linear_.clean()
if isinstance(module_, ReLU) or isinstance(module_, Linear) or isinstance(module_, Conv2d) or isinstance(module_, MaxPool2d) or isinstance(module_, Dropout):
module_.clean()
return deepcopy(model)
def get_model(model):
return deepcopy(model.state_dict())
def set_model_(model,state_dict):
model.load_state_dict(deepcopy(state_dict))
return
def freeze_model(model):
for param in model.parameters():
param.requires_grad = False
return
########################################################################################################################
def compute_conv_output_size(Lin,kernel_size,stride=1,padding=0,dilation=1):
return int(np.floor((Lin+2*padding-dilation*(kernel_size-1)-1)/float(stride)+1))
########################################################################################################################
def compute_mean_std_dataset(dataset):
# dataset already put ToTensor
mean=0
std=0
loader = torch.utils.data.DataLoader(dataset, batch_size=1, shuffle=False)
for image, _ in loader:
mean+=image.mean(3).mean(2)
mean /= len(dataset)
mean_expanded=mean.view(mean.size(0),mean.size(1),1,1).expand_as(image)
for image, _ in loader:
std+=(image-mean_expanded).pow(2).sum(3).sum(2)
std=(std/(len(dataset)*image.size(2)*image.size(3)-1)).sqrt()
return mean, std
########################################################################################################################
def fisher_matrix_diag(t,x,y,model,criterion,sbatch=20):
# Init
fisher={}
for n,p in model.named_parameters():
fisher[n]=0*p.data
# Compute
model.train()
criterion = torch.nn.CrossEntropyLoss()
for i in tqdm(range(0,x.size(0),sbatch),desc='Fisher diagonal',ncols=100,ascii=True):
b=torch.LongTensor(np.arange(i,np.min([i+sbatch,x.size(0)]))).cuda()
images=x[b]
target=y[b]
# Forward and backward
model.zero_grad()
outputs = model.forward(images)[t]
loss= criterion(outputs, target)
loss.backward()
# Get gradients
for n,p in model.named_parameters():
if p.grad is not None:
fisher[n]+=sbatch*p.grad.data.pow(2)
# Mean
with torch.no_grad():
for n,_ in model.named_parameters():
fisher[n]=fisher[n]/x.size(0)
return fisher
def fisher_matrix_diag_emp(t,x,y,model,criterion,sbatch=20):
# Init
fisher={}
for n,p in model.named_parameters():
fisher[n]=0*p.data
fo={}
for n,p in model.named_parameters():
fo[n]=0*p.data
# Compute
model.train()
criterion = torch.nn.CrossEntropyLoss()
for i in tqdm(range(0,x.size(0),sbatch),desc='Fisher diagonal',ncols=100,ascii=True):
b=torch.LongTensor(np.arange(i,np.min([i+sbatch,x.size(0)]))).cuda()
images=x[b]
target=y[b]
# Forward and backward
model.zero_grad()
outputs = model.forward(images)[t]
loss= criterion(outputs, target)
loss.backward()
# Get gradients
for n,p in model.named_parameters():
if p.grad is not None:
fisher[n]+=sbatch*p.grad.data.pow(2)
fo[n] += sbatch * p.grad.data
# Mean
with torch.no_grad():
for n,_ in model.named_parameters():
fisher[n]=fisher[n]/x.size(0)
fo[n] = fo[n] / x.size(0)
return fisher, fo
########################################################################################################################
def cross_entropy(outputs,targets,exp=1,size_average=True,eps=1e-5):
out=torch.nn.functional.softmax(outputs)
tar=torch.nn.functional.softmax(targets)
if exp!=1:
out=out.pow(exp)
out=out/out.sum(1).view(-1,1).expand_as(out)
tar=tar.pow(exp)
tar=tar/tar.sum(1).view(-1,1).expand_as(tar)
out=out+eps/out.size(1)
out=out/out.sum(1).view(-1,1).expand_as(out)
ce=-(tar*out.log()).sum(1)
if size_average:
ce=ce.mean()
return ce
########################################################################################################################
def set_req_grad(layer,req_grad):
if hasattr(layer,'weight'):
layer.weight.requires_grad=req_grad
if hasattr(layer,'bias'):
layer.bias.requires_grad=req_grad
return
########################################################################################################################
def is_number(s):
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
return False
########################################################################################################################
def clip_relevance_norm_(parameters, max_norm, norm_type=2):
r"""Clips gradient norm of an iterable of parameters.
The norm is computed over all gradients together, as if they were
concatenated into a single vector. Gradients are modified in-place.
Arguments:
parameters (Iterable[Tensor] or Tensor): an iterable of Tensors or a
single Tensor that will have gradients normalized
max_norm (float or int): max norm of the gradients
norm_type (float or int): type of the used p-norm. Can be ``'inf'`` for
infinity norm.
Returns:
Total norm of the parameters (viewed as a single vector).
"""
if isinstance(parameters, torch.Tensor):
parameters = [parameters]
parameters = list(filter(lambda p: p is not None, parameters))
max_norm = float(max_norm)
norm_type = float(norm_type)
if norm_type == inf:
total_norm = max(p.data.abs().max() for p in parameters)
else:
total_norm = 0
for p in parameters:
param_norm = p.data.norm(norm_type)
total_norm += param_norm.item() ** norm_type
total_norm = total_norm ** (1. / norm_type)
clip_coef = max_norm / (total_norm + 1e-6)
if clip_coef < 1:
for p in parameters:
p.data.mul_(clip_coef)
return total_norm
######################################################################################################################## | [
"copy.deepcopy",
"torch.nn.CrossEntropyLoss",
"sklearn.feature_extraction.image.mean",
"torch.mean",
"torch.no_grad",
"torch.utils.data.DataLoader",
"arguments.get_args",
"unicodedata.numeric",
"sklearn.feature_extraction.image.size",
"torch.nn.functional.softmax"
] | [((348, 358), 'arguments.get_args', 'get_args', ([], {}), '()\n', (356, 358), False, 'from arguments import get_args\n'), ((2982, 2997), 'copy.deepcopy', 'deepcopy', (['model'], {}), '(model)\n', (2990, 2997), False, 'from copy import deepcopy\n'), ((3781, 3846), 'torch.utils.data.DataLoader', 'torch.utils.data.DataLoader', (['dataset'], {'batch_size': '(1)', 'shuffle': '(False)'}), '(dataset, batch_size=1, shuffle=False)\n', (3808, 3846), False, 'import torch\n'), ((4507, 4534), 'torch.nn.CrossEntropyLoss', 'torch.nn.CrossEntropyLoss', ([], {}), '()\n', (4532, 4534), False, 'import torch\n'), ((5486, 5513), 'torch.nn.CrossEntropyLoss', 'torch.nn.CrossEntropyLoss', ([], {}), '()\n', (5511, 5513), False, 'import torch\n'), ((6476, 6512), 'torch.nn.functional.softmax', 'torch.nn.functional.softmax', (['outputs'], {}), '(outputs)\n', (6503, 6512), False, 'import torch\n'), ((6521, 6557), 'torch.nn.functional.softmax', 'torch.nn.functional.softmax', (['targets'], {}), '(targets)\n', (6548, 6557), False, 'import torch\n'), ((1585, 1600), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (1598, 1600), False, 'import torch\n'), ((3122, 3142), 'copy.deepcopy', 'deepcopy', (['state_dict'], {}), '(state_dict)\n', (3130, 3142), False, 'from copy import deepcopy\n'), ((5085, 5100), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (5098, 5100), False, 'import torch\n'), ((6110, 6125), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (6123, 6125), False, 'import torch\n'), ((7477, 7499), 'unicodedata.numeric', 'unicodedata.numeric', (['s'], {}), '(s)\n', (7496, 7499), False, 'import unicodedata\n'), ((1090, 1110), 'torch.mean', 'torch.mean', (['j'], {'dim': '(0)'}), '(j, dim=0)\n', (1100, 1110), False, 'import torch\n'), ((3889, 3902), 'sklearn.feature_extraction.image.mean', 'image.mean', (['(3)'], {}), '(3)\n', (3899, 3902), False, 'from sklearn.feature_extraction import image\n'), ((4139, 4152), 'sklearn.feature_extraction.image.size', 'image.size', (['(3)'], {}), '(3)\n', (4149, 4152), False, 'from sklearn.feature_extraction import image\n'), ((4125, 4138), 'sklearn.feature_extraction.image.size', 'image.size', (['(2)'], {}), '(2)\n', (4135, 4138), False, 'from sklearn.feature_extraction import image\n')] |
# -*- coding: utf-8 -*-
"""
@author: miko
"""
from sklearn.feature_extraction import DictVectorizer
import csv
from sklearn import tree
from sklearn import preprocessing
from sklearn.externals.six import StringIO
import numpy as np
np.set_printoptions(threshold = 1e6)#设置打印数量的阈值
# Read in the csv file and put features into list of dict and list of class label
allElectronicsData = open(r'D:\development\DailyImprove\July机器学习与深度学习\(Part One)深度学习基础\代码与素材\代码与素材(1)\01DTree\AllElectronics.csv', 'r')
reader = csv.reader(allElectronicsData)
#headers = reader.next()
headers = next(reader)
print(headers)
print("~"*10+"headers end"+"~"*10)
featureList = []
labelList = []
for row in reader: # 遍历每一列
labelList.append(row[len(row)-1]) # 标签列表
rowDict = {} # 每一行的所有特征放入一个字典
for i in range(1, len(row)-1): # 左闭右开 遍历从age到credit_rating
rowDict[headers[i]] = row[i] # 字典的赋值
featureList.append(rowDict) #将每一行的特征字典装入特征列表内
print(featureList)
print("~"*10+"featureList end"+"~"*10)
# Vetorize features
vec = DictVectorizer() # Vectorizer 矢量化
dummyX = vec.fit_transform(featureList).toarray()
print("dummyX: " + str(dummyX))
print(vec.get_feature_names())
print("~"*10+"dummyX end"+"~"*10)
print("labelList: " + str(labelList))
print("~"*10+"labelList end"+"~"*10)
# vectorize class labels
lb = preprocessing.LabelBinarizer()
dummyY = lb.fit_transform(labelList)
print("dummyY: " + str(dummyY))
print("~"*10+"dummyY end"+"~"*10)
# Using decision tree for classification
# clf = tree.DecisionTreeClassifier()
clf = tree.DecisionTreeClassifier(criterion='entropy') # 标准 熵
clf = clf.fit(dummyX, dummyY)
print("clf: " + str(clf))
# Visualize model
with open("allElectronicInformationGainOri.dot", 'w') as f:
# 输出到dot文件里,安装 Graphviz软件后,可使用 dot -Tpdf allElectronicInformationGainOri.dot -o outpu.pdf 命令 转化dot文件至pdf可视化决策树
f = tree.export_graphviz(clf, feature_names=vec.get_feature_names(), out_file=f)
oneRowX = dummyX[0, :]
print("oneRowX: " + str(oneRowX))
newRowX = oneRowX
newRowX[0] = 1
newRowX[2] = 0
print("newRowX: " + str(newRowX))
predictedY = clf.predict(newRowX)
print("predictedY: " + str(predictedY))
| [
"sklearn.preprocessing.LabelBinarizer",
"sklearn.feature_extraction.DictVectorizer",
"sklearn.tree.DecisionTreeClassifier",
"csv.reader",
"numpy.set_printoptions"
] | [((236, 276), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'threshold': '(1000000.0)'}), '(threshold=1000000.0)\n', (255, 276), True, 'import numpy as np\n'), ((512, 542), 'csv.reader', 'csv.reader', (['allElectronicsData'], {}), '(allElectronicsData)\n', (522, 542), False, 'import csv\n'), ((1073, 1089), 'sklearn.feature_extraction.DictVectorizer', 'DictVectorizer', ([], {}), '()\n', (1087, 1089), False, 'from sklearn.feature_extraction import DictVectorizer\n'), ((1365, 1395), 'sklearn.preprocessing.LabelBinarizer', 'preprocessing.LabelBinarizer', ([], {}), '()\n', (1393, 1395), False, 'from sklearn import preprocessing\n'), ((1586, 1634), 'sklearn.tree.DecisionTreeClassifier', 'tree.DecisionTreeClassifier', ([], {'criterion': '"""entropy"""'}), "(criterion='entropy')\n", (1613, 1634), False, 'from sklearn import tree\n')] |
# -*- coding: utf-8 -*-
"""
Bot behavior
"""
from irc3 import plugin, event, rfc
from irc3.plugins.cron import cron
from lxml import html
import aiohttp
import random
import re
@plugin
class Behaviors(object):
"""
Defines bot's behavior by scheduling actions or handling channel events
"""
def __init__(self, bot):
self.bot = bot
# List of rules for channel messages
# Each item has a tuple containing an RE and a reference to the
# procedure to be executed
self.channel_rules = self.compile_rules([
('(https?://[^ \t>\n\r\x01-\x1f]+)', self.handle_url),
])
@classmethod
def reload(cls, old):
print("reloading plugin {}".format(cls.__name__))
return cls(old.bot)
def compile_rules(self, rules):
"""
Compile a list of RE and return a new list with
each RE compiled and its procedure reference
"""
if type(rules) is list:
return [(re.compile(rule, re.UNICODE), func)
for (rule, func) in rules]
else:
return None
# Here we can schedule something to be said or made in a specific time
@cron('0 9 * * 1-5')
def good_morning(self):
"""
Says something in the morning at work days
"""
feeling_sleepy = [
'Good morning',
'Good morning fellas',
'Morning',
'Hello everyone',
'I definitely need a coffee. Oh, hello btw.'
]
to_say = random.choice(feeling_sleepy)
for channel in list(self.bot.channels):
self.bot.privmsg(channel, to_say)
@cron('0 12 * * 1-5')
def lunch_time(self):
"""
Say something at 12 am at work days
"""
feeling_hungry = ['Lunch time', 'I\'m gonna get something to eat']
to_say = random.choice(feeling_hungry)
for channel in list(self.bot.channels):
self.bot.privmsg(channel, to_say)
# Here we can handle channel events to trigger something to be said or made
@event(rfc.JOIN)
def say_hi(self, mask=None, channel=None):
"""
Say hi for everyone who join the channel
"""
if self.bot.nick != mask.nick:
# initialize greeting message
message = '%s: Hi!' % mask.nick
# them create Redis key that should store
# greetings for these nick and channel
key = 'greetings:%s:%s' % (
channel.replace('#', ''),
mask.nick.lower())
# if there was at least one greeting use
# these instead default message
self.bot.db.SIGINT()
greetings = self.bot.db.get(key)
if greetings is not None:
greeting = random.choice(greetings['greetings'].splitlines())
message = '%s: %s' % (mask.nick, greeting)
self.bot.privmsg(channel, message)
@event(rfc.PRIVMSG)
async def handle_message(self, mask=None, event=None, target=None, data=None):
"""
Handle channel messages
"""
if self.channel_rules and type(self.channel_rules) is list:
try:
# Check channel rules looking for some nice interaction
# If at least one rule match with the channel message execute
# it's callback
for rule, func in self.channel_rules:
match = rule.search(data)
if match:
await func(target, match.group(1).encode('utf-8'))
except Exception as e:
print(e)
self.bot.privmsg(target, 'Booom shakalaka')
async def handle_url(self, target, url):
"""
Load URL address and send its web page title back to the
channel
"""
# MIME Type Handling functions
def handle_text(target, subtype, data, charset):
try:
content = str(data, encoding=charset)
except UnicodeDecodeError as e:
# It's still possible that part of the site processing changes
# the encoding (i.e. ascii animations). Hence we try to find the
# title within the range with correct charset
content = str(data[:e.end-1], encoding=charset)
page = html.fromstring(content)
title = page.findtext('.//title')
if title is not None:
self.bot.privmsg(target, ('[%s]' % title.strip()))
def handle_image(target, subtype, data):
self.bot.privmsg(target, 'Looks like an image')
def handle_audio(target, subtype, data):
self.bot.privmsg(target, 'Do you know I\'m deaf right?')
def handle_video(target, subtype, data):
self.bot.privmsg(target, 'For God sake I\'m blind')
def handle_default(target, subtype, data):
self.bot.privmsg(target, 'What kind of weed is that?')
# MIME Type dict
type_handlers = {
u'text': handle_text,
u'image': handle_image,
u'audio': handle_audio,
u'video': handle_video
}
# First of all load the page
async with aiohttp.ClientSession() as session:
async with session.get(url.decode('utf-8')) as request:
# Extract mime type
rule = re.compile('^(\w+)/([\w\-\+]+)( *;.*)?$')
match = rule.search(request.headers['CONTENT-TYPE'])
if not match:
self.bot.privmsg(
target,
'My sources say that this links does not exists')
return
mime_type = match.group(1)
subtype = match.group(2)
# Then parses its HTML and search for the title
data = await request.read()
# Handle content
if mime_type in type_handlers:
if mime_type == u'text':
type_handlers[mime_type](target, subtype, data, request.charset)
else:
type_handlers[mime_type](target, subtype, data)
else:
self.handle_default(target, subtype, data)
| [
"aiohttp.ClientSession",
"random.choice",
"re.compile",
"lxml.html.fromstring",
"irc3.plugins.cron.cron",
"irc3.event"
] | [((1210, 1229), 'irc3.plugins.cron.cron', 'cron', (['"""0 9 * * 1-5"""'], {}), "('0 9 * * 1-5')\n", (1214, 1229), False, 'from irc3.plugins.cron import cron\n'), ((1695, 1715), 'irc3.plugins.cron.cron', 'cron', (['"""0 12 * * 1-5"""'], {}), "('0 12 * * 1-5')\n", (1699, 1715), False, 'from irc3.plugins.cron import cron\n'), ((2118, 2133), 'irc3.event', 'event', (['rfc.JOIN'], {}), '(rfc.JOIN)\n', (2123, 2133), False, 'from irc3 import plugin, event, rfc\n'), ((3012, 3030), 'irc3.event', 'event', (['rfc.PRIVMSG'], {}), '(rfc.PRIVMSG)\n', (3017, 3030), False, 'from irc3 import plugin, event, rfc\n'), ((1564, 1593), 'random.choice', 'random.choice', (['feeling_sleepy'], {}), '(feeling_sleepy)\n', (1577, 1593), False, 'import random\n'), ((1906, 1935), 'random.choice', 'random.choice', (['feeling_hungry'], {}), '(feeling_hungry)\n', (1919, 1935), False, 'import random\n'), ((4444, 4468), 'lxml.html.fromstring', 'html.fromstring', (['content'], {}), '(content)\n', (4459, 4468), False, 'from lxml import html\n'), ((5339, 5362), 'aiohttp.ClientSession', 'aiohttp.ClientSession', ([], {}), '()\n', (5360, 5362), False, 'import aiohttp\n'), ((5502, 5547), 're.compile', 're.compile', (['"""^(\\\\w+)/([\\\\w\\\\-\\\\+]+)( *;.*)?$"""'], {}), "('^(\\\\w+)/([\\\\w\\\\-\\\\+]+)( *;.*)?$')\n", (5512, 5547), False, 'import re\n'), ((1007, 1035), 're.compile', 're.compile', (['rule', 're.UNICODE'], {}), '(rule, re.UNICODE)\n', (1017, 1035), False, 'import re\n')] |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf import settings
from django.core import validators
from django.db import models
from django.db.models import fields as django_fields
from django.db.models.signals import pre_save, post_save
from django.dispatch import receiver
from django.utils import six
from django.utils.translation import ugettext_lazy as _
from dirtyfields import DirtyFieldsMixin
from ..text import slugify, downgrading_slugify, django_slugify
if six.PY3:
from functools import reduce
SLUG_HELP = _("Kurzfassung des Namens für die Adresszeile im Browser. Vorzugsweise englisch, keine Umlaute, nur Bindestrich als Sonderzeichen.")
slug_re = validators._lazy_re_compile(r'^[-a-z0-9]+\Z')
validate_downgraded_slug = validators.RegexValidator(
slug_re,
_("Enter a valid 'slug' consisting of lower-case letters, numbers or hyphens."),
'invalid'
)
class AutoSlugField(django_fields.SlugField):
"""
SlugField which optionally populates the value and/or makes sure that
the value is unique. By default as stricter slugify function is used.
populate_from: Field name
unique_slug: Boolean, automatically make the field value unique
"""
def __init__(self, *args, **kwargs):
kwargs.setdefault('max_length', 50)
kwargs.setdefault('help_text', SLUG_HELP)
if 'populate_from' in kwargs:
self.populate_from = kwargs.pop('populate_from')
self.unique_slug = kwargs.pop('unique_slug', False)
# FIXME Enforce unique=True
# if self.unique_slug:
# kwargs['unique'] = True
# TODO Refactor: We need a sibling FormField which also does our pre_save work and then validates correctly (called from Model.clean_fields)
super(AutoSlugField, self).__init__(*args, **kwargs)
def slugify(self, value):
return slugify(value)
def pre_save(self, model_instance, add):
value = getattr(model_instance, self.attname)
if not value:
if hasattr(self, 'populate_from'):
if callable(self.populate_from):
value = self.populate_from(model_instance, self)
else:
# Follow dotted path (e.g. "occupation.corporation.name")
value = reduce(lambda obj, attr: getattr(obj, attr),
self.populate_from.split("."), model_instance)
if callable(value):
value = value()
value = self.slugify(value)
if not value and not self.blank:
value = model_instance._meta.model_name
if self.unique_slug:
# TODO Move import to top of file once AutoSlugField is removed from shared.utils.fields and we no longer have a circular import
from ..fields import uniquify_field_value
return uniquify_field_value(
model_instance, self.name, value, max_length=self.max_length)
else:
return value
class DowngradingSlugField(AutoSlugField):
"""
SlugField which allows only lowercase ASCII characters and the dash,
automatically downgrading/replacing the entered content.
"""
default_validators = [validate_downgraded_slug]
def __init__(self, *args, **kwargs):
kwargs['allow_unicode'] = False
super(DowngradingSlugField, self).__init__(*args, **kwargs)
def slugify(self, value):
return downgrading_slugify(value)
def to_python(self, value):
# Downgrade immediately so that validators work
value = super().to_python(value)
return self.slugify(value)
def formfield(self, **kwargs):
# Remove the slug validator from the form field so that we can modify
# the field value in the model
field = super().formfield(**kwargs)
if field.default_validators:
try:
field.validators.remove(field.default_validators[0])
except ValueError:
pass
return field
class SlugTreeMixin(DirtyFieldsMixin, models.Model):
"""
Expects a `slug` and a `parent` field.
`has_url`: The node itself has an URL. It is possible that a node does
node have an URL, but its children have.
Maintains the `slug_path` field of the node and its children, watching if
either the `slug`, `parent` or `has_url` fields have changed.
"""
slug_path = models.CharField(_("URL path"),
unique=True, max_length=2000, editable=False)
# TODO Add validator to slug_path?
# validators=[
# RegexValidator(
# regex=r"^/(|.+/)$",
# message=_("Path must start and end with a slash (/)."),
# )
# ],
# TODO Make slug_path manually overridable (see feincms3 -> use_static_path)
has_url = models.BooleanField(_("has webaddress"), default=True)
FIELDS_TO_CHECK = ['slug', 'parent', 'has_url']
class Meta:
abstract = True
def _get_slug_path(self):
if self.pk:
ancestors = self.get_ancestors(include_self=False).filter(has_url=True).values_list('slug', flat=True)
parts = list(ancestors)
else:
parts = []
if self.slug:
parts += [self.slug]
return "/".join(parts)
def _rebuild_descendants_slug_path(self):
for p in self.get_descendants():
p.slug_path = p._get_slug_path()
p.save()
@receiver(pre_save)
def slug_tree_mixin_pre_save(sender, instance, **kwargs):
if isinstance(instance, SlugTreeMixin):
# FIXME: find a way to not always call this
instance.slug = instance._meta.get_field('slug').pre_save(instance, False)
instance.slug_path = instance._get_slug_path()
@receiver(post_save)
def slug_tree_mixin_post_save(sender, instance, **kwargs):
if isinstance(instance, SlugTreeMixin):
if kwargs.get('created'):
# Always get a new database instance before saving again
# or MPTTModel.save() will interpret the newly .save as
# not allowed tree move action
# FIXME Not clear if this is a proper solution -> get rid of the slug_path stuff altogether
instance_copy = type(instance).objects.get(pk=instance.pk)
instance_copy.slug_path = instance_copy._get_slug_path()
if 'slug_path' in instance_copy.get_dirty_fields().keys():
instance_copy.save()
elif instance.get_dirty_fields().keys() & {'slug_path'}:
instance._rebuild_descendants_slug_path()
| [
"django.dispatch.receiver",
"django.utils.translation.ugettext_lazy",
"django.core.validators._lazy_re_compile"
] | [((561, 698), 'django.utils.translation.ugettext_lazy', '_', (['"""Kurzfassung des Namens für die Adresszeile im Browser. Vorzugsweise englisch, keine Umlaute, nur Bindestrich als Sonderzeichen."""'], {}), "('Kurzfassung des Namens für die Adresszeile im Browser. Vorzugsweise englisch, keine Umlaute, nur Bindestrich als Sonderzeichen.'\n )\n", (562, 698), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((706, 751), 'django.core.validators._lazy_re_compile', 'validators._lazy_re_compile', (['"""^[-a-z0-9]+\\\\Z"""'], {}), "('^[-a-z0-9]+\\\\Z')\n", (733, 751), False, 'from django.core import validators\n'), ((5482, 5500), 'django.dispatch.receiver', 'receiver', (['pre_save'], {}), '(pre_save)\n', (5490, 5500), False, 'from django.dispatch import receiver\n'), ((5796, 5815), 'django.dispatch.receiver', 'receiver', (['post_save'], {}), '(post_save)\n', (5804, 5815), False, 'from django.dispatch import receiver\n'), ((823, 902), 'django.utils.translation.ugettext_lazy', '_', (['"""Enter a valid \'slug\' consisting of lower-case letters, numbers or hyphens."""'], {}), '("Enter a valid \'slug\' consisting of lower-case letters, numbers or hyphens.")\n', (824, 902), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((4478, 4491), 'django.utils.translation.ugettext_lazy', '_', (['"""URL path"""'], {}), "('URL path')\n", (4479, 4491), True, 'from django.utils.translation import ugettext_lazy as _\n'), ((4871, 4890), 'django.utils.translation.ugettext_lazy', '_', (['"""has webaddress"""'], {}), "('has webaddress')\n", (4872, 4890), True, 'from django.utils.translation import ugettext_lazy as _\n')] |
import unittest
from forestgame.colour import colour_to_hex
class ToHexTest(unittest.TestCase):
def test_convert_solid_black(self):
hex_code = colour_to_hex((0, 0, 0))
self.assertEqual(hex_code, "#000000")
def test_convert_solid_whex_codeite(self):
hex_code = colour_to_hex((255, 255, 255))
self.assertEqual(hex_code, "#FFFFFF")
def test_convert_solid_red(self):
hex_code = colour_to_hex((255, 0, 0))
self.assertEqual(hex_code, "#FF0000")
def test_convert_solid_green(self):
hex_code = colour_to_hex((0, 255, 0))
self.assertEqual(hex_code, "#00FF00")
def test_convert_solid_blue(self):
hex_code = colour_to_hex((0, 0, 255))
self.assertEqual(hex_code, "#0000FF")
def test_convert_low_values(self):
hex_code = colour_to_hex((15, 15, 15))
self.assertEqual(hex_code, "#0F0F0F")
| [
"forestgame.colour.colour_to_hex"
] | [((151, 175), 'forestgame.colour.colour_to_hex', 'colour_to_hex', (['(0, 0, 0)'], {}), '((0, 0, 0))\n', (164, 175), False, 'from forestgame.colour import colour_to_hex\n'), ((279, 309), 'forestgame.colour.colour_to_hex', 'colour_to_hex', (['(255, 255, 255)'], {}), '((255, 255, 255))\n', (292, 309), False, 'from forestgame.colour import colour_to_hex\n'), ((404, 430), 'forestgame.colour.colour_to_hex', 'colour_to_hex', (['(255, 0, 0)'], {}), '((255, 0, 0))\n', (417, 430), False, 'from forestgame.colour import colour_to_hex\n'), ((527, 553), 'forestgame.colour.colour_to_hex', 'colour_to_hex', (['(0, 255, 0)'], {}), '((0, 255, 0))\n', (540, 553), False, 'from forestgame.colour import colour_to_hex\n'), ((649, 675), 'forestgame.colour.colour_to_hex', 'colour_to_hex', (['(0, 0, 255)'], {}), '((0, 0, 255))\n', (662, 675), False, 'from forestgame.colour import colour_to_hex\n'), ((771, 798), 'forestgame.colour.colour_to_hex', 'colour_to_hex', (['(15, 15, 15)'], {}), '((15, 15, 15))\n', (784, 798), False, 'from forestgame.colour import colour_to_hex\n')] |
from setuptools import setup
NAME = 'XOR_CheckSum_zsd'
VERSION = '1.0.7'
URL = 'https://github.com/zhangsheng377/XOR_CheckSum_zsd'
KEYWORDS = 'XOR checksum string zsd'
EMAIL = '<EMAIL>'
DESCRIPTION = 'XOR_CheckSum tools'
LONG_DESCRIPTION = '''
\>\>\> from XOR_CheckSum import xor_checksum_string
\>\>\> xor_checksum_string('CCICA,0,00')
123
\>\>\> hex(xor_checksum_string('CCICA,0,00'))
'0x7b'
\>\>\> hex(xor_checksum_string('CCICA,0,00', encoding="utf-8"))
'0x7b'
\>\>\> hex(xor_checksum_string('CCICA,0,00', encoding="utf-16"))
'0x7a'
'''
REQUIRES = []
PACKAGES = ['XOR_CheckSum']
setup(
name=NAME,
author='zhangsheng377',
license='MIT',
zip_safe=False,
url=URL,
version=VERSION,
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
author_email=EMAIL,
keywords=KEYWORDS,
install_requires=REQUIRES,
packages=PACKAGES,
classifiers=[
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
],
)
| [
"setuptools.setup"
] | [((593, 1119), 'setuptools.setup', 'setup', ([], {'name': 'NAME', 'author': '"""zhangsheng377"""', 'license': '"""MIT"""', 'zip_safe': '(False)', 'url': 'URL', 'version': 'VERSION', 'description': 'DESCRIPTION', 'long_description': 'LONG_DESCRIPTION', 'author_email': 'EMAIL', 'keywords': 'KEYWORDS', 'install_requires': 'REQUIRES', 'packages': 'PACKAGES', 'classifiers': "['Programming Language :: Python', 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6']"}), "(name=NAME, author='zhangsheng377', license='MIT', zip_safe=False, url\n =URL, version=VERSION, description=DESCRIPTION, long_description=\n LONG_DESCRIPTION, author_email=EMAIL, keywords=KEYWORDS,\n install_requires=REQUIRES, packages=PACKAGES, classifiers=[\n 'Programming Language :: Python', 'Programming Language :: Python :: 2',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6'])\n", (598, 1119), False, 'from setuptools import setup\n')] |
from django.shortcuts import redirect
def index(request):
return redirect('/home/') | [
"django.shortcuts.redirect"
] | [((68, 86), 'django.shortcuts.redirect', 'redirect', (['"""/home/"""'], {}), "('/home/')\n", (76, 86), False, 'from django.shortcuts import redirect\n')] |
import os, sys
import logging
import weakref
import pygame
from .resourceLoaders import *
class ResourceError(Exception):
pass
_GAME_PATH=calculate_real_path(os.path.dirname(sys.argv[0]))
def _BuildLogger():
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
log_format = logging.Formatter("[%(levelname)s : %(asctime)s] %(message)s")
log_handler = logging.FileHandler(join_path(_GAME_PATH, "logs/gbe.log"))
log_handler.setFormatter(log_format)
logger.addHandler(log_handler)
return logger
_l = _BuildLogger()
_RESOURCES={}
def define_resource_type(rtype, sub_path, loader_fn, saver_fn=None):
global _RESOURCES, _GAME_PATH, join_path
if rtype in _RESOURCES:
_l.error("Resource '{}' already defined.".format(rtype))
return
fullpath = join_path(_GAME_PATH, sub_path)
if not os.path.isdir(fullpath):
_l.warning("'{}' is not a valid directory.".format(sub_path))
if not callable(loader_fn):
raise ResourceError("Expected a callable as the resource loader.")
_RESOURCES[rtype]={"r":[], "loader":loader_fn, "saver":saver_fn, "path":fullpath}
_l.info("Added resource type '{}' with search path '{}'.".format(rtype, sub_path))
def configure(conf):
global _RESOURCES, join_path
if not isinstance(conf, dict):
raise TypeError("Expected a dictionary.")
for key in conf:
if key in _RESOURCES:
fullpath = join_path(_GAME_PATH, conf[key])
if not os.path.isdir(fullpath):
_l.warning("'{}' is not a valid directory.".format(conf[key]))
_RESOURCES[key]["path"] = fullpath
_RESOURCES[key]["r"] = [] # Completely drop old list.
class ResourceManager:
def __init__(self):
pass
@property
def game_path(self):
global _GAME_PATH
return _GAME_PATH
@property
def resource_types(self):
global _RESOURCES
rtypes = []
for key in _RESOURCES:
rtypes.append(key)
return rtypes
def _getResourceDict(self, rtype, src):
global _RESOURCES
if rtype in _RESOURCES:
for r in _RESOURCES[rtype]["r"]:
if r["src"] == src:
return r
return None
def is_valid(self, rtype, src):
global _RESOURCES
if rtype in _RESOURCES:
return file_exists(join_path(_RESOURCES[rtype]["path"], src))
return false
def has(self, rtype, src):
return (self._getResourceDict(rtype, src) is not None)
def store(self, rtype, src):
global _RESOURCES
if rtype not in _RESOURCES:
raise ResourceError("Unknown resource type '{}'.".format(rtype))
if self._getResourceDict(rtype, src) == None:
_RESOURCES[rtype]["r"].append({"src":src, "instance":None, "locked":False})
return self
def remove(self, rtype, src):
global _RESOURCES
d = self._getResourceDict(rtype, src)
if d is None:
raise ResourceError("No '{}' resource '{}' stored.".format(rtype, src))
_RESOURCES[rtype]["r"].remove(d)
return self
def clear(self, rtype, src, ignore_lock=False):
d = self._getResourceDict(rtype, src)
if d is None:
raise ResourceError("No '{}' resource '{}' stored.".format(rtype, src))
if d["locked"] == False or ignore_lock == True:
d["instance"] = None
return self
def get(self, rtype, src, params={}):
global _RESOURCES
if rtype not in _RESOURCES:
raise ResourceError("Unknown resource type '{}'.".format(rtype))
d = self._getResourceDict(rtype, src)
if d is None:
raise ResourceError("No '{}' resource '{}' stored.".format(rtype, src))
if d["instance"] is None:
loader = _RESOURCES[rtype]["loader"]
filename = join_path(_RESOURCES[rtype]["path"], src)
try:
d["instance"] = loader(filename, params)
except Exception as e:
raise e
_l.error("{}".format(e))
return None
return weakref.ref(d["instance"])
def load(self, rtype, src, params={}):
global _RESOURCES
if rtype not in _RESOURCES:
raise ResourceError("Unknown resource type '{}'.".format(rtype))
loader = _RESOURCES[rtype]["loader"]
filename = join_path(_RESOURCES[rtype]["path"], src)
try:
return loader(filename, params)
except Exception as e:
raise e
def save(self, rtype, dst, data):
global _RESOURCES
if rtype not in _RESOURCES:
raise ResourceError("Unknown resource type '{}'.".format(rtype))
if _RESOURCES[rtype]["saver"] is None:
raise ResourceError("Resource type '{}' has no defined saving function.".format(rtype))
saver = _RESOURCES[rtype]["saver"]
filename = join_path(_RESOURCES[rtype]["path"], dst)
try:
saver(filename, data)
except Exception as e:
raise e
def lock(self, rtype, src, lock=True):
d = self._getResourceDict(rtype, src)
if d is None:
raise ResourceError("No '{}' resource '{}' stored.".format(rtype, src))
d["locked"]=lock
return self
def is_locked(self, rtype, src):
d = self._getResourceDict(rtype, src)
if d is not None and d["src"] == src:
return d["locked"]
return False
def clear_resource_type(self, rtype, ignore_lock=False):
global _RESOURCES
if rtype in _RESOURCES:
for r in _RESOURCES[rtype]["r"]:
if r["locked"] == False or ignore_lock == True:
r["instance"] = None
return self
def clear_resources(self, ignore_lock=False):
global _RESOURCES
for key in _RESOURCES:
self.clear_resource_type(key, ignore_lock)
return self
def remove_resource_type(self, rtype):
global _RESOURCES
if rtype not in _RESOURCES:
raise ResourceError("Unknown resource type '{}'.".format(rtype))
_RESOURCES[rtype]["r"] = []
return self
def remove_resources(self):
global _RESOURCES
for key in _RESOURCES:
_RESOURCES[key]["r"] = []
return self
# ---------------------------------------------------------------
# Defining the built-in loaders located in resourceLoaders.py
# ---------------------------------------------------------------
define_resource_type("graphic", "graphics/", load_image)
define_resource_type("audio", "audio/", load_audio)
define_resource_type("json", "data/json/", load_JSON)
define_resource_type("maps", "data/maps/", load_JSON)
define_resource_type("user_maps", "maps/", load_JSON, save_JSON)
define_resource_type("font", "fonts/", load_font)
| [
"logging.getLogger",
"logging.Formatter",
"os.path.dirname",
"os.path.isdir",
"weakref.ref"
] | [((167, 195), 'os.path.dirname', 'os.path.dirname', (['sys.argv[0]'], {}), '(sys.argv[0])\n', (182, 195), False, 'import os, sys\n'), ((231, 258), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (248, 258), False, 'import logging\n'), ((311, 373), 'logging.Formatter', 'logging.Formatter', (['"""[%(levelname)s : %(asctime)s] %(message)s"""'], {}), "('[%(levelname)s : %(asctime)s] %(message)s')\n", (328, 373), False, 'import logging\n'), ((861, 884), 'os.path.isdir', 'os.path.isdir', (['fullpath'], {}), '(fullpath)\n', (874, 884), False, 'import os, sys\n'), ((4189, 4215), 'weakref.ref', 'weakref.ref', (["d['instance']"], {}), "(d['instance'])\n", (4200, 4215), False, 'import weakref\n'), ((1503, 1526), 'os.path.isdir', 'os.path.isdir', (['fullpath'], {}), '(fullpath)\n', (1516, 1526), False, 'import os, sys\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 16 15:57:57 2020
@author: snoone
"""
###FTP transfer of most up to date diff file for the GHCND from NOAA/NCEI
#####
import ftplib
import os
os.chdir(r"/gws/nopw/j04/c3s311a_lot2/data/level0/land/daily_data_processing/superghcnd_daily_updates")
#Open ftp connection works OK and get the last update tar.gz file (diff)
ftp = ftplib.FTP('ftp.ncdc.noaa.gov')
ftp.login(user='anonymous', passwd = '<PASSWORD>')
names = ftp.nlst("/pub/data/ghcn/daily/superghcnd/*.tar.gz")
#names ='*tar.gz'
latest_time = None
latest_name = None
for name in names:
time = ftp.voidcmd("MDTM " + name)
if (latest_time is None) or (time > latest_time):
latest_name = name
latest_time = time
##split the string to remove the path and get the file name
split=latest_name.split("/")
latest_file=split[6]
print(latest_file)
last_file = open('last_file.txt', 'r').read()
##compare todays file name with yesterdays if same quit else continue
if latest_file == last_file:
ftp.quit()
print ("not updated")
else:
print("updated")
import ftplib
path = '/pub/data/ghcn/daily/superghcnd/'
filename = (latest_file)
ftp = ftplib.FTP("ftp.ncdc.noaa.gov")
ftp.login("anonymous", "anonymous")
ftp.cwd(path)
ftp.retrbinary("RETR " + filename, open(filename, 'wb').write)
with open("last_file.txt", "w") as output:
output.write(str(filename))
ftp.quit() | [
"os.chdir",
"ftplib.FTP"
] | [((235, 347), 'os.chdir', 'os.chdir', (['"""/gws/nopw/j04/c3s311a_lot2/data/level0/land/daily_data_processing/superghcnd_daily_updates"""'], {}), "(\n '/gws/nopw/j04/c3s311a_lot2/data/level0/land/daily_data_processing/superghcnd_daily_updates'\n )\n", (243, 347), False, 'import os\n'), ((421, 452), 'ftplib.FTP', 'ftplib.FTP', (['"""ftp.ncdc.noaa.gov"""'], {}), "('ftp.ncdc.noaa.gov')\n", (431, 452), False, 'import ftplib\n'), ((1267, 1298), 'ftplib.FTP', 'ftplib.FTP', (['"""ftp.ncdc.noaa.gov"""'], {}), "('ftp.ncdc.noaa.gov')\n", (1277, 1298), False, 'import ftplib\n')] |
"""Data generator for image datasets."""
import itertools
import random
import numpy as np
from kaishi.image.util import swap_channel_dimension
from kaishi.image import ops
def augment_and_label(imobj):
"""Augment an image with common issues and return the modified image + label vector.
Labels at output layer (probabilities, no softmax): [DOCUMENT, RECTIFIED, ROTATED_RIGHT, ROTATED_LEFT, UPSIDE_DOWN, STRETCHING]
:param imobj: image object to randomly augment and label
:type imobj: :class:`kaishi.image.file.ImageFile`
:return: augmented image and label vector applied
:rtype: :class:`kaishi.image.file.ImageFile` and `numpy.array`
"""
label = np.zeros((6,))
im = imobj.small_image.convert("RGB")
if "document" in imobj.relative_path: # Document label
label[0] = 1
if np.random.random() < 0.5: # Remove colors sometimes, no matter the source
im = im.convert("L").convert("RGB")
rot_param = np.random.random() # Rotation (<0.25 does nothing)
if rot_param <= 0.25:
label[1] = 1
elif 0.25 < rot_param <= 0.5:
im = ops.add_rotation(im, ccw_rotation_degrees=90)
label[3] = 1
elif 0.5 < rot_param <= 0.75:
im = ops.add_rotation(im, ccw_rotation_degrees=180)
label[4] = 1
elif rot_param > 0.75:
im = ops.add_rotation(im, ccw_rotation_degrees=270)
label[2] = 1
stretch_param = np.random.random() # Stretching
if 0.25 < stretch_param <= 0.75:
if 0.25 < stretch_param <= 0.5:
h_stretch = 100
v_stretch = 0
elif 0.5 < stretch_param <= 0.75:
h_stretch = 0
v_stretch = 100
pre_stretch_size = im.size
im = ops.add_stretching(im, h_stretch, v_stretch)
im = ops.extract_patch(
im, pre_stretch_size
) # Crop back to original size if stretched
label[5] = 1
return im, label
def train_generator(self, batch_size: int = 32, string_to_match: str = None):
"""Generator for training the data labeler. Operates on a :class:`kaishi.image.dataset.ImageDataset` object.
:param self: image dataset
:type self: :class:`kaishi.image.dataset.ImageDatset`
:param batch_size: batch size for generated data
:type batch_size: int
:param string_to_match: string to match (ignores files without this string in the relative path)
:type string_to_match: str
:return: batch arrays and label vectors
:rtype: :class:`numpy.array` and list
"""
indexes = list(range(len(self.files)))
random.seed(42)
np.random.seed(42)
random.shuffle(indexes)
bi = 0 # Index within batch
for imind in itertools.cycle(indexes):
if "validate" in self.files[imind].relative_path: # Don't use validation data
continue
if "high_res" in self.files[imind].relative_path: # Use only low res photos
continue
if (
string_to_match is not None
and string_to_match not in self.files[imind].relative_path
):
continue
self.files[imind].verify_loaded()
if self.files[imind].image is None:
continue
if bi == 0: # Initialize the batch if needed
batch = [None] * batch_size
labels = np.zeros((batch_size, 6))
# Perturb the image randomly and label
batch[bi], labels[bi, :] = augment_and_label(self.files[imind])
if bi == batch_size - 1:
bi = 0
batch = np.stack(batch)
yield swap_channel_dimension(batch), labels
else:
bi += 1
def generate_validation_data(self, n_examples: int = 400, string_to_match: str = None):
"""Generate a reproducibly random validation data set.
:param n_examples: number of examples in the validation set
:type n_examples: int
:param string_to_match: string to match (ignores files without this string in the relative path)
:type string_to_match: str
:return: stacked training examples (first dimension is batch) and stacked labels
:rtype: `numpy.array` and `numpy.array`
"""
indexes = list(range(len(self.files)))
random.seed(42)
np.random.seed(42)
random.shuffle(indexes)
X = [None] * n_examples
y = np.zeros((n_examples, 6))
i = 0
for imind in itertools.cycle(indexes):
if i == n_examples:
break
if (
"validate" not in self.files[imind].relative_path
): # Use only validation data
continue
if "high_res" in self.files[imind].relative_path: # Disregard high res images
continue
if (
string_to_match is not None
and string_to_match not in self.files[imind].relative_path
):
continue
self.files[imind].verify_loaded()
if self.files[imind].image is None:
continue
# Perturb the image randomly and label
X[i], y[i, :] = augment_and_label(self.files[imind])
i += 1
X = np.stack(X)
return swap_channel_dimension(X), y
| [
"itertools.cycle",
"kaishi.image.util.swap_channel_dimension",
"random.shuffle",
"kaishi.image.ops.add_stretching",
"numpy.random.random",
"random.seed",
"numpy.stack",
"numpy.zeros",
"kaishi.image.ops.add_rotation",
"numpy.random.seed",
"kaishi.image.ops.extract_patch"
] | [((684, 698), 'numpy.zeros', 'np.zeros', (['(6,)'], {}), '((6,))\n', (692, 698), True, 'import numpy as np\n'), ((966, 984), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (982, 984), True, 'import numpy as np\n'), ((1422, 1440), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (1438, 1440), True, 'import numpy as np\n'), ((2571, 2586), 'random.seed', 'random.seed', (['(42)'], {}), '(42)\n', (2582, 2586), False, 'import random\n'), ((2591, 2609), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (2605, 2609), True, 'import numpy as np\n'), ((2614, 2637), 'random.shuffle', 'random.shuffle', (['indexes'], {}), '(indexes)\n', (2628, 2637), False, 'import random\n'), ((2689, 2713), 'itertools.cycle', 'itertools.cycle', (['indexes'], {}), '(indexes)\n', (2704, 2713), False, 'import itertools\n'), ((4189, 4204), 'random.seed', 'random.seed', (['(42)'], {}), '(42)\n', (4200, 4204), False, 'import random\n'), ((4209, 4227), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (4223, 4227), True, 'import numpy as np\n'), ((4232, 4255), 'random.shuffle', 'random.shuffle', (['indexes'], {}), '(indexes)\n', (4246, 4255), False, 'import random\n'), ((4292, 4317), 'numpy.zeros', 'np.zeros', (['(n_examples, 6)'], {}), '((n_examples, 6))\n', (4300, 4317), True, 'import numpy as np\n'), ((4346, 4370), 'itertools.cycle', 'itertools.cycle', (['indexes'], {}), '(indexes)\n', (4361, 4370), False, 'import itertools\n'), ((5057, 5068), 'numpy.stack', 'np.stack', (['X'], {}), '(X)\n', (5065, 5068), True, 'import numpy as np\n'), ((831, 849), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (847, 849), True, 'import numpy as np\n'), ((1730, 1774), 'kaishi.image.ops.add_stretching', 'ops.add_stretching', (['im', 'h_stretch', 'v_stretch'], {}), '(im, h_stretch, v_stretch)\n', (1748, 1774), False, 'from kaishi.image import ops\n'), ((1788, 1827), 'kaishi.image.ops.extract_patch', 'ops.extract_patch', (['im', 'pre_stretch_size'], {}), '(im, pre_stretch_size)\n', (1805, 1827), False, 'from kaishi.image import ops\n'), ((5081, 5106), 'kaishi.image.util.swap_channel_dimension', 'swap_channel_dimension', (['X'], {}), '(X)\n', (5103, 5106), False, 'from kaishi.image.util import swap_channel_dimension\n'), ((1112, 1157), 'kaishi.image.ops.add_rotation', 'ops.add_rotation', (['im'], {'ccw_rotation_degrees': '(90)'}), '(im, ccw_rotation_degrees=90)\n', (1128, 1157), False, 'from kaishi.image import ops\n'), ((3308, 3333), 'numpy.zeros', 'np.zeros', (['(batch_size, 6)'], {}), '((batch_size, 6))\n', (3316, 3333), True, 'import numpy as np\n'), ((3527, 3542), 'numpy.stack', 'np.stack', (['batch'], {}), '(batch)\n', (3535, 3542), True, 'import numpy as np\n'), ((1226, 1272), 'kaishi.image.ops.add_rotation', 'ops.add_rotation', (['im'], {'ccw_rotation_degrees': '(180)'}), '(im, ccw_rotation_degrees=180)\n', (1242, 1272), False, 'from kaishi.image import ops\n'), ((1334, 1380), 'kaishi.image.ops.add_rotation', 'ops.add_rotation', (['im'], {'ccw_rotation_degrees': '(270)'}), '(im, ccw_rotation_degrees=270)\n', (1350, 1380), False, 'from kaishi.image import ops\n'), ((3561, 3590), 'kaishi.image.util.swap_channel_dimension', 'swap_channel_dimension', (['batch'], {}), '(batch)\n', (3583, 3590), False, 'from kaishi.image.util import swap_channel_dimension\n')] |
import unittest
from nlu import *
class TestMarian(unittest.TestCase):
# GENERATE NAME SPACE ENTRIES PROGRAMMATICLY?!??
def test_marian_en_to_de(self):
pipe = nlu.load('en.translate_to.de',verbose=True)
print('QQP')
# pipe.print_info()
# pipe['t5'].setTask('Answer the question')
# test for each tasks
data = ['Who is president of germany', 'Who is <NAME> ?', 'What is NLP?', 'How to make tea?']
df = pipe.predict(data)
print(df.columns)
print(df['translation'])
print(df.columns)
def test_marian_de_to_en(self):
pipe = nlu.load('de.translate_to.en',verbose=True)
print('QQP')
# pipe.print_info()
# pipe['t5'].setTask('Answer the question')
# test for each tasks
data = ['Wer ist Praesident von Deutschland', 'Wer ist <NAME> ?', 'Was ist NLP?', 'Wie macht man Tee?']
df = pipe.predict(data)
print(df.columns)
print(df['translation'])
print(df.columns)
def test_marian_de_to_en_pipe(self):
pipe = nlu.load('de.marian.translate_to.en',verbose=True)
print('QQP')
# pipe.print_info()
# pipe['t5'].setTask('Answer the question')
# test for each tasks
data = ['Wer ist Praesident von Deutschland', 'Wer ist <NAME> ?', 'Was ist NLP?', 'Wie macht man Tee?']
df = pipe.predict(data)
print(df.columns)
print(df['marian'])
print(df.columns)
def test_quick(self):
matrix_quotes = [
'You are here because Zion is about to be destroyed. Its every living inhabitant terminated, its entire existence eradicated.',
'Denial is the most predictable of all human responses. But, rest assured, this will be the sixth time we have destroyed it, and we have become exceedingly efficient at it.',
'Your life is the sum of a remainder of an unbalanced equation inherent to the programming of the matrix. You are the eventuality of an anomaly, which despite my sincerest efforts I have been unable to eliminate from what is otherwise a harmony of mathematical precision. While it remains a burden assiduously avoided, it is not unexpected, and thus not beyond a measure of control. Which has led you, inexorably, here.',
'Hope, it is the quintessential human delusion, simultaneously the source of your greatest strength, and your greatest weakness.',
'Dont Think You Are, Know You Are.',
'As you were undoubtedly gathering, the anomaly is systemic, creating fluctuations in even the most simplistic equations.',
'If I am the father of the Matrix, she would undoubtedly be its mother.',]
translate_pipe = nlu.load('en.translate_to.de')
de_df = translate_pipe.predict(matrix_quotes, output_level='document')
print( de_df[['document','translation']])
if __name__ == '__main__':
unittest.main()
| [
"unittest.main"
] | [((2940, 2955), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2953, 2955), False, 'import unittest\n')] |
# Generated by Django 2.2.10 on 2020-04-29 14:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0024_auto_20200423_1601'),
]
operations = [
migrations.AlterField(
model_name='imagereport',
name='status',
field=models.CharField(choices=[('pending_review', 'pending_review'), ('mature_filtered', 'mature_filtered'), ('deindexed', 'deindexed'), ('no_action', 'no_action')], default='pending_review', max_length=20),
),
migrations.DeleteModel(
name='ImageTags',
),
]
| [
"django.db.migrations.DeleteModel",
"django.db.models.CharField"
] | [((560, 600), 'django.db.migrations.DeleteModel', 'migrations.DeleteModel', ([], {'name': '"""ImageTags"""'}), "(name='ImageTags')\n", (582, 600), False, 'from django.db import migrations, models\n'), ((338, 549), 'django.db.models.CharField', 'models.CharField', ([], {'choices': "[('pending_review', 'pending_review'), ('mature_filtered',\n 'mature_filtered'), ('deindexed', 'deindexed'), ('no_action', 'no_action')]", 'default': '"""pending_review"""', 'max_length': '(20)'}), "(choices=[('pending_review', 'pending_review'), (\n 'mature_filtered', 'mature_filtered'), ('deindexed', 'deindexed'), (\n 'no_action', 'no_action')], default='pending_review', max_length=20)\n", (354, 549), False, 'from django.db import migrations, models\n')] |
import pytest
from streaming_form_data.validators import MaxSizeValidator, ValidationError
def test_max_size_validator_empty_input():
validator = MaxSizeValidator(0)
with pytest.raises(ValidationError):
validator('x')
def test_max_size_validator_normal():
validator = MaxSizeValidator(5)
for char in 'hello':
validator(char)
with pytest.raises(ValidationError):
validator('x')
| [
"streaming_form_data.validators.MaxSizeValidator",
"pytest.raises"
] | [((153, 172), 'streaming_form_data.validators.MaxSizeValidator', 'MaxSizeValidator', (['(0)'], {}), '(0)\n', (169, 172), False, 'from streaming_form_data.validators import MaxSizeValidator, ValidationError\n'), ((294, 313), 'streaming_form_data.validators.MaxSizeValidator', 'MaxSizeValidator', (['(5)'], {}), '(5)\n', (310, 313), False, 'from streaming_form_data.validators import MaxSizeValidator, ValidationError\n'), ((183, 213), 'pytest.raises', 'pytest.raises', (['ValidationError'], {}), '(ValidationError)\n', (196, 213), False, 'import pytest\n'), ((374, 404), 'pytest.raises', 'pytest.raises', (['ValidationError'], {}), '(ValidationError)\n', (387, 404), False, 'import pytest\n')] |
import os;
import abc;
import math;
import multiprocessing;
import psutil;
import numpy as np;
import matplotlib.pyplot as plt;
from Errors import *;
from KMeans import *;
from UnaryLinearRegression import *;
class _Node:
def __init__(self, samplesCount, featureIndex = None, featureValue = None, leftChild = None, rightChild = None):
self.samplesCount = samplesCount;
self.featureIndex = featureIndex;
self.featureValue = featureValue;
self.leftChild = leftChild;
self.rightChild = rightChild;
def __repr__(self):
return self.__str__();
def __str__(self):
if self.isLeaf():
return "Leaf node, {0} samples".format(self.samplesCount);
else:
return "Internal node, {0} samples, feature {1} of value {2}".format(self.samplesCount, self.featureIndex, self.featureValue);
def isLeaf(self):
return self.featureIndex is None;
def getLeafCount(self):
if self.isLeaf():
return 1;
return (self.leftChild.getLeafCount() if self.leftChild is not None else 0) +\
(self.rightChild.getLeafCount() if self.rightChild is not None else 0);
class IsolationForest:
def __init__(self, treeCount = 100, subSamplingSize = 256, thresholdFinder = None):
if thresholdFinder is None or not isinstance(thresholdFinder, IThresholdFinder):
raise ValueError();
self.__treeCount = treeCount;
self.__subSamplingSize = subSamplingSize;
self.__treesList = [];
self.__scores = None;
self.__threshold = None;
self.__thresholdFinder = thresholdFinder;
@property
def scores(self):
return self.__scores;
@property
def threshold(self):
return self.__threshold;
@threshold.setter
def threshold(self, value):
if value <= 0.5 or value >= 1:
raise ValueError();
self.__threshold = value;
def __calcHarmonicNumber(self, i):
return np.log(i) + np.euler_gamma;
def __calcAveragePathLength(self, psi):
if psi < 2:
return 0;
if psi == 2:
return 1;
return 2 * self.__calcHarmonicNumber(psi - 1) - 2 * (psi - 1) / psi;
def __getPathLength(self, instance, node, currentLength, lengthLimit):
if node.isLeaf() or currentLength >= lengthLimit:
return currentLength + self.__calcAveragePathLength(node.samplesCount);
if instance[0, node.featureIndex] < node.featureValue:
return self.__getPathLength(instance, node.leftChild, currentLength + 1, lengthLimit);
else:
return self.__getPathLength(instance, node.rightChild, currentLength + 1, lengthLimit);
def __getAnomalyScore(self, instance, lengthLimit):
length = 0;
for tree in self.__treesList:
length += self.__getPathLength(instance, tree, 0, lengthLimit);
length /= self.__treeCount;
return 1 / (2 ** (length / self.__calcAveragePathLength(self.__subSamplingSize)));
def __hasSameFeatureValues(self, dataSet, featureIndex):
if dataSet.shape[0] == 0:
return True;
result = True;
value = dataSet[0, featureIndex];
for rowIndex in range(0, dataSet.shape[0]):
if dataSet[rowIndex, featureIndex] != value:
result = False;
break;
return result;
def __choiceFeatureIndex(self, features):
if len(features) == 1:
return features[0];
return features[np.random.randint(0, len(features))];
def __choiceFeatureValue(self, dataSet, featureIndex):
values = dataSet[:, featureIndex];
minValue, maxValue = values.min(), values.max();
return minValue + (maxValue - minValue) * np.random.random();
def __createNode(self, dataSet, features, currentHeight):
samplesCount = dataSet.shape[0];
if samplesCount == 0:
return None;
if samplesCount == 1:
return _Node(samplesCount);
for index in [item for item in features if self.__hasSameFeatureValues(dataSet, item)]:
features.remove(index);
if len(features) == 0:
return _Node(samplesCount);
featureIndex = self.__choiceFeatureIndex(features);
featureValue = self.__choiceFeatureValue(dataSet, featureIndex);
return _Node(samplesCount, featureIndex, featureValue,
self.__createNode(dataSet[(dataSet[:, featureIndex] < featureValue).A.flatten(), :], features[:], currentHeight + 1),
self.__createNode(dataSet[(dataSet[:, featureIndex] >= featureValue).A.flatten(), :], features[:], currentHeight + 1));
def _createTree(self, subSet):
return self.__createNode(subSet, list(range(0, subSet.shape[1])), 0);
def fill(self, dataSet):
if dataSet is None or not isinstance(dataSet, np.matrix):
raise ValueError();
self.__scores = None;
self.__threshold = None;
n = dataSet.shape[0];
with multiprocessing.Pool(max(1, psutil.cpu_count(False) - 2)) as pool:
self.__treesList = pool.map(self._createTree, [dataSet[np.random.choice(n, self.__subSamplingSize, False), :] for i in range(0, self.__treeCount)]);
def getAnomalyScore(self, instance):
if instance is None:
raise ValueError();
return self.__getAnomalyScore(instance, self.__subSamplingSize - 1);
def train(self, dataSet):
if self.__threshold is not None and self.__scores is not None:
return False;
if dataSet is None or not isinstance(dataSet, np.matrix):
raise ValueError();
if len(self.__treesList) != self.__treeCount:
raise InvalidOperationError();
with multiprocessing.Pool(max(1, psutil.cpu_count(False) - 2)) as pool:
self.__scores = pool.map(self.getAnomalyScore, [item for item in dataSet]);
self.__threshold = self.__thresholdFinder.find(self.__scores);
return True;
class IThresholdFinder(metaclass = abc.ABCMeta):
@abc.abstractmethod
def find(self, scores):
pass;
class ProportionThresholdFinder(IThresholdFinder):
def __init__(self, proportion):
self.__proportion = max(0, max(1, proportion));
def find(self, scores):
scores.sort(reverse = True);
return np.quantile(scores, self.__proportion);
class CurvesThresholdFinder(IThresholdFinder):
MIN_SAMPLES_NUMBER = 10;
MIN_PARALLEL_NUMBER = 10000;
def __init__(self, minCheckValue, maxCheckValue, defaultThreshold, showPlot = False):
self._minCheckValue = minCheckValue;
self._maxCheckValue = maxCheckValue;
self._defaultThreshold = defaultThreshold;
self.__showPlot = showPlot;
self._values = [];
self._curves = None;
self._leftLines = None;
self._rightLines = None;
def __reset(self):
self._curves = None;
self._leftLines = None;
self._rightLines = None;
def _leftOnly(self, y):
maxValue = y.max();
value, residual = None, None;
for i in range(CurvesThresholdFinder.MIN_SAMPLES_NUMBER, y.shape[0]):
line = UnaryLinearRegression();
line.fit(np.mat(np.arange(i)).T, y[:i, 0]);
line.sigLevel = None;
if line.slop <= 0:
continue;
value = line.predictValue(i - 1);
if value > maxValue:
continue;
residual = y[i:, 0] - value;
self._leftLines[i] = (line, value);
self._curves.append([line, i - 1, None, None, value, line.rss + (residual.T * residual)[0, 0]]);
def _rightOnly(self, y):
n, maxValue = y.shape[0], y.max();
value, residual = None, None;
for j in range(n - CurvesThresholdFinder.MIN_SAMPLES_NUMBER, 0, -1):
line = UnaryLinearRegression();
line.fit(np.mat(np.arange(j, n)).T, y[j:, 0]);
line.sigLevel = None;
if line.slop >= 0:
continue;
value = line.predictValue(j);
if value > maxValue:
continue;
residual = y[:j, 0] - value;
self._rightLines[j] = (line, value);
self._curves.append([None, None, line, j, value, line.rss + (residual.T * residual)[0, 0]]);
def _processItem(self, i, j, y, maxValue):
leftLine, leftValue = self._leftLines[i] if i in self._leftLines else (None, None);
if leftLine is None:
return None;
rightLine, rightValue = self._rightLines[j] if j in self._rightLines else (None, None);
if rightLine is None:
return None;
value, residual = None, None;
endIndex, startIndex = None, None;
if leftValue < rightValue:
value = rightValue;
startIndex = j;
endIndex = math.floor(leftLine.inverse(rightValue));
elif rightValue < leftValue:
value = leftValue;
endIndex = i - 1;
startIndex = math.ceil(rightLine.inverse(leftValue));
else:
endIndex = i - 1;
startIndex = j;
value = leftValue;
if endIndex >= startIndex - 1 or value > maxValue:
return None;
residual = y[endIndex + 1:startIndex, 0] - value;
leftRss = (leftLine.calcRss(np.mat(np.arange(i, endIndex + 1)).T, y[i:endIndex + 1, 0]) if endIndex > i - 1 else 0) + leftLine.rss;
rightRss = (rightLine.calcRss(np.mat(np.arange(startIndex, j)).T, y[startIndex:j, 0]) if startIndex < j else 0) + rightLine.rss;
return [leftLine, endIndex, rightLine, startIndex, value, leftRss + rightRss + (residual.T * residual)[0, 0]];
def _bothSides(self, y):
points = [];
n, maxValue = y.shape[0], y.max();
for i in range(CurvesThresholdFinder.MIN_SAMPLES_NUMBER, n - CurvesThresholdFinder.MIN_SAMPLES_NUMBER - 1):
for j in range(n - CurvesThresholdFinder.MIN_SAMPLES_NUMBER, i, -1):
points.append((i, j, y, maxValue));
curves = None;
if len(points) >= CurvesThresholdFinder.MIN_PARALLEL_NUMBER:
with multiprocessing.Pool(max(1, psutil.cpu_count(False) - 2)) as pool:
curves = pool.starmap(self._processItem, points);
else:
curves = list(map(lambda obj: self._processItem(*obj), points));
for item in curves:
if item is None:
continue;
self._curves.append(item);
def _fit(self, y):
if y is None:
raise ValueError();
n = y.shape[0];
if n < CurvesThresholdFinder.MIN_SAMPLES_NUMBER * 2 + 1:
return None, None;
self._curves = [];
self._leftLines = {};
self._rightLines = {};
self._leftOnly(y);
self._rightOnly(y);
self._bothSides(y);
if len(self._curves) == 0:
value = y.mean();
self._values.append(value);
return [0, n - 1], [value, value];
self._curves = np.mat(self._curves);
leftLine, endIndex, rightLine, startIndex, value, rss = tuple(self._curves[self._curves[:, -1].argmin(0)[0, 0], :].A.flatten().tolist());
self._values.append(value);
if leftLine is not None and rightLine is not None:
return [0, endIndex, endIndex + 1, startIndex - 1, startIndex, n - 1],\
[leftLine.predictValue(0), leftLine.predictValue(endIndex), value, value, rightLine.predictValue(startIndex), rightLine.predictValue(n - 1)];
elif leftLine is not None:
return [0, endIndex, n - 1], [leftLine.predictValue(0), leftLine.predictValue(endIndex), leftLine.predictValue(endIndex)];
elif rightLine is not None:
return [0, startIndex, n - 1], [rightLine.predictValue(startIndex), rightLine.predictValue(startIndex), rightLine.predictValue(n - 1)];
else:
return None, None;
def find(self, scores):
scale = 100;
data = np.mat(scores).T * scale;
indices, distances, center = KMeans(lambda X, k: np.mat([X.min(), X.mean(), X.max()]).T).clustering(data, 3, 1);
print("anomaly score centers:{0}".format(center.T));
checkValue = center[2, 0];
minCheckValue = self._minCheckValue * scale;
maxCheckValue = self._maxCheckValue * scale;
defaultThreshold = self._defaultThreshold * scale;
minValue = data[(indices == 2).A.flatten(), :].min(0)[0, 0];
maxValue = data[(indices == 2).A.flatten(), :].max(0)[0, 0];
if maxValue <= defaultThreshold:
return defaultThreshold / scale;
if checkValue >= defaultThreshold:
checkValue = (minValue + checkValue) / 2;
elif checkValue <= minCheckValue:
checkValue = (checkValue + maxValue) / 2;
if checkValue < minCheckValue:
checkValue = minCheckValue;
elif checkValue > maxCheckValue:
checkValue = maxCheckValue;
print("threshold check value: {0}".format(checkValue));
i = None;
for j in range(0, data.shape[0]):
if data[j, 0] >= checkValue and i is None:
i = j;
if data[j, 0] < checkValue and i is not None:
if j - i > CurvesThresholdFinder.MIN_SAMPLES_NUMBER * 2:
x, y = self._fit(data[i:j, 0]);
if self.__showPlot:
plt.figure(1, (16, 10));
plt.plot(list(range(0, j - i)), data[i:j, 0].A.flatten().tolist(), color = "b", marker = "x");
if x is not None and y is not None:
plt.plot(x, y, color = "r");
plt.show();
i = None;
print("threshold all values: {0}".format(self._values));
threshold = (np.mean(self._values) if len(self._values) > 0 else defaultThreshold) / scale;
print("threshold found: {0}".format(threshold));
self.__reset();
return threshold;
| [
"numpy.mat",
"numpy.mean",
"numpy.random.random",
"numpy.random.choice",
"numpy.log",
"matplotlib.pyplot.plot",
"numpy.quantile",
"matplotlib.pyplot.figure",
"psutil.cpu_count",
"numpy.arange",
"matplotlib.pyplot.show"
] | [((6468, 6506), 'numpy.quantile', 'np.quantile', (['scores', 'self.__proportion'], {}), '(scores, self.__proportion)\n', (6479, 6506), True, 'import numpy as np\n'), ((11234, 11254), 'numpy.mat', 'np.mat', (['self._curves'], {}), '(self._curves)\n', (11240, 11254), True, 'import numpy as np\n'), ((2021, 2030), 'numpy.log', 'np.log', (['i'], {}), '(i)\n', (2027, 2030), True, 'import numpy as np\n'), ((3839, 3857), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (3855, 3857), True, 'import numpy as np\n'), ((12208, 12222), 'numpy.mat', 'np.mat', (['scores'], {}), '(scores)\n', (12214, 12222), True, 'import numpy as np\n'), ((14059, 14080), 'numpy.mean', 'np.mean', (['self._values'], {}), '(self._values)\n', (14066, 14080), True, 'import numpy as np\n'), ((5154, 5177), 'psutil.cpu_count', 'psutil.cpu_count', (['(False)'], {}), '(False)\n', (5170, 5177), False, 'import psutil\n'), ((5903, 5926), 'psutil.cpu_count', 'psutil.cpu_count', (['(False)'], {}), '(False)\n', (5919, 5926), False, 'import psutil\n'), ((7375, 7387), 'numpy.arange', 'np.arange', (['i'], {}), '(i)\n', (7384, 7387), True, 'import numpy as np\n'), ((8062, 8077), 'numpy.arange', 'np.arange', (['j', 'n'], {}), '(j, n)\n', (8071, 8077), True, 'import numpy as np\n'), ((13648, 13671), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)', '(16, 10)'], {}), '(1, (16, 10))\n', (13658, 13671), True, 'import matplotlib.pyplot as plt\n'), ((13933, 13943), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (13941, 13943), True, 'import matplotlib.pyplot as plt\n'), ((5260, 5310), 'numpy.random.choice', 'np.random.choice', (['n', 'self.__subSamplingSize', '(False)'], {}), '(n, self.__subSamplingSize, False)\n', (5276, 5310), True, 'import numpy as np\n'), ((9527, 9553), 'numpy.arange', 'np.arange', (['i', '(endIndex + 1)'], {}), '(i, endIndex + 1)\n', (9536, 9553), True, 'import numpy as np\n'), ((9669, 9693), 'numpy.arange', 'np.arange', (['startIndex', 'j'], {}), '(startIndex, j)\n', (9678, 9693), True, 'import numpy as np\n'), ((10364, 10387), 'psutil.cpu_count', 'psutil.cpu_count', (['(False)'], {}), '(False)\n', (10380, 10387), False, 'import psutil\n'), ((13880, 13905), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y'], {'color': '"""r"""'}), "(x, y, color='r')\n", (13888, 13905), True, 'import matplotlib.pyplot as plt\n')] |
import torch
def model_to_vector(model, emb_layer_name='input_emb'):
"""
get the wordvec weight
:param model:
:param emb_layer_name:
:return:
"""
sd = model.state_dict()
return sd[emb_layer_name + '.weight'].cpu().numpy().tolist()
def save_embedding(file_name, embeddings, id2word):
"""
wordvec save to text file
:param file_name:
:param embeddings:
:param id2word:
:return:
"""
fo = open(file_name, 'w')
for idx in range(len(embeddings)):
word = id2word[idx]
embed = embeddings[idx]
embed_list = [str(i) for i in embed]
line_str = ' '.join(embed_list)
fo.write(word + ' ' + line_str + '\n')
fo.close()
def nearest(model, vali_examples, vali_size, id2word_dict, top_k=8):
"""
find the nearest word of vali_examples
:param model: model
:param vali_examples: []
:param vali_size: int
:param id2word_dict: {}
:param top_k: int
:return:
"""
vali_examples = torch.tensor(vali_examples, dtype=torch.long).cuda()
vali_emb = model.predict(vali_examples)
# sim: [batch_size, vocab_size]
sim = torch.mm(vali_emb, model.input_emb.weight.transpose(0, 1))
for i in range(vali_size):
vali_word = id2word_dict[vali_examples[i].item()]
nearest = (-sim[i, :]).sort()[1][1: top_k + 1]
log_str = 'Nearest to %s:' % vali_word
for k in range(top_k):
close_word = id2word_dict[nearest[k].item()]
log_str = '%s %s,' % (log_str, close_word)
print(log_str) | [
"torch.tensor"
] | [((1010, 1055), 'torch.tensor', 'torch.tensor', (['vali_examples'], {'dtype': 'torch.long'}), '(vali_examples, dtype=torch.long)\n', (1022, 1055), False, 'import torch\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 15 15:13:29 2018
@author: kazuki.onodera
"""
import numpy as np
import pandas as pd
import os, gc
from glob import glob
from tqdm import tqdm
import sys
sys.path.append(f'/home/{os.environ.get("USER")}/PythonLibrary')
import lgbextension as ex
import lightgbm as lgb
from multiprocessing import cpu_count
import utils
utils.start(__file__)
#==============================================================================
SUBMIT_FILE_PATH = '../output/1015-4.csv.gz'
COMMENT = '1015-2 + weight'
EXE_SUBMIT = True
DROP = ['f001_hostgal_specz']
SEED = np.random.randint(9999)
print('SEED:', SEED)
NFOLD = 4
LOOP = 2
param = {
'objective': 'multiclass',
'num_class': 14,
'metric': 'multi_logloss',
'learning_rate': 0.01,
'max_depth': 6,
'num_leaves': 63,
'max_bin': 255,
'min_child_weight': 10,
'min_data_in_leaf': 150,
'reg_lambda': 0.5, # L2 regularization term on weights.
'reg_alpha': 0.5, # L1 regularization term on weights.
'colsample_bytree': 0.5,
'subsample': 0.5,
# 'nthread': 32,
'nthread': cpu_count(),
'bagging_freq': 1,
'verbose':-1,
}
classes = [6, 15, 16, 42, 52, 53, 62, 64, 65, 67, 88, 90, 92, 95]
class_weight = {6: 1,
15: 2,
16: 1,
42: 1,
52: 1,
53: 1,
62: 1,
64: 2,
65: 1,
67: 1,
88: 1,
90: 1,
92: 1,
95: 1}
# =============================================================================
# load
# =============================================================================
files_tr = sorted(glob('../data/train_f*.f'))
[print(f) for f in files_tr]
X = pd.concat([
pd.read_feather(f) for f in tqdm(files_tr, mininterval=60)
], axis=1)
y = utils.load_target().target
X.drop(DROP, axis=1, inplace=True)
target_dict = {}
target_dict_r = {}
for i,e in enumerate(y.sort_values().unique()):
target_dict[e] = i
target_dict_r[i] = e
y = y.replace(target_dict)
if X.columns.duplicated().sum()>0:
raise Exception(f'duplicated!: { X.columns[X.columns.duplicated()] }')
print('no dup :) ')
print(f'X.shape {X.shape}')
gc.collect()
COL = X.columns.tolist()
#CAT = list( set(X.columns)&set(utils_cat.ALL))
#print(f'CAT: {CAT}')
# =============================================================================
# cv
# =============================================================================
def lgb_multi_weighted_logloss(y_preds, train_data):
"""
@author olivier https://www.kaggle.com/ogrellier
https://www.kaggle.com/ogrellier/plasticc-in-a-kernel-meta-and-data/code
multi logloss for PLAsTiCC challenge
"""
# class_weights taken from Giba's topic : https://www.kaggle.com/titericz
# https://www.kaggle.com/c/PLAsTiCC-2018/discussion/67194
# with <NAME>'s post https://www.kaggle.com/kyleboone
y_true = train_data.get_label()
if len(np.unique(y_true)) > 14:
classes.append(99)
class_weight[99] = 2
y_p = y_preds.reshape(y_true.shape[0], len(classes), order='F')
# Trasform y_true in dummies
y_ohe = pd.get_dummies(y_true)
# Normalize rows and limit y_preds to 1e-15, 1-1e-15
y_p = np.clip(a=y_p, a_min=1e-15, a_max=1 - 1e-15)
# Transform to log
y_p_log = np.log(y_p)
# Get the log for ones, .values is used to drop the index of DataFrames
# Exclude class 99 for now, since there is no class99 in the training set
# we gave a special process for that class
y_log_ones = np.sum(y_ohe.values * y_p_log, axis=0)
# Get the number of positives for each class
nb_pos = y_ohe.sum(axis=0).values.astype(float)
# Weight average and divide by the number of positives
class_arr = np.array([class_weight[k] for k in sorted(class_weight.keys())])
y_w = y_log_ones * class_arr / nb_pos
loss = - np.sum(y_w) / np.sum(class_arr)
return 'wloss', loss, False
dtrain = lgb.Dataset(X, y, #categorical_feature=CAT,
free_raw_data=False)
gc.collect()
model_all = []
for i in range(LOOP):
gc.collect()
param['seed'] = np.random.randint(9999)
ret, models = lgb.cv(param, dtrain, 99999, nfold=NFOLD,
feval=lgb_multi_weighted_logloss,
early_stopping_rounds=100, verbose_eval=50,
seed=SEED)
model_all += models
result = f"CV auc-mean: {ret['multi_logloss-mean'][-1]} + {ret['multi_logloss-stdv'][-1]}"
print(result)
imp = ex.getImp(model_all)
imp['split'] /= imp['split'].max()
imp['gain'] /= imp['gain'].max()
imp['total'] = imp['split'] + imp['gain']
imp.sort_values('total', ascending=False, inplace=True)
imp.reset_index(drop=True, inplace=True)
imp.to_csv(f'LOG/imp_{__file__}.csv', index=False)
png = f'LOG/imp_{__file__}.png'
utils.savefig_imp(imp, png, x='total', title=f'{__file__}')
utils.send_line(result, png)
# =============================================================================
# test
# =============================================================================
files_te = sorted(glob('../data/test_f*.f'))
X_test = pd.concat([
pd.read_feather(f) for f in tqdm(files_te, mininterval=60)
], axis=1)[COL]
for i,model in enumerate(tqdm(model_all)):
y_pred = model.predict(X_test)
if i==0:
y_pred_all = y_pred
else:
y_pred_all += y_pred
y_pred_all /= len(model_all)
sub = pd.read_csv('../input/sample_submission.csv.zip')
df = pd.DataFrame(y_pred_all, columns=sub.columns[1:-1])
# Compute preds_99 as the proba of class not being any of the others
# preds_99 = 0.1 gives 1.769
preds_99 = np.ones(df.shape[0])
for i in range(df.shape[1]):
preds_99 *= (1 - df.iloc[:, i])
df['class_99'] = preds_99
sub = pd.concat([sub[['object_id']], df], axis=1)
sub.to_csv(SUBMIT_FILE_PATH, index=False, compression='gzip')
sub.iloc[:, 1:].hist(bins=30, figsize=(16, 12))
png = f'LOG/sub_{__file__}.png'
utils.savefig_sub(sub, png)
utils.send_line('DONE!', png)
# =============================================================================
# submission
# =============================================================================
if EXE_SUBMIT:
print('submit')
utils.submit(SUBMIT_FILE_PATH, COMMENT)
#==============================================================================
utils.end(__file__)
utils.stop_instance()
| [
"numpy.clip",
"pandas.read_csv",
"utils.send_line",
"numpy.log",
"multiprocessing.cpu_count",
"utils.start",
"lightgbm.Dataset",
"utils.submit",
"utils.savefig_sub",
"pandas.read_feather",
"pandas.DataFrame",
"glob.glob",
"utils.stop_instance",
"numpy.ones",
"utils.savefig_imp",
"gc.co... | [((392, 413), 'utils.start', 'utils.start', (['__file__'], {}), '(__file__)\n', (403, 413), False, 'import utils\n'), ((627, 650), 'numpy.random.randint', 'np.random.randint', (['(9999)'], {}), '(9999)\n', (644, 650), True, 'import numpy as np\n'), ((2473, 2485), 'gc.collect', 'gc.collect', ([], {}), '()\n', (2483, 2485), False, 'import os, gc\n'), ((4241, 4279), 'lightgbm.Dataset', 'lgb.Dataset', (['X', 'y'], {'free_raw_data': '(False)'}), '(X, y, free_raw_data=False)\n', (4252, 4279), True, 'import lightgbm as lgb\n'), ((4328, 4340), 'gc.collect', 'gc.collect', ([], {}), '()\n', (4338, 4340), False, 'import os, gc\n'), ((4802, 4822), 'lgbextension.getImp', 'ex.getImp', (['model_all'], {}), '(model_all)\n', (4811, 4822), True, 'import lgbextension as ex\n'), ((5117, 5176), 'utils.savefig_imp', 'utils.savefig_imp', (['imp', 'png'], {'x': '"""total"""', 'title': 'f"""{__file__}"""'}), "(imp, png, x='total', title=f'{__file__}')\n", (5134, 5176), False, 'import utils\n'), ((5177, 5205), 'utils.send_line', 'utils.send_line', (['result', 'png'], {}), '(result, png)\n', (5192, 5205), False, 'import utils\n'), ((5744, 5793), 'pandas.read_csv', 'pd.read_csv', (['"""../input/sample_submission.csv.zip"""'], {}), "('../input/sample_submission.csv.zip')\n", (5755, 5793), True, 'import pandas as pd\n'), ((5799, 5850), 'pandas.DataFrame', 'pd.DataFrame', (['y_pred_all'], {'columns': 'sub.columns[1:-1]'}), '(y_pred_all, columns=sub.columns[1:-1])\n', (5811, 5850), True, 'import pandas as pd\n'), ((5961, 5981), 'numpy.ones', 'np.ones', (['df.shape[0]'], {}), '(df.shape[0])\n', (5968, 5981), True, 'import numpy as np\n'), ((6081, 6124), 'pandas.concat', 'pd.concat', (["[sub[['object_id']], df]"], {'axis': '(1)'}), "([sub[['object_id']], df], axis=1)\n", (6090, 6124), True, 'import pandas as pd\n'), ((6270, 6297), 'utils.savefig_sub', 'utils.savefig_sub', (['sub', 'png'], {}), '(sub, png)\n', (6287, 6297), False, 'import utils\n'), ((6298, 6327), 'utils.send_line', 'utils.send_line', (['"""DONE!"""', 'png'], {}), "('DONE!', png)\n", (6313, 6327), False, 'import utils\n'), ((6666, 6685), 'utils.end', 'utils.end', (['__file__'], {}), '(__file__)\n', (6675, 6685), False, 'import utils\n'), ((6686, 6707), 'utils.stop_instance', 'utils.stop_instance', ([], {}), '()\n', (6705, 6707), False, 'import utils\n'), ((1245, 1256), 'multiprocessing.cpu_count', 'cpu_count', ([], {}), '()\n', (1254, 1256), False, 'from multiprocessing import cpu_count\n'), ((1910, 1936), 'glob.glob', 'glob', (['"""../data/train_f*.f"""'], {}), "('../data/train_f*.f')\n", (1914, 1936), False, 'from glob import glob\n'), ((2089, 2108), 'utils.load_target', 'utils.load_target', ([], {}), '()\n', (2106, 2108), False, 'import utils\n'), ((3428, 3450), 'pandas.get_dummies', 'pd.get_dummies', (['y_true'], {}), '(y_true)\n', (3442, 3450), True, 'import pandas as pd\n'), ((3518, 3562), 'numpy.clip', 'np.clip', ([], {'a': 'y_p', 'a_min': '(1e-15)', 'a_max': '(1 - 1e-15)'}), '(a=y_p, a_min=1e-15, a_max=1 - 1e-15)\n', (3525, 3562), True, 'import numpy as np\n'), ((3600, 3611), 'numpy.log', 'np.log', (['y_p'], {}), '(y_p)\n', (3606, 3611), True, 'import numpy as np\n'), ((3830, 3868), 'numpy.sum', 'np.sum', (['(y_ohe.values * y_p_log)'], {'axis': '(0)'}), '(y_ohe.values * y_p_log, axis=0)\n', (3836, 3868), True, 'import numpy as np\n'), ((4383, 4395), 'gc.collect', 'gc.collect', ([], {}), '()\n', (4393, 4395), False, 'import os, gc\n'), ((4416, 4439), 'numpy.random.randint', 'np.random.randint', (['(9999)'], {}), '(9999)\n', (4433, 4439), True, 'import numpy as np\n'), ((4458, 4592), 'lightgbm.cv', 'lgb.cv', (['param', 'dtrain', '(99999)'], {'nfold': 'NFOLD', 'feval': 'lgb_multi_weighted_logloss', 'early_stopping_rounds': '(100)', 'verbose_eval': '(50)', 'seed': 'SEED'}), '(param, dtrain, 99999, nfold=NFOLD, feval=lgb_multi_weighted_logloss,\n early_stopping_rounds=100, verbose_eval=50, seed=SEED)\n', (4464, 4592), True, 'import lightgbm as lgb\n'), ((5393, 5418), 'glob.glob', 'glob', (['"""../data/test_f*.f"""'], {}), "('../data/test_f*.f')\n", (5397, 5418), False, 'from glob import glob\n'), ((5574, 5589), 'tqdm.tqdm', 'tqdm', (['model_all'], {}), '(model_all)\n', (5578, 5589), False, 'from tqdm import tqdm\n'), ((6541, 6580), 'utils.submit', 'utils.submit', (['SUBMIT_FILE_PATH', 'COMMENT'], {}), '(SUBMIT_FILE_PATH, COMMENT)\n', (6553, 6580), False, 'import utils\n'), ((2000, 2018), 'pandas.read_feather', 'pd.read_feather', (['f'], {}), '(f)\n', (2015, 2018), True, 'import pandas as pd\n'), ((4180, 4197), 'numpy.sum', 'np.sum', (['class_arr'], {}), '(class_arr)\n', (4186, 4197), True, 'import numpy as np\n'), ((251, 273), 'os.environ.get', 'os.environ.get', (['"""USER"""'], {}), "('USER')\n", (265, 273), False, 'import os, gc\n'), ((2028, 2058), 'tqdm.tqdm', 'tqdm', (['files_tr'], {'mininterval': '(60)'}), '(files_tr, mininterval=60)\n', (2032, 2058), False, 'from tqdm import tqdm\n'), ((3233, 3250), 'numpy.unique', 'np.unique', (['y_true'], {}), '(y_true)\n', (3242, 3250), True, 'import numpy as np\n'), ((4166, 4177), 'numpy.sum', 'np.sum', (['y_w'], {}), '(y_w)\n', (4172, 4177), True, 'import numpy as np\n'), ((5458, 5476), 'pandas.read_feather', 'pd.read_feather', (['f'], {}), '(f)\n', (5473, 5476), True, 'import pandas as pd\n'), ((5486, 5516), 'tqdm.tqdm', 'tqdm', (['files_te'], {'mininterval': '(60)'}), '(files_te, mininterval=60)\n', (5490, 5516), False, 'from tqdm import tqdm\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import sys, os
import tracking
setup(
name='django-tracking',
version=tracking.get_version(),
description="Basic visitor tracking and blacklisting for Django",
long_description=open('README.rst', 'r').read(),
keywords='django, tracking, visitors',
author='<NAME>',
author_email='<EMAIL>',
url='http://bitbucket.org/codekoala/django-tracking',
license='MIT',
package_dir={'tracking': 'tracking'},
include_package_data=True,
packages=find_packages(),
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: Developers",
"Intended Audience :: Information Technology",
"Intended Audience :: System Administrators",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Topic :: Internet :: Log Analysis",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content :: Page Counters",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware",
"Topic :: Security",
"Topic :: System :: Monitoring",
"Topic :: Utilities",
]
)
| [
"setuptools.find_packages",
"tracking.get_version"
] | [((170, 192), 'tracking.get_version', 'tracking.get_version', ([], {}), '()\n', (190, 192), False, 'import tracking\n'), ((572, 587), 'setuptools.find_packages', 'find_packages', ([], {}), '()\n', (585, 587), False, 'from setuptools import setup, find_packages\n')] |
#!/usr/bin/python
# (c) 2018, NetApp, Inc
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = """
---
module: update_file_list
short_description: Update log file containing comma separated list.
description:
- Add and remove items to comma separated list found in log file.
author: <NAME> (@ndswartz)
options:
file:
description: Absolute file path on remote system
required: True
type: str
item:
description: Item(s) to add or remove from file.
required: True
type: str
mode:
description: Whether to add or remove items.
required: False
default: "add"
choices: ["add", "remove", "content"]
type: str
"""
EXAMPLES = """
- update_file_list:
mode: add
file: /var/log/test
items:
- item3
- item4
- update_file_list:
mode: remove
file: /var/log/test
items:
- item2
- item3
- item5
"""
RETURN = """
msg:
description: Success message
returned: always
type: str
changed:
description: Whether change was made to the log file.
returned: always
type: str
list:
description: List of items in comma separated list
returned: always
type: list
"""
from ansible.module_utils.basic import AnsibleModule
class UpdateFileList(object):
def __init__(self):
ansible_options = dict(mode=dict(type='str', required=True, choices=["add", "remove", "content"]),
file=dict(type='str', required=True),
items=dict(type='list', required=False))
required_if = [["mode", "add", ["items"]], ["mode", "remove", ["items"]]]
self.module = AnsibleModule(argument_spec=ansible_options, required_if=required_if, supports_check_mode=True)
args = self.module.params
self.mode = args["mode"]
self.file = args["file"]
self.items_list = set()
self.items = set()
if self.mode in ["add", "remove"]:
for item in args["items"]:
self.items.add(item)
def add(self):
"""Add item(s) to list."""
for item in self.items:
if item not in self.items_list:
self.items_list.add(item)
def remove(self):
"""Remove item(s) from list."""
for item in self.items:
if item in self.items_list:
self.items_list.remove(item)
def update(self):
"""Initiate the file update."""
try:
fh = open(self.file, "r")
item_list = fh.read()
for item in item_list.split("\n"):
if item:
self.items_list.add(item)
except IOError as error:
pass
update_required = False
if self.items:
if self.mode == "add":
for item in self.items:
if item not in self.items_list:
update_required = True
elif self.mode == "remove":
for item in self.items:
if item in self.items_list:
update_required = True
if update_required and not self.module.check_mode:
if self.mode == "add":
self.add()
elif self.mode == "remove":
self.remove()
with open(self.file, "w") as fh:
fh.write("\n".join(self.items_list))
self.module.exit_json(msg="List is up to date.", list=self.items_list, changed=update_required)
def main():
item_list = UpdateFileList()
item_list.update()
if __name__ == '__main__':
main()
| [
"ansible.module_utils.basic.AnsibleModule"
] | [((1838, 1937), 'ansible.module_utils.basic.AnsibleModule', 'AnsibleModule', ([], {'argument_spec': 'ansible_options', 'required_if': 'required_if', 'supports_check_mode': '(True)'}), '(argument_spec=ansible_options, required_if=required_if,\n supports_check_mode=True)\n', (1851, 1937), False, 'from ansible.module_utils.basic import AnsibleModule\n')] |
import os
import subprocess
def render_movie(output_filename, frames_dir, frame_rate):
subprocess.call([
'ffmpeg', '-vcodec', 'png', '-framerate',
str(frame_rate), '-i',
os.path.join(frames_dir, r'frame.%06d.png'), '-pix_fmt', 'yuv420p',
'-vcodec', 'libx264', '-crf', '17', '-threads', '0', '-preset', 'slow',
'-y', output_filename + '.mp4'
])
| [
"os.path.join"
] | [((200, 242), 'os.path.join', 'os.path.join', (['frames_dir', '"""frame.%06d.png"""'], {}), "(frames_dir, 'frame.%06d.png')\n", (212, 242), False, 'import os\n')] |
import sys
import os
import numpy.random
from amuse.test import amusetest
from amuse.units import units, nbody_system
from amuse.ext.boss_bodenheimer import bb79_cloud
numpy.random.seed(1234567)
class BossBodenheimerTests(amusetest.TestCase):
def test1(self):
numpy.random.seed(1234)
mc=bb79_cloud(targetN=1000).result
self.assertEqual(len(mc),1000)
ek=mc.kinetic_energy()
ep=mc.potential_energy(G=nbody_system.G)
eth=mc.thermal_energy()
self.assertAlmostEqual(eth/ep, -0.25, 2)
self.assertAlmostEqual(ek/ep, -0.2, 2)
def test2(self):
numpy.random.seed(1234)
convert=nbody_system.nbody_to_si(1. | units.MSun,3.2e16| units.cm)
mc=bb79_cloud(targetN=1000,convert_nbody=convert).result
self.assertEqual(len(mc),1000)
ek=mc.kinetic_energy()
ep=mc.potential_energy()
eth=mc.thermal_energy()
self.assertAlmostEqual(eth/ep, -0.25, 2)
self.assertAlmostEqual(ek/ep, -0.2, 2)
| [
"amuse.ext.boss_bodenheimer.bb79_cloud",
"amuse.units.nbody_system.nbody_to_si"
] | [((659, 721), 'amuse.units.nbody_system.nbody_to_si', 'nbody_system.nbody_to_si', (['(1.0 | units.MSun)', '(3.2e+16 | units.cm)'], {}), '(1.0 | units.MSun, 3.2e+16 | units.cm)\n', (683, 721), False, 'from amuse.units import units, nbody_system\n'), ((310, 334), 'amuse.ext.boss_bodenheimer.bb79_cloud', 'bb79_cloud', ([], {'targetN': '(1000)'}), '(targetN=1000)\n', (320, 334), False, 'from amuse.ext.boss_bodenheimer import bb79_cloud\n'), ((729, 776), 'amuse.ext.boss_bodenheimer.bb79_cloud', 'bb79_cloud', ([], {'targetN': '(1000)', 'convert_nbody': 'convert'}), '(targetN=1000, convert_nbody=convert)\n', (739, 776), False, 'from amuse.ext.boss_bodenheimer import bb79_cloud\n')] |
#!/usr/bin/env python
# Copyright 2018- The Pixie Authors.
#
# 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.
#
# SPDX-License-Identifier: Apache-2.0
import socket
import ssl
import time
import random
host_addr = '127.0.0.1'
host_port = 8082
server_sni_hostname = 'example.com'
client_cert = 'client.crt'
client_key = 'client.key'
server_cert = 'server.crt'
context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH, cafile=server_cert)
context.load_cert_chain(certfile=client_cert, keyfile=client_key)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
conn = context.wrap_socket(s, server_side=False, server_hostname=server_sni_hostname)
conn.connect((host_addr, host_port))
print("SSL established.")
count = 0
while True:
time.sleep(1)
secret = random.randint(0, 1024 * 1024 * 1024)
conn.send("Client secret {} is {}".format(count, secret).encode())
data = conn.recv(1024)
print(data.decode())
count += 1
print("Closing connection")
conn.close()
| [
"ssl.create_default_context",
"time.sleep",
"random.randint",
"socket.socket"
] | [((868, 939), 'ssl.create_default_context', 'ssl.create_default_context', (['ssl.Purpose.SERVER_AUTH'], {'cafile': 'server_cert'}), '(ssl.Purpose.SERVER_AUTH, cafile=server_cert)\n', (894, 939), False, 'import ssl\n'), ((1011, 1060), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (1024, 1060), False, 'import socket\n'), ((1237, 1250), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (1247, 1250), False, 'import time\n'), ((1264, 1301), 'random.randint', 'random.randint', (['(0)', '(1024 * 1024 * 1024)'], {}), '(0, 1024 * 1024 * 1024)\n', (1278, 1301), False, 'import random\n')] |
"""
Copyright 2012-2019 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from hqlib import utils
from .alerts_metrics import AlertsMetric
from ... import metric_source
class OWASPDependencyWarnings(AlertsMetric):
""" Base class for metrics that measure the number of external dependencies of the project that have OWASP
warnings with a certain priority. """
unit = 'waarschuwingen'
norm_template = 'Dependencies van het product hebben geen {risk_level} prioriteit OWASP {unit}. ' \
'Meer dan {low_target} is rood.'
template = 'Dependencies van {name} hebben {value} {risk_level} prioriteit {unit}.'
metric_source_class = metric_source.OWASPDependencyReport
extra_info_headers = {
"dependency": "Dependency",
"CVE_count": "Aantal CVE's__detail-column-number",
"links": "CVE's"
}
def extra_info_rows(self) -> list:
metric_source_ids = self._get_metric_source_ids()
dependencies = []
for metric_id in metric_source_ids:
dependencies += self._metric_source.get_dependencies_info(metric_id, self.risk_level_key)
return dependencies
def convert_item_to_extra_info(self, item: metric_source.Dependency) -> (str, str, int, list):
""" Transform a dependency item to a link and integer. """
cves = []
for cve in item.cve_links:
cves.append(utils.format_link_object(cve[1], cve[0]) if item.cve_links else '')
return (item.file_name, item.nr_vulnerabilities, tuple(cves)) if item else None
def _nr_alerts(self) -> int:
""" Return the number of warnings. """
ids = self._get_metric_source_ids()
return self._metric_source.nr_warnings(tuple(ids), self.risk_level_key) if self._metric_source else -1
class HighPriorityOWASPDependencyWarnings(OWASPDependencyWarnings):
""" Metric for measuring the number of external dependencies of the project that have high priority OWASP
warnings. """
name = 'Hoeveelheid OWASP dependency waarschuwingen met hoge prioriteit'
risk_level = 'hoge'
risk_level_key = 'high'
low_target_value = 3
url_label_text = "Waarschuwingen met hoge prioriteit"
class NormalPriorityOWASPDependencyWarnings(OWASPDependencyWarnings):
""" Metric for measuring the number of external dependencies of the project that have high priority OWASP
warnings. """
name = 'Hoeveelheid OWASP dependency waarschuwingen met normale prioriteit'
risk_level = 'normale'
risk_level_key = 'normal'
low_target_value = 10
url_label_text = "Waarschuwingen met normale prioriteit"
| [
"hqlib.utils.format_link_object"
] | [((1893, 1933), 'hqlib.utils.format_link_object', 'utils.format_link_object', (['cve[1]', 'cve[0]'], {}), '(cve[1], cve[0])\n', (1917, 1933), False, 'from hqlib import utils\n')] |
# This script goes through OpenSim funcionalties
# required for OpenSim-RL
import opensim
# Settings
stepsize = 0.01
# Load existing model
model_path = "../osim/models/gait9dof18musc.osim"
model = opensim.Model(model_path)
model.setUseVisualizer(True)
# Create the ball
r = 0.000001
ballBody = opensim.Body('ball', 0.0001 , opensim.Vec3(0), opensim.Inertia(1,1,.0001,0,0,0) );
ballGeometry = opensim.Ellipsoid(r, r, r)
ballGeometry.setColor(opensim.Gray)
ballBody.attachGeometry(ballGeometry)
# Attach ball to the model
ballJoint = opensim.FreeJoint("weldball",
model.getGround(), # PhysicalFrame
opensim.Vec3(0, 0, 0),
opensim.Vec3(0, 0, 0),
ballBody, # PhysicalFrame
opensim.Vec3(0, 0, 0),
opensim.Vec3(0, 0, 0))
model.addComponent(ballJoint)
model.addComponent(ballBody)
# Add contact
ballContact = opensim.ContactSphere(r, opensim.Vec3(0,0,0), ballBody);
model.addContactGeometry(ballContact)
# Reinitialize the system with the new controller
state = model.initSystem()
for i in range(6):
ballJoint.getCoordinate(i).setLocked(state, True)
state.setTime(0)
manager = opensim.Manager(model)
manager.setIntegratorAccuracy(5e-4)
manager.initialize(state)
# Simulate
for i in range(100):
manager.integrate(i + stepsize)
# Restart the model every 10 frames, with the new position of the ball
if (i + 1) % 10 == 0:
newloc = opensim.Vec3(float(i) / 5, 0, 0)
opensim.PhysicalOffsetFrame.safeDownCast(ballJoint.getChildFrame()).set_translation(newloc)
r = i * 0.005
#ballGeometry.set_radii(opensim.Vec3(r,r,r))
#ballBody.scale(opensim.Vec3(r, r, r))
ballContact.setRadius(r)
state = model.initializeState()
ballJoint.getCoordinate(3).setValue(state, i / 100.0)
for i in range(6):
ballJoint.getCoordinate(i).setLocked(state, True)
| [
"opensim.Manager",
"opensim.Model",
"opensim.Inertia",
"opensim.Ellipsoid",
"opensim.Vec3"
] | [((208, 233), 'opensim.Model', 'opensim.Model', (['model_path'], {}), '(model_path)\n', (221, 233), False, 'import opensim\n'), ((410, 436), 'opensim.Ellipsoid', 'opensim.Ellipsoid', (['r', 'r', 'r'], {}), '(r, r, r)\n', (427, 436), False, 'import opensim\n'), ((1273, 1295), 'opensim.Manager', 'opensim.Manager', (['model'], {}), '(model)\n', (1288, 1295), False, 'import opensim\n'), ((341, 356), 'opensim.Vec3', 'opensim.Vec3', (['(0)'], {}), '(0)\n', (353, 356), False, 'import opensim\n'), ((358, 396), 'opensim.Inertia', 'opensim.Inertia', (['(1)', '(1)', '(0.0001)', '(0)', '(0)', '(0)'], {}), '(1, 1, 0.0001, 0, 0, 0)\n', (373, 396), False, 'import opensim\n'), ((673, 694), 'opensim.Vec3', 'opensim.Vec3', (['(0)', '(0)', '(0)'], {}), '(0, 0, 0)\n', (685, 694), False, 'import opensim\n'), ((722, 743), 'opensim.Vec3', 'opensim.Vec3', (['(0)', '(0)', '(0)'], {}), '(0, 0, 0)\n', (734, 743), False, 'import opensim\n'), ((823, 844), 'opensim.Vec3', 'opensim.Vec3', (['(0)', '(0)', '(0)'], {}), '(0, 0, 0)\n', (835, 844), False, 'import opensim\n'), ((872, 893), 'opensim.Vec3', 'opensim.Vec3', (['(0)', '(0)', '(0)'], {}), '(0, 0, 0)\n', (884, 893), False, 'import opensim\n'), ((1013, 1034), 'opensim.Vec3', 'opensim.Vec3', (['(0)', '(0)', '(0)'], {}), '(0, 0, 0)\n', (1025, 1034), False, 'import opensim\n')] |
#!/usr/bin/env python
import os
import sys
BASE_APP_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(os.path.join(BASE_APP_DIR, 'src/'))
sys.path.append(os.path.join(BASE_APP_DIR, 'venv/lib/python3.4/site-packages'))
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application() | [
"os.environ.setdefault",
"django.core.wsgi.get_wsgi_application",
"os.path.join",
"os.path.abspath"
] | [((253, 316), 'os.environ.setdefault', 'os.environ.setdefault', (['"""DJANGO_SETTINGS_MODULE"""', '"""app.settings"""'], {}), "('DJANGO_SETTINGS_MODULE', 'app.settings')\n", (274, 316), False, 'import os\n'), ((382, 404), 'django.core.wsgi.get_wsgi_application', 'get_wsgi_application', ([], {}), '()\n', (402, 404), False, 'from django.core.wsgi import get_wsgi_application\n'), ((136, 170), 'os.path.join', 'os.path.join', (['BASE_APP_DIR', '"""src/"""'], {}), "(BASE_APP_DIR, 'src/')\n", (148, 170), False, 'import os\n'), ((188, 250), 'os.path.join', 'os.path.join', (['BASE_APP_DIR', '"""venv/lib/python3.4/site-packages"""'], {}), "(BASE_APP_DIR, 'venv/lib/python3.4/site-packages')\n", (200, 250), False, 'import os\n'), ((91, 116), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (106, 116), False, 'import os\n')] |
# Generated by Django 3.1.7 on 2021-04-07 15:24
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('projectroles', '0019_project_public_guest_access'),
('timeline', '0006_update_user_optional'),
]
operations = [
migrations.AlterField(
model_name='projectevent',
name='project',
field=models.ForeignKey(help_text='Project to which the event belongs (null for no project)', null=True, on_delete=django.db.models.deletion.CASCADE, related_name='events', to='projectroles.project'),
),
]
| [
"django.db.models.ForeignKey"
] | [((441, 648), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'help_text': '"""Project to which the event belongs (null for no project)"""', 'null': '(True)', 'on_delete': 'django.db.models.deletion.CASCADE', 'related_name': '"""events"""', 'to': '"""projectroles.project"""'}), "(help_text=\n 'Project to which the event belongs (null for no project)', null=True,\n on_delete=django.db.models.deletion.CASCADE, related_name='events', to=\n 'projectroles.project')\n", (458, 648), False, 'from django.db import migrations, models\n')] |
from collections import defaultdict
def dict_sample_target_iter_concat(sample_target_iter: iter):
"""Gets an sample target iterator of dict samples.
Returns a concatenation of the samples based on each key and the
target list.
Example:
::
sample_target_iter = [({'a': 'a1', 'b': 'b1'}, 0), ({'a': 'a2', 'b': 'b2'}, 1)]
x = dict_sample_iter_concat([({'a': 'a1', 'b': 'b1'}, 0), ({'a': 'a2', 'b': 'b2'}, 1)])
print(x)
({'a': ['a1', 'a2'], 'b': ['b1', 'b2']}, [0, 1])
"""
samples = defaultdict(list)
targets = []
for sample_dict, y in sample_target_iter:
for k, v in sample_dict.items():
samples[k].append(v)
targets.append(y)
samples = dict(samples)
length = len(samples[next(iter(samples))])
assert all(len(samples[k]) == length for k in samples)
return samples, targets | [
"collections.defaultdict"
] | [((546, 563), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (557, 563), False, 'from collections import defaultdict\n')] |
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from tapi_server.models.base_model_ import Model
from tapi_server.models.tapi_common_local_class import TapiCommonLocalClass # noqa: F401,E501
from tapi_server.models.tapi_common_name_and_value import TapiCommonNameAndValue # noqa: F401,E501
from tapi_server.models.tapi_common_time_period import TapiCommonTimePeriod # noqa: F401,E501
from tapi_server import util
class TapiOamPmHistoryData(Model):
"""NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
Do not edit the class manually.
"""
def __init__(self, name=None, local_id=None, granularity_period=None, period_end_time=None, suspect_interval_flag=False): # noqa: E501
"""TapiOamPmHistoryData - a model defined in OpenAPI
:param name: The name of this TapiOamPmHistoryData. # noqa: E501
:type name: List[TapiCommonNameAndValue]
:param local_id: The local_id of this TapiOamPmHistoryData. # noqa: E501
:type local_id: str
:param granularity_period: The granularity_period of this TapiOamPmHistoryData. # noqa: E501
:type granularity_period: TapiCommonTimePeriod
:param period_end_time: The period_end_time of this TapiOamPmHistoryData. # noqa: E501
:type period_end_time: str
:param suspect_interval_flag: The suspect_interval_flag of this TapiOamPmHistoryData. # noqa: E501
:type suspect_interval_flag: bool
"""
self.openapi_types = {
'name': List[TapiCommonNameAndValue],
'local_id': str,
'granularity_period': TapiCommonTimePeriod,
'period_end_time': str,
'suspect_interval_flag': bool
}
self.attribute_map = {
'name': 'name',
'local_id': 'local-id',
'granularity_period': 'granularity-period',
'period_end_time': 'period-end-time',
'suspect_interval_flag': 'suspect-interval-flag'
}
self._name = name
self._local_id = local_id
self._granularity_period = granularity_period
self._period_end_time = period_end_time
self._suspect_interval_flag = suspect_interval_flag
@classmethod
def from_dict(cls, dikt) -> 'TapiOamPmHistoryData':
"""Returns the dict as a model
:param dikt: A dict.
:type: dict
:return: The tapi.oam.PmHistoryData of this TapiOamPmHistoryData. # noqa: E501
:rtype: TapiOamPmHistoryData
"""
return util.deserialize_model(dikt, cls)
@property
def name(self):
"""Gets the name of this TapiOamPmHistoryData.
List of names. A property of an entity with a value that is unique in some namespace but may change during the life of the entity. A name carries no semantics with respect to the purpose of the entity. # noqa: E501
:return: The name of this TapiOamPmHistoryData.
:rtype: List[TapiCommonNameAndValue]
"""
return self._name
@name.setter
def name(self, name):
"""Sets the name of this TapiOamPmHistoryData.
List of names. A property of an entity with a value that is unique in some namespace but may change during the life of the entity. A name carries no semantics with respect to the purpose of the entity. # noqa: E501
:param name: The name of this TapiOamPmHistoryData.
:type name: List[TapiCommonNameAndValue]
"""
self._name = name
@property
def local_id(self):
"""Gets the local_id of this TapiOamPmHistoryData.
none # noqa: E501
:return: The local_id of this TapiOamPmHistoryData.
:rtype: str
"""
return self._local_id
@local_id.setter
def local_id(self, local_id):
"""Sets the local_id of this TapiOamPmHistoryData.
none # noqa: E501
:param local_id: The local_id of this TapiOamPmHistoryData.
:type local_id: str
"""
self._local_id = local_id
@property
def granularity_period(self):
"""Gets the granularity_period of this TapiOamPmHistoryData.
:return: The granularity_period of this TapiOamPmHistoryData.
:rtype: TapiCommonTimePeriod
"""
return self._granularity_period
@granularity_period.setter
def granularity_period(self, granularity_period):
"""Sets the granularity_period of this TapiOamPmHistoryData.
:param granularity_period: The granularity_period of this TapiOamPmHistoryData.
:type granularity_period: TapiCommonTimePeriod
"""
self._granularity_period = granularity_period
@property
def period_end_time(self):
"""Gets the period_end_time of this TapiOamPmHistoryData.
none # noqa: E501
:return: The period_end_time of this TapiOamPmHistoryData.
:rtype: str
"""
return self._period_end_time
@period_end_time.setter
def period_end_time(self, period_end_time):
"""Sets the period_end_time of this TapiOamPmHistoryData.
none # noqa: E501
:param period_end_time: The period_end_time of this TapiOamPmHistoryData.
:type period_end_time: str
"""
self._period_end_time = period_end_time
@property
def suspect_interval_flag(self):
"""Gets the suspect_interval_flag of this TapiOamPmHistoryData.
This attribute indicates that the performance data may not be reliable. # noqa: E501
:return: The suspect_interval_flag of this TapiOamPmHistoryData.
:rtype: bool
"""
return self._suspect_interval_flag
@suspect_interval_flag.setter
def suspect_interval_flag(self, suspect_interval_flag):
"""Sets the suspect_interval_flag of this TapiOamPmHistoryData.
This attribute indicates that the performance data may not be reliable. # noqa: E501
:param suspect_interval_flag: The suspect_interval_flag of this TapiOamPmHistoryData.
:type suspect_interval_flag: bool
"""
self._suspect_interval_flag = suspect_interval_flag
| [
"tapi_server.util.deserialize_model"
] | [((2650, 2683), 'tapi_server.util.deserialize_model', 'util.deserialize_model', (['dikt', 'cls'], {}), '(dikt, cls)\n', (2672, 2683), False, 'from tapi_server import util\n')] |
from projex.lazymodule import lazy_import
from ..sqliteconnection import SQLiteStatement
orb = lazy_import('orb')
class CREATE(SQLiteStatement):
def __call__(self, model, owner='', includeReferences=True):
if issubclass(model, orb.Table):
return self._createTable(model, owner, includeReferences)
elif issubclass(model, orb.View):
return self._createView(model, owner, includeReferences)
else:
raise orb.errors.OrbError('Cannot create model for type: '.format(type(model)))
def _createTable(self, model, owner, includeReferences):
ADD_COLUMN = self.byName('ADD COLUMN')
add_i18n = []
add_standard = []
# divide columns between standard and translatable
for col in model.schema().columns(recurse=False).values():
if col.testFlag(col.Flags.Virtual):
continue
if not includeReferences and isinstance(col, orb.ReferenceColumn):
continue
if col.testFlag(col.Flags.I18n):
add_i18n.append(col)
else:
add_standard.append(col)
# create the standard model
cmd_body = []
if add_standard:
cmd_body += [ADD_COLUMN(col)[0].replace('ADD COLUMN ', '') for col in add_standard]
inherits = model.schema().inherits()
if inherits:
inherits_model = orb.system.model(inherits)
if not inherits_model:
raise orb.errors.ModelNotFound(schema=inherits)
cmd_body.append('__base_id INTEGER')
# get the primary column
id_column = model.schema().idColumn()
if id_column and not inherits:
pcol = '`{0}`'.format(id_column.field())
cmd_body.append('CONSTRAINT `{0}_pkey` PRIMARY KEY ({1})'.format(model.schema().dbname(), pcol))
body = ',\n\t'.join(cmd_body)
if body:
body = '\n\t' + body + '\n'
cmd = 'CREATE TABLE IF NOT EXISTS `{table}` ({body});\n'
cmd = cmd.format(table=model.schema().dbname(), body=body, owner=owner)
# create the i18n model
if add_i18n:
id_column = model.schema().idColumn()
id_type = id_column.dbType('SQLite')
i18n_body = ',\n\t'.join([ADD_COLUMN(col)[0].replace('ADD COLUMN ', '') for col in add_i18n])
i18n_cmd = 'CREATE TABLE `{table}_i18n` (\n'
i18n_cmd += ' `locale` CHARACTER VARYING(5),\n'
i18n_cmd += ' `{table}_id` {id_type} REFERENCES `{table}` ({pcol}),\n'
i18n_cmd += ' {body},\n'
i18n_cmd += ' CONSTRAINT `{table}_i18n_pkey` PRIMARY KEY (`{table}_id`, `locale`)\n'
i18n_cmd += ');\n'
i18n_cmd = i18n_cmd.format(table=model.schema().dbname(),
id_type=id_type, pcol=pcol, body=i18n_body, owner=owner)
cmd += '\n' + i18n_cmd
return cmd, {}
SQLiteStatement.registerAddon('CREATE', CREATE()) | [
"projex.lazymodule.lazy_import"
] | [((96, 114), 'projex.lazymodule.lazy_import', 'lazy_import', (['"""orb"""'], {}), "('orb')\n", (107, 114), False, 'from projex.lazymodule import lazy_import\n')] |
from raytkTools import RaytkTools
# noinspection PyUnreachableCode
if False:
# noinspection PyUnresolvedReferences
from _stubs import *
from ..ropEditor.ropEditor import ROPEditor
iop.ropEditor = ROPEditor(COMP())
class CreateRopDialog:
def __init__(self, ownerComp: 'COMP'):
self.ownerComp = ownerComp
def _setMessageText(self, message):
dat = self.ownerComp.op('set_messageText')
dat.clear()
dat.write(message or '')
def Open(self, _=None):
self.ownerComp.op('window').par.winopen.pulse()
self.ownerComp.op('typeName_field').par.Value0 = ''
self._setMessageText('')
def Close(self, _=None):
self.ownerComp.op('window').par.winclose.pulse()
self._setMessageText('')
def Create(self):
self._setMessageText('')
category = self.ownerComp.op('category_dropmenu').par.Value0.eval()
name = self.ownerComp.op('typeName_field').par.Value0.eval()
try:
rop = RaytkTools().createNewRopType(typeName=name, category=category)
except Exception as err:
self._setMessageText(str(err))
return
iop.ropEditor.LoadROP(rop)
self.Close()
| [
"raytkTools.RaytkTools"
] | [((894, 906), 'raytkTools.RaytkTools', 'RaytkTools', ([], {}), '()\n', (904, 906), False, 'from raytkTools import RaytkTools\n')] |
"""
Test the stream module
Does it provide an interface compatible with circus?
"""
from calendar import timegm
from io import StringIO
from pytest import fixture
from mock import patch
from codado import parseDate, py
from circusbase import stream
@fixture
def stdoutStream(pRemoji):
ret = stream.EmojiStdoutStream()
ret._out = StringIO()
return ret
@fixture
def pRemoji():
"""
A function that returns "random" choices
"""
with patch.object(stream, 'remoji', side_effect=[py.EMOJI[2], py.EMOJI[4]]):
yield
def test_stream(stdoutStream):
"""
Does it add the prefix before writing?
"""
_1109 = parseDate('2018-11-09 11:11:11-0800')
data = {
'data': 'hello dolly',
'pid': 999,
'timestamp': timegm(_1109.timetuple())
}
stdoutStream(data)
# fyi there's a change in the timezone due to our use of timegm,
# and we don't account for it here.
expected = '2018-11-09 03:11:11 [999] 🤖 💫 | hello dolly\n'
assert stdoutStream.out.getvalue() == expected
stdoutStream.out.truncate(0)
stdoutStream.out.seek(0)
data2 = data.copy()
del data2['timestamp']
with patch.object(stdoutStream, 'now', return_value=_1109):
stdoutStream(data2)
expected = '2018-11-09 11:11:11 [999] 🤖 💫 | hello dolly\n'
assert stdoutStream.out.getvalue() == expected
| [
"mock.patch.object",
"circusbase.stream.EmojiStdoutStream",
"io.StringIO",
"codado.parseDate"
] | [((302, 328), 'circusbase.stream.EmojiStdoutStream', 'stream.EmojiStdoutStream', ([], {}), '()\n', (326, 328), False, 'from circusbase import stream\n'), ((344, 354), 'io.StringIO', 'StringIO', ([], {}), '()\n', (352, 354), False, 'from io import StringIO\n'), ((656, 693), 'codado.parseDate', 'parseDate', (['"""2018-11-09 11:11:11-0800"""'], {}), "('2018-11-09 11:11:11-0800')\n", (665, 693), False, 'from codado import parseDate, py\n'), ((466, 536), 'mock.patch.object', 'patch.object', (['stream', '"""remoji"""'], {'side_effect': '[py.EMOJI[2], py.EMOJI[4]]'}), "(stream, 'remoji', side_effect=[py.EMOJI[2], py.EMOJI[4]])\n", (478, 536), False, 'from mock import patch\n'), ((1181, 1234), 'mock.patch.object', 'patch.object', (['stdoutStream', '"""now"""'], {'return_value': '_1109'}), "(stdoutStream, 'now', return_value=_1109)\n", (1193, 1234), False, 'from mock import patch\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 19 15:37:36 2018
@author: phoenix
"""
import glob
path = glob.glob('dataset/*')
for each in path:
print(glob.glob(each+'/*')[0].split('/')[1])
dynamic_dict = { glob.glob(each+'/*')[0].split('/')[1]:glob.glob(each+'/*')[0] for each in path}
print(dynamic_dict) | [
"glob.glob"
] | [((130, 152), 'glob.glob', 'glob.glob', (['"""dataset/*"""'], {}), "('dataset/*')\n", (139, 152), False, 'import glob\n'), ((276, 298), 'glob.glob', 'glob.glob', (["(each + '/*')"], {}), "(each + '/*')\n", (285, 298), False, 'import glob\n'), ((238, 260), 'glob.glob', 'glob.glob', (["(each + '/*')"], {}), "(each + '/*')\n", (247, 260), False, 'import glob\n'), ((181, 203), 'glob.glob', 'glob.glob', (["(each + '/*')"], {}), "(each + '/*')\n", (190, 203), False, 'import glob\n')] |
import typer
cli = typer.Typer()
| [
"typer.Typer"
] | [((20, 33), 'typer.Typer', 'typer.Typer', ([], {}), '()\n', (31, 33), False, 'import typer\n')] |
"""ResNets.
With only TensorFlow backend.
Follows fchollet's design
Author: <NAME>
Email : <EMAIL>
"""
from __future__ import print_function, absolute_import
from builtins import range
from spiker import log
logger = log.get_logger("models-resnet", log.DEBUG)
try:
from keras.layers import Input
from keras.layers import Dense
from keras.layers import Conv2D
from keras.layers import BatchNormalization
from keras.layers import Activation
from keras.layers import GlobalAveragePooling2D
from keras.layers import add
from keras.models import Model
from keras.regularizers import l2
except ImportError:
logger.critical("There is no keras available.")
def resnet_block(input_tensor, kernel_size,
filters, stage, block, strides=(2, 2),
block_type="identity", bottleneck=True):
"""ResNet Block.
Parameters
----------
input_tensors : Keras tensor
input tensor
kernel_size :
"""
filters1, filters2, filters3 = filters
bn_axis = 3
conv_name_base = "res"+str(stage)+block+"_branch"
bn_name_base = "bn"+str(stage)+block+"_branch"
shortcut = Conv2D(filters3, (1, 1), strides=strides,
kernel_initializer="he_normal",
kernel_regularizer=l2(0.0001),
bias_initializer="zeros",
name=conv_name_base+"1")(input_tensor) \
if block_type == "conv" else input_tensor
# first transition
if bottleneck is True:
x = Conv2D(filters1, (1, 1), strides=strides,
kernel_initializer="he_normal",
kernel_regularizer=l2(0.0001),
bias_initializer="zeros",
name=conv_name_base+"2a")(input_tensor) \
if block_type == "conv" else \
Conv2D(filters1, (1, 1),
kernel_initializer="he_normal",
kernel_regularizer=l2(0.0001),
bias_initializer="zeros",
name=conv_name_base+"2a")(input_tensor)
else:
x = Conv2D(filters1, kernel_size, strides=strides,
padding="same",
kernel_initializer="he_normal",
kernel_regularizer=l2(0.0001),
bias_initializer="zeros",
name=conv_name_base+"2a")(input_tensor) \
if block_type == "conv" else \
Conv2D(filters1, kernel_size,
padding="same",
kernel_initializer="he_normal",
kernel_regularizer=l2(0.0001),
bias_initializer="zeros",
name=conv_name_base+"2a")(input_tensor)
x = BatchNormalization(axis=bn_axis, name=bn_name_base+"2a")(x)
x = Activation("relu")(x)
# second transition
x = Conv2D(filters2, kernel_size,
kernel_initializer="he_normal",
kernel_regularizer=l2(0.0001),
bias_initializer="zeros",
padding="same", name=conv_name_base+"2b")(x)
x = BatchNormalization(axis=bn_axis, name=bn_name_base+"2b")(x)
if bottleneck is True:
x = Activation("relu")(x)
# third transition
if bottleneck is True:
x = Conv2D(filters3, (1, 1),
kernel_initializer="he_normal",
kernel_regularizer=l2(0.0001),
bias_initializer="zeros",
name=conv_name_base+"2c")(x)
x = BatchNormalization(axis=bn_axis, name=bn_name_base+"2c")(x)
# merge
x = add([x, shortcut])
x = Activation("relu")(x)
return x
def resnet_builder(model_name, input_shape, batch_size, filter_list,
kernel_size, output_dim, stages, blocks, bottleneck=True,
network_type="regress", conv_only=False):
"""Build ResNet.
TODO: add more flexiblities to initialization, regularization, etc
"""
bn_axis = 3
# prepare input
# img_input = Input(batch_shape=(batch_size,)+input_shape)
img_input = Input(shape=input_shape)
# pre stage
x = Conv2D(filter_list[0][-1], kernel_size, padding="same",
kernel_initializer="he_normal",
kernel_regularizer=l2(0.0001),
bias_initializer="zeros",
name="conv1")(img_input)
x = BatchNormalization(axis=bn_axis, name="bn_conv1")(x)
x = Activation("relu")(x)
# first stage
# for block_idx in range(blocks):
# x = resnet_block(x, kernel_size, filter_list[0],
# 1, str(block_idx+1), strides=(1, 1),
# block_type="identity", bottleneck=bottleneck)
for stage_idx in range(0, stages):
# input block
x = resnet_block(x, kernel_size, filter_list[stage_idx],
stage_idx+1, "1", strides=(2, 2),
block_type="conv", bottleneck=bottleneck)
for block_idx in range(1, blocks):
x = resnet_block(x, kernel_size, filter_list[stage_idx],
stage_idx+1, str(block_idx+1), strides=(1, 1),
block_type="identity", bottleneck=bottleneck)
# post stage
x = BatchNormalization(axis=bn_axis)(x)
x = Activation("relu")(x)
x = GlobalAveragePooling2D(data_format="channels_last",
name="avg-pool")(x)
# Return current function if only returns convolution part
if conv_only:
return img_input, x
if network_type == "corl":
steering = Dense(output_dim,
kernel_initializer="he_normal",
kernel_regularizer=l2(0.0001),
bias_initializer="zeros",
name="steering")(x)
throttle = Dense(output_dim,
kernel_initializer="he_normal",
kernel_regularizer=l2(0.0001),
bias_initializer="zeros",
name="throttle")(x)
else:
x = Dense(output_dim,
kernel_initializer="he_normal",
kernel_regularizer=l2(0.0001),
bias_initializer="zeros",
name="output")(x)
# for classification
if network_type == "class":
x = Activation("softmax")(x)
elif network_type == "binary":
x = Activation("sigmoid")(x)
if network_type == "corl":
model = Model(img_input, [steering, throttle], name=model_name)
else:
model = Model(img_input, x, name=model_name)
return model
| [
"keras.layers.add",
"keras.layers.Input",
"builtins.range",
"spiker.log.get_logger",
"keras.layers.Activation",
"keras.models.Model",
"keras.regularizers.l2",
"keras.layers.GlobalAveragePooling2D",
"keras.layers.BatchNormalization"
] | [((222, 264), 'spiker.log.get_logger', 'log.get_logger', (['"""models-resnet"""', 'log.DEBUG'], {}), "('models-resnet', log.DEBUG)\n", (236, 264), False, 'from spiker import log\n'), ((3569, 3587), 'keras.layers.add', 'add', (['[x, shortcut]'], {}), '([x, shortcut])\n', (3572, 3587), False, 'from keras.layers import add\n'), ((4059, 4083), 'keras.layers.Input', 'Input', ([], {'shape': 'input_shape'}), '(shape=input_shape)\n', (4064, 4083), False, 'from keras.layers import Input\n'), ((4709, 4725), 'builtins.range', 'range', (['(0)', 'stages'], {}), '(0, stages)\n', (4714, 4725), False, 'from builtins import range\n'), ((2718, 2776), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': 'bn_axis', 'name': "(bn_name_base + '2a')"}), "(axis=bn_axis, name=bn_name_base + '2a')\n", (2736, 2776), False, 'from keras.layers import BatchNormalization\n'), ((2786, 2804), 'keras.layers.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (2796, 2804), False, 'from keras.layers import Activation\n'), ((3073, 3131), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': 'bn_axis', 'name': "(bn_name_base + '2b')"}), "(axis=bn_axis, name=bn_name_base + '2b')\n", (3091, 3131), False, 'from keras.layers import BatchNormalization\n'), ((3596, 3614), 'keras.layers.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (3606, 3614), False, 'from keras.layers import Activation\n'), ((4347, 4396), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': 'bn_axis', 'name': '"""bn_conv1"""'}), "(axis=bn_axis, name='bn_conv1')\n", (4365, 4396), False, 'from keras.layers import BatchNormalization\n'), ((4408, 4426), 'keras.layers.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (4418, 4426), False, 'from keras.layers import Activation\n'), ((4965, 4981), 'builtins.range', 'range', (['(1)', 'blocks'], {}), '(1, blocks)\n', (4970, 4981), False, 'from builtins import range\n'), ((5229, 5261), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': 'bn_axis'}), '(axis=bn_axis)\n', (5247, 5261), False, 'from keras.layers import BatchNormalization\n'), ((5273, 5291), 'keras.layers.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (5283, 5291), False, 'from keras.layers import Activation\n'), ((5303, 5371), 'keras.layers.GlobalAveragePooling2D', 'GlobalAveragePooling2D', ([], {'data_format': '"""channels_last"""', 'name': '"""avg-pool"""'}), "(data_format='channels_last', name='avg-pool')\n", (5325, 5371), False, 'from keras.layers import GlobalAveragePooling2D\n'), ((6474, 6529), 'keras.models.Model', 'Model', (['img_input', '[steering, throttle]'], {'name': 'model_name'}), '(img_input, [steering, throttle], name=model_name)\n', (6479, 6529), False, 'from keras.models import Model\n'), ((6556, 6592), 'keras.models.Model', 'Model', (['img_input', 'x'], {'name': 'model_name'}), '(img_input, x, name=model_name)\n', (6561, 6592), False, 'from keras.models import Model\n'), ((3172, 3190), 'keras.layers.Activation', 'Activation', (['"""relu"""'], {}), "('relu')\n", (3182, 3190), False, 'from keras.layers import Activation\n'), ((3488, 3546), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {'axis': 'bn_axis', 'name': "(bn_name_base + '2c')"}), "(axis=bn_axis, name=bn_name_base + '2c')\n", (3506, 3546), False, 'from keras.layers import BatchNormalization\n'), ((6329, 6350), 'keras.layers.Activation', 'Activation', (['"""softmax"""'], {}), "('softmax')\n", (6339, 6350), False, 'from keras.layers import Activation\n'), ((2952, 2962), 'keras.regularizers.l2', 'l2', (['(0.0001)'], {}), '(0.0001)\n', (2954, 2962), False, 'from keras.regularizers import l2\n'), ((4246, 4256), 'keras.regularizers.l2', 'l2', (['(0.0001)'], {}), '(0.0001)\n', (4248, 4256), False, 'from keras.regularizers import l2\n'), ((6401, 6422), 'keras.layers.Activation', 'Activation', (['"""sigmoid"""'], {}), "('sigmoid')\n", (6411, 6422), False, 'from keras.layers import Activation\n'), ((1304, 1314), 'keras.regularizers.l2', 'l2', (['(0.0001)'], {}), '(0.0001)\n', (1306, 1314), False, 'from keras.regularizers import l2\n'), ((3371, 3381), 'keras.regularizers.l2', 'l2', (['(0.0001)'], {}), '(0.0001)\n', (3373, 3381), False, 'from keras.regularizers import l2\n'), ((5686, 5696), 'keras.regularizers.l2', 'l2', (['(0.0001)'], {}), '(0.0001)\n', (5688, 5696), False, 'from keras.regularizers import l2\n'), ((5932, 5942), 'keras.regularizers.l2', 'l2', (['(0.0001)'], {}), '(0.0001)\n', (5934, 5942), False, 'from keras.regularizers import l2\n'), ((6167, 6177), 'keras.regularizers.l2', 'l2', (['(0.0001)'], {}), '(0.0001)\n', (6169, 6177), False, 'from keras.regularizers import l2\n'), ((1671, 1681), 'keras.regularizers.l2', 'l2', (['(0.0001)'], {}), '(0.0001)\n', (1673, 1681), False, 'from keras.regularizers import l2\n'), ((1958, 1968), 'keras.regularizers.l2', 'l2', (['(0.0001)'], {}), '(0.0001)\n', (1960, 1968), False, 'from keras.regularizers import l2\n'), ((2267, 2277), 'keras.regularizers.l2', 'l2', (['(0.0001)'], {}), '(0.0001)\n', (2269, 2277), False, 'from keras.regularizers import l2\n'), ((2594, 2604), 'keras.regularizers.l2', 'l2', (['(0.0001)'], {}), '(0.0001)\n', (2596, 2604), False, 'from keras.regularizers import l2\n')] |
from pathlib import Path
from openpecha import formatters
from openpecha.formatters import PedurmaFormatter
from openpecha.serializers import PedurmaSerializer
if __name__ == "__main__":
opf_path = "./output/opfs/D1111/D1111.opf/"
opfs_path = "./output/opfs/"
preview_path = "./output/D1111/"
# preview to opf
formatter = PedurmaFormatter(output_path=opfs_path)
formatter.create_opf(preview_path)
# OPf to diplomatic
serializer = PedurmaSerializer(opf_path)
serializer.serialize() | [
"openpecha.serializers.PedurmaSerializer",
"openpecha.formatters.PedurmaFormatter"
] | [((345, 384), 'openpecha.formatters.PedurmaFormatter', 'PedurmaFormatter', ([], {'output_path': 'opfs_path'}), '(output_path=opfs_path)\n', (361, 384), False, 'from openpecha.formatters import PedurmaFormatter\n'), ((466, 493), 'openpecha.serializers.PedurmaSerializer', 'PedurmaSerializer', (['opf_path'], {}), '(opf_path)\n', (483, 493), False, 'from openpecha.serializers import PedurmaSerializer\n')] |
from logmagic.loggerutil import make_logger
from unittest import TestCase
import unittest
import sys
from io import StringIO
import contextlib
import re
class ConsoleOutTest(TestCase):
def test_debugout(self):
# global saved_stdout # Use sys.__stdout__ instead
# saved_stdout = sys.stdout
# global out_stream
out_stream = StringIO()
# sys.stdout = out_stream
with contextlib.redirect_stdout(out_stream):
with contextlib.redirect_stderr(out_stream):
logger = make_logger()
logger.debug('Log Message')
output = out_stream.getvalue()
# sys.stdout = saved_stdout # Use sys.__stdout__ instead
regex_match = \
re.fullmatch( \
'[0-9]{4}\-[0-9]{2}\-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2},[0-9]{3} \- Default Logger \- DEBUG \- Log Message\n' \
, output)
self.assertIsNotNone(regex_match)
if __name__ == '__main__':
unittest.main()
| [
"contextlib.redirect_stdout",
"re.fullmatch",
"contextlib.redirect_stderr",
"logmagic.loggerutil.make_logger",
"unittest.main",
"io.StringIO"
] | [((978, 993), 'unittest.main', 'unittest.main', ([], {}), '()\n', (991, 993), False, 'import unittest\n'), ((361, 371), 'io.StringIO', 'StringIO', ([], {}), '()\n', (369, 371), False, 'from io import StringIO\n'), ((740, 890), 're.fullmatch', 're.fullmatch', (['"""[0-9]{4}\\\\-[0-9]{2}\\\\-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2},[0-9]{3} \\\\- Default Logger \\\\- DEBUG \\\\- Log Message\n"""', 'output'], {}), '(\n """[0-9]{4}\\\\-[0-9]{2}\\\\-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2},[0-9]{3} \\\\- Default Logger \\\\- DEBUG \\\\- Log Message\n"""\n , output)\n', (752, 890), False, 'import re\n'), ((419, 457), 'contextlib.redirect_stdout', 'contextlib.redirect_stdout', (['out_stream'], {}), '(out_stream)\n', (445, 457), False, 'import contextlib\n'), ((476, 514), 'contextlib.redirect_stderr', 'contextlib.redirect_stderr', (['out_stream'], {}), '(out_stream)\n', (502, 514), False, 'import contextlib\n'), ((541, 554), 'logmagic.loggerutil.make_logger', 'make_logger', ([], {}), '()\n', (552, 554), False, 'from logmagic.loggerutil import make_logger\n')] |
import logging
import re
import gzip
from pathlib import Path
from argparse import ArgumentParser
from Bio import AlignIO
from make_prg.from_msa import MSA
from make_prg.prg_encoder import PrgEncoder, PRG_Ints
def load_alignment_file(msa_file: str, alignment_format: str) -> MSA:
msa_file = str(msa_file)
logging.info("Read from MSA file %s", msa_file)
if msa_file.endswith(".gz"):
logging.debug("MSA is gzipped")
handle = gzip.open(msa_file, "rt")
alignment = AlignIO.read(handle, alignment_format)
handle.close()
else:
alignment = AlignIO.read(msa_file, alignment_format)
for record in alignment:
record.seq = record.seq.upper()
return alignment
# ************/
# GFA code */
# ***********/
class GFA_Output:
"""
A simple class for converting a PRG string into a GFA file
TODO: Update to GFA2 format
"""
def __init__(self, gfa_string="", gfa_id=0, gfa_site=5):
self.gfa_string = gfa_string
self.gfa_id = gfa_id
self.gfa_site = gfa_site
self.delim_char = " " # This mirrors the AlignedSeq class.
def split_on_site(self, prg_string, site_num):
site_coords = [
(a.start(), a.end())
for a in list(
re.finditer(
"%s%d%s" % (self.delim_char, site_num, self.delim_char), prg_string
)
)
]
last_pos = None
split_strings = []
for (start, end) in site_coords:
split_strings.append(prg_string[last_pos:start])
last_pos = end
split_strings.append(prg_string[last_pos:])
delim = "%s%d%s" % (self.delim_char, site_num, self.delim_char)
check_string = delim.join(split_strings)
assert check_string == prg_string, (
"Something has gone wrong with the string split for site %d\nsplit_"
"strings: %s" % (site_num, split_strings)
)
return split_strings
def build_gfa_string(self, prg_string, pre_var_id=None):
"""Takes prg_string and builds a gfa_string with fragments
from the prg_string."""
end_ids = []
# iterate through sites present, updating gfa_string with each in turn
while str(self.gfa_site) in prg_string:
logging.debug("gfa_site: %d", self.gfa_site)
prgs = self.split_on_site(prg_string, self.gfa_site)
logging.debug("prgs: %s", prgs)
assert len(prgs) == 3, "Invalid prg sequence %s for site %d and id %d" % (
prg_string,
self.gfa_site,
self.gfa_id,
)
# add pre-var site string and links from previous seq fragments
if prgs[0] != "":
self.gfa_string += "S\t%d\t%s\tRC:i:0\n" % (self.gfa_id, prgs[0])
else:
# adds an empty node for empty pre var site seqs
self.gfa_string += "S\t%d\t%s\tRC:i:0\n" % (self.gfa_id, "*")
pre_var_id = self.gfa_id
self.gfa_id += 1
for id in end_ids:
self.gfa_string += "L\t%d\t+\t%d\t+\t0M\n" % (id, pre_var_id)
end_ids = []
# recursively add segments for each of the variant haplotypes at
# this site, saving the end id for each haplotype
vars = self.split_on_site(prgs[1], self.gfa_site + 1)
assert len(vars) > 1, "Invalid prg sequence %s for site %d and id %d" % (
prg_string,
self.gfa_site + 1,
self.gfa_id,
)
logging.debug("vars: %s", vars)
self.gfa_site += 2
logging.debug("gfa_site: %d", self.gfa_site)
for var_string in vars:
if pre_var_id != None:
self.gfa_string += "L\t%d\t+\t%d\t+\t0M\n" % (
pre_var_id,
self.gfa_id,
)
var_end_ids = self.build_gfa_string(
prg_string=var_string, pre_var_id=pre_var_id
)
end_ids.extend(var_end_ids)
prg_string = prgs[2]
pre_var_id = None
# finally add the final bit of sequence after variant site
if prg_string != "":
self.gfa_string += "S\t%d\t%s\tRC:i:0\n" % (self.gfa_id, prg_string)
else:
self.gfa_string += "S\t%d\t%s\tRC:i:0\n" % (self.gfa_id, "*")
for id in end_ids:
self.gfa_string += "L\t%d\t+\t%d\t+\t0M\n" % (id, self.gfa_id)
end_ids = []
return_id = [self.gfa_id]
self.gfa_id += 1
return return_id
def write_gfa(outfile, prg_string):
"""
Writes a gfa file from prg string.
"""
with open(outfile, "w") as f:
# initialize gfa_string, id and site, then update string with the prg
gfa_string = "H\tVN:Z:1.0\tbn:Z:--linear --singlearr\n"
gfa_id = 0
gfa_site = 5
gfa_obj = GFA_Output(gfa_string)
gfa_obj.build_gfa_string(prg_string=prg_string)
f.write(gfa_obj.gfa_string)
# ******************/
# Write PRG code */
# *****************/
def write_prg(prg_fname: Path, prg_string: str, options: ArgumentParser):
"""
Writes th prg to `output_file`.
Writes it as a human readable string, and also as an integer vector
"""
seqid = options.seqid or options.prg_name
if options.output_type.prg:
with prg_fname.open("w") as prg:
header = f">{seqid} max_nest={options.max_nesting} min_match={options.min_match_length}"
print(f"{header}\n{prg_string}", file=prg)
if options.output_type.binary:
prg_ints_fpath = prg_fname.with_suffix(".bin")
prg_encoder = PrgEncoder()
prg_ints: PRG_Ints = prg_encoder.encode(prg_string)
with prg_ints_fpath.open("wb") as ostream:
prg_encoder.write(prg_ints, ostream)
| [
"Bio.AlignIO.read",
"logging.debug",
"gzip.open",
"make_prg.prg_encoder.PrgEncoder",
"re.finditer",
"logging.info"
] | [((317, 364), 'logging.info', 'logging.info', (['"""Read from MSA file %s"""', 'msa_file'], {}), "('Read from MSA file %s', msa_file)\n", (329, 364), False, 'import logging\n'), ((406, 437), 'logging.debug', 'logging.debug', (['"""MSA is gzipped"""'], {}), "('MSA is gzipped')\n", (419, 437), False, 'import logging\n'), ((455, 480), 'gzip.open', 'gzip.open', (['msa_file', '"""rt"""'], {}), "(msa_file, 'rt')\n", (464, 480), False, 'import gzip\n'), ((501, 539), 'Bio.AlignIO.read', 'AlignIO.read', (['handle', 'alignment_format'], {}), '(handle, alignment_format)\n', (513, 539), False, 'from Bio import AlignIO\n'), ((593, 633), 'Bio.AlignIO.read', 'AlignIO.read', (['msa_file', 'alignment_format'], {}), '(msa_file, alignment_format)\n', (605, 633), False, 'from Bio import AlignIO\n'), ((5794, 5806), 'make_prg.prg_encoder.PrgEncoder', 'PrgEncoder', ([], {}), '()\n', (5804, 5806), False, 'from make_prg.prg_encoder import PrgEncoder, PRG_Ints\n'), ((2317, 2361), 'logging.debug', 'logging.debug', (['"""gfa_site: %d"""', 'self.gfa_site'], {}), "('gfa_site: %d', self.gfa_site)\n", (2330, 2361), False, 'import logging\n'), ((2439, 2470), 'logging.debug', 'logging.debug', (['"""prgs: %s"""', 'prgs'], {}), "('prgs: %s', prgs)\n", (2452, 2470), False, 'import logging\n'), ((3624, 3655), 'logging.debug', 'logging.debug', (['"""vars: %s"""', 'vars'], {}), "('vars: %s', vars)\n", (3637, 3655), False, 'import logging\n'), ((3699, 3743), 'logging.debug', 'logging.debug', (['"""gfa_site: %d"""', 'self.gfa_site'], {}), "('gfa_site: %d', self.gfa_site)\n", (3712, 3743), False, 'import logging\n'), ((1281, 1366), 're.finditer', 're.finditer', (["('%s%d%s' % (self.delim_char, site_num, self.delim_char))", 'prg_string'], {}), "('%s%d%s' % (self.delim_char, site_num, self.delim_char), prg_string\n )\n", (1292, 1366), False, 'import re\n')] |
from __future__ import print_function
import os
import warnings
import shutil
import re
import numpy as np
import sami
from astropy.io import fits
class Tester():
"""This class handles the testing of the SAMI pipeline. To run it requires
additional data:
1) the folder ``sami_ppl_test_data``, i.e. the raw data to be reduced
locally (~1.1 GB - ~0.5 GB xz archive)
2) the reduced data (folders ``slow_test_reference`` or
``fast_test_reference`` for the ``slow`` and ``fast`` reduction
respectively (~7.5 GB - ~4.1 GB xz archive).
To run the test (fast mode):
>>> import sami.tester
>>> mytest = tester.Tester(fast=True)
>>> mngr = mytest.dr_reduce()
>>> comp = mytest.dr_comparison()
1) mngr is the instance of ``sami.manager.Manager`` that controls the local
data reduction. It can be used to perform additional operations on the
local data reduction, but strictly speaking should not be needed.
2) comp is the result of the comparison. Should be True.
Parameters
----------
fast : bool, optional
Whether to use the ``fast`` or ``slow`` data reduction option for the
``sami.manager.Manager``.
rtol : float, optional
The relative tolerance to assess whether any two numbers are the same.
The default value of 1.e-07 is appropriate for single precision numbers.
output_dir : str, optional
The directory where to write the local data reduction. Default
is None, which uses either ``slow_test`` or ``fast_test``, depending on
the value of the keyword ``fast``.
reference_dir : str, optional
The directory where to search for the reference data reduction. Default
is None, which uses either ``slow_test_reference`` or
``fast_test_reference``, depending on the value of the keyword ``fast``.
create_reduction : bool, optional
This flag is set to True in order to create the reference data
reduction. When testing one should leave this keyword to its default
value (False).
"""
def __init__(self, fast=True, rtol=1.e-07, output_dir=None,
reference_dir=None, create_reduction=False):
self.fast=fast
self.rtol=rtol
if output_dir is None:
self.output_dir = 'fast_test' if fast else 'slow_test'
else:
self.output_dir = output_dir
if reference_dir is None:
self.reference_dir = 'fast_test_reference' if fast \
else 'slow_test_reference'
else:
self.reference_dir = reference_dir
if not create_reduction:
# Check that ``reference_dir`` contains the expected files.
self._check_reference_exists()
def _check_reference_exists(self):
"""Method to assess whether the required reference data exists in the
directory ``self.reference_dir``.
"""
if not _check_existing_cubing(self.reference_dir):
error_message = ('The directory "{}" does not appear to contain ' \
+ ' the required (reduced) data. Please contact the pipeline ' \
+ ' support team to obtain the reference dataset.').format(
self.reference_dir)
raise IOError(error_message)
else:
pass
def dr_reduce(self,
overwrite_bias=False, overwrite_dark=False,
overwrite_lflat=False, overwrite_tlm=False,
overwrite_arc_n_flat=False, overwrite_sky_n_object=False,
overwrite_fluxcal=False, overwrite_cubing=False):
mngr = dr_reduce(
fast=self.fast, output_dir=self.output_dir,
overwrite_bias=overwrite_bias, overwrite_dark=overwrite_dark,
overwrite_lflat=overwrite_lflat, overwrite_tlm=overwrite_tlm,
overwrite_arc_n_flat=overwrite_arc_n_flat,
overwrite_sky_n_object=overwrite_sky_n_object,
overwrite_fluxcal=overwrite_fluxcal,
overwrite_cubing=overwrite_cubing)
return mngr
def dr_comparison(self):
return dr_comparison(self.output_dir, self.reference_dir,
rtol=self.rtol)
# Example usage:
# >>> import sami.tester
# >>> res = tester.dr_reduce(fast=True)
# Test to relative tolerance.
# >>> comp = tester.dr_comparison('fast_test', 'fast_test_reference', rtol=1.e-07)
# +---+------------------------------------------------------------------------+
# |1. | Performing the data reduction. |
# +---+------------------------------------------------------------------------+
def dr_reduce(fast=True, output_dir=None,
overwrite_bias=False, overwrite_dark=False, overwrite_lflat=False,
overwrite_tlm=False, overwrite_arc_n_flat=False,
overwrite_sky_n_object=False, overwrite_fluxcal=False,
overwrite_cubing=False):
"""This method does the data reduction on the test data suite.
Parameters
----------
fast: bool, True
whether to perform the fast or slow data reduction (see the
relevant documentation for sami.manager.Manager for more information).
overwrite_<function>: bool, False
whether to manually overwrite the preexisting data reduction step
corresponding to <function> (if exists).
Return
------
mngr: ``sami.manager.Manager`` instance
The Manager instance with the data reduction.
"""
# Declare the output directory.
if output_dir is None:
output_dir = 'fast_test' if fast else 'slow_test'
# If an old reduction exists, ask the user whether to delete it or keep it.
if _check_existing_reduction(output_dir):
_delete_existing_reduction(output_dir)
# Importing the data.
mngr = sami.manager.Manager(output_dir, fast=fast)
mngr.import_dir('sami_ppl_test_data')
mngr.remove_directory_locks()
message('Processing the bias data...')
mngr.reduce_bias(overwrite=overwrite_bias)
mngr.combine_bias(overwrite=overwrite_bias)
message('Processing the dark data...')
mngr.reduce_dark(overwrite=overwrite_dark)
mngr.combine_dark(overwrite=overwrite_dark)
message('Processing the detector flat (lflat) data...')
mngr.reduce_lflat(overwrite=overwrite_lflat)
mngr.combine_lflat(overwrite=overwrite_lflat)
message('Tracing the fibres (tramlines)...')
mngr.make_tlm(overwrite=overwrite_tlm)
message('Reducing the arc & flat frames...')
mngr.reduce_arc(overwrite=overwrite_arc_n_flat)
mngr.reduce_fflat(overwrite=overwrite_arc_n_flat)
message('Reducing the sky and object frames...')
mngr.reduce_sky(overwrite=overwrite_sky_n_object)
mngr.reduce_object(overwrite=overwrite_sky_n_object)
message('Flux calibration...')
mngr.derive_transfer_function(overwrite=overwrite_fluxcal)
mngr.combine_transfer_function(overwrite=overwrite_fluxcal)
mngr.flux_calibrate(overwrite=overwrite_fluxcal)
mngr.telluric_correct(overwrite=overwrite_fluxcal)
mngr.get_stellar_photometry()
mngr.scale_frames(overwrite=overwrite_fluxcal)
mngr.measure_offsets(overwrite=overwrite_fluxcal)
message('Cubing...')
# Check whether cubing has been done in the past. If yes, use the keyword
# ``overwrite_cubing`` to determine whether or not to redo this process.
# This step is necessary because the keyword ``overwrite`` does not work
# for ``sami.manager.Manager.cube``.
if (not _check_existing_cubing(output_dir)) or overwrite_cubing:
warn_message = 'Notice: sami.manager.Manger.cube`` is time consuming.' \
+ '\nThis tester will only cube one IFU (the secondary star one).'
warnings.warn(warn_message)
mngr.cube(overwrite=overwrite_cubing, star_only=True)
mngr.scale_cubes(overwrite=overwrite_cubing)
#mngr.record_dust(overwrite=overwrite_cubing)
#mngr.gzip_cubes(overwrite=overwrite_cubing) # Unsupported
mngr.qc_summary()
check_results(mngr)
return mngr
# +---+------------------------------------------------------------------------+
# |2. | Assessing the results. |
# +---+------------------------------------------------------------------------+
def dr_comparison(output_dir, reference_dir, rtol=1.e-07):
comparison = []
for prod_name in ['bias', 'dark', 'lflat', 'calibrators', 'ststar', 'main',
'cubed']:
filelist_a, filelist_b = _retrieve_filenames(prod_name, output_dir,
reference_dir)
for fn_a, fn_b in zip(filelist_a, filelist_b):
fa, fb = os.path.basename(fn_a), os.path.basename(fn_b)
comparison.append([fa, fb, _compare_files(fn_a, fn_b, rtol=rtol)])
all_equal = [comp[2] for comp in comparison]
if np.all(all_equal):
return True
else:
warnings.warn('Not all comparisons have been successfull')
return comparison
def _retrieve_filenames(input_product_name, output_dir, reference_dir):
"""This method retrieves the filenames from the data reduction (directory
``output_dir``) and from the standard (or reference) data reduction
(directory ``reference_dir``). It returns couples of filenames that need to
be compared.
input_product_name: str
['bias'|'dark'|'lflat'|'main'|'calibrators'|'ststar'|'cubed']
Return
------
Two lists of filenames, with the names of the files that need to be compared
as in:
[file_1a, file_2a, ..., file_Na], [file_1b, file_2b, ..., file_Nb]
"""
pn_dic = {'bias': 'bias', 'dark': 'dark', 'lflat': 'lflat', 'cubed': 'cubed',
'main': 'main', 'calibrators': 'calibrators', 'ststar': 'EG21'}
product_name = pn_dic[input_product_name]
pn_regex = {'bias': '.*' + product_name + \
'.*/([0-9]{2,2}[a-z]{3,3}[0-9]{5,5}red.fits|' + \
'.*BIAScombined.*fits)',
'dark': '.*' + product_name + \
'.*/([0-9]{2,2}[a-z]{3,3}[0-9]{5,5}red.fits|' + \
'.*DARKcombined.*fits)',
'lflat': '.*' + product_name + \
'.*/([0-9]{2,2}[a-z]{3,3}[0-9]{5,5}red.fits|' + \
'.*LFLATcombined.*fits)',
'main': '.*' + product_name + \
'.*/[0-9]{2,2}[a-z]{3,3}[0-9]{5,5}sci.fits',
'calibrators': '.*' + product_name + \
'.*/[0-9]{2,2}[a-z]{3,3}[0-9]{5,5}red.fits',
'ststar': '.*' + product_name + \
'.*/[0-9]{2,2}[a-z]{3,3}[0-9]{5,5}im.fits',
'cubed': '.*' + product_name + \
'.*/[0-9]{4,}_(blue|red)_.*_Y.*.fits$'}
regex = pn_regex[input_product_name]
# Loop over all directories of processed galaxies.
match_files = re.compile(regex)
# Result files.
result_file_list = [dirpath + '/' + filename
for dirpath, dirnames, filenames in os.walk(output_dir)
for filename in filenames
if match_files.search(dirpath + '/' + filename)]
reference_file_list = [dirpath + '/' + filename
for dirpath, dirnames, filenames in os.walk(reference_dir)
for filename in filenames
if match_files.search(dirpath + '/' + filename)]
if input_product_name == 'main':
result_file_list = _replace_names(result_file_list,
instr='sci', outstr='red')
reference_file_list = _replace_names(reference_file_list,
instr='sci', outstr='red')
elif input_product_name == 'ststar':
result_file_list = _replace_names(result_file_list,
instr='im', outstr='red')
reference_file_list = _replace_names(reference_file_list,
instr='im', outstr='red')
result_file_list.sort(), reference_file_list.sort()
# Assess whether the files are correctly matched (i.e. result_file_list[n]
# has the same filename as reference_file_list[n], for every n).
matched = _assess_matched_files(reference_file_list, result_file_list)
if not matched:
error_message = ('The filenames associated with the product "{}" ' \
+ 'between the directories "{}" and "{}" do not match.\n' \
+ 'Please inspect the relevant directories manually.').format(
product_name, output_dir, reference_dir)
raise AssertionError(error_message)
else:
return result_file_list, reference_file_list
def _compare_files(file_a, file_b, rtol=1.e-07):
"""Compare the contents of the FITS files ``file_a`` and ``file_b`` to a
precision of ``rtol``.
Return
------
True if the data is equal to the required precision, False otherwise.
"""
data_a, data_b = fits.open(file_a), fits.open(file_b)
# List to store the results
are_close = [True for ext in data_a]
for n, (ext_a, ext_b) in enumerate(zip(data_a, data_b)):
try:
are_close[n] = np.testing.assert_allclose(
ext_a.data, ext_b.data, rtol=rtol,
atol=0., verbose=True)
except TypeError:
warnings.warn('Skipping binary table(s): testing not implemented yet.')
pass
except AssertionError as ae:
warnings.warn(ae.args[0])
return False
return True
def _assess_matched_files(filenames_list_a, filenames_list_b):
"""Assess whether the filenames in the input lists ``filenames_list_a`` and
``filenames_list_b`` are the same (apart from the path). This is a helper
method for ``_retrieve_filenames``.
Return
------
True if the check is passed, False otherwise.
"""
if len(filenames_list_a) != len(filenames_list_b):
return False
else:
for fn_a, fn_b in zip(filenames_list_a, filenames_list_b):
if os.path.basename(fn_a) != os.path.basename(fn_b):
return False
# If it gets here, all checks have been passed and the list have the
# same filenames in the correct order.
return True
# +---+------------------------------------------------------------------------+
# |3. | Utilities. Hic sunt leones. |
# +---+------------------------------------------------------------------------+
def _check_existing_reduction(dir_name):
reduction_exists = os.path.exists(dir_name)
if reduction_exists:
warn_message = 'An old reduction has been detected.\n' \
+ 'Please notice that it might (or might not) be incomplete.'
warnings.warn(warn_message)
return reduction_exists
def _check_existing_cubing(dir_name):
regex = '.*cubed.*/[0-9]{4,}_(blue|red)_.*_Y.*.fits$'
# Loop over all directories of processed galaxies.
match_files = re.compile(regex)
# Result files.
cubes_file_list = [dirpath + '/' + filename
for dirpath, dirnames, filenames in os.walk(dir_name)
for filename in filenames
if match_files.search(dirpath + '/' + filename)]
return len(cubes_file_list)==2 # 1 IFU (star_only=True) x 2 spectrogroph arms.
return len(cubes_file_list)==26 # 13 IFUs x 2 spectrogroph arms.
def _delete_existing_reduction(dir_name):
"""Ask the user whether to delete the old data reduction.
"""
delete_er = input(('Delete the old reduction ({}) or resume it? ' \
+ '(y=yes / any other key=continue):\n').format(dir_name))
if delete_er == 'y':
shutil.rmtree(dir_name)
else:
warnings.warn('Continuing the existing data reduction...')
pass
def _replace_names(input_list, instr='sci', outstr='red'):
"""Replace ``instr`` with ``outstr`` in every element of ``input_list``.
"""
instr += '.fits'
outstr += '.fits'
for n in range(len(input_list)):
input_list[n] = input_list[n].replace(instr, outstr)
return input_list
def check_results(input_mngr):
"""Asks the user whether to perform manual checking of the results. """
do_checks = True
while do_checks:
do_checks = input('Check the results? (y=yes, any other key=no):\n')
if do_checks == 'y':
try:
input_mngr.check_next_group()
do_checks = True
except IndexError:
message('No more checks to be done')
do_checks = False
else:
message('No more checks will be done')
do_checks = False
def message(message):
"""Yapp, yet another pritty printer. ``message`` is the text to be printed.
"""
print()
print('*******************************************************************')
print('* {0:<{1}} *'.format(message, 63))
print('*******************************************************************')
print()
| [
"os.path.exists",
"re.compile",
"numpy.testing.assert_allclose",
"shutil.rmtree",
"os.path.basename",
"astropy.io.fits.open",
"warnings.warn",
"numpy.all",
"os.walk",
"sami.manager.Manager"
] | [((5894, 5937), 'sami.manager.Manager', 'sami.manager.Manager', (['output_dir'], {'fast': 'fast'}), '(output_dir, fast=fast)\n', (5914, 5937), False, 'import sami\n'), ((8989, 9006), 'numpy.all', 'np.all', (['all_equal'], {}), '(all_equal)\n', (8995, 9006), True, 'import numpy as np\n'), ((11015, 11032), 're.compile', 're.compile', (['regex'], {}), '(regex)\n', (11025, 11032), False, 'import re\n'), ((14679, 14703), 'os.path.exists', 'os.path.exists', (['dir_name'], {}), '(dir_name)\n', (14693, 14703), False, 'import os\n'), ((15108, 15125), 're.compile', 're.compile', (['regex'], {}), '(regex)\n', (15118, 15125), False, 'import re\n'), ((7813, 7840), 'warnings.warn', 'warnings.warn', (['warn_message'], {}), '(warn_message)\n', (7826, 7840), False, 'import warnings\n'), ((9046, 9104), 'warnings.warn', 'warnings.warn', (['"""Not all comparisons have been successfull"""'], {}), "('Not all comparisons have been successfull')\n", (9059, 9104), False, 'import warnings\n'), ((13052, 13069), 'astropy.io.fits.open', 'fits.open', (['file_a'], {}), '(file_a)\n', (13061, 13069), False, 'from astropy.io import fits\n'), ((13071, 13088), 'astropy.io.fits.open', 'fits.open', (['file_b'], {}), '(file_b)\n', (13080, 13088), False, 'from astropy.io import fits\n'), ((14877, 14904), 'warnings.warn', 'warnings.warn', (['warn_message'], {}), '(warn_message)\n', (14890, 14904), False, 'import warnings\n'), ((15796, 15819), 'shutil.rmtree', 'shutil.rmtree', (['dir_name'], {}), '(dir_name)\n', (15809, 15819), False, 'import shutil\n'), ((15838, 15896), 'warnings.warn', 'warnings.warn', (['"""Continuing the existing data reduction..."""'], {}), "('Continuing the existing data reduction...')\n", (15851, 15896), False, 'import warnings\n'), ((11147, 11166), 'os.walk', 'os.walk', (['output_dir'], {}), '(output_dir)\n', (11154, 11166), False, 'import os\n'), ((11355, 11377), 'os.walk', 'os.walk', (['reference_dir'], {}), '(reference_dir)\n', (11362, 11377), False, 'import os\n'), ((13266, 13355), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['ext_a.data', 'ext_b.data'], {'rtol': 'rtol', 'atol': '(0.0)', 'verbose': '(True)'}), '(ext_a.data, ext_b.data, rtol=rtol, atol=0.0,\n verbose=True)\n', (13292, 13355), True, 'import numpy as np\n'), ((15239, 15256), 'os.walk', 'os.walk', (['dir_name'], {}), '(dir_name)\n', (15246, 15256), False, 'import os\n'), ((8805, 8827), 'os.path.basename', 'os.path.basename', (['fn_a'], {}), '(fn_a)\n', (8821, 8827), False, 'import os\n'), ((8829, 8851), 'os.path.basename', 'os.path.basename', (['fn_b'], {}), '(fn_b)\n', (8845, 8851), False, 'import os\n'), ((13422, 13493), 'warnings.warn', 'warnings.warn', (['"""Skipping binary table(s): testing not implemented yet."""'], {}), "('Skipping binary table(s): testing not implemented yet.')\n", (13435, 13493), False, 'import warnings\n'), ((13560, 13585), 'warnings.warn', 'warnings.warn', (['ae.args[0]'], {}), '(ae.args[0])\n', (13573, 13585), False, 'import warnings\n'), ((14145, 14167), 'os.path.basename', 'os.path.basename', (['fn_a'], {}), '(fn_a)\n', (14161, 14167), False, 'import os\n'), ((14171, 14193), 'os.path.basename', 'os.path.basename', (['fn_b'], {}), '(fn_b)\n', (14187, 14193), False, 'import os\n')] |
from __future__ import absolute_import, division, print_function, unicode_literals
import csv
def csv_filename_to_objects(filename, json_handler):
with open(filename, "r") as f:
objects = csv_stream_to_objects(f, json_handler=json_handler)
return objects
def csv_stream_to_objects(stream, json_handler, params=dict()):
reader = csv.DictReader(stream)
objects = []
for row in reader:
obj = json_handler(row)
if hasattr(obj, "asset_manager_id"):
obj.asset_manager_id = int(obj.asset_manager_id)
objects.append(obj)
return objects
def objects_to_csv(objects, filename, clazz=None):
with open(filename, "w") as csvfile:
objects_to_csv_stream(objects=objects, stream=csvfile, clazz=clazz)
def objects_to_csv_stream(objects, stream, clazz=None):
if not objects:
return
object_dicts = []
for obj in objects:
obj_dict = obj.to_json()
if clazz and hasattr(clazz, "children"):
# FOR NOW - remove all children
[obj_dict.pop(child, None) for child in clazz.children().keys()]
object_dicts.append(obj_dict)
fieldnames = object_dicts[0].keys()
writer = csv.DictWriter(stream, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(object_dicts)
| [
"csv.DictWriter",
"csv.DictReader"
] | [((353, 375), 'csv.DictReader', 'csv.DictReader', (['stream'], {}), '(stream)\n', (367, 375), False, 'import csv\n'), ((1204, 1249), 'csv.DictWriter', 'csv.DictWriter', (['stream'], {'fieldnames': 'fieldnames'}), '(stream, fieldnames=fieldnames)\n', (1218, 1249), False, 'import csv\n')] |
import os, re
FILE_DIR = os.path.dirname(os.path.abspath(__file__))
README_PATH = os.path.join(FILE_DIR, os.pardir, 'README.md')
README_CODE_PATH = os.path.join(FILE_DIR, 'README_commands.py')
CODE_INIT = '''
#------------ CODE INIT ------------
# make sure imports from ../src work
import os, sys
FILE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(FILE_DIR, os.pardir, 'src'))
# simulate console output of expressions
_p_ = None
# print result of last expression
def _p():
global _p_
if _p_ is not None:
print(_p_.__repr__())
_p_ = None
#------------ CODE INIT ------------
'''
insideCode = False
codeType = None
linePrev = None
def _isExpression(line):
STATEMENT_STARTS = ['def ', 'import ', 'from ', 'print(']
line = line.strip()
for start in STATEMENT_STARTS:
if line.startswith(start): return False
# assignment?
if re.match(r'^[A-Za-z0-9_]+[ \t]*=.*', line): return False
return len(line) > 0
with open(README_PATH) as fileIn:
with open(README_CODE_PATH, 'w') as fileOut:
fileOut.write(CODE_INIT)
for line in fileIn:
if line.startswith('```'):
insideCode = not insideCode
if insideCode:
codeType = line[3:].strip()
else:
if linePrev and linePrev.startswith('>>> ') and _isExpression(linePrev[4:]):
#print("linePrev='%s'" % linePrev)
fileOut.write('_p()\n')
codeType = None
linePrev = None
continue
if insideCode and codeType == 'python':
if line.startswith('>>> '):
command = line[4:]
if _isExpression(command):
command = '_p_= ' + command
fileOut.write(command)
elif line.startswith('#'):
fileOut.write(line)
elif len(line.strip()) > 0 and linePrev and _isExpression(linePrev[4:]):
fileOut.write('_p()\n')
linePrev = line
| [
"os.path.abspath",
"os.path.join",
"re.match"
] | [((83, 129), 'os.path.join', 'os.path.join', (['FILE_DIR', 'os.pardir', '"""README.md"""'], {}), "(FILE_DIR, os.pardir, 'README.md')\n", (95, 129), False, 'import os, re\n'), ((149, 193), 'os.path.join', 'os.path.join', (['FILE_DIR', '"""README_commands.py"""'], {}), "(FILE_DIR, 'README_commands.py')\n", (161, 193), False, 'import os, re\n'), ((42, 67), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (57, 67), False, 'import os, re\n'), ((872, 914), 're.match', 're.match', (['"""^[A-Za-z0-9_]+[ \\\\t]*=.*"""', 'line'], {}), "('^[A-Za-z0-9_]+[ \\\\t]*=.*', line)\n", (880, 914), False, 'import os, re\n')] |
#!/usr/bin/env python3
import os, re, random
import numpy as np
from myClass import Theta
from functions import grad_loss
from hyperParameters import hyperParameters
# hyperParameters
T, D = hyperParameters.T, hyperParameters.D
alpha, epsilon = hyperParameters.alpha, hyperParameters.epsilon
moment = hyperParameters.moment
# directory (train files)
dir = os.getcwd() + '/train/'
# train graph_files
files = [file for file in os.listdir(dir) if re.search('_graph.txt', file)]
num_of_files = len(files)
# stochastic gradient descent (sgd)
# Let b_files be a list of file_name of batchs, theta be learnable parameters.
def sgd(b_files, theta):
batch_size = len(b_files)
tmp_theta = Theta(
np.zeros((D,D)),
np.zeros(D).T,
0
)
for graph_file in b_files:
label_file = graph_file.rstrip('_graph.txt') + '_label.txt'
file = open(dir+graph_file)
N, adj = int(file.readline()), []
for i in range(N):
adj.append([int(x) for x in file.readline().split()])
adj = np.array(adj)
file.close()
file = open(dir+label_file)
y = int(file.readline())
file.close()
tmp_theta += grad_loss(adj, y, theta)
delta_theta = tmp_theta*(1/batch_size)
return theta + delta_theta*(-alpha)
# momentum stochastic gradient descent (momentum_sgd)
def momentum_sgd(b_files, theta, w):
batch_size = len(b_files)
tmp_theta = Theta(
np.zeros((D,D)),
np.zeros(D).T,
0
)
for graph_file in b_files:
label_file = graph_file.rstrip('_graph.txt') + '_label.txt'
file = open(dir+graph_file)
N, adj = int(file.readline()), []
for i in range(N):
adj.append([int(x) for x in file.readline().split()])
adj = np.array(adj)
file.close()
file = open(dir+label_file)
y = int(file.readline())
file.close()
tmp_theta += grad_loss(adj, y, theta)
delta_theta = tmp_theta*(1/batch_size)
theta += delta_theta*(-alpha) + w*moment
w += delta_theta*(-alpha) + w*moment
return (theta, w)
| [
"functions.grad_loss",
"os.listdir",
"os.getcwd",
"numpy.array",
"numpy.zeros",
"re.search"
] | [((359, 370), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (368, 370), False, 'import os, re, random\n'), ((430, 445), 'os.listdir', 'os.listdir', (['dir'], {}), '(dir)\n', (440, 445), False, 'import os, re, random\n'), ((449, 478), 're.search', 're.search', (['"""_graph.txt"""', 'file'], {}), "('_graph.txt', file)\n", (458, 478), False, 'import os, re, random\n'), ((708, 724), 'numpy.zeros', 'np.zeros', (['(D, D)'], {}), '((D, D))\n', (716, 724), True, 'import numpy as np\n'), ((1049, 1062), 'numpy.array', 'np.array', (['adj'], {}), '(adj)\n', (1057, 1062), True, 'import numpy as np\n'), ((1197, 1221), 'functions.grad_loss', 'grad_loss', (['adj', 'y', 'theta'], {}), '(adj, y, theta)\n', (1206, 1221), False, 'from functions import grad_loss\n'), ((1459, 1475), 'numpy.zeros', 'np.zeros', (['(D, D)'], {}), '((D, D))\n', (1467, 1475), True, 'import numpy as np\n'), ((1800, 1813), 'numpy.array', 'np.array', (['adj'], {}), '(adj)\n', (1808, 1813), True, 'import numpy as np\n'), ((1948, 1972), 'functions.grad_loss', 'grad_loss', (['adj', 'y', 'theta'], {}), '(adj, y, theta)\n', (1957, 1972), False, 'from functions import grad_loss\n'), ((733, 744), 'numpy.zeros', 'np.zeros', (['D'], {}), '(D)\n', (741, 744), True, 'import numpy as np\n'), ((1484, 1495), 'numpy.zeros', 'np.zeros', (['D'], {}), '(D)\n', (1492, 1495), True, 'import numpy as np\n')] |
from netmiko import ConnectHandler
# our devices info to connect and session log files to save output
arista_1 = {
'device_type': 'arista_eos',
'ip': 'your_ip',
'username': 'your_username',
'password': '<PASSWORD>',
'session_log': 'sw1.txt'
}
arista_2 = {
'device_type': 'arista_eos',
'ip': 'your_ip',
'username': 'your_username',
'password': '<PASSWORD>',
'session_log': 'sw2.txt'
}
arista_3 = {
'device_type': 'arista_eos',
'ip': 'your_ip',
'username': 'your_username',
'password': '<PASSWORD>',
'session_log': 'sw3.txt'
}
# command to run on switches
commands = ['username oxidized privilege 15 role network-operator secret sha512 <secret>']
# for loop to connect to devices in enabled mode, run on switches, write config, and print output
for device in (arista_1, arista_2, arista_3):
net_connect = ConnectHandler(**device)
output = net_connect.send_config_set(commands)
output += net_connect.save_config()
print()
print('#' * 70)
print(output)
print('#' * 70)
print()
| [
"netmiko.ConnectHandler"
] | [((872, 896), 'netmiko.ConnectHandler', 'ConnectHandler', ([], {}), '(**device)\n', (886, 896), False, 'from netmiko import ConnectHandler\n')] |
from django.contrib.auth import authenticate
from rest_framework import viewsets
from rest_framework.authtoken.models import Token
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.status import HTTP_404_NOT_FOUND, HTTP_200_OK
from rest_framework.views import APIView
from .models import Book
from .serializers import BookSerializer
class Login(APIView):
def post(self, request):
user = authenticate(username=request.data.get("username"), password=request.data.get("password"))
if not user:
return Response({'error': 'Credentials are incorrect or user does not exist'}, status=HTTP_404_NOT_FOUND)
token, _ = Token.objects.get_or_create(user=user)
return Response({'token': token.key}, status=HTTP_200_OK)
class BookViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
authentication_classes = [TokenAuthentication]
permission_classes = [IsAuthenticated]
| [
"rest_framework.response.Response",
"rest_framework.authtoken.models.Token.objects.get_or_create"
] | [((784, 822), 'rest_framework.authtoken.models.Token.objects.get_or_create', 'Token.objects.get_or_create', ([], {'user': 'user'}), '(user=user)\n', (811, 822), False, 'from rest_framework.authtoken.models import Token\n'), ((838, 888), 'rest_framework.response.Response', 'Response', (["{'token': token.key}"], {'status': 'HTTP_200_OK'}), "({'token': token.key}, status=HTTP_200_OK)\n", (846, 888), False, 'from rest_framework.response import Response\n'), ((666, 768), 'rest_framework.response.Response', 'Response', (["{'error': 'Credentials are incorrect or user does not exist'}"], {'status': 'HTTP_404_NOT_FOUND'}), "({'error': 'Credentials are incorrect or user does not exist'},\n status=HTTP_404_NOT_FOUND)\n", (674, 768), False, 'from rest_framework.response import Response\n')] |
"""empty message
Revision ID: f5a5f9bbd6e2
Revises: <PASSWORD>
Create Date: 2018-04-20 19:02:32.403757
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'f5a5f9bbd6e2'
down_revision = '<PASSWORD>'
branch_labels = None
depends_on = None
def upgrade():
op.add_column('categories', sa.Column('cover_image_id', sa.Integer(), nullable=True))
op.create_foreign_key('fk_categories_file', 'categories', 'files', ['cover_image_id'], ['id'])
op.add_column('events', sa.Column('cover_image_id', sa.Integer(), nullable=True))
op.create_foreign_key('fk_events_file', 'events', 'files', ['cover_image_id'], ['id'])
op.add_column('groups', sa.Column('event_id', sa.Integer(), nullable=True))
op.add_column('groups', sa.Column('year_id', sa.Integer(), nullable=True))
op.create_foreign_key('fk_groups_event', 'groups', 'events', ['event_id'], ['id'])
op.create_foreign_key('fk_groups_year', 'groups', 'years', ['year_id'], ['id'])
op.add_column('years', sa.Column('cover_image_id', sa.Integer(), nullable=True))
op.create_foreign_key('fk_years_file', 'years', 'files', ['cover_image_id'], ['id'])
def downgrade():
op.drop_constraint('fk_years_file', 'years', type_='foreignkey')
op.drop_column('years', 'cover_image_id')
op.drop_constraint('fk_groups_event', 'groups', type_='foreignkey')
op.drop_constraint('fk_groups_year', 'groups', type_='foreignkey')
op.drop_column('groups', 'year_id')
op.drop_column('groups', 'event_id')
op.drop_constraint('fk_events_file', 'events', type_='foreignkey')
op.drop_column('events', 'cover_image_id')
op.drop_constraint('fk_categories_file', 'categories', type_='foreignkey')
op.drop_column('categories', 'cover_image_id')
| [
"alembic.op.drop_constraint",
"alembic.op.drop_column",
"sqlalchemy.Integer",
"alembic.op.create_foreign_key"
] | [((404, 503), 'alembic.op.create_foreign_key', 'op.create_foreign_key', (['"""fk_categories_file"""', '"""categories"""', '"""files"""', "['cover_image_id']", "['id']"], {}), "('fk_categories_file', 'categories', 'files', [\n 'cover_image_id'], ['id'])\n", (425, 503), False, 'from alembic import op\n'), ((589, 680), 'alembic.op.create_foreign_key', 'op.create_foreign_key', (['"""fk_events_file"""', '"""events"""', '"""files"""', "['cover_image_id']", "['id']"], {}), "('fk_events_file', 'events', 'files', [\n 'cover_image_id'], ['id'])\n", (610, 680), False, 'from alembic import op\n'), ((839, 925), 'alembic.op.create_foreign_key', 'op.create_foreign_key', (['"""fk_groups_event"""', '"""groups"""', '"""events"""', "['event_id']", "['id']"], {}), "('fk_groups_event', 'groups', 'events', ['event_id'],\n ['id'])\n", (860, 925), False, 'from alembic import op\n'), ((926, 1005), 'alembic.op.create_foreign_key', 'op.create_foreign_key', (['"""fk_groups_year"""', '"""groups"""', '"""years"""', "['year_id']", "['id']"], {}), "('fk_groups_year', 'groups', 'years', ['year_id'], ['id'])\n", (947, 1005), False, 'from alembic import op\n'), ((1095, 1183), 'alembic.op.create_foreign_key', 'op.create_foreign_key', (['"""fk_years_file"""', '"""years"""', '"""files"""', "['cover_image_id']", "['id']"], {}), "('fk_years_file', 'years', 'files', ['cover_image_id'],\n ['id'])\n", (1116, 1183), False, 'from alembic import op\n'), ((1203, 1267), 'alembic.op.drop_constraint', 'op.drop_constraint', (['"""fk_years_file"""', '"""years"""'], {'type_': '"""foreignkey"""'}), "('fk_years_file', 'years', type_='foreignkey')\n", (1221, 1267), False, 'from alembic import op\n'), ((1272, 1313), 'alembic.op.drop_column', 'op.drop_column', (['"""years"""', '"""cover_image_id"""'], {}), "('years', 'cover_image_id')\n", (1286, 1313), False, 'from alembic import op\n'), ((1318, 1385), 'alembic.op.drop_constraint', 'op.drop_constraint', (['"""fk_groups_event"""', '"""groups"""'], {'type_': '"""foreignkey"""'}), "('fk_groups_event', 'groups', type_='foreignkey')\n", (1336, 1385), False, 'from alembic import op\n'), ((1390, 1456), 'alembic.op.drop_constraint', 'op.drop_constraint', (['"""fk_groups_year"""', '"""groups"""'], {'type_': '"""foreignkey"""'}), "('fk_groups_year', 'groups', type_='foreignkey')\n", (1408, 1456), False, 'from alembic import op\n'), ((1461, 1496), 'alembic.op.drop_column', 'op.drop_column', (['"""groups"""', '"""year_id"""'], {}), "('groups', 'year_id')\n", (1475, 1496), False, 'from alembic import op\n'), ((1501, 1537), 'alembic.op.drop_column', 'op.drop_column', (['"""groups"""', '"""event_id"""'], {}), "('groups', 'event_id')\n", (1515, 1537), False, 'from alembic import op\n'), ((1542, 1608), 'alembic.op.drop_constraint', 'op.drop_constraint', (['"""fk_events_file"""', '"""events"""'], {'type_': '"""foreignkey"""'}), "('fk_events_file', 'events', type_='foreignkey')\n", (1560, 1608), False, 'from alembic import op\n'), ((1613, 1655), 'alembic.op.drop_column', 'op.drop_column', (['"""events"""', '"""cover_image_id"""'], {}), "('events', 'cover_image_id')\n", (1627, 1655), False, 'from alembic import op\n'), ((1660, 1734), 'alembic.op.drop_constraint', 'op.drop_constraint', (['"""fk_categories_file"""', '"""categories"""'], {'type_': '"""foreignkey"""'}), "('fk_categories_file', 'categories', type_='foreignkey')\n", (1678, 1734), False, 'from alembic import op\n'), ((1739, 1785), 'alembic.op.drop_column', 'op.drop_column', (['"""categories"""', '"""cover_image_id"""'], {}), "('categories', 'cover_image_id')\n", (1753, 1785), False, 'from alembic import op\n'), ((370, 382), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (380, 382), True, 'import sqlalchemy as sa\n'), ((555, 567), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (565, 567), True, 'import sqlalchemy as sa\n'), ((726, 738), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (736, 738), True, 'import sqlalchemy as sa\n'), ((805, 817), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (815, 817), True, 'import sqlalchemy as sa\n'), ((1061, 1073), 'sqlalchemy.Integer', 'sa.Integer', ([], {}), '()\n', (1071, 1073), True, 'import sqlalchemy as sa\n')] |
from __future__ import annotations
import pygame
from scripts.engine import world
from scripts.engine.component import Position
from scripts.engine.core import queries
from scripts.engine.core.constants import GameEvent
__all__ = ["process_win_condition"]
def process_win_condition():
"""
Process the win condition, checking if it has been met.
"""
player = world.get_player()
player_pos = world.get_entitys_component(player, Position)
for entity, (position, _) in queries.position_and_win_condition:
if player_pos.x == position.x and player_pos.y == position.y:
event = pygame.event.Event(GameEvent.WIN_CONDITION_MET)
pygame.event.post(event)
break
| [
"scripts.engine.world.get_entitys_component",
"scripts.engine.world.get_player",
"pygame.event.post",
"pygame.event.Event"
] | [((380, 398), 'scripts.engine.world.get_player', 'world.get_player', ([], {}), '()\n', (396, 398), False, 'from scripts.engine import world\n'), ((416, 461), 'scripts.engine.world.get_entitys_component', 'world.get_entitys_component', (['player', 'Position'], {}), '(player, Position)\n', (443, 461), False, 'from scripts.engine import world\n'), ((622, 669), 'pygame.event.Event', 'pygame.event.Event', (['GameEvent.WIN_CONDITION_MET'], {}), '(GameEvent.WIN_CONDITION_MET)\n', (640, 669), False, 'import pygame\n'), ((682, 706), 'pygame.event.post', 'pygame.event.post', (['event'], {}), '(event)\n', (699, 706), False, 'import pygame\n')] |
# Generated by Django 3.1.5 on 2021-09-02 21:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('newapp1', '0004_auto_20210830_2333'),
]
operations = [
migrations.AddField(
model_name='userreview',
name='prolific_id',
field=models.CharField(blank=True, max_length=300, null=True),
),
]
| [
"django.db.models.CharField"
] | [((343, 398), 'django.db.models.CharField', 'models.CharField', ([], {'blank': '(True)', 'max_length': '(300)', 'null': '(True)'}), '(blank=True, max_length=300, null=True)\n', (359, 398), False, 'from django.db import migrations, models\n')] |
# Time: O(|V| + |E|)
# Space: O(|V| + |E|)
# 886
# Given a set of N people (numbered 1, 2, ..., N),
# we would like to split everyone into two groups of any size.
#
# Each person may dislike some other people,
# and they should not go into the same group.
#
# Formally, if dislikes[i] = [a, b],
# it means it is not allowed to put the people numbered a and b into the same group.
#
# Return true if and only if it is possible to split everyone into two groups in this way.
#
# Example 1:
#
# Input: N = 4, dislikes = [[1,2],[1,3],[2,4]]
# Output: true
# Explanation: group1 [1,4], group2 [2,3]
# Example 2:
#
# Input: N = 3, dislikes = [[1,2],[1,3],[2,3]]
# Output: false
# Example 3:
#
# Input: N = 5, dislikes = [[1,2],[2,3],[3,4],[4,5],[1,5]]
# Output: false
#
# Note:
# - 1 <= N <= 2000
# - 0 <= dislikes.length <= 10000
# - 1 <= dislikes[i][j] <= N
# - dislikes[i][0] < dislikes[i][1]
# - There does not exist i != j for which dislikes[i] == dislikes[j].
# Solution: Consider the graph on N people formed by the given "dislike" edges. We want to check that each
# connected component of this graph is bipartite. Either DFS or BFS to traverse the graph, check whether the graph
# is bipartite by trying to coloring nodes with two colors.
import collections
class Solution(object):
def possibleBipartition(self, N, dislikes): # DFS, USE THIS
"""
:type N: int
:type dislikes: List[List[int]]
:rtype: bool
"""
graph = collections.defaultdict(set)
for u, v in dislikes:
graph[u].add(v)
graph[v].add(u)
color = {} # OR USE color = [None] * (N+1)
for node in range(1, N + 1):
if node not in color:
color[node] = 0
stk = [node]
while stk:
i = stk.pop()
for nei in graph[i]:
if nei in color and color[nei] == color[i]:
return False
if nei not in color:
color[nei] = 1 - color[i]
stk.append(nei)
return True
def possibleBipartition_bfs(self, N, dislikes):
graph = collections.defaultdict(list)
for u, v in dislikes:
graph[u].append(v)
graph[v].append(u)
q = collections.deque([])
color = {}
for node in range(1, N+1):
if node not in color:
color[node] = 0
q.append(node)
while q:
cur = q.popleft()
for nei in graph[cur]:
if nei in color and color[nei] == color[cur]:
return False
if nei not in color:
color[nei] = 1-color[cur]
q.append(nei)
return True
# sequential process of 'dislikes' may make wrong decision in the middle
# because it doesn't know the information in later pairs.
def possibleBipartition_wrong(self, N, dislikes):
sA, sB = set(), set()
for x, y in dislikes:
if x in sA:
if y in sA: return False
sB.add(y)
elif x in sB:
if y in sB: return False
sA.add(y)
else:
if y in sA:
sB.add(x)
elif y in sB:
sA.add(x)
else:
sA.add(x) # problem: the partition here cannot be reliably determined
sB.add(y)
return True | [
"collections.deque",
"collections.defaultdict"
] | [((1478, 1506), 'collections.defaultdict', 'collections.defaultdict', (['set'], {}), '(set)\n', (1501, 1506), False, 'import collections\n'), ((2220, 2249), 'collections.defaultdict', 'collections.defaultdict', (['list'], {}), '(list)\n', (2243, 2249), False, 'import collections\n'), ((2355, 2376), 'collections.deque', 'collections.deque', (['[]'], {}), '([])\n', (2372, 2376), False, 'import collections\n')] |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import random as rdm
# temporary variable, only used in testing, replace with actual graph inputs
# currently, generates 100 evenly spaced numbers between 0 and pi
ps1 = np.linspace(0, 1 * np.pi, 100)
# create the graph plot
fig, ax = plt.subplots()
# animated=True tells matplotlib to only draw the artist when we
# explicitly request it
# create artist "lin", which is an axis on fig "ax",
(lin,) = ax.plot(ps1, np.sin(ps1), animated=True)
ax.set_xlim(0, 5000)
# make sure the window is raised, but the script keeps going
plt.show(block=False)
# stop to admire our empty window axes and ensure it is rendered at
# least once.
#
# We need to fully draw the figure at its final size on the screen
# before we continue on so that :
# a) we have the correctly sized and drawn background to grab
# b) we have a cached renderer so that ``ax.draw_artist`` works
# so we spin the event loop to let the backend process any pending operations
plt.pause(0.1)
# get copy of entire figure (everything inside fig.bbox) sans animated artist
bg = fig.canvas.copy_from_bbox(fig.bbox)
# draw the animated artist, this uses a cached renderer
ax.draw_artist(lin)
# show the result to the screen, this pushes the updated RGBA buffer from the
# renderer to the GUI framework, so you can see it
fig.canvas.blit(fig.bbox)
for j in range(1000):
# reset the background back in the canvas state, screen unchanged
fig.canvas.restore_region(bg)
# update the artist, neither the canvas state nor the screen have changed
lin.set_ydata(np.sin(ps1 + (j / 100) * np.pi))
# re-render the artist, updating the canvas state, but not the screen
ax.draw_artist(lin)
# copy the image to the GUI state, but screen might not be changed yet
fig.canvas.blit(fig.bbox)
# flush any pending GUI events, re-painting the screen if needed
fig.canvas.flush_events()
# you can put a pause in if you want to slow things down
# plt.pause(.1)
| [
"numpy.sin",
"numpy.linspace",
"matplotlib.pyplot.pause",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show"
] | [((263, 293), 'numpy.linspace', 'np.linspace', (['(0)', '(1 * np.pi)', '(100)'], {}), '(0, 1 * np.pi, 100)\n', (274, 293), True, 'import numpy as np\n'), ((329, 343), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (341, 343), True, 'import matplotlib.pyplot as plt\n'), ((622, 643), 'matplotlib.pyplot.show', 'plt.show', ([], {'block': '(False)'}), '(block=False)\n', (630, 643), True, 'import matplotlib.pyplot as plt\n'), ((1036, 1050), 'matplotlib.pyplot.pause', 'plt.pause', (['(0.1)'], {}), '(0.1)\n', (1045, 1050), True, 'import matplotlib.pyplot as plt\n'), ((510, 521), 'numpy.sin', 'np.sin', (['ps1'], {}), '(ps1)\n', (516, 521), True, 'import numpy as np\n'), ((1625, 1654), 'numpy.sin', 'np.sin', (['(ps1 + j / 100 * np.pi)'], {}), '(ps1 + j / 100 * np.pi)\n', (1631, 1654), True, 'import numpy as np\n')] |
import urllib.request
import shutil
import requests
...
# Download the file from `url` and save it locally under `file_name`:
from fasp.loc import sdlDRSClient
def download(url):
print('in download')
file_name = 'test_file.bam'
req = requests.get(url)
print (req)
file = open(file_name, 'wb')
for chunk in req.iter_content(100000):
print('writing a chunk')
file.write(chunk)
file.close()
if __name__ == "__main__":
# client1 = sdlDRSClient('~/.keys/prj_14565.ngc')
# res = client1.getObject('SRR1999478.bam')
# print('--Get Info--')
# print (res)
# print('--Get a URL--')
# res = client1.getAccessURL('SRR1999478.bam','gs.us')
# print (res)
# print ('-----------------')
client2 = sdlDRSClient('~/.keys/prj_11218_D17199.ngc', debug=True)
res = client2.getObject('SRR5368359.sra')
print('--Get Info--')
print (res)
print('--Get a URL--')
res = client2.getAccessURL('SRR5368359.sra','gs.us')
#print (json.dumps(res, indent=2))
print (res['url'])
download(res['url'])
| [
"fasp.loc.sdlDRSClient",
"requests.get"
] | [((248, 265), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (260, 265), False, 'import requests\n'), ((713, 769), 'fasp.loc.sdlDRSClient', 'sdlDRSClient', (['"""~/.keys/prj_11218_D17199.ngc"""'], {'debug': '(True)'}), "('~/.keys/prj_11218_D17199.ngc', debug=True)\n", (725, 769), False, 'from fasp.loc import sdlDRSClient\n')] |
import pytest
from pettingzoo.test.api_test import api_test
from pettingzoo.test.max_cycles_test import max_cycles_test
from pettingzoo.test.parallel_test import parallel_api_test
from pettingzoo.test.render_test import render_test
from pettingzoo.test.seed_test import check_environment_deterministic, seed_test
from pettingzoo.test.state_test import state_test
from pettingzoo.utils import aec_to_parallel, parallel_to_aec
from .all_modules import * # noqa: F403
from .all_modules import all_environments
parameterized_envs = [
["atari/boxing_v2", boxing_v2, dict(obs_type="grayscale_image")],
["atari/boxing_v2", boxing_v2, dict(obs_type="ram")],
["atari/boxing_v2", boxing_v2, dict(full_action_space=False)],
["atari/combat_plane_v2", combat_plane_v2, dict(game_version="jet")],
["atari/combat_plane_v2", combat_plane_v2, dict(guided_missile=True)],
["atari/combat_tank_v2", combat_tank_v2, dict(has_maze=True)],
["atari/combat_tank_v2", combat_tank_v2, dict(is_invisible=True)],
["atari/combat_tank_v2", combat_tank_v2, dict(billiard_hit=True)],
["atari/maze_craze_v3", maze_craze_v3, dict(game_version="race")],
["atari/maze_craze_v3", maze_craze_v3, dict(game_version="capture")],
["atari/maze_craze_v3", maze_craze_v3, dict(visibilty_level=1)],
["atari/maze_craze_v3", maze_craze_v3, dict(visibilty_level=3)],
[
"atari/space_invaders_v2",
space_invaders_v2,
dict(
alternating_control=True,
moving_shields=True,
zigzaging_bombs=True,
fast_bomb=True,
invisible_invaders=True,
),
],
["classic/leduc_holdem_v4", leduc_holdem_v4, dict(num_players=2)],
["classic/leduc_holdem_v4", leduc_holdem_v4, dict(num_players=3)],
["classic/leduc_holdem_v4", leduc_holdem_v4, dict(num_players=4)],
["classic/texas_holdem_v4", texas_holdem_v4, dict(num_players=2)],
["classic/texas_holdem_v4", texas_holdem_v4, dict(num_players=3)],
["classic/texas_holdem_v4", texas_holdem_v4, dict(num_players=4)],
["classic/texas_holdem_no_limit_v6", texas_holdem_no_limit_v6, dict(num_players=2)],
["classic/texas_holdem_no_limit_v6", texas_holdem_no_limit_v6, dict(num_players=3)],
["classic/texas_holdem_no_limit_v6", texas_holdem_no_limit_v6, dict(num_players=4)],
[
"butterfly/knights_archers_zombies_v10",
knights_archers_zombies_v10,
dict(spawn_rate=50),
],
[
"butterfly/knights_archers_zombies_v10",
knights_archers_zombies_v10,
dict(num_knights=4, num_archers=5),
],
[
"butterfly/knights_archers_zombies_v10",
knights_archers_zombies_v10,
dict(killable_knights=True, killable_archers=True),
],
[
"butterfly/knights_archers_zombies_v10",
knights_archers_zombies_v10,
dict(killable_knights=False, killable_archers=False),
],
[
"butterfly/knights_archers_zombies_v10",
knights_archers_zombies_v10,
dict(line_death=False),
],
[
"butterfly/knights_archers_zombies_v10",
knights_archers_zombies_v10,
dict(vector_state=False),
],
[
"butterfly/knights_archers_zombies_v10",
knights_archers_zombies_v10,
dict(vector_state=False, pad_observation=False),
],
[
"butterfly/knights_archers_zombies_v10",
knights_archers_zombies_v10,
dict(max_cycles=100),
],
[
"butterfly/knights_archers_zombies_v10",
knights_archers_zombies_v10,
dict(use_typemasks=False),
],
[
"butterfly/knights_archers_zombies_v10",
knights_archers_zombies_v10,
dict(max_zombies=2, max_arrows=60),
],
["butterfly/pistonball_v6", pistonball_v6, dict(continuous=True)],
["butterfly/pistonball_v6", pistonball_v6, dict(n_pistons=30)],
["butterfly/pistonball_v6", pistonball_v6, dict(continuous=False)],
[
"butterfly/pistonball_v6",
pistonball_v6,
dict(random_drop=True, random_rotate=True),
],
[
"butterfly/pistonball_v6",
pistonball_v6,
dict(random_drop=False, random_rotate=False),
],
[
"butterfly/prospector_v4",
prospector_v4,
dict(
ind_reward=0.8,
group_reward=0.1,
other_group_reward=0.1,
prospec_find_gold_reward=1,
prospec_handoff_gold_reward=1,
banker_receive_gold_reward=1,
banker_deposit_gold_reward=1,
max_cycles=900,
),
],
["classic/go_v5", go_v5, dict(board_size=13, komi=2.5)],
["classic/go_v5", go_v5, dict(board_size=9, komi=0.0)],
["classic/hanabi_v4", hanabi_v4, dict(colors=3)],
["classic/hanabi_v4", hanabi_v4, dict(ranks=3)],
["classic/hanabi_v4", hanabi_v4, dict(players=4)],
["classic/hanabi_v4", hanabi_v4, dict(hand_size=5)],
["classic/hanabi_v4", hanabi_v4, dict(max_information_tokens=3)],
["classic/hanabi_v4", hanabi_v4, dict(max_life_tokens=2)],
[
"classic/hanabi_v4",
hanabi_v4,
dict(
colors=5,
ranks=3,
players=4,
hand_size=5,
max_information_tokens=3,
max_life_tokens=2,
),
],
["classic/hanabi_v4", hanabi_v4, dict(observation_type=0)],
["classic/hanabi_v4", hanabi_v4, dict(observation_type=1)],
["classic/hanabi_v4", hanabi_v4, dict(random_start_player=False)],
["classic/hanabi_v4", hanabi_v4, dict(random_start_player=True)],
["magent/tiger_deer_v4", tiger_deer_v4, dict(minimap_mode=True)],
["magent/battle_v4", battle_v4, dict(minimap_mode=False)],
[
"magent/battlefield_v5",
battlefield_v5,
dict(minimap_mode=False, extra_features=False),
],
[
"magent/battlefield_v5",
battlefield_v5,
dict(minimap_mode=False, extra_features=True),
],
[
"magent/battlefield_v5",
battlefield_v5,
dict(minimap_mode=True, extra_features=False),
],
[
"magent/battlefield_v5",
battlefield_v5,
dict(minimap_mode=True, extra_features=True),
],
["magent/adversarial_pursuit_v4", adversarial_pursuit_v4, dict(map_size=15)],
["magent/battle_v4", battle_v4, dict(map_size=15)],
["magent/battlefield_v5", battlefield_v5, dict(map_size=46)],
["magent/combined_arms_v6", combined_arms_v6, dict(map_size=16)],
["magent/tiger_deer_v4", tiger_deer_v4, dict(map_size=15)],
["mpe/simple_adversary_v2", simple_adversary_v2, dict(N=4)],
["mpe/simple_reference_v2", simple_reference_v2, dict(local_ratio=0.2)],
["mpe/simple_spread_v2", simple_spread_v2, dict(N=5)],
[
"mpe/simple_tag_v2",
simple_tag_v2,
dict(num_good=5, num_adversaries=10, num_obstacles=4),
],
[
"mpe/simple_tag_v2",
simple_tag_v2,
dict(num_good=1, num_adversaries=1, num_obstacles=1),
],
[
"mpe/simple_world_comm_v2",
simple_world_comm_v2,
dict(num_good=5, num_adversaries=10, num_obstacles=4, num_food=3),
],
[
"mpe/simple_world_comm_v2",
simple_world_comm_v2,
dict(num_good=1, num_adversaries=1, num_obstacles=1, num_food=1),
],
[
"mpe/simple_adversary_v2",
simple_adversary_v2,
dict(N=4, continuous_actions=True),
],
[
"mpe/simple_reference_v2",
simple_reference_v2,
dict(local_ratio=0.2, continuous_actions=True),
],
["mpe/simple_spread_v2", simple_spread_v2, dict(N=5, continuous_actions=True)],
[
"mpe/simple_tag_v2",
simple_tag_v2,
dict(num_good=5, num_adversaries=10, num_obstacles=4, continuous_actions=True),
],
[
"mpe/simple_tag_v2",
simple_tag_v2,
dict(num_good=1, num_adversaries=1, num_obstacles=1, continuous_actions=True),
],
[
"mpe/simple_world_comm_v2",
simple_world_comm_v2,
dict(
num_good=5,
num_adversaries=10,
num_obstacles=4,
num_food=3,
continuous_actions=True,
),
],
[
"mpe/simple_world_comm_v2",
simple_world_comm_v2,
dict(
num_good=1,
num_adversaries=1,
num_obstacles=1,
num_food=1,
continuous_actions=True,
),
],
["sisl/multiwalker_v9", multiwalker_v9, dict(n_walkers=10)],
["sisl/multiwalker_v9", multiwalker_v9, dict(shared_reward=False)],
["sisl/multiwalker_v9", multiwalker_v9, dict(terminate_on_fall=False)],
[
"sisl/multiwalker_v8",
multiwalker_v9,
dict(terminate_on_fall=False, remove_on_fall=False),
],
["sisl/pursuit_v4", pursuit_v4, dict(x_size=8, y_size=19)],
["sisl/pursuit_v4", pursuit_v4, dict(shared_reward=True)],
["sisl/pursuit_v4", pursuit_v4, dict(n_evaders=5, n_pursuers=16)],
["sisl/pursuit_v4", pursuit_v4, dict(obs_range=15)],
["sisl/pursuit_v4", pursuit_v4, dict(n_catch=3)],
["sisl/pursuit_v4", pursuit_v4, dict(freeze_evaders=True)],
["sisl/waterworld_v3", waterworld_v3, dict(n_pursuers=3, n_evaders=6)],
["sisl/waterworld_v3", waterworld_v3, dict(n_coop=1)],
["sisl/waterworld_v3", waterworld_v3, dict(n_coop=1)],
["sisl/waterworld_v3", waterworld_v3, dict(n_poison=4)],
["sisl/waterworld_v3", waterworld_v3, dict(n_sensors=4)],
["sisl/waterworld_v3", waterworld_v3, dict(local_ratio=0.5)],
["sisl/waterworld_v3", waterworld_v3, dict(speed_features=False)],
]
@pytest.mark.parametrize(["name", "env_module", "kwargs"], parameterized_envs)
def test_module(name, env_module, kwargs):
_env = env_module.env(**kwargs)
api_test(_env)
# some atari environments fail this test
if "atari/" not in name:
seed_test(lambda: env_module.env(**kwargs), 50)
render_test(lambda: env_module.env(**kwargs))
if hasattr(env_module, "parallel_env"):
par_env = env_module.parallel_env(**kwargs)
try:
_env.state()
state_test(_env, par_env)
except NotImplementedError:
# no issue if state is simply not implemented
pass
| [
"pytest.mark.parametrize",
"pettingzoo.test.state_test.state_test",
"pettingzoo.test.api_test.api_test"
] | [((9632, 9709), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (["['name', 'env_module', 'kwargs']", 'parameterized_envs'], {}), "(['name', 'env_module', 'kwargs'], parameterized_envs)\n", (9655, 9709), False, 'import pytest\n'), ((9793, 9807), 'pettingzoo.test.api_test.api_test', 'api_test', (['_env'], {}), '(_env)\n', (9801, 9807), False, 'from pettingzoo.test.api_test import api_test\n'), ((10124, 10149), 'pettingzoo.test.state_test.state_test', 'state_test', (['_env', 'par_env'], {}), '(_env, par_env)\n', (10134, 10149), False, 'from pettingzoo.test.state_test import state_test\n')] |
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, TextAreaField, SelectField, BooleanField
from wtforms.validators import InputRequired, Length, EqualTo, ValidationError, Email, Required
from ..models import User
from wtforms import ValidationError
from flask_wtf.file import FileField, FileAllowed
def invalid_credentials(form, field):
"""Username and password checker"""
username_entered =form.username.data
password_entered = field.data
user_object = User.query.filter_by(username=username_entered).first()
if user_object is None or not user_object.verify_password(password_entered):
raise ValidationError("Username or Password is incorrect")
class RegistrationForm(FlaskForm):
"""Restration form"""
email = StringField('Your Email Address',validators=[InputRequired(),Email()])
username = StringField('username', validators=[InputRequired(message='Username required'), Length(min=4, max=25, message='Username must be between 4 and 25 characters')])
password = PasswordField('password', validators=[InputRequired(message='Password required'), Length(min=4, max=25, message='Password must be between 4 and 25 characters')])
confirm_pswd = PasswordField('confirm Password', validators=[InputRequired(message='Password required'), EqualTo('password', message="Passwords must match")])
remember = BooleanField('Subscribe')
submit_button = SubmitField('Sign up')
def validate_email(self,data_field):
if User.query.filter_by(email =data_field.data).first():
raise ValidationError('There is an account with that email')
def validate_username(self,data_field):
if User.query.filter_by(username = data_field.data).first():
raise ValidationError('That username is taken')
class LoginForm(FlaskForm):
"""Login form"""
username = StringField('username', validators=[InputRequired(message="Username required")])
password = PasswordField('password', validators=[InputRequired(message="Password required"), invalid_credentials])
remember = BooleanField('Remember Me')
submit_button = SubmitField('Sign In')
class PostForm(FlaskForm):
topic = StringField('Topic', validators=[InputRequired(message="Topic required")])
category = SelectField('Category', choices=[('product', 'product'), ('interview', 'interview'), ('promotion', 'promotion')], validators=[InputRequired(message="Category required")])
description = StringField('Description', validators=[InputRequired(message="Description required")])
submit= SubmitField('Post')
class UpdateProfile(FlaskForm):
bio = TextAreaField('Tell us about you.',validators = [Required()])
email = StringField('Your Email Address',validators=[InputRequired(),Email()])
username = StringField('username', validators=[InputRequired(message='Username required'), Length(min=4, max=25, message='Username must be between 4 and 25 characters')])
profile_pic_path = FileField('Update Profile Picture', validators=[FileAllowed(['jpg', 'png'])])
submit = SubmitField('Submit')
class CommentsForm(FlaskForm):
comment = TextAreaField('Type Comment.',validators = [Required()])
submit = SubmitField('Submit') | [
"wtforms.validators.Email",
"wtforms.validators.InputRequired",
"flask_wtf.file.FileAllowed",
"wtforms.BooleanField",
"wtforms.SubmitField",
"wtforms.validators.EqualTo",
"wtforms.validators.Required",
"wtforms.validators.Length",
"wtforms.ValidationError"
] | [((1399, 1424), 'wtforms.BooleanField', 'BooleanField', (['"""Subscribe"""'], {}), "('Subscribe')\n", (1411, 1424), False, 'from wtforms import StringField, PasswordField, SubmitField, TextAreaField, SelectField, BooleanField\n'), ((1445, 1467), 'wtforms.SubmitField', 'SubmitField', (['"""Sign up"""'], {}), "('Sign up')\n", (1456, 1467), False, 'from wtforms import StringField, PasswordField, SubmitField, TextAreaField, SelectField, BooleanField\n'), ((2111, 2138), 'wtforms.BooleanField', 'BooleanField', (['"""Remember Me"""'], {}), "('Remember Me')\n", (2123, 2138), False, 'from wtforms import StringField, PasswordField, SubmitField, TextAreaField, SelectField, BooleanField\n'), ((2159, 2181), 'wtforms.SubmitField', 'SubmitField', (['"""Sign In"""'], {}), "('Sign In')\n", (2170, 2181), False, 'from wtforms import StringField, PasswordField, SubmitField, TextAreaField, SelectField, BooleanField\n'), ((2600, 2619), 'wtforms.SubmitField', 'SubmitField', (['"""Post"""'], {}), "('Post')\n", (2611, 2619), False, 'from wtforms import StringField, PasswordField, SubmitField, TextAreaField, SelectField, BooleanField\n'), ((3098, 3119), 'wtforms.SubmitField', 'SubmitField', (['"""Submit"""'], {}), "('Submit')\n", (3109, 3119), False, 'from wtforms import StringField, PasswordField, SubmitField, TextAreaField, SelectField, BooleanField\n'), ((3237, 3258), 'wtforms.SubmitField', 'SubmitField', (['"""Submit"""'], {}), "('Submit')\n", (3248, 3258), False, 'from wtforms import StringField, PasswordField, SubmitField, TextAreaField, SelectField, BooleanField\n'), ((666, 718), 'wtforms.ValidationError', 'ValidationError', (['"""Username or Password is incorrect"""'], {}), "('Username or Password is incorrect')\n", (681, 718), False, 'from wtforms import ValidationError\n'), ((1601, 1655), 'wtforms.ValidationError', 'ValidationError', (['"""There is an account with that email"""'], {}), "('There is an account with that email')\n", (1616, 1655), False, 'from wtforms import ValidationError\n'), ((1788, 1829), 'wtforms.ValidationError', 'ValidationError', (['"""That username is taken"""'], {}), "('That username is taken')\n", (1803, 1829), False, 'from wtforms import ValidationError\n'), ((843, 858), 'wtforms.validators.InputRequired', 'InputRequired', ([], {}), '()\n', (856, 858), False, 'from wtforms.validators import InputRequired, Length, EqualTo, ValidationError, Email, Required\n'), ((859, 866), 'wtforms.validators.Email', 'Email', ([], {}), '()\n', (864, 866), False, 'from wtforms.validators import InputRequired, Length, EqualTo, ValidationError, Email, Required\n'), ((920, 962), 'wtforms.validators.InputRequired', 'InputRequired', ([], {'message': '"""Username required"""'}), "(message='Username required')\n", (933, 962), False, 'from wtforms.validators import InputRequired, Length, EqualTo, ValidationError, Email, Required\n'), ((964, 1041), 'wtforms.validators.Length', 'Length', ([], {'min': '(4)', 'max': '(25)', 'message': '"""Username must be between 4 and 25 characters"""'}), "(min=4, max=25, message='Username must be between 4 and 25 characters')\n", (970, 1041), False, 'from wtforms.validators import InputRequired, Length, EqualTo, ValidationError, Email, Required\n'), ((1097, 1139), 'wtforms.validators.InputRequired', 'InputRequired', ([], {'message': '"""Password required"""'}), "(message='Password required')\n", (1110, 1139), False, 'from wtforms.validators import InputRequired, Length, EqualTo, ValidationError, Email, Required\n'), ((1141, 1218), 'wtforms.validators.Length', 'Length', ([], {'min': '(4)', 'max': '(25)', 'message': '"""Password must be between 4 and 25 characters"""'}), "(min=4, max=25, message='Password must be between 4 and 25 characters')\n", (1147, 1218), False, 'from wtforms.validators import InputRequired, Length, EqualTo, ValidationError, Email, Required\n'), ((1286, 1328), 'wtforms.validators.InputRequired', 'InputRequired', ([], {'message': '"""Password required"""'}), "(message='Password required')\n", (1299, 1328), False, 'from wtforms.validators import InputRequired, Length, EqualTo, ValidationError, Email, Required\n'), ((1330, 1381), 'wtforms.validators.EqualTo', 'EqualTo', (['"""password"""'], {'message': '"""Passwords must match"""'}), "('password', message='Passwords must match')\n", (1337, 1381), False, 'from wtforms.validators import InputRequired, Length, EqualTo, ValidationError, Email, Required\n'), ((1932, 1974), 'wtforms.validators.InputRequired', 'InputRequired', ([], {'message': '"""Username required"""'}), "(message='Username required')\n", (1945, 1974), False, 'from wtforms.validators import InputRequired, Length, EqualTo, ValidationError, Email, Required\n'), ((2030, 2072), 'wtforms.validators.InputRequired', 'InputRequired', ([], {'message': '"""Password required"""'}), "(message='Password required')\n", (2043, 2072), False, 'from wtforms.validators import InputRequired, Length, EqualTo, ValidationError, Email, Required\n'), ((2255, 2294), 'wtforms.validators.InputRequired', 'InputRequired', ([], {'message': '"""Topic required"""'}), "(message='Topic required')\n", (2268, 2294), False, 'from wtforms.validators import InputRequired, Length, EqualTo, ValidationError, Email, Required\n'), ((2438, 2480), 'wtforms.validators.InputRequired', 'InputRequired', ([], {'message': '"""Category required"""'}), "(message='Category required')\n", (2451, 2480), False, 'from wtforms.validators import InputRequired, Length, EqualTo, ValidationError, Email, Required\n'), ((2540, 2585), 'wtforms.validators.InputRequired', 'InputRequired', ([], {'message': '"""Description required"""'}), "(message='Description required')\n", (2553, 2585), False, 'from wtforms.validators import InputRequired, Length, EqualTo, ValidationError, Email, Required\n'), ((2713, 2723), 'wtforms.validators.Required', 'Required', ([], {}), '()\n', (2721, 2723), False, 'from wtforms.validators import InputRequired, Length, EqualTo, ValidationError, Email, Required\n'), ((2783, 2798), 'wtforms.validators.InputRequired', 'InputRequired', ([], {}), '()\n', (2796, 2798), False, 'from wtforms.validators import InputRequired, Length, EqualTo, ValidationError, Email, Required\n'), ((2799, 2806), 'wtforms.validators.Email', 'Email', ([], {}), '()\n', (2804, 2806), False, 'from wtforms.validators import InputRequired, Length, EqualTo, ValidationError, Email, Required\n'), ((2860, 2902), 'wtforms.validators.InputRequired', 'InputRequired', ([], {'message': '"""Username required"""'}), "(message='Username required')\n", (2873, 2902), False, 'from wtforms.validators import InputRequired, Length, EqualTo, ValidationError, Email, Required\n'), ((2904, 2981), 'wtforms.validators.Length', 'Length', ([], {'min': '(4)', 'max': '(25)', 'message': '"""Username must be between 4 and 25 characters"""'}), "(min=4, max=25, message='Username must be between 4 and 25 characters')\n", (2910, 2981), False, 'from wtforms.validators import InputRequired, Length, EqualTo, ValidationError, Email, Required\n'), ((3055, 3082), 'flask_wtf.file.FileAllowed', 'FileAllowed', (["['jpg', 'png']"], {}), "(['jpg', 'png'])\n", (3066, 3082), False, 'from flask_wtf.file import FileField, FileAllowed\n'), ((3211, 3221), 'wtforms.validators.Required', 'Required', ([], {}), '()\n', (3219, 3221), False, 'from wtforms.validators import InputRequired, Length, EqualTo, ValidationError, Email, Required\n')] |
#
# Copyright (c) 2017 nexB Inc. and others. All rights reserved.
# http://nexb.com and https://github.com/nexB/scancode-toolkit/
# The ScanCode software is licensed under the Apache License version 2.0.
# Data generated with ScanCode require an acknowledgment.
# ScanCode is a trademark of nexB Inc.
#
# You may not use this software except in compliance with the License.
# You may obtain a copy of the License at: http://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.
#
# When you publish or redistribute any data created with ScanCode or any ScanCode
# derivative work, you must accompany this data with the following acknowledgment:
#
# Generated with ScanCode and provided on an "AS IS" BASIS, WITHOUT WARRANTIES
# OR CONDITIONS OF ANY KIND, either express or implied. No content created from
# ScanCode should be considered or used as legal advice. Consult an Attorney
# for any legal advice.
# ScanCode is a free software code scanning tool from nexB Inc. and others.
# Visit https://github.com/nexB/scancode-toolkit/ for support and download.
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import chardet
from lxml import etree
from textcode import analysis
"""
Utility functions for dealing with XML.
"""
def parse(location, handler):
"""
Given the location of an XML file and a handler function accepting a
etree document, parse the file at location and invoke the handler on
the etree doc. If parsing fails while calling handler, another
approach to parsing is used.
This is a workaround some lxml bug/weirdness wrt unicode in the 2.3
version in use.
The `handler` function must have no side effects and can be called
again on failures without risk.
Try first to call lxml from a location then try from a string to
deal with weird encodings
"""
try:
parser = etree.XMLParser(recover=True, remove_blank_text=True, resolve_entities=False)
xdoc = etree.parse(location, parser)
return handler(xdoc)
except:
parser = etree.XMLParser(recover=True, remove_blank_text=True, resolve_entities=False)
text = analysis.unicode_text(location)
xdoc= etree.fromstring(_as_unicode_bytes(text), parser)
return handler(xdoc)
# FIXME: encoding should be processed/detected elsewhere
def _as_unicode_bytes(text):
"""
Given a unicode text, return a unicode encoded byte string.
"""
try:
return text.encode('utf-8')
except UnicodeEncodeError:
encoding = chardet.detect(text[:4096])
if encoding:
encoding = encoding.get('encoding')
return text.encode(encoding)
else:
raise
def find_text(xdoc, xpath):
"""
Return a list of text values from an `xpath` expression found in an
etree `xdoc`.
"""
result = xdoc.xpath(xpath)
# xpath can return a list (nodeset), bool, float or string
texts = []
if isinstance(result, list):
for element in result:
if element.text:
texts.append(element.text.strip())
else:
# FIXME: this could fail
texts.append(unicode(result).strip())
return texts
def namespace_unaware(xpath):
"""
Return a new namespace-unaware xpath expression accepting any namespace
given a simple xpath expression using only single slashes.
This is achieved by wrapping each step of an expression with the local-
name() XPath function. XPath expressions with namespaced XML can be complex
and hard to read and write: this helps keep expression simple when
namespaces do not matter.
Use with caution: this works only for simple expression using only single /.
For example:
>>> simple_xpath = '/project/organization/url'
>>> expected = "/*[local-name()='project']/*[local-name()='organization']/*[local-name()='url']"
>>> assert expected == namespace_unaware(simple_xpath)
"""
# Search * and then a local-name in the returned elements
ignore_namespace = "*[local-name()='%s']"
new_steps = []
# we assume that the input expression is simple using only /
for step in xpath.split('/'):
if step:
new_steps.append(ignore_namespace % step)
else:
new_steps.append(step)
return '/'.join(new_steps)
def strip_namespace(tag_name):
"""
Strip all namespaces or namespace prefixes if present in an XML tag name .
For example:
>>> tag_name = '{http://maven.apache.org/POM/4.0.0}geronimo.osgi.export.pkg'
>>> expected = 'geronimo.osgi.export.pkg'
>>> assert expected == strip_namespace(tag_name)
"""
head, brace, tail = tag_name.rpartition('}')
return tail if brace else head
def name_value(elem):
"""
Return the name, value of an etree element `elem` stripping all namespaces
and prefixes from the tag name.
"""
name = strip_namespace(elem.tag).strip()
value = elem.text and elem.text.strip() or ''
return name, value
| [
"textcode.analysis.unicode_text",
"chardet.detect",
"lxml.etree.XMLParser",
"lxml.etree.parse"
] | [((2217, 2294), 'lxml.etree.XMLParser', 'etree.XMLParser', ([], {'recover': '(True)', 'remove_blank_text': '(True)', 'resolve_entities': '(False)'}), '(recover=True, remove_blank_text=True, resolve_entities=False)\n', (2232, 2294), False, 'from lxml import etree\n'), ((2310, 2339), 'lxml.etree.parse', 'etree.parse', (['location', 'parser'], {}), '(location, parser)\n', (2321, 2339), False, 'from lxml import etree\n'), ((2398, 2475), 'lxml.etree.XMLParser', 'etree.XMLParser', ([], {'recover': '(True)', 'remove_blank_text': '(True)', 'resolve_entities': '(False)'}), '(recover=True, remove_blank_text=True, resolve_entities=False)\n', (2413, 2475), False, 'from lxml import etree\n'), ((2491, 2522), 'textcode.analysis.unicode_text', 'analysis.unicode_text', (['location'], {}), '(location)\n', (2512, 2522), False, 'from textcode import analysis\n'), ((2879, 2906), 'chardet.detect', 'chardet.detect', (['text[:4096]'], {}), '(text[:4096])\n', (2893, 2906), False, 'import chardet\n')] |