code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
"""
This tests the Real Time Clock (RTC) component of a PIM Mini, using the I2C protocol.
These test cases require that a PC is attached to the SDA and SCL lines between the MPU and
I2C components in order to use the Aardvark drivers.
If the PC is running Linux, it is assumed that it is running a 64-bit version.
"""
import unittest
import time
from datetime import datetime, timedelta
from collections import namedtuple
from aardvark_py.aai2c_slave import aa_open, aa_configure, aa_i2c_pullup, aa_target_power,\
aa_i2c_bitrate, aa_i2c_bus_timeout, aa_close, aa_i2c_write, aa_i2c_read, AA_CONFIG_GPIO_I2C,\
AA_I2C_PULLUP_BOTH, AA_TARGET_POWER_BOTH, AA_UNABLE_TO_CLOSE, AA_I2C_NO_FLAGS, array
from aardvark_settings import RTC_PORT_NUMBER as PORT_NUMBER, RTC_SLAVE_ADDRESS as SLAVE_ADDRESS,\
SECONDS_ADDRESS, MINUTE_ADDRESS, HOUR_ADDRESS, DAY_OF_WEEK_ADDRESS, DAY_OF_MONTH_ADDRESS,\
MONTH_ADDRESS, YEAR_ADDRESS, TIME_PERIOD
ClockData = namedtuple("ClockData", [
"year",
"month",
"day_of_month",
"day_of_week",
"hours",
"minutes",
"seconds"
])
class I2CRTC(unittest.TestCase): # pylint: disable=R0904
"""
Tests various scenarios relating to the Real Time Clock (RTC), via the I2C protocol.
The tests are numbered to ensure that they are executed in order.
"""
def __init__(self, methodName='runTest'):
"""Initializer for attributes"""
unittest.TestCase.__init__(self, methodName=methodName)
self.handle = None
def setUp(self):
"""Is executed before every test"""
self.handle = aa_open(PORT_NUMBER)
aa_configure(self.handle, AA_CONFIG_GPIO_I2C)
aa_i2c_pullup(self.handle, AA_I2C_PULLUP_BOTH)
aa_target_power(self.handle, AA_TARGET_POWER_BOTH)
aa_i2c_bitrate(self.handle, 400) # bitrate = 400
aa_i2c_bus_timeout(self.handle, 10) # timeout = 10ms
@staticmethod
def b10tob16(value):
"""
Converts decimal numbers to hexadecimal numbers.
Code courtesy of
[the Linux kernel v4.6](elixir.free-electrons.com/linux/v4.6/source/include/linux/bcd.h).
"""
return (int(value / 10) << 4) + value % 10
@staticmethod
def b16tob10(value):
"""
Converts hexadecimal numbers to decimal numbers.
Code courtesy of
[the Linux kernel v4.6](elixir.free-electrons.com/linux/v4.6/source/include/linux/bcd.h).
"""
return ((value) & 0x0f) + ((value) >> 4) * 10
@staticmethod
def _write_convert(data):
"""Converts data for writing to the RTC"""
century_bit = (1 << 7) if (data.year - 1900) > 199 else 0
data_out = ClockData(
year=I2CRTC.b10tob16(data.year % 100),
month=I2CRTC.b10tob16(data.month) | century_bit,
day_of_month=I2CRTC.b10tob16(data.day_of_month),
day_of_week=I2CRTC.b10tob16(data.day_of_week),
hours=I2CRTC.b10tob16(data.hours),
minutes=I2CRTC.b10tob16(data.minutes),
seconds=I2CRTC.b10tob16(data.seconds)
)
return data_out
def _write(self, address, value):
"""Method which actually writes to the addresses"""
data_out = array('B', [address & 0xff, value])
result = aa_i2c_write(aardvark=self.handle, slave_addr=address,
flags=AA_I2C_NO_FLAGS, data_out=data_out)
self.assertGreater(result, 0)
self.assertEqual(result, 1)
def write(self, data):
"""Writes data to the RTC"""
data_out = I2CRTC._write_convert(data)
self._write(YEAR_ADDRESS, data_out.year)
self._write(MONTH_ADDRESS, data_out.month)
self._write(DAY_OF_MONTH_ADDRESS, data_out.day_of_month)
self._write(DAY_OF_WEEK_ADDRESS, data_out.day_of_week)
self._write(HOUR_ADDRESS, data_out.hours)
self._write(MINUTE_ADDRESS, data_out.minutes)
self._write(SECONDS_ADDRESS, data_out.seconds)
def read(self):
"""Reads data from the RTC and converts it back into the correct format"""
reg_month = self._read(
MONTH_ADDRESS) # this is going to be used twice, so keep it
data_in = ClockData(
year=I2CRTC.b16tob10(self._read(YEAR_ADDRESS)) + 100,
month=I2CRTC.b16tob10(reg_month & 0x1f),
day_of_month=I2CRTC.b16tob10(self._read(DAY_OF_MONTH_ADDRESS)),
day_of_week=I2CRTC.b16tob10(self._read(DAY_OF_WEEK_ADDRESS)),
hours=I2CRTC.b16tob10(self._read(HOUR_ADDRESS) & 0x3f),
minutes=I2CRTC.b16tob10(self._read(MINUTE_ADDRESS)),
seconds=I2CRTC.b16tob10(self._read(SECONDS_ADDRESS)),
)
if reg_month & (1 << 7):
data_in.year += 1
return data_in
def _read(self, address):
"""Reads an address and returns it"""
aa_i2c_write(aardvark=self.handle, slave_addr=SLAVE_ADDRESS,
flags=AA_I2C_NO_FLAGS, data_out=array('B', [address & 0xff]))
count, data_in = aa_i2c_read(
aardvark=self.handle, slave_addr=address, flags=AA_I2C_NO_FLAGS, data_in=1)
self.assertEqual(count, 1)
return data_in[0]
def check(self, data, time_period=10):
"""
Checks that the clock can accurately keep the time.
: `data` : - The data which will be initially written to the RTC
: `time_period` : - The time delta (seconds) after which the RTC will be checked.
default - `10`
"""
delta = timedelta(seconds=time_period)
data_formatted = datetime(
data.year,
data.month,
data.day_of_month,
data.hours,
data.minutes,
data.seconds)
self.assertEqual(data.day_of_week, data_formatted.weekday() + 1)
self.write(data)
time.sleep(delta.total_seconds)
data_in = self.read()
data_in_formatted = datetime(
data_in.year,
data_in.month,
data_in.day_of_month,
data_in.hours,
data_in.minutes,
data_in.seconds)
check_data = data_formatted + delta
self.assertEqual(check_data, data_in_formatted)
self.assertEqual(check_data.weekday() + 1, data_in.day_of_week)
def tearDown(self):
"""Is executed after every test"""
if aa_close(self.handle) == AA_UNABLE_TO_CLOSE:
raise Exception("The handle failed to close")
self.handle = None
def test_01_set_second(self):
"""Checks that the seconds turn over the minute correctly (i.e. mod 60)"""
data = ClockData(
year=2017,
month=12,
day_of_month=8,
day_of_week=5,
hours=14,
minutes=0,
seconds=55
)
self.check(data)
def test_02_set_second_incr(self):
"""Checks that the seconds increment correctly"""
data = ClockData(
year=2017,
month=12,
day_of_month=8,
day_of_week=5,
hours=14,
minutes=0,
seconds=10
)
self.check(data)
def test_03_set_minute(self):
"""Checks that the minutes turn over the hour correctly (i.e. mod 60)"""
data = ClockData(
year=2017,
month=12,
day_of_month=8,
day_of_week=5,
hours=14,
minutes=59,
seconds=55
)
self.check(data)
def test_04_set_minute_incr(self):
"""Checks that the minutes increment correctly"""
data = ClockData(
year=2017,
month=12,
day_of_month=8,
day_of_week=5,
hours=14,
minutes=0,
seconds=55
)
self.check(data)
def test_05_set_hour_24(self):
"""Checks that the hours turn over the day correctly (i.e. mod 24)"""
data = ClockData(
year=2017,
month=12,
day_of_month=8,
day_of_week=5,
hours=23,
minutes=59,
seconds=55
)
self.check(data)
def test_06_set_hour_incr_24(self):
"""Checks that the hours increment correctly"""
data = ClockData(
year=2017,
month=12,
day_of_month=8,
day_of_week=5,
hours=14,
minutes=59,
seconds=55
)
self.check(data)
def test_07_set_day_31(self):
"""Checks that the days turn over the month correctly (i.e. mod 31)"""
data = ClockData(
year=2017,
month=10,
day_of_month=31,
day_of_week=2,
hours=23,
minutes=59,
seconds=55
)
self.check(data)
def test_08_set_day_30(self):
"""Checks that the days turn over the month correctly (i.e. mod 30)"""
data = ClockData(
year=2017,
month=9,
day_of_month=30,
day_of_week=6,
hours=23,
minutes=59,
seconds=55
)
self.check(data)
def test_09_set_day_28(self):
"""
Checks that the days turn over the month correctly for an invalid leap year (i.e. mod 28)
"""
data = ClockData(
year=2017,
month=2,
day_of_month=28,
day_of_week=2,
hours=23,
minutes=59,
seconds=55
)
self.check(data)
def test_10_leap_year_div4(self):
"""Checks that the days turn over the month correctly for a valid leap year"""
data = ClockData(
year=2004,
month=2,
day_of_month=28,
day_of_week=6,
hours=23,
minutes=59,
seconds=55
)
self.check(data)
def test_11_leap_year_div100(self):
"""
Checks that the days turn over the month correctly for an invalid leap year
(when the year is divisible by 100)
"""
data = ClockData(
year=2100,
month=2,
day_of_month=28,
day_of_week=7,
hours=23,
minutes=59,
seconds=55
)
self.check(data)
def test_12_leap_year_div400(self):
"""
Checks that the days turn over the month correctly for an valid leap year
(when the year is divisible by 400)
"""
data = ClockData(
year=2000,
month=2,
day_of_month=28,
day_of_week=1,
hours=23,
minutes=59,
seconds=55
)
self.check(data)
def test_13_set_day_incr(self):
"""Checks that the days increment correctly"""
data = ClockData(
year=2017,
month=12,
day_of_month=8,
day_of_week=5,
hours=23,
minutes=59,
seconds=55
)
self.check(data)
def test_14_set_month(self):
"""Checks that the months turn over the year correctly"""
data = ClockData(
year=2017,
month=12,
day_of_month=31,
day_of_week=7,
hours=23,
minutes=59,
seconds=55
)
self.check(data)
def test_15_set_month_incr(self):
"""Checks that the months increment correctly"""
data = ClockData(
year=2017,
month=8,
day_of_month=31,
day_of_week=4,
hours=23,
minutes=59,
seconds=55
)
self.check(data)
def test_16_set_year(self):
"""Checks that the years turn over the century correctly"""
data = ClockData(
year=2099,
month=12,
day_of_month=31,
day_of_week=4,
hours=23,
minutes=0,
seconds=55
)
self.check(data)
def test_17_set_year_incr(self):
"""Checks that the years increment correctly"""
data = ClockData(
year=2017,
month=12,
day_of_month=31,
day_of_week=7,
hours=23,
minutes=0,
seconds=55
)
self.check(data)
def test_18_period(self):
"""Checks that the RTC is accurate over the specified time period"""
data = ClockData(
year=2000,
month=1,
day_of_month=1,
day_of_week=1,
hours=0,
minutes=0,
seconds=0
)
self.check(data, TIME_PERIOD)
def construct_test_suite():
"""Constructs the test suite"""
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(I2CRTC))
return suite
def main():
"""Runs the test suite"""
test_runner = unittest.TextTestRunner(verbosity=2)
test_runner.run(construct_test_suite())
if __name__ == '__main__':
main()
| [
"datetime.datetime",
"unittest.TestSuite",
"collections.namedtuple",
"aardvark_py.aai2c_slave.aa_configure",
"unittest.makeSuite",
"aardvark_py.aai2c_slave.aa_target_power",
"time.sleep",
"aardvark_py.aai2c_slave.aa_i2c_write",
"aardvark_py.aai2c_slave.aa_i2c_read",
"aardvark_py.aai2c_slave.aa_ope... | [((954, 1062), 'collections.namedtuple', 'namedtuple', (['"""ClockData"""', "['year', 'month', 'day_of_month', 'day_of_week', 'hours', 'minutes', 'seconds']"], {}), "('ClockData', ['year', 'month', 'day_of_month', 'day_of_week',\n 'hours', 'minutes', 'seconds'])\n", (964, 1062), False, 'from collections import namedtuple\n'), ((12875, 12895), 'unittest.TestSuite', 'unittest.TestSuite', ([], {}), '()\n', (12893, 12895), False, 'import unittest\n'), ((13021, 13057), 'unittest.TextTestRunner', 'unittest.TextTestRunner', ([], {'verbosity': '(2)'}), '(verbosity=2)\n', (13044, 13057), False, 'import unittest\n'), ((1422, 1477), 'unittest.TestCase.__init__', 'unittest.TestCase.__init__', (['self'], {'methodName': 'methodName'}), '(self, methodName=methodName)\n', (1448, 1477), False, 'import unittest\n'), ((1593, 1613), 'aardvark_py.aai2c_slave.aa_open', 'aa_open', (['PORT_NUMBER'], {}), '(PORT_NUMBER)\n', (1600, 1613), False, 'from aardvark_py.aai2c_slave import aa_open, aa_configure, aa_i2c_pullup, aa_target_power, aa_i2c_bitrate, aa_i2c_bus_timeout, aa_close, aa_i2c_write, aa_i2c_read, AA_CONFIG_GPIO_I2C, AA_I2C_PULLUP_BOTH, AA_TARGET_POWER_BOTH, AA_UNABLE_TO_CLOSE, AA_I2C_NO_FLAGS, array\n'), ((1622, 1667), 'aardvark_py.aai2c_slave.aa_configure', 'aa_configure', (['self.handle', 'AA_CONFIG_GPIO_I2C'], {}), '(self.handle, AA_CONFIG_GPIO_I2C)\n', (1634, 1667), False, 'from aardvark_py.aai2c_slave import aa_open, aa_configure, aa_i2c_pullup, aa_target_power, aa_i2c_bitrate, aa_i2c_bus_timeout, aa_close, aa_i2c_write, aa_i2c_read, AA_CONFIG_GPIO_I2C, AA_I2C_PULLUP_BOTH, AA_TARGET_POWER_BOTH, AA_UNABLE_TO_CLOSE, AA_I2C_NO_FLAGS, array\n'), ((1676, 1722), 'aardvark_py.aai2c_slave.aa_i2c_pullup', 'aa_i2c_pullup', (['self.handle', 'AA_I2C_PULLUP_BOTH'], {}), '(self.handle, AA_I2C_PULLUP_BOTH)\n', (1689, 1722), False, 'from aardvark_py.aai2c_slave import aa_open, aa_configure, aa_i2c_pullup, aa_target_power, aa_i2c_bitrate, aa_i2c_bus_timeout, aa_close, aa_i2c_write, aa_i2c_read, AA_CONFIG_GPIO_I2C, AA_I2C_PULLUP_BOTH, AA_TARGET_POWER_BOTH, AA_UNABLE_TO_CLOSE, AA_I2C_NO_FLAGS, array\n'), ((1731, 1781), 'aardvark_py.aai2c_slave.aa_target_power', 'aa_target_power', (['self.handle', 'AA_TARGET_POWER_BOTH'], {}), '(self.handle, AA_TARGET_POWER_BOTH)\n', (1746, 1781), False, 'from aardvark_py.aai2c_slave import aa_open, aa_configure, aa_i2c_pullup, aa_target_power, aa_i2c_bitrate, aa_i2c_bus_timeout, aa_close, aa_i2c_write, aa_i2c_read, AA_CONFIG_GPIO_I2C, AA_I2C_PULLUP_BOTH, AA_TARGET_POWER_BOTH, AA_UNABLE_TO_CLOSE, AA_I2C_NO_FLAGS, array\n'), ((1790, 1822), 'aardvark_py.aai2c_slave.aa_i2c_bitrate', 'aa_i2c_bitrate', (['self.handle', '(400)'], {}), '(self.handle, 400)\n', (1804, 1822), False, 'from aardvark_py.aai2c_slave import aa_open, aa_configure, aa_i2c_pullup, aa_target_power, aa_i2c_bitrate, aa_i2c_bus_timeout, aa_close, aa_i2c_write, aa_i2c_read, AA_CONFIG_GPIO_I2C, AA_I2C_PULLUP_BOTH, AA_TARGET_POWER_BOTH, AA_UNABLE_TO_CLOSE, AA_I2C_NO_FLAGS, array\n'), ((1848, 1883), 'aardvark_py.aai2c_slave.aa_i2c_bus_timeout', 'aa_i2c_bus_timeout', (['self.handle', '(10)'], {}), '(self.handle, 10)\n', (1866, 1883), False, 'from aardvark_py.aai2c_slave import aa_open, aa_configure, aa_i2c_pullup, aa_target_power, aa_i2c_bitrate, aa_i2c_bus_timeout, aa_close, aa_i2c_write, aa_i2c_read, AA_CONFIG_GPIO_I2C, AA_I2C_PULLUP_BOTH, AA_TARGET_POWER_BOTH, AA_UNABLE_TO_CLOSE, AA_I2C_NO_FLAGS, array\n'), ((3235, 3269), 'aardvark_py.aai2c_slave.array', 'array', (['"""B"""', '[address & 255, value]'], {}), "('B', [address & 255, value])\n", (3240, 3269), False, 'from aardvark_py.aai2c_slave import aa_open, aa_configure, aa_i2c_pullup, aa_target_power, aa_i2c_bitrate, aa_i2c_bus_timeout, aa_close, aa_i2c_write, aa_i2c_read, AA_CONFIG_GPIO_I2C, AA_I2C_PULLUP_BOTH, AA_TARGET_POWER_BOTH, AA_UNABLE_TO_CLOSE, AA_I2C_NO_FLAGS, array\n'), ((3288, 3389), 'aardvark_py.aai2c_slave.aa_i2c_write', 'aa_i2c_write', ([], {'aardvark': 'self.handle', 'slave_addr': 'address', 'flags': 'AA_I2C_NO_FLAGS', 'data_out': 'data_out'}), '(aardvark=self.handle, slave_addr=address, flags=\n AA_I2C_NO_FLAGS, data_out=data_out)\n', (3300, 3389), False, 'from aardvark_py.aai2c_slave import aa_open, aa_configure, aa_i2c_pullup, aa_target_power, aa_i2c_bitrate, aa_i2c_bus_timeout, aa_close, aa_i2c_write, aa_i2c_read, AA_CONFIG_GPIO_I2C, AA_I2C_PULLUP_BOTH, AA_TARGET_POWER_BOTH, AA_UNABLE_TO_CLOSE, AA_I2C_NO_FLAGS, array\n'), ((5044, 5135), 'aardvark_py.aai2c_slave.aa_i2c_read', 'aa_i2c_read', ([], {'aardvark': 'self.handle', 'slave_addr': 'address', 'flags': 'AA_I2C_NO_FLAGS', 'data_in': '(1)'}), '(aardvark=self.handle, slave_addr=address, flags=AA_I2C_NO_FLAGS,\n data_in=1)\n', (5055, 5135), False, 'from aardvark_py.aai2c_slave import aa_open, aa_configure, aa_i2c_pullup, aa_target_power, aa_i2c_bitrate, aa_i2c_bus_timeout, aa_close, aa_i2c_write, aa_i2c_read, AA_CONFIG_GPIO_I2C, AA_I2C_PULLUP_BOTH, AA_TARGET_POWER_BOTH, AA_UNABLE_TO_CLOSE, AA_I2C_NO_FLAGS, array\n'), ((5540, 5570), 'datetime.timedelta', 'timedelta', ([], {'seconds': 'time_period'}), '(seconds=time_period)\n', (5549, 5570), False, 'from datetime import datetime, timedelta\n'), ((5596, 5690), 'datetime.datetime', 'datetime', (['data.year', 'data.month', 'data.day_of_month', 'data.hours', 'data.minutes', 'data.seconds'], {}), '(data.year, data.month, data.day_of_month, data.hours, data.minutes,\n data.seconds)\n', (5604, 5690), False, 'from datetime import datetime, timedelta\n'), ((5867, 5898), 'time.sleep', 'time.sleep', (['delta.total_seconds'], {}), '(delta.total_seconds)\n', (5877, 5898), False, 'import time\n'), ((5957, 6069), 'datetime.datetime', 'datetime', (['data_in.year', 'data_in.month', 'data_in.day_of_month', 'data_in.hours', 'data_in.minutes', 'data_in.seconds'], {}), '(data_in.year, data_in.month, data_in.day_of_month, data_in.hours,\n data_in.minutes, data_in.seconds)\n', (5965, 6069), False, 'from datetime import datetime, timedelta\n'), ((12914, 12940), 'unittest.makeSuite', 'unittest.makeSuite', (['I2CRTC'], {}), '(I2CRTC)\n', (12932, 12940), False, 'import unittest\n'), ((6390, 6411), 'aardvark_py.aai2c_slave.aa_close', 'aa_close', (['self.handle'], {}), '(self.handle)\n', (6398, 6411), False, 'from aardvark_py.aai2c_slave import aa_open, aa_configure, aa_i2c_pullup, aa_target_power, aa_i2c_bitrate, aa_i2c_bus_timeout, aa_close, aa_i2c_write, aa_i2c_read, AA_CONFIG_GPIO_I2C, AA_I2C_PULLUP_BOTH, AA_TARGET_POWER_BOTH, AA_UNABLE_TO_CLOSE, AA_I2C_NO_FLAGS, array\n'), ((4989, 5016), 'aardvark_py.aai2c_slave.array', 'array', (['"""B"""', '[address & 255]'], {}), "('B', [address & 255])\n", (4994, 5016), False, 'from aardvark_py.aai2c_slave import aa_open, aa_configure, aa_i2c_pullup, aa_target_power, aa_i2c_bitrate, aa_i2c_bus_timeout, aa_close, aa_i2c_write, aa_i2c_read, AA_CONFIG_GPIO_I2C, AA_I2C_PULLUP_BOTH, AA_TARGET_POWER_BOTH, AA_UNABLE_TO_CLOSE, AA_I2C_NO_FLAGS, array\n')] |
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------
# Copyright (c) 2021
#
# See the LICENSE file for details
# see the AUTHORS file for authors
# ----------------------------------------------------------------------
#--------------------
# System wide imports
# -------------------
import os
import os.path
import logging
#--------------
# local imports
# -------------
from streetool.utils import paging
# -----------------------
# Module global variables
# -----------------------
log = logging.getLogger("streetoool")
# ----------------
# Module constants
# ----------------
def purge_zoo_export_t(connection):
log.info("Deleting all contents from table zoo_export_t")
cursor = connection.cursor()
cursor.execute('DELETE FROM zoo_export_t')
def purge_export_window_t(connection):
log.info("Deleting all contents from table zoo_export_window_t")
cursor = connection.cursor()
cursor.execute('DELETE FROM zoo_export_window_t')
def purge_light_sources_t(connection):
log.info("Deleting all contents from table light_sources_t")
cursor = connection.cursor()
cursor.execute('DELETE FROM light_sources_t')
def purge_spectra_classification_t(connection):
log.info("Deleting all contents from table spectra_classification_t")
cursor = connection.cursor()
cursor.execute('DELETE FROM spectra_classification_t')
def purge_epicollect5_t(connection):
log.info("Deleting all contents from table epicollect5_t")
cursor = connection.cursor()
cursor.execute('DELETE FROM epicollect5_t')
def purge_images_t(connection):
log.info("Deleting all contents from table images_t")
cursor = connection.cursor()
cursor.execute('DELETE FROM images_t')
def purge_metadata_files_t(connection):
log.info("Deleting all contents from table metadata_files_t")
cursor = connection.cursor()
cursor.execute('DELETE FROM metadata_files_t')
def purge_zenodo_csv_t(connection):
log.info("Deleting all contents from table zenodo_csv_t")
cursor = connection.cursor()
cursor.execute('DELETE FROM zenodo_csv_t')
def purge_classifications(connection):
purge_light_sources_t(connection)
purge_spectra_classification_t(connection)
purge_export_window_t(connection)
purge_zoo_export_t(connection)
def purge_publishing(connection):
purge_zenodo_csv_t(connection)
def purge_collection(connection):
purge_epicollect5_t(connection)
def purge_maps(connection):
purge_images_t(connection)
purge_metadata_files_t(connection)
# ========
# COMMANDS
# ========
def purge(connection, options):
if options.all:
purge_classifications(connection)
purge_collection(connection)
purge_publishing(connection)
connection.commit()
elif options.classif:
purge_classifications(connection)
connection.commit()
elif options.publ:
purge_publishing(connection)
connection.commit()
elif options.collect:
purge_collection(connection)
connection.commit()
elif options.maps:
purge_maps(connection)
connection.commit()
else:
raise ValueError("Command line option not recognized") | [
"logging.getLogger"
] | [((542, 573), 'logging.getLogger', 'logging.getLogger', (['"""streetoool"""'], {}), "('streetoool')\n", (559, 573), False, 'import logging\n')] |
import pandas as pd
import nltk
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import os
nltk.download('stopwords')
nltk.download('punkt')
nltk.download('wordnet_ic')
nltk.download('genesis')
nltk.download('averaged_perceptron_tagger')
nltk.download('wordnet')
from src.Preprocess import Utils
from src.Preprocess import Lexical_Features
from src.Preprocess import WordNet_Features
from src.Normalization import Normalization
# Set seed for all libraries
np.random.seed(123)
# To print the whole df
pd.options.display.width= None
pd.options.display.max_columns= None
pd.set_option('display.max_rows', 100)
pd.set_option('display.max_columns', 100)
# Load the datasets
names = [
'PhrasIS_test_h_n',
'PhrasIS_test_h_p',
'PhrasIS_test_i_n',
'PhrasIS_test_i_p',
'PhrasIS_train_h_n',
'PhrasIS_train_h_p',
'PhrasIS_train_i_n',
'PhrasIS_train_i_p'
]
paths = [
'dataset/PhrasIS.test.headlines.negatives.txt',
'dataset/PhrasIS.test.headlines.positives.txt',
'dataset/PhrasIS.test.images.negatives.txt',
'dataset/PhrasIS.test.images.positives.txt',
'dataset/PhrasIS.train.headlines.negatives.txt',
'dataset/PhrasIS.train.headlines.positives.txt',
'dataset/PhrasIS.train.images.negatives.txt',
'dataset/PhrasIS.train.images.positives.txt',
]
# For development only
nrows=30
datasets = dict( {name : Utils.readDataset(path, nrows=nrows) for (name,path) in zip(names,paths)})
# Preprocess dataset
preprocess_pipeline = [
Utils.addColumnsLower,
Utils.addColumnsStrip,
Utils.addColumnsTokenized,
Utils.addColumnsNoPunctuations,
Utils.addColumnsPOStags,
Utils.addColumnsLemmatized,
Utils.addColumnsContentWords,
Utils.addColumnsStopWords
]
step=1
for name,dataset in datasets.items():
for func in preprocess_pipeline:
func(dataset)
print("Processing dataset {}/{}".format(step, len(datasets.keys())))
step+=1
# Compute lexical features
lexical_pipeline = [
Lexical_Features.addColumnsJaccardStripTokenized,
Lexical_Features.addColumnsJaccardContentWords,
Lexical_Features.addColumnsJaccardStopwords,
Lexical_Features.addColumnsLength,
Lexical_Features.addColumnsLeftRight,
Lexical_Features.addColumnsRightLeft
]
step=1
for name,dataset in datasets.items():
for func in lexical_pipeline:
func(dataset)
print("Processing lexical features {}/{}".format(step, len(datasets.keys())))
step+=1
# Compute wordnet features
wordnet_pipeline = [
WordNet_Features.addColumnsPathSimilarity,
WordNet_Features.addColumnsLchSimilarityNouns,
WordNet_Features.addColumnsLchSimilarityVerbs,
WordNet_Features.addColumnsJcnSimilarityBrownNouns,
WordNet_Features.addColumnsJcnSimilarityBrownVerbs,
WordNet_Features.addColumnsJcnSimilarityGenesisNouns,
WordNet_Features.addColumnsJcnSimilarityGenesisVerbs,
WordNet_Features.addColumnsWupSimilarity,
WordNet_Features.addColumnsPathSimilarityRoot,
WordNet_Features.addColumnsLchSimilarityNounsRoot,
WordNet_Features.addColumnsLchSimilarityVerbsRoot,
WordNet_Features.addColumnsWupSimilarityRoot,
WordNet_Features.addColumnsChunkMaximum,
WordNet_Features.addColumnsChunk1Specific,
WordNet_Features.addColumnsChunk2Specific,
WordNet_Features.addColumnsDifference,
WordNet_Features.addColumnsMinimumDifference,
WordNet_Features.addColumnsMaximumDifference
]
step=1
for name,dataset in datasets.items():
for func in wordnet_pipeline:
func(dataset)
print("Processing wordnet features {}/{}".format(step, len(datasets.keys())))
step+=1
# Normalization
normalization_pipeline= [
Normalization.miniMaxNormalization
#Normalization.standardNormalization
]
step=1
for name,dataset in datasets.items():
for func in normalization_pipeline:
func(dataset)
print("Normalizing {}/{}".format(step, len(datasets.keys())))
step += 1
# Save files
saveFolder ="dirty"
if not os.path.exists(saveFolder):
os.makedirs(saveFolder+"/bin")
os.makedirs(saveFolder+ "/csv")
for name, df in datasets.items():
Utils.saveDatasetCSV(df, os.path.join("dirty/csv", name + ".csv"))
Utils.saveDatasetPickle(df, os.path.join("dirty/bin" , name + ".pickle"))
| [
"os.path.exists",
"os.makedirs",
"nltk.download",
"src.Preprocess.Utils.readDataset",
"os.path.join",
"pandas.set_option",
"numpy.random.seed"
] | [((116, 142), 'nltk.download', 'nltk.download', (['"""stopwords"""'], {}), "('stopwords')\n", (129, 142), False, 'import nltk\n'), ((143, 165), 'nltk.download', 'nltk.download', (['"""punkt"""'], {}), "('punkt')\n", (156, 165), False, 'import nltk\n'), ((166, 193), 'nltk.download', 'nltk.download', (['"""wordnet_ic"""'], {}), "('wordnet_ic')\n", (179, 193), False, 'import nltk\n'), ((194, 218), 'nltk.download', 'nltk.download', (['"""genesis"""'], {}), "('genesis')\n", (207, 218), False, 'import nltk\n'), ((219, 262), 'nltk.download', 'nltk.download', (['"""averaged_perceptron_tagger"""'], {}), "('averaged_perceptron_tagger')\n", (232, 262), False, 'import nltk\n'), ((263, 287), 'nltk.download', 'nltk.download', (['"""wordnet"""'], {}), "('wordnet')\n", (276, 287), False, 'import nltk\n'), ((485, 504), 'numpy.random.seed', 'np.random.seed', (['(123)'], {}), '(123)\n', (499, 504), True, 'import numpy as np\n'), ((598, 636), 'pandas.set_option', 'pd.set_option', (['"""display.max_rows"""', '(100)'], {}), "('display.max_rows', 100)\n", (611, 636), True, 'import pandas as pd\n'), ((637, 678), 'pandas.set_option', 'pd.set_option', (['"""display.max_columns"""', '(100)'], {}), "('display.max_columns', 100)\n", (650, 678), True, 'import pandas as pd\n'), ((3992, 4018), 'os.path.exists', 'os.path.exists', (['saveFolder'], {}), '(saveFolder)\n', (4006, 4018), False, 'import os\n'), ((4024, 4056), 'os.makedirs', 'os.makedirs', (["(saveFolder + '/bin')"], {}), "(saveFolder + '/bin')\n", (4035, 4056), False, 'import os\n'), ((4059, 4091), 'os.makedirs', 'os.makedirs', (["(saveFolder + '/csv')"], {}), "(saveFolder + '/csv')\n", (4070, 4091), False, 'import os\n'), ((1386, 1422), 'src.Preprocess.Utils.readDataset', 'Utils.readDataset', (['path'], {'nrows': 'nrows'}), '(path, nrows=nrows)\n', (1403, 1422), False, 'from src.Preprocess import Utils\n'), ((4155, 4195), 'os.path.join', 'os.path.join', (['"""dirty/csv"""', "(name + '.csv')"], {}), "('dirty/csv', name + '.csv')\n", (4167, 4195), False, 'import os\n'), ((4229, 4272), 'os.path.join', 'os.path.join', (['"""dirty/bin"""', "(name + '.pickle')"], {}), "('dirty/bin', name + '.pickle')\n", (4241, 4272), False, 'import os\n')] |
import hmac
import hashlib
from typing import Optional
import json
from hdwallet import BIP44HDWallet
from hdwallet.cryptocurrencies import EthereumMainnet
from hdwallet.derivations import BIP44Derivation
from hdwallet.utils import generate_mnemonic
from decouple import config
def generate_address(account_index) -> str:
MNEMONIC = config('MNEMONIC')
# Initialize Ethereum mainnet BIP44HDWallet
bip44_hdwallet: BIP44HDWallet = BIP44HDWallet(cryptocurrency=EthereumMainnet)
# Get Ethereum BIP44HDWallet from mnemonic
bip44_hdwallet.from_mnemonic(
mnemonic=MNEMONIC, language="english"
)
# Clean default BIP44 derivation indexes/paths
bip44_hdwallet.clean_derivation()
# Derivation from Ethereum BIP44 derivation path
bip44_derivation: BIP44Derivation = BIP44Derivation(
cryptocurrency=EthereumMainnet, account=0, change=False, address=account_index
)
# Drive Ethereum BIP44HDWallet
bip44_hdwallet.from_path(path=bip44_derivation)
return bip44_hdwallet.address()
def signature_generator(user_id, reference, amount_in_kobo) -> str:
destination_account_number = config("DESTINATION_ACCOUNT_NUMBER")
destination_bank_code = config("DESTINATION_BANK_CODE")
payload = f"{user_id}:{reference}:{amount_in_kobo}:{destination_account_number}:{destination_bank_code}"
sendcash_signature_token = config("SENDCASH_SIGNATURE_TOKEN")
sendcash_signature_token_in_byte = bytes(sendcash_signature_token, 'UTF-8') # key.encode() would also work in this case
payload_encoded = payload.encode()
h = hmac.new(sendcash_signature_token_in_byte, payload_encoded, hashlib.sha256)
return h.hexdigest()
def compare_hashes(request):
body = request.POST
json_body = json.dumps(body)
sendcash_signature_token = config("SENDCASH_SIGNATURE_TOKEN")
transfer_signature = request.headers.get('X-Transfers-Signature')
sendcash_signature_token_in_byte = bytes(sendcash_signature_token, 'UTF-8')
json_body_encoded = json_body.encode()
h = hmac.new(sendcash_signature_token_in_byte, json_body_encoded, hashlib.sha256)
return transfer_signature == h.hexdigest()
| [
"hmac.new",
"hdwallet.derivations.BIP44Derivation",
"json.dumps",
"decouple.config",
"hdwallet.BIP44HDWallet"
] | [((341, 359), 'decouple.config', 'config', (['"""MNEMONIC"""'], {}), "('MNEMONIC')\n", (347, 359), False, 'from decouple import config\n'), ((445, 490), 'hdwallet.BIP44HDWallet', 'BIP44HDWallet', ([], {'cryptocurrency': 'EthereumMainnet'}), '(cryptocurrency=EthereumMainnet)\n', (458, 490), False, 'from hdwallet import BIP44HDWallet\n'), ((809, 908), 'hdwallet.derivations.BIP44Derivation', 'BIP44Derivation', ([], {'cryptocurrency': 'EthereumMainnet', 'account': '(0)', 'change': '(False)', 'address': 'account_index'}), '(cryptocurrency=EthereumMainnet, account=0, change=False,\n address=account_index)\n', (824, 908), False, 'from hdwallet.derivations import BIP44Derivation\n'), ((1146, 1182), 'decouple.config', 'config', (['"""DESTINATION_ACCOUNT_NUMBER"""'], {}), "('DESTINATION_ACCOUNT_NUMBER')\n", (1152, 1182), False, 'from decouple import config\n'), ((1211, 1242), 'decouple.config', 'config', (['"""DESTINATION_BANK_CODE"""'], {}), "('DESTINATION_BANK_CODE')\n", (1217, 1242), False, 'from decouple import config\n'), ((1384, 1418), 'decouple.config', 'config', (['"""SENDCASH_SIGNATURE_TOKEN"""'], {}), "('SENDCASH_SIGNATURE_TOKEN')\n", (1390, 1418), False, 'from decouple import config\n'), ((1597, 1672), 'hmac.new', 'hmac.new', (['sendcash_signature_token_in_byte', 'payload_encoded', 'hashlib.sha256'], {}), '(sendcash_signature_token_in_byte, payload_encoded, hashlib.sha256)\n', (1605, 1672), False, 'import hmac\n'), ((1770, 1786), 'json.dumps', 'json.dumps', (['body'], {}), '(body)\n', (1780, 1786), False, 'import json\n'), ((1819, 1853), 'decouple.config', 'config', (['"""SENDCASH_SIGNATURE_TOKEN"""'], {}), "('SENDCASH_SIGNATURE_TOKEN')\n", (1825, 1853), False, 'from decouple import config\n'), ((2057, 2134), 'hmac.new', 'hmac.new', (['sendcash_signature_token_in_byte', 'json_body_encoded', 'hashlib.sha256'], {}), '(sendcash_signature_token_in_byte, json_body_encoded, hashlib.sha256)\n', (2065, 2134), False, 'import hmac\n')] |
import numpy as np
from prml.nn.function import Function
class Product(Function):
def __init__(self, axis=None, keepdims=False):
if isinstance(axis, int):
axis = (axis,)
elif isinstance(axis, tuple):
axis = tuple(sorted(axis))
self.axis = axis
self.keepdims = keepdims
def _forward(self, x):
self.output = np.prod(x, axis=self.axis, keepdims=True)
if not self.keepdims:
return np.squeeze(self.output)
else:
return self.output
def backward(self, delta, x):
if not self.keepdims and self.axis is not None:
for ax in self.axis:
delta = np.expand_dims(delta, ax)
dx = delta * self.output / x
return dx
def prod(x, axis=None, keepdims=False):
"""
product of all element in the array
Parameters
----------
x : tensor_like
input array
axis : int, tuple of ints
axis or axes along which a product is performed
keepdims : bool
keep dimensionality or not
Returns
-------
product : tensor_like
product of all element
"""
return Product(axis=axis, keepdims=keepdims).forward(x)
| [
"numpy.prod",
"numpy.expand_dims",
"numpy.squeeze"
] | [((382, 423), 'numpy.prod', 'np.prod', (['x'], {'axis': 'self.axis', 'keepdims': '(True)'}), '(x, axis=self.axis, keepdims=True)\n', (389, 423), True, 'import numpy as np\n'), ((473, 496), 'numpy.squeeze', 'np.squeeze', (['self.output'], {}), '(self.output)\n', (483, 496), True, 'import numpy as np\n'), ((690, 715), 'numpy.expand_dims', 'np.expand_dims', (['delta', 'ax'], {}), '(delta, ax)\n', (704, 715), True, 'import numpy as np\n')] |
import factory
import pytest
from django.conf import settings
from django.db.utils import IntegrityError
from datahub.company.models import OneListTier
from datahub.company.test.factories import (
AdviserFactory,
CompanyExportCountryFactory,
CompanyExportCountryHistoryFactory,
CompanyFactory,
ContactFactory,
OneListCoreTeamMemberFactory,
)
from datahub.core.test_utils import random_obj_for_model
from datahub.metadata.models import Country
# mark the whole module for db use
pytestmark = pytest.mark.django_db
class TestCompany:
"""Tests for the company model."""
def test_get_absolute_url(self):
"""Test that Company.get_absolute_url() returns the correct URL."""
company = CompanyFactory.build()
assert company.get_absolute_url() == (
f'{settings.DATAHUB_FRONTEND_URL_PREFIXES["company"]}/{company.pk}'
)
@pytest.mark.parametrize(
'build_global_headquarters',
(
lambda: CompanyFactory.build(),
lambda: None,
),
ids=('as_subsidiary', 'as_non_subsidiary'),
)
def test_get_group_global_headquarters(self, build_global_headquarters):
"""
Test that `get_group_global_headquarters` returns `self` if the company has
no `global_headquarters` or the `global_headquarters` otherwise.
"""
company = CompanyFactory.build(
global_headquarters=build_global_headquarters(),
)
expected_group_global_headquarters = company.global_headquarters or company
assert company.get_group_global_headquarters() == expected_group_global_headquarters
@pytest.mark.parametrize(
'build_company',
(
# subsidiary with Global Headquarters on the One List
lambda one_list_tier: CompanyFactory(
one_list_tier=None,
global_headquarters=CompanyFactory(one_list_tier=one_list_tier),
),
# subsidiary with Global Headquarters not on the One List
lambda one_list_tier: CompanyFactory(
one_list_tier=None,
global_headquarters=CompanyFactory(one_list_tier=None),
),
# single company on the One List
lambda one_list_tier: CompanyFactory(
one_list_tier=one_list_tier,
global_headquarters=None,
),
# single company not on the One List
lambda one_list_tier: CompanyFactory(
one_list_tier=None,
global_headquarters=None,
),
),
ids=(
'as_subsidiary_of_one_list_company',
'as_subsidiary_of_non_one_list_company',
'as_one_list_company',
'as_non_one_list_company',
),
)
def test_get_one_list_group_tier(self, build_company):
"""
Test that `get_one_list_group_tier` returns the One List Tier of `self`
if company has no `global_headquarters` or the one of its `global_headquarters`
otherwise.
"""
one_list_tier = OneListTier.objects.first()
company = build_company(one_list_tier)
group_global_headquarters = company.global_headquarters or company
if not group_global_headquarters.one_list_tier:
assert not company.get_one_list_group_tier()
else:
assert company.get_one_list_group_tier() == one_list_tier
@pytest.mark.parametrize(
'build_company',
(
# as subsidiary
lambda gam: CompanyFactory(
global_headquarters=CompanyFactory(one_list_account_owner=gam),
),
# as single company
lambda gam: CompanyFactory(
global_headquarters=None,
one_list_account_owner=gam,
),
),
ids=('as_subsidiary', 'as_non_subsidiary'),
)
@pytest.mark.parametrize(
'with_global_account_manager',
(True, False),
ids=lambda val: f'{"With" if val else "Without"} global account manager',
)
def test_get_one_list_group_core_team(
self,
build_company,
with_global_account_manager,
):
"""
Test that `get_one_list_group_core_team` returns the Core Team of `self` if the company
has no `global_headquarters` or the one of its `global_headquarters` otherwise.
"""
team_member_advisers = AdviserFactory.create_batch(
3,
first_name=factory.Iterator(
('Adam', 'Barbara', 'Chris'),
),
)
global_account_manager = team_member_advisers[0] if with_global_account_manager else None
company = build_company(global_account_manager)
group_global_headquarters = company.global_headquarters or company
OneListCoreTeamMemberFactory.create_batch(
len(team_member_advisers),
company=group_global_headquarters,
adviser=factory.Iterator(team_member_advisers),
)
core_team = company.get_one_list_group_core_team()
assert core_team == [
{
'adviser': adviser,
'is_global_account_manager': adviser is global_account_manager,
}
for adviser in team_member_advisers
]
@pytest.mark.parametrize(
'build_company',
(
# subsidiary with Global Headquarters on the One List
lambda one_list_tier, gam: CompanyFactory(
one_list_tier=None,
global_headquarters=CompanyFactory(
one_list_tier=one_list_tier,
one_list_account_owner=gam,
),
),
# subsidiary with Global Headquarters not on the One List
lambda one_list_tier, gam: CompanyFactory(
one_list_tier=None,
global_headquarters=CompanyFactory(
one_list_tier=None,
one_list_account_owner=None,
),
),
# single company on the One List
lambda one_list_tier, gam: CompanyFactory(
one_list_tier=one_list_tier,
one_list_account_owner=gam,
global_headquarters=None,
),
# single company not on the One List
lambda one_list_tier, gam: CompanyFactory(
one_list_tier=None,
global_headquarters=None,
one_list_account_owner=None,
),
),
ids=(
'as_subsidiary_of_one_list_company',
'as_subsidiary_of_non_one_list_company',
'as_one_list_company',
'as_non_one_list_company',
),
)
def test_get_one_list_group_global_account_manager(self, build_company):
"""
Test that `get_one_list_group_global_account_manager` returns
the One List Global Account Manager of `self` if the company has no
`global_headquarters` or the one of its `global_headquarters` otherwise.
"""
global_account_manager = AdviserFactory()
one_list_tier = OneListTier.objects.first()
company = build_company(one_list_tier, global_account_manager)
group_global_headquarters = company.global_headquarters or company
actual_global_account_manager = company.get_one_list_group_global_account_manager()
assert group_global_headquarters.one_list_account_owner == actual_global_account_manager
class TestContact:
"""Tests for the contact model."""
def test_get_absolute_url(self):
"""Test that Contact.get_absolute_url() returns the correct URL."""
contact = ContactFactory.build()
assert contact.get_absolute_url() == (
f'{settings.DATAHUB_FRONTEND_URL_PREFIXES["contact"]}/{contact.pk}'
)
@pytest.mark.parametrize(
'first_name,last_name,company_factory,expected_output',
(
('First', 'Last', lambda: CompanyFactory(name='Company'), 'First Last (Company)'),
('', 'Last', lambda: CompanyFactory(name='Company'), 'Last (Company)'),
('First', '', lambda: CompanyFactory(name='Company'), 'First (Company)'),
('First', 'Last', lambda: None, 'First Last'),
('First', 'Last', lambda: CompanyFactory(name=''), 'First Last'),
('', '', lambda: CompanyFactory(name='Company'), '(no name) (Company)'),
('', '', lambda: None, '(no name)'),
),
)
def test_str(self, first_name, last_name, company_factory, expected_output):
"""Test the human-friendly string representation of a Contact object."""
contact = ContactFactory.build(
first_name=first_name,
last_name=last_name,
company=company_factory(),
)
assert str(contact) == expected_output
class TestCompanyExportCountry:
"""Tests Company export country model"""
def test_str(self):
"""Test the human friendly string representation of the object"""
export_country = CompanyExportCountryFactory()
status = f'{export_country.company} {export_country.country} {export_country.status}'
assert str(export_country) == status
def test_unique_constraint(self):
"""
Test unique constraint
a company and country combination can't be added more than once
"""
company_1 = CompanyFactory()
country = random_obj_for_model(Country)
CompanyExportCountryFactory(
company=company_1,
country=country,
)
with pytest.raises(IntegrityError):
CompanyExportCountryFactory(
company=company_1,
country=country,
)
class TestCompanyExportCountryHistory:
"""Tests Company export country history model"""
def test_str(self):
"""Test the human friendly string representation of the object"""
history = CompanyExportCountryHistoryFactory()
status = f'{history.company} {history.country} {history.status}'
assert str(history) == status
| [
"datahub.company.test.factories.CompanyExportCountryFactory",
"datahub.company.test.factories.CompanyFactory",
"datahub.company.test.factories.AdviserFactory",
"factory.Iterator",
"datahub.company.test.factories.CompanyFactory.build",
"datahub.company.models.OneListTier.objects.first",
"datahub.company.... | [((3939, 4087), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""with_global_account_manager"""', '(True, False)'], {'ids': '(lambda val: f"{\'With\' if val else \'Without\'} global account manager")'}), '(\'with_global_account_manager\', (True, False), ids=\n lambda val: f"{\'With\' if val else \'Without\'} global account manager")\n', (3962, 4087), False, 'import pytest\n'), ((732, 754), 'datahub.company.test.factories.CompanyFactory.build', 'CompanyFactory.build', ([], {}), '()\n', (752, 754), False, 'from datahub.company.test.factories import AdviserFactory, CompanyExportCountryFactory, CompanyExportCountryHistoryFactory, CompanyFactory, ContactFactory, OneListCoreTeamMemberFactory\n'), ((3114, 3141), 'datahub.company.models.OneListTier.objects.first', 'OneListTier.objects.first', ([], {}), '()\n', (3139, 3141), False, 'from datahub.company.models import OneListTier\n'), ((7172, 7188), 'datahub.company.test.factories.AdviserFactory', 'AdviserFactory', ([], {}), '()\n', (7186, 7188), False, 'from datahub.company.test.factories import AdviserFactory, CompanyExportCountryFactory, CompanyExportCountryHistoryFactory, CompanyFactory, ContactFactory, OneListCoreTeamMemberFactory\n'), ((7213, 7240), 'datahub.company.models.OneListTier.objects.first', 'OneListTier.objects.first', ([], {}), '()\n', (7238, 7240), False, 'from datahub.company.models import OneListTier\n'), ((7770, 7792), 'datahub.company.test.factories.ContactFactory.build', 'ContactFactory.build', ([], {}), '()\n', (7790, 7792), False, 'from datahub.company.test.factories import AdviserFactory, CompanyExportCountryFactory, CompanyExportCountryHistoryFactory, CompanyFactory, ContactFactory, OneListCoreTeamMemberFactory\n'), ((9157, 9186), 'datahub.company.test.factories.CompanyExportCountryFactory', 'CompanyExportCountryFactory', ([], {}), '()\n', (9184, 9186), False, 'from datahub.company.test.factories import AdviserFactory, CompanyExportCountryFactory, CompanyExportCountryHistoryFactory, CompanyFactory, ContactFactory, OneListCoreTeamMemberFactory\n'), ((9512, 9528), 'datahub.company.test.factories.CompanyFactory', 'CompanyFactory', ([], {}), '()\n', (9526, 9528), False, 'from datahub.company.test.factories import AdviserFactory, CompanyExportCountryFactory, CompanyExportCountryHistoryFactory, CompanyFactory, ContactFactory, OneListCoreTeamMemberFactory\n'), ((9547, 9576), 'datahub.core.test_utils.random_obj_for_model', 'random_obj_for_model', (['Country'], {}), '(Country)\n', (9567, 9576), False, 'from datahub.core.test_utils import random_obj_for_model\n'), ((9586, 9649), 'datahub.company.test.factories.CompanyExportCountryFactory', 'CompanyExportCountryFactory', ([], {'company': 'company_1', 'country': 'country'}), '(company=company_1, country=country)\n', (9613, 9649), False, 'from datahub.company.test.factories import AdviserFactory, CompanyExportCountryFactory, CompanyExportCountryHistoryFactory, CompanyFactory, ContactFactory, OneListCoreTeamMemberFactory\n'), ((10064, 10100), 'datahub.company.test.factories.CompanyExportCountryHistoryFactory', 'CompanyExportCountryHistoryFactory', ([], {}), '()\n', (10098, 10100), False, 'from datahub.company.test.factories import AdviserFactory, CompanyExportCountryFactory, CompanyExportCountryHistoryFactory, CompanyFactory, ContactFactory, OneListCoreTeamMemberFactory\n'), ((9699, 9728), 'pytest.raises', 'pytest.raises', (['IntegrityError'], {}), '(IntegrityError)\n', (9712, 9728), False, 'import pytest\n'), ((9742, 9805), 'datahub.company.test.factories.CompanyExportCountryFactory', 'CompanyExportCountryFactory', ([], {'company': 'company_1', 'country': 'country'}), '(company=company_1, country=country)\n', (9769, 9805), False, 'from datahub.company.test.factories import AdviserFactory, CompanyExportCountryFactory, CompanyExportCountryHistoryFactory, CompanyFactory, ContactFactory, OneListCoreTeamMemberFactory\n'), ((990, 1012), 'datahub.company.test.factories.CompanyFactory.build', 'CompanyFactory.build', ([], {}), '()\n', (1010, 1012), False, 'from datahub.company.test.factories import AdviserFactory, CompanyExportCountryFactory, CompanyExportCountryHistoryFactory, CompanyFactory, ContactFactory, OneListCoreTeamMemberFactory\n'), ((2292, 2361), 'datahub.company.test.factories.CompanyFactory', 'CompanyFactory', ([], {'one_list_tier': 'one_list_tier', 'global_headquarters': 'None'}), '(one_list_tier=one_list_tier, global_headquarters=None)\n', (2306, 2361), False, 'from datahub.company.test.factories import AdviserFactory, CompanyExportCountryFactory, CompanyExportCountryHistoryFactory, CompanyFactory, ContactFactory, OneListCoreTeamMemberFactory\n'), ((2493, 2553), 'datahub.company.test.factories.CompanyFactory', 'CompanyFactory', ([], {'one_list_tier': 'None', 'global_headquarters': 'None'}), '(one_list_tier=None, global_headquarters=None)\n', (2507, 2553), False, 'from datahub.company.test.factories import AdviserFactory, CompanyExportCountryFactory, CompanyExportCountryHistoryFactory, CompanyFactory, ContactFactory, OneListCoreTeamMemberFactory\n'), ((4544, 4590), 'factory.Iterator', 'factory.Iterator', (["('Adam', 'Barbara', 'Chris')"], {}), "(('Adam', 'Barbara', 'Chris'))\n", (4560, 4590), False, 'import factory\n'), ((5021, 5059), 'factory.Iterator', 'factory.Iterator', (['team_member_advisers'], {}), '(team_member_advisers)\n', (5037, 5059), False, 'import factory\n'), ((3748, 3816), 'datahub.company.test.factories.CompanyFactory', 'CompanyFactory', ([], {'global_headquarters': 'None', 'one_list_account_owner': 'gam'}), '(global_headquarters=None, one_list_account_owner=gam)\n', (3762, 3816), False, 'from datahub.company.test.factories import AdviserFactory, CompanyExportCountryFactory, CompanyExportCountryHistoryFactory, CompanyFactory, ContactFactory, OneListCoreTeamMemberFactory\n'), ((6189, 6290), 'datahub.company.test.factories.CompanyFactory', 'CompanyFactory', ([], {'one_list_tier': 'one_list_tier', 'one_list_account_owner': 'gam', 'global_headquarters': 'None'}), '(one_list_tier=one_list_tier, one_list_account_owner=gam,\n global_headquarters=None)\n', (6203, 6290), False, 'from datahub.company.test.factories import AdviserFactory, CompanyExportCountryFactory, CompanyExportCountryHistoryFactory, CompanyFactory, ContactFactory, OneListCoreTeamMemberFactory\n'), ((6439, 6532), 'datahub.company.test.factories.CompanyFactory', 'CompanyFactory', ([], {'one_list_tier': 'None', 'global_headquarters': 'None', 'one_list_account_owner': 'None'}), '(one_list_tier=None, global_headquarters=None,\n one_list_account_owner=None)\n', (6453, 6532), False, 'from datahub.company.test.factories import AdviserFactory, CompanyExportCountryFactory, CompanyExportCountryHistoryFactory, CompanyFactory, ContactFactory, OneListCoreTeamMemberFactory\n'), ((8073, 8103), 'datahub.company.test.factories.CompanyFactory', 'CompanyFactory', ([], {'name': '"""Company"""'}), "(name='Company')\n", (8087, 8103), False, 'from datahub.company.test.factories import AdviserFactory, CompanyExportCountryFactory, CompanyExportCountryHistoryFactory, CompanyFactory, ContactFactory, OneListCoreTeamMemberFactory\n'), ((8163, 8193), 'datahub.company.test.factories.CompanyFactory', 'CompanyFactory', ([], {'name': '"""Company"""'}), "(name='Company')\n", (8177, 8193), False, 'from datahub.company.test.factories import AdviserFactory, CompanyExportCountryFactory, CompanyExportCountryHistoryFactory, CompanyFactory, ContactFactory, OneListCoreTeamMemberFactory\n'), ((8248, 8278), 'datahub.company.test.factories.CompanyFactory', 'CompanyFactory', ([], {'name': '"""Company"""'}), "(name='Company')\n", (8262, 8278), False, 'from datahub.company.test.factories import AdviserFactory, CompanyExportCountryFactory, CompanyExportCountryHistoryFactory, CompanyFactory, ContactFactory, OneListCoreTeamMemberFactory\n'), ((8397, 8420), 'datahub.company.test.factories.CompanyFactory', 'CompanyFactory', ([], {'name': '""""""'}), "(name='')\n", (8411, 8420), False, 'from datahub.company.test.factories import AdviserFactory, CompanyExportCountryFactory, CompanyExportCountryHistoryFactory, CompanyFactory, ContactFactory, OneListCoreTeamMemberFactory\n'), ((8466, 8496), 'datahub.company.test.factories.CompanyFactory', 'CompanyFactory', ([], {'name': '"""Company"""'}), "(name='Company')\n", (8480, 8496), False, 'from datahub.company.test.factories import AdviserFactory, CompanyExportCountryFactory, CompanyExportCountryHistoryFactory, CompanyFactory, ContactFactory, OneListCoreTeamMemberFactory\n'), ((1910, 1953), 'datahub.company.test.factories.CompanyFactory', 'CompanyFactory', ([], {'one_list_tier': 'one_list_tier'}), '(one_list_tier=one_list_tier)\n', (1924, 1953), False, 'from datahub.company.test.factories import AdviserFactory, CompanyExportCountryFactory, CompanyExportCountryHistoryFactory, CompanyFactory, ContactFactory, OneListCoreTeamMemberFactory\n'), ((2162, 2196), 'datahub.company.test.factories.CompanyFactory', 'CompanyFactory', ([], {'one_list_tier': 'None'}), '(one_list_tier=None)\n', (2176, 2196), False, 'from datahub.company.test.factories import AdviserFactory, CompanyExportCountryFactory, CompanyExportCountryHistoryFactory, CompanyFactory, ContactFactory, OneListCoreTeamMemberFactory\n'), ((3633, 3675), 'datahub.company.test.factories.CompanyFactory', 'CompanyFactory', ([], {'one_list_account_owner': 'gam'}), '(one_list_account_owner=gam)\n', (3647, 3675), False, 'from datahub.company.test.factories import AdviserFactory, CompanyExportCountryFactory, CompanyExportCountryHistoryFactory, CompanyFactory, ContactFactory, OneListCoreTeamMemberFactory\n'), ((5622, 5693), 'datahub.company.test.factories.CompanyFactory', 'CompanyFactory', ([], {'one_list_tier': 'one_list_tier', 'one_list_account_owner': 'gam'}), '(one_list_tier=one_list_tier, one_list_account_owner=gam)\n', (5636, 5693), False, 'from datahub.company.test.factories import AdviserFactory, CompanyExportCountryFactory, CompanyExportCountryHistoryFactory, CompanyFactory, ContactFactory, OneListCoreTeamMemberFactory\n'), ((5966, 6029), 'datahub.company.test.factories.CompanyFactory', 'CompanyFactory', ([], {'one_list_tier': 'None', 'one_list_account_owner': 'None'}), '(one_list_tier=None, one_list_account_owner=None)\n', (5980, 6029), False, 'from datahub.company.test.factories import AdviserFactory, CompanyExportCountryFactory, CompanyExportCountryHistoryFactory, CompanyFactory, ContactFactory, OneListCoreTeamMemberFactory\n')] |
# Copyright 2019 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from typing import cast
from pants.core.util_rules.external_tool import (
DownloadedExternalTool,
ExternalTool,
ExternalToolRequest,
)
from pants.engine.console import Console
from pants.engine.fs import (
CreateDigest,
Digest,
DigestContents,
FileContent,
MergeDigests,
SourcesSnapshot,
)
from pants.engine.goal import Goal, GoalSubsystem
from pants.engine.platform import Platform
from pants.engine.process import Process, ProcessResult
from pants.engine.rules import Get, collect_rules, goal_rule
from pants.util.logging import LogLevel
from pants.util.strutil import pluralize
class ClocBinary(ExternalTool):
"""The cloc lines-of-code counter (https://github.com/AlDanial/cloc)."""
options_scope = "cloc-binary"
name = "cloc"
default_version = "1.80"
default_known_versions = [
"1.80|darwin|2b23012b1c3c53bd6b9dd43cd6aa75715eed4feb2cb6db56ac3fbbd2dffeac9d|546279",
"1.80|linux |2b23012b1c3c53bd6b9dd43cd6aa75715eed4feb2cb6db56ac3fbbd2dffeac9d|546279",
]
def generate_url(self, _: Platform) -> str:
return (
f"https://github.com/AlDanial/cloc/releases/download/{self.version}/"
f"cloc-{self.version}.pl"
)
def generate_exe(self, _: Platform) -> str:
return f"./cloc-{self.version}.pl"
class CountLinesOfCodeSubsystem(GoalSubsystem):
"""Count lines of code."""
name = "cloc"
@classmethod
def register_options(cls, register) -> None:
super().register_options(register)
register(
"--ignored",
type=bool,
default=False,
help="Show information about files ignored by cloc.",
)
@property
def ignored(self) -> bool:
return cast(bool, self.options.ignored)
class CountLinesOfCode(Goal):
subsystem_cls = CountLinesOfCodeSubsystem
@goal_rule
async def run_cloc(
console: Console,
cloc_subsystem: CountLinesOfCodeSubsystem,
cloc_binary: ClocBinary,
sources_snapshot: SourcesSnapshot,
) -> CountLinesOfCode:
"""Runs the cloc Perl script."""
if not sources_snapshot.snapshot.files:
return CountLinesOfCode(exit_code=0)
input_files_filename = "input_files.txt"
input_file_digest = await Get(
Digest,
CreateDigest(
[FileContent(input_files_filename, "\n".join(sources_snapshot.snapshot.files).encode())]
),
)
downloaded_cloc_binary = await Get(
DownloadedExternalTool, ExternalToolRequest, cloc_binary.get_request(Platform.current)
)
digest = await Get(
Digest,
MergeDigests(
(input_file_digest, downloaded_cloc_binary.digest, sources_snapshot.snapshot.digest)
),
)
report_filename = "report.txt"
ignore_filename = "ignored.txt"
cmd = (
"/usr/bin/perl",
downloaded_cloc_binary.exe,
"--skip-uniqueness", # Skip the file uniqueness check.
f"--ignored={ignore_filename}", # Write the names and reasons of ignored files to this file.
f"--report-file={report_filename}", # Write the output to this file rather than stdout.
f"--list-file={input_files_filename}", # Read an exhaustive list of files to process from this file.
)
req = Process(
argv=cmd,
input_digest=digest,
output_files=(report_filename, ignore_filename),
description=(
f"Count lines of code for {pluralize(len(sources_snapshot.snapshot.files), 'file')}"
),
level=LogLevel.DEBUG,
)
exec_result = await Get(ProcessResult, Process, req)
report_digest_contents = await Get(DigestContents, Digest, exec_result.output_digest)
reports = {
file_content.path: file_content.content.decode() for file_content in report_digest_contents
}
for line in reports[report_filename].splitlines():
console.print_stdout(line)
if cloc_subsystem.ignored:
console.print_stderr("\nIgnored the following files:")
for line in reports[ignore_filename].splitlines():
console.print_stderr(line)
return CountLinesOfCode(exit_code=0)
def rules():
return collect_rules()
| [
"typing.cast",
"pants.engine.rules.Get",
"pants.engine.fs.MergeDigests",
"pants.engine.rules.collect_rules"
] | [((4318, 4333), 'pants.engine.rules.collect_rules', 'collect_rules', ([], {}), '()\n', (4331, 4333), False, 'from pants.engine.rules import Get, collect_rules, goal_rule\n'), ((1898, 1930), 'typing.cast', 'cast', (['bool', 'self.options.ignored'], {}), '(bool, self.options.ignored)\n', (1902, 1930), False, 'from typing import cast\n'), ((3720, 3752), 'pants.engine.rules.Get', 'Get', (['ProcessResult', 'Process', 'req'], {}), '(ProcessResult, Process, req)\n', (3723, 3752), False, 'from pants.engine.rules import Get, collect_rules, goal_rule\n'), ((3789, 3843), 'pants.engine.rules.Get', 'Get', (['DigestContents', 'Digest', 'exec_result.output_digest'], {}), '(DigestContents, Digest, exec_result.output_digest)\n', (3792, 3843), False, 'from pants.engine.rules import Get, collect_rules, goal_rule\n'), ((2754, 2856), 'pants.engine.fs.MergeDigests', 'MergeDigests', (['(input_file_digest, downloaded_cloc_binary.digest, sources_snapshot.\n snapshot.digest)'], {}), '((input_file_digest, downloaded_cloc_binary.digest,\n sources_snapshot.snapshot.digest))\n', (2766, 2856), False, 'from pants.engine.fs import CreateDigest, Digest, DigestContents, FileContent, MergeDigests, SourcesSnapshot\n')] |
"""
Check that we have a valid class to work upon in our live tile notifications
"""
from django.core.exceptions import ImproperlyConfigured
from mezzanine.utils.importing import import_dotted_path
from mezzanine.conf import settings
model_class_path, fields = settings.WINDOWS_TILE_MODEL
try:
import_dotted_path(model_class_path)
except ImportError:
raise ImproperlyConfigured("The WINDOWS_TILE_MODEL setting contains %s modle which can not be imported" %model_class_path)
| [
"django.core.exceptions.ImproperlyConfigured",
"mezzanine.utils.importing.import_dotted_path"
] | [((297, 333), 'mezzanine.utils.importing.import_dotted_path', 'import_dotted_path', (['model_class_path'], {}), '(model_class_path)\n', (315, 333), False, 'from mezzanine.utils.importing import import_dotted_path\n'), ((361, 488), 'django.core.exceptions.ImproperlyConfigured', 'ImproperlyConfigured', (["('The WINDOWS_TILE_MODEL setting contains %s modle which can not be imported' %\n model_class_path)"], {}), "(\n 'The WINDOWS_TILE_MODEL setting contains %s modle which can not be imported'\n % model_class_path)\n", (381, 488), False, 'from django.core.exceptions import ImproperlyConfigured\n')] |
import time
from datetime import datetime, timedelta
from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort
from blog import constants, db
from blog.models import User, Category, Blogs
from blog.utils.commons import login_required
# from blog.utils.image_storage import storage
from blog.utils.response_code import RET
from . import admin_blue
@admin_blue.route('/index')
@login_required
def index():
"""后台管理首页"""
user = g.user
return render_template('admin/index.html', user=user.to_dict())
@admin_blue.route('/login', methods=['GET', 'POST'])
def login():
"""
后台管理员登录
1、如果为get请求,使用session获取登录信息,user_id,is_admin,
2、判断用户如果用户id存在并是管理员,重定向到后台管理页面
3、获取参数,user_name,password
4、校验参数完整性
5、查询数据库,确认用户存在,is_admin为true,校验密码
6、缓存用户信息,user_id,mobile,nick_name,is_admin
7、跳转到后台管理页面
:return:
"""
if request.method == 'GET':
user_id = session.get('user_id', None)
is_admin = session.get('is_admin', False)
if user_id and is_admin:
return redirect(url_for('admin.index'))
return render_template('admin/login.html')
user_name = request.form.get('username')
password = request.form.get('password')
if not all([user_name, password]):
return render_template('admin/login.html', errmsg='参数不完整')
try:
user = User.query.filter(User.mobile == user_name, User.is_admin == True).first()
except Exception as e:
current_app.logger.error(e)
return render_template('admin/login.html', errmsg='数据库查询错误')
if user is None or not user.check_password(password):
return render_template('admin/login.html', errmsg='用户名或密码错误')
session['user_id'] = user.id
session['mobile'] = user.mobile
session['nick_name'] = user.nick_name
# 必须要缓存is_admin字段,用来确认用户是管理员还是普通用户
session['is_admin'] = user.is_admin
return redirect(url_for('admin.index'))
@admin_blue.route('/user_count')
def user_count():
"""
用户统计:非管理员的人数
1、总人数
2、月新增人数(新注册)
3、日新增人数(新注册)
:return:
"""
# 总人数
total_count = 0
try:
total_count = User.query.filter(User.is_admin == False).count()
except Exception as e:
current_app.logger.error(e)
return jsonify(errno=RET.DBERR, errmsg='查询总人数失败')
# 月人数:当月1号到当前日期的注册人数
t = time.localtime()
# tm_year=2018, tm_mon=10, tm_mday=12
# 定义每月的开始日期的字符串:2018-01-01;2018-10-01
mon_begin_date_str = '%d-%02d-01' % (t.tm_year, t.tm_mon)
# 把日期字符串转成日期对象
mon_begin_date = datetime.strptime(mon_begin_date_str, '%Y-%m-%d')
# 比较日期
mon_count = 0
try:
mon_count = User.query.filter(User.is_admin == False, User.create_time > mon_begin_date).count()
except Exception as e:
current_app.logger.error(e)
return jsonify(errno=RET.DBERR, errmsg='查询月人数失败')
# 日新增人数
day_count = 0
# 每天的开始日期字符串
day_begin_date_str = '%d-%02d-%02d' % (t.tm_year, t.tm_mon, t.tm_mday)
# 把日期字符串转成日期对象
day_begin_date = datetime.strptime(day_begin_date_str, '%Y-%m-%d')
# 比较日期
try:
day_count = User.query.filter(User.is_admin == False, User.create_time > day_begin_date).count()
except Exception as e:
current_app.logger.error(e)
return jsonify(errno=RET.DBERR, errmsg='查询日人数失败')
# 统计用户活跃度、活跃时间
active_count = []
active_time = []
# datetime.now() - timedelta(days=)
# 获取当前日期
now_date_str = '%d-%02d-%02d' % (t.tm_year, t.tm_mon, t.tm_mday)
# 格式化日期对象
now_date = datetime.strptime(now_date_str, '%Y-%m-%d')
# 循环往前推31天,获取每天的开始时间和结束时间
for d in range(0, 31):
begin_date = now_date - timedelta(days=d)
end_date = now_date - timedelta(days=(d - 1))
# 比较日期
try:
count = User.query.filter(User.is_admin == False, User.last_login >= begin_date,
User.last_login < end_date).count()
except Exception as e:
current_app.logger.error(e)
return jsonify(errno=RET.DBERR, errmsg='查询活跃人数失败')
# 把查询结果存入列表
active_count.append(count)
# 把日期对象转成日期字符串
begin_date_str = datetime.strftime(begin_date, '%Y-%m-%d')
# 把日期存入列表
active_time.append(begin_date_str)
# 列表反转
active_time.reverse()
active_count.reverse()
data = {
'total_count': total_count,
'mon_count': mon_count,
'day_count': day_count,
'active_count': active_count,
'active_time': active_time
}
return render_template('admin/user_count.html', data=data)
@admin_blue.route('/user_list')
def user_list():
"""
用户列表
1、获取参数,页数page,默认1
2、校验参数,int(page)
3、查询数据库,为管理员,分页
4、遍历查询结果,转成字典数据
5、返回模板admin/user_list.html,users,total_page,current_page
:return:
"""
page = request.args.get('p', '1')
try:
page = int(page)
except Exception as e:
current_app.logger.error(e)
users = []
follows = []
current_page = 1
total_page = 1
try:
paginate = User.query.filter(User.is_admin == False).paginate(page, constants.USER_FOLLOWED_MAX_COUNT, False)
current_page = paginate.page
total_page = paginate.pages
users = paginate.items
except Exception as e:
current_app.logger.error(e)
return jsonify(errno=RET.DBERR, errmsg='查询数据错误')
# 定义容器遍历查询结果
user_dict_list = []
for user in users:
user_dict_list.append(user.to_admin_dict())
data = {
'users': user_dict_list,
'current_page': current_page,
'total_page': total_page
}
return render_template('admin/user_list.html', data=data)
@admin_blue.route('/blogs_review')
def blogs_review():
"""
博客审核列表
1、获取参数,页数p,默认1,关键字参数keywords,默认None
2、校验参数,int(page)
3、定义过滤条件,filter[blogs.status!=0],如果keywords存在,添加到过滤条件中
4、查询博客数据库,默认按照博客的发布时间,分页
5、遍历查询结果
6、返回模板admin/blogs_review.html,total_page,current_page,blogs_list
:return:
"""
page = request.args.get("p", 1)
keywords = request.args.get("keywords", None)
try:
page = int(page)
except Exception as e:
current_app.logger.error(e)
page = 1
blogs_list = []
current_page = 1
total_page = 1
# filters = [Blogs.status != 0]
filters = []
# 如果关键字存在,那么就添加关键字搜索
if keywords:
filters.append(Blogs.title.contains(keywords))
try:
paginate = Blogs.query.filter(*filters) \
.order_by(Blogs.create_time.desc()) \
.paginate(page, constants.ADMIN_BLOGS_PAGE_MAX_COUNT, False)
blogs_list = paginate.items
current_page = paginate.page
total_page = paginate.pages
except Exception as e:
current_app.logger.error(e)
blogs_dict_list = []
for blogs in blogs_list:
blogs_dict_list.append(blogs.to_review_dict())
data = {"total_page": total_page, "current_page": current_page, "blogs_list": blogs_dict_list}
return render_template('admin/blogs_review.html', data=data)
@admin_blue.route('/blogs_review_detail/<int:blogs_id>')
def blogs_review_detail(blogs_id):
"""
博客详情
1、根据blogs_id查询数据库
2、判断查询结果
3、返回模板,blogs:blogs.to_dict()
:param blogs_id:
:return:
"""
blogs = None
try:
blogs = Blogs.query.get(blogs_id)
except Exception as e:
current_app.logger.error(e)
if not blogs:
return render_template('admin/blogs_review_detail.html', data={'errmsg': '未查到数据'})
data = {"blogs": blogs.to_dict()}
return render_template('admin/blogs_review_detail.html', data=data)
@admin_blue.route('/blogs_review_action', methods=['POST'])
def blogs_review_action():
"""
博客审核
1、获取参数,blogs_id,action
2、校验参数完整
3、校验参数action是否为accept,reject
4、查询博客数据,校验查询结果
5、判断action,如果接受,blogs_status = 0
6、否则获取拒绝原因,reason,
blogs_status = -1
blogs_reason = reason
7、返回结果
:return:
"""
blogs_id = request.json.get('blogs_id')
action = request.json.get('action')
if not all([blogs_id, action]):
return jsonify(errno=RET.PARAMERR, errmsg='参数缺失')
if action not in ("accept", "reject"):
return jsonify(errno=RET.PARAMERR, errmsg="参数类型错误")
# 查询到指定的博客数据
try:
blogs = Blogs.query.get(blogs_id)
except Exception as e:
current_app.logger.error(e)
return jsonify(errno=RET.DBERR, errmsg="数据查询失败")
if not blogs:
return jsonify(errno=RET.NODATA, errmsg="未查询到数据")
if action == "accept":
# 代表接受
blogs.status = 0
else:
# 代表拒绝
reason = request.json.get("reason")
if not reason:
return jsonify(errno=RET.PARAMERR, errmsg="请输入拒绝原因")
blogs.status = -1
blogs.reason = reason
try:
db.session.commit()
except Exception as e:
current_app.logger.error(e)
db.session.rollback()
return jsonify(errno=RET.DBERR, errmsg='保存数据失败')
return jsonify(errno=RET.OK, errmsg="OK")
@admin_blue.route('/blogs_edit')
def blogs_edit():
"""
博客板式编辑
1、获取参数,页数p,默认1,关键字参数keywords,默认None
2、校验参数,int(page)
3、初始化变量,blogs_list[],current_page = 1,total_page = 1
4、定义过滤条件,filter[blogs.status==0],如果keywords存在,添加到过滤条件中
5、查询博客数据库,默认按照博客的发布时间,分页
6、遍历查询结果
7、返回模板admin/blogs_review.html,total_page,current_page,blogs_list
:return:
"""
page = request.args.get('p', '1')
keywords = request.args.get('keywords', None)
try:
page = int(page)
except Exception as e:
current_app.logger.error(e)
blogs_list = []
current_page = 1
total_page = 1
filters = [Blogs.status != 0]
# filters = []
if keywords:
filters.append(Blogs.title.contains(keywords))
try:
paginate = Blogs.query.filter(*filters).paginate(page, constants.ADMIN_BLOGS_PAGE_MAX_COUNT, False)
blogs_list = paginate.items
current_page = paginate.page
total_page = paginate.pages
except Exception as e:
current_app.logger.error(e)
blogs_dict_list = []
for blogs in blogs_list:
blogs_dict_list.append(blogs.to_basic_dict())
data = {
'total_page': total_page,
'current_page': current_page,
'blogs_list': blogs_dict_list
}
return render_template('admin/blogs_edit.html', data=data)
@admin_blue.route('/blogs_edit_detail', methods=['GET', 'PUT'])
def blogs_edit_detail():
"""
博客编辑详情
1、如果get请求,获取blogs_id,校验参数存在,转成int,默认渲染模板
2、查询数据库,校验查询结果
3、查询分类数据,Category
4、遍历查询结果,确认博客分类属于当前分类,如果是cate_dict['is_selected'] = True
5、移除'最新'的分类,category_dict_li.pop(0)
6、返回模板admin/blogs_edit_detail.html,blogs,categories
7、如果post请求,获取表单参数,blogs_id,title,digest,content,index_image,category_id
8、判断参数完整性
9、查询数据库,校验结果,确认博客的存在
10、读取图片数据,调用七牛云接口上传图片,获取图片名称,拼接图片绝对路径
11、保存数据到数据库,title、digest、content、category_id
12、返回结果
:return:
"""
if request.method == 'GET':
blogs_id = request.args.get('blogs_id')
if not blogs_id:
abort(404)
try:
blogs_id = int(blogs_id)
except Exception as e:
current_app.logger.error(e)
return render_template('admin/blogs_edit_detail.html', errmsg='参数类型错误')
try:
blogs = Blogs.query.get(blogs_id)
except Exception as e:
current_app.logger.error(e)
return render_template('admin/blogs_edit_detail.html', errmsg='查询数据错误')
if not blogs:
return render_template('admin/blogs_edit_detail.html', errmsg='未查询到数据')
try:
categories = Category.query.all()
except Exception as e:
current_app.logger.error(e)
return render_template('admin/blogs_edit_detail.html', errmsg='查询分类数据错误')
category_dict_list = []
# 遍历分类数据,需要判断当前遍历到的分类和博客所属分类一致
for category in categories:
cate_dict = category.to_dict()
if category.id == blogs.category_id:
cate_dict['is_selected'] = True
category_dict_list.append(cate_dict)
# category_dict_list.pop(0)
data = {
'blogs': blogs.to_dict(),
'categories': category_dict_list
}
return render_template('admin/blogs_edit_detail.html', data=data)
blogs_id = request.json.get('blogs_id')
title = request.json.get('title')
digest = request.json.get('digest')
content = request.json.get('content')
# index_image = request.files.get('index_image')
category_id = request.json.get('category_id')
if not all([title, digest, content, category_id]):
return jsonify(errno=RET.PARAMERR, errmsg='参数缺失')
try:
blogs = Blogs.query.get(blogs_id)
except Exception as e:
current_app.logger.error(e)
return jsonify(errno=RET.DBERR, errmsg='查询数据错误')
if not blogs:
return jsonify(errno=RET.NODATA, errmsg='无博客数据')
# if index_image:
# image = index_image.read()
# try:
# image_name = ""
# # TODO img name
# except Exception as e:
# current_app.logger.error(e)
# return jsonify(errno=RET.THIRDERR, errmsg='上传图片失败')
# blogs.image_url = image_name
blogs.image_url = '无'
blogs.title = title
blogs.digest = digest
blogs.content = content
blogs.category_id = category_id
try:
db.session.add(blogs)
db.session.commit()
except Exception as e:
current_app.logger.error(e)
db.session.rollback()
return jsonify(errno=RET.DBERR, errmsg='保存数据失败')
return jsonify(errno=RET.OK, errmsg='OK')
@admin_blue.route('/add_blog', methods=['GET'])
def blogs_add_detail():
try:
categories = Category.query.all()
except Exception as e:
current_app.logger.error(e)
return render_template('admin/blogs_add_detail.html', errmsg='查询分类数据错误')
category_dict_list = []
# print(categories)
# 遍历分类数据,需要判断当前遍历到的分类和博客所属分类一致
for category in categories:
category_dict_list.append(category.to_dict())
data = {
# 'blogs': blogs.to_dict(),
'categories': category_dict_list
}
return render_template('admin/blogs_add_detail.html', data=data)
@admin_blue.route('/blogs_add_action', methods=['POST'])
def blogs_add_action():
"""
博客添加详情
:return:
"""
title = request.json.get('title')
digest = request.json.get('digest')
content = request.json.get('content')
category_id = request.json.get('category_id')
if not all([title, digest, content, category_id]):
return jsonify(errno=RET.PARAMERR, errmsg='参数缺失')
blogs = Blogs()
blogs.image_url = ''
blogs.title = title
blogs.user_id = 1
blogs.source = '个人发布'
blogs.digest = digest
blogs.content = content
blogs.category_id = category_id
blogs.status = 1
blogs.content_url = '/#'
try:
db.session.add(blogs)
db.session.commit()
except Exception as e:
current_app.logger.error(e)
db.session.rollback()
return jsonify(errno=RET.DBERR, errmsg='保存数据失败')
return jsonify(errno=RET.OK, errmsg='OK')
@admin_blue.route('/blogs_type', methods=['GET', 'POST'])
def blogs_type():
"""
博客分类
1、如果get请求,查询分类数据,遍历查询结果,移除'最新'的分类
2、返回模板admin/blogs_type.html,categories
3、如果post请求,获取参数,name,id(表示编辑已存在的分类)
4、校验name参数存在
5、如果id存在(即修改已有的分类),转成int,根据分类id查询数据库,校验查询结果,category.name = name
6、实例化分类对象,保存分类名称,提交数据到数据库
7、返回结果
:return:
"""
if request.method == 'GET':
try:
categories = Category.query.all()
except Exception as e:
current_app.logger.error(e)
return render_template('admin/blogs_type.html', errmsg='查询数据错误')
categories_dict_list = []
for category in categories:
categories_dict_list.append(category.to_dict())
# categories_dict_list.pop(0)
data = {
'categories': categories_dict_list
}
return render_template('admin/blogs_type.html', data=data)
cname = request.json.get('name')
cid = request.json.get('id')
if not cname:
return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
if cid:
try:
cid = int(cid)
category = Category.query.get(cid)
except Exception as e:
current_app.logger.error(e)
return jsonify(errno=RET.DBERR, errmsg='查询数据错误')
if not category:
return jsonify(errno=RET.NODATA, errmsg='未查询到分类数据')
category.name = cname
else:
category = Category()
category.name = cname
db.session.add(category)
try:
db.session.commit()
except Exception as e:
current_app.logger.error(e)
return jsonify(errno=RET.DBERR, errmsg='保存数据失败')
return jsonify(errno=RET.OK, errmsg='OK')
| [
"flask.render_template",
"flask.request.args.get",
"blog.models.Blogs.title.contains",
"datetime.timedelta",
"flask.jsonify",
"blog.models.Category",
"blog.models.Category.query.get",
"flask.request.form.get",
"flask.request.json.get",
"flask.abort",
"time.localtime",
"flask.current_app.logger... | [((1177, 1205), 'flask.request.form.get', 'request.form.get', (['"""username"""'], {}), "('username')\n", (1193, 1205), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((1221, 1249), 'flask.request.form.get', 'request.form.get', (['"""password"""'], {}), "('password')\n", (1237, 1249), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((2358, 2374), 'time.localtime', 'time.localtime', ([], {}), '()\n', (2372, 2374), False, 'import time\n'), ((2561, 2610), 'datetime.datetime.strptime', 'datetime.strptime', (['mon_begin_date_str', '"""%Y-%m-%d"""'], {}), "(mon_begin_date_str, '%Y-%m-%d')\n", (2578, 2610), False, 'from datetime import datetime, timedelta\n'), ((3038, 3087), 'datetime.datetime.strptime', 'datetime.strptime', (['day_begin_date_str', '"""%Y-%m-%d"""'], {}), "(day_begin_date_str, '%Y-%m-%d')\n", (3055, 3087), False, 'from datetime import datetime, timedelta\n'), ((3547, 3590), 'datetime.datetime.strptime', 'datetime.strptime', (['now_date_str', '"""%Y-%m-%d"""'], {}), "(now_date_str, '%Y-%m-%d')\n", (3564, 3590), False, 'from datetime import datetime, timedelta\n'), ((4557, 4608), 'flask.render_template', 'render_template', (['"""admin/user_count.html"""'], {'data': 'data'}), "('admin/user_count.html', data=data)\n", (4572, 4608), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((4853, 4879), 'flask.request.args.get', 'request.args.get', (['"""p"""', '"""1"""'], {}), "('p', '1')\n", (4869, 4879), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((5650, 5700), 'flask.render_template', 'render_template', (['"""admin/user_list.html"""'], {'data': 'data'}), "('admin/user_list.html', data=data)\n", (5665, 5700), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((6041, 6065), 'flask.request.args.get', 'request.args.get', (['"""p"""', '(1)'], {}), "('p', 1)\n", (6057, 6065), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((6081, 6115), 'flask.request.args.get', 'request.args.get', (['"""keywords"""', 'None'], {}), "('keywords', None)\n", (6097, 6115), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((7019, 7072), 'flask.render_template', 'render_template', (['"""admin/blogs_review.html"""'], {'data': 'data'}), "('admin/blogs_review.html', data=data)\n", (7034, 7072), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((7584, 7644), 'flask.render_template', 'render_template', (['"""admin/blogs_review_detail.html"""'], {'data': 'data'}), "('admin/blogs_review_detail.html', data=data)\n", (7599, 7644), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((8008, 8036), 'flask.request.json.get', 'request.json.get', (['"""blogs_id"""'], {}), "('blogs_id')\n", (8024, 8036), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((8050, 8076), 'flask.request.json.get', 'request.json.get', (['"""action"""'], {}), "('action')\n", (8066, 8076), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((9020, 9054), 'flask.jsonify', 'jsonify', ([], {'errno': 'RET.OK', 'errmsg': '"""OK"""'}), "(errno=RET.OK, errmsg='OK')\n", (9027, 9054), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((9448, 9474), 'flask.request.args.get', 'request.args.get', (['"""p"""', '"""1"""'], {}), "('p', '1')\n", (9464, 9474), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((9490, 9524), 'flask.request.args.get', 'request.args.get', (['"""keywords"""', 'None'], {}), "('keywords', None)\n", (9506, 9524), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((10344, 10395), 'flask.render_template', 'render_template', (['"""admin/blogs_edit.html"""'], {'data': 'data'}), "('admin/blogs_edit.html', data=data)\n", (10359, 10395), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((12389, 12417), 'flask.request.json.get', 'request.json.get', (['"""blogs_id"""'], {}), "('blogs_id')\n", (12405, 12417), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((12430, 12455), 'flask.request.json.get', 'request.json.get', (['"""title"""'], {}), "('title')\n", (12446, 12455), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((12469, 12495), 'flask.request.json.get', 'request.json.get', (['"""digest"""'], {}), "('digest')\n", (12485, 12495), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((12510, 12537), 'flask.request.json.get', 'request.json.get', (['"""content"""'], {}), "('content')\n", (12526, 12537), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((12609, 12640), 'flask.request.json.get', 'request.json.get', (['"""category_id"""'], {}), "('category_id')\n", (12625, 12640), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((13684, 13718), 'flask.jsonify', 'jsonify', ([], {'errno': 'RET.OK', 'errmsg': '"""OK"""'}), "(errno=RET.OK, errmsg='OK')\n", (13691, 13718), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((14268, 14325), 'flask.render_template', 'render_template', (['"""admin/blogs_add_detail.html"""'], {'data': 'data'}), "('admin/blogs_add_detail.html', data=data)\n", (14283, 14325), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((14461, 14486), 'flask.request.json.get', 'request.json.get', (['"""title"""'], {}), "('title')\n", (14477, 14486), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((14500, 14526), 'flask.request.json.get', 'request.json.get', (['"""digest"""'], {}), "('digest')\n", (14516, 14526), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((14541, 14568), 'flask.request.json.get', 'request.json.get', (['"""content"""'], {}), "('content')\n", (14557, 14568), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((14587, 14618), 'flask.request.json.get', 'request.json.get', (['"""category_id"""'], {}), "('category_id')\n", (14603, 14618), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((14744, 14751), 'blog.models.Blogs', 'Blogs', ([], {}), '()\n', (14749, 14751), False, 'from blog.models import User, Category, Blogs\n'), ((15218, 15252), 'flask.jsonify', 'jsonify', ([], {'errno': 'RET.OK', 'errmsg': '"""OK"""'}), "(errno=RET.OK, errmsg='OK')\n", (15225, 15252), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((16178, 16202), 'flask.request.json.get', 'request.json.get', (['"""name"""'], {}), "('name')\n", (16194, 16202), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((16213, 16235), 'flask.request.json.get', 'request.json.get', (['"""id"""'], {}), "('id')\n", (16229, 16235), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((16933, 16967), 'flask.jsonify', 'jsonify', ([], {'errno': 'RET.OK', 'errmsg': '"""OK"""'}), "(errno=RET.OK, errmsg='OK')\n", (16940, 16967), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((945, 973), 'flask.session.get', 'session.get', (['"""user_id"""', 'None'], {}), "('user_id', None)\n", (956, 973), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((993, 1023), 'flask.session.get', 'session.get', (['"""is_admin"""', '(False)'], {}), "('is_admin', False)\n", (1004, 1023), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((1124, 1159), 'flask.render_template', 'render_template', (['"""admin/login.html"""'], {}), "('admin/login.html')\n", (1139, 1159), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((1304, 1355), 'flask.render_template', 'render_template', (['"""admin/login.html"""'], {'errmsg': '"""参数不完整"""'}), "('admin/login.html', errmsg='参数不完整')\n", (1319, 1355), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((1660, 1714), 'flask.render_template', 'render_template', (['"""admin/login.html"""'], {'errmsg': '"""用户名或密码错误"""'}), "('admin/login.html', errmsg='用户名或密码错误')\n", (1675, 1714), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((1925, 1947), 'flask.url_for', 'url_for', (['"""admin.index"""'], {}), "('admin.index')\n", (1932, 1947), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((4184, 4225), 'datetime.datetime.strftime', 'datetime.strftime', (['begin_date', '"""%Y-%m-%d"""'], {}), "(begin_date, '%Y-%m-%d')\n", (4201, 4225), False, 'from datetime import datetime, timedelta\n'), ((7337, 7362), 'blog.models.Blogs.query.get', 'Blogs.query.get', (['blogs_id'], {}), '(blogs_id)\n', (7352, 7362), False, 'from blog.models import User, Category, Blogs\n'), ((7459, 7534), 'flask.render_template', 'render_template', (['"""admin/blogs_review_detail.html"""'], {'data': "{'errmsg': '未查到数据'}"}), "('admin/blogs_review_detail.html', data={'errmsg': '未查到数据'})\n", (7474, 7534), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((8128, 8170), 'flask.jsonify', 'jsonify', ([], {'errno': 'RET.PARAMERR', 'errmsg': '"""参数缺失"""'}), "(errno=RET.PARAMERR, errmsg='参数缺失')\n", (8135, 8170), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((8229, 8273), 'flask.jsonify', 'jsonify', ([], {'errno': 'RET.PARAMERR', 'errmsg': '"""参数类型错误"""'}), "(errno=RET.PARAMERR, errmsg='参数类型错误')\n", (8236, 8273), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((8317, 8342), 'blog.models.Blogs.query.get', 'Blogs.query.get', (['blogs_id'], {}), '(blogs_id)\n', (8332, 8342), False, 'from blog.models import User, Category, Blogs\n'), ((8497, 8539), 'flask.jsonify', 'jsonify', ([], {'errno': 'RET.NODATA', 'errmsg': '"""未查询到数据"""'}), "(errno=RET.NODATA, errmsg='未查询到数据')\n", (8504, 8539), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((8650, 8676), 'flask.request.json.get', 'request.json.get', (['"""reason"""'], {}), "('reason')\n", (8666, 8676), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((8838, 8857), 'blog.db.session.commit', 'db.session.commit', ([], {}), '()\n', (8855, 8857), False, 'from blog import constants, db\n'), ((11040, 11068), 'flask.request.args.get', 'request.args.get', (['"""blogs_id"""'], {}), "('blogs_id')\n", (11056, 11068), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((12315, 12373), 'flask.render_template', 'render_template', (['"""admin/blogs_edit_detail.html"""'], {'data': 'data'}), "('admin/blogs_edit_detail.html', data=data)\n", (12330, 12373), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((12712, 12754), 'flask.jsonify', 'jsonify', ([], {'errno': 'RET.PARAMERR', 'errmsg': '"""参数缺失"""'}), "(errno=RET.PARAMERR, errmsg='参数缺失')\n", (12719, 12754), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((12780, 12805), 'blog.models.Blogs.query.get', 'Blogs.query.get', (['blogs_id'], {}), '(blogs_id)\n', (12795, 12805), False, 'from blog.models import User, Category, Blogs\n'), ((12959, 13000), 'flask.jsonify', 'jsonify', ([], {'errno': 'RET.NODATA', 'errmsg': '"""无博客数据"""'}), "(errno=RET.NODATA, errmsg='无博客数据')\n", (12966, 13000), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((13473, 13494), 'blog.db.session.add', 'db.session.add', (['blogs'], {}), '(blogs)\n', (13487, 13494), False, 'from blog import constants, db\n'), ((13503, 13522), 'blog.db.session.commit', 'db.session.commit', ([], {}), '()\n', (13520, 13522), False, 'from blog import constants, db\n'), ((13823, 13843), 'blog.models.Category.query.all', 'Category.query.all', ([], {}), '()\n', (13841, 13843), False, 'from blog.models import User, Category, Blogs\n'), ((14689, 14731), 'flask.jsonify', 'jsonify', ([], {'errno': 'RET.PARAMERR', 'errmsg': '"""参数缺失"""'}), "(errno=RET.PARAMERR, errmsg='参数缺失')\n", (14696, 14731), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((15007, 15028), 'blog.db.session.add', 'db.session.add', (['blogs'], {}), '(blogs)\n', (15021, 15028), False, 'from blog import constants, db\n'), ((15037, 15056), 'blog.db.session.commit', 'db.session.commit', ([], {}), '()\n', (15054, 15056), False, 'from blog import constants, db\n'), ((16114, 16165), 'flask.render_template', 'render_template', (['"""admin/blogs_type.html"""'], {'data': 'data'}), "('admin/blogs_type.html', data=data)\n", (16129, 16165), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((16269, 16311), 'flask.jsonify', 'jsonify', ([], {'errno': 'RET.PARAMERR', 'errmsg': '"""参数错误"""'}), "(errno=RET.PARAMERR, errmsg='参数错误')\n", (16276, 16311), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((16691, 16701), 'blog.models.Category', 'Category', ([], {}), '()\n', (16699, 16701), False, 'from blog.models import User, Category, Blogs\n'), ((16740, 16764), 'blog.db.session.add', 'db.session.add', (['category'], {}), '(category)\n', (16754, 16764), False, 'from blog import constants, db\n'), ((16782, 16801), 'blog.db.session.commit', 'db.session.commit', ([], {}), '()\n', (16799, 16801), False, 'from blog import constants, db\n'), ((1490, 1517), 'flask.current_app.logger.error', 'current_app.logger.error', (['e'], {}), '(e)\n', (1514, 1517), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((1533, 1586), 'flask.render_template', 'render_template', (['"""admin/login.html"""'], {'errmsg': '"""数据库查询错误"""'}), "('admin/login.html', errmsg='数据库查询错误')\n", (1548, 1586), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((2238, 2265), 'flask.current_app.logger.error', 'current_app.logger.error', (['e'], {}), '(e)\n', (2262, 2265), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((2281, 2323), 'flask.jsonify', 'jsonify', ([], {'errno': 'RET.DBERR', 'errmsg': '"""查询总人数失败"""'}), "(errno=RET.DBERR, errmsg='查询总人数失败')\n", (2288, 2323), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((2789, 2816), 'flask.current_app.logger.error', 'current_app.logger.error', (['e'], {}), '(e)\n', (2813, 2816), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((2832, 2874), 'flask.jsonify', 'jsonify', ([], {'errno': 'RET.DBERR', 'errmsg': '"""查询月人数失败"""'}), "(errno=RET.DBERR, errmsg='查询月人数失败')\n", (2839, 2874), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((3248, 3275), 'flask.current_app.logger.error', 'current_app.logger.error', (['e'], {}), '(e)\n', (3272, 3275), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((3291, 3333), 'flask.jsonify', 'jsonify', ([], {'errno': 'RET.DBERR', 'errmsg': '"""查询日人数失败"""'}), "(errno=RET.DBERR, errmsg='查询日人数失败')\n", (3298, 3333), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((3680, 3697), 'datetime.timedelta', 'timedelta', ([], {'days': 'd'}), '(days=d)\n', (3689, 3697), False, 'from datetime import datetime, timedelta\n'), ((3728, 3749), 'datetime.timedelta', 'timedelta', ([], {'days': '(d - 1)'}), '(days=d - 1)\n', (3737, 3749), False, 'from datetime import datetime, timedelta\n'), ((4949, 4976), 'flask.current_app.logger.error', 'current_app.logger.error', (['e'], {}), '(e)\n', (4973, 4976), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((5315, 5342), 'flask.current_app.logger.error', 'current_app.logger.error', (['e'], {}), '(e)\n', (5339, 5342), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((5358, 5399), 'flask.jsonify', 'jsonify', ([], {'errno': 'RET.DBERR', 'errmsg': '"""查询数据错误"""'}), "(errno=RET.DBERR, errmsg='查询数据错误')\n", (5365, 5399), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((6185, 6212), 'flask.current_app.logger.error', 'current_app.logger.error', (['e'], {}), '(e)\n', (6209, 6212), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((6410, 6440), 'blog.models.Blogs.title.contains', 'Blogs.title.contains', (['keywords'], {}), '(keywords)\n', (6430, 6440), False, 'from blog.models import User, Category, Blogs\n'), ((6769, 6796), 'flask.current_app.logger.error', 'current_app.logger.error', (['e'], {}), '(e)\n', (6793, 6796), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((7398, 7425), 'flask.current_app.logger.error', 'current_app.logger.error', (['e'], {}), '(e)\n', (7422, 7425), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((8378, 8405), 'flask.current_app.logger.error', 'current_app.logger.error', (['e'], {}), '(e)\n', (8402, 8405), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((8421, 8462), 'flask.jsonify', 'jsonify', ([], {'errno': 'RET.DBERR', 'errmsg': '"""数据查询失败"""'}), "(errno=RET.DBERR, errmsg='数据查询失败')\n", (8428, 8462), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((8719, 8764), 'flask.jsonify', 'jsonify', ([], {'errno': 'RET.PARAMERR', 'errmsg': '"""请输入拒绝原因"""'}), "(errno=RET.PARAMERR, errmsg='请输入拒绝原因')\n", (8726, 8764), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((8893, 8920), 'flask.current_app.logger.error', 'current_app.logger.error', (['e'], {}), '(e)\n', (8917, 8920), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((8929, 8950), 'blog.db.session.rollback', 'db.session.rollback', ([], {}), '()\n', (8948, 8950), False, 'from blog import constants, db\n'), ((8966, 9007), 'flask.jsonify', 'jsonify', ([], {'errno': 'RET.DBERR', 'errmsg': '"""保存数据失败"""'}), "(errno=RET.DBERR, errmsg='保存数据失败')\n", (8973, 9007), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((9594, 9621), 'flask.current_app.logger.error', 'current_app.logger.error', (['e'], {}), '(e)\n', (9618, 9621), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((9775, 9805), 'blog.models.Blogs.title.contains', 'Blogs.title.contains', (['keywords'], {}), '(keywords)\n', (9795, 9805), False, 'from blog.models import User, Category, Blogs\n'), ((10068, 10095), 'flask.current_app.logger.error', 'current_app.logger.error', (['e'], {}), '(e)\n', (10092, 10095), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((11106, 11116), 'flask.abort', 'abort', (['(404)'], {}), '(404)\n', (11111, 11116), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((11355, 11380), 'blog.models.Blogs.query.get', 'Blogs.query.get', (['blogs_id'], {}), '(blogs_id)\n', (11370, 11380), False, 'from blog.models import User, Category, Blogs\n'), ((11577, 11641), 'flask.render_template', 'render_template', (['"""admin/blogs_edit_detail.html"""'], {'errmsg': '"""未查询到数据"""'}), "('admin/blogs_edit_detail.html', errmsg='未查询到数据')\n", (11592, 11641), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((11680, 11700), 'blog.models.Category.query.all', 'Category.query.all', ([], {}), '()\n', (11698, 11700), False, 'from blog.models import User, Category, Blogs\n'), ((12841, 12868), 'flask.current_app.logger.error', 'current_app.logger.error', (['e'], {}), '(e)\n', (12865, 12868), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((12884, 12925), 'flask.jsonify', 'jsonify', ([], {'errno': 'RET.DBERR', 'errmsg': '"""查询数据错误"""'}), "(errno=RET.DBERR, errmsg='查询数据错误')\n", (12891, 12925), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((13558, 13585), 'flask.current_app.logger.error', 'current_app.logger.error', (['e'], {}), '(e)\n', (13582, 13585), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((13594, 13615), 'blog.db.session.rollback', 'db.session.rollback', ([], {}), '()\n', (13613, 13615), False, 'from blog import constants, db\n'), ((13631, 13672), 'flask.jsonify', 'jsonify', ([], {'errno': 'RET.DBERR', 'errmsg': '"""保存数据失败"""'}), "(errno=RET.DBERR, errmsg='保存数据失败')\n", (13638, 13672), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((13879, 13906), 'flask.current_app.logger.error', 'current_app.logger.error', (['e'], {}), '(e)\n', (13903, 13906), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((13922, 13987), 'flask.render_template', 'render_template', (['"""admin/blogs_add_detail.html"""'], {'errmsg': '"""查询分类数据错误"""'}), "('admin/blogs_add_detail.html', errmsg='查询分类数据错误')\n", (13937, 13987), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((15092, 15119), 'flask.current_app.logger.error', 'current_app.logger.error', (['e'], {}), '(e)\n', (15116, 15119), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((15128, 15149), 'blog.db.session.rollback', 'db.session.rollback', ([], {}), '()\n', (15147, 15149), False, 'from blog import constants, db\n'), ((15165, 15206), 'flask.jsonify', 'jsonify', ([], {'errno': 'RET.DBERR', 'errmsg': '"""保存数据失败"""'}), "(errno=RET.DBERR, errmsg='保存数据失败')\n", (15172, 15206), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((15688, 15708), 'blog.models.Category.query.all', 'Category.query.all', ([], {}), '()\n', (15706, 15708), False, 'from blog.models import User, Category, Blogs\n'), ((16387, 16410), 'blog.models.Category.query.get', 'Category.query.get', (['cid'], {}), '(cid)\n', (16405, 16410), False, 'from blog.models import User, Category, Blogs\n'), ((16587, 16631), 'flask.jsonify', 'jsonify', ([], {'errno': 'RET.NODATA', 'errmsg': '"""未查询到分类数据"""'}), "(errno=RET.NODATA, errmsg='未查询到分类数据')\n", (16594, 16631), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((16837, 16864), 'flask.current_app.logger.error', 'current_app.logger.error', (['e'], {}), '(e)\n', (16861, 16864), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((16880, 16921), 'flask.jsonify', 'jsonify', ([], {'errno': 'RET.DBERR', 'errmsg': '"""保存数据失败"""'}), "(errno=RET.DBERR, errmsg='保存数据失败')\n", (16887, 16921), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((1085, 1107), 'flask.url_for', 'url_for', (['"""admin.index"""'], {}), "('admin.index')\n", (1092, 1107), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((1380, 1446), 'blog.models.User.query.filter', 'User.query.filter', (['(User.mobile == user_name)', '(User.is_admin == True)'], {}), '(User.mobile == user_name, User.is_admin == True)\n', (1397, 1446), False, 'from blog.models import User, Category, Blogs\n'), ((2153, 2194), 'blog.models.User.query.filter', 'User.query.filter', (['(User.is_admin == False)'], {}), '(User.is_admin == False)\n', (2170, 2194), False, 'from blog.models import User, Category, Blogs\n'), ((2669, 2745), 'blog.models.User.query.filter', 'User.query.filter', (['(User.is_admin == False)', '(User.create_time > mon_begin_date)'], {}), '(User.is_admin == False, User.create_time > mon_begin_date)\n', (2686, 2745), False, 'from blog.models import User, Category, Blogs\n'), ((3128, 3204), 'blog.models.User.query.filter', 'User.query.filter', (['(User.is_admin == False)', '(User.create_time > day_begin_date)'], {}), '(User.is_admin == False, User.create_time > day_begin_date)\n', (3145, 3204), False, 'from blog.models import User, Category, Blogs\n'), ((3990, 4017), 'flask.current_app.logger.error', 'current_app.logger.error', (['e'], {}), '(e)\n', (4014, 4017), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((4037, 4080), 'flask.jsonify', 'jsonify', ([], {'errno': 'RET.DBERR', 'errmsg': '"""查询活跃人数失败"""'}), "(errno=RET.DBERR, errmsg='查询活跃人数失败')\n", (4044, 4080), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((5077, 5118), 'blog.models.User.query.filter', 'User.query.filter', (['(User.is_admin == False)'], {}), '(User.is_admin == False)\n', (5094, 5118), False, 'from blog.models import User, Category, Blogs\n'), ((9835, 9863), 'blog.models.Blogs.query.filter', 'Blogs.query.filter', (['*filters'], {}), '(*filters)\n', (9853, 9863), False, 'from blog.models import User, Category, Blogs\n'), ((11210, 11237), 'flask.current_app.logger.error', 'current_app.logger.error', (['e'], {}), '(e)\n', (11234, 11237), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((11257, 11321), 'flask.render_template', 'render_template', (['"""admin/blogs_edit_detail.html"""'], {'errmsg': '"""参数类型错误"""'}), "('admin/blogs_edit_detail.html', errmsg='参数类型错误')\n", (11272, 11321), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((11424, 11451), 'flask.current_app.logger.error', 'current_app.logger.error', (['e'], {}), '(e)\n', (11448, 11451), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((11471, 11535), 'flask.render_template', 'render_template', (['"""admin/blogs_edit_detail.html"""'], {'errmsg': '"""查询数据错误"""'}), "('admin/blogs_edit_detail.html', errmsg='查询数据错误')\n", (11486, 11535), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((11744, 11771), 'flask.current_app.logger.error', 'current_app.logger.error', (['e'], {}), '(e)\n', (11768, 11771), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((11791, 11857), 'flask.render_template', 'render_template', (['"""admin/blogs_edit_detail.html"""'], {'errmsg': '"""查询分类数据错误"""'}), "('admin/blogs_edit_detail.html', errmsg='查询分类数据错误')\n", (11806, 11857), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((15752, 15779), 'flask.current_app.logger.error', 'current_app.logger.error', (['e'], {}), '(e)\n', (15776, 15779), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((15799, 15856), 'flask.render_template', 'render_template', (['"""admin/blogs_type.html"""'], {'errmsg': '"""查询数据错误"""'}), "('admin/blogs_type.html', errmsg='查询数据错误')\n", (15814, 15856), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((16454, 16481), 'flask.current_app.logger.error', 'current_app.logger.error', (['e'], {}), '(e)\n', (16478, 16481), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((16501, 16542), 'flask.jsonify', 'jsonify', ([], {'errno': 'RET.DBERR', 'errmsg': '"""查询数据错误"""'}), "(errno=RET.DBERR, errmsg='查询数据错误')\n", (16508, 16542), False, 'from flask import g, render_template, request, session, redirect, url_for, jsonify, current_app, abort\n'), ((3800, 3905), 'blog.models.User.query.filter', 'User.query.filter', (['(User.is_admin == False)', '(User.last_login >= begin_date)', '(User.last_login < end_date)'], {}), '(User.is_admin == False, User.last_login >= begin_date, \n User.last_login < end_date)\n', (3817, 3905), False, 'from blog.models import User, Category, Blogs\n'), ((6523, 6547), 'blog.models.Blogs.create_time.desc', 'Blogs.create_time.desc', ([], {}), '()\n', (6545, 6547), False, 'from blog.models import User, Category, Blogs\n'), ((6470, 6498), 'blog.models.Blogs.query.filter', 'Blogs.query.filter', (['*filters'], {}), '(*filters)\n', (6488, 6498), False, 'from blog.models import User, Category, Blogs\n')] |
import os
import stripe
from flask import Flask, jsonify, render_template, request
app = Flask(__name__)
stripe_keys = {
"secret_key": os.environ["STRIPE_SECRET_KEY"],
"publishable_key": os.environ["STRIPE_PUBLISHABLE_KEY"],
"price_id": os.environ["STRIPE_PRICE_ID"],
"endpoint_secret": os.environ["STRIPE_ENDPOINT_SECRET"],
}
stripe.api_key = stripe_keys["secret_key"]
@app.route("/hello")
def hello_world():
return jsonify("hello, world!")
@app.route("/")
def index():
# you should force the user to log in/sign
return render_template("index.html")
@app.route("/config")
def get_publishable_key():
stripe_config = {"publicKey": stripe_keys["publishable_key"]}
return jsonify(stripe_config)
@app.route("/create-checkout-session")
def create_checkout_session():
domain_url = "http://localhost:5000/"
stripe.api_key = stripe_keys["secret_key"]
try:
checkout_session = stripe.checkout.Session.create(
# you should get the user id here and pass it along as 'client_reference_id'
#
# this will allow you to associate the Stripe session with
# the user saved in your database
#
# example: client_reference_id=user.id,
success_url=domain_url + "success?session_id={CHECKOUT_SESSION_ID}",
cancel_url=domain_url + "cancel",
payment_method_types=["card"],
mode="subscription",
line_items=[
{
"price": stripe_keys["price_id"],
"quantity": 1,
}
]
)
return jsonify({"sessionId": checkout_session["id"]})
except Exception as e:
return jsonify(error=str(e)), 403
@app.route("/success")
def success():
return render_template("success.html")
@app.route("/cancel")
def cancelled():
return render_template("cancel.html")
@app.route("/webhook", methods=["POST"])
def stripe_webhook():
payload = request.get_data(as_text=True)
sig_header = request.headers.get("Stripe-Signature")
try:
event = stripe.Webhook.construct_event(
payload, sig_header, stripe_keys["endpoint_secret"]
)
except ValueError as e:
# Invalid payload
return "Invalid payload", 400
except stripe.error.SignatureVerificationError as e:
# Invalid signature
return "Invalid signature", 400
# Handle the checkout.session.completed event
if event["type"] == "checkout.session.completed":
session = event["data"]["object"]
# Fulfill the purchase...
handle_checkout_session(session)
return "Success", 200
def handle_checkout_session(session):
# here you should fetch the details from the session and save the relevant information
# to the database (e.g. associate the user with their subscription)
print("Subscription was successful.")
if __name__ == "__main__":
app.run()
| [
"flask.render_template",
"flask.Flask",
"stripe.Webhook.construct_event",
"flask.request.get_data",
"stripe.checkout.Session.create",
"flask.request.headers.get",
"flask.jsonify"
] | [((91, 106), 'flask.Flask', 'Flask', (['__name__'], {}), '(__name__)\n', (96, 106), False, 'from flask import Flask, jsonify, render_template, request\n'), ((443, 467), 'flask.jsonify', 'jsonify', (['"""hello, world!"""'], {}), "('hello, world!')\n", (450, 467), False, 'from flask import Flask, jsonify, render_template, request\n'), ((557, 586), 'flask.render_template', 'render_template', (['"""index.html"""'], {}), "('index.html')\n", (572, 586), False, 'from flask import Flask, jsonify, render_template, request\n'), ((715, 737), 'flask.jsonify', 'jsonify', (['stripe_config'], {}), '(stripe_config)\n', (722, 737), False, 'from flask import Flask, jsonify, render_template, request\n'), ((1813, 1844), 'flask.render_template', 'render_template', (['"""success.html"""'], {}), "('success.html')\n", (1828, 1844), False, 'from flask import Flask, jsonify, render_template, request\n'), ((1897, 1927), 'flask.render_template', 'render_template', (['"""cancel.html"""'], {}), "('cancel.html')\n", (1912, 1927), False, 'from flask import Flask, jsonify, render_template, request\n'), ((2007, 2037), 'flask.request.get_data', 'request.get_data', ([], {'as_text': '(True)'}), '(as_text=True)\n', (2023, 2037), False, 'from flask import Flask, jsonify, render_template, request\n'), ((2055, 2094), 'flask.request.headers.get', 'request.headers.get', (['"""Stripe-Signature"""'], {}), "('Stripe-Signature')\n", (2074, 2094), False, 'from flask import Flask, jsonify, render_template, request\n'), ((936, 1197), 'stripe.checkout.Session.create', 'stripe.checkout.Session.create', ([], {'success_url': "(domain_url + 'success?session_id={CHECKOUT_SESSION_ID}')", 'cancel_url': "(domain_url + 'cancel')", 'payment_method_types': "['card']", 'mode': '"""subscription"""', 'line_items': "[{'price': stripe_keys['price_id'], 'quantity': 1}]"}), "(success_url=domain_url +\n 'success?session_id={CHECKOUT_SESSION_ID}', cancel_url=domain_url +\n 'cancel', payment_method_types=['card'], mode='subscription',\n line_items=[{'price': stripe_keys['price_id'], 'quantity': 1}])\n", (966, 1197), False, 'import stripe\n'), ((1646, 1692), 'flask.jsonify', 'jsonify', (["{'sessionId': checkout_session['id']}"], {}), "({'sessionId': checkout_session['id']})\n", (1653, 1692), False, 'from flask import Flask, jsonify, render_template, request\n'), ((2121, 2209), 'stripe.Webhook.construct_event', 'stripe.Webhook.construct_event', (['payload', 'sig_header', "stripe_keys['endpoint_secret']"], {}), "(payload, sig_header, stripe_keys[\n 'endpoint_secret'])\n", (2151, 2209), False, 'import stripe\n')] |
import utils
import model
import pandas as pd
dictionary = pd.read_csv(
'/.../dictionary.csv'
)
item_occurrences = utils.stream_csv(
'/.../item_co_occurrences.csv'
)
sim_model = model.SimilarityModel(
dictionary,
item_occurrences,
1_234_567 # num of occurrences must be previously known
)
sim_model.build()
df = sim_model.as_dataframe()
sim_model.store_in_db()
| [
"utils.stream_csv",
"model.SimilarityModel",
"pandas.read_csv"
] | [((61, 95), 'pandas.read_csv', 'pd.read_csv', (['"""/.../dictionary.csv"""'], {}), "('/.../dictionary.csv')\n", (72, 95), True, 'import pandas as pd\n'), ((121, 169), 'utils.stream_csv', 'utils.stream_csv', (['"""/.../item_co_occurrences.csv"""'], {}), "('/.../item_co_occurrences.csv')\n", (137, 169), False, 'import utils\n'), ((189, 249), 'model.SimilarityModel', 'model.SimilarityModel', (['dictionary', 'item_occurrences', '(1234567)'], {}), '(dictionary, item_occurrences, 1234567)\n', (210, 249), False, 'import model\n')] |
import requests
import urllib3
adddress = "http://businesscorp.com.br"
def webrequest( ):
site = requests.get(adddress)
site.content
print (site.content)
print ("Status code:", site.status_code)
print ("Headers:", site.headers)
print ("Server:", site.headers['Server'])
site = requests.options("http://businesscorp.com.br")
print(site.headers)
print(site.headers['Allow'])
#https://urllib3.readthedocs.io/en/latest/user-guide.html
def urllibExample():
http = urllib3.PoolManager()
r = http.request('GET', adddress)
print("Response: ", type(r), "Content: ", r )
print("r.data: ", type(r.data), "Content: ", r.data )
print ("r.status(): ", r.status)
print ("r.headers(): ", r.headers)
print ("Server: ", r.headers['Server'])
print ("r.headers(): ", r.headers)
#r.
#print(site.content)
#print("Status code:", site.status_code)
#print("Headers:", site.headers)
#print("Server:", site.headers['Server'])
#urllib3.
#webrequest()
urllibExample() | [
"urllib3.PoolManager",
"requests.get",
"requests.options"
] | [((105, 127), 'requests.get', 'requests.get', (['adddress'], {}), '(adddress)\n', (117, 127), False, 'import requests\n'), ((310, 356), 'requests.options', 'requests.options', (['"""http://businesscorp.com.br"""'], {}), "('http://businesscorp.com.br')\n", (326, 356), False, 'import requests\n'), ((506, 527), 'urllib3.PoolManager', 'urllib3.PoolManager', ([], {}), '()\n', (525, 527), False, 'import urllib3\n')] |
# -*- mode: python; encoding: utf-8 -*-
#
# Copyright 2017 the Critic contributors, Opera Software ASA
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations under
# the License.
import api
class CommentError(api.APIError):
pass
class InvalidCommentId(CommentError):
"""Raised when an invalid comment id is used."""
def __init__(self, comment_id):
"""Constructor"""
super(InvalidCommentId, self).__init__(
"Invalid comment id: %d" % comment_id)
self.comment_id = comment_id
class InvalidCommentIds(CommentError):
"""Raised by fetchMany() when invalid comment ids are used."""
def __init__(self, comment_ids):
"""Constructor"""
super(InvalidCommentIds, self).__init__(
"Invalid comment ids: %s" % ", ".join(map(str, comment_ids)))
self.comment_ids = comment_ids
class InvalidLocation(CommentError):
"""Raised when attempting to specify an invalid comment location"""
pass
class Comment(api.APIObject):
TYPE_VALUES = frozenset(["issue", "note"])
@property
def id(self):
"""The comment's unique id"""
return self._impl.id
@property
def type(self):
"""The comment's type
The type is one of "issue" and "note"."""
pass
@property
def is_draft(self):
"""True if the comment is not yet published
Unpublished comments are not displayed to other users."""
return self._impl.is_draft
@property
def review(self):
"""The review to which the comment belongs
The review is returned as an api.review.Review object."""
return self._impl.getReview(self.critic)
@property
def author(self):
"""The comment's author
The author is returned as an api.user.User object."""
return self._impl.getAuthor(self.critic)
@property
def timestamp(self):
"""The comment's timestamp
The return value is a datetime.datetime object."""
return self._impl.timestamp
@property
def location(self):
"""The location of the comment, or None
If the comment was made against lines in a commit message, the return
value is a api.comment.CommitMessageLocation object. If the comment
was made against lines in a file version, the return value is
api.comment.FileVersionLocation object. Otherwise, the return value
is None."""
return self._impl.getLocation(self.critic)
@property
def text(self):
"""The comment's text"""
return self._impl.text
@property
def replies(self):
"""The replies to the comment
The replies are returned as a list of api.reply.Reply objects."""
return self._impl.getReplies(self.critic)
class DraftChanges(object):
"""Draft changes to the comment"""
def __init__(self, author, is_draft, reply, new_type):
self.__author = author
self.__is_draft = is_draft
self.__reply = reply
self.__new_type = new_type
@property
def author(self):
"""The author of these draft changes
The author is returned as an api.user.User object."""
return self.__author
@property
def is_draft(self):
"""True if the comment itself is a draft (not published)"""
return self.__is_draft
@property
def reply(self):
"""The current unpublished reply
The reply is returned as an api.reply.Reply object, or None if
there is no current unpublished reply."""
return self.__reply
@property
def new_type(self):
"""The new type of an unpublished type change
The type is returned as a string. Comment.TYPE_VALUES defines the
set of possible return values."""
return self.__new_type
@property
def draft_changes(self):
"""The comment's current draft changes
The draft changes are returned as a Comment.DraftChanges object, or
None if the current user has no unpublished changes to this comment.
If the comment is currently an issue, or the current user has an
unpublished change of the comment's type to issue, the returned
object will be an Issue.DraftChanges instead."""
return self._impl.getDraftChanges(self.critic)
class Issue(Comment):
STATE_VALUES = frozenset(["open", "addressed", "resolved"])
@property
def type(self):
return "issue"
@property
def state(self):
"""The issue's state
The state is one of the strings "open", "addressed" or "resolved"."""
return self._impl.state
@property
def addressed_by(self):
"""The commit that addressed the issue, or None
The value is an api.commit.Commit object, or None if the issue's
state is not "addressed"."""
return self._impl.getAddressedBy(self.critic)
@property
def resolved_by(self):
"""The user that resolved the issue, or None
The value is an api.user.User object, or None if the issue's state is
not "resolved"."""
return self._impl.getResolvedBy(self.critic)
class DraftChanges(Comment.DraftChanges):
"""Draft changes to the issue"""
def __init__(self, author, is_draft, reply, new_type, new_state,
new_location):
super(Issue.DraftChanges, self).__init__(
author, is_draft, reply, new_type)
self.__new_state = new_state
self.__new_location = new_location
@property
def new_state(self):
"""The issue's new state
The new state is returned as a string, or None if the current
user has not resolved or reopened the issue. Issue.STATE_VALUES
defines the set of possible return values."""
return self.__new_state
@property
def new_location(self):
"""The issue's new location
The new location is returned as a FileVersionLocation objects, or
None if the issue has not been reopened, or if it was manually
resolved rather than addressed and did not need to be relocated
when being reopened.
Since only issues in file version locations can be addressed,
that is the only possible type of new location."""
return self.__new_location
class Note(Comment):
@property
def type(self):
return "note"
class Location(api.APIObject):
TYPE_VALUES = frozenset(["general", "commit-message", "file-version"])
def __len__(self):
"""Return the the length of the location, in lines"""
return (self.last_line - self.first_line) + 1
@property
def type(self):
"""The location's type
The type is one of "commit-message" and "file-version"."""
pass
@property
def first_line(self):
"""The line number of the first commented line
Note that line numbers are one-based."""
return self._impl.first_line
@property
def last_line(self):
"""The line number of the last commented line
Note that line numbers are one-based."""
return self._impl.last_line
class CommitMessageLocation(Location):
@property
def type(self):
return "commit-message"
@property
def commit(self):
"""The commit whose message was commented"""
return self._impl.getCommit(self.critic)
@staticmethod
def make(critic, first_line, last_line, commit):
return api.impl.comment.makeCommitMessageLocation(
critic, first_line, last_line, commit)
class FileVersionLocation(Location):
@property
def type(self):
return "file-version"
@property
def changeset(self):
"""The changeset containing the comment
The changeset is returned as an api.changeset.Changeset object.
If the comment was created while looking at a diff, this will
initially be that changeset. As additional commits are added to the
review, this changeset may be "extended" to contain those added
commits.
This is the ideal changeset to use to display the comment, unless it
is an issue that has been addressed, in which case a better changeset
would be the diff of the commit returned by Issue.addressed_by.
If the user did not make the comment while looking at a diff but
rather while looking at a single version of the file, then this
attribute returns None.
If this is an object returned by translateTo() called with a
changeset argument, then this will be that changeset."""
return self._impl.getChangeset(self.critic)
@property
def side(self):
"""The commented side ("old" or "new") of the changeset
If the user did not make the comment while looking at a changeset
(i.e. a diff) but rather while looking at a single version of the
file, then this attribute returns None."""
return self._impl.side
@property
def commit(self):
"""The commit whose version of the file this location references
The commit is returned as an api.commit.Commit object.
If this is an object returned by translateTo() called with a commit
argument, then this is the commit that was given as an argument to
it. If this is the primary location of the comment (returned from
Comment.location) then this is the commit whose version of the file
the comment was originally made against, or None if the comment was
made while looking at a diff."""
return self._impl.getCommit(self.critic)
@property
def file(self):
"""The commented file"""
return self._impl.getFile(self.critic)
@property
def is_translated(self):
"""True if this is a location returned by |translateTo()|"""
return self._impl.is_translated
def translateTo(self, changeset=None, commit=None):
"""Return a translated file version location, or None
The location is translated to the version of the file in a certain
commit. If |changeset| is not None, that commit is the changeset's
|to_commit|, unless the comment is not present there, and otherwise
the changeset's |from_commit|. If |commit| is not None, that's the
commit.
If the comment is not present in the commit, None is returned.
The returned object's |is_translated| will be True.
If the |changeset| argument is not None, then the returned object's
|changeset| will be that changeset, and its |side| will reflect which
of its |from_commit| and |to_commit| ended up being used. The
returned object's |commit| will be None.
If the |commit| argument is not None, the returned object's |commit|
will be that commit, and its |changeset| and |side| will be None."""
assert changeset is None \
or isinstance(changeset, api.changeset.Changeset)
assert commit is None or isinstance(commit, api.commit.Commit)
assert (changeset is None) != (commit is None)
return self._impl.translateTo(self.critic, changeset, commit)
@staticmethod
def make(critic, first_line, last_line, file, changeset=None, side=None,
commit=None):
# File is required.
assert isinstance(file, api.file.File)
# Changeset and side go together.
assert (changeset is None) == (side is None)
assert (changeset is None) \
or isinstance(changeset, api.changeset.Changeset)
# Commit conflicts with changeset, but one is required.
assert (commit is None) != (changeset is None)
assert (commit is None) or isinstance(commit, api.commit.Commit)
return api.impl.comment.makeFileVersionLocation(
critic, first_line, last_line, file, changeset, side, commit)
def fetch(critic, comment_id):
"""Fetch the Comment object with the given id"""
import api.impl
assert isinstance(critic, api.critic.Critic)
assert isinstance(comment_id, int)
return api.impl.comment.fetch(critic, comment_id)
def fetchMany(critic, comment_ids):
"""Fetch multiple Comment objects with the given ids"""
import api.impl
assert isinstance(critic, api.critic.Critic)
comment_ids = list(comment_ids)
assert all(isinstance(comment_id, int) for comment_id in comment_ids)
return api.impl.comment.fetchMany(critic, comment_ids)
def fetchAll(critic, review=None, author=None, comment_type=None, state=None,
location_type=None, changeset=None, commit=None):
"""Fetch all Comment objects
If |review| is not None, only comments in the specified review are
returned.
If |author| is not None, only comments created by the specified user are
returned.
If |comment_type| is not None, only comments of the specified type are
returned.
If |state| is not None, only issues in the specified state are returned.
This implies type="issue".
If |location_type| is not None, only issues in the specified type of
location are returned.
If |changeset| is not None, only comments against file versions that are
referenced by the specified changeset are returned. Must be combined with
|review|, and can not be combined with |commit|.
If |commit| is not None, only comments against the commit's message or
file versions referenced by the commit are returned. Must be combined
with |review|, and can not be combined with |changeset|."""
import api.impl
assert isinstance(critic, api.critic.Critic)
assert review is None or isinstance(review, api.review.Review)
assert author is None or isinstance(author, api.user.User)
assert comment_type is None or comment_type in Comment.TYPE_VALUES
assert state is None or state in Issue.STATE_VALUES
assert state is None or comment_type in (None, "issue")
assert location_type is None or location_type in Location.TYPE_VALUES
assert changeset is None or isinstance(changeset, api.changeset.Changeset)
assert changeset is None or review is not None
assert commit is None or isinstance(commit, api.commit.Commit)
assert commit is None or review is not None
assert changeset is None or commit is None
return api.impl.comment.fetchAll(critic, review, author, comment_type,
state, location_type, changeset, commit)
| [
"api.impl.comment.makeFileVersionLocation",
"api.impl.comment.fetch",
"api.impl.comment.makeCommitMessageLocation",
"api.impl.comment.fetchMany",
"api.impl.comment.fetchAll"
] | [((13046, 13088), 'api.impl.comment.fetch', 'api.impl.comment.fetch', (['critic', 'comment_id'], {}), '(critic, comment_id)\n', (13068, 13088), False, 'import api\n'), ((13376, 13423), 'api.impl.comment.fetchMany', 'api.impl.comment.fetchMany', (['critic', 'comment_ids'], {}), '(critic, comment_ids)\n', (13402, 13423), False, 'import api\n'), ((15311, 15419), 'api.impl.comment.fetchAll', 'api.impl.comment.fetchAll', (['critic', 'review', 'author', 'comment_type', 'state', 'location_type', 'changeset', 'commit'], {}), '(critic, review, author, comment_type, state,\n location_type, changeset, commit)\n', (15336, 15419), False, 'import api\n'), ((8292, 8377), 'api.impl.comment.makeCommitMessageLocation', 'api.impl.comment.makeCommitMessageLocation', (['critic', 'first_line', 'last_line', 'commit'], {}), '(critic, first_line, last_line,\n commit)\n', (8334, 8377), False, 'import api\n'), ((12726, 12832), 'api.impl.comment.makeFileVersionLocation', 'api.impl.comment.makeFileVersionLocation', (['critic', 'first_line', 'last_line', 'file', 'changeset', 'side', 'commit'], {}), '(critic, first_line, last_line,\n file, changeset, side, commit)\n', (12766, 12832), False, 'import api\n')] |
from importlib.metadata import entry_points
from setuptools import find_packages, setup
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name="flitton_fib_py",
version=("0.0.1"),
author=("KKK"),
author_email=("<EMAIL>"),
description="Calculates a Fibonacci number",
long_description= long_description,
url="...",
install_requires=[],
packages=find_packages(exclude=("tests",)),
classifiers=[
"Development Status :: 4 - Beta",
"Programming Language :: Python :: 3",
"Operating System :: OS Independent",
],
entry_points={
'console_scripts': [
'fib-number = flitton_fib_py.cmd.fib_numb:fib_numb',
],
},
python_requires='>=3',
tests_require=['pytest'],
) | [
"setuptools.find_packages"
] | [((407, 440), 'setuptools.find_packages', 'find_packages', ([], {'exclude': "('tests',)"}), "(exclude=('tests',))\n", (420, 440), False, 'from setuptools import find_packages, setup\n')] |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name = 'cardiopy',
version = "1.0.0",
author = "<NAME>",
author_email = "<EMAIL>",
description = "Analysis package for single-lead clinical EKG data",
long_description = long_description,
long_description_content_type = "text/markdown",
url="https://github.com/CardioPy/CardioPy",
packages = setuptools.find_packages(),
classifiers = [
"Programming Language :: Python :: 3",
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Intended Audience :: Science/Research",
"Topic :: Scientific/Engineering :: Medical Science Apps."
],
python_requires = '>=3.6',
install_requires = [
"datetime",
"matplotlib",
"pandas",
"scipy",
"statistics",
"mne",
"numpy",
"biosignalsnotebooks"
]
)
| [
"setuptools.find_packages"
] | [((404, 430), 'setuptools.find_packages', 'setuptools.find_packages', ([], {}), '()\n', (428, 430), False, 'import setuptools\n')] |
import flow
import tensorflow as tf
import gin
import numpy as np
import numpy.testing as npt
def test_f():
mol = gin.i_o.from_smiles.to_mol('CC')
mol = gin.deterministic.hydrogen.add_hydrogen(mol)
atoms, adjacency_map = mol
chinese_postman_routes = tf.constant(
[
[0, 1, 4, 1, 5, 1, 2, 3, 2, 7, 2, 6],
[0, 1, 4, 1, 5, 1, 2, 3, 2, 6, 2, 7],
[0, 1, 4, 1, 5, 1, 2, 6, 2, 3, 2, 7],
[0, 1, 4, 1, 5, 1, 2, 6, 2, 7, 2, 3],
[0, 1, 4, 1, 5, 1, 2, 7, 2, 6, 2, 3],
[0, 1, 4, 1, 5, 1, 2, 7, 2, 3, 2, 6],
[0, 1, 5, 1, 4, 1, 2, 3, 2, 7, 2, 6],
[0, 1, 5, 1, 4, 1, 2, 3, 2, 6, 2, 7],
[0, 1, 5, 1, 4, 1, 2, 6, 2, 3, 2, 7],
[0, 1, 5, 1, 4, 1, 2, 6, 2, 7, 2, 3],
[0, 1, 5, 1, 4, 1, 2, 7, 2, 6, 2, 3],
[0, 1, 5, 1, 4, 1, 2, 7, 2, 3, 2, 6],
[5, 1, 0, 1, 4, 1, 2, 3, 2, 7, 2, 6],
[5, 1, 0, 1, 4, 1, 2, 3, 2, 6, 2, 7],
[5, 1, 0, 1, 4, 1, 2, 6, 2, 3, 2, 7],
[5, 1, 0, 1, 4, 1, 2, 6, 2, 7, 2, 3],
[5, 1, 0, 1, 4, 1, 2, 7, 2, 6, 2, 3],
[5, 1, 0, 1, 4, 1, 2, 7, 2, 3, 2, 6],
[5, 1, 4, 1, 0, 1, 2, 3, 2, 7, 2, 6],
[5, 1, 4, 1, 0, 1, 2, 3, 2, 6, 2, 7],
[5, 1, 4, 1, 0, 1, 2, 6, 2, 3, 2, 7],
[5, 1, 4, 1, 0, 1, 2, 6, 2, 7, 2, 3],
[5, 1, 4, 1, 0, 1, 2, 7, 2, 6, 2, 3],
[5, 1, 4, 1, 0, 1, 2, 7, 2, 3, 2, 6],
[4, 1, 5, 1, 0, 1, 2, 3, 2, 7, 2, 6],
[4, 1, 5, 1, 0, 1, 2, 3, 2, 6, 2, 7],
[4, 1, 5, 1, 0, 1, 2, 6, 2, 3, 2, 7],
[4, 1, 5, 1, 0, 1, 2, 6, 2, 7, 2, 3],
[4, 1, 5, 1, 0, 1, 2, 7, 2, 6, 2, 3],
[4, 1, 5, 1, 0, 1, 2, 7, 2, 3, 2, 6],
[4, 1, 0, 1, 5, 1, 2, 3, 2, 7, 2, 6],
[4, 1, 0, 1, 5, 1, 2, 3, 2, 6, 2, 7],
[4, 1, 0, 1, 5, 1, 2, 6, 2, 3, 2, 7],
[4, 1, 0, 1, 5, 1, 2, 6, 2, 7, 2, 3],
[4, 1, 0, 1, 5, 1, 2, 7, 2, 6, 2, 3],
[4, 1, 0, 1, 5, 1, 2, 7, 2, 3, 2, 6],
],
dtype=tf.int64)
graph_flow = flow.GraphFlow(whiten=False)
z = tf.random.normal(
shape = (36, 6, 3))
x, log_det_zx = graph_flow.f_zx(z, atoms, adjacency_map, chinese_postman_routes)
z_, log_det_xz = graph_flow.f_xz(x, atoms, adjacency_map, chinese_postman_routes)
npt.assert_almost_equal(to_return_0.numpy(), to_return_1.numpy())
# x_, log_det_zx_ = graph_flow.f_zx(z_, atoms, adjacency_map, chinese_postman_routes)
# npt.assert_almost_equal(z_.numpy(), z.numpy())
# npt.assert_almost_equal(z.numpy(), z_.numpy())
# npt.assert_almost_equal(log_det_zx.numpy(), log_det_xz.numpy())
# npt.assert_almost_equal(x.numpy(), x_.numpy())
| [
"tensorflow.random.normal",
"gin.i_o.from_smiles.to_mol",
"gin.deterministic.hydrogen.add_hydrogen",
"flow.GraphFlow",
"tensorflow.constant"
] | [((120, 152), 'gin.i_o.from_smiles.to_mol', 'gin.i_o.from_smiles.to_mol', (['"""CC"""'], {}), "('CC')\n", (146, 152), False, 'import gin\n'), ((163, 207), 'gin.deterministic.hydrogen.add_hydrogen', 'gin.deterministic.hydrogen.add_hydrogen', (['mol'], {}), '(mol)\n', (202, 207), False, 'import gin\n'), ((269, 1742), 'tensorflow.constant', 'tf.constant', (['[[0, 1, 4, 1, 5, 1, 2, 3, 2, 7, 2, 6], [0, 1, 4, 1, 5, 1, 2, 3, 2, 6, 2, 7],\n [0, 1, 4, 1, 5, 1, 2, 6, 2, 3, 2, 7], [0, 1, 4, 1, 5, 1, 2, 6, 2, 7, 2,\n 3], [0, 1, 4, 1, 5, 1, 2, 7, 2, 6, 2, 3], [0, 1, 4, 1, 5, 1, 2, 7, 2, 3,\n 2, 6], [0, 1, 5, 1, 4, 1, 2, 3, 2, 7, 2, 6], [0, 1, 5, 1, 4, 1, 2, 3, 2,\n 6, 2, 7], [0, 1, 5, 1, 4, 1, 2, 6, 2, 3, 2, 7], [0, 1, 5, 1, 4, 1, 2, 6,\n 2, 7, 2, 3], [0, 1, 5, 1, 4, 1, 2, 7, 2, 6, 2, 3], [0, 1, 5, 1, 4, 1, 2,\n 7, 2, 3, 2, 6], [5, 1, 0, 1, 4, 1, 2, 3, 2, 7, 2, 6], [5, 1, 0, 1, 4, 1,\n 2, 3, 2, 6, 2, 7], [5, 1, 0, 1, 4, 1, 2, 6, 2, 3, 2, 7], [5, 1, 0, 1, 4,\n 1, 2, 6, 2, 7, 2, 3], [5, 1, 0, 1, 4, 1, 2, 7, 2, 6, 2, 3], [5, 1, 0, 1,\n 4, 1, 2, 7, 2, 3, 2, 6], [5, 1, 4, 1, 0, 1, 2, 3, 2, 7, 2, 6], [5, 1, 4,\n 1, 0, 1, 2, 3, 2, 6, 2, 7], [5, 1, 4, 1, 0, 1, 2, 6, 2, 3, 2, 7], [5, 1,\n 4, 1, 0, 1, 2, 6, 2, 7, 2, 3], [5, 1, 4, 1, 0, 1, 2, 7, 2, 6, 2, 3], [5,\n 1, 4, 1, 0, 1, 2, 7, 2, 3, 2, 6], [4, 1, 5, 1, 0, 1, 2, 3, 2, 7, 2, 6],\n [4, 1, 5, 1, 0, 1, 2, 3, 2, 6, 2, 7], [4, 1, 5, 1, 0, 1, 2, 6, 2, 3, 2,\n 7], [4, 1, 5, 1, 0, 1, 2, 6, 2, 7, 2, 3], [4, 1, 5, 1, 0, 1, 2, 7, 2, 6,\n 2, 3], [4, 1, 5, 1, 0, 1, 2, 7, 2, 3, 2, 6], [4, 1, 0, 1, 5, 1, 2, 3, 2,\n 7, 2, 6], [4, 1, 0, 1, 5, 1, 2, 3, 2, 6, 2, 7], [4, 1, 0, 1, 5, 1, 2, 6,\n 2, 3, 2, 7], [4, 1, 0, 1, 5, 1, 2, 6, 2, 7, 2, 3], [4, 1, 0, 1, 5, 1, 2,\n 7, 2, 6, 2, 3], [4, 1, 0, 1, 5, 1, 2, 7, 2, 3, 2, 6]]'], {'dtype': 'tf.int64'}), '([[0, 1, 4, 1, 5, 1, 2, 3, 2, 7, 2, 6], [0, 1, 4, 1, 5, 1, 2, 3,\n 2, 6, 2, 7], [0, 1, 4, 1, 5, 1, 2, 6, 2, 3, 2, 7], [0, 1, 4, 1, 5, 1, 2,\n 6, 2, 7, 2, 3], [0, 1, 4, 1, 5, 1, 2, 7, 2, 6, 2, 3], [0, 1, 4, 1, 5, 1,\n 2, 7, 2, 3, 2, 6], [0, 1, 5, 1, 4, 1, 2, 3, 2, 7, 2, 6], [0, 1, 5, 1, 4,\n 1, 2, 3, 2, 6, 2, 7], [0, 1, 5, 1, 4, 1, 2, 6, 2, 3, 2, 7], [0, 1, 5, 1,\n 4, 1, 2, 6, 2, 7, 2, 3], [0, 1, 5, 1, 4, 1, 2, 7, 2, 6, 2, 3], [0, 1, 5,\n 1, 4, 1, 2, 7, 2, 3, 2, 6], [5, 1, 0, 1, 4, 1, 2, 3, 2, 7, 2, 6], [5, 1,\n 0, 1, 4, 1, 2, 3, 2, 6, 2, 7], [5, 1, 0, 1, 4, 1, 2, 6, 2, 3, 2, 7], [5,\n 1, 0, 1, 4, 1, 2, 6, 2, 7, 2, 3], [5, 1, 0, 1, 4, 1, 2, 7, 2, 6, 2, 3],\n [5, 1, 0, 1, 4, 1, 2, 7, 2, 3, 2, 6], [5, 1, 4, 1, 0, 1, 2, 3, 2, 7, 2,\n 6], [5, 1, 4, 1, 0, 1, 2, 3, 2, 6, 2, 7], [5, 1, 4, 1, 0, 1, 2, 6, 2, 3,\n 2, 7], [5, 1, 4, 1, 0, 1, 2, 6, 2, 7, 2, 3], [5, 1, 4, 1, 0, 1, 2, 7, 2,\n 6, 2, 3], [5, 1, 4, 1, 0, 1, 2, 7, 2, 3, 2, 6], [4, 1, 5, 1, 0, 1, 2, 3,\n 2, 7, 2, 6], [4, 1, 5, 1, 0, 1, 2, 3, 2, 6, 2, 7], [4, 1, 5, 1, 0, 1, 2,\n 6, 2, 3, 2, 7], [4, 1, 5, 1, 0, 1, 2, 6, 2, 7, 2, 3], [4, 1, 5, 1, 0, 1,\n 2, 7, 2, 6, 2, 3], [4, 1, 5, 1, 0, 1, 2, 7, 2, 3, 2, 6], [4, 1, 0, 1, 5,\n 1, 2, 3, 2, 7, 2, 6], [4, 1, 0, 1, 5, 1, 2, 3, 2, 6, 2, 7], [4, 1, 0, 1,\n 5, 1, 2, 6, 2, 3, 2, 7], [4, 1, 0, 1, 5, 1, 2, 6, 2, 7, 2, 3], [4, 1, 0,\n 1, 5, 1, 2, 7, 2, 6, 2, 3], [4, 1, 0, 1, 5, 1, 2, 7, 2, 3, 2, 6]],\n dtype=tf.int64)\n', (280, 1742), True, 'import tensorflow as tf\n'), ((2151, 2179), 'flow.GraphFlow', 'flow.GraphFlow', ([], {'whiten': '(False)'}), '(whiten=False)\n', (2165, 2179), False, 'import flow\n'), ((2188, 2222), 'tensorflow.random.normal', 'tf.random.normal', ([], {'shape': '(36, 6, 3)'}), '(shape=(36, 6, 3))\n', (2204, 2222), True, 'import tensorflow as tf\n')] |
import factory
from factory import fuzzy
from .. import models
class RegionFactory(factory.django.DjangoModelFactory):
class Meta:
model = models.Region
name = fuzzy.FuzzyChoice(models.RegionName)
| [
"factory.fuzzy.FuzzyChoice"
] | [((180, 216), 'factory.fuzzy.FuzzyChoice', 'fuzzy.FuzzyChoice', (['models.RegionName'], {}), '(models.RegionName)\n', (197, 216), False, 'from factory import fuzzy\n')] |
INPUTPATH = "input.txt"
#INPUTPATH = "input-test.txt"
with open(INPUTPATH) as ifile:
raw = ifile.read()
program = tuple(map(int, raw.strip().split(",")))
from enum import Enum
class Mde(Enum):
POS = 0
IMM = 1
REL = 2
from itertools import chain, repeat, islice
from collections import defaultdict
from typing import Dict, Callable, List, Iterable, Optional, ClassVar
class Ico:
liv: bool
ptr: int
reb: int
mem: Dict[int, int]
cal: Callable[[], int]
log: List[int]
def __init__(
self,
prg: Iterable[int],
cal: Callable[[], int] = lambda: 0
) -> None:
self.liv = True
self.ptr = 0
self.reb = 0
self.mem = defaultdict(int, enumerate(prg))
self.cal = cal
self.log = list()
def get(self, mde: Mde) -> int:
if mde == Mde.POS: idx = self.mem[self.ptr]
elif mde == Mde.IMM: idx = self.ptr
elif mde == Mde.REL: idx = self.mem[self.ptr] + self.reb
self.ptr += 1
return idx
def ste(self) -> int:
if not self.liv: return 99
val = self.mem[self.get(Mde.IMM)]
opc = val % 100
mds = map(Mde, chain(map(int, reversed(str(val // 100))), repeat(0)))
opr = self.ops[opc]
opr(self, *map(self.get, islice(mds, opr.__code__.co_argcount - 1)))
return opc
def run(self) -> List[int]:
while self.liv: self.ste()
return self.log
def add(self, idx: int, jdx: int, kdx: int) -> None:
self.mem[kdx] = self.mem[idx] + self.mem[jdx]
def mul(self, idx: int, jdx: int, kdx: int) -> None:
self.mem[kdx] = self.mem[idx] * self.mem[jdx]
def inp(self, idx: int) -> None:
self.mem[idx] = self.cal()
def out(self, idx: int) -> None:
self.log.append(self.mem[idx])
def jit(self, idx: int, jdx: int) -> None:
if self.mem[idx]: self.ptr = self.mem[jdx]
def jif(self, idx: int, jdx: int) -> None:
if not self.mem[idx]: self.ptr = self.mem[jdx]
def les(self, idx: int, jdx: int, kdx: int) -> None:
self.mem[kdx] = int(self.mem[idx] < self.mem[jdx])
def equ(self, idx: int, jdx: int, kdx: int) -> None:
self.mem[kdx] = int(self.mem[idx] == self.mem[jdx])
def adj(self, idx: int) -> None:
self.reb += self.mem[idx]
def hal(self) -> None:
self.liv = False
ops: ClassVar[Dict[int, Callable[..., None]]] = {
1: add,
2: mul,
3: inp,
4: out,
5: jit,
6: jif,
7: les,
8: equ,
9: adj,
99: hal
}
from typing import Tuple
class ArcadeCabinet:
ico: Ico
index: int
screen: Dict[Tuple[int, int], int]
score: int
auto: bool
tile_to_char: ClassVar[Dict[int, str]] = {
0: " ",
1: "|",
2: "#",
3: "_",
4: "o"
}
char_to_joystick: ClassVar[Dict[str, int]] = {
"a": -1,
"s": 0,
"d": 1
}
def __init__(self, program: Iterable[int], auto: bool = True) -> None:
self.ico = Ico(program)
self.ico.cal = self
self.index = 0
self.screen = defaultdict(int)
self.score = 0
self.auto = auto
def __call__(self) -> int:
self.consume_log()
if self.auto:
return 0
else:
return self.prompt_joystick()
def __str__(self) -> str:
indexes, jndexes = zip(*self.screen)
return "\n".join(
"".join(
self.tile_to_char[self.screen[i, j]]
for j in range(min(jndexes), max(jndexes) + 1)
)
for i in range(min(indexes), max(indexes) + 1)
)
def run(self) -> None:
self.ico.run()
self.consume_log()
def consume_log(self) -> None:
while self.index < len(self.ico.log):
j, i, value = self.ico.log[self.index: self.index + 3]
if (j, i) == (-1, 0): self.score = value
else: self.screen[i, j] = value
self.index += 3
def prompt_joystick(self) -> int:
print(self)
msg = f"<{'|'.join(self.char_to_joystick)}>: "
while (j := self.char_to_joystick.get(input(msg))) is None: pass
return j
demo = ArcadeCabinet(program)
demo.run()
print(sum(1 for tile in demo.screen.values() if tile == 2))
game = ArcadeCabinet((2,) + program[1:], False)
game.run()
print(game.score)
| [
"itertools.islice",
"collections.defaultdict",
"itertools.repeat"
] | [((2725, 2741), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (2736, 2741), False, 'from collections import defaultdict\n'), ((1073, 1082), 'itertools.repeat', 'repeat', (['(0)'], {}), '(0)\n', (1079, 1082), False, 'from itertools import chain, repeat, islice\n'), ((1134, 1175), 'itertools.islice', 'islice', (['mds', '(opr.__code__.co_argcount - 1)'], {}), '(mds, opr.__code__.co_argcount - 1)\n', (1140, 1175), False, 'from itertools import chain, repeat, islice\n')] |
""" This example sends a simple query to the ARAX API.
A one-line curl equivalent is:
curl -X POST "https://arax.ncats.io/devED/api/arax/v1.0/query?bypass_cache=false" -H "accept: application/json" -H "Content-Type: application/json" -d "{\"asynchronous\":\"stream\",\"message\":{\"query_graph\":{\"edges\":{\"e00\":{\"subject\":\"n00\",\"object\":\"n01\",\"predicate\":\"biolink:physically_interacts_with\"}},\"nodes\":{\"n00\":{\"id\":\"CHEMBL.COMPOUND:CHEMBL112\",\"category\":\"biolink:ChemicalSubstance\"},\"n01\":{\"category\":\"biolink:Protein\"}}}}}"
To trigger a streaming response of progress, try this:
curl -X POST "https://arax.ncats.io/devED/api/arax/v1.0/query?bypass_cache=false" -H "accept: application/json" -H "Content-Type: application/json" -d "{\"asynchronous\"\"stream\",\"message\":{\"query_graph\":{\"edges\":{\"e00\":{\"subject\":\"n00\",\"object\":\"n01\",\"predicate\":\"biolink:physically_interacts_with\"}},\"nodes\":{\"n00\":{\"id\":\"CHEMBL.COMPOUND:CHEMBL112\",\"category\":\"biolink:ChemicalSubstance\"},\"n01\":{\"category\":\"biolink:Protein\"}}}}}"
"""
#### Import some needed modules
import requests
import json
import re
# Set the base URL for the ARAX reasoner and its endpoint
endpoint_url = 'https://arax.ncats.io/devED/api/arax/v1.0/query'
#### Create a dict of the request, specifying the query type and its parameters
#### Note that predicates and categories must have the biolink: prefix to be valid
query = { "message": {
"query_graph": {
"edges": {
"e00": {
"subject": "n00",
"object": "n01",
"predicate": "biolink:physically_interacts_with"
}
},
"nodes": {
"n00": {
"id": "CHEMBL.COMPOUND:CHEMBL112",
"category": "biolink:ChemicalSubstance"
},
"n01": {
"category": "biolink:Protein"
}
}
}
}}
# Send the request to RTX and check the status
response_content = requests.post(endpoint_url, json=query, headers={'accept': 'application/json'})
status_code = response_content.status_code
if status_code != 200:
print("ERROR returned with status "+str(status_code))
print(response_content.json())
exit()
#### Unpack the response content into a dict
response_dict = response_content.json()
#print(json.dumps(response_dict, indent=4, sort_keys=True))
# Display the information log
for message in response_dict['logs']:
if message['level'] != 'DEBUG':
print(f"{message['timestamp']}: {message['level']}: {message['message']}")
# Display the results
print("Results:")
for result in response_dict['message']['results']:
confidence = result['confidence']
if confidence is None:
confidence = 0.0
print(" -" + '{:6.3f}'.format(confidence) + f"\t{result['essence']}")
# These URLs provide direct access to resulting data and GUI
print(f"Data: {response_dict['id']}")
if response_dict['id'] is not None:
match = re.search(r'(\d+)$', response_dict['id'])
if match:
print(f"GUI: https://arax.ncats.io/?r={match.group(1)}")
# Also print the operations actions
print(f"Executed operations:")
if 'operations' in response_dict and response_dict['operations'] is not None:
if 'actions' in response_dict['operations'] and response_dict['operations']['actions'] is not None:
for action in response_dict['operations']['actions']:
print(f" - {action}")
| [
"requests.post",
"re.search"
] | [((2026, 2105), 'requests.post', 'requests.post', (['endpoint_url'], {'json': 'query', 'headers': "{'accept': 'application/json'}"}), "(endpoint_url, json=query, headers={'accept': 'application/json'})\n", (2039, 2105), False, 'import requests\n'), ((3016, 3057), 're.search', 're.search', (['"""(\\\\d+)$"""', "response_dict['id']"], {}), "('(\\\\d+)$', response_dict['id'])\n", (3025, 3057), False, 'import re\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from lxml import html
class JREast:
URL = 'http://traininfo.jreast.co.jp/train_info/{}.aspx'
lines = {
'kanto': ('東海道線', '京浜東北線', '横須賀線', '南武線', '横浜線',
'伊東線', '相模線', '鶴見線',
'宇都宮線', '高崎線', '京浜東北線', '埼京線', '川越線',
'武蔵野線', '上越線', '信越本線', '吾妻線', '烏山線',
'八高線', '日光線', '両毛線',
'中央線快速電車', '中央・総武各駅停車', '中央本線',
'武蔵野線', '五日市線', '青梅線', '八高線', '小海線',
'常磐線', '常磐線快速電車', '常磐線各駅停車', '水郡線',
'水戸線',
'総武快速線', '総武本線', '中央・総武各駅停車', '京葉線',
'武蔵野線', '内房線', '鹿島線', '久留里線', '外房線',
'東金線', '成田線',
'山手線',
'上野東京ライン', '湘南新宿ライン'),
'tohoku': ('羽越本線', '奥羽本線', '奥羽本線(山形線)', '常磐線',
'仙山線', '仙石線', '仙石東北ライン', '東北本線',
'磐越西線', '左沢線', '石巻線', '大船渡線',
'大船渡線BRT', '大湊線', '男鹿線', '釜石線', '北上線',
'気仙沼線', '気仙沼線BRT', '五能線', '水郡線',
'田沢湖線', '只見線', '津軽線', '八戸線', '花輪線',
'磐越東線', '山田線', '米坂線', '陸羽西線', '陸羽東線'),
'shinetsu': ('羽越本線', '信越本線', '上越線', '篠ノ井線', '中央本線',
'白新線', '磐越西線', '飯山線', '越後線', '大糸線',
'小海線', '只見線', '弥彦線', '米坂線')
}
def _extract_status(self, th):
s = {}
td = th.getnext()
s['status'] = td.xpath('img')[0].attrib['alt']
if s['status'] != '平常運転':
td = td.getnext()
s['publishedAt'] = td.text.strip()
td = th.getparent().getnext().xpath('td[@class="cause"]')[0]
s['detail'] = td.text.strip()
return s
def status(self, line):
self.area = None
for area in JREast.lines:
for l in JREast.lines[area]:
if l == line:
self.area = area
break
if self.area:
break
m = {'area': self.area, 'line': line, 'statuses': []}
if self.area:
url = JREast.URL.format(self.area)
else:
return m
dom = html.parse(url)
th = None
for node in dom.xpath('//th[@class="text-tit-xlarge"]'):
if node.text.strip() == line:
m['statuses'].append(self._extract_status(node))
return m
if __name__ == '__main__':
import pprint
jr = JREast()
pprint.pprint(jr.status('山田線'))
pprint.pprint(jr.status('京葉線'))
| [
"lxml.html.parse"
] | [((2200, 2215), 'lxml.html.parse', 'html.parse', (['url'], {}), '(url)\n', (2210, 2215), False, 'from lxml import html\n')] |
import datetime
from django.db import models
from django.utils import timezone
class Question( models.Model):
question_text = models.CharField( max_length=200 )
pub_date = models.DateTimeField( 'date published' )
def __str__( self ):
return self.question_text
def was_published_recently( self ):
return self.pub_date >= timezone.now() - datetime.timedelta( days=1 )
was_published_recently.admin_order_field = 'pub_date'
was_published_recently.boolean = True
was_published_recently.short_description = 'Published recently?'
class Choice(models.Model):
question = models.ForeignKey( Question, on_delete=models.CASCADE )
choice_text = models.CharField( max_length=200 )
votes = models.IntegerField( default=0 )
def __str__( self ):
return self.choice_text
| [
"django.db.models.IntegerField",
"django.db.models.ForeignKey",
"django.utils.timezone.now",
"django.db.models.DateTimeField",
"datetime.timedelta",
"django.db.models.CharField"
] | [((130, 162), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(200)'}), '(max_length=200)\n', (146, 162), False, 'from django.db import models\n'), ((178, 216), 'django.db.models.DateTimeField', 'models.DateTimeField', (['"""date published"""'], {}), "('date published')\n", (198, 216), False, 'from django.db import models\n'), ((593, 646), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Question'], {'on_delete': 'models.CASCADE'}), '(Question, on_delete=models.CASCADE)\n', (610, 646), False, 'from django.db import models\n'), ((665, 697), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(200)'}), '(max_length=200)\n', (681, 697), False, 'from django.db import models\n'), ((710, 740), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'default': '(0)'}), '(default=0)\n', (729, 740), False, 'from django.db import models\n'), ((340, 354), 'django.utils.timezone.now', 'timezone.now', ([], {}), '()\n', (352, 354), False, 'from django.utils import timezone\n'), ((357, 383), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': '(1)'}), '(days=1)\n', (375, 383), False, 'import datetime\n')] |
# Generated by Django 3.2.7 on 2021-10-30 10:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('market', '0004_auto_20211029_1856'),
]
operations = [
migrations.AddField(
model_name='fiat_details',
name='account_name',
field=models.CharField(default='None', max_length=50),
),
]
| [
"django.db.models.CharField"
] | [((345, 392), 'django.db.models.CharField', 'models.CharField', ([], {'default': '"""None"""', 'max_length': '(50)'}), "(default='None', max_length=50)\n", (361, 392), False, 'from django.db import migrations, models\n')] |
from skfem import *
from skfem.helpers import dot, grad
# # enable additional mesh validity checks, sacrificing performance
# import logging
# logging.basicConfig(format='%(levelname)s %(asctime)s %(name)s %(message)s')
# logging.getLogger('skfem').setLevel(logging.DEBUG)
# create the mesh
m = MeshTri().refined(4)
# or, with your own points and cells:
# m = MeshTri(points, cells)
e = ElementTriP1()
basis = Basis(m, e)
# this method could also be imported from skfem.models.laplace
@BilinearForm
def laplace(u, v, _):
return dot(grad(u), grad(v))
# this method could also be imported from skfem.models.unit_load
@LinearForm
def rhs(v, _):
return 1.0 * v
A = asm(laplace, basis)
b = asm(rhs, basis)
# or:
# A = laplace.assemble(basis)
# b = rhs.assemble(basis)
# enforce Dirichlet boundary conditions
A, b = enforce(A, b, D=m.boundary_nodes())
# solve -- can be anything that takes a sparse matrix and a right-hand side
x = solve(A, b)
if __name__ == "__main__":
from os.path import splitext
from sys import argv
from skfem.visuals.matplotlib import plot, savefig
plot(m, x, shading='gouraud', colorbar=True)
savefig(splitext(argv[0])[0] + '_solution.png')
| [
"skfem.helpers.grad",
"os.path.splitext",
"skfem.visuals.matplotlib.plot"
] | [((1101, 1145), 'skfem.visuals.matplotlib.plot', 'plot', (['m', 'x'], {'shading': '"""gouraud"""', 'colorbar': '(True)'}), "(m, x, shading='gouraud', colorbar=True)\n", (1105, 1145), False, 'from skfem.visuals.matplotlib import plot, savefig\n'), ((540, 547), 'skfem.helpers.grad', 'grad', (['u'], {}), '(u)\n', (544, 547), False, 'from skfem.helpers import dot, grad\n'), ((549, 556), 'skfem.helpers.grad', 'grad', (['v'], {}), '(v)\n', (553, 556), False, 'from skfem.helpers import dot, grad\n'), ((1158, 1175), 'os.path.splitext', 'splitext', (['argv[0]'], {}), '(argv[0])\n', (1166, 1175), False, 'from os.path import splitext\n')] |
import xrootdpyfs
import pdb
from subprocess import call, PIPE
import os
from fs.opener import opener
def connect_test():
"""Do some test connecting awww yeahhhh"""
kdestroy()
# `klist` is empty (returns 0 when not empty)
with open(os.devnull, 'wb') as discard:
call(['klist'], stdout=discard,
stderr=discard)
# pdb.set_trace()
kinit_via_tab('cern.butts', 'otrondru')
xrdfs, path = connect()
assert xrdfs
def connect():
"""Connect to the EOS server thingy."""
remote_root = "root://eosuser.cern.ch"
remote_dir = "//eos/user/o/otrondru/"
return opener.parse(remote_root + remote_dir)
def kinit_via_tab(keytab, principal):
"""Get a kerberos ticket via a keytab."""
cmd = ['kinit', '-t', keytab, principal]
call_discard(cmd)
def kdestroy():
"""Destroy kerberos tickets on system."""
call_discard(['kdestroy'])
def call_discard(cmd):
"""Call `cmd` and discard the stderr and -out."""
with open(os.devnull, 'wb') as discard:
call(cmd, stdout=discard,
stderr=discard)
if __name__ == '__main__':
connect_test()
| [
"fs.opener.opener.parse",
"subprocess.call"
] | [((621, 659), 'fs.opener.opener.parse', 'opener.parse', (['(remote_root + remote_dir)'], {}), '(remote_root + remote_dir)\n', (633, 659), False, 'from fs.opener import opener\n'), ((290, 337), 'subprocess.call', 'call', (["['klist']"], {'stdout': 'discard', 'stderr': 'discard'}), "(['klist'], stdout=discard, stderr=discard)\n", (294, 337), False, 'from subprocess import call, PIPE\n'), ((1039, 1080), 'subprocess.call', 'call', (['cmd'], {'stdout': 'discard', 'stderr': 'discard'}), '(cmd, stdout=discard, stderr=discard)\n', (1043, 1080), False, 'from subprocess import call, PIPE\n')] |
#!/usr/bin/python3
'''
Simple q-learning algorithm implementation
MIT License
Copyright (c) 2019 <NAME> (<EMAIL>)
See LICENSE file
'''
import random
import logging
import pickle
dataset = {}
history = []
model_filename = 'data/.deepq.pickle'
logger = logging.getLogger(__name__)
try:
dataset = pickle.load( open( model_filename , "rb" ) )
except FileNotFoundError:
pickle.dump( dataset , open( model_filename , "wb" ) )
def get_features(data,act):
features_bin = 0
board = data.copy()
board[act] = 1
for p in range(0,9):
features_bin = features_bin << 2
if board[p] == 1:
features_bin = features_bin | 0x01
if board[p] == -1:
features_bin = features_bin | 0x02
return features_bin
def rebuild_q_table(history,award):
global dataset
GRADIENT = 0.90
gamma = 1
logger.debug("[RECALCQ]Process award %s" % (award))
data_list = pickle.load( open( model_filename , "rb" ) )
for f in reversed(history):
score = gamma * award;
''' Use simple moving avarage'''
logger.debug("[RECALCQ]Process history prev score %s(%s)" % (f,dataset.get(f,0)))
dataset[f] = dataset.get(f,0) + score
logger.debug("[RECALCQ]Process history %s Score %s(%s)" % (f,score,dataset[f]))
gamma = gamma * GRADIENT
pickle.dump( dataset , open( model_filename , "wb" ) )
def update_stats(board,winner):
global history
award = 0.5 #Draw is still good
if winner == 1:
award = 1
if winner == -1:
award = -1
rebuild_q_table(history,award)
history.clear()
def make_move(board):
logger.debug("[MAKEMOVE]Process board : %s" % board)
scores = []
for p in range(0,9):
if board[p] != 0:
continue
f = get_features(board,p)
scores.append((p, dataset.get(f,0),f))
best_score = max(scores,key=lambda tup: tup[1])[1]
logger.debug("[MAKEMOVE]Scores : %s Max: %s" % (scores,best_score) );
actions = [ (p[0],p[2]) for p in scores if p[1] == best_score]
#Curiosity makes me smarter.
if best_score != 0:
curiosity = [ (p[0],p[2]) for p in scores if p[1] > -1 and p[1] < best_score ]
if(len(curiosity) > 0):
logger.debug("[MAKEMOVE][CURIOSITY]Scores : %s" % (curiosity) );
actions = actions + curiosity
#Select random from all avaliable moves
logger.debug("[MAKEMOVE]Best : %s" % actions )
act = random.choice (actions)
history.append(int(act[1]))
logger.debug("[MAKEMOVE]Selected action : %s" % act[0] )
return act[0]
if __name__ == '__main__':
import sys,os
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
logger.addHandler( logging.StreamHandler(sys.stdout) )
board = [-1,-1,-1,0,0,0,1,1,0]
print( make_move(board) )
| [
"logging.getLogger",
"random.choice",
"logging.StreamHandler"
] | [((259, 286), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (276, 286), False, 'import logging\n'), ((2506, 2528), 'random.choice', 'random.choice', (['actions'], {}), '(actions)\n', (2519, 2528), False, 'import random\n'), ((2703, 2722), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (2720, 2722), False, 'import logging\n'), ((2781, 2814), 'logging.StreamHandler', 'logging.StreamHandler', (['sys.stdout'], {}), '(sys.stdout)\n', (2802, 2814), False, 'import logging\n')] |
import tensorflow as tf
import tfcoreml
from coremltools.proto import FeatureTypes_pb2 as _FeatureTypes_pb2
import coremltools
"""FIND GRAPH INFO"""
tf_model_path = "./graph.pb"
with open(tf_model_path, "rb") as f:
serialized = f.read()
tf.reset_default_graph()
original_gdef = tf.GraphDef()
original_gdef.ParseFromString(serialized)
with tf.Graph().as_default() as g:
tf.import_graph_def(original_gdef, name="")
ops = g.get_operations()
N = len(ops)
for i in [0, 1, 2, N - 3, N - 2, N - 1]:
print('\n\nop id {} : op type: "{}"'.format(str(i), ops[i].type))
print("input(s):")
for x in ops[i].inputs:
print("name = {}, shape: {}, ".format(x.name, x.get_shape()))
print("\noutput(s):"),
for x in ops[i].outputs:
print("name = {}, shape: {},".format(x.name, x.get_shape()))
| [
"tensorflow.import_graph_def",
"tensorflow.Graph",
"tensorflow.reset_default_graph",
"tensorflow.GraphDef"
] | [((242, 266), 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), '()\n', (264, 266), True, 'import tensorflow as tf\n'), ((283, 296), 'tensorflow.GraphDef', 'tf.GraphDef', ([], {}), '()\n', (294, 296), True, 'import tensorflow as tf\n'), ((379, 422), 'tensorflow.import_graph_def', 'tf.import_graph_def', (['original_gdef'], {'name': '""""""'}), "(original_gdef, name='')\n", (398, 422), True, 'import tensorflow as tf\n'), ((345, 355), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (353, 355), True, 'import tensorflow as tf\n')] |
from django.db import models
# from django import forms
from django.contrib.auth.models import User, Group
from rest_framework import serializers
from .models import Call, Album
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'password', 'first_name', 'last_name', 'email', 'groups')
class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Group
fields = ('url', 'name')
class EmployeeSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'first_name', 'last_name', 'email', 'groups')
class CallSerializer(serializers.ModelSerializer):
class Meta:
model = User
class BillSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Group
fields = ('url', 'name')
class PriceSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Group
fields = ('url', 'name')
class AlbumSerializer(serializers.ModelSerializer):
tracks = serializers.StringRelatedField(many=True)
class Meta:
model = Album
fields = ('album_name', 'artist', 'tracks')
# fields = ('url', 'username')
class PhoneSerializer(serializers.ModelSerializer):
class Meta:
model = Call
fields = ('url', 'record_type', 'call_identifier', 'origin_phone_number',
'destination_phone_number', 'record_timestamp', 'duration') | [
"rest_framework.serializers.StringRelatedField"
] | [((1127, 1168), 'rest_framework.serializers.StringRelatedField', 'serializers.StringRelatedField', ([], {'many': '(True)'}), '(many=True)\n', (1157, 1168), False, 'from rest_framework import serializers\n')] |
from rest_framework import viewsets
from .serializers import TeamSerializer
from .models import Team
from django.core.exceptions import PermissionDenied
class TeamViewSet(viewsets.ModelViewSet):
serializer_class = TeamSerializer
queryset = Team.objects.all()
def get_queryset(self):
teams = self.request.user.teams.all()
if not teams:
Team.objects.create(name='', org_number='', created_by=self.request.user)
return self.queryset.filter(created_by=self.request.user)
def perform_create(self, serializer):
serializer.save(created_by=self.request.user)
def perform_update(self, serializer):
obj = self.get_object()
if self.request.user != obj.created_by:
raise PermissionDenied('Wrong object owner')
serializer.save() | [
"django.core.exceptions.PermissionDenied"
] | [((776, 814), 'django.core.exceptions.PermissionDenied', 'PermissionDenied', (['"""Wrong object owner"""'], {}), "('Wrong object owner')\n", (792, 814), False, 'from django.core.exceptions import PermissionDenied\n')] |
def main():
from matplotlib import rc
rc('backend', qt4="PySide")
import automator, sys
try:
mainGui = automator.Automator()
except SystemExit:
del mainGui
sys.exit()
exit
# Instantiate a class
if __name__ == '__main__': # Windows multiprocessing safety
main()
| [
"sys.exit",
"matplotlib.rc",
"automator.Automator"
] | [((47, 74), 'matplotlib.rc', 'rc', (['"""backend"""'], {'qt4': '"""PySide"""'}), "('backend', qt4='PySide')\n", (49, 74), False, 'from matplotlib import rc\n'), ((133, 154), 'automator.Automator', 'automator.Automator', ([], {}), '()\n', (152, 154), False, 'import automator, sys\n'), ((206, 216), 'sys.exit', 'sys.exit', ([], {}), '()\n', (214, 216), False, 'import automator, sys\n')] |
from collections import OrderedDict
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.utils.data import DataLoader
torch.set_printoptions(linewidth=120)
torch.set_grad_enabled(True)
import torchvision
from torchvision.transforms import transforms
import sys
sys.path.append("..")
from base.base_net import BaseNet
class ResBlock(nn.Module):
"""
A two-convolutional layer residual block.
"""
def __init__(self, c_in, c_out, k, s=1, p=1, mode='encode'):
assert mode in ['encode', 'decode'], "Mode must be either 'encode' or 'decode'."
super(ResBlock, self).__init__()
if mode == 'encode':
self.conv1 = nn.Conv2d(c_in, c_out, k, s, p, bias=False)
self.conv2 = nn.Conv2d(c_out, c_out, 3, 1, 1, bias=False)
elif mode == 'decode':
self.conv1 = nn.ConvTranspose2d(c_in, c_out, k, s, p, bias=False)
self.conv2 = nn.ConvTranspose2d(c_out, c_out, 3, 1, 1, bias=False)
self.relu = nn.ReLU()
self.BN = nn.BatchNorm2d(c_out)
self.resize = s > 1 or (s == 1 and p == 0) or c_out != c_in
def forward(self, x):
conv1 = self.BN(self.conv1(x))
relu = self.relu(conv1)
conv2 = self.BN(self.conv2(relu))
if self.resize:
x = self.BN(self.conv1(x))
return self.relu(x + conv2)
class Encoder(BaseNet):
"""
Encoder class, mainly consisting of three residual blocks.
"""
def __init__(self):
super(Encoder, self).__init__()
self.rep_dim = 100
self.init_conv = nn.Conv2d(1, 16, 3, 1, 1, bias=False)
self.BN = nn.BatchNorm2d(16)
self.rb1 = ResBlock(16, 16, 3, 2, 1, 'encode')
self.rb2 = ResBlock(16, 32, 3, 1, 1, 'encode')
self.rb3 = ResBlock(32, 32, 3, 2, 1, 'encode')
self.rb4 = ResBlock(32, 48, 3, 1, 1, 'encode')
self.rb5 = ResBlock(48, 48, 3, 2, 1, 'encode')
self.rb6 = ResBlock(48, 2, 3, 2, 1, 'encode')
self.fc1 = nn.Linear(2 * 40 * 40, self.rep_dim, bias=False)
self.relu = nn.ReLU()
def forward(self, inputs):
init_conv = self.relu(self.BN(self.init_conv(inputs)))
rb1 = self.rb1(init_conv)
rb2 = self.rb2(rb1)
rb3 = self.rb3(rb2)
rb4 = self.rb4(rb3)
rb5 = self.rb5(rb4)
rb6 = self.rb6(rb5)
x = rb6.view(rb6.size(0),-1)
x = self.fc1(x)
return x
class Decoder(nn.Module):
"""
Decoder class, mainly consisting of two residual blocks.
"""
def __init__(self):
super(Decoder, self).__init__()
self.rep_dim = 100
self.fc1 = nn.Linear(self.rep_dim, 2 * 40 * 40, bias=False)
self.rb1 = ResBlock(2, 48, 2, 2, 0, 'decode') # 48 4 4
self.rb2 = ResBlock(48, 48, 2, 2, 0, 'decode') # 48 8 8
self.rb3 = ResBlock(48, 32, 3, 1, 1, 'decode') # 32 8 8
self.rb4 = ResBlock(32, 32, 2, 2, 0, 'decode') # 32 16 16
self.rb5 = ResBlock(32, 16, 3, 1, 1, 'decode') # 16 16 16
self.rb6 = ResBlock(16, 16, 2, 2, 0, 'decode') # 16 32 32
self.out_conv = nn.ConvTranspose2d(16, 1, 3, 1, 1, bias=False) # 3 32 32
self.tanh = nn.Tanh()
def forward(self, inputs):
fc1 = self.fc1(inputs)
fc1 = fc1.view(fc1.size(0), 2, 40, 40)
rb1 = self.rb1(fc1)
rb2 = self.rb2(rb1)
rb3 = self.rb3(rb2)
rb4 = self.rb4(rb3)
rb5 = self.rb5(rb4)
rb6 = self.rb6(rb5)
out_conv = self.out_conv(rb6)
output = self.tanh(out_conv)
return output
class Autoencoder(BaseNet):
"""
Autoencoder class, combines encoder and decoder model.
"""
def __init__(self):
super(Autoencoder, self).__init__()
self.encoder = Encoder()
self.decoder = Decoder()
# @property
# def num_params(self):
# model_parameters = filter(lambda p: p.requires_grad, self.parameters())
# num_p = sum([np.prod(p.size()) for p in model_parameters])
# return num_p
def forward(self, inputs):
encoded = self.encoder(inputs)
decoded = self.decoder(encoded)
return decoded | [
"torch.nn.ConvTranspose2d",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU",
"torch.nn.Tanh",
"torch.set_printoptions",
"torch.nn.Conv2d",
"torch.nn.Linear",
"torch.set_grad_enabled",
"sys.path.append"
] | [((192, 229), 'torch.set_printoptions', 'torch.set_printoptions', ([], {'linewidth': '(120)'}), '(linewidth=120)\n', (214, 229), False, 'import torch\n'), ((230, 258), 'torch.set_grad_enabled', 'torch.set_grad_enabled', (['(True)'], {}), '(True)\n', (252, 258), False, 'import torch\n'), ((337, 358), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (352, 358), False, 'import sys\n'), ((1060, 1069), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (1067, 1069), True, 'import torch.nn as nn\n'), ((1088, 1109), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['c_out'], {}), '(c_out)\n', (1102, 1109), True, 'import torch.nn as nn\n'), ((1660, 1697), 'torch.nn.Conv2d', 'nn.Conv2d', (['(1)', '(16)', '(3)', '(1)', '(1)'], {'bias': '(False)'}), '(1, 16, 3, 1, 1, bias=False)\n', (1669, 1697), True, 'import torch.nn as nn\n'), ((1717, 1735), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['(16)'], {}), '(16)\n', (1731, 1735), True, 'import torch.nn as nn\n'), ((2088, 2136), 'torch.nn.Linear', 'nn.Linear', (['(2 * 40 * 40)', 'self.rep_dim'], {'bias': '(False)'}), '(2 * 40 * 40, self.rep_dim, bias=False)\n', (2097, 2136), True, 'import torch.nn as nn\n'), ((2157, 2166), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (2164, 2166), True, 'import torch.nn as nn\n'), ((2746, 2794), 'torch.nn.Linear', 'nn.Linear', (['self.rep_dim', '(2 * 40 * 40)'], {'bias': '(False)'}), '(self.rep_dim, 2 * 40 * 40, bias=False)\n', (2755, 2794), True, 'import torch.nn as nn\n'), ((3208, 3254), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', (['(16)', '(1)', '(3)', '(1)', '(1)'], {'bias': '(False)'}), '(16, 1, 3, 1, 1, bias=False)\n', (3226, 3254), True, 'import torch.nn as nn\n'), ((3285, 3294), 'torch.nn.Tanh', 'nn.Tanh', ([], {}), '()\n', (3292, 3294), True, 'import torch.nn as nn\n'), ((738, 781), 'torch.nn.Conv2d', 'nn.Conv2d', (['c_in', 'c_out', 'k', 's', 'p'], {'bias': '(False)'}), '(c_in, c_out, k, s, p, bias=False)\n', (747, 781), True, 'import torch.nn as nn\n'), ((807, 851), 'torch.nn.Conv2d', 'nn.Conv2d', (['c_out', 'c_out', '(3)', '(1)', '(1)'], {'bias': '(False)'}), '(c_out, c_out, 3, 1, 1, bias=False)\n', (816, 851), True, 'import torch.nn as nn\n'), ((908, 960), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', (['c_in', 'c_out', 'k', 's', 'p'], {'bias': '(False)'}), '(c_in, c_out, k, s, p, bias=False)\n', (926, 960), True, 'import torch.nn as nn\n'), ((986, 1039), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', (['c_out', 'c_out', '(3)', '(1)', '(1)'], {'bias': '(False)'}), '(c_out, c_out, 3, 1, 1, bias=False)\n', (1004, 1039), True, 'import torch.nn as nn\n')] |
import operator
def pozicijaSprite(broj, x_velicina):
#vraca pixel na kojem se sprite nalazi
pixel = broj * (x_velicina + 1) #1 je prazan red izmedu spritova
return(pixel)
#spriteSlova = ["A", "B", "C", "D", "E", "F", "G", "H", "i", "s", "e"]
spriteSlova = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "s", ",", "'", "1", "2", "4", "8", "6", "3", ".", "5", "7", "9", "0", "M", "B", "I", "N", "S", "E", "R", "T", " ", "-", "V","U" ,"A", "L", "O", "D", ":", "m", "j", "n", "u", "C", "H", "k", "l", "o", "p", "r", "t", "v", "z", "K", "P", "%", "/"]
def pixel2Ton(pixel):
rezolucija = 90
indent = -12 #extra pixeli
height = 3
broj = ( rezolucija - pixel - indent ) / height
return(int(broj))
predikati = {
0 : 0,
1 : -1,
2 : 1,
3 : 0
}
kljucevi = {
0 : ("d", ",,"),
1 : ("e", ",,"),
2 : ("f", ",,"),
3 : ("g", ",,"),
4 : ("a", ",,"),
5 : ("h", ",,"),
6 : ("c", ","),
7 : ("d", ","),
8 : ("e", ","),
9 : ("f", ","),
10 : ("g", ","),
11 : ("a", ","),
12 : ("h", ","),
13 : ("c", ""),
14 : ("d", ""),
15 : ("e", ""),
16 : ("f", ""),
17 : ("g", ""),
18 : ("a", ""),
19 : ("h", ""),
20 : ("c", "'"),
21 : ("d", "'"),
22 : ("e", "'"),
23 : ("f", "'"),
24 : ("g", "'"),
25 : ("a", "'"),
26 : ("h", "'"),
27 : ("c", "''"),
28 : ("d", "''"),
29 : ("e", "''"),
30 : ("f", "''"),
31 : ("g", "''"),
32 : ("a", "''"),
33 : ("h", "''"),
34 : ("c", "'''"),
35 : ("d", "'''"),
36 : ("e", "'''"),
37 : ("f", "'''"),
38 : ("g", "'''"),
39 : ("a", "'''"),
40 : ("h", "'''")
}
def removeLily(slovo):
return(slovo.replace(',', '').replace('\'', '').upper())
def slovoPozicija(slovo):
for i in [i for i,x in enumerate(spriteSlova) if x == slovo]:
return(i)
rijecnikNotnihVrijednosti = {
0 : "16",
1 : "8",
2 : "8.",
3 : "4",
4 : "416",
5 : "4.",
6 : "4.16",
7 : "2",
8 : "216",
9 : "28",
10 : "28.",
11 : "2.",
12 : "2.16",
13 : "2.8",
14 : "2.8.",
15 : "1"
}
def pixel2Pozicija(pixel):
rezolucija = 90
indent = 19 #extra pixeli
width = 6
broj = ( pixel - indent ) / width
return(int(broj))
def pixel2Trajanje(pixel):
indent = 4
width = 6
broj = ( pixel - indent ) / width
return(int(broj))
def ton2Pixel(ton):
rezolucija = 90
indent = -12
height = 3
pixel = rezolucija - indent - ( ton * height )
return(pixel)
def pozicija2Pixel(pozicija):
rezolucija = 90
indent = 19 #extra pixeli
width = 6
pixel = pozicija * width + indent
return(pixel)
def trajanje2Pixel(trajanje):
indent = 4
width = 6
pixel = trajanje * width + indent
return(pixel)
class dodaj_notu(object):
def __init__(self, pozicija, ton, trajanje, predikat):
self.pozicija=pozicija
self.ton=ton
self.trajanje=trajanje
self.predikat=predikat
self.ligatura=False
class add_chord(object):
def __init__(self, pozicija, ton, trajanje, predikat):
self.pozicija=pozicija
self.ton=ton
self.trajanje=trajanje
self.predikat=predikat
self.ligatura=False
class add_markup(object):
def __init__(self, pozicija, ton, trajanje, predikat):
self.pozicija=pozicija
self.ton=ton
self.trajanje=trajanje
self.predikat=predikat
self.ligatura=False
class cursor(object):
def __init__(self, pozicija, ton, trajanje):
self.pozicija = pozicija
self.ton = ton
self.trajanje = trajanje
self.sprite = 0
self.bg_scroll_x = 0
self.bg_scroll_y = 0
self.bg_scroll_x_offset = 0 #used for cursor follow efect
self.bg_scroll_y_offset = 0 #used for cursor follow efect
self.apsolute_x = 0 #used for cursor follow efect
self.apsolute_y = 0 #used for cursor follow efect
def checkXColision(nota, cursorLeft, trajanje):
if ( nota.pozicija == cursorLeft):
print("kolizija na pocetku note s CL")
return(True)
elif ( cursorLeft > nota.pozicija ) & ( cursorLeft < ( nota.pozicija + nota.trajanje )):
print("kolizija na sredini note s CL")
return(True)
elif ( cursorLeft == ( nota.pozicija + nota.trajanje )):
print("kolizija na kraju note s CL")
return(True)
elif ( nota.pozicija == ( cursorLeft + trajanje)):
print("kolizija na pocetku note s CR")
return(True)
elif ( ( cursorLeft + trajanje ) > nota.pozicija ) & ( ( cursorLeft + trajanje ) < ( nota.pozicija + nota.trajanje )):
print("kolizija na sredini note sa CR")
return(True)
elif ( ( cursorLeft + trajanje ) == ( nota.pozicija + nota.trajanje )):
print("kolizija na kraju note s CR")
return(True)
elif ( ( cursorLeft < nota.pozicija ) & ( ( cursorLeft + trajanje ) > (nota.pozicija + nota.trajanje ))):
print("kolizija note unutar Cursora")
return(True)
else:
return(False)
#sortiraj listu klasa
#lista.sort(key=operator.attrgetter('broj'))
def findNote(nota, cursorLeft, trajanje):
if ( nota.pozicija == cursorLeft):
print("na pocetku note s CL")
return(1)
elif ( cursorLeft > nota.pozicija ) & ( cursorLeft < ( nota.pozicija + nota.trajanje )):
print("na sredini note s CL")
return(2)
elif ( cursorLeft == ( nota.pozicija + nota.trajanje )):
print("na kraju note s CL")
return(3)
elif ( nota.pozicija == ( cursorLeft + trajanje)):
print("na pocetku note s CR")
return(4)
elif ( ( cursorLeft + trajanje ) > nota.pozicija ) & ( ( cursorLeft + trajanje ) < ( nota.pozicija + nota.trajanje )):
print("na sredini note sa CR")
return(5)
elif ( ( cursorLeft + trajanje ) == ( nota.pozicija + nota.trajanje )):
print("na kraju note s CR")
return(6)
elif ( ( cursorLeft < nota.pozicija ) & ( ( cursorLeft + trajanje ) > (nota.pozicija + nota.trajanje ))):
print("note unutar Cursora")
return(7)
else:
return(False)
letter2MidiNumberPrefix = {
"c" : "0",
"d" : "2",
"e" : "4",
"f" : "5",
"g" : "7",
"a" : "9",
"h" : "11",
}
letter2MidiOctave = {
",," : "24",
"," : "36",
"" : "48",
"'" : "60",
"''" : "72",
"'''" : "84",
}
predikat2Midi = {
0 : 0,
1 : 1,
2 : -1,
}
def nota2MidiNumber(nota):
return(int(letter2MidiNumberPrefix[kljucevi[nota.ton][0]]) + int(letter2MidiOctave[kljucevi[nota.ton][1]]) + int(predikat2Midi[nota.predikat]))
def get_git_revision_short_hash():
import subprocess
return subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD'])
| [
"subprocess.check_output"
] | [((6499, 6563), 'subprocess.check_output', 'subprocess.check_output', (["['git', 'rev-parse', '--short', 'HEAD']"], {}), "(['git', 'rev-parse', '--short', 'HEAD'])\n", (6522, 6563), False, 'import subprocess\n')] |
# -*- coding: utf-8 -*-
from pyspark.mllib.clustering import KMeans, KMeansModel
from numpy import array
from math import sqrt
from pyspark import SparkContext, SparkConf
conf = SparkConf()
conf.setAppName("deep test")#.setMaster("spark://192.168.1.14:7077")#.setExecutorEnv("CLASSPATH", path)
#conf.set("spark.scheduler.mode", "FAIR")
#conf.set("spark.cores.max",44)
#conf.set("spark.executor.memory",'5g')
sc = SparkContext(conf=conf)
# Load and parse the data
data = sc.textFile("kmeans_data.txt")
parsedData = data.map(lambda line: array([float(x) for x in line.split(' ')]))
# Build the model (cluster the data)
clusters = KMeans.train(parsedData, 2, maxIterations=10,
runs=10, initializationMode="random")
# Evaluate clustering by computing Within Set Sum of Squared Errors
def error(point):
center = clusters.centers[clusters.predict(point)]
return sqrt(sum([x**2 for x in (point - center)]))
WSSSE = parsedData.map(lambda point: error(point)).reduce(lambda x, y: x + y)
print("Within Set Sum of Squared Error = " + str(WSSSE))
# Save and load model
clusters.save(sc, "myModelPath")
sameModel = KMeansModel.load(sc, "myModelPath")
| [
"pyspark.mllib.clustering.KMeansModel.load",
"pyspark.SparkContext",
"pyspark.SparkConf",
"pyspark.mllib.clustering.KMeans.train"
] | [((179, 190), 'pyspark.SparkConf', 'SparkConf', ([], {}), '()\n', (188, 190), False, 'from pyspark import SparkContext, SparkConf\n'), ((415, 438), 'pyspark.SparkContext', 'SparkContext', ([], {'conf': 'conf'}), '(conf=conf)\n', (427, 438), False, 'from pyspark import SparkContext, SparkConf\n'), ((632, 720), 'pyspark.mllib.clustering.KMeans.train', 'KMeans.train', (['parsedData', '(2)'], {'maxIterations': '(10)', 'runs': '(10)', 'initializationMode': '"""random"""'}), "(parsedData, 2, maxIterations=10, runs=10, initializationMode=\n 'random')\n", (644, 720), False, 'from pyspark.mllib.clustering import KMeans, KMeansModel\n'), ((1125, 1160), 'pyspark.mllib.clustering.KMeansModel.load', 'KMeansModel.load', (['sc', '"""myModelPath"""'], {}), "(sc, 'myModelPath')\n", (1141, 1160), False, 'from pyspark.mllib.clustering import KMeans, KMeansModel\n')] |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-09-02 04:17
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Questions',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', models.DateTimeField(auto_now_add=True)),
('last_updated', models.DateTimeField(auto_now=True)),
('question', models.TextField(max_length=100)),
('a', models.CharField(max_length=30)),
('b', models.CharField(max_length=30)),
('c', models.CharField(max_length=30)),
('d', models.CharField(max_length=30)),
('anwser', models.CharField(choices=[('a', 'a.'), ('b', 'b.'), ('c', 'c.'), ('d', 'd.')], max_length=1)),
],
),
]
| [
"django.db.models.DateTimeField",
"django.db.models.AutoField",
"django.db.models.TextField",
"django.db.models.CharField"
] | [((369, 462), '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", (385, 462), False, 'from django.db import migrations, models\n'), ((489, 528), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)'}), '(auto_now_add=True)\n', (509, 528), False, 'from django.db import migrations, models\n'), ((564, 599), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now': '(True)'}), '(auto_now=True)\n', (584, 599), False, 'from django.db import migrations, models\n'), ((631, 663), 'django.db.models.TextField', 'models.TextField', ([], {'max_length': '(100)'}), '(max_length=100)\n', (647, 663), False, 'from django.db import migrations, models\n'), ((688, 719), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(30)'}), '(max_length=30)\n', (704, 719), False, 'from django.db import migrations, models\n'), ((744, 775), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(30)'}), '(max_length=30)\n', (760, 775), False, 'from django.db import migrations, models\n'), ((800, 831), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(30)'}), '(max_length=30)\n', (816, 831), False, 'from django.db import migrations, models\n'), ((856, 887), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(30)'}), '(max_length=30)\n', (872, 887), False, 'from django.db import migrations, models\n'), ((917, 1014), 'django.db.models.CharField', 'models.CharField', ([], {'choices': "[('a', 'a.'), ('b', 'b.'), ('c', 'c.'), ('d', 'd.')]", 'max_length': '(1)'}), "(choices=[('a', 'a.'), ('b', 'b.'), ('c', 'c.'), ('d', 'd.'\n )], max_length=1)\n", (933, 1014), False, 'from django.db import migrations, models\n')] |
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
import os
import seaborn as sns
from mantis import sdp_km_burer_monteiro
from data import toy
from experiments.utils import plot_matrix, plot_data_clustered
dir_name = '../results/'
if not os.path.exists(dir_name):
os.mkdir(dir_name)
dir_name += 'clustering/'
if not os.path.exists(dir_name):
os.mkdir(dir_name)
def test_clustering(X, gt, n_clusters, filename, palette='Set1'):
Y = sdp_km_burer_monteiro(X, n_clusters, rank=len(X), tol=1e-6,
verbose=True)
D = X.dot(X.T)
Q = Y.dot(Y.T)
sns.set_style('white')
plt.figure(figsize=(12, 3.5), tight_layout=True)
gs = gridspec.GridSpec(1, 4, wspace=0.15)
ax = plt.subplot(gs[0])
plot_data_clustered(X, gt, ax=ax, palette=palette)
ax.set_title('Input dataset', fontsize='xx-large')
titles = [r'$\mathbf{X}^\top \mathbf{X}$',
r'$\mathbf{Y}^\top \mathbf{Y}$',
r'$\mathbf{Y}^\top$'
]
for i, (M, t, wl) in enumerate(zip([D, Q, Y], titles,
['both', 'both', 'vertical'])):
ax = plt.subplot(gs[i + 1])
plot_matrix(M, ax=ax, labels=gt, which_labels=wl,
labels_palette=palette, colorbar_labelsize=15)
ax.set_title(t, fontsize='xx-large')
plt.tight_layout()
plt.savefig('{}{}.pdf'.format(dir_name, filename))
if __name__ == '__main__':
X, gt = toy.gaussian_blobs()
test_clustering(X, gt, 6, 'gaussian_blobs')
X, gt = toy.circles()
test_clustering(X, gt, 16, 'circles')
X, gt = toy.moons()
test_clustering(X, gt, 16, 'moons')
X, gt = toy.double_swiss_roll()
test_clustering(X, gt, 48, 'double_swiss_roll')
plt.show()
| [
"os.path.exists",
"matplotlib.pyplot.show",
"data.toy.moons",
"experiments.utils.plot_matrix",
"seaborn.set_style",
"matplotlib.pyplot.figure",
"matplotlib.gridspec.GridSpec",
"os.mkdir",
"matplotlib.pyplot.tight_layout",
"experiments.utils.plot_data_clustered",
"data.toy.double_swiss_roll",
"... | [((261, 285), 'os.path.exists', 'os.path.exists', (['dir_name'], {}), '(dir_name)\n', (275, 285), False, 'import os\n'), ((291, 309), 'os.mkdir', 'os.mkdir', (['dir_name'], {}), '(dir_name)\n', (299, 309), False, 'import os\n'), ((343, 367), 'os.path.exists', 'os.path.exists', (['dir_name'], {}), '(dir_name)\n', (357, 367), False, 'import os\n'), ((373, 391), 'os.mkdir', 'os.mkdir', (['dir_name'], {}), '(dir_name)\n', (381, 391), False, 'import os\n'), ((615, 637), 'seaborn.set_style', 'sns.set_style', (['"""white"""'], {}), "('white')\n", (628, 637), True, 'import seaborn as sns\n'), ((642, 690), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(12, 3.5)', 'tight_layout': '(True)'}), '(figsize=(12, 3.5), tight_layout=True)\n', (652, 690), True, 'import matplotlib.pyplot as plt\n'), ((700, 736), 'matplotlib.gridspec.GridSpec', 'gridspec.GridSpec', (['(1)', '(4)'], {'wspace': '(0.15)'}), '(1, 4, wspace=0.15)\n', (717, 736), True, 'import matplotlib.gridspec as gridspec\n'), ((747, 765), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs[0]'], {}), '(gs[0])\n', (758, 765), True, 'import matplotlib.pyplot as plt\n'), ((770, 820), 'experiments.utils.plot_data_clustered', 'plot_data_clustered', (['X', 'gt'], {'ax': 'ax', 'palette': 'palette'}), '(X, gt, ax=ax, palette=palette)\n', (789, 820), False, 'from experiments.utils import plot_matrix, plot_data_clustered\n'), ((1352, 1370), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (1368, 1370), True, 'import matplotlib.pyplot as plt\n'), ((1467, 1487), 'data.toy.gaussian_blobs', 'toy.gaussian_blobs', ([], {}), '()\n', (1485, 1487), False, 'from data import toy\n'), ((1549, 1562), 'data.toy.circles', 'toy.circles', ([], {}), '()\n', (1560, 1562), False, 'from data import toy\n'), ((1618, 1629), 'data.toy.moons', 'toy.moons', ([], {}), '()\n', (1627, 1629), False, 'from data import toy\n'), ((1683, 1706), 'data.toy.double_swiss_roll', 'toy.double_swiss_roll', ([], {}), '()\n', (1704, 1706), False, 'from data import toy\n'), ((1764, 1774), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1772, 1774), True, 'import matplotlib.pyplot as plt\n'), ((1154, 1176), 'matplotlib.pyplot.subplot', 'plt.subplot', (['gs[i + 1]'], {}), '(gs[i + 1])\n', (1165, 1176), True, 'import matplotlib.pyplot as plt\n'), ((1185, 1285), 'experiments.utils.plot_matrix', 'plot_matrix', (['M'], {'ax': 'ax', 'labels': 'gt', 'which_labels': 'wl', 'labels_palette': 'palette', 'colorbar_labelsize': '(15)'}), '(M, ax=ax, labels=gt, which_labels=wl, labels_palette=palette,\n colorbar_labelsize=15)\n', (1196, 1285), False, 'from experiments.utils import plot_matrix, plot_data_clustered\n')] |
import numpy as np
from scipy import sparse
from sklearn.model_selection import train_test_split
rows = [0,1,2,8]
cols = [1,0,4,8]
vals = [1,2,1,4]
A = sparse.coo_matrix((vals, (rows, cols)))
print(A.todense())
B = A.tocsr()
C = sparse.csr_matrix(np.array([0,1,0,0,2,0,0,0,1]).reshape(1,9))
print(B.shape,C.shape)
D = sparse.vstack([B,C])
print(D.todense())
## read and write
file_name = "sparse_matrix.npz"
sparse.save_npz(file_name, D)
E = sparse.load_npz(file_name)
X = E
y = np.random.randint(0,2,E.shape[0])
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)
| [
"sklearn.model_selection.train_test_split",
"scipy.sparse.load_npz",
"numpy.array",
"numpy.random.randint",
"scipy.sparse.coo_matrix",
"scipy.sparse.save_npz",
"scipy.sparse.vstack"
] | [((156, 195), 'scipy.sparse.coo_matrix', 'sparse.coo_matrix', (['(vals, (rows, cols))'], {}), '((vals, (rows, cols)))\n', (173, 195), False, 'from scipy import sparse\n'), ((325, 346), 'scipy.sparse.vstack', 'sparse.vstack', (['[B, C]'], {}), '([B, C])\n', (338, 346), False, 'from scipy import sparse\n'), ((417, 446), 'scipy.sparse.save_npz', 'sparse.save_npz', (['file_name', 'D'], {}), '(file_name, D)\n', (432, 446), False, 'from scipy import sparse\n'), ((451, 477), 'scipy.sparse.load_npz', 'sparse.load_npz', (['file_name'], {}), '(file_name)\n', (466, 477), False, 'from scipy import sparse\n'), ((490, 525), 'numpy.random.randint', 'np.random.randint', (['(0)', '(2)', 'E.shape[0]'], {}), '(0, 2, E.shape[0])\n', (507, 525), True, 'import numpy as np\n'), ((559, 614), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.33)', 'random_state': '(42)'}), '(X, y, test_size=0.33, random_state=42)\n', (575, 614), False, 'from sklearn.model_selection import train_test_split\n'), ((254, 291), 'numpy.array', 'np.array', (['[0, 1, 0, 0, 2, 0, 0, 0, 1]'], {}), '([0, 1, 0, 0, 2, 0, 0, 0, 1])\n', (262, 291), True, 'import numpy as np\n')] |
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import os
import paddle
import shutil
from paddlenlp.utils.log import logger
from predict import LongDocClassifier
# yapf: disable
parser = argparse.ArgumentParser()
parser.add_argument("--batch_size", default=16, type=int,
help="Batch size per GPU/CPU for predicting (In static mode, it should be the same as in model training process.)")
parser.add_argument("--model_name_or_path", type=str, default="ernie-doc-base-zh",
help="Pretraining or finetuned model name or path")
parser.add_argument("--max_seq_length", type=int, default=512,
help="The maximum total input sequence length after SentencePiece tokenization.")
parser.add_argument("--memory_length", type=int, default=128, help="Length of the retained previous heads.")
parser.add_argument("--device", type=str, default="cpu", choices=["cpu", "gpu"],
help="Select cpu, gpu devices to train model.")
parser.add_argument("--dataset", default="iflytek", choices=["imdb", "iflytek", "thucnews", "hyp"], type=str,
help="The training dataset")
parser.add_argument("--static_path", default=None, type=str,
help="The path which your static model is at or where you want to save after converting.")
args = parser.parse_args()
# yapf: enable
if __name__ == "__main__":
paddle.set_device(args.device)
if os.path.exists(args.model_name_or_path):
logger.info("init checkpoint from %s" % args.model_name_or_path)
if args.static_path and os.path.exists(args.static_path):
logger.info("will remove the old model")
shutil.rmtree(args.static_path)
predictor = LongDocClassifier(model_name_or_path=args.model_name_or_path,
batch_size=args.batch_size,
max_seq_length=args.max_seq_length,
memory_len=args.memory_length,
static_mode=True,
static_path=args.static_path)
| [
"os.path.exists",
"argparse.ArgumentParser",
"predict.LongDocClassifier",
"shutil.rmtree",
"paddlenlp.utils.log.logger.info",
"paddle.set_device"
] | [((768, 793), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (791, 793), False, 'import argparse\n'), ((1972, 2002), 'paddle.set_device', 'paddle.set_device', (['args.device'], {}), '(args.device)\n', (1989, 2002), False, 'import paddle\n'), ((2011, 2050), 'os.path.exists', 'os.path.exists', (['args.model_name_or_path'], {}), '(args.model_name_or_path)\n', (2025, 2050), False, 'import os\n'), ((2294, 2508), 'predict.LongDocClassifier', 'LongDocClassifier', ([], {'model_name_or_path': 'args.model_name_or_path', 'batch_size': 'args.batch_size', 'max_seq_length': 'args.max_seq_length', 'memory_len': 'args.memory_length', 'static_mode': '(True)', 'static_path': 'args.static_path'}), '(model_name_or_path=args.model_name_or_path, batch_size=\n args.batch_size, max_seq_length=args.max_seq_length, memory_len=args.\n memory_length, static_mode=True, static_path=args.static_path)\n', (2311, 2508), False, 'from predict import LongDocClassifier\n'), ((2060, 2124), 'paddlenlp.utils.log.logger.info', 'logger.info', (["('init checkpoint from %s' % args.model_name_or_path)"], {}), "('init checkpoint from %s' % args.model_name_or_path)\n", (2071, 2124), False, 'from paddlenlp.utils.log import logger\n'), ((2154, 2186), 'os.path.exists', 'os.path.exists', (['args.static_path'], {}), '(args.static_path)\n', (2168, 2186), False, 'import os\n'), ((2196, 2236), 'paddlenlp.utils.log.logger.info', 'logger.info', (['"""will remove the old model"""'], {}), "('will remove the old model')\n", (2207, 2236), False, 'from paddlenlp.utils.log import logger\n'), ((2245, 2276), 'shutil.rmtree', 'shutil.rmtree', (['args.static_path'], {}), '(args.static_path)\n', (2258, 2276), False, 'import shutil\n')] |
import numpy as np
import matplotlib.pyplot as plt
# mass, spring constant, initial position and velocity
m = 1
k = 1
x = 0
v = 1
# Creating first two data using Euler's method
t_max = 0.2
dt = 0.1
t_array = np.arange(0, t_max, dt)
x_list = []
v_list = []
for t in t_array:
x_list.append(x)
v_list.append(v)
a = -k * x / m
x = x + dt * v
v = v + dt * a
# Verlet method
t_max = 10
dt = 0.1
t_array = np.arange(0.2, t_max, dt)
# initialise empty lists to record trajectories
counter = 1
# Euler integration
for t in t_array:
# append current state to trajectories
# calculate new position and velocity
a = -k * x / m
x = 2*x_list[counter]-x_list[counter-1]+(dt**2)*a
v = (1/dt)*(x-x_list[counter])
x_list.append(x)
v_list.append(v)
counter +=1
# convert trajectory lists into arrays, so they can be sliced (useful for Assignment 2)
x_array = np.array(x_list)
v_array = np.array(v_list)
t_array_plot = np.arange(0, t_max, dt)
# plot the position-time graph
plt.figure(1)
plt.clf()
plt.xlabel('time (s)')
plt.grid()
plt.plot(t_array_plot, x_array, label='x (m)')
plt.plot(t_array_plot, v_array, label='v (m/s)')
plt.legend()
plt.show()
| [
"matplotlib.pyplot.grid",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.clf",
"matplotlib.pyplot.plot",
"numpy.array",
"matplotlib.pyplot.figure",
"numpy.arange",
"matplotlib.pyplot.show"
] | [((210, 233), 'numpy.arange', 'np.arange', (['(0)', 't_max', 'dt'], {}), '(0, t_max, dt)\n', (219, 233), True, 'import numpy as np\n'), ((426, 451), 'numpy.arange', 'np.arange', (['(0.2)', 't_max', 'dt'], {}), '(0.2, t_max, dt)\n', (435, 451), True, 'import numpy as np\n'), ((905, 921), 'numpy.array', 'np.array', (['x_list'], {}), '(x_list)\n', (913, 921), True, 'import numpy as np\n'), ((932, 948), 'numpy.array', 'np.array', (['v_list'], {}), '(v_list)\n', (940, 948), True, 'import numpy as np\n'), ((966, 989), 'numpy.arange', 'np.arange', (['(0)', 't_max', 'dt'], {}), '(0, t_max, dt)\n', (975, 989), True, 'import numpy as np\n'), ((1021, 1034), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {}), '(1)\n', (1031, 1034), True, 'import matplotlib.pyplot as plt\n'), ((1035, 1044), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (1042, 1044), True, 'import matplotlib.pyplot as plt\n'), ((1045, 1067), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""time (s)"""'], {}), "('time (s)')\n", (1055, 1067), True, 'import matplotlib.pyplot as plt\n'), ((1068, 1078), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (1076, 1078), True, 'import matplotlib.pyplot as plt\n'), ((1079, 1125), 'matplotlib.pyplot.plot', 'plt.plot', (['t_array_plot', 'x_array'], {'label': '"""x (m)"""'}), "(t_array_plot, x_array, label='x (m)')\n", (1087, 1125), True, 'import matplotlib.pyplot as plt\n'), ((1126, 1174), 'matplotlib.pyplot.plot', 'plt.plot', (['t_array_plot', 'v_array'], {'label': '"""v (m/s)"""'}), "(t_array_plot, v_array, label='v (m/s)')\n", (1134, 1174), True, 'import matplotlib.pyplot as plt\n'), ((1175, 1187), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (1185, 1187), True, 'import matplotlib.pyplot as plt\n'), ((1188, 1198), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1196, 1198), True, 'import matplotlib.pyplot as plt\n')] |
#!/usr/bin/env python3
import sys
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime as dt
import numpy as np
import argparse
global pred_map,sat_map,inst_map
pred_map = { 1 : '1 (constant) ',
2 : '1000-300hPa thickness',
3 : '200-50hPa thickness ',
4 : 'T_skin ',
5 : 'total column water ',
6 : '10-2hPa thickness ',
7 : '50-5hPa thickness ',
8 : 'surface wind speed ',
9 : 'nadir view angle ',
10 : 'nadir view angle **2 ',
11 : 'nadir view angle **3 ',
12 : 'nadir view angle **4 ',
13 : 'cos solar zen angle ',
14 : 'solar elevation ',
15 : 'TMI diurnal bias ',
16 : 'land or sea ice mask ',
17 : 'view angle (land) ',
18 : 'view angle **2 (land)',
19 : 'view angle **3 (land)',
20 : 'ln(rain rate+1) (1)',
21 : 'ln(rain rate+1)**2(1)',
22 : 'ln(rain rate+1)**3(1)',
23 : 'ln(rain rate+1) (2)',
24 : 'ln(rain rate+1)**2(2)',
25 : 'ln(rain rate+1)**3(2)',
26 : 'ascent rate (hPa/s) ',
27 : 'descent rate (hPa/s) ',
28 : 'land mask times winds',
29 : 'day/night ',
30 : 'thermal contrast ',
31 : 'Radiosonde T 100-850 ',
32 : 'Radiosonde T 30-200 ',
33 : 'Radiosonde T 0- 60 ',
34 : 'Radiosonde T s.elv**1',
35 : 'Radiosonde T s.elv**2',
36 : 'Radiosonde log press ',
37 : 'cos solar zen (full) ',
}
pred_cols = { 1 : 'black',
2 : 'red',
3 : 'orange',
4 : 'black',
5 : 'red',
6 : 'black',
7 : 'black',
8 : 'green',
9 : 'purple',
10 : 'magenta',
11 : 'blue',
12 : 'black',
13 : 'black',
14 : 'black',
15 : 'black',
16 : 'black',
17 : 'black',
18 : 'black',
19 : 'black',
20 : 'black',
21 : 'black',
22 : 'black',
23 : 'black',
24 : 'black',
25 : 'black',
26 : 'black',
27 : 'black',
28 : 'black',
29 : 'black',
30 : 'black',
31 : 'black',
32 : 'black',
33 : 'black',
34 : 'black',
35 : 'black',
36 : 'black',
37 : 'black',
}
sat_map = {
3 : "Metop-B",
4 : "Metop-A",
5 : "Metop-C",
70 : "METEOSAT-11",
206 : "NOAA-15",
207 : "NOAA-16",
209 : "NOAA-18",
223 : "NOAA-19",
225 : "NOAA-20",
523 : "FY-3D",
}
sen_map = {
0 : "HIRS",
1 : "MSU",
2 : "SSU",
3 : "AMSU-A",
4 : "AMSU-B",
11 : "AIRS",
15 : "MHS",
16 : "IASI",
19 : "ATMS",
27 : "CRIS",
21 : "SEVIRI",
29 : "SEVIRI HR",
34 : "SAPHIR",
72 : "MWTS2",
73 : "MWHS2",
}
#############################################################################################
def plot_varbc_pred_ts(datetime,data,labels,lloc,batch) :
# Grab meta data from the first row of data
nsat=int(data[1][1])
nsen=int(data[2][1])
nchn=int(data[3][1])
npred=int(data[5][1])
# Number of observations
nobs=data[3]
fig, ax = plt.subplots(figsize=(8.27,3.6))
title_string='VarBC Predictors for '+sat_map[nsat]+': ' +sen_map[nsen]+ ' Channel '+str(nchn)
plt.title(title_string)
ax2=ax.twinx()
# Hide the right and top spines
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
# Only show ticks on the left and bottom spines
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')
ax.xaxis.set_visible(True)
ax.yaxis.set_visible(True)
ax.yaxis.grid() #vertical lines
ax.xaxis.grid() #horizontal lines
dfmt = mdates.DateFormatter('%d')
ax.xaxis.set_major_formatter(dfmt)
ax2.xaxis.set_major_formatter(dfmt)
ax2.plot_date(x=datetime,y=data[4],fmt=':',color='lightgrey',label='nobs',linewidth=1)
for pred in range(1,npred+1):
totpred=np.add(data[pred+5],data[5+npred+pred])
label_entry=int(data[5+npred+npred+pred][1])
ax.plot_date(x=datetime,y=totpred,fmt='-',color=pred_cols[label_entry+1],label=pred_map[label_entry+1],linewidth=2)
ax.set_xlabel('Day',fontsize=10)
majdfmt = mdates.DateFormatter("%b\n%d")
ax.xaxis.set_major_formatter(majdfmt)
# Ensure a major tick for each week using (interval=1)
ax.xaxis.set_major_locator(mdates.WeekdayLocator(interval=1))
ax.set_ylabel('Normalised Predictor Value',fontsize=10)
ax2.set_ylabel('Number of observations',fontsize=10)
#plot legend
ax.legend(loc=lloc,prop={'size':10},labelspacing=0,fancybox=False, frameon=True, ncol=1)
#defining display layout
plt.tight_layout()
figsuffix=str(nsat)+'_'+str(nsen)+'_'+str(nchn)
figname = 'varbc_pred_'+figsuffix+'.png'
plt.savefig(figname)
print("Output:",figname)
if not batch :
plt.show()
#############################################################################################
def read_data(filename):
data = {}
dtdata = []
print("Read:",filename)
with open(filename, "r") as a_file:
for line in a_file:
line = line.strip()
tmp = line.split()
dto = dt.datetime.strptime(tmp[0], '%Y%m%d:%H%M%S')
dtdata.append(dto)
for x in range(1,len(tmp)) :
if x not in data :
data[x] = []
data[x].append(float(tmp[x]))
a_file.close()
return dtdata, data
#############################################################################################
def main(argv) :
parser = argparse.ArgumentParser(description='Plot VarBC predictor time-series')
parser.add_argument('-i',dest="ipath",help='Input file name',default=None,required=True)
parser.add_argument('-l',dest="lloc",help='Legend location using matplotlib syntax',default=None,required=False)
parser.add_argument('-d',dest="labels",help='Optional experiment description',default=None,required=False)
parser.add_argument('-b',action="store_true",help='Batch mode, produce png only',default=False,required=False)
if len(argv) == 1:
parser.print_help()
sys.exit(1)
args = parser.parse_args()
if args.labels is None :
labels = None
else:
labels = args.labels
data = {}
ipath = args.ipath
tsdatetime,tsdata = read_data(ipath)
plot_varbc_pred_ts(tsdatetime,tsdata,args.labels,args.lloc,args.b)
if __name__ == "__main__":
sys.exit(main(sys.argv))
| [
"matplotlib.pyplot.savefig",
"numpy.add",
"argparse.ArgumentParser",
"matplotlib.dates.WeekdayLocator",
"datetime.datetime.strptime",
"matplotlib.dates.DateFormatter",
"matplotlib.pyplot.tight_layout",
"sys.exit",
"matplotlib.pyplot.title",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show"
... | [((3935, 3968), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(8.27, 3.6)'}), '(figsize=(8.27, 3.6))\n', (3947, 3968), True, 'import matplotlib.pyplot as plt\n'), ((4067, 4090), 'matplotlib.pyplot.title', 'plt.title', (['title_string'], {}), '(title_string)\n', (4076, 4090), True, 'import matplotlib.pyplot as plt\n'), ((4490, 4516), 'matplotlib.dates.DateFormatter', 'mdates.DateFormatter', (['"""%d"""'], {}), "('%d')\n", (4510, 4516), True, 'import matplotlib.dates as mdates\n'), ((4987, 5017), 'matplotlib.dates.DateFormatter', 'mdates.DateFormatter', (['"""%b\n%d"""'], {}), "('%b\\n%d')\n", (5007, 5017), True, 'import matplotlib.dates as mdates\n'), ((5431, 5449), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (5447, 5449), True, 'import matplotlib.pyplot as plt\n'), ((5546, 5566), 'matplotlib.pyplot.savefig', 'plt.savefig', (['figname'], {}), '(figname)\n', (5557, 5566), True, 'import matplotlib.pyplot as plt\n'), ((6266, 6337), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Plot VarBC predictor time-series"""'}), "(description='Plot VarBC predictor time-series')\n", (6289, 6337), False, 'import argparse\n'), ((4727, 4773), 'numpy.add', 'np.add', (['data[pred + 5]', 'data[5 + npred + pred]'], {}), '(data[pred + 5], data[5 + npred + pred])\n', (4733, 4773), True, 'import numpy as np\n'), ((5146, 5179), 'matplotlib.dates.WeekdayLocator', 'mdates.WeekdayLocator', ([], {'interval': '(1)'}), '(interval=1)\n', (5167, 5179), True, 'import matplotlib.dates as mdates\n'), ((5615, 5625), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5623, 5625), True, 'import matplotlib.pyplot as plt\n'), ((6824, 6835), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (6832, 6835), False, 'import sys\n'), ((5917, 5962), 'datetime.datetime.strptime', 'dt.datetime.strptime', (['tmp[0]', '"""%Y%m%d:%H%M%S"""'], {}), "(tmp[0], '%Y%m%d:%H%M%S')\n", (5937, 5962), True, 'import datetime as dt\n')] |
# -*- coding: utf-8 -*-
import json
import urllib.parse
import tornado.gen
from app.const import *
from app.base.configs import tp_cfg
from app.base.session import tp_session
from app.base.core_server import core_service_async_post_http
from app.model import record
from app.base.stats import tp_stats
from app.base.logger import *
from app.base.controller import TPBaseJsonHandler
class RpcHandler(TPBaseJsonHandler):
@tornado.gen.coroutine
def get(self):
_uri = self.request.uri.split('?', 1)
if len(_uri) != 2:
return self.write_json(TPE_PARAM)
yield self._dispatch(urllib.parse.unquote(_uri[1]))
@tornado.gen.coroutine
def post(self):
req = self.request.body.decode('utf-8')
if req == '':
return self.write_json(TPE_PARAM)
yield self._dispatch(req)
@tornado.gen.coroutine
def _dispatch(self, req):
try:
_req = json.loads(req)
if 'method' not in _req or 'param' not in _req:
return self.write_json(TPE_PARAM)
except:
return self.write_json(TPE_JSON_FORMAT)
# log.d('WEB-JSON-RPC, method=`{}`\n'.format(_req['method']))
if 'get_conn_info' == _req['method']:
return self._get_conn_info(_req['param'])
elif 'session_begin' == _req['method']:
return self._session_begin(_req['param'])
elif 'session_update' == _req['method']:
return self._session_update(_req['param'])
elif 'session_end' == _req['method']:
return self._session_end(_req['param'])
elif 'register_core' == _req['method']:
return self._register_core(_req['param'])
elif 'exit' == _req['method']:
return self._exit()
else:
log.e('WEB-JSON-RPC got unknown method: `{}`.\n'.format(_req['method']))
return self.write_json(TPE_UNKNOWN_CMD)
def _get_conn_info(self, param):
if 'conn_id' not in param:
return self.write_json(TPE_PARAM)
conn_id = param['conn_id']
x = tp_session().taken('tmp-conn-info-{}'.format(conn_id), None)
if x is None:
return self.write_json(TPE_NOT_EXISTS)
else:
return self.write_json(TPE_OK, data=x)
def _session_begin(self, param):
try:
_sid = param['sid']
_user_id = param['user_id']
_host_id = param['host_id']
_account_id = param['acc_id']
_user_name = param['user_username']
_acc_name = param['acc_username']
_host_ip = param['host_ip']
_conn_ip = param['conn_ip']
_conn_port = param['conn_port']
_client_ip = param['client_ip']
_auth_type = param['auth_type']
_protocol_type = param['protocol_type']
_protocol_sub_type = param['protocol_sub_type']
except IndexError:
return self.write_json(TPE_PARAM)
err, record_id = record.session_begin(_sid, _user_id, _host_id, _account_id, _user_name, _acc_name, _host_ip, _conn_ip, _conn_port, _client_ip, _auth_type, _protocol_type, _protocol_sub_type)
if err != TPE_OK:
return self.write_json(err, message='can not write database.')
else:
tp_stats().conn_counter_change(1)
return self.write_json(TPE_OK, data={'rid': record_id})
def _session_update(self, param):
try:
rid = param['rid']
protocol_sub_type = param['protocol_sub_type']
code = param['code']
except:
return self.write_json(TPE_PARAM)
if 'rid' not in param or 'code' not in param:
return self.write_json(TPE_PARAM)
if not record.session_update(rid, protocol_sub_type, code):
return self.write_json(TPE_DATABASE, 'can not write database.')
else:
return self.write_json(TPE_OK)
def _session_end(self, param):
if 'rid' not in param or 'code' not in param:
return self.write_json(TPE_PARAM, message='invalid request.')
if not record.session_end(param['rid'], param['code']):
return self.write_json(TPE_DATABASE, 'can not write database.')
else:
tp_stats().conn_counter_change(-1)
return self.write_json(TPE_OK)
def _register_core(self, param):
# 因为core服务启动了(之前可能非正常终止了),做一下数据库中会话状态的修复操作
record.session_fix()
if 'rpc' not in param:
return self.write_json(TPE_PARAM, 'invalid param.')
tp_cfg().common.core_server_rpc = param['rpc']
# 获取core服务的配置信息
req = {'method': 'get_config', 'param': []}
_yr = core_service_async_post_http(req)
code, ret_data = yield _yr
if code != TPE_OK:
return self.write_json(code, 'get config from core-service failed.')
log.d('update base server config info.\n')
tp_cfg().update_core(ret_data)
# 将运行时配置发送给核心服务
req = {'method': 'set_config', 'param': {'noop_timeout': tp_cfg().sys.session.noop_timeout}}
_yr = core_service_async_post_http(req)
code, ret_data = yield _yr
if code != TPE_OK:
return self.write_json(code, 'set runtime-config to core-service failed.')
return self.write_json(TPE_OK)
def _exit(self):
# set exit flag.
return self.write_json(TPE_OK)
| [
"app.model.record.session_begin",
"json.loads",
"app.base.stats.tp_stats",
"app.base.configs.tp_cfg",
"app.base.session.tp_session",
"app.model.record.session_update",
"app.base.core_server.core_service_async_post_http",
"app.model.record.session_fix",
"app.model.record.session_end"
] | [((3018, 3200), 'app.model.record.session_begin', 'record.session_begin', (['_sid', '_user_id', '_host_id', '_account_id', '_user_name', '_acc_name', '_host_ip', '_conn_ip', '_conn_port', '_client_ip', '_auth_type', '_protocol_type', '_protocol_sub_type'], {}), '(_sid, _user_id, _host_id, _account_id, _user_name,\n _acc_name, _host_ip, _conn_ip, _conn_port, _client_ip, _auth_type,\n _protocol_type, _protocol_sub_type)\n', (3038, 3200), False, 'from app.model import record\n'), ((4467, 4487), 'app.model.record.session_fix', 'record.session_fix', ([], {}), '()\n', (4485, 4487), False, 'from app.model import record\n'), ((4731, 4764), 'app.base.core_server.core_service_async_post_http', 'core_service_async_post_http', (['req'], {}), '(req)\n', (4759, 4764), False, 'from app.base.core_server import core_service_async_post_http\n'), ((5139, 5172), 'app.base.core_server.core_service_async_post_http', 'core_service_async_post_http', (['req'], {}), '(req)\n', (5167, 5172), False, 'from app.base.core_server import core_service_async_post_http\n'), ((938, 953), 'json.loads', 'json.loads', (['req'], {}), '(req)\n', (948, 953), False, 'import json\n'), ((3775, 3826), 'app.model.record.session_update', 'record.session_update', (['rid', 'protocol_sub_type', 'code'], {}), '(rid, protocol_sub_type, code)\n', (3796, 3826), False, 'from app.model import record\n'), ((4141, 4188), 'app.model.record.session_end', 'record.session_end', (["param['rid']", "param['code']"], {}), "(param['rid'], param['code'])\n", (4159, 4188), False, 'from app.model import record\n'), ((2097, 2109), 'app.base.session.tp_session', 'tp_session', ([], {}), '()\n', (2107, 2109), False, 'from app.base.session import tp_session\n'), ((4593, 4601), 'app.base.configs.tp_cfg', 'tp_cfg', ([], {}), '()\n', (4599, 4601), False, 'from app.base.configs import tp_cfg\n'), ((4968, 4976), 'app.base.configs.tp_cfg', 'tp_cfg', ([], {}), '()\n', (4974, 4976), False, 'from app.base.configs import tp_cfg\n'), ((3320, 3330), 'app.base.stats.tp_stats', 'tp_stats', ([], {}), '()\n', (3328, 3330), False, 'from app.base.stats import tp_stats\n'), ((4292, 4302), 'app.base.stats.tp_stats', 'tp_stats', ([], {}), '()\n', (4300, 4302), False, 'from app.base.stats import tp_stats\n'), ((5089, 5097), 'app.base.configs.tp_cfg', 'tp_cfg', ([], {}), '()\n', (5095, 5097), False, 'from app.base.configs import tp_cfg\n')] |
"""
Copy the contents of a local directory into the correct S3 location,
using the correct metadata as supplied by the metadata file (or
internal defaults).
"""
####
#### Copy the contents of a local directory into the correct S3
#### location, using the correct metadata as supplied by the metadata
#### file (or internal defaults).
####
#### Example usage:
#### python3 s3-uploader.py --help
#### mkdir -p /tmp/mnt || true
#### mkdir -p /tmp/foo || true
#### sshfs -oStrictHostKeyChecking=no -o IdentitiesOnly=true -o IdentityFile=/home/sjcarbon/local/share/secrets/bbop/ssh-keys/foo.skyhook -o idmap=user <EMAIL>:/home/skyhook /tmp/mnt/
#### cp -r /tmp/mnt/master/* /tmp/foo
#### fusermount -u /tmp/mnt
#### python3 ./scripts/s3-uploader.py -v --credentials ~/local/share/secrets/bbop/aws/s3/aws-go-push.json --directory ~/tmp/elpa/archives --bucket go-data-testing-sandbox --number 7 --pipeline foo-pipe
####
## Standard imports.
import sys
import urllib
import argparse
import logging
import os
import json
import boto3
import math
from filechunkio import FileChunkIO
## Default mimetype metadata--everything that we'll be dealing with,
## so controlled.
MIMES = {
'csv': 'text/csv',
'gaf': 'text/plain',
'gz': 'application/gzip',
'html': 'text/html',
## http://www.rfc-editor.org/rfc/rfc2046.txt
'jnl': 'application/octet-stream',
'js': 'application/javascript',
'json': 'application/json',
'md': 'text/markdown',
'obo': 'text/obo',
'owl': 'application/rdf+xml',
'report': 'text/plain',
## https://www.w3.org/TeamSubmission/turtle/#sec-mime
'ttl': 'text/turtle',
'tsv': 'text/tab-separated-values',
'txt': 'text/plain',
'yaml': 'text/yaml',
'yml': 'text/yaml',
## Default.
'': 'text/plain'
}
## Logger basic setup.
logging.basicConfig(level=logging.INFO)
LOG = logging.getLogger('aggregate')
LOG.setLevel(logging.WARNING)
def die_screaming(instr):
"""
Make sure we exit in a way that will get Jenkins's attention.
"""
LOG.error(instr)
sys.exit(1)
def get_args():
"""
Deal with incoming.
"""
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('-v', '--verbose', action='store_true',
help='More verbose output')
parser.add_argument('-c', '--credentials',
help='The credentials to used, in JSON')
parser.add_argument('-d', '--directory',
help='The directory to copy from')
parser.add_argument('-b', '--bucket',
help='The S3 bucket to copy into')
parser.add_argument('-n', '--number',
help='Optional: the "build-number" to add to the meta')
parser.add_argument('-p', '--pipeline',
help='Optional: the "build-pipeline" to add to the meta')
parser.add_argument('-m', '--mimetypes',
help='TODO: The mimetypes metadata to use, in JSON')
parser.add_argument('-l', '--location',
help='TODO: The S3 location to use')
return parser
def main():
"""The main runner for our script."""
parser = get_args()
args = parser.parse_args()
if args.verbose:
LOG.setLevel(logging.INFO)
LOG.info('Verbose: on')
else:
## If not verbose, turn down boto3.
boto3.set_stream_logger(name='boto3', level=logging.WARNING)
boto3.set_stream_logger(name='botocore', level=logging.WARNING)
logging.getLogger("requests").setLevel(logging.WARNING)
## Ensure credentials.
if not args.credentials:
die_screaming('need a credentials argument')
LOG.info('Will use credentials: ' + args.credentials)
## Ensure directory.
if not args.directory:
die_screaming('need a directory argument')
args.directory = args.directory.rstrip('//')
LOG.info('Will operate in: ' + args.directory)
## Ensure bucket.
if not args.bucket:
die_screaming('need a bucket argument')
bucket, slash, toppath = args.bucket.partition('/')
if toppath != '':
LOG.info('Will put to bucket: ' + bucket + '; with path: ' + toppath)
else:
LOG.info('Will put to bucket at top level: ' + bucket)
## Ensure mimetype metadata.
if not args.mimetypes:
LOG.info('Will use internal mimetype defaults')
else:
LOG.info('TODO: Will get mimetype metadata from: ' + args.metadata)
## Ensure bucket location.
if not args.location:
args.location = 'us-east-1'
LOG.info('Will use S3 bucket location default: ' + args.location)
else:
LOG.info('Will use S3 bucket location: ' + args.location)
## Extract S3 credentials.
creds = None
with open(args.credentials) as chandle:
creds = json.loads(chandle.read())
#LOG.info(creds)
s3 = boto3.resource('s3', region_name=args.location,
aws_access_key_id=creds['accessKeyId'],
aws_secret_access_key=creds['secretAccessKey'])
# s3 = boto3.resource("s3", creds['accessKeyId'], creds['secretAccessKey'])
#s3.Object('mybucket', 'hello.txt').put(Body=open('/tmp/hello.txt', 'rb'))
## Walk tree.
for curr_dir, dirs, files in os.walk(args.directory):
## We can navigate up if we are not in the root.
relative_to_start = curr_dir.rstrip('//')[len(args.directory):]
relative_to_start = relative_to_start.lstrip('//')
LOG.info('curr_dir: ' + curr_dir + ' (' + relative_to_start + ')')
## Note files and directories.
for fname in files:
## Get correct mime type.
fext = os.path.splitext(fname)[1].lstrip('.')
mime = MIMES.get('') # start with default
if MIMES.get(fext, False):
mime = MIMES.get(fext)
## Figure out S3 path/key and final filename, keeping in
## mind that relative_to_Start can be empty if root.
s3path = fname
if relative_to_start:
s3path = relative_to_start + '/' + fname
filename = os.path.join(curr_dir, fname)
tags = {}
if args.number:
tags['build-number'] = args.number
if args.pipeline:
tags['build-pipeline'] = args.pipeline
tags_str = urllib.parse.urlencode(tags)
## Visual check.
LOG.info('file: ' + filename)
if toppath != '':
s3path = toppath + '/' + s3path
LOG.info(' -> [' + bucket + '] ' + s3path + \
'(' + mime + ', ' + tags_str + ')')
## Create the new object that we want.
s3bucket = s3.Bucket(bucket)
multipart_upload(filename, s3bucket, s3path, content_type=mime, metadata=tags, policy="public-read")
# newobj = s3.Object(args.bucket, s3path)
# outfile = open(filename, 'rb')
# newobj.put(Body=outfile, \
# ContentType=mime, \
# Metadata=tags,
# ACL='public-read') #Tagging=tags_str)
# outbod = open(os.path.join(curr_dir, fname), 'rb')
# .put(Body=outbod, 'rb')
# for dname in dirs:
# #LOG.info('dir: ' + os.path.join(curr_dir, dname))
# pass
def multipart_upload(source_file_path, s3_bucket, s3_path, content_type=None, metadata=None, policy=None):
header = {}
if content_type:
header["ContentType"] = content_type
if metadata:
header["Metadata"] = metadata
if policy:
header["ACL"] = policy
s3_bucket.upload_file(source_file_path, s3_path, ExtraArgs=header)
## You saw it coming...
if __name__ == '__main__':
main()
| [
"logging.basicConfig",
"logging.getLogger",
"argparse.ArgumentParser",
"os.path.join",
"os.path.splitext",
"boto3.resource",
"boto3.set_stream_logger",
"sys.exit",
"urllib.parse.urlencode",
"os.walk"
] | [((1816, 1855), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (1835, 1855), False, 'import logging\n'), ((1862, 1892), 'logging.getLogger', 'logging.getLogger', (['"""aggregate"""'], {}), "('aggregate')\n", (1879, 1892), False, 'import logging\n'), ((2057, 2068), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (2065, 2068), False, 'import sys\n'), ((2140, 2243), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '__doc__', 'formatter_class': 'argparse.RawDescriptionHelpFormatter'}), '(description=__doc__, formatter_class=argparse.\n RawDescriptionHelpFormatter)\n', (2163, 2243), False, 'import argparse\n'), ((4948, 5088), 'boto3.resource', 'boto3.resource', (['"""s3"""'], {'region_name': 'args.location', 'aws_access_key_id': "creds['accessKeyId']", 'aws_secret_access_key': "creds['secretAccessKey']"}), "('s3', region_name=args.location, aws_access_key_id=creds[\n 'accessKeyId'], aws_secret_access_key=creds['secretAccessKey'])\n", (4962, 5088), False, 'import boto3\n'), ((5349, 5372), 'os.walk', 'os.walk', (['args.directory'], {}), '(args.directory)\n', (5356, 5372), False, 'import os\n'), ((3445, 3505), 'boto3.set_stream_logger', 'boto3.set_stream_logger', ([], {'name': '"""boto3"""', 'level': 'logging.WARNING'}), "(name='boto3', level=logging.WARNING)\n", (3468, 3505), False, 'import boto3\n'), ((3514, 3577), 'boto3.set_stream_logger', 'boto3.set_stream_logger', ([], {'name': '"""botocore"""', 'level': 'logging.WARNING'}), "(name='botocore', level=logging.WARNING)\n", (3537, 3577), False, 'import boto3\n'), ((6211, 6240), 'os.path.join', 'os.path.join', (['curr_dir', 'fname'], {}), '(curr_dir, fname)\n', (6223, 6240), False, 'import os\n'), ((6451, 6479), 'urllib.parse.urlencode', 'urllib.parse.urlencode', (['tags'], {}), '(tags)\n', (6473, 6479), False, 'import urllib\n'), ((3586, 3615), 'logging.getLogger', 'logging.getLogger', (['"""requests"""'], {}), "('requests')\n", (3603, 3615), False, 'import logging\n'), ((5764, 5787), 'os.path.splitext', 'os.path.splitext', (['fname'], {}), '(fname)\n', (5780, 5787), False, 'import os\n')] |
#!/usr/bin/env python
__author__ = '<NAME>'
import turtle
from datetime import datetime
import requests
import json
# Cleans up the json so that it is readable
def jprint(obj):
text = json.dumps(obj, sort_keys=True, indent=4)
print(text)
# gets the number and name of each astronaught
def get_astronauts_information(URL):
people = []
res = requests.get(URL + "/astros.json")
person = res.json()["people"]
amount = res.json()["number"]
# craft = res.json()["craft"]
for p in person:
# person = p["name"]
people.append(p)
# print(amount)
jprint(people)
# Get the ISS current geographic coordinates and a timestamp
def get_ISS_information(URL):
res = requests.get(URL)
time_stamp = datetime.fromtimestamp(res.json()["timestamp"])
location = res.json()["iss_position"]
latitude = location["latitude"]
longitude = location["longitude"]
return [time_stamp, latitude, longitude]
def create_world(shape, lat, long):
screen = turtle.Screen()
screen.title("ISS Location")
screen.setup(720, 360)
screen.setworldcoordinates(-180, -90, 180, 90)
screen.bgpic("map.gif")
screen.register_shape(shape)
create_ISS(shape, lat, long)
pass_over_Indy()
turtle.mainloop()
def create_ISS(shape, lat, long):
iss = turtle.Turtle()
iss.shape(shape)
iss.setheading(90)
iss.penup()
iss.goto(long, lat)
def pass_over_Indy():
indy_lat = 39.7684
indy_long = -86.1581
location = turtle.Turtle()
location.penup()
location.color("yellow")
location.goto(indy_long, indy_lat)
location.dot(5)
time = pass_over_info("http://api.open-notify.org/iss-pass.json",
indy_lat, indy_long)
style = ('Arial', 10, "bold")
location.write(time, font=style)
location.hideturtle()
def pass_over_info(URL, lat, long):
URL = URL + '?lat=' + str(lat) + '&lon=' + str(long)
res = requests.get(URL)
passover_time = datetime.fromtimestamp(
res.json()["response"][1]["risetime"])
return passover_time
def main():
get_astronauts_information("http://api.open-notify.org/")
iss = "iss.gif"
# get_astronauts("http://api.open-notify.org/astros.json")
time_stamp = get_ISS_information(
"http://api.open-notify.org/iss-now.json")[0]
latitude = float(get_ISS_information(
"http://api.open-notify.org/iss-now.json")[1])
longitude = float(get_ISS_information(
"http://api.open-notify.org/iss-now.json")[2])
create_world(iss, latitude, longitude)
print(f"Latitude: {latitude}\nLongitude: {longitude}\nTime :{time_stamp}")
if __name__ == '__main__':
main()
| [
"json.dumps",
"requests.get",
"turtle.mainloop",
"turtle.Screen",
"turtle.Turtle"
] | [((192, 233), 'json.dumps', 'json.dumps', (['obj'], {'sort_keys': '(True)', 'indent': '(4)'}), '(obj, sort_keys=True, indent=4)\n', (202, 233), False, 'import json\n'), ((364, 398), 'requests.get', 'requests.get', (["(URL + '/astros.json')"], {}), "(URL + '/astros.json')\n", (376, 398), False, 'import requests\n'), ((719, 736), 'requests.get', 'requests.get', (['URL'], {}), '(URL)\n', (731, 736), False, 'import requests\n'), ((1015, 1030), 'turtle.Screen', 'turtle.Screen', ([], {}), '()\n', (1028, 1030), False, 'import turtle\n'), ((1262, 1279), 'turtle.mainloop', 'turtle.mainloop', ([], {}), '()\n', (1277, 1279), False, 'import turtle\n'), ((1326, 1341), 'turtle.Turtle', 'turtle.Turtle', ([], {}), '()\n', (1339, 1341), False, 'import turtle\n'), ((1515, 1530), 'turtle.Turtle', 'turtle.Turtle', ([], {}), '()\n', (1528, 1530), False, 'import turtle\n'), ((1959, 1976), 'requests.get', 'requests.get', (['URL'], {}), '(URL)\n', (1971, 1976), False, 'import requests\n')] |
#!/usr/bin/env python3
import unittest
import os
import sys
import requests
import utils_test
from multiprocessing import Process
import time
sys.path.append(os.path.abspath('engram'))
import engram
class TestRedirect(utils_test.EngramTestCase):
def test_index(self):
"""
Story: Bookmark pages loads.
In order to access the bookmarks
I want to be able to use the endpoint /bookmarks
Scenario: requesting /bookmarks gets a response.
Given a running engram server on localhost:5000
When someone sends /bookmarks
Then the server sends back a html page
And the response has status 200.
"""
index_response = requests.get('http://localhost:5000/', timeout = 10)
assert index_response.status_code == 200
assert index_response.headers['content-type'] == "text/html; charset=utf-8"
unittest.main()
| [
"unittest.main",
"os.path.abspath",
"requests.get"
] | [((840, 855), 'unittest.main', 'unittest.main', ([], {}), '()\n', (853, 855), False, 'import unittest\n'), ((164, 189), 'os.path.abspath', 'os.path.abspath', (['"""engram"""'], {}), "('engram')\n", (179, 189), False, 'import os\n'), ((648, 698), 'requests.get', 'requests.get', (['"""http://localhost:5000/"""'], {'timeout': '(10)'}), "('http://localhost:5000/', timeout=10)\n", (660, 698), False, 'import requests\n')] |
from thunder.utils.common import checkParams
from thunder.extraction.source import SourceModel
class SourceExtraction(object):
"""
Factory for constructing source extraction methods.
Returns a source extraction method given a string identifier.
Options include: 'nmf', 'localmax', 'sima'
"""
def __new__(cls, method, **kwargs):
from thunder.extraction.block.methods.nmf import BlockNMF
from thunder.extraction.block.methods.sima import BlockSIMA
from thunder.extraction.feature.methods.localmax import LocalMax
EXTRACTION_METHODS = {
'nmf': BlockNMF,
'localmax': LocalMax,
'sima': BlockSIMA
}
checkParams(method, EXTRACTION_METHODS.keys())
return EXTRACTION_METHODS[method](**kwargs)
@staticmethod
def load(file):
return SourceModel.load(file)
@staticmethod
def deserialize(file):
return SourceModel.deserialize(file)
class SourceExtractionMethod(object):
def fit(self, data):
raise NotImplementedError
def run(self, data):
model = self.fit(data)
series = model.transform(data)
return model, series
| [
"thunder.extraction.source.SourceModel.load",
"thunder.extraction.source.SourceModel.deserialize"
] | [((860, 882), 'thunder.extraction.source.SourceModel.load', 'SourceModel.load', (['file'], {}), '(file)\n', (876, 882), False, 'from thunder.extraction.source import SourceModel\n'), ((944, 973), 'thunder.extraction.source.SourceModel.deserialize', 'SourceModel.deserialize', (['file'], {}), '(file)\n', (967, 973), False, 'from thunder.extraction.source import SourceModel\n')] |
from nonebot import on_command
from nonebot.typing import T_State
from nonebot.adapters.cqhttp import Bot, MessageEvent, MessageSegment, unescape
from .data_source import t2p, m2p
__des__ = '文本、Markdown转图片'
__cmd__ = '''
text2pic/t2p {text}
md2pic/m2p {text}
'''.strip()
__short_cmd__ = 't2p、m2p'
__example__ = '''
t2p test
m2p $test$ test `test`
'''.strip()
__usage__ = f'{__des__}\nUsage:\n{__cmd__}\nExample:\n{__example__}'
text2pic = on_command('text2pic', aliases={'t2p'}, priority=12)
md2pic = on_command('md2pic', aliases={'markdown', 'm2p'}, priority=12)
@text2pic.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State):
msg = unescape(event.get_plaintext().strip())
if not msg:
await text2pic.finish()
img = await t2p(msg)
if img:
await text2pic.finish(MessageSegment.image(img))
@md2pic.handle()
async def _(bot: Bot, event: MessageEvent, state: T_State):
msg = unescape(event.get_plaintext().strip())
if not msg:
await md2pic.finish()
img = await m2p(msg)
if img:
await md2pic.finish(MessageSegment.image(img))
| [
"nonebot.on_command",
"nonebot.adapters.cqhttp.MessageSegment.image"
] | [((443, 495), 'nonebot.on_command', 'on_command', (['"""text2pic"""'], {'aliases': "{'t2p'}", 'priority': '(12)'}), "('text2pic', aliases={'t2p'}, priority=12)\n", (453, 495), False, 'from nonebot import on_command\n'), ((505, 567), 'nonebot.on_command', 'on_command', (['"""md2pic"""'], {'aliases': "{'markdown', 'm2p'}", 'priority': '(12)'}), "('md2pic', aliases={'markdown', 'm2p'}, priority=12)\n", (515, 567), False, 'from nonebot import on_command\n'), ((815, 840), 'nonebot.adapters.cqhttp.MessageSegment.image', 'MessageSegment.image', (['img'], {}), '(img)\n', (835, 840), False, 'from nonebot.adapters.cqhttp import Bot, MessageEvent, MessageSegment, unescape\n'), ((1083, 1108), 'nonebot.adapters.cqhttp.MessageSegment.image', 'MessageSegment.image', (['img'], {}), '(img)\n', (1103, 1108), False, 'from nonebot.adapters.cqhttp import Bot, MessageEvent, MessageSegment, unescape\n')] |
import pytest
from helpers import create_request
import acurl
def test_to_curl():
r = create_request("GET", "http://foo.com")
assert r.to_curl() == "curl -X GET http://foo.com"
def test_to_curl_headers():
r = create_request(
"GET", "http://foo.com", headers=("Foo: bar", "My-Header: is-awesome")
)
assert (
r.to_curl()
== "curl -X GET -H 'Foo: bar' -H 'My-Header: is-awesome' http://foo.com"
)
def test_to_curl_cookies():
r = create_request(
"GET",
"http://foo.com",
cookies=(acurl._Cookie(False, "foo.com", True, "/", False, 0, "123", "456"),),
)
assert r.to_curl() == "curl -X GET --cookie 123=456 http://foo.com"
def test_to_curl_multiple_cookies():
r = create_request(
"GET",
"http://foo.com",
cookies=(
acurl._Cookie(False, "foo.com", True, "/", False, 0, "123", "456"),
acurl._Cookie(False, "foo.com", True, "/", False, 0, "789", "abc"),
),
)
assert r.to_curl() == "curl -X GET --cookie '123=456;789=abc' http://foo.com"
@pytest.mark.skip(reason="unimplemented")
def test_to_curl_cookies_wrong_domain():
# I'm not sure if this is a valid test case...Request objects should
# probably only be constructed via Session.request, which always creates
# cookies for the domain of the request. So the case this is exercising
# won't ever happen.
r = create_request(
"GET",
"http://foo.com",
cookies=(
acurl._Cookie(
False,
"bar.com", # The domain doesn't match, the cookie should not be passed
True,
"/",
False,
0,
"123",
"456",
),
),
)
assert r.to_curl() == "curl -X GET http://foo.com"
def test_to_curl_auth():
r = create_request("GET", "http://foo.com", auth=("user", "pass"))
assert r.to_curl() == "curl -X GET --user user:pass http://foo.com"
| [
"pytest.mark.skip",
"acurl._Cookie",
"helpers.create_request"
] | [((1104, 1144), 'pytest.mark.skip', 'pytest.mark.skip', ([], {'reason': '"""unimplemented"""'}), "(reason='unimplemented')\n", (1120, 1144), False, 'import pytest\n'), ((93, 132), 'helpers.create_request', 'create_request', (['"""GET"""', '"""http://foo.com"""'], {}), "('GET', 'http://foo.com')\n", (107, 132), False, 'from helpers import create_request\n'), ((230, 320), 'helpers.create_request', 'create_request', (['"""GET"""', '"""http://foo.com"""'], {'headers': "('Foo: bar', 'My-Header: is-awesome')"}), "('GET', 'http://foo.com', headers=('Foo: bar',\n 'My-Header: is-awesome'))\n", (244, 320), False, 'from helpers import create_request\n'), ((1912, 1974), 'helpers.create_request', 'create_request', (['"""GET"""', '"""http://foo.com"""'], {'auth': "('user', 'pass')"}), "('GET', 'http://foo.com', auth=('user', 'pass'))\n", (1926, 1974), False, 'from helpers import create_request\n'), ((566, 632), 'acurl._Cookie', 'acurl._Cookie', (['(False)', '"""foo.com"""', '(True)', '"""/"""', '(False)', '(0)', '"""123"""', '"""456"""'], {}), "(False, 'foo.com', True, '/', False, 0, '123', '456')\n", (579, 632), False, 'import acurl\n'), ((851, 917), 'acurl._Cookie', 'acurl._Cookie', (['(False)', '"""foo.com"""', '(True)', '"""/"""', '(False)', '(0)', '"""123"""', '"""456"""'], {}), "(False, 'foo.com', True, '/', False, 0, '123', '456')\n", (864, 917), False, 'import acurl\n'), ((931, 997), 'acurl._Cookie', 'acurl._Cookie', (['(False)', '"""foo.com"""', '(True)', '"""/"""', '(False)', '(0)', '"""789"""', '"""abc"""'], {}), "(False, 'foo.com', True, '/', False, 0, '789', 'abc')\n", (944, 997), False, 'import acurl\n'), ((1533, 1599), 'acurl._Cookie', 'acurl._Cookie', (['(False)', '"""bar.com"""', '(True)', '"""/"""', '(False)', '(0)', '"""123"""', '"""456"""'], {}), "(False, 'bar.com', True, '/', False, 0, '123', '456')\n", (1546, 1599), False, 'import acurl\n')] |
import torch
import torch.nn as nn
class Conv4(nn.Module):
def __init__(self, in_ch, imgsz, num_classes=10):
super(Conv4, self).__init__()
self.conv1 = nn.Conv2d(in_ch, 64, kernel_size=(3, 3), stride=1, padding=1)
self.conv2 = nn.Conv2d(64, 64, kernel_size=(3, 3), stride=1, padding=1)
self.conv3 = nn.Conv2d(64, 128, kernel_size=(3, 3), stride=1, padding=1)
self.conv4 = nn.Conv2d(128, 128, kernel_size=(3, 3), stride=1, padding=1)
self.maxpool = nn.MaxPool2d(kernel_size=2)
self.relu = nn.ReLU(inplace=True)
self.fc1 = nn.Linear(128*(imgsz//4)*(imgsz//4), 256)
self.fc2 = nn.Linear(256, 256)
self.fc3 = nn.Linear(256, num_classes)
def forward(self, x):
x = self.relu(self.conv1(x))
x = self.relu(self.conv2(x))
x = self.maxpool(x)
x = self.relu(self.conv3(x))
x = self.relu(self.conv4(x))
x = self.maxpool(x)
x = x.view( x.size(0), -1)
x = self.relu(self.fc1(x))
x = self.relu(self.fc2(x))
x = self.fc3(x)
return x | [
"torch.nn.ReLU",
"torch.nn.MaxPool2d",
"torch.nn.Linear",
"torch.nn.Conv2d"
] | [((163, 224), 'torch.nn.Conv2d', 'nn.Conv2d', (['in_ch', '(64)'], {'kernel_size': '(3, 3)', 'stride': '(1)', 'padding': '(1)'}), '(in_ch, 64, kernel_size=(3, 3), stride=1, padding=1)\n', (172, 224), True, 'import torch.nn as nn\n'), ((242, 300), 'torch.nn.Conv2d', 'nn.Conv2d', (['(64)', '(64)'], {'kernel_size': '(3, 3)', 'stride': '(1)', 'padding': '(1)'}), '(64, 64, kernel_size=(3, 3), stride=1, padding=1)\n', (251, 300), True, 'import torch.nn as nn\n'), ((318, 377), 'torch.nn.Conv2d', 'nn.Conv2d', (['(64)', '(128)'], {'kernel_size': '(3, 3)', 'stride': '(1)', 'padding': '(1)'}), '(64, 128, kernel_size=(3, 3), stride=1, padding=1)\n', (327, 377), True, 'import torch.nn as nn\n'), ((395, 455), 'torch.nn.Conv2d', 'nn.Conv2d', (['(128)', '(128)'], {'kernel_size': '(3, 3)', 'stride': '(1)', 'padding': '(1)'}), '(128, 128, kernel_size=(3, 3), stride=1, padding=1)\n', (404, 455), True, 'import torch.nn as nn\n'), ((475, 502), 'torch.nn.MaxPool2d', 'nn.MaxPool2d', ([], {'kernel_size': '(2)'}), '(kernel_size=2)\n', (487, 502), True, 'import torch.nn as nn\n'), ((519, 540), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (526, 540), True, 'import torch.nn as nn\n'), ((556, 605), 'torch.nn.Linear', 'nn.Linear', (['(128 * (imgsz // 4) * (imgsz // 4))', '(256)'], {}), '(128 * (imgsz // 4) * (imgsz // 4), 256)\n', (565, 605), True, 'import torch.nn as nn\n'), ((613, 632), 'torch.nn.Linear', 'nn.Linear', (['(256)', '(256)'], {}), '(256, 256)\n', (622, 632), True, 'import torch.nn as nn\n'), ((648, 675), 'torch.nn.Linear', 'nn.Linear', (['(256)', 'num_classes'], {}), '(256, num_classes)\n', (657, 675), True, 'import torch.nn as nn\n')] |
'''
This code is used for testing MoDL on JPEG-compressed data, for the results shown in figures 6, 7 and 8c in the paper.
Before running this script you should update the following:
basic_data_folder - it should be the same as the output folder defined in the script /crime_2_jpeg/data_prep/jpeg_data_prep.py
(c) <NAME>, UC Berkeley, 2021
'''
import logging
import os
import matplotlib.pyplot as plt
import numpy as np
import torch
from MoDL_single import UnrolledModel
from subtle_data_crimes.functions.error_funcs import error_metrics
from utils import complex_utils as cplx
from utils.datasets import create_data_loaders
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
# create a folder for the test figures
if not os.path.exists('test_figs'):
os.makedirs('test_figs')
##################### create test loader ###########################
class Namespace:
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
# Hyper parameters
params = Namespace()
params.batch_size = 1
# image dimensions
params.NX = 640
params.NY = 372
# calib is assumed to be 12 for NX=640
calib_x = int(12)
calib_y = int(12 * params.NY / params.NX)
params.calib = np.array([calib_x, calib_y])
params.shuffle_flag = False # should be True for training, False for testing. Notice that this is not a string, semicolons aren't necessary.
params.sampling_flag = 'var_dens_2D'
params.var_dens_flag = 'strong' # 'weak' / 'strong'
checkpoint_num = int(69) # load saved model (trained network)
q_vec = np.array([20, 50, 75, 999])
R_vec = np.array([4])
N_examples_4display = 15 # number of examples to display
N_examples_stats = 15 # number of examples over which the mean and STD will be computed
NRMSE_av_vs_q_and_R = np.zeros((R_vec.shape[0], q_vec.shape[0]))
NRMSE_std_vs_q_and_R = np.zeros((R_vec.shape[0], q_vec.shape[0]))
SSIM_av_vs_q_and_R = np.zeros((R_vec.shape[0], q_vec.shape[0]))
SSIM_std_vs_q_and_R = np.zeros((R_vec.shape[0], q_vec.shape[0]))
N_calc_err = 200
NRMSE_examples_4display = np.zeros((R_vec.shape[0], q_vec.shape[0], N_calc_err))
SSIM_examples_4display = np.zeros((R_vec.shape[0], q_vec.shape[0], N_calc_err))
small_dataset_flag = 0
for r in range(R_vec.shape[0]):
R = R_vec[r]
print('================================================== ')
print(' R={} '.format(R))
print('================================================== ')
# Important - here we update R in the params in order to create masks with appropriate sampling
# The mask is created in the DataTransform (utils/datasets
params.R = R
for qi in range(q_vec.shape[0]):
q = q_vec[qi]
params.q = q
# update the next path to YOUR path
basic_data_folder = "/mikQNAP/NYU_knee_data/multicoil_efrat/5_JPEG_compressed_data/"
data_type = 'test'
im_type_str = 'full_im' # training & validation is done on blocks (to accelerate training). Test is done on full-size images.
params.data_path = basic_data_folder + data_type + "/q" + str(params.q) + "/" + im_type_str + "/"
test_loader = create_data_loaders(params)
N_test_batches = len(test_loader.dataset)
print('N_test_batches =', N_test_batches)
checkpoint_file = 'R{}_q{}/checkpoints/model_{}.pt'.format(R, q, checkpoint_num)
checkpoint = torch.load(checkpoint_file, map_location=device)
# load the parameters of the trained network
params_loaded = checkpoint["params"]
single_MoDL = UnrolledModel(params_loaded).to(device)
single_MoDL.load_state_dict(checkpoint['model'])
single_MoDL.eval()
NRMSE_test_list = []
SSIM_test_list = []
cnt = 0
with torch.no_grad():
for iter, data in enumerate(test_loader):
if iter % 10 == 0:
print('loading test batch ', iter)
# input_batch, target_batch, mask_batch, target_no_JPEG_batch = data
input_batch, target_batch, mask_batch = data
# display the mask (before converting it to torch tensor)
if (iter == 0):
# print('mask_batch shape:',mask_batch.shape)
mask_squeezed = mask_batch[0, :, :, 0].squeeze()
# fig = plt.figure()
# plt.imshow(mask_squeezed, cmap="gray")
# plt.title(params.sampling_flag + ' epoch 0, iter {}'.format(iter))
# plt.show()
# fig.savefig('mask_iter{}.png'.format(iter))
# move data to GPU
input_batch = input_batch.to(device)
target_batch = target_batch.to(device)
mask_batch = mask_batch.to(device)
# forward pass - for the full batch
out_batch = single_MoDL(input_batch.float(), mask=mask_batch)
for i in range(params.batch_size):
cnt += 1 # counts the number of test images
print('cnt={}'.format(cnt))
im_input = cplx.to_numpy(input_batch.cpu())[i, :, :]
im_target = cplx.to_numpy(target_batch.cpu())[i, :, :]
im_out = cplx.to_numpy(out_batch.cpu())[i, :, :]
MoDL_err = error_metrics(np.abs(im_target), np.abs(im_out))
MoDL_err.calc_NRMSE()
MoDL_err.calc_SSIM()
NRMSE_test_list.append(MoDL_err.NRMSE)
SSIM_test_list.append(MoDL_err.SSIM)
if cnt < N_calc_err:
NRMSE_examples_4display[r, qi, cnt - 1] = MoDL_err.NRMSE
SSIM_examples_4display[r, qi, cnt - 1] = MoDL_err.SSIM
if cnt <= N_examples_4display:
target_im_rotated = np.rot90(np.abs(im_target), 2)
im_out_rotated = np.rot90(np.abs(im_out), 2)
NX = im_out_rotated.shape[0]
NY = im_out_rotated.shape[1]
if (r == 0) & (qi == 0) & (iter == 0):
TARGETS = np.zeros((NX, NY, q_vec.shape[0], N_examples_4display))
RECS = np.zeros((NX, NY, R_vec.shape[0], q_vec.shape[0], N_examples_4display))
TARGETS[:, :, qi, iter] = target_im_rotated
RECS[:, :, r, qi, iter] = im_out_rotated
# if iter==0:
fig = plt.figure()
plt.imshow(target_im_rotated, cmap="gray")
plt.colorbar(shrink=0.5)
plt.axis('off')
plt.title('target - iter={} - R{} q{}'.format(iter, R, q))
plt.show()
figname = 'check3_target_R{}_q{}_iter{}'.format(R, q, iter)
fig.savefig(figname)
if iter >= N_examples_stats:
break
# NRMSE - calc av & std
NRMSE_test_array = np.asarray(NRMSE_test_list)
NRMSE_av = np.mean(NRMSE_test_array[0:N_examples_stats].squeeze())
NRMSE_std = np.std(NRMSE_test_array[0:N_examples_stats].squeeze())
NRMSE_av_vs_q_and_R[r, qi] = NRMSE_av
NRMSE_std_vs_q_and_R[r, qi] = NRMSE_std
# SSIM - calc av & std
SSIM_test_array = np.asarray(SSIM_test_list)
SSIM_av = np.mean(SSIM_test_array[0:N_examples_stats].squeeze())
SSIM_std = np.std(SSIM_test_array[0:N_examples_stats].squeeze())
SSIM_av_vs_q_and_R[r, qi] = SSIM_av
SSIM_std_vs_q_and_R[r, qi] = SSIM_std
print('q={} NRMSE_av = {}, SSIM_av = {}'.format(q, NRMSE_av, SSIM_av))
# save NRMSE_av & SSIM
print('saving results')
results_filename = 'Res_for_Fig6.npz'
np.savez(results_filename, R_vec=R_vec, q_vec=q_vec, params=params, checkpoint_num=checkpoint_num,
NRMSE_av_vs_q_and_R=NRMSE_av_vs_q_and_R,
NRMSE_std_vs_q_and_R=NRMSE_std_vs_q_and_R,
SSIM_av_vs_q_and_R=SSIM_av_vs_q_and_R,
SSIM_std_vs_q_and_R=SSIM_std_vs_q_and_R,
NRMSE_examples_4display=NRMSE_examples_4display,
SSIM_examples_4display=SSIM_examples_4display,
N_examples_stats=N_examples_stats,
N_examples_4display=N_examples_4display,
TARGETS=TARGETS,
RECS=RECS,
)
| [
"logging.getLogger",
"utils.datasets.create_data_loaders",
"MoDL_single.UnrolledModel",
"numpy.array",
"torch.cuda.is_available",
"matplotlib.pyplot.imshow",
"os.path.exists",
"numpy.savez",
"numpy.asarray",
"matplotlib.pyplot.axis",
"numpy.abs",
"matplotlib.pyplot.show",
"logging.basicConfi... | [((652, 691), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (671, 691), False, 'import logging\n'), ((702, 729), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (719, 729), False, 'import logging\n'), ((1324, 1352), 'numpy.array', 'np.array', (['[calib_x, calib_y]'], {}), '([calib_x, calib_y])\n', (1332, 1352), True, 'import numpy as np\n'), ((1667, 1694), 'numpy.array', 'np.array', (['[20, 50, 75, 999]'], {}), '([20, 50, 75, 999])\n', (1675, 1694), True, 'import numpy as np\n'), ((1704, 1717), 'numpy.array', 'np.array', (['[4]'], {}), '([4])\n', (1712, 1717), True, 'import numpy as np\n'), ((1894, 1936), 'numpy.zeros', 'np.zeros', (['(R_vec.shape[0], q_vec.shape[0])'], {}), '((R_vec.shape[0], q_vec.shape[0]))\n', (1902, 1936), True, 'import numpy as np\n'), ((1961, 2003), 'numpy.zeros', 'np.zeros', (['(R_vec.shape[0], q_vec.shape[0])'], {}), '((R_vec.shape[0], q_vec.shape[0]))\n', (1969, 2003), True, 'import numpy as np\n'), ((2026, 2068), 'numpy.zeros', 'np.zeros', (['(R_vec.shape[0], q_vec.shape[0])'], {}), '((R_vec.shape[0], q_vec.shape[0]))\n', (2034, 2068), True, 'import numpy as np\n'), ((2092, 2134), 'numpy.zeros', 'np.zeros', (['(R_vec.shape[0], q_vec.shape[0])'], {}), '((R_vec.shape[0], q_vec.shape[0]))\n', (2100, 2134), True, 'import numpy as np\n'), ((2184, 2238), 'numpy.zeros', 'np.zeros', (['(R_vec.shape[0], q_vec.shape[0], N_calc_err)'], {}), '((R_vec.shape[0], q_vec.shape[0], N_calc_err))\n', (2192, 2238), True, 'import numpy as np\n'), ((2265, 2319), 'numpy.zeros', 'np.zeros', (['(R_vec.shape[0], q_vec.shape[0], N_calc_err)'], {}), '((R_vec.shape[0], q_vec.shape[0], N_calc_err))\n', (2273, 2319), True, 'import numpy as np\n'), ((8231, 8719), 'numpy.savez', 'np.savez', (['results_filename'], {'R_vec': 'R_vec', 'q_vec': 'q_vec', 'params': 'params', 'checkpoint_num': 'checkpoint_num', 'NRMSE_av_vs_q_and_R': 'NRMSE_av_vs_q_and_R', 'NRMSE_std_vs_q_and_R': 'NRMSE_std_vs_q_and_R', 'SSIM_av_vs_q_and_R': 'SSIM_av_vs_q_and_R', 'SSIM_std_vs_q_and_R': 'SSIM_std_vs_q_and_R', 'NRMSE_examples_4display': 'NRMSE_examples_4display', 'SSIM_examples_4display': 'SSIM_examples_4display', 'N_examples_stats': 'N_examples_stats', 'N_examples_4display': 'N_examples_4display', 'TARGETS': 'TARGETS', 'RECS': 'RECS'}), '(results_filename, R_vec=R_vec, q_vec=q_vec, params=params,\n checkpoint_num=checkpoint_num, NRMSE_av_vs_q_and_R=NRMSE_av_vs_q_and_R,\n NRMSE_std_vs_q_and_R=NRMSE_std_vs_q_and_R, SSIM_av_vs_q_and_R=\n SSIM_av_vs_q_and_R, SSIM_std_vs_q_and_R=SSIM_std_vs_q_and_R,\n NRMSE_examples_4display=NRMSE_examples_4display, SSIM_examples_4display\n =SSIM_examples_4display, N_examples_stats=N_examples_stats,\n N_examples_4display=N_examples_4display, TARGETS=TARGETS, RECS=RECS)\n', (8239, 8719), True, 'import numpy as np\n'), ((853, 880), 'os.path.exists', 'os.path.exists', (['"""test_figs"""'], {}), "('test_figs')\n", (867, 880), False, 'import os\n'), ((887, 911), 'os.makedirs', 'os.makedirs', (['"""test_figs"""'], {}), "('test_figs')\n", (898, 911), False, 'import os\n'), ((765, 790), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (788, 790), False, 'import torch\n'), ((3318, 3345), 'utils.datasets.create_data_loaders', 'create_data_loaders', (['params'], {}), '(params)\n', (3337, 3345), False, 'from utils.datasets import create_data_loaders\n'), ((3566, 3614), 'torch.load', 'torch.load', (['checkpoint_file'], {'map_location': 'device'}), '(checkpoint_file, map_location=device)\n', (3576, 3614), False, 'import torch\n'), ((3964, 3979), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (3977, 3979), False, 'import torch\n'), ((7394, 7421), 'numpy.asarray', 'np.asarray', (['NRMSE_test_list'], {}), '(NRMSE_test_list)\n', (7404, 7421), True, 'import numpy as np\n'), ((7771, 7797), 'numpy.asarray', 'np.asarray', (['SSIM_test_list'], {}), '(SSIM_test_list)\n', (7781, 7797), True, 'import numpy as np\n'), ((3740, 3768), 'MoDL_single.UnrolledModel', 'UnrolledModel', (['params_loaded'], {}), '(params_loaded)\n', (3753, 3768), False, 'from MoDL_single import UnrolledModel\n'), ((5593, 5610), 'numpy.abs', 'np.abs', (['im_target'], {}), '(im_target)\n', (5599, 5610), True, 'import numpy as np\n'), ((5612, 5626), 'numpy.abs', 'np.abs', (['im_out'], {}), '(im_out)\n', (5618, 5626), True, 'import numpy as np\n'), ((6825, 6837), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (6835, 6837), True, 'import matplotlib.pyplot as plt\n'), ((6863, 6905), 'matplotlib.pyplot.imshow', 'plt.imshow', (['target_im_rotated'], {'cmap': '"""gray"""'}), "(target_im_rotated, cmap='gray')\n", (6873, 6905), True, 'import matplotlib.pyplot as plt\n'), ((6931, 6955), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {'shrink': '(0.5)'}), '(shrink=0.5)\n', (6943, 6955), True, 'import matplotlib.pyplot as plt\n'), ((6981, 6996), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (6989, 6996), True, 'import matplotlib.pyplot as plt\n'), ((7106, 7116), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (7114, 7116), True, 'import matplotlib.pyplot as plt\n'), ((6147, 6164), 'numpy.abs', 'np.abs', (['im_target'], {}), '(im_target)\n', (6153, 6164), True, 'import numpy as np\n'), ((6220, 6234), 'numpy.abs', 'np.abs', (['im_out'], {}), '(im_out)\n', (6226, 6234), True, 'import numpy as np\n'), ((6452, 6507), 'numpy.zeros', 'np.zeros', (['(NX, NY, q_vec.shape[0], N_examples_4display)'], {}), '((NX, NY, q_vec.shape[0], N_examples_4display))\n', (6460, 6507), True, 'import numpy as np\n'), ((6544, 6615), 'numpy.zeros', 'np.zeros', (['(NX, NY, R_vec.shape[0], q_vec.shape[0], N_examples_4display)'], {}), '((NX, NY, R_vec.shape[0], q_vec.shape[0], N_examples_4display))\n', (6552, 6615), True, 'import numpy as np\n')] |
"""Common entities."""
from __future__ import annotations
from abc import ABC
import logging
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from homeassistant.util import slugify
from .const import DOMAIN as MULTIMATIC
from .coordinator import MultimaticCoordinator
_LOGGER = logging.getLogger(__name__)
class MultimaticEntity(CoordinatorEntity, ABC):
"""Define base class for multimatic entities."""
coordinator: MultimaticCoordinator
def __init__(self, coordinator: MultimaticCoordinator, domain, device_id):
"""Initialize entity."""
super().__init__(coordinator)
id_part = slugify(
device_id
+ (f"_{coordinator.api.serial}" if coordinator.api.fixed_serial else "")
)
self.entity_id = f"{domain}.{id_part}"
self._unique_id = slugify(f"{MULTIMATIC}_{coordinator.api.serial}_{device_id}")
self._remove_listener = None
@property
def unique_id(self) -> str:
"""Return a unique ID."""
return self._unique_id
async def async_added_to_hass(self):
"""Call when entity is added to hass."""
await super().async_added_to_hass()
_LOGGER.debug("%s added", self.entity_id)
self.coordinator.add_api_listener(self.unique_id)
async def async_will_remove_from_hass(self) -> None:
"""Run when entity will be removed from hass."""
await super().async_will_remove_from_hass()
self.coordinator.remove_api_listener(self.unique_id)
@property
def available(self) -> bool:
"""Return if entity is available."""
return super().available and self.coordinator.data
| [
"logging.getLogger",
"homeassistant.util.slugify"
] | [((304, 331), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (321, 331), False, 'import logging\n'), ((645, 741), 'homeassistant.util.slugify', 'slugify', (["(device_id + (f'_{coordinator.api.serial}' if coordinator.api.fixed_serial else\n ''))"], {}), "(device_id + (f'_{coordinator.api.serial}' if coordinator.api.\n fixed_serial else ''))\n", (652, 741), False, 'from homeassistant.util import slugify\n'), ((845, 906), 'homeassistant.util.slugify', 'slugify', (['f"""{MULTIMATIC}_{coordinator.api.serial}_{device_id}"""'], {}), "(f'{MULTIMATIC}_{coordinator.api.serial}_{device_id}')\n", (852, 906), False, 'from homeassistant.util import slugify\n')] |
"""
# Problem: flip_bit_mutation.py
# Description:
# Created by ngocjr7 on [2020-03-31 16:49:14]
"""
from __future__ import absolute_import
from geneticpython.models.binary_individual import BinaryIndividual
from .mutation import Mutation
from geneticpython.utils.validation import check_random_state
from random import Random
import random
class FlipBitMutation(Mutation):
def __init__(self, pm : float, pe : float = None):
super(FlipBitMutation, self).__init__(pm=pm)
if pe is None:
pe = pm
if pe <= 0.0 or pe > 1.0:
raise ValueError('Invalid mutation probability')
self.pe = pe
def mutate(self, individual: BinaryIndividual, random_state=None):
random_state = check_random_state(random_state)
do_mutation = True if random_state.random() <= self.pm else False
ret_individual = individual.clone()
if do_mutation:
for i, genome in enumerate(ret_individual.chromosome.genes):
flip = True if random_state.random() <= self.pe else False
if flip:
ret_individual.chromosome.genes[i] = genome^1
return ret_individual
| [
"geneticpython.utils.validation.check_random_state"
] | [((780, 812), 'geneticpython.utils.validation.check_random_state', 'check_random_state', (['random_state'], {}), '(random_state)\n', (798, 812), False, 'from geneticpython.utils.validation import check_random_state\n')] |
from __future__ import unicode_literals
from django.conf import settings
from django.contrib.auth import logout
def cradmin_logoutview(request, template_name='cradmin_authenticate/logout.django.html'):
next_page = None
if 'next' in request.GET:
next_page = request.GET['next']
return logout(
request,
template_name=template_name,
next_page=next_page,
extra_context={
'LOGIN_URL': settings.LOGIN_URL
})
| [
"django.contrib.auth.logout"
] | [((306, 424), 'django.contrib.auth.logout', 'logout', (['request'], {'template_name': 'template_name', 'next_page': 'next_page', 'extra_context': "{'LOGIN_URL': settings.LOGIN_URL}"}), "(request, template_name=template_name, next_page=next_page,\n extra_context={'LOGIN_URL': settings.LOGIN_URL})\n", (312, 424), False, 'from django.contrib.auth import logout\n')] |
from gemstone.core.modules import Module
import gemstone
class SecondModule(Module):
@gemstone.exposed_method("module2.say_hello")
def say_hello(self):
return "Hello from module 2!"
| [
"gemstone.exposed_method"
] | [((92, 136), 'gemstone.exposed_method', 'gemstone.exposed_method', (['"""module2.say_hello"""'], {}), "('module2.say_hello')\n", (115, 136), False, 'import gemstone\n')] |
from ..entity.host import Node
from ..valueobject.validator import ValidatorResult
import time
import datetime
import tornado.log
class Validator:
max_cache_time = 120.0
# static
cache = {}
def __init__(self, max_cache_time: int):
self.max_cache_time = max_cache_time
def _get_cache_ident(self, node: Node):
return str(node) + '_' + str(type(self).__name__)
def _cache_results(self, result: ValidatorResult, node: Node) -> ValidatorResult:
result.inject_last_check_time(datetime.datetime.now().strftime('%d.%m.%Y %H:%M:%S'))
Validator.cache[self._get_cache_ident(node)] = {
'result': result,
'created_at': time.time()
}
tornado.log.app_log.info('Cache created')
return Validator.cache[self._get_cache_ident(node)]['result']
def _get_results_from_cache(self, node: Node):
ident = self._get_cache_ident(node)
if ident not in Validator.cache:
tornado.log.app_log.info('Cache not found')
return None, None
cached = Validator.cache[ident]
if not cached['result']:
tornado.log.app_log.info('Cache not warmed up yet...')
return None, None
if time.time() >= (cached['created_at'] + self.max_cache_time):
tornado.log.app_log.info('Cache expired')
return cached['result'], cached['created_at']
def is_valid(self, node: Node, force=False, only_cache=False) -> ValidatorResult:
results, cache_time = self._get_results_from_cache(node)
if only_cache and not results:
return ValidatorResult(False, 'Status not ready, waiting for check to be initially performed...', [])
if results and not force:
return results
return self._cache_results(self._is_valid(node), node)
def _is_valid(self, node: Node) -> ValidatorResult:
pass
| [
"datetime.datetime.now",
"time.time"
] | [((694, 705), 'time.time', 'time.time', ([], {}), '()\n', (703, 705), False, 'import time\n'), ((1246, 1257), 'time.time', 'time.time', ([], {}), '()\n', (1255, 1257), False, 'import time\n'), ((525, 548), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (546, 548), False, 'import datetime\n')] |
import numpy as np
from scipy.spatial import cKDTree as KDTree
import math
import argparse
# ref: https://github.com/facebookresearch/DeepSDF/blob/master/deep_sdf/metrics/chamfer.py
# takes one pair of reconstructed and gt point cloud and return the cd
def compute_cd(gt_points, gen_points):
# one direction
gen_points_kd_tree = KDTree(gen_points)
one_distances, one_vertex_ids = gen_points_kd_tree.query(gt_points)
gt_to_gen_chamfer = np.mean(np.square(one_distances))
# other direction
gt_points_kd_tree = KDTree(gt_points)
two_distances, two_vertex_ids = gt_points_kd_tree.query(gen_points)
gen_to_gt_chamfer = np.mean(np.square(two_distances))
return gt_to_gen_chamfer + gen_to_gt_chamfer
if __name__ == '__main__':
num_gen_pts_sample = 30000
parser = argparse.ArgumentParser()
parser.add_argument('--gt_pts_path', type=str, help='Path to ground truth point clouds (numpy array)')
parser.add_argument('--gen_pts_path', type=str, help='Path to corresponsing reconstructed point clouds (numpy array)')
args = parser.parse_args()
test_gt_pts = np.load(args.gt_pts_path, allow_pickle=True)
test_gen_pts = np.load(args.gen_pts_path, allow_pickle=True)
assert test_gen_pts.shape[0] == test_gt_pts.shape[0]
num_instances = test_gen_pts.shape[0]
chamfer_results = []
print('Might take a few minutes ...')
for instance_idx in range(num_instances):
gt_pts_instance = test_gt_pts[instance_idx]
gen_pts_instance = test_gen_pts[instance_idx]
if gen_pts_instance.shape[0] < 2000:
continue
# if the number of points in reconstructed point cloud is < num_gen_pts_sample,
# repeat the points randomly to make number of points = num_gen_pts_sample
if gen_pts_instance.shape[0]<num_gen_pts_sample:
pt_indices = np.concatenate([
np.arange(len(gen_pts_instance)),
np.random.choice(len(gen_pts_instance), num_gen_pts_sample-len(gen_pts_instance))
])
gen_pts_instance = gen_pts_instance[pt_indices]
np.random.shuffle(gt_pts_instance)
np.random.shuffle(gen_pts_instance)
cd = compute_cd(gt_pts_instance, gen_pts_instance)
if math.isnan(cd):
continue
chamfer_results.append(cd)
chamfer_results.sort()
print('Ground truth point cloud: {}'.format(args.gt_pts_path))
print('Reconstructed point cloud: {}'.format(args.gen_pts_path))
cd_avg = sum(chamfer_results) / float(len(chamfer_results))
print('Average Chamfer Distance: {}'.format(cd_avg))
print('Median Chamfer Distance: {}'.format(chamfer_results[len(chamfer_results)//2]))
print('-'*80)
| [
"argparse.ArgumentParser",
"scipy.spatial.cKDTree",
"numpy.square",
"math.isnan",
"numpy.load",
"numpy.random.shuffle"
] | [((341, 359), 'scipy.spatial.cKDTree', 'KDTree', (['gen_points'], {}), '(gen_points)\n', (347, 359), True, 'from scipy.spatial import cKDTree as KDTree\n'), ((537, 554), 'scipy.spatial.cKDTree', 'KDTree', (['gt_points'], {}), '(gt_points)\n', (543, 554), True, 'from scipy.spatial import cKDTree as KDTree\n'), ((810, 835), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (833, 835), False, 'import argparse\n'), ((1117, 1161), 'numpy.load', 'np.load', (['args.gt_pts_path'], {'allow_pickle': '(True)'}), '(args.gt_pts_path, allow_pickle=True)\n', (1124, 1161), True, 'import numpy as np\n'), ((1181, 1226), 'numpy.load', 'np.load', (['args.gen_pts_path'], {'allow_pickle': '(True)'}), '(args.gen_pts_path, allow_pickle=True)\n', (1188, 1226), True, 'import numpy as np\n'), ((464, 488), 'numpy.square', 'np.square', (['one_distances'], {}), '(one_distances)\n', (473, 488), True, 'import numpy as np\n'), ((659, 683), 'numpy.square', 'np.square', (['two_distances'], {}), '(two_distances)\n', (668, 683), True, 'import numpy as np\n'), ((2137, 2171), 'numpy.random.shuffle', 'np.random.shuffle', (['gt_pts_instance'], {}), '(gt_pts_instance)\n', (2154, 2171), True, 'import numpy as np\n'), ((2180, 2215), 'numpy.random.shuffle', 'np.random.shuffle', (['gen_pts_instance'], {}), '(gen_pts_instance)\n', (2197, 2215), True, 'import numpy as np\n'), ((2288, 2302), 'math.isnan', 'math.isnan', (['cd'], {}), '(cd)\n', (2298, 2302), False, 'import math\n')] |
#!/usr/bin/env python3
# This is the master ImageAnalysis processing script. For DJI and
# Sentera cameras it should typically be able to run through with
# default settings and produce a good result with no further input.
#
# If something goes wrong, there are usually specific sub-scripts that
# can be run to fix the problem and then this script can be re-run to
# continue.
#
# If your camera isn't yet supported, you can run a script that mostly
# automates the process of adding a new camera (possibly with a small
# amount of extra info that you can usually research by googling.
#
# If you run into an unsolvable glitch and are willing to share your
# data set, I may be able to look at the issue and make some sort of
# determination or fix.
import argparse
import numpy as np
import os
import pickle
import socket # gethostname()
import time
from lib import camera
from lib import groups
from lib.logger import log
from lib import matcher
from lib import match_cleanup
from lib import optimizer
from lib import pose
from lib import project
from lib import render_panda3d
from lib import smart
from lib import srtm
from lib import state
from props import getNode, PropertyNode # from the aura-props python package
import props_json
parser = argparse.ArgumentParser(description='Create an empty project.')
parser.add_argument('project', help='Directory with a set of aerial images.')
# camera setup options
parser.add_argument('--camera', help='camera config file')
parser.add_argument('--yaw-deg', type=float, default=0.0,
help='camera yaw mounting offset from aircraft')
parser.add_argument('--pitch-deg', type=float, default=-90.0,
help='camera pitch mounting offset from aircraft')
parser.add_argument('--roll-deg', type=float, default=0.0,
help='camera roll mounting offset from aircraft')
# pose setup options
parser.add_argument('--max-angle', type=float, default=25.0, help='max pitch or roll angle for image inclusion')
parser.add_argument('--force-altitude', type=float, help='Fudge altitude geotag for stupid dji phantom 4 pro v2.0')
# feature detection options
parser.add_argument('--scale', type=float, default=0.4, help='scale images before detecting features, this acts much like a noise filter')
parser.add_argument('--detector', default='SIFT',
choices=['SIFT', 'SURF', 'ORB', 'Star'])
parser.add_argument('--surf-hessian-threshold', default=600,
help='hessian threshold for surf method')
parser.add_argument('--surf-noctaves', default=4,
help='use a bigger number to detect bigger features')
parser.add_argument('--orb-max-features', default=20000,
help='maximum ORB features')
parser.add_argument('--grid-detect', default=1,
help='run detect on gridded squares for (maybe) better feature distribution, 4 is a good starting value, only affects ORB method')
parser.add_argument('--star-max-size', default=16,
help='4, 6, 8, 11, 12, 16, 22, 23, 32, 45, 46, 64, 90, 128')
parser.add_argument('--star-response-threshold', default=30)
parser.add_argument('--star-line-threshold-projected', default=10)
parser.add_argument('--star-line-threshold-binarized', default=8)
parser.add_argument('--star-suppress-nonmax-size', default=5)
parser.add_argument('--reject-margin', default=0, help='reject features within this distance of the image outer edge margin')
# feature matching arguments
parser.add_argument('--match-strategy', default='traditional',
choices=['smart', 'bestratio', 'traditional', 'bruteforce'])
parser.add_argument('--match-ratio', default=0.75, type=float,
help='match ratio')
parser.add_argument('--min-pairs', default=25, type=int,
help='minimum matches between image pairs to keep')
parser.add_argument('--min-dist', type=float,
help='minimum 2d camera distance for pair comparison')
parser.add_argument('--max-dist', type=float,
help='maximum 2d camera distance for pair comparison')
parser.add_argument('--filter', default='gms',
choices=['gms', 'homography', 'fundamental', 'essential', 'none'])
parser.add_argument('--min-chain-length', type=int, default=3, help='minimum match chain length (3 recommended)')
# for smart matching
parser.add_argument('--ground', type=float, help="ground elevation")
# optimizer arguments
parser.add_argument('--group', type=int, default=0, help='group number')
parser.add_argument('--cam-calibration', action='store_true', help='include camera calibration in the optimization.')
parser.add_argument('--refine', action='store_true', help='refine a previous optimization.')
args = parser.parse_args()
log("Project processed on host:", socket.gethostname())
log("Project processed with arguments:", args)
############################################################################
log("Step 1: setup the project", fancy=True)
############################################################################
### 1a. initialize a new project workspace
# test if images directory exists
if not os.path.isdir(args.project):
print("Images directory doesn't exist:", args.project)
quit()
# create an empty project and save...
proj = project.ProjectMgr(args.project, create=True)
proj.save()
log("Created project:", args.project)
### 1b. intialize camera
if args.camera:
# specified on command line
camera_file = args.camera
else:
# auto detect camera from image meta data
camera_name, make, model, lens_model = proj.detect_camera()
camera_file = os.path.join("..", "cameras", camera_name + ".json")
log("Camera auto-detected:", camera_name, make, model, lens_model)
log("Camera file:", camera_file)
# copy/overlay/update the specified camera config into the existing
# project configuration
cam_node = getNode('/config/camera', True)
tmp_node = PropertyNode()
if props_json.load(camera_file, tmp_node):
props_json.overlay(cam_node, tmp_node)
if cam_node.getString("make") == "DJI":
# phantom, et al.
camera.set_mount_params(0.0, 0.0, 0.0)
elif cam_node.getString("make") == "Hasselblad":
# mavic pro
camera.set_mount_params(0.0, 0.0, 0.0)
else:
# assume a nadir camera rigidly mounted to airframe
camera.set_mount_params(args.yaw_deg, args.pitch_deg, args.roll_deg)
# note: dist_coeffs = array[5] = k1, k2, p1, p2, k3
# ... and save
proj.save()
else:
# failed to load camera config file
if not args.camera:
log("Camera autodetection failed. Consider running the new camera script to create a camera config and then try running this script again.")
else:
log("Specified camera config not found:", args.camera)
log("Aborting due to camera detection failure.")
quit()
state.update("STEP1")
############################################################################
log("Step 2: configure camera poses and per-image meta data files", fancy=True)
############################################################################
log("Configuring images")
# create pose file (if it doesn't already exist, for example sentera
# cameras will generate the pix4d.csv file automatically, dji does not)
pix4d_file = os.path.join(args.project, 'pix4d.csv')
meta_file = os.path.join(args.project, 'image-metadata.txt')
if os.path.exists(pix4d_file):
log("Found a pose file:", pix4d_file)
elif os.path.exists(meta_file):
log("Found a pose file:", meta_file)
else:
pose.make_pix4d(args.project, args.force_altitude)
pix4d_file = os.path.join(args.project, 'pix4d.csv')
meta_file = os.path.join(args.project, 'image-metadata.txt')
if os.path.exists(pix4d_file):
pose.set_aircraft_poses(proj, pix4d_file, order='rpy',
max_angle=args.max_angle)
elif os.path.exists(meta_file):
pose.set_aircraft_poses(proj, meta_file, order='ypr',
max_angle=args.max_angle)
else:
log("Error: no pose file found in image directory:", args.project)
quit()
# save the initial meta .json file for each posed image
proj.save_images_info()
# now, load the image meta data and init the proj.image_list
proj.load_images_info()
# compute the project's NED reference location (based on average of
# aircraft poses)
proj.compute_ned_reference_lla()
ref_node = getNode('/config/ned_reference', True)
ref = [ ref_node.getFloat('lat_deg'),
ref_node.getFloat('lon_deg'),
ref_node.getFloat('alt_m') ]
log("NED reference location:", ref)
# set the camera poses (fixed offset from aircraft pose) Camera pose
# location is specfied in ned, so do this after computing the ned
# reference point for this project.
pose.compute_camera_poses(proj)
# local surface approximation
srtm.initialize( ref, 6000, 6000, 30)
smart.load(proj.analysis_dir)
smart.update_srtm_elevations(proj)
smart.save(proj.analysis_dir)
# save the poses
proj.save_images_info()
# save initial proejct config (mainly the ned reference)
proj.save()
state.update("STEP2")
############################################################################
log("Step 3: feature matching", fancy=True)
############################################################################
if not state.check("STEP3a"):
proj.load_images_info()
proj.load_match_pairs()
smart.load(proj.analysis_dir)
smart.set_yaw_error_estimates(proj)
# setup project detector parameters
detector_node = getNode('/config/detector', True)
detector_node.setString('detector', args.detector)
detector_node.setString('scale', args.scale)
if args.detector == 'SIFT':
pass
elif args.detector == 'SURF':
detector_node.setInt('surf_hessian_threshold', args.surf_hessian_threshold)
detector_node.setInt('surf_noctaves', args.surf_noctaves)
elif args.detector == 'ORB':
detector_node.setInt('grid_detect', args.grid_detect)
detector_node.setInt('orb_max_features', args.orb_max_features)
elif args.detector == 'Star':
detector_node.setInt('star_max_size', args.star_max_size)
detector_node.setInt('star_response_threshold',
args.star_response_threshold)
detector_node.setInt('star_line_threshold_projected',
args.star_response_threshold)
detector_node.setInt('star_line_threshold_binarized',
args.star_line_threshold_binarized)
detector_node.setInt('star_suppress_nonmax_size',
args.star_suppress_nonmax_size)
log("detector:", args.detector)
log("image scale for fearture detection/matching:", args.scale)
matcher_node = getNode('/config/matcher', True)
matcher_node.setFloat('match_ratio', args.match_ratio)
matcher_node.setString('filter', args.filter)
matcher_node.setInt('min_pairs', args.min_pairs)
if args.min_dist:
matcher_node.setFloat('min_dist', args.min_dist)
if args.max_dist:
matcher_node.setFloat('max_dist', args.max_dist)
matcher_node.setInt('min_chain_len', args.min_chain_length)
if args.ground:
matcher_node.setFloat('ground_m', args.ground)
# save any config changes
proj.save()
# camera calibration
K = camera.get_K()
# print("K:", K)
log("Matching features")
# fire up the matcher
matcher.configure()
matcher.find_matches(proj, K, strategy=args.match_strategy,
transform=args.filter, sort=True, review=False)
feature_count = 0
image_count = 0
for image in proj.image_list:
feature_count += image.num_features
image_count += 1
log("Average # of features per image found = %.0f" % (feature_count / image_count))
state.update("STEP3a")
matches_name = os.path.join(proj.analysis_dir, "matches_grouped")
if not state.check("STEP3b"):
proj.load_images_info()
proj.load_features(descriptors=False)
proj.load_match_pairs()
match_cleanup.merge_duplicates(proj)
match_cleanup.check_for_pair_dups(proj)
match_cleanup.check_for_1vn_dups(proj)
matches_direct = match_cleanup.make_match_structure(proj)
matches_grouped = match_cleanup.link_matches(proj, matches_direct)
log("Writing full group chain file:", matches_name)
pickle.dump(matches_grouped, open(matches_name, "wb"))
state.update("STEP3b")
if not state.check("STEP3c"):
proj.load_images_info()
K = camera.get_K(optimized=False)
IK = np.linalg.inv(K)
log("Loading source matches:", matches_name)
matches_grouped = pickle.load( open(matches_name, 'rb') )
match_cleanup.triangulate_smart(proj, matches_grouped)
log("Writing triangulated group file:", matches_name)
pickle.dump(matches_grouped, open(matches_name, "wb"))
state.update("STEP3c")
if not state.check("STEP3d"):
proj.load_images_info()
log("Loading source matches:", matches_name)
matches = pickle.load( open( matches_name, 'rb' ) )
log("matched features:", len(matches))
# compute the group connections within the image set.
group_list = groups.compute(proj.image_list, matches)
groups.save(proj.analysis_dir, group_list)
log("Total images:", len(proj.image_list))
line = "Group sizes:"
for g in group_list:
line += " " + str(len(g))
log(line)
log("Counting allocated features...")
count = 0
for i, match in enumerate(matches):
if match[1] >= 0:
count += 1
print("Features: %d/%d" % (count, len(matches)))
log("Writing grouped tagged matches:", matches_name)
pickle.dump(matches, open(matches_name, "wb"))
state.update("STEP3d")
############################################################################
log("Step 4: Optimization (fit)", fancy=True)
############################################################################
if not state.check("STEP4"):
proj.load_images_info()
log("Loading source matches:", matches_name)
matches = pickle.load( open( matches_name, 'rb' ) )
log("matched features:", len(matches))
# load the group connections within the image set
group_list = groups.load(proj.analysis_dir)
opt = optimizer.Optimizer(args.project)
# setup the data structures
opt.setup( proj, group_list, args.group, matches, optimized=args.refine,
cam_calib=args.cam_calibration)
# run the optimization (fit)
cameras, features, cam_index_map, feat_index_map, \
fx_opt, fy_opt, cu_opt, cv_opt, distCoeffs_opt \
= opt.run()
# update camera poses
opt.update_camera_poses(proj)
# update and save the optimized camera calibration
camera.set_K(fx_opt, fy_opt, cu_opt, cv_opt, optimized=True)
camera.set_dist_coeffs(distCoeffs_opt.tolist(), optimized=True)
proj.save()
# reposition the optimized data set to best fit the original gps
# locations of the camera poses.
opt.refit(proj, matches, group_list, args.group)
# write out the updated match_dict
log("Writing optimized (fitted) matches:", matches_name)
pickle.dump(matches, open(matches_name, 'wb'))
state.update("STEP4")
############################################################################
log("Step 5: Create the map", fancy=True)
############################################################################
if not state.check("STEP6"):
# load the group connections within the image set
group_list = groups.load(proj.analysis_dir)
render_panda3d.build_map(proj, group_list, args.group)
#state.update("STEP6")
| [
"lib.smart.update_srtm_elevations",
"lib.pose.set_aircraft_poses",
"lib.optimizer.Optimizer",
"lib.match_cleanup.triangulate_smart",
"props_json.load",
"lib.match_cleanup.merge_duplicates",
"os.path.exists",
"lib.state.check",
"argparse.ArgumentParser",
"lib.pose.make_pix4d",
"lib.matcher.find_m... | [((1275, 1338), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Create an empty project."""'}), "(description='Create an empty project.')\n", (1298, 1338), False, 'import argparse\n'), ((4865, 4911), 'lib.logger.log', 'log', (['"""Project processed with arguments:"""', 'args'], {}), "('Project processed with arguments:', args)\n", (4868, 4911), False, 'from lib.logger import log\n'), ((4990, 5034), 'lib.logger.log', 'log', (['"""Step 1: setup the project"""'], {'fancy': '(True)'}), "('Step 1: setup the project', fancy=True)\n", (4993, 5034), False, 'from lib.logger import log\n'), ((5343, 5388), 'lib.project.ProjectMgr', 'project.ProjectMgr', (['args.project'], {'create': '(True)'}), '(args.project, create=True)\n', (5361, 5388), False, 'from lib import project\n'), ((5402, 5439), 'lib.logger.log', 'log', (['"""Created project:"""', 'args.project'], {}), "('Created project:', args.project)\n", (5405, 5439), False, 'from lib.logger import log\n'), ((5803, 5835), 'lib.logger.log', 'log', (['"""Camera file:"""', 'camera_file'], {}), "('Camera file:', camera_file)\n", (5806, 5835), False, 'from lib.logger import log\n'), ((5940, 5971), 'props.getNode', 'getNode', (['"""/config/camera"""', '(True)'], {}), "('/config/camera', True)\n", (5947, 5971), False, 'from props import getNode, PropertyNode\n'), ((5983, 5997), 'props.PropertyNode', 'PropertyNode', ([], {}), '()\n', (5995, 5997), False, 'from props import getNode, PropertyNode\n'), ((6001, 6039), 'props_json.load', 'props_json.load', (['camera_file', 'tmp_node'], {}), '(camera_file, tmp_node)\n', (6016, 6039), False, 'import props_json\n'), ((6917, 6938), 'lib.state.update', 'state.update', (['"""STEP1"""'], {}), "('STEP1')\n", (6929, 6938), False, 'from lib import state\n'), ((7018, 7097), 'lib.logger.log', 'log', (['"""Step 2: configure camera poses and per-image meta data files"""'], {'fancy': '(True)'}), "('Step 2: configure camera poses and per-image meta data files', fancy=True)\n", (7021, 7097), False, 'from lib.logger import log\n'), ((7176, 7201), 'lib.logger.log', 'log', (['"""Configuring images"""'], {}), "('Configuring images')\n", (7179, 7201), False, 'from lib.logger import log\n'), ((7357, 7396), 'os.path.join', 'os.path.join', (['args.project', '"""pix4d.csv"""'], {}), "(args.project, 'pix4d.csv')\n", (7369, 7396), False, 'import os\n'), ((7409, 7457), 'os.path.join', 'os.path.join', (['args.project', '"""image-metadata.txt"""'], {}), "(args.project, 'image-metadata.txt')\n", (7421, 7457), False, 'import os\n'), ((7461, 7487), 'os.path.exists', 'os.path.exists', (['pix4d_file'], {}), '(pix4d_file)\n', (7475, 7487), False, 'import os\n'), ((7683, 7722), 'os.path.join', 'os.path.join', (['args.project', '"""pix4d.csv"""'], {}), "(args.project, 'pix4d.csv')\n", (7695, 7722), False, 'import os\n'), ((7735, 7783), 'os.path.join', 'os.path.join', (['args.project', '"""image-metadata.txt"""'], {}), "(args.project, 'image-metadata.txt')\n", (7747, 7783), False, 'import os\n'), ((7787, 7813), 'os.path.exists', 'os.path.exists', (['pix4d_file'], {}), '(pix4d_file)\n', (7801, 7813), False, 'import os\n'), ((8457, 8495), 'props.getNode', 'getNode', (['"""/config/ned_reference"""', '(True)'], {}), "('/config/ned_reference', True)\n", (8464, 8495), False, 'from props import getNode, PropertyNode\n'), ((8609, 8644), 'lib.logger.log', 'log', (['"""NED reference location:"""', 'ref'], {}), "('NED reference location:', ref)\n", (8612, 8644), False, 'from lib.logger import log\n'), ((8817, 8848), 'lib.pose.compute_camera_poses', 'pose.compute_camera_poses', (['proj'], {}), '(proj)\n', (8842, 8848), False, 'from lib import pose\n'), ((8880, 8916), 'lib.srtm.initialize', 'srtm.initialize', (['ref', '(6000)', '(6000)', '(30)'], {}), '(ref, 6000, 6000, 30)\n', (8895, 8916), False, 'from lib import srtm\n'), ((8918, 8947), 'lib.smart.load', 'smart.load', (['proj.analysis_dir'], {}), '(proj.analysis_dir)\n', (8928, 8947), False, 'from lib import smart\n'), ((8948, 8982), 'lib.smart.update_srtm_elevations', 'smart.update_srtm_elevations', (['proj'], {}), '(proj)\n', (8976, 8982), False, 'from lib import smart\n'), ((8983, 9012), 'lib.smart.save', 'smart.save', (['proj.analysis_dir'], {}), '(proj.analysis_dir)\n', (8993, 9012), False, 'from lib import smart\n'), ((9126, 9147), 'lib.state.update', 'state.update', (['"""STEP2"""'], {}), "('STEP2')\n", (9138, 9147), False, 'from lib import state\n'), ((9227, 9270), 'lib.logger.log', 'log', (['"""Step 3: feature matching"""'], {'fancy': '(True)'}), "('Step 3: feature matching', fancy=True)\n", (9230, 9270), False, 'from lib.logger import log\n'), ((11928, 11978), 'os.path.join', 'os.path.join', (['proj.analysis_dir', '"""matches_grouped"""'], {}), "(proj.analysis_dir, 'matches_grouped')\n", (11940, 11978), False, 'import os\n'), ((13901, 13946), 'lib.logger.log', 'log', (['"""Step 4: Optimization (fit)"""'], {'fancy': '(True)'}), "('Step 4: Optimization (fit)', fancy=True)\n", (13904, 13946), False, 'from lib.logger import log\n'), ((15387, 15428), 'lib.logger.log', 'log', (['"""Step 5: Create the map"""'], {'fancy': '(True)'}), "('Step 5: Create the map', fancy=True)\n", (15390, 15428), False, 'from lib.logger import log\n'), ((4843, 4863), 'socket.gethostname', 'socket.gethostname', ([], {}), '()\n', (4861, 4863), False, 'import socket\n'), ((5198, 5225), 'os.path.isdir', 'os.path.isdir', (['args.project'], {}), '(args.project)\n', (5211, 5225), False, 'import os\n'), ((5679, 5731), 'os.path.join', 'os.path.join', (['""".."""', '"""cameras"""', "(camera_name + '.json')"], {}), "('..', 'cameras', camera_name + '.json')\n", (5691, 5731), False, 'import os\n'), ((5736, 5802), 'lib.logger.log', 'log', (['"""Camera auto-detected:"""', 'camera_name', 'make', 'model', 'lens_model'], {}), "('Camera auto-detected:', camera_name, make, model, lens_model)\n", (5739, 5802), False, 'from lib.logger import log\n'), ((6045, 6083), 'props_json.overlay', 'props_json.overlay', (['cam_node', 'tmp_node'], {}), '(cam_node, tmp_node)\n', (6063, 6083), False, 'import props_json\n'), ((6856, 6904), 'lib.logger.log', 'log', (['"""Aborting due to camera detection failure."""'], {}), "('Aborting due to camera detection failure.')\n", (6859, 6904), False, 'from lib.logger import log\n'), ((7493, 7530), 'lib.logger.log', 'log', (['"""Found a pose file:"""', 'pix4d_file'], {}), "('Found a pose file:', pix4d_file)\n", (7496, 7530), False, 'from lib.logger import log\n'), ((7536, 7561), 'os.path.exists', 'os.path.exists', (['meta_file'], {}), '(meta_file)\n', (7550, 7561), False, 'import os\n'), ((7819, 7904), 'lib.pose.set_aircraft_poses', 'pose.set_aircraft_poses', (['proj', 'pix4d_file'], {'order': '"""rpy"""', 'max_angle': 'args.max_angle'}), "(proj, pix4d_file, order='rpy', max_angle=args.max_angle\n )\n", (7842, 7904), False, 'from lib import pose\n'), ((7933, 7958), 'os.path.exists', 'os.path.exists', (['meta_file'], {}), '(meta_file)\n', (7947, 7958), False, 'import os\n'), ((9356, 9377), 'lib.state.check', 'state.check', (['"""STEP3a"""'], {}), "('STEP3a')\n", (9367, 9377), False, 'from lib import state\n'), ((9439, 9468), 'lib.smart.load', 'smart.load', (['proj.analysis_dir'], {}), '(proj.analysis_dir)\n', (9449, 9468), False, 'from lib import smart\n'), ((9473, 9508), 'lib.smart.set_yaw_error_estimates', 'smart.set_yaw_error_estimates', (['proj'], {}), '(proj)\n', (9502, 9508), False, 'from lib import smart\n'), ((9574, 9607), 'props.getNode', 'getNode', (['"""/config/detector"""', '(True)'], {}), "('/config/detector', True)\n", (9581, 9607), False, 'from props import getNode, PropertyNode\n'), ((10695, 10726), 'lib.logger.log', 'log', (['"""detector:"""', 'args.detector'], {}), "('detector:', args.detector)\n", (10698, 10726), False, 'from lib.logger import log\n'), ((10731, 10794), 'lib.logger.log', 'log', (['"""image scale for fearture detection/matching:"""', 'args.scale'], {}), "('image scale for fearture detection/matching:', args.scale)\n", (10734, 10794), False, 'from lib.logger import log\n'), ((10815, 10847), 'props.getNode', 'getNode', (['"""/config/matcher"""', '(True)'], {}), "('/config/matcher', True)\n", (10822, 10847), False, 'from props import getNode, PropertyNode\n'), ((11392, 11406), 'lib.camera.get_K', 'camera.get_K', ([], {}), '()\n', (11404, 11406), False, 'from lib import camera\n'), ((11433, 11457), 'lib.logger.log', 'log', (['"""Matching features"""'], {}), "('Matching features')\n", (11436, 11457), False, 'from lib.logger import log\n'), ((11493, 11512), 'lib.matcher.configure', 'matcher.configure', ([], {}), '()\n', (11510, 11512), False, 'from lib import matcher\n'), ((11517, 11629), 'lib.matcher.find_matches', 'matcher.find_matches', (['proj', 'K'], {'strategy': 'args.match_strategy', 'transform': 'args.filter', 'sort': '(True)', 'review': '(False)'}), '(proj, K, strategy=args.match_strategy, transform=args.\n filter, sort=True, review=False)\n', (11537, 11629), False, 'from lib import matcher\n'), ((11800, 11887), 'lib.logger.log', 'log', (["('Average # of features per image found = %.0f' % (feature_count / image_count)\n )"], {}), "('Average # of features per image found = %.0f' % (feature_count /\n image_count))\n", (11803, 11887), False, 'from lib.logger import log\n'), ((11889, 11911), 'lib.state.update', 'state.update', (['"""STEP3a"""'], {}), "('STEP3a')\n", (11901, 11911), False, 'from lib import state\n'), ((11987, 12008), 'lib.state.check', 'state.check', (['"""STEP3b"""'], {}), "('STEP3b')\n", (11998, 12008), False, 'from lib import state\n'), ((12117, 12153), 'lib.match_cleanup.merge_duplicates', 'match_cleanup.merge_duplicates', (['proj'], {}), '(proj)\n', (12147, 12153), False, 'from lib import match_cleanup\n'), ((12158, 12197), 'lib.match_cleanup.check_for_pair_dups', 'match_cleanup.check_for_pair_dups', (['proj'], {}), '(proj)\n', (12191, 12197), False, 'from lib import match_cleanup\n'), ((12202, 12240), 'lib.match_cleanup.check_for_1vn_dups', 'match_cleanup.check_for_1vn_dups', (['proj'], {}), '(proj)\n', (12234, 12240), False, 'from lib import match_cleanup\n'), ((12262, 12302), 'lib.match_cleanup.make_match_structure', 'match_cleanup.make_match_structure', (['proj'], {}), '(proj)\n', (12296, 12302), False, 'from lib import match_cleanup\n'), ((12325, 12373), 'lib.match_cleanup.link_matches', 'match_cleanup.link_matches', (['proj', 'matches_direct'], {}), '(proj, matches_direct)\n', (12351, 12373), False, 'from lib import match_cleanup\n'), ((12379, 12430), 'lib.logger.log', 'log', (['"""Writing full group chain file:"""', 'matches_name'], {}), "('Writing full group chain file:', matches_name)\n", (12382, 12430), False, 'from lib.logger import log\n'), ((12495, 12517), 'lib.state.update', 'state.update', (['"""STEP3b"""'], {}), "('STEP3b')\n", (12507, 12517), False, 'from lib import state\n'), ((12526, 12547), 'lib.state.check', 'state.check', (['"""STEP3c"""'], {}), "('STEP3c')\n", (12537, 12547), False, 'from lib import state\n'), ((12590, 12619), 'lib.camera.get_K', 'camera.get_K', ([], {'optimized': '(False)'}), '(optimized=False)\n', (12602, 12619), False, 'from lib import camera\n'), ((12629, 12645), 'numpy.linalg.inv', 'np.linalg.inv', (['K'], {}), '(K)\n', (12642, 12645), True, 'import numpy as np\n'), ((12651, 12695), 'lib.logger.log', 'log', (['"""Loading source matches:"""', 'matches_name'], {}), "('Loading source matches:', matches_name)\n", (12654, 12695), False, 'from lib.logger import log\n'), ((12762, 12816), 'lib.match_cleanup.triangulate_smart', 'match_cleanup.triangulate_smart', (['proj', 'matches_grouped'], {}), '(proj, matches_grouped)\n', (12793, 12816), False, 'from lib import match_cleanup\n'), ((12821, 12874), 'lib.logger.log', 'log', (['"""Writing triangulated group file:"""', 'matches_name'], {}), "('Writing triangulated group file:', matches_name)\n", (12824, 12874), False, 'from lib.logger import log\n'), ((12939, 12961), 'lib.state.update', 'state.update', (['"""STEP3c"""'], {}), "('STEP3c')\n", (12951, 12961), False, 'from lib import state\n'), ((12970, 12991), 'lib.state.check', 'state.check', (['"""STEP3d"""'], {}), "('STEP3d')\n", (12981, 12991), False, 'from lib import state\n'), ((13026, 13070), 'lib.logger.log', 'log', (['"""Loading source matches:"""', 'matches_name'], {}), "('Loading source matches:', matches_name)\n", (13029, 13070), False, 'from lib.logger import log\n'), ((13246, 13286), 'lib.groups.compute', 'groups.compute', (['proj.image_list', 'matches'], {}), '(proj.image_list, matches)\n', (13260, 13286), False, 'from lib import groups\n'), ((13291, 13333), 'lib.groups.save', 'groups.save', (['proj.analysis_dir', 'group_list'], {}), '(proj.analysis_dir, group_list)\n', (13302, 13333), False, 'from lib import groups\n'), ((13471, 13480), 'lib.logger.log', 'log', (['line'], {}), '(line)\n', (13474, 13480), False, 'from lib.logger import log\n'), ((13486, 13523), 'lib.logger.log', 'log', (['"""Counting allocated features..."""'], {}), "('Counting allocated features...')\n", (13489, 13523), False, 'from lib.logger import log\n'), ((13690, 13742), 'lib.logger.log', 'log', (['"""Writing grouped tagged matches:"""', 'matches_name'], {}), "('Writing grouped tagged matches:', matches_name)\n", (13693, 13742), False, 'from lib.logger import log\n'), ((13799, 13821), 'lib.state.update', 'state.update', (['"""STEP3d"""'], {}), "('STEP3d')\n", (13811, 13821), False, 'from lib import state\n'), ((14032, 14052), 'lib.state.check', 'state.check', (['"""STEP4"""'], {}), "('STEP4')\n", (14043, 14052), False, 'from lib import state\n'), ((14087, 14131), 'lib.logger.log', 'log', (['"""Loading source matches:"""', 'matches_name'], {}), "('Loading source matches:', matches_name)\n", (14090, 14131), False, 'from lib.logger import log\n'), ((14303, 14333), 'lib.groups.load', 'groups.load', (['proj.analysis_dir'], {}), '(proj.analysis_dir)\n', (14314, 14333), False, 'from lib import groups\n'), ((14345, 14378), 'lib.optimizer.Optimizer', 'optimizer.Optimizer', (['args.project'], {}), '(args.project)\n', (14364, 14378), False, 'from lib import optimizer\n'), ((14824, 14884), 'lib.camera.set_K', 'camera.set_K', (['fx_opt', 'fy_opt', 'cu_opt', 'cv_opt'], {'optimized': '(True)'}), '(fx_opt, fy_opt, cu_opt, cv_opt, optimized=True)\n', (14836, 14884), False, 'from lib import camera\n'), ((15173, 15229), 'lib.logger.log', 'log', (['"""Writing optimized (fitted) matches:"""', 'matches_name'], {}), "('Writing optimized (fitted) matches:', matches_name)\n", (15176, 15229), False, 'from lib.logger import log\n'), ((15286, 15307), 'lib.state.update', 'state.update', (['"""STEP4"""'], {}), "('STEP4')\n", (15298, 15307), False, 'from lib import state\n'), ((15514, 15534), 'lib.state.check', 'state.check', (['"""STEP6"""'], {}), "('STEP6')\n", (15525, 15534), False, 'from lib import state\n'), ((15607, 15637), 'lib.groups.load', 'groups.load', (['proj.analysis_dir'], {}), '(proj.analysis_dir)\n', (15618, 15637), False, 'from lib import groups\n'), ((15643, 15697), 'lib.render_panda3d.build_map', 'render_panda3d.build_map', (['proj', 'group_list', 'args.group'], {}), '(proj, group_list, args.group)\n', (15667, 15697), False, 'from lib import render_panda3d\n'), ((6162, 6200), 'lib.camera.set_mount_params', 'camera.set_mount_params', (['(0.0)', '(0.0)', '(0.0)'], {}), '(0.0, 0.0, 0.0)\n', (6185, 6200), False, 'from lib import camera\n'), ((6637, 6783), 'lib.logger.log', 'log', (['"""Camera autodetection failed. Consider running the new camera script to create a camera config and then try running this script again."""'], {}), "('Camera autodetection failed. Consider running the new camera script to create a camera config and then try running this script again.'\n )\n", (6640, 6783), False, 'from lib.logger import log\n'), ((6797, 6851), 'lib.logger.log', 'log', (['"""Specified camera config not found:"""', 'args.camera'], {}), "('Specified camera config not found:', args.camera)\n", (6800, 6851), False, 'from lib.logger import log\n'), ((7567, 7603), 'lib.logger.log', 'log', (['"""Found a pose file:"""', 'meta_file'], {}), "('Found a pose file:', meta_file)\n", (7570, 7603), False, 'from lib.logger import log\n'), ((7614, 7664), 'lib.pose.make_pix4d', 'pose.make_pix4d', (['args.project', 'args.force_altitude'], {}), '(args.project, args.force_altitude)\n', (7629, 7664), False, 'from lib import pose\n'), ((7964, 8043), 'lib.pose.set_aircraft_poses', 'pose.set_aircraft_poses', (['proj', 'meta_file'], {'order': '"""ypr"""', 'max_angle': 'args.max_angle'}), "(proj, meta_file, order='ypr', max_angle=args.max_angle)\n", (7987, 8043), False, 'from lib import pose\n'), ((8082, 8148), 'lib.logger.log', 'log', (['"""Error: no pose file found in image directory:"""', 'args.project'], {}), "('Error: no pose file found in image directory:', args.project)\n", (8085, 8148), False, 'from lib.logger import log\n'), ((6282, 6320), 'lib.camera.set_mount_params', 'camera.set_mount_params', (['(0.0)', '(0.0)', '(0.0)'], {}), '(0.0, 0.0, 0.0)\n', (6305, 6320), False, 'from lib import camera\n'), ((6399, 6467), 'lib.camera.set_mount_params', 'camera.set_mount_params', (['args.yaw_deg', 'args.pitch_deg', 'args.roll_deg'], {}), '(args.yaw_deg, args.pitch_deg, args.roll_deg)\n', (6422, 6467), False, 'from lib import camera\n')] |
#!/usr/bin/env python3
import click
import requests
import re
import os
from bs4 import BeautifulSoup
headers = {
'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.82 Safari/537.36"
}
sources = {
'boj': {
'url': 'https://acmicpc.net/problem/%s',
'input': lambda soup: soup.find_all(attrs={'id':re.compile('sample-input-\d*')}),
'ans': lambda soup: soup.find_all(attrs={'id':re.compile('sample-output-\d*')}),
},
'cf-contest': {
'url': 'https://codeforces.com/contest/%s/problem/%s',
'input': lambda soup: \
list(map(lambda div: div.find('pre'), soup.find_all(attrs={'class': 'input'}))),
'ans': lambda soup: \
list(map(lambda div: div.find('pre'), soup.find_all(attrs={'class': 'output'}))),
}
}
def guess_src(src):
for key, val in sources.items():
if key.startswith(src):
return key, val
raise click.ClickException('Invalid source ' + src)
@click.command()
@click.argument('source', nargs=1)
@click.argument('problem', nargs=-1)
@click.option('--testcase-directory', '-tc', default='testcase', type=click.Path(),
help='testcase directory')
@click.option('--no-subdirectory', '-N', is_flag = True,
help='directly find TCs in "testcase-directory/"' +
'\ndefault is "testcase-directory/{filename}"')
def get(source, problem, testcase_directory, no_subdirectory):
"""Fetch testcase"""
key, src = guess_src(source)
webpage = requests.get(src['url']%problem, headers=headers)
soup = BeautifulSoup(webpage.content, 'html.parser')
INS = src['input'](soup)
ANS = src['ans'](soup)
if len(INS) == 0:
raise click.ClickException('Cannot find testcases from ' + src['url']%problem)
if not no_subdirectory:
testcase_directory = os.path.join(testcase_directory, ''.join(problem))
testcase_directory.rstrip('/')
testcase_directory += '/'
if not os.path.exists(testcase_directory):
os.makedirs(testcase_directory)
for i, IN, AN in zip(map(str,range(1,len(INS)+1)), INS, ANS):
with open(testcase_directory + str(i) + '.in', 'w') as f:
f.write(IN.text.strip().replace('\r',''))
with open(testcase_directory + str(i) + '.ans', 'w') as f:
f.write(AN.text.strip().replace('\r',''))
click.echo(f'Successfully crawled {len(INS)} testcases ', nl=False)
click.secho(f'from {key}', fg='bright_black')
if __name__ == '__main__':
get() | [
"os.path.exists",
"click.argument",
"os.makedirs",
"click.secho",
"click.option",
"re.compile",
"requests.get",
"bs4.BeautifulSoup",
"click.ClickException",
"click.Path",
"click.command"
] | [((1029, 1044), 'click.command', 'click.command', ([], {}), '()\n', (1042, 1044), False, 'import click\n'), ((1046, 1079), 'click.argument', 'click.argument', (['"""source"""'], {'nargs': '(1)'}), "('source', nargs=1)\n", (1060, 1079), False, 'import click\n'), ((1081, 1116), 'click.argument', 'click.argument', (['"""problem"""'], {'nargs': '(-1)'}), "('problem', nargs=-1)\n", (1095, 1116), False, 'import click\n'), ((1243, 1409), 'click.option', 'click.option', (['"""--no-subdirectory"""', '"""-N"""'], {'is_flag': '(True)', 'help': '(\'directly find TCs in "testcase-directory/"\' +\n """\ndefault is "testcase-directory/{filename}\\"""")'}), '(\'--no-subdirectory\', \'-N\', is_flag=True, help=\n \'directly find TCs in "testcase-directory/"\' +\n """\ndefault is "testcase-directory/{filename}\\"""")\n', (1255, 1409), False, 'import click\n'), ((981, 1026), 'click.ClickException', 'click.ClickException', (["('Invalid source ' + src)"], {}), "('Invalid source ' + src)\n", (1001, 1026), False, 'import click\n'), ((1562, 1613), 'requests.get', 'requests.get', (["(src['url'] % problem)"], {'headers': 'headers'}), "(src['url'] % problem, headers=headers)\n", (1574, 1613), False, 'import requests\n'), ((1623, 1668), 'bs4.BeautifulSoup', 'BeautifulSoup', (['webpage.content', '"""html.parser"""'], {}), "(webpage.content, 'html.parser')\n", (1636, 1668), False, 'from bs4 import BeautifulSoup\n'), ((2480, 2525), 'click.secho', 'click.secho', (['f"""from {key}"""'], {'fg': '"""bright_black"""'}), "(f'from {key}', fg='bright_black')\n", (2491, 2525), False, 'import click\n'), ((1762, 1836), 'click.ClickException', 'click.ClickException', (["('Cannot find testcases from ' + src['url'] % problem)"], {}), "('Cannot find testcases from ' + src['url'] % problem)\n", (1782, 1836), False, 'import click\n'), ((2020, 2054), 'os.path.exists', 'os.path.exists', (['testcase_directory'], {}), '(testcase_directory)\n', (2034, 2054), False, 'import os\n'), ((2064, 2095), 'os.makedirs', 'os.makedirs', (['testcase_directory'], {}), '(testcase_directory)\n', (2075, 2095), False, 'import os\n'), ((1187, 1199), 'click.Path', 'click.Path', ([], {}), '()\n', (1197, 1199), False, 'import click\n'), ((383, 414), 're.compile', 're.compile', (['"""sample-input-\\\\d*"""'], {}), "('sample-input-\\\\d*')\n", (393, 414), False, 'import re\n'), ((471, 503), 're.compile', 're.compile', (['"""sample-output-\\\\d*"""'], {}), "('sample-output-\\\\d*')\n", (481, 503), False, 'import re\n')] |
# Copyright 2017 National Research Foundation (Square Kilometre Array)
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import logging
import asyncio
import re
import ipaddress
import socket
import time
import inspect
import functools
import types
from typing import Any, Optional, Iterable, Callable, cast
import decorator
from . import core
logger = logging.getLogger(__name__)
DEFAULT_LIMIT = 16 * 1024**2
_BLANK_RE = re.compile(br'^[ \t]*[\r\n]?$')
class ConvertCRProtocol(asyncio.StreamReaderProtocol):
"""Protocol that converts incoming carriage returns to newlines.
This simplifies extracting the data with :class:`asyncio.StreamReader`,
whose :meth:`~asyncio.StreamReader.readuntil` method is limited to a single
separator.
"""
def data_received(self, data: bytes) -> None:
super().data_received(data.replace(b'\r', b'\n'))
async def _discard_to_eol(stream: asyncio.StreamReader) -> None:
"""Discard all data up to and including the next newline, or end of file."""
while True:
try:
await stream.readuntil()
except asyncio.IncompleteReadError:
break # EOF reached
except asyncio.LimitOverrunError as error:
# Extract the data that's already in the buffer
consumed = error.consumed
await stream.readexactly(consumed)
else:
break
async def read_message(stream: asyncio.StreamReader) -> Optional[core.Message]:
"""Read a single message from an asynchronous stream.
If EOF is reached before reading the newline, returns ``None`` if
there was no data, otherwise raises
:exc:`aiokatcp.core.KatcpSyntaxError`.
Parameters
----------
stream
Input stream
Raises
------
aiokatcp.core.KatcpSyntaxError
if the line was too long or malformed.
"""
while True:
try:
raw = await stream.readuntil()
except asyncio.IncompleteReadError as error:
raw = error.partial
if not raw:
return None # End of stream reached
except asyncio.LimitOverrunError:
await _discard_to_eol(stream)
raise core.KatcpSyntaxError('Message exceeded stream buffer size')
if not _BLANK_RE.match(raw):
return core.Message.parse(raw)
class FailReply(Exception):
"""Indicate to the remote end that a request failed, without backtrace"""
class InvalidReply(Exception):
"""Indicate to the remote end that a request was unrecognised"""
class ConnectionLoggerAdapter(logging.LoggerAdapter):
def process(self, msg, kwargs):
return '{} [{}]'.format(msg, self.extra['address']), kwargs
class Connection:
def __init__(self, owner: Any,
reader: asyncio.StreamReader, writer: asyncio.StreamWriter,
is_server: bool) -> None:
# Set TCP_NODELAY to avoid unnecessary transmission delays. This is
# on by default in asyncio from Python 3.6, but not in 3.5.
writer.get_extra_info('socket').setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
self.owner = owner
self.reader = reader
self.writer = writer # type: Optional[asyncio.StreamWriter]
host, port, *_ = writer.get_extra_info('peername')
self.address = core.Address(ipaddress.ip_address(host), port)
self._drain_lock = asyncio.Lock()
self.is_server = is_server
self.logger = ConnectionLoggerAdapter(logger, dict(address=self.address))
self._task = self.owner.loop.create_task(self._run())
self._task.add_done_callback(self._done_callback)
self._closing = False
self._closed_event = asyncio.Event()
def _close_writer(self):
if self.writer is not None:
self.writer.close()
self.writer = None
def write_messages(self, msgs: Iterable[core.Message]) -> None:
"""Write a stream of messages to the connection.
Connection errors are logged and swallowed.
"""
if self.writer is None:
return # We previously detected that it was closed
try:
# Normally this would be checked by the internals of
# self.writer.drain and bubble out to self.drain, but there is no
# guarantee that self.drain will be called in the near future
# (see Github issue #11).
if self.writer.transport.is_closing():
raise ConnectionResetError('Connection lost')
raw = b''.join(bytes(msg) for msg in msgs)
self.writer.write(raw)
self.logger.debug('Sent message %r', raw)
except ConnectionError as error:
self.logger.warning('Connection closed before message could be sent: %s', error)
self._close_writer()
def write_message(self, msg: core.Message) -> None:
"""Write a message to the connection.
Connection errors are logged and swallowed.
"""
self.write_messages([msg])
async def drain(self) -> None:
"""Block until the outgoing write buffer is small enough."""
# The Python 3.5 implementation of StreamWriter.drain is not reentrant,
# so we use a lock.
async with self._drain_lock:
if self.writer is not None:
try:
await self.writer.drain()
except ConnectionError as error:
# The writer could have been closed during the await
if self.writer is not None:
self.logger.warning('Connection closed while draining: %s', error)
self._close_writer()
async def _run(self) -> None:
while True:
# If the output buffer gets too full, pause processing requests
await self.drain()
try:
msg = await read_message(self.reader)
except core.KatcpSyntaxError as error:
self.logger.warning('Malformed message received', exc_info=True)
if self.is_server:
# TODO: #log informs are supposed to go to all clients
self.write_message(
core.Message.inform('log', 'error', time.time(), __name__, str(error)))
except ConnectionResetError:
# Client closed connection without consuming everything we sent it.
break
else:
if msg is None: # EOF received
break
self.logger.debug('Received message %r', bytes(msg))
await self.owner.handle_message(self, msg)
def _done_callback(self, task: asyncio.Future) -> None:
self._closed_event.set()
if not task.cancelled():
try:
task.result()
except Exception:
self.logger.exception('Exception in connection handler')
def close(self) -> None:
"""Start closing the connection.
Any currently running message handler will be cancelled. The closing
process completes asynchronously. Use :meth:`wait_closed` to wait for
things to be completely closed off.
"""
if not self._closing:
self._task.cancel()
self._close_writer()
self._closing = True
async def wait_closed(self) -> None:
"""Wait until the connection is closed.
This can be used either after :meth:`close`, or without :meth:`close`
to wait for the remote end to close the connection.
"""
await self._closed_event.wait()
@decorator.decorator
def _identity_decorator(func, *args, **kwargs):
"""Identity decorator.
This isn't as useless as it sounds: given a function with a
``__signature__`` attribute, it generates a wrapper that really
does have that signature.
"""
return func(*args, **kwargs)
def wrap_handler(name: str, handler: Callable, fixed: int) -> Callable:
"""Convert a handler that takes a sequence of typed arguments into one
that takes a message.
The message is unpacked to the types given by the signature. If it could
not be unpacked, the wrapper raises :exc:`FailReply`.
Parameters
----------
name
Name of the message (only used to form error messages).
handler
The callable to wrap (may be a coroutine).
fixed
Number of leading parameters in `handler` that do not correspond to
message arguments.
"""
sig = inspect.signature(handler)
pos = []
var_pos = None
for parameter in sig.parameters.values():
if parameter.kind == inspect.Parameter.VAR_POSITIONAL:
var_pos = parameter
elif parameter.kind in (inspect.Parameter.POSITIONAL_ONLY,
inspect.Parameter.POSITIONAL_OR_KEYWORD):
pos.append(parameter)
if parameter.name == '_msg':
raise ValueError('Parameter cannot be named _msg')
if len(pos) < fixed:
raise TypeError('Handler must accept at least {} positional argument(s)'.format(fixed))
# Exclude transferring __annotations__ from the wrapped function,
# because the decorator does not preserve signature.
@functools.wraps(handler, assigned=['__module__', '__name__', '__qualname__', '__doc__'])
def wrapper(*args):
assert len(args) == fixed + 1
msg = args[-1]
args = list(args[:-1])
for argument in msg.arguments:
if len(args) >= len(pos):
if var_pos is None:
raise FailReply('too many arguments for {}'.format(name))
else:
hint = var_pos.annotation
else:
hint = pos[len(args)].annotation
if hint is inspect.Signature.empty:
hint = bytes
try:
args.append(core.decode(hint, argument))
except ValueError as error:
raise FailReply(str(error)) from error
try:
return handler(*args)
except TypeError as error:
raise FailReply(str(error)) from error # e.g. too few arguments
if inspect.iscoroutinefunction(handler):
wrapper = cast(Callable, types.coroutine(wrapper))
wrapper_parameters = pos[:fixed]
wrapper_parameters.append(
inspect.Parameter('_msg', inspect.Parameter.POSITIONAL_OR_KEYWORD,
annotation=core.Message))
wrapper.__signature__ = sig.replace(parameters=wrapper_parameters) # type: ignore
wrapper = _identity_decorator(wrapper)
wrapper._aiokatcp_orig_handler = handler # type: ignore
return wrapper
| [
"logging.getLogger",
"re.compile",
"inspect.signature",
"inspect.iscoroutinefunction",
"functools.wraps",
"asyncio.Lock",
"asyncio.Event",
"inspect.Parameter",
"time.time",
"types.coroutine",
"ipaddress.ip_address"
] | [((1782, 1809), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1799, 1809), False, 'import logging\n'), ((1851, 1884), 're.compile', 're.compile', (["b'^[ \\\\t]*[\\\\r\\\\n]?$'"], {}), "(b'^[ \\\\t]*[\\\\r\\\\n]?$')\n", (1861, 1884), False, 'import re\n'), ((9995, 10021), 'inspect.signature', 'inspect.signature', (['handler'], {}), '(handler)\n', (10012, 10021), False, 'import inspect\n'), ((10724, 10816), 'functools.wraps', 'functools.wraps', (['handler'], {'assigned': "['__module__', '__name__', '__qualname__', '__doc__']"}), "(handler, assigned=['__module__', '__name__', '__qualname__',\n '__doc__'])\n", (10739, 10816), False, 'import functools\n'), ((11668, 11704), 'inspect.iscoroutinefunction', 'inspect.iscoroutinefunction', (['handler'], {}), '(handler)\n', (11695, 11704), False, 'import inspect\n'), ((4832, 4846), 'asyncio.Lock', 'asyncio.Lock', ([], {}), '()\n', (4844, 4846), False, 'import asyncio\n'), ((5143, 5158), 'asyncio.Event', 'asyncio.Event', ([], {}), '()\n', (5156, 5158), False, 'import asyncio\n'), ((11842, 11937), 'inspect.Parameter', 'inspect.Parameter', (['"""_msg"""', 'inspect.Parameter.POSITIONAL_OR_KEYWORD'], {'annotation': 'core.Message'}), "('_msg', inspect.Parameter.POSITIONAL_OR_KEYWORD,\n annotation=core.Message)\n", (11859, 11937), False, 'import inspect\n'), ((4771, 4797), 'ipaddress.ip_address', 'ipaddress.ip_address', (['host'], {}), '(host)\n', (4791, 4797), False, 'import ipaddress\n'), ((11739, 11763), 'types.coroutine', 'types.coroutine', (['wrapper'], {}), '(wrapper)\n', (11754, 11763), False, 'import types\n'), ((7711, 7722), 'time.time', 'time.time', ([], {}), '()\n', (7720, 7722), False, 'import time\n')] |
#!/usr/bin/python3
import os
import subprocess
import sys
import json
import requests
import time
# --- Function to execute command with interactive printout sent to web-terminal in real-time
def interactive_command(cmd,session_name):
# --- Execute command
try:
cmd2 = 'printf "' + cmd + '" > /VVebUQ_runs/'+session_name+'/terminal_command.txt'
process = subprocess.Popen(cmd2, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
process.wait()
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
process.wait()
except Exception as exc:
print('Failed to execute command:\n%s' % (cmd))
print('due to exception:', exc)
sys.exit()
# --- Get output to web-terminal printout
try:
output = str(process.stdout.read(),'utf-8')
cmd2 = 'printf "new container: ' + output + '" >> /VVebUQ_runs/'+session_name+'/terminal_output.txt'
process = subprocess.Popen(cmd2, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
process.wait()
except Exception as exc:
print('Failed to print web-terminal output for command:\n%s' % (cmd))
print('due to exception:', exc)
sys.exit()
# --- Get the Prominence Session Token if it exists
def get_prominence_token():
if os.path.isfile(os.path.expanduser('~/.prominence/token')):
try:
with open(os.path.expanduser('~/.prominence/token')) as json_data:
data = json.load(json_data)
except Exception as ex:
print('Error trying to read token:', ex)
return None
if 'access_token' in data:
token = data['access_token']
return token
else:
print('The saved token file does not contain access_token')
return None
else:
print('PROMINENCE token file ~/.prominence/token does not exist')
return None
# --- Get a temporary URL from Prominence which can be used for uploading the run directory tarball
def get_prominence_upload_url(filename, headers):
try:
response = requests.post('%s/data/upload' % os.environ['PROMINENCE_URL'],
json={'filename':os.path.basename(filename)},
timeout=30,
headers=headers)
except requests.exceptions.RequestException as exc:
print('Unable to get URL due to', exc)
return None
if response.status_code == 401:
print('Authentication failed')
if response.status_code == 201:
if 'url' in response.json():
return response.json()['url']
return None
# ---------------
# --- Main script
# ---------------
# --- Extract arguments
with open('arguments_for_vvuq_script.txt') as args_file:
data = args_file.read()
my_args = data.strip().split(' ')
if (len(my_args) != 12):
print('run_script: not enough arguments in arguments_for_vvuq_script.txt')
sys.exit()
container_name = my_args[0]
run_dir = my_args[1]
image_name = my_args[2]
filename = my_args[3]
file_type = my_args[4]
data_filename = my_args[5]
user_inter_dir = my_args[6]
use_prominence = my_args[7]
n_cpu = my_args[8]
RAM = my_args[9]
selected_vvuq = my_args[10]
session_name = my_args[11]
# --- Get paths
path = os.getcwd()
my_run = path.split('/')
my_run = my_run[len(my_run)-1]
# --- Get all task-directories
try:
cmd = 'ls |grep "workdir_VVebUQ"'
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
process.wait()
subdirs = str(process.stdout.read(),'utf-8')
subdirs = subdirs.splitlines()
except Exception as exc:
print('Failed to execute command:\n%s' % (cmd))
print('due to exception:', exc)
sys.exit()
# --- Get Prominence token to check session is valid
token = get_prominence_token()
headers = {'Authorization':'Bearer %s' % token}
# --- Upload Dakota user interface
tarball = 'VVebUQ_user_interface.tgz'
interactive_command('tar -cvzf '+tarball+' /VVebUQ_user_interface',session_name)
# --- Get url from Prominence for this upload
url = get_prominence_upload_url(tarball, headers)
if (url is None):
print('Prominence: Unable to obtain upload URL for VVebUQ_user_interface')
sys.exit()
# --- Upload zipped file to Prominence
try:
with open(tarball, 'rb') as file_obj:
response = requests.put(url, data=file_obj, timeout=60)
except Exception as exc:
print('Prominence: Unable to upload VVebUQ_user_interface tarball due to', exc)
sys.exit()
if (response.status_code != 200):
print('Prominence: Unable to upload VVebUQ_user_interface tarball due to status error: ', response.status_code)
sys.exit()
# --- Remove zipped file now that it's uploaded
os.remove(tarball)
# --- Create .json job for each dir
for my_dir in subdirs:
if (my_dir.strip() == ''): continue
# --- Create tarball of directory
tarball = my_run+'___'+my_dir+'.tar.gz'
tarball_fullpath = my_dir+'/'+tarball
interactive_command('cd '+my_dir+'; tar -cvzf '+tarball+' ../'+my_dir+'; cd --',session_name)
# --- Get url from Prominence for this upload
url = get_prominence_upload_url(tarball_fullpath, headers)
if (url is None):
print('Prominence: Unable to obtain upload URL')
sys.exit()
# --- Upload zipped file to Prominence
try:
with open(tarball_fullpath, 'rb') as file_obj:
response = requests.put(url, data=file_obj, timeout=60)
except Exception as exc:
print('Prominence: Unable to upload tarball due to', exc)
sys.exit()
if (response.status_code != 200):
print('Prominence: Unable to upload tarball due to status error: ', response.status_code)
sys.exit()
# --- Remove zipped file now that it's uploaded
os.remove(tarball_fullpath)
# --- Create json file to define job for Prominence
resources = {}
resources['cpus'] = int(n_cpu)
resources['memory'] = int(RAM)
resources['disk'] = 10
resources['nodes'] = 1
resources['walltime'] = 21600
task = {}
task['cmd'] = ''
task['image'] = image_name
task['runtime'] = 'udocker'
task['workdir'] = '/tmp/work_dir'
artifact1 = {}
artifact1['url'] = tarball
artifact1['mountpoint'] = '%s:/tmp/work_dir' % my_dir
artifact2 = {}
artifact2['url'] = 'VVebUQ_user_interface.tgz'
artifact2['mountpoint'] = 'VVebUQ_user_interface:/VVebUQ_user_interface'
job = {}
job['name'] = '%s' % my_dir
job['name'] = job['name'].replace('.', '_')
job['tasks'] = [task]
job['resources'] = resources
job['artifacts'] = [artifact1,artifact2]
job['outputDirs'] = [my_dir]
with open('%s.json' % my_dir, 'w') as outfile:
json.dump(job, outfile)
# --- Create .json workflow containing all jobs
jobs = []
for my_dir in subdirs:
if (my_dir.strip() == ''): continue
with open(my_dir+'.json') as json_file:
data = json.load(json_file)
jobs.append(data)
workflow = {}
workflow['jobs'] = jobs
workflow['name'] = my_run
with open('prominence_workflow.json', 'w') as outfile:
json.dump(workflow, outfile)
# --- Submit Workflow
cmd = 'prominence run prominence_workflow.json'
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
process.wait()
output = str(process.stdout.read(),'utf-8')
# --- Record Workflow id
workflow_id = output.partition('Workflow created with id ')[2].strip()
if (workflow_id == ''):
time.sleep(10.0)
cmd = 'prominence list workflows | grep "'+my_run+'"'
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
process.wait()
output = str(process.stdout.read(),'utf-8')
workflow_id = output.partition(my_run)[0].strip()
with open('prominence_workflow_id.txt', 'w') as outfile:
outfile.write(workflow_id)
| [
"os.path.expanduser",
"subprocess.Popen",
"time.sleep",
"os.getcwd",
"os.path.basename",
"requests.put",
"sys.exit",
"json.load",
"json.dump",
"os.remove"
] | [((3409, 3420), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (3418, 3420), False, 'import os\n'), ((4863, 4881), 'os.remove', 'os.remove', (['tarball'], {}), '(tarball)\n', (4872, 4881), False, 'import os\n'), ((7341, 7427), 'subprocess.Popen', 'subprocess.Popen', (['cmd'], {'shell': '(True)', 'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.PIPE'}), '(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess\n .PIPE)\n', (7357, 7427), False, 'import subprocess\n'), ((3034, 3044), 'sys.exit', 'sys.exit', ([], {}), '()\n', (3042, 3044), False, 'import sys\n'), ((3566, 3652), 'subprocess.Popen', 'subprocess.Popen', (['cmd'], {'shell': '(True)', 'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.PIPE'}), '(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess\n .PIPE)\n', (3582, 3652), False, 'import subprocess\n'), ((4365, 4375), 'sys.exit', 'sys.exit', ([], {}), '()\n', (4373, 4375), False, 'import sys\n'), ((4804, 4814), 'sys.exit', 'sys.exit', ([], {}), '()\n', (4812, 4814), False, 'import sys\n'), ((5915, 5942), 'os.remove', 'os.remove', (['tarball_fullpath'], {}), '(tarball_fullpath)\n', (5924, 5942), False, 'import os\n'), ((7231, 7259), 'json.dump', 'json.dump', (['workflow', 'outfile'], {}), '(workflow, outfile)\n', (7240, 7259), False, 'import json\n'), ((7606, 7622), 'time.sleep', 'time.sleep', (['(10.0)'], {}), '(10.0)\n', (7616, 7622), False, 'import time\n'), ((7695, 7781), 'subprocess.Popen', 'subprocess.Popen', (['cmd'], {'shell': '(True)', 'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.PIPE'}), '(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess\n .PIPE)\n', (7711, 7781), False, 'import subprocess\n'), ((380, 467), 'subprocess.Popen', 'subprocess.Popen', (['cmd2'], {'shell': '(True)', 'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.PIPE'}), '(cmd2, shell=True, stdout=subprocess.PIPE, stderr=\n subprocess.PIPE)\n', (396, 467), False, 'import subprocess\n'), ((504, 590), 'subprocess.Popen', 'subprocess.Popen', (['cmd'], {'shell': '(True)', 'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.PIPE'}), '(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess\n .PIPE)\n', (520, 590), False, 'import subprocess\n'), ((988, 1075), 'subprocess.Popen', 'subprocess.Popen', (['cmd2'], {'shell': '(True)', 'stdout': 'subprocess.PIPE', 'stderr': 'subprocess.PIPE'}), '(cmd2, shell=True, stdout=subprocess.PIPE, stderr=\n subprocess.PIPE)\n', (1004, 1075), False, 'import subprocess\n'), ((1366, 1407), 'os.path.expanduser', 'os.path.expanduser', (['"""~/.prominence/token"""'], {}), "('~/.prominence/token')\n", (1384, 1407), False, 'import os\n'), ((3869, 3879), 'sys.exit', 'sys.exit', ([], {}), '()\n', (3877, 3879), False, 'import sys\n'), ((4481, 4525), 'requests.put', 'requests.put', (['url'], {'data': 'file_obj', 'timeout': '(60)'}), '(url, data=file_obj, timeout=60)\n', (4493, 4525), False, 'import requests\n'), ((4639, 4649), 'sys.exit', 'sys.exit', ([], {}), '()\n', (4647, 4649), False, 'import sys\n'), ((5404, 5414), 'sys.exit', 'sys.exit', ([], {}), '()\n', (5412, 5414), False, 'import sys\n'), ((5848, 5858), 'sys.exit', 'sys.exit', ([], {}), '()\n', (5856, 5858), False, 'import sys\n'), ((6856, 6879), 'json.dump', 'json.dump', (['job', 'outfile'], {}), '(job, outfile)\n', (6865, 6879), False, 'import json\n'), ((7061, 7081), 'json.load', 'json.load', (['json_file'], {}), '(json_file)\n', (7070, 7081), False, 'import json\n'), ((743, 753), 'sys.exit', 'sys.exit', ([], {}), '()\n', (751, 753), False, 'import sys\n'), ((1250, 1260), 'sys.exit', 'sys.exit', ([], {}), '()\n', (1258, 1260), False, 'import sys\n'), ((5545, 5589), 'requests.put', 'requests.put', (['url'], {'data': 'file_obj', 'timeout': '(60)'}), '(url, data=file_obj, timeout=60)\n', (5557, 5589), False, 'import requests\n'), ((5693, 5703), 'sys.exit', 'sys.exit', ([], {}), '()\n', (5701, 5703), False, 'import sys\n'), ((1525, 1545), 'json.load', 'json.load', (['json_data'], {}), '(json_data)\n', (1534, 1545), False, 'import json\n'), ((1445, 1486), 'os.path.expanduser', 'os.path.expanduser', (['"""~/.prominence/token"""'], {}), "('~/.prominence/token')\n", (1463, 1486), False, 'import os\n'), ((2266, 2292), 'os.path.basename', 'os.path.basename', (['filename'], {}), '(filename)\n', (2282, 2292), False, 'import os\n')] |
import datetime
import random
from typing import Union
from modules.duel_history import DuelHistory
def get_latest_duel(group_id: int) -> Union[DuelHistory, None]:
"""
:说明:
根据群号获取最近一场决斗记录
:参数
* group_id:QQ群号
:返回
* DuelHistory:俄罗斯轮盘决斗记录
* None:不存在记录
"""
r = DuelHistory\
.select()\
.where(DuelHistory.group_id == group_id)\
.order_by(DuelHistory.start_time.desc())
if len(r) <= 0:
return None
return r[0]
def get_latest_can_handle_duel(group_id: int) -> Union[DuelHistory, None]:
"""
:说明:
根据群号获取最近一场可被接受/拒绝的决斗记录
:参数
* group_id:QQ群号
:返回
* DuelHistory:俄罗斯轮盘决斗记录
* None:不存在记录
"""
r = DuelHistory\
.select()\
.where(DuelHistory.group_id == group_id, DuelHistory.state == 0)\
.order_by(DuelHistory.start_time.desc())
if len(r) <= 0:
return None
return r[0]
def get_latest_can_shot_duel(group_id: int) -> Union[DuelHistory, None]:
"""
:说明:
根据群号获取最近一场决斗中的记录
:参数
* group_id:QQ群号
:返回
* DuelHistory:俄罗斯轮盘决斗记录
* None:不存在记录
"""
r = DuelHistory\
.select()\
.where(DuelHistory.group_id == group_id, DuelHistory.state == 1)\
.order_by(DuelHistory.start_time.desc())
if len(r) <= 0:
return None
return r[0]
def insert_duel(
group_id: int,
player1: int,
player2: int,
wager: int,
):
"""
:说明:
插入一条新的决斗记录
:参数
* group_id:QQ群号
* player1:决斗者QQ号
* player2:被决斗者QQ号
* wager:赌注
:返回
* DuelHistory:俄罗斯轮盘决斗记录
* None:不存在记录
"""
DuelHistory.create(
group_id=group_id,
player1_id=player1,
player2_id=player2,
in_turn=player1,
wager=wager,
state=0,
start_time=datetime.datetime.now(),
)
def duel_accept(duel: DuelHistory):
bullet_list = []
# 随机子弹数
c_r = random.uniform(0, 1)
if c_r < 0.35:
c = 1
elif 0.35 <= c_r < 0.7:
c = 2
elif 0.7 <= c_r < 0.85:
c = 3
elif 0.85 <= c_r < 0.95:
c = 4
else:
c = 5
# 理论每个弹孔的子弹出现几率
p = c / 6
# 生成弹闸列表
for index in range(0, 6):
# 每装一个弹孔都要修正其几率
pt = c / (6 - index)
r = random.uniform(0, 1)
if r < pt and c != 0:
bullet_list.append('1')
c -= 1
else:
bullet_list.append('0')
# 默认是player1开首枪
duel.in_turn = duel.player1_id
duel.bullet = ','.join(bullet_list)
duel.probability = p * 100
duel.state = 1
duel.last_shot_time = datetime.datetime.now()
duel.save()
def duel_end(duel: DuelHistory):
duel.state = 2
duel.end_time = datetime.datetime.now()
duel.save()
def duel_denied(duel: DuelHistory):
duel.state = -1
duel.save()
def duel_shot(duel: DuelHistory) -> bool:
"""
开枪,同时更换开枪选手
True -> 被击中
False -> 未被击中
"""
result = duel.current_bullet
duel.order = duel.order + 1
duel.switch()
duel.last_shot_time = datetime.datetime.now()
duel.save()
return result
def duel_switch(duel: DuelHistory):
duel.switch()
duel.last_shot_time = datetime.datetime.now()
duel.save()
| [
"modules.duel_history.DuelHistory.select",
"datetime.datetime.now",
"random.uniform",
"modules.duel_history.DuelHistory.start_time.desc"
] | [((2009, 2029), 'random.uniform', 'random.uniform', (['(0)', '(1)'], {}), '(0, 1)\n', (2023, 2029), False, 'import random\n'), ((2683, 2706), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (2704, 2706), False, 'import datetime\n'), ((2797, 2820), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (2818, 2820), False, 'import datetime\n'), ((3130, 3153), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (3151, 3153), False, 'import datetime\n'), ((3270, 3293), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (3291, 3293), False, 'import datetime\n'), ((417, 446), 'modules.duel_history.DuelHistory.start_time.desc', 'DuelHistory.start_time.desc', ([], {}), '()\n', (444, 446), False, 'from modules.duel_history import DuelHistory\n'), ((864, 893), 'modules.duel_history.DuelHistory.start_time.desc', 'DuelHistory.start_time.desc', ([], {}), '()\n', (891, 893), False, 'from modules.duel_history import DuelHistory\n'), ((1303, 1332), 'modules.duel_history.DuelHistory.start_time.desc', 'DuelHistory.start_time.desc', ([], {}), '()\n', (1330, 1332), False, 'from modules.duel_history import DuelHistory\n'), ((2356, 2376), 'random.uniform', 'random.uniform', (['(0)', '(1)'], {}), '(0, 1)\n', (2370, 2376), False, 'import random\n'), ((1897, 1920), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (1918, 1920), False, 'import datetime\n'), ((317, 337), 'modules.duel_history.DuelHistory.select', 'DuelHistory.select', ([], {}), '()\n', (335, 337), False, 'from modules.duel_history import DuelHistory\n'), ((740, 760), 'modules.duel_history.DuelHistory.select', 'DuelHistory.select', ([], {}), '()\n', (758, 760), False, 'from modules.duel_history import DuelHistory\n'), ((1179, 1199), 'modules.duel_history.DuelHistory.select', 'DuelHistory.select', ([], {}), '()\n', (1197, 1199), False, 'from modules.duel_history import DuelHistory\n')] |
import os, lmdb
class UTXOIndex:
'''
Basically it is index [public_key -> set of unspent outputs with this public key]
'''
__shared_states = {}
def __init__(self, storage_space, path):
if not path in self.__shared_states:
self.__shared_states[path]={}
self.__dict__ = self.__shared_states[path]
self.directory = path
if not os.path.exists(path):
os.makedirs(self.directory) #TODO catch
self.env = lmdb.open(self.directory, max_dbs=10)
with self.env.begin(write=True) as txn:
self.main_db = self.env.open_db(b'main_db', txn=txn, dupsort=True, dupfixed=True) #TODO duplicate
self.storage_space = storage_space
self.storage_space.register_utxo_index(self)
def _add(self, serialized_pubkey, utxo_hash_and_pc):
with self.env.begin(write=True) as txn:
txn.put( serialized_pubkey, utxo_hash_and_pc, db=self.main_db, dupdata=True)
def add_utxo(self, output):
self._add(output.address.pubkey.serialize(), output.serialized_index)
def _remove(self, serialized_pubkey, utxo_hash_and_pc):
with self.env.begin(write=True) as txn:
txn.delete( serialized_pubkey, utxo_hash_and_pc, db=self.main_db)
def remove_utxo(self, output):
self._remove(output.address.pubkey.serialize(), output.serialized_index)
def get_all_unspent(self, pubkey):
return self.get_all_unspent_for_serialized_pubkey(pubkey.serialize())
def get_all_unspent_for_serialized_pubkey(self, serialized_pubkey):
with self.env.begin(write=False) as txn:
cursor = txn.cursor(db=self.main_db)
if not cursor.set_key(serialized_pubkey):
return []
else:
return list(cursor.iternext_dup())
| [
"os.path.exists",
"lmdb.open",
"os.makedirs"
] | [((448, 485), 'lmdb.open', 'lmdb.open', (['self.directory'], {'max_dbs': '(10)'}), '(self.directory, max_dbs=10)\n', (457, 485), False, 'import os, lmdb\n'), ((362, 382), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (376, 382), False, 'import os, lmdb\n'), ((393, 420), 'os.makedirs', 'os.makedirs', (['self.directory'], {}), '(self.directory)\n', (404, 420), False, 'import os, lmdb\n')] |
#!/usr/bin/env python
#
# genbank_get_genomes_by_taxon.py
#
# A script that takes an NCBI taxonomy identifier (or string, though this is
# not reliable for taxonomy tree subgraphs...) and downloads all genomes it
# can find from NCBI in the corresponding taxon subgraph with the passed
# argument as root.
#
# (c) TheJames Hutton Institute 2015
# Author: <NAME>
import logging
import logging.handlers
import os
import shutil
import sys
import time
import traceback
from argparse import ArgumentParser
from collections import defaultdict
from Bio import Entrez, SeqIO
# Parse command-line
def parse_cmdline(args):
"""Parse command-line arguments"""
parser = ArgumentParser(prog="genbacnk_get_genomes_by_taxon.py")
parser.add_argument("-o", "--outdir", dest="outdirname",
action="store", default=None,
help="Output directory")
parser.add_argument("-t", "--taxon", dest="taxon",
action="store", default=None,
help="NCBI taxonomy ID")
parser.add_argument("-v", "--verbose", dest="verbose",
action="store_true", default=False,
help="Give verbose output")
parser.add_argument("-f", "--force", dest="force",
action="store_true", default=False,
help="Force file overwriting")
parser.add_argument("--noclobber", dest="noclobber",
action="store_true", default=False,
help="Don't nuke existing files")
parser.add_argument("-l", "--logfile", dest="logfile",
action="store", default=None,
help="Logfile location")
parser.add_argument("--format", dest="format",
action="store", default="gbk,fasta",
help="Output file format [gbk|fasta]")
parser.add_argument("--email", dest="email",
action="store", default=None,
help="Email associated with NCBI queries")
return parser.parse_args()
# Set contact email for NCBI
def set_ncbi_email():
"""Set contact email for NCBI."""
Entrez.email = args.email
logger.info("Set NCBI contact email to %s" % args.email)
Entrez.tool = "genbank_get_genomes_by_taxon.py"
# Create output directory if it doesn't exist
def make_outdir():
"""Make the output directory, if required.
This is a little involved. If the output directory already exists,
we take the safe option by default, and stop with an error. We can,
however, choose to force the program to go on, in which case we can
either clobber the existing directory, or not. The options turn out
as the following, if the directory exists:
DEFAULT: stop and report the collision
FORCE: continue, and remove the existing output directory
NOCLOBBER+FORCE: continue, but do not remove the existing output
"""
if os.path.exists(args.outdirname):
if not args.force:
logger.error("Output directory %s would " % args.outdirname +
"overwrite existing files (exiting)")
sys.exit(1)
else:
logger.info("--force output directory use")
if args.noclobber:
logger.warning("--noclobber: existing output directory kept")
else:
logger.info("Removing directory %s and everything below it" %
args.outdirname)
shutil.rmtree(args.outdirname)
logger.info("Creating directory %s" % args.outdirname)
try:
os.makedirs(args.outdirname) # We make the directory recursively
except OSError:
# This gets thrown if the directory exists. If we've forced overwrite/
# delete and we're not clobbering, we let things slide
if args.noclobber and args.force:
logger.info("NOCLOBBER+FORCE: not creating directory")
else:
logger.error(last_exception)
sys.exit(1)
# Get assembly UIDs for the root taxon
def get_asm_uids(taxon_uid):
"""Returns a set of NCBI UIDs associated with the passed taxon.
This query at NCBI returns all assemblies for the taxon subtree
rooted at the passed taxon_uid.
"""
asm_ids = set() # Holds unique assembly UIDs
query = "txid%s[Organism:exp]" % taxon_uid
logger.info("ESearch for %s" % query)
# Perform initial search with usehistory
handle = Entrez.esearch(db="assembly", term=query, format="xml",
usehistory="y")
record = Entrez.read(handle)
result_count = int(record['Count'])
logger.info("Entrez ESearch returns %d assembly IDs" % result_count)
# Recover all child nodes
batch_size = 250
for start in range(0, result_count, batch_size):
tries, success = 0, False
while not success and tries < 20:
try:
batch_handle = Entrez.efetch(db="assembly", retmode="xml",
retstart=start,
retmax=batch_size,
webenv=record["WebEnv"],
query_key=record["QueryKey"])
batch_record = Entrez.read(batch_handle)
asm_ids = asm_ids.union(set(batch_record))
success = True
except:
tries += 1
logger.warning("Entrez batch query failed (#%d)" % tries)
if not success:
logger.error("Too many download attempt failures (exiting)")
sys.exit(1)
logger.info("Identified %d unique assemblies" % len(asm_ids))
return asm_ids
# Get contig UIDs for a specified assembly UID
def get_contig_uids(asm_uid):
"""Returns a set of NCBI UIDs associated with the passed assembly.
The UIDs returns are for assembly_nuccore_insdc sequences - the
assembly contigs."""
logger.info("Finding contig UIDs for assembly %s" % asm_uid)
contig_ids = set() # Holds unique contig UIDs
links = Entrez.read(Entrez.elink(dbfrom="assembly", db="nucleotide",
retmode="gb", from_uid=asm_uid))
contigs = [l for l in links[0]['LinkSetDb'] \
if l['LinkName'] == 'assembly_nuccore_insdc'][0]
contig_uids = set([e['Id'] for e in contigs['Link']])
logger.info("Identified %d contig UIDs" % len(contig_uids))
return contig_uids
# Write contigs for a single assembly out to file
def write_contigs(asm_uid, contig_uids):
"""Writes assembly contigs out to a single FASTA file in the script's
designated output directory.
FASTA records are returned, as GenBank and even GenBankWithParts format
records don't reliably give correct sequence in all cases.
The script returns two strings for each assembly, a 'class' and a 'label'
string - this is for use with, e.g. pyani.
"""
logger.info("Collecting contig data for %s" % asm_uid)
# Assembly record - get binomial and strain names
asm_record = Entrez.read(Entrez.esummary(db='assembly', id=asm_uid,
rettype='text'))
asm_organism = asm_record['DocumentSummarySet']['DocumentSummary']\
[0]['SpeciesName']
try:
asm_strain = asm_record['DocumentSummarySet']['DocumentSummary']\
[0]['Biosource']['InfraspeciesList'][0]['Sub_value']
except:
asm_strain = ""
# Assembly UID (long form) for the output filename
gname = asm_record['DocumentSummarySet']['DocumentSummary']\
[0]['AssemblyAccession'].split('.')[0]
outfilename = "%s.fasta" % os.path.join(args.outdirname, gname)
# Create label and class strings
genus, species = asm_organism.split(' ', 1)
ginit = genus[0] + '.'
labeltxt = "%s\t%s %s %s" % (gname, ginit, species, asm_strain)
classtxt = "%s\t%s" % (gname, asm_organism)
# Get FASTA records for contigs
logger.info("Downloading FASTA records for assembly %s (%s)" %
(asm_uid, ' '.join([ginit, species, asm_strain])))
query_uids = ','.join(contig_uids)
tries, success = 0, False
while not success and tries < 20:
try:
tries += 1
records = list(SeqIO.parse(Entrez.efetch(db='nucleotide',
id=query_uids,
rettype='fasta',
retmode='text'), 'fasta'))
# Check only that correct number of records returned.
if len(records) == len(contig_uids):
success = True
else:
logger.warning("FASTA download for assembly %s failed" %
asm_uid)
logger.warning("try %d/20" % tries)
# Could also check expected assembly sequence length?
totlen = sum([len(r) for r in records])
logger.info("Downloaded genome size: %d" % totlen)
except:
logger.warning("FASTA download for assembly %s failed" % asm_uid)
logger.warning("try %d/20" % tries)
if not success:
logger.error("Failed to download records for %s (exiting)" % asm_uid)
sys.exit(1)
# Write contigs to file
retval = SeqIO.write(records, outfilename, 'fasta')
logger.info("Wrote %d contigs to %s" % (retval, outfilename))
# Return labels for this genome
return classtxt, labeltxt
# Run as script
if __name__ == '__main__':
# Parse command-line
args = parse_cmdline(sys.argv)
# Set up logging
logger = logging.getLogger('genbank_get_genomes_by_taxon.py')
logger.setLevel(logging.DEBUG)
err_handler = logging.StreamHandler(sys.stderr)
err_formatter = logging.Formatter('%(levelname)s: %(message)s')
err_handler.setFormatter(err_formatter)
# Was a logfile specified? If so, use it
if args.logfile is not None:
try:
logstream = open(args.logfile, 'w')
err_handler_file = logging.StreamHandler(logstream)
err_handler_file.setFormatter(err_formatter)
err_handler_file.setLevel(logging.INFO)
logger.addHandler(err_handler_file)
except:
logger.error("Could not open %s for logging" %
args.logfile)
sys.exit(1)
# Do we need verbosity?
if args.verbose:
err_handler.setLevel(logging.INFO)
else:
err_handler.setLevel(logging.WARNING)
logger.addHandler(err_handler)
# Report arguments, if verbose
logger.info("genbank_get_genomes_by_taxon.py: %s" % time.asctime())
logger.info("command-line: %s" % ' '.join(sys.argv))
logger.info(args)
# Have we got an output directory? If not, exit.
if args.email is None:
logger.error("No email contact address provided (exiting)")
sys.exit(1)
set_ncbi_email()
# Have we got an output directory? If not, exit.
if args.outdirname is None:
logger.error("No output directory name (exiting)")
sys.exit(1)
make_outdir()
logger.info("Output directory: %s" % args.outdirname)
# We might have more than one taxon in a comma-separated list
taxon_ids = args.taxon.split(',')
logger.info("Passed taxon IDs: %s" % ', '.join(taxon_ids))
# Get all NCBI assemblies for each taxon UID
asm_dict = defaultdict(set)
for tid in taxon_ids:
asm_dict[tid] = get_asm_uids(tid)
for tid, asm_uids in asm_dict.items():
logger.info("Taxon %s: %d assemblies" % (tid, len(asm_uids)))
# Get links to the nucleotide database for each assembly UID
contig_dict = defaultdict(set)
for tid, asm_uids in asm_dict.items():
for asm_uid in asm_uids:
contig_dict[asm_uid] = get_contig_uids(asm_uid)
for asm_uid, contig_uids in contig_dict.items():
logger.info("Assembly %s: %d contigs" % (asm_uid, len(contig_uids)))
# Write each recovered assembly's contig set to a file in the
# specified output directory, and collect string labels to write in
# class and label files (e.g. for use with pyani).
classes, labels = [], []
for asm_uid, contig_uids in contig_dict.items():
classtxt, labeltxt = write_contigs(asm_uid, contig_uids)
classes.append(classtxt)
labels.append(labeltxt)
# Write class and label files
classfilename = os.path.join(args.outdirname, 'classes.txt')
labelfilename = os.path.join(args.outdirname, 'labels.txt')
logger.info("Writing classes file to %s" % classfilename)
with open(classfilename, 'w') as fh:
fh.write('\n'.join(classes))
logger.info("Writing labels file to %s" % labelfilename)
with open(labelfilename, 'w') as fh:
fh.write('\n'.join(labels))
| [
"logging.getLogger",
"os.path.exists",
"logging.StreamHandler",
"time.asctime",
"argparse.ArgumentParser",
"Bio.Entrez.esearch",
"os.makedirs",
"logging.Formatter",
"os.path.join",
"Bio.Entrez.elink",
"Bio.Entrez.esummary",
"shutil.rmtree",
"collections.defaultdict",
"Bio.Entrez.read",
"... | [((670, 725), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'prog': '"""genbacnk_get_genomes_by_taxon.py"""'}), "(prog='genbacnk_get_genomes_by_taxon.py')\n", (684, 725), False, 'from argparse import ArgumentParser\n'), ((2980, 3011), 'os.path.exists', 'os.path.exists', (['args.outdirname'], {}), '(args.outdirname)\n', (2994, 3011), False, 'import os\n'), ((4514, 4585), 'Bio.Entrez.esearch', 'Entrez.esearch', ([], {'db': '"""assembly"""', 'term': 'query', 'format': '"""xml"""', 'usehistory': '"""y"""'}), "(db='assembly', term=query, format='xml', usehistory='y')\n", (4528, 4585), False, 'from Bio import Entrez, SeqIO\n'), ((4627, 4646), 'Bio.Entrez.read', 'Entrez.read', (['handle'], {}), '(handle)\n', (4638, 4646), False, 'from Bio import Entrez, SeqIO\n'), ((9465, 9507), 'Bio.SeqIO.write', 'SeqIO.write', (['records', 'outfilename', '"""fasta"""'], {}), "(records, outfilename, 'fasta')\n", (9476, 9507), False, 'from Bio import Entrez, SeqIO\n'), ((9782, 9834), 'logging.getLogger', 'logging.getLogger', (['"""genbank_get_genomes_by_taxon.py"""'], {}), "('genbank_get_genomes_by_taxon.py')\n", (9799, 9834), False, 'import logging\n'), ((9888, 9921), 'logging.StreamHandler', 'logging.StreamHandler', (['sys.stderr'], {}), '(sys.stderr)\n', (9909, 9921), False, 'import logging\n'), ((9942, 9989), 'logging.Formatter', 'logging.Formatter', (['"""%(levelname)s: %(message)s"""'], {}), "('%(levelname)s: %(message)s')\n", (9959, 9989), False, 'import logging\n'), ((11572, 11588), 'collections.defaultdict', 'defaultdict', (['set'], {}), '(set)\n', (11583, 11588), False, 'from collections import defaultdict\n'), ((11854, 11870), 'collections.defaultdict', 'defaultdict', (['set'], {}), '(set)\n', (11865, 11870), False, 'from collections import defaultdict\n'), ((12599, 12643), 'os.path.join', 'os.path.join', (['args.outdirname', '"""classes.txt"""'], {}), "(args.outdirname, 'classes.txt')\n", (12611, 12643), False, 'import os\n'), ((12664, 12707), 'os.path.join', 'os.path.join', (['args.outdirname', '"""labels.txt"""'], {}), "(args.outdirname, 'labels.txt')\n", (12676, 12707), False, 'import os\n'), ((3644, 3672), 'os.makedirs', 'os.makedirs', (['args.outdirname'], {}), '(args.outdirname)\n', (3655, 3672), False, 'import os\n'), ((6166, 6251), 'Bio.Entrez.elink', 'Entrez.elink', ([], {'dbfrom': '"""assembly"""', 'db': '"""nucleotide"""', 'retmode': '"""gb"""', 'from_uid': 'asm_uid'}), "(dbfrom='assembly', db='nucleotide', retmode='gb', from_uid=asm_uid\n )\n", (6178, 6251), False, 'from Bio import Entrez, SeqIO\n'), ((7160, 7218), 'Bio.Entrez.esummary', 'Entrez.esummary', ([], {'db': '"""assembly"""', 'id': 'asm_uid', 'rettype': '"""text"""'}), "(db='assembly', id=asm_uid, rettype='text')\n", (7175, 7218), False, 'from Bio import Entrez, SeqIO\n'), ((7770, 7806), 'os.path.join', 'os.path.join', (['args.outdirname', 'gname'], {}), '(args.outdirname, gname)\n', (7782, 7806), False, 'import os\n'), ((9411, 9422), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (9419, 9422), False, 'import sys\n'), ((11061, 11072), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (11069, 11072), False, 'import sys\n'), ((11247, 11258), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (11255, 11258), False, 'import sys\n'), ((3189, 3200), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (3197, 3200), False, 'import sys\n'), ((5684, 5695), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (5692, 5695), False, 'import sys\n'), ((10205, 10237), 'logging.StreamHandler', 'logging.StreamHandler', (['logstream'], {}), '(logstream)\n', (10226, 10237), False, 'import logging\n'), ((10809, 10823), 'time.asctime', 'time.asctime', ([], {}), '()\n', (10821, 10823), False, 'import time\n'), ((3537, 3567), 'shutil.rmtree', 'shutil.rmtree', (['args.outdirname'], {}), '(args.outdirname)\n', (3550, 3567), False, 'import shutil\n'), ((4049, 4060), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (4057, 4060), False, 'import sys\n'), ((4993, 5131), 'Bio.Entrez.efetch', 'Entrez.efetch', ([], {'db': '"""assembly"""', 'retmode': '"""xml"""', 'retstart': 'start', 'retmax': 'batch_size', 'webenv': "record['WebEnv']", 'query_key': "record['QueryKey']"}), "(db='assembly', retmode='xml', retstart=start, retmax=\n batch_size, webenv=record['WebEnv'], query_key=record['QueryKey'])\n", (5006, 5131), False, 'from Bio import Entrez, SeqIO\n'), ((5338, 5363), 'Bio.Entrez.read', 'Entrez.read', (['batch_handle'], {}), '(batch_handle)\n', (5349, 5363), False, 'from Bio import Entrez, SeqIO\n'), ((10521, 10532), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (10529, 10532), False, 'import sys\n'), ((8389, 8467), 'Bio.Entrez.efetch', 'Entrez.efetch', ([], {'db': '"""nucleotide"""', 'id': 'query_uids', 'rettype': '"""fasta"""', 'retmode': '"""text"""'}), "(db='nucleotide', id=query_uids, rettype='fasta', retmode='text')\n", (8402, 8467), False, 'from Bio import Entrez, SeqIO\n')] |
import datetime
from django.test import TestCase
from ..utils import get_fiscal_year, Holiday
import logging
logger = logging.getLogger(__name__)
__author__ = 'lberrocal'
class TestUtils(TestCase):
def test_get_fiscal_year(self):
cdates = [[datetime.date(2015, 10, 1), 'AF16'],
[datetime.date(2015, 9, 30), 'AF15'],
[datetime.date(2016, 1, 5), 'AF16'],]
for cdate in cdates:
fy = get_fiscal_year(cdate[0])
self.assertEqual(cdate[1], fy)
def test_get_fiscal_year_datetime(self):
cdates = [[datetime.datetime(2015, 10, 1, 16, 0), 'AF16'],
[datetime.datetime(2015, 9, 30, 2, 45), 'AF15'],
[datetime.datetime(2016, 1, 5, 3, 45), 'AF16'],]
for cdate in cdates:
fy = get_fiscal_year(cdate[0])
self.assertEqual(cdate[1], fy)
class TestHolidays(TestCase):
def test_is_holiday(self):
holiday = datetime.date(2015,12,25)
holiday_manager = Holiday()
self.assertTrue(holiday_manager.is_holiday(holiday))
non_holiday = datetime.date(2015,12,24)
self.assertFalse(holiday_manager.is_holiday(non_holiday))
def test_working_days_between(self):
holiday_manager = Holiday()
start_date = datetime.date(2016, 1,1)
end_date = datetime.date(2016,1,31)
self.assertEqual(19, holiday_manager.working_days_between(start_date, end_date))
| [
"logging.getLogger",
"datetime.datetime",
"datetime.date"
] | [((118, 145), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (135, 145), False, 'import logging\n'), ((963, 990), 'datetime.date', 'datetime.date', (['(2015)', '(12)', '(25)'], {}), '(2015, 12, 25)\n', (976, 990), False, 'import datetime\n'), ((1109, 1136), 'datetime.date', 'datetime.date', (['(2015)', '(12)', '(24)'], {}), '(2015, 12, 24)\n', (1122, 1136), False, 'import datetime\n'), ((1300, 1325), 'datetime.date', 'datetime.date', (['(2016)', '(1)', '(1)'], {}), '(2016, 1, 1)\n', (1313, 1325), False, 'import datetime\n'), ((1344, 1370), 'datetime.date', 'datetime.date', (['(2016)', '(1)', '(31)'], {}), '(2016, 1, 31)\n', (1357, 1370), False, 'import datetime\n'), ((255, 281), 'datetime.date', 'datetime.date', (['(2015)', '(10)', '(1)'], {}), '(2015, 10, 1)\n', (268, 281), False, 'import datetime\n'), ((311, 337), 'datetime.date', 'datetime.date', (['(2015)', '(9)', '(30)'], {}), '(2015, 9, 30)\n', (324, 337), False, 'import datetime\n'), ((367, 392), 'datetime.date', 'datetime.date', (['(2016)', '(1)', '(5)'], {}), '(2016, 1, 5)\n', (380, 392), False, 'import datetime\n'), ((584, 621), 'datetime.datetime', 'datetime.datetime', (['(2015)', '(10)', '(1)', '(16)', '(0)'], {}), '(2015, 10, 1, 16, 0)\n', (601, 621), False, 'import datetime\n'), ((651, 688), 'datetime.datetime', 'datetime.datetime', (['(2015)', '(9)', '(30)', '(2)', '(45)'], {}), '(2015, 9, 30, 2, 45)\n', (668, 688), False, 'import datetime\n'), ((718, 754), 'datetime.datetime', 'datetime.datetime', (['(2016)', '(1)', '(5)', '(3)', '(45)'], {}), '(2016, 1, 5, 3, 45)\n', (735, 754), False, 'import datetime\n')] |
import pytorch_lightning as pl
import torch
from torch.utils.data import Dataset, DataLoader, random_split
from sklearn.preprocessing import LabelEncoder
from PIL import Image
import numpy as np
import pandas as pd
def encode_labels(labels):
le = LabelEncoder()
encoded = le.fit_transform(labels)
return le, encoded
def read_image(path, w, h):
img = Image.open(path)
img = img.resize((w, h))
img = img.convert('RGB')
return np.array(img)
class ImageNetDataset(Dataset):
def __init__(self, width, height, img_paths, labels):
super().__init__()
self.width, self.height = width, height
self.img_paths = img_paths
self.encoder, self.labels = encode_labels(labels)
def __len__(self):
return self.img_paths.shape[0]
def __getitem__(self, i):
img = read_image(self.img_paths[i], self.width, self.height)
label = self.labels[i]
img = np.transpose(img, (2, 0, 1)).astype('float32')/255
return img, label
class DataModule(pl.LightningDataModule):
def __init__(self, path, n, width, height, batch_size=32, num_workers=8, split={'train':.8, 'test':.1, 'val':.1}):
super().__init__()
self.path = path
self.n = n
self.width, self.height = width, height
self.batch_size = batch_size
self.num_workers = num_workers
self.split = split
def prepare_data(self):
df = pd.read_csv(self.path).to_numpy()[:self.n]
img_paths, labels = df[:, 0], df [:, 1]
self.dataset = ImageNetDataset(self.width, self.height, img_paths, labels)
def setup(self, stage=None):
if stage=='fit' or stage is None:
n = len(self.dataset)
l = [self.split['val'], self.split['test']]
val, test = map(lambda x: int(x*n), l)
train = n - (val + test)
self.train, self.val, self.test = random_split(self.dataset, [train, val, test], generator=torch.Generator().manual_seed(42))
def train_dataloader(self):
return DataLoader(self.train, batch_size=self.batch_size, num_workers=self.num_workers, pin_memory=True)
def val_dataloader(self):
return DataLoader(self.val, batch_size=self.batch_size, num_workers=self.num_workers, pin_memory=True)
def test_dataloader(self):
return DataLoader(self.test, batch_size=self.batch_size, num_workers=self.num_workers, pin_memory=True)
| [
"sklearn.preprocessing.LabelEncoder",
"PIL.Image.open",
"pandas.read_csv",
"numpy.array",
"torch.utils.data.DataLoader",
"numpy.transpose",
"torch.Generator"
] | [((256, 270), 'sklearn.preprocessing.LabelEncoder', 'LabelEncoder', ([], {}), '()\n', (268, 270), False, 'from sklearn.preprocessing import LabelEncoder\n'), ((384, 400), 'PIL.Image.open', 'Image.open', (['path'], {}), '(path)\n', (394, 400), False, 'from PIL import Image\n'), ((470, 483), 'numpy.array', 'np.array', (['img'], {}), '(img)\n', (478, 483), True, 'import numpy as np\n'), ((2125, 2227), 'torch.utils.data.DataLoader', 'DataLoader', (['self.train'], {'batch_size': 'self.batch_size', 'num_workers': 'self.num_workers', 'pin_memory': '(True)'}), '(self.train, batch_size=self.batch_size, num_workers=self.\n num_workers, pin_memory=True)\n', (2135, 2227), False, 'from torch.utils.data import Dataset, DataLoader, random_split\n'), ((2269, 2369), 'torch.utils.data.DataLoader', 'DataLoader', (['self.val'], {'batch_size': 'self.batch_size', 'num_workers': 'self.num_workers', 'pin_memory': '(True)'}), '(self.val, batch_size=self.batch_size, num_workers=self.\n num_workers, pin_memory=True)\n', (2279, 2369), False, 'from torch.utils.data import Dataset, DataLoader, random_split\n'), ((2412, 2513), 'torch.utils.data.DataLoader', 'DataLoader', (['self.test'], {'batch_size': 'self.batch_size', 'num_workers': 'self.num_workers', 'pin_memory': '(True)'}), '(self.test, batch_size=self.batch_size, num_workers=self.\n num_workers, pin_memory=True)\n', (2422, 2513), False, 'from torch.utils.data import Dataset, DataLoader, random_split\n'), ((974, 1002), 'numpy.transpose', 'np.transpose', (['img', '(2, 0, 1)'], {}), '(img, (2, 0, 1))\n', (986, 1002), True, 'import numpy as np\n'), ((1503, 1525), 'pandas.read_csv', 'pd.read_csv', (['self.path'], {}), '(self.path)\n', (1514, 1525), True, 'import pandas as pd\n'), ((2042, 2059), 'torch.Generator', 'torch.Generator', ([], {}), '()\n', (2057, 2059), False, 'import torch\n')] |
#
# This file is part of pysnmp software.
#
# Copyright (c) 2005-2019, <NAME> <<EMAIL>>
# License: http://snmplabs.com/pysnmp/license.html
#
# This file instantiates some of the MIB managed objects for SNMP engine use
#
if 'mibBuilder' not in globals():
import sys
sys.stderr.write(__doc__)
sys.exit(1)
MibScalarInstance, = mibBuilder.importSymbols(
'SNMPv2-SMI',
'MibScalarInstance'
)
(snmpTargetSpinLock,
snmpUnavailableContexts,
snmpUnknownContexts) = mibBuilder.importSymbols(
'SNMP-TARGET-MIB',
'snmpTargetSpinLock',
'snmpUnavailableContexts',
'snmpUnknownContexts'
)
_snmpTargetSpinLock = MibScalarInstance(
snmpTargetSpinLock.name, (0,),
snmpTargetSpinLock.syntax.clone(0)
)
_snmpUnavailableContexts = MibScalarInstance(
snmpUnavailableContexts.name, (0,),
snmpUnavailableContexts.syntax.clone(0)
)
_snmpUnknownContexts = MibScalarInstance(
snmpUnknownContexts.name, (0,),
snmpUnknownContexts.syntax.clone(0)
)
mibBuilder.exportSymbols(
'__SNMP-TARGET-MIB',
snmpTargetSpinLock=_snmpTargetSpinLock,
snmpUnavailableContexts=_snmpUnavailableContexts,
snmpUnknownContexts=_snmpUnknownContexts
)
| [
"sys.stderr.write",
"sys.exit"
] | [((275, 300), 'sys.stderr.write', 'sys.stderr.write', (['__doc__'], {}), '(__doc__)\n', (291, 300), False, 'import sys\n'), ((305, 316), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (313, 316), False, 'import sys\n')] |
import argparse
import shutil
import numpy as np
from project.data_preprocessing.preprocessing import Preprocessor
from project.data_preprocessing.data_loader import Loader
from project.models.model import Model
from prostagma.techniques.grid_search import GridSearch
from prostagma.performances.cross_validation import CrossValidation
parser = argparse.ArgumentParser()
""" General Parameters """
parser.add_argument('--test', type=bool, default=False,
help='if True test the model.')
parser.add_argument('--train', type=bool, default=False,
help='if True train the model.')
""" Model Parameters """
parser.add_argument('--log_dir', type=str, default='./tensorbaord',
help='directory where to store tensorbaord values.')
parser.add_argument('--model_path', type=str,
default='./project/weights/model',
help='model checkpoints directory.')
parser.add_argument('--epochs', type=int, default=10,
help='number of batch iterations.')
parser.add_argument('--batch_size', type=int, default=32,
help='number of samples in the training batch.')
parser.add_argument('--number_of_samples', type=int, default=1500,
help='number of samples to load in memory.')
parser.add_argument('--train_samples', type=int, default=50,
help='number of samples to load in memory.')
parser.add_argument('--val_samples', type=int, default=50,
help='number of samples to load in memory.')
parser.add_argument('--test_samples', type=int, default=100,
help='number of samples to load in memory.')
args = parser.parse_args()
def main():
# Remove Tensorboard Folder
try:
shutil.rmtree('./tensorbaord')
except FileNotFoundError:
pass
# Fix the seed
np.random.seed(0)
# Load the data
loader = Loader(number_of_samples=args.number_of_samples)
X, y = loader.load_data()
print("Loaded the data...")
# Preprocess the data
preprocessor = Preprocessor(
train_samples=args.train_samples,
test_samples=args.test_samples,
val_samples=args.val_samples)
X_train, y_train, X_test, y_test, X_val, y_val = preprocessor.fit_transform(X, y)
# Define the Model
model = Model(
log_dir=args.log_dir,
model_path=args.model_path
)
# Directly Validate the model
validator = CrossValidation(
k_fold=5,
epochs=args.epochs,
batch_size=args.batch_size)
results = validator.fit(X_train, y_train, model.build_model)
print("Mean: %f Std(%f)" % (results.mean(), results.std()))
# Tuning The Parameters
# Define the dictionary of parameters
parameters = {
"dropout" : [0.25, 0.5, 0.75],
"learning_rate" : [0.1, 0.01, 0.001, 0.0001]
}
# Define the Strategy to use
strategy = GridSearch(
parameters=parameters,
model=model.build_model,
performance_validator=CrossValidation(
k_fold=5,
epochs=args.epochs,
batch_size=args.batch_size
)
)
strategy.fit(X_train, y_train)
# Show the results
print("Best Parameters: ")
print(strategy.best_param)
print("Best Score Obtained: ")
print(strategy.best_score)
return
main() | [
"project.data_preprocessing.data_loader.Loader",
"argparse.ArgumentParser",
"project.data_preprocessing.preprocessing.Preprocessor",
"numpy.random.seed",
"shutil.rmtree",
"prostagma.performances.cross_validation.CrossValidation",
"project.models.model.Model"
] | [((348, 373), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (371, 373), False, 'import argparse\n'), ((1718, 1735), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (1732, 1735), True, 'import numpy as np\n'), ((1770, 1818), 'project.data_preprocessing.data_loader.Loader', 'Loader', ([], {'number_of_samples': 'args.number_of_samples'}), '(number_of_samples=args.number_of_samples)\n', (1776, 1818), False, 'from project.data_preprocessing.data_loader import Loader\n'), ((1927, 2040), 'project.data_preprocessing.preprocessing.Preprocessor', 'Preprocessor', ([], {'train_samples': 'args.train_samples', 'test_samples': 'args.test_samples', 'val_samples': 'args.val_samples'}), '(train_samples=args.train_samples, test_samples=args.\n test_samples, val_samples=args.val_samples)\n', (1939, 2040), False, 'from project.data_preprocessing.preprocessing import Preprocessor\n'), ((2176, 2231), 'project.models.model.Model', 'Model', ([], {'log_dir': 'args.log_dir', 'model_path': 'args.model_path'}), '(log_dir=args.log_dir, model_path=args.model_path)\n', (2181, 2231), False, 'from project.models.model import Model\n'), ((2309, 2382), 'prostagma.performances.cross_validation.CrossValidation', 'CrossValidation', ([], {'k_fold': '(5)', 'epochs': 'args.epochs', 'batch_size': 'args.batch_size'}), '(k_fold=5, epochs=args.epochs, batch_size=args.batch_size)\n', (2324, 2382), False, 'from prostagma.performances.cross_validation import CrossValidation\n'), ((1616, 1646), 'shutil.rmtree', 'shutil.rmtree', (['"""./tensorbaord"""'], {}), "('./tensorbaord')\n", (1629, 1646), False, 'import shutil\n'), ((2874, 2947), 'prostagma.performances.cross_validation.CrossValidation', 'CrossValidation', ([], {'k_fold': '(5)', 'epochs': 'args.epochs', 'batch_size': 'args.batch_size'}), '(k_fold=5, epochs=args.epochs, batch_size=args.batch_size)\n', (2889, 2947), False, 'from prostagma.performances.cross_validation import CrossValidation\n')] |
from __future__ import unicode_literals
from django.db import models
from ckeditor_uploader.fields import RichTextUploadingField
from django.db.models.signals import pre_save
from django.template.defaultfilters import slugify
from django.dispatch import receiver
class Season(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(max_length=100)
def __str__(self):
return self.name
class Competition(models.Model):
name = models.CharField(max_length=100)
season = models.ForeignKey(Season)
slug = models.SlugField(max_length=100)
def __str__(self):
return self.name
class Robot(models.Model):
name = models.CharField(max_length=100)
season = models.ForeignKey(Season)
competition = models.ForeignKey(Competition)
software = RichTextUploadingField()
electronic = RichTextUploadingField()
mechanic = RichTextUploadingField()
slug = models.SlugField(max_length=100)
def __str__(self):
return self.name
class RoboticsSponsors(models.Model):
name = models.CharField(max_length=100)
season = models.ForeignKey(Season)
content = RichTextUploadingField()
is_success = models.BooleanField(default=False)
slug = models.SlugField(max_length=100)
def __str__(self):
return self.name
class RoboticsPress(models.Model):
name = models.CharField(max_length=100)
season = models.ForeignKey(Season)
content = RichTextUploadingField()
created_at = models.DateTimeField(auto_now_add=True)
slug = models.SlugField()
def __str__(self):
return self.name
@receiver(pre_save,sender=Season)
def season_slug_handler(sender, instance, *args, **kwargs):
instance.slug = slugify(instance.name)
@receiver(pre_save,sender=Robot)
def robot_slug_handler(sender,instance,*args,**kwargs):
instance.slug = slugify(instance.name)
@receiver(pre_save,sender=Competition)
def competition_slug_handler(sender,instance,*args,**kwargs):
instance.slug = slugify(instance.name)
@receiver(pre_save,sender=RoboticsSponsors)
def sponsors_slug_handler(sender,instance,*args,**kwargs):
instance.slug = slugify(instance.name)
@receiver(pre_save,sender=RoboticsPress)
def press_slug_handler(sender,instance,*args,**kwargs):
instance.slug = slugify(instance.name) | [
"ckeditor_uploader.fields.RichTextUploadingField",
"django.db.models.ForeignKey",
"django.db.models.DateTimeField",
"django.db.models.BooleanField",
"django.template.defaultfilters.slugify",
"django.db.models.SlugField",
"django.dispatch.receiver",
"django.db.models.CharField"
] | [((1623, 1656), 'django.dispatch.receiver', 'receiver', (['pre_save'], {'sender': 'Season'}), '(pre_save, sender=Season)\n', (1631, 1656), False, 'from django.dispatch import receiver\n'), ((1761, 1793), 'django.dispatch.receiver', 'receiver', (['pre_save'], {'sender': 'Robot'}), '(pre_save, sender=Robot)\n', (1769, 1793), False, 'from django.dispatch import receiver\n'), ((1898, 1936), 'django.dispatch.receiver', 'receiver', (['pre_save'], {'sender': 'Competition'}), '(pre_save, sender=Competition)\n', (1906, 1936), False, 'from django.dispatch import receiver\n'), ((2043, 2086), 'django.dispatch.receiver', 'receiver', (['pre_save'], {'sender': 'RoboticsSponsors'}), '(pre_save, sender=RoboticsSponsors)\n', (2051, 2086), False, 'from django.dispatch import receiver\n'), ((2190, 2230), 'django.dispatch.receiver', 'receiver', (['pre_save'], {'sender': 'RoboticsPress'}), '(pre_save, sender=RoboticsPress)\n', (2198, 2230), False, 'from django.dispatch import receiver\n'), ((304, 336), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)'}), '(max_length=100)\n', (320, 336), False, 'from django.db import models\n'), ((348, 380), 'django.db.models.SlugField', 'models.SlugField', ([], {'max_length': '(100)'}), '(max_length=100)\n', (364, 380), False, 'from django.db import models\n'), ((476, 508), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)'}), '(max_length=100)\n', (492, 508), False, 'from django.db import models\n'), ((522, 547), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Season'], {}), '(Season)\n', (539, 547), False, 'from django.db import models\n'), ((559, 591), 'django.db.models.SlugField', 'models.SlugField', ([], {'max_length': '(100)'}), '(max_length=100)\n', (575, 591), False, 'from django.db import models\n'), ((681, 713), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)'}), '(max_length=100)\n', (697, 713), False, 'from django.db import models\n'), ((727, 752), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Season'], {}), '(Season)\n', (744, 752), False, 'from django.db import models\n'), ((771, 801), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Competition'], {}), '(Competition)\n', (788, 801), False, 'from django.db import models\n'), ((817, 841), 'ckeditor_uploader.fields.RichTextUploadingField', 'RichTextUploadingField', ([], {}), '()\n', (839, 841), False, 'from ckeditor_uploader.fields import RichTextUploadingField\n'), ((859, 883), 'ckeditor_uploader.fields.RichTextUploadingField', 'RichTextUploadingField', ([], {}), '()\n', (881, 883), False, 'from ckeditor_uploader.fields import RichTextUploadingField\n'), ((899, 923), 'ckeditor_uploader.fields.RichTextUploadingField', 'RichTextUploadingField', ([], {}), '()\n', (921, 923), False, 'from ckeditor_uploader.fields import RichTextUploadingField\n'), ((935, 967), 'django.db.models.SlugField', 'models.SlugField', ([], {'max_length': '(100)'}), '(max_length=100)\n', (951, 967), False, 'from django.db import models\n'), ((1069, 1101), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)'}), '(max_length=100)\n', (1085, 1101), False, 'from django.db import models\n'), ((1115, 1140), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Season'], {}), '(Season)\n', (1132, 1140), False, 'from django.db import models\n'), ((1155, 1179), 'ckeditor_uploader.fields.RichTextUploadingField', 'RichTextUploadingField', ([], {}), '()\n', (1177, 1179), False, 'from ckeditor_uploader.fields import RichTextUploadingField\n'), ((1197, 1231), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(False)'}), '(default=False)\n', (1216, 1231), False, 'from django.db import models\n'), ((1243, 1275), 'django.db.models.SlugField', 'models.SlugField', ([], {'max_length': '(100)'}), '(max_length=100)\n', (1259, 1275), False, 'from django.db import models\n'), ((1373, 1405), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(100)'}), '(max_length=100)\n', (1389, 1405), False, 'from django.db import models\n'), ((1419, 1444), 'django.db.models.ForeignKey', 'models.ForeignKey', (['Season'], {}), '(Season)\n', (1436, 1444), False, 'from django.db import models\n'), ((1459, 1483), 'ckeditor_uploader.fields.RichTextUploadingField', 'RichTextUploadingField', ([], {}), '()\n', (1481, 1483), False, 'from ckeditor_uploader.fields import RichTextUploadingField\n'), ((1501, 1540), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'auto_now_add': '(True)'}), '(auto_now_add=True)\n', (1521, 1540), False, 'from django.db import models\n'), ((1552, 1570), 'django.db.models.SlugField', 'models.SlugField', ([], {}), '()\n', (1568, 1570), False, 'from django.db import models\n'), ((1736, 1758), 'django.template.defaultfilters.slugify', 'slugify', (['instance.name'], {}), '(instance.name)\n', (1743, 1758), False, 'from django.template.defaultfilters import slugify\n'), ((1869, 1891), 'django.template.defaultfilters.slugify', 'slugify', (['instance.name'], {}), '(instance.name)\n', (1876, 1891), False, 'from django.template.defaultfilters import slugify\n'), ((2018, 2040), 'django.template.defaultfilters.slugify', 'slugify', (['instance.name'], {}), '(instance.name)\n', (2025, 2040), False, 'from django.template.defaultfilters import slugify\n'), ((2165, 2187), 'django.template.defaultfilters.slugify', 'slugify', (['instance.name'], {}), '(instance.name)\n', (2172, 2187), False, 'from django.template.defaultfilters import slugify\n'), ((2306, 2328), 'django.template.defaultfilters.slugify', 'slugify', (['instance.name'], {}), '(instance.name)\n', (2313, 2328), False, 'from django.template.defaultfilters import slugify\n')] |
from django.shortcuts import render, redirect
from django.db import connection
from .forms import ProfileForm, LocationForm, SearchLocationForm
import populartimes
import datetime
import math
from mycrawl import popCrawl
def index(request):
# Render the HTML template index.html with the data in the context variable.
return render(
request,
'index.html',
)
def CreateUser(request):
return render(request, 'catalog/user_info_create.html')
def str2list(in_str):
return in_str.split(',')
def list2str(in_list):
return ",".join(in_list)
def InsertUserForm(request):
if request.method == "POST":
prof = ProfileForm(request.POST)
with connection.cursor() as cursor:
cursor.execute("SELECT * FROM Profile WHERE Profile.userid = %s", [str(request.user.id)])
row = cursor.fetchall()
# update Profile table
if len(row) == 0:
cursor.execute("INSERT INTO Profile(name, netid, phone, userid) VALUES(%s, %s, %s, %s)", [prof.data['name'], prof.data['netid'], prof.data['phone'], str(request.user.id)])
else:
return render(request, 'catalog/user_info_duplicate.html')
# prof.data['course'] is a comma seperated string
course_list = str2list(prof.data['course'])
for c in course_list:
cursor.execute("INSERT INTO Course(netid, course) VALUES(%s, %s)", [prof.data['netid'], c])
return redirect('user-detail')
def UserUpdate(request):
return render(request, 'catalog/user_info_update.html')
def UpdateUserForm(request):
if request.method == "POST":
prof = ProfileForm(request.POST)
with connection.cursor() as cursor:
cursor.execute("SELECT netid FROM Profile WHERE Profile.userid = %s", [str(request.user.id)])
row = cursor.fetchall()
if len(row) == 0:
print("User does not exists in Profile, please insert user info before update!!!")
else:
if prof.data['name']:
cursor.execute("UPDATE Profile SET name=%s WHERE Profile.netid = %s", [prof.data['name'], row[0]])
if prof.data['phone']:
cursor.execute("UPDATE Profile SET phone=%s WHERE Profile.netid = %s", [prof.data['phone'], row[0]])
if prof.data['course']:
# delete all existing courses for this user
cursor.execute("DELETE FROM Course WHERE Course.netid = %s", [row[0]])
# then insert new courses one by one
course_list = str2list(prof.data['course'])
for c in course_list:
cursor.execute("INSERT INTO Course(netid, course) VALUES(%s, %s)",
[row[0], c])
# print('User Info Upated')
return redirect('user-detail')
def UserDetail(request):
if request.method == "GET":
with connection.cursor() as cursor:
cursor.execute("SELECT * FROM Profile WHERE Profile.userid = %s", [str(request.user.id)])
row = cursor.fetchall()
if len(row) == 0:
print("User does not exists, please register first!!!")
return render(request, 'catalog/user_info_not_found.html')
else:
cursor.execute("SELECT * FROM Course WHERE Course.netid = %s", [row[0][1]])
row_course = cursor.fetchall()
c_list = []
for item in row_course:
c_list.append(item[1])
c_str = list2str(c_list)
# Render the HTML template index.html with the data in the context variable.
return render(
request,
'catalog/user_info.html',
context={'Name': row[0][0],
'netid': row[0][1],
'phone': row[0][2],
'course': c_str,
})
def UserDelete(request):
with connection.cursor() as cursor:
cursor.execute("SELECT netid FROM Profile WHERE Profile.userid = %s", [str(request.user.id)])
row = cursor.fetchall()
cursor.execute("DELETE FROM Profile WHERE Profile.netid = %s", [row[0]])
cursor.execute("DELETE FROM Course WHERE Course.netid = %s", [row[0]])
return render(request, 'catalog/user_info_deleted.html')
def getDist(lat1, lon1, lat2, lon2):
lat1, lon1 = float(lat1), float(lon1)
lat2, lon2 = float(lat2), float(lon2)
R = 3961
dlon = (lon2 - lon1) * math.pi /180
dlat = (lat2 - lat1) * math.pi /180
a = (math.sin(dlat/2))**2 + math.cos(lat1) * math.cos(lat2) * (math.sin(dlon/2))**2
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
distance = R * c
return distance
def UserMatch(request):
if request.method == "POST":
place_name = SearchLocationForm(request.POST).data['name']
print(str(place_name))
distanceLimit = SearchLocationForm(request.POST).data['distanceLimit']
with connection.cursor() as cursor:
cursor.execute("SELECT Course.course FROM Course INNER JOIN Profile ON Course.netid = Profile.netid WHERE Profile.userid = %s", [str(request.user.id)])
self_course = set(cursor.fetchall())
cursor.execute("SELECT * FROM Place WHERE Place.name = %s", [place_name])
location = cursor.fetchall()[0]
name = location[0]
longitude = location[1]
latitude = location[2]
crowdedness = location[3]
type = location[4]
candidates = []
range = float(distanceLimit)
cursor.execute("SELECT * FROM Location")
user_location = cursor.fetchall()
for item in user_location:
distance = getDist(item[2], item[1], latitude, longitude)
if distance < range:
candidates.append(item[0])
final_list = []
for student in candidates:
cursor.execute("SELECT Course.course FROM Course WHERE Course.netid = %s", [student])
row_course = set(cursor.fetchall())
if self_course.intersection(row_course):
final_list.append(student)
return render(request, 'catalog/user_match.html', context={'userList': final_list})
def UserDeleted(request):
return redirect("logout")
def Search(request):
return redirect('user-detail')
def CrawlMyPop(request):
mycrawl = popCrawl()
mycrawl.engine(request)
return redirect('user-detail')
def CrawlPopularity(request):
popdata_library = populartimes.get("<KEY>", ["library"], (40.116193536286815, -88.2435300726317), (40.08857770924527, -88.2047958483285))
popdata_cafe = populartimes.get("<KEY>", ["cafe"], (40.116193536286815, -88.2435300726317), (40.08857770924527, -88.2047958483285))
# for item1 in popdata_library:
# facility = populartimes.get_id("<KEY>vCW98",item1['id'])
# if 'current_popularity' not in facility:
# facility['current_popularity'] = None
# print(item1['name'], item1['coordinates']['lng'], item1['coordinates']['lat'], facility['current_popularity'])
to_weekday = {1:"Monday",2:"Tuesday",3:"Wednesday", 4:"Thursday", 5:"Friday",6:"Saturday",7:"Sunday"}
today = to_weekday[datetime.datetime.today().weekday()]
with connection.cursor() as cursor:
for item1, item2 in zip(popdata_library, popdata_cafe):
library = populartimes.get_id("<KEY>",item1['id'])
cafe = populartimes.get_id("<KEY>",item2['id'])
if 'current_popularity' not in library:
library['current_popularity'] = 0
if 'current_popularity' not in cafe:
cafe['current_popularity'] = 0
try:
cursor.execute("INSERT INTO Place(name, longitude, latitude, crowdedness, type) VALUE (%s, %s, %s, %s, %s)",\
[str(item1['name']), \
str(item1['coordinates']['lng']), str(item1['coordinates']['lat']), \
str(library['current_popularity']),\
"Library"])
except:
pass
try:
cursor.execute("INSERT INTO Place(name, longitude, latitude, crowdedness, type) VALUE (%s, %s, %s, %s, %s)",\
[str(item2['name']), \
str(item2['coordinates']['lng']), str(item2['coordinates']['lat']), \
str(cafe['current_popularity']),
"Cafe"])
except:
pass
return redirect("user-detail")
def UpdateLocation(request):
if request.method == "POST":
location = LocationForm(request.POST)
print(location)
return redirect('user-insert')
def SearchLocation(request):
if request.method == "POST":
curLongitude = LocationForm(request.POST).data['longitude']
curLatitude = LocationForm(request.POST).data['latitude']
locationType = SearchLocationForm(request.POST).data['locationType']
print (locationType, curLongitude, curLatitude)
distanceLimit = SearchLocationForm(request.POST).data['distanceLimit']
print (distanceLimit)
placeList = []
with connection.cursor() as cursor:
cursor.execute("SELECT * FROM Place WHERE Place.type = %s", [str(locationType)])
row_location = cursor.fetchall()
for location in row_location:
print (location)
name = location[0]
longitude = location[1]
latitude = location[2]
crowdedness = location[3]
type = location[4]
lat1, lon1 = 40.113746, -88.221730
lat2, lon2 = 40.091162, -88.239937
if curLongitude and curLatitude:
lat1, lon1 = float(curLatitude), float(curLongitude)
if (longitude) and (latitude):
lat2, lon2 = float(latitude), float(longitude)
R = 3961
dlon = (lon2 - lon1)* math.pi /180
dlat = (lat2 - lat1)* math.pi /180
a = (math.sin(dlat/2))**2 + math.cos(lat1) * math.cos(lat2) * (math.sin(dlon/2))**2
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a) )
distance = R * c
range = float(distanceLimit)
if distance < range:
placeList.append((name, type, crowdedness, distance))
sortedPlaceList = sorted(placeList, key = lambda x: x[3])
return render(
request,
'catalog/match_location.html',
context={'allPlaces' : sortedPlaceList}
)
def MatchUser(request):
return render(request, "catalog/match_user.html")
def MatchPlace(request):
return render(request, "catalog/match_location.html")
# def PlaceDetail(request, placeId):
# if request.method == "GET":
# placeName = ""
# if placeId == 1:
# placeName = "Grainger Library"
# elif placeId == 2:
# placeName = "UGL"
# elif placeId == 3:
# placeName = "Main Library"
# elif placeId == 4:
# placeName = "ECEB"
# elif placeId == 5:
# placeName = "Siebel Center"
#
# with connection.cursor() as cursor:
# cursor.execute("SELECT crowdness FROM catalog_place WHERE name = %s",[placeName])
# crowdness = cursor.fetchone()
# if crowdness:
# crowdness = crowdness[0]
# else:
# crowdness = [0]
# cursor.execute("SELECT COUNT(*) FROM catalog_location INNER JOIN catalog_place on catalog_location.placename = catalog_place.name WHERE catalog_place.name = %s GROUP BY(catalog_location.placename)",[placeName])
# row = cursor.fetchone()
# if row:
# matched_user = row[0]
# else:
# matched_user = 0
#
#
# return render(request, 'catalog/place.html', context={
# 'place_id':placeId,
# 'place_name':placeName,
# 'place_crowdedness': crowdness[0],
# 'matched_user_number': matched_user})
#
# def ReportCrowd(request, placeId):
# if request.method == "POST":
# place = PlaceForm(request.POST)
# crowdness = place.data['crowdness']
# crowdness = min(max(float(crowdness), 0.0), 1.0)
#
# placeName = ""
# if placeId == 1:
# placeName = "Grainger Library"
# elif placeId == 2:
# placeName = "UGL"
# elif placeId == 3:
# placeName = "Main Library"
# elif placeId == 4:
# placeName = "ECEB"
# elif placeId == 5:
# placeName = "Siebel Center"
# with connection.cursor() as cursor:
# try:
# cursor.execute("INSERT INTO catalog_usercrowdness(user, place, crowdness) VALUE (%s, %s, %s)",[str(request.user.netid), placeName, crowdness])
# except:
# cursor.execute("UPDATE catalog_usercrowdness SET user=%s, place=%s, crowdness=%s",[str(request.user.netid), placeName, crowdness])
#
# return render(request, 'catalog/place.html', context={
# 'place_id':placeId,
# 'place_name':placeName,
# # 'place_crowdedness':crowdness,
# 'place_distance':1.0})
| [
"django.shortcuts.render",
"populartimes.get",
"populartimes.get_id",
"mycrawl.popCrawl",
"math.sqrt",
"math.cos",
"django.shortcuts.redirect",
"django.db.connection.cursor",
"datetime.datetime.today",
"math.sin"
] | [((336, 365), 'django.shortcuts.render', 'render', (['request', '"""index.html"""'], {}), "(request, 'index.html')\n", (342, 365), False, 'from django.shortcuts import render, redirect\n'), ((427, 475), 'django.shortcuts.render', 'render', (['request', '"""catalog/user_info_create.html"""'], {}), "(request, 'catalog/user_info_create.html')\n", (433, 475), False, 'from django.shortcuts import render, redirect\n'), ((1553, 1601), 'django.shortcuts.render', 'render', (['request', '"""catalog/user_info_update.html"""'], {}), "(request, 'catalog/user_info_update.html')\n", (1559, 1601), False, 'from django.shortcuts import render, redirect\n'), ((2901, 2924), 'django.shortcuts.redirect', 'redirect', (['"""user-detail"""'], {}), "('user-detail')\n", (2909, 2924), False, 'from django.shortcuts import render, redirect\n'), ((4411, 4460), 'django.shortcuts.render', 'render', (['request', '"""catalog/user_info_deleted.html"""'], {}), "(request, 'catalog/user_info_deleted.html')\n", (4417, 4460), False, 'from django.shortcuts import render, redirect\n'), ((6361, 6437), 'django.shortcuts.render', 'render', (['request', '"""catalog/user_match.html"""'], {'context': "{'userList': final_list}"}), "(request, 'catalog/user_match.html', context={'userList': final_list})\n", (6367, 6437), False, 'from django.shortcuts import render, redirect\n'), ((6476, 6494), 'django.shortcuts.redirect', 'redirect', (['"""logout"""'], {}), "('logout')\n", (6484, 6494), False, 'from django.shortcuts import render, redirect\n'), ((6528, 6551), 'django.shortcuts.redirect', 'redirect', (['"""user-detail"""'], {}), "('user-detail')\n", (6536, 6551), False, 'from django.shortcuts import render, redirect\n'), ((6596, 6606), 'mycrawl.popCrawl', 'popCrawl', ([], {}), '()\n', (6604, 6606), False, 'from mycrawl import popCrawl\n'), ((6646, 6669), 'django.shortcuts.redirect', 'redirect', (['"""user-detail"""'], {}), "('user-detail')\n", (6654, 6669), False, 'from django.shortcuts import render, redirect\n'), ((6723, 6847), 'populartimes.get', 'populartimes.get', (['"""<KEY>"""', "['library']", '(40.116193536286815, -88.2435300726317)', '(40.08857770924527, -88.2047958483285)'], {}), "('<KEY>', ['library'], (40.116193536286815, -\n 88.2435300726317), (40.08857770924527, -88.2047958483285))\n", (6739, 6847), False, 'import populartimes\n'), ((6862, 6982), 'populartimes.get', 'populartimes.get', (['"""<KEY>"""', "['cafe']", '(40.116193536286815, -88.2435300726317)', '(40.08857770924527, -88.2047958483285)'], {}), "('<KEY>', ['cafe'], (40.116193536286815, -88.2435300726317),\n (40.08857770924527, -88.2047958483285))\n", (6878, 6982), False, 'import populartimes\n'), ((8745, 8768), 'django.shortcuts.redirect', 'redirect', (['"""user-detail"""'], {}), "('user-detail')\n", (8753, 8768), False, 'from django.shortcuts import render, redirect\n'), ((8913, 8936), 'django.shortcuts.redirect', 'redirect', (['"""user-insert"""'], {}), "('user-insert')\n", (8921, 8936), False, 'from django.shortcuts import render, redirect\n'), ((10922, 10964), 'django.shortcuts.render', 'render', (['request', '"""catalog/match_user.html"""'], {}), "(request, 'catalog/match_user.html')\n", (10928, 10964), False, 'from django.shortcuts import render, redirect\n'), ((11002, 11048), 'django.shortcuts.render', 'render', (['request', '"""catalog/match_location.html"""'], {}), "(request, 'catalog/match_location.html')\n", (11008, 11048), False, 'from django.shortcuts import render, redirect\n'), ((1492, 1515), 'django.shortcuts.redirect', 'redirect', (['"""user-detail"""'], {}), "('user-detail')\n", (1500, 1515), False, 'from django.shortcuts import render, redirect\n'), ((4075, 4094), 'django.db.connection.cursor', 'connection.cursor', ([], {}), '()\n', (4092, 4094), False, 'from django.db import connection\n'), ((7483, 7502), 'django.db.connection.cursor', 'connection.cursor', ([], {}), '()\n', (7500, 7502), False, 'from django.db import connection\n'), ((10752, 10842), 'django.shortcuts.render', 'render', (['request', '"""catalog/match_location.html"""'], {'context': "{'allPlaces': sortedPlaceList}"}), "(request, 'catalog/match_location.html', context={'allPlaces':\n sortedPlaceList})\n", (10758, 10842), False, 'from django.shortcuts import render, redirect\n'), ((699, 718), 'django.db.connection.cursor', 'connection.cursor', ([], {}), '()\n', (716, 718), False, 'from django.db import connection\n'), ((1719, 1738), 'django.db.connection.cursor', 'connection.cursor', ([], {}), '()\n', (1736, 1738), False, 'from django.db import connection\n'), ((2997, 3016), 'django.db.connection.cursor', 'connection.cursor', ([], {}), '()\n', (3014, 3016), False, 'from django.db import connection\n'), ((3761, 3892), 'django.shortcuts.render', 'render', (['request', '"""catalog/user_info.html"""'], {'context': "{'Name': row[0][0], 'netid': row[0][1], 'phone': row[0][2], 'course': c_str}"}), "(request, 'catalog/user_info.html', context={'Name': row[0][0],\n 'netid': row[0][1], 'phone': row[0][2], 'course': c_str})\n", (3767, 3892), False, 'from django.shortcuts import render, redirect\n'), ((4687, 4705), 'math.sin', 'math.sin', (['(dlat / 2)'], {}), '(dlat / 2)\n', (4695, 4705), False, 'import math\n'), ((4789, 4801), 'math.sqrt', 'math.sqrt', (['a'], {}), '(a)\n', (4798, 4801), False, 'import math\n'), ((4803, 4819), 'math.sqrt', 'math.sqrt', (['(1 - a)'], {}), '(1 - a)\n', (4812, 4819), False, 'import math\n'), ((5110, 5129), 'django.db.connection.cursor', 'connection.cursor', ([], {}), '()\n', (5127, 5129), False, 'from django.db import connection\n'), ((7600, 7641), 'populartimes.get_id', 'populartimes.get_id', (['"""<KEY>"""', "item1['id']"], {}), "('<KEY>', item1['id'])\n", (7619, 7641), False, 'import populartimes\n'), ((7660, 7701), 'populartimes.get_id', 'populartimes.get_id', (['"""<KEY>"""', "item2['id']"], {}), "('<KEY>', item2['id'])\n", (7679, 7701), False, 'import populartimes\n'), ((9412, 9431), 'django.db.connection.cursor', 'connection.cursor', ([], {}), '()\n', (9429, 9431), False, 'from django.db import connection\n'), ((1162, 1213), 'django.shortcuts.render', 'render', (['request', '"""catalog/user_info_duplicate.html"""'], {}), "(request, 'catalog/user_info_duplicate.html')\n", (1168, 1213), False, 'from django.shortcuts import render, redirect\n'), ((3291, 3342), 'django.shortcuts.render', 'render', (['request', '"""catalog/user_info_not_found.html"""'], {}), "(request, 'catalog/user_info_not_found.html')\n", (3297, 3342), False, 'from django.shortcuts import render, redirect\n'), ((4710, 4724), 'math.cos', 'math.cos', (['lat1'], {}), '(lat1)\n', (4718, 4724), False, 'import math\n'), ((4727, 4741), 'math.cos', 'math.cos', (['lat2'], {}), '(lat2)\n', (4735, 4741), False, 'import math\n'), ((4745, 4763), 'math.sin', 'math.sin', (['(dlon / 2)'], {}), '(dlon / 2)\n', (4753, 4763), False, 'import math\n'), ((7436, 7461), 'datetime.datetime.today', 'datetime.datetime.today', ([], {}), '()\n', (7459, 7461), False, 'import datetime\n'), ((10335, 10353), 'math.sin', 'math.sin', (['(dlat / 2)'], {}), '(dlat / 2)\n', (10343, 10353), False, 'import math\n'), ((10449, 10461), 'math.sqrt', 'math.sqrt', (['a'], {}), '(a)\n', (10458, 10461), False, 'import math\n'), ((10463, 10479), 'math.sqrt', 'math.sqrt', (['(1 - a)'], {}), '(1 - a)\n', (10472, 10479), False, 'import math\n'), ((10358, 10372), 'math.cos', 'math.cos', (['lat1'], {}), '(lat1)\n', (10366, 10372), False, 'import math\n'), ((10375, 10389), 'math.cos', 'math.cos', (['lat2'], {}), '(lat2)\n', (10383, 10389), False, 'import math\n'), ((10393, 10411), 'math.sin', 'math.sin', (['(dlon / 2)'], {}), '(dlon / 2)\n', (10401, 10411), False, 'import math\n')] |
# -*- coding: utf-8 -*-
#
# cli.py
# questioner
#
"""
A command-line client for annotating things.
"""
import re
import os
from typing import List, Set, Optional
import readchar
import blessings
SKIP_KEY = '\r'
SKIP_LINE = ''
QUIT_KEY = 'q'
QUIT_LINE = 'q'
EMAIL_REGEX = '^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,6}$'
class QuestionSkipped(Exception):
pass
class QuitCli(Exception):
pass
class Cli:
def __init__(self,
skip_key=SKIP_KEY,
skip_line=SKIP_LINE,
quit_key=QUIT_KEY,
quit_line=QUIT_LINE):
self.skip_key = skip_key
self.skip_line = skip_line
self.quit_key = quit_key
self.quit_line = quit_line
self.terminal = blessings.Terminal()
def __enter__(self):
return self
def __exit__(self, *args):
pass
def yes_or_no(self, prompt, newline=True):
v = self.input_bool(prompt)
if newline:
print()
return v
def underline(self, s):
return self.terminal.underline(str(s))
def choose_one(self, prompt, options):
print(prompt)
if len(options) < 10:
for i, option in enumerate(options):
print(' {}. {}'.format(self.underline(i), option))
ix = self.input_number_quick(0, len(options) - 1)
else:
for i, option in enumerate(options):
print(f' {i}. {option}')
ix = self.input_number(0, len(options) - 1)
print()
return options[ix]
def choose_many(self, prompt, options):
print(prompt)
vs = set([o for o in options
if self.yes_or_no(f' {o}', newline=False)])
print()
return vs
def give_an_int(self, prompt, minimum=None, maximum=None):
print(prompt)
is_digit_range = (minimum is not None
and maximum is not None
and (0 <= minimum <= maximum <= 9))
if is_digit_range:
v = self.input_number_quick(minimum, maximum)
else:
v = self.input_number(minimum, maximum)
print()
return v
def read_char(self):
c = readchar.readchar()
if c == self.skip_key:
raise QuestionSkipped()
elif c == self.quit_key:
raise QuitCli()
print(c, end='', flush=True)
return c
def read_line(self, prompt):
line = input(prompt).rstrip('\n')
if line == self.skip_line:
raise QuestionSkipped()
elif line == self.quit_line:
raise QuitCli()
def input_bool(self, query: str) -> bool:
print('{}? ({}/{})'.format(query,
self.underline('y'),
self.underline('n')),
end=' ', flush=True)
while True:
c = self.read_char()
print()
if c in ('y', 'n'):
break
print('ERROR: please press y, n, or return')
return c == 'y'
def input_number(self,
query: str,
minimum: Optional[int] = None,
maximum: Optional[int] = None) -> int:
number_query = query + '> '
while True:
r = self.read_line(number_query)
try:
v = int(r)
if ((minimum is None or minimum <= v)
and (maximum is None or maximum >= v)):
return v
else:
print('ERROR: invalid number provided')
except ValueError:
print('ERROR: please enter a number')
def input_number_quick(self,
minimum: Optional[int] = None,
maximum: Optional[int] = None) -> int:
assert minimum >= 0 and maximum <= 9
while True:
r = self.read_char()
print()
try:
v = int(r)
if ((minimum is None or minimum <= v)
and (maximum is None or maximum >= v)):
return v
else:
print('ERROR: invalid number provided')
except ValueError:
print('ERROR: please enter a number')
def input_multi_options(self, title: str, options: List[str]) -> Set[str]:
print(title)
selected = set([o for o in options if self.input_bool(' ' + o)])
return selected
def input_single_option(self, title: str, options: List[str]) -> str:
print(title)
for i, o in enumerate(options):
print(' {0}. {1}'.format(i + 1, o))
v = self.input_number('pick one', minimum=1, maximum=len(options))
return options[v - 1]
def input_email(self) -> str:
while True:
v = self.read_line('email address> ')
if re.match(EMAIL_REGEX, v, re.IGNORECASE):
return v
print('ERROR: please enter a valid email address')
def input_string(query: str, allow_empty: bool = False) -> str:
while True:
v = input(query + '> ').strip()
if allow_empty or v:
return v
print('ERROR: cannot be left empty')
def pause(message: str = 'Press any key to continue...') -> None:
readchar.readchar()
def clear_screen() -> None:
os.system('clear')
| [
"os.system",
"re.match",
"readchar.readchar",
"blessings.Terminal"
] | [((750, 770), 'blessings.Terminal', 'blessings.Terminal', ([], {}), '()\n', (768, 770), False, 'import blessings\n'), ((2235, 2254), 'readchar.readchar', 'readchar.readchar', ([], {}), '()\n', (2252, 2254), False, 'import readchar\n'), ((5433, 5452), 'readchar.readchar', 'readchar.readchar', ([], {}), '()\n', (5450, 5452), False, 'import readchar\n'), ((5494, 5512), 'os.system', 'os.system', (['"""clear"""'], {}), "('clear')\n", (5503, 5512), False, 'import os\n'), ((4983, 5022), 're.match', 're.match', (['EMAIL_REGEX', 'v', 're.IGNORECASE'], {}), '(EMAIL_REGEX, v, re.IGNORECASE)\n', (4991, 5022), False, 'import re\n')] |
"""
Hu moments calculation
"""
# Import required packages:
import cv2
from matplotlib import pyplot as plt
def centroid(moments):
"""Returns centroid based on moments"""
x_centroid = round(moments['m10'] / moments['m00'])
y_centroid = round(moments['m01'] / moments['m00'])
return x_centroid, y_centroid
def draw_contour_outline(img, cnts, color, thickness=1):
"""Draws contours outlines of each contour"""
for cnt in cnts:
cv2.drawContours(img, [cnt], 0, color, thickness)
def show_img_with_matplotlib(color_img, title, pos):
"""Shows an image using matplotlib capabilities"""
# Convert BGR image to RGB
img_RGB = color_img[:, :, ::-1]
ax = plt.subplot(1, 1, pos)
plt.imshow(img_RGB)
plt.title(title)
plt.axis('off')
# Create the dimensions of the figure and set title:
fig = plt.figure(figsize=(12, 5))
plt.suptitle("Hu moments", fontsize=14, fontweight='bold')
fig.patch.set_facecolor('silver')
# Load the image and convert it to grayscale:
image = cv2.imread("shape_features.png")
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Apply cv2.threshold() to get a binary image:
ret, thresh = cv2.threshold(gray_image, 70, 255, cv2.THRESH_BINARY)
# Compute moments:
M = cv2.moments(thresh, True)
print("moments: '{}'".format(M))
# Calculate the centroid of the contour based on moments:
x, y = centroid(M)
# Compute Hu moments:
HuM = cv2.HuMoments(M)
print("Hu moments: '{}'".format(HuM))
# Find contours in the thresholded image:
# Note: cv2.findContours() has been changed to return only the contours and the hierarchy
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
# Compute moments:
M2 = cv2.moments(contours[0])
print("moments: '{}'".format(M2))
# Calculate the centroid of the contour based on moments:
x2, y2 = centroid(M2)
# Compute Hu moments:
HuM2 = cv2.HuMoments(M2)
print("Hu moments: '{}'".format(HuM2))
# Draw the outline of the detected contour:
draw_contour_outline(image, contours, (255, 0, 0), 10)
# Draw the centroids (it should be the same point):
# (make it big to see the difference)
cv2.circle(image, (x, y), 25, (255, 0, 0), -1)
cv2.circle(image, (x2, y2), 25, (0, 255, 0), -1)
print("('x','y'): ('{}','{}')".format(x, y))
print("('x2','y2'): ('{}','{}')".format(x2, y2))
# Plot the images:
show_img_with_matplotlib(image, "detected contour and centroid", 1)
# Show the Figure:
plt.show()
| [
"matplotlib.pyplot.imshow",
"cv2.drawContours",
"cv2.threshold",
"cv2.HuMoments",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.figure",
"cv2.circle",
"cv2.cvtColor",
"cv2.moments",
"cv2.findContours",
"matplotlib.pyplot.title",
"cv2.imread",
"matplotlib.pyplot.... | [((850, 877), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(12, 5)'}), '(figsize=(12, 5))\n', (860, 877), True, 'from matplotlib import pyplot as plt\n'), ((878, 936), 'matplotlib.pyplot.suptitle', 'plt.suptitle', (['"""Hu moments"""'], {'fontsize': '(14)', 'fontweight': '"""bold"""'}), "('Hu moments', fontsize=14, fontweight='bold')\n", (890, 936), True, 'from matplotlib import pyplot as plt\n'), ((1026, 1058), 'cv2.imread', 'cv2.imread', (['"""shape_features.png"""'], {}), "('shape_features.png')\n", (1036, 1058), False, 'import cv2\n'), ((1072, 1111), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2GRAY'], {}), '(image, cv2.COLOR_BGR2GRAY)\n', (1084, 1111), False, 'import cv2\n'), ((1174, 1227), 'cv2.threshold', 'cv2.threshold', (['gray_image', '(70)', '(255)', 'cv2.THRESH_BINARY'], {}), '(gray_image, 70, 255, cv2.THRESH_BINARY)\n', (1187, 1227), False, 'import cv2\n'), ((1252, 1277), 'cv2.moments', 'cv2.moments', (['thresh', '(True)'], {}), '(thresh, True)\n', (1263, 1277), False, 'import cv2\n'), ((1418, 1434), 'cv2.HuMoments', 'cv2.HuMoments', (['M'], {}), '(M)\n', (1431, 1434), False, 'import cv2\n'), ((1628, 1694), 'cv2.findContours', 'cv2.findContours', (['thresh', 'cv2.RETR_EXTERNAL', 'cv2.CHAIN_APPROX_NONE'], {}), '(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)\n', (1644, 1694), False, 'import cv2\n'), ((1720, 1744), 'cv2.moments', 'cv2.moments', (['contours[0]'], {}), '(contours[0])\n', (1731, 1744), False, 'import cv2\n'), ((1890, 1907), 'cv2.HuMoments', 'cv2.HuMoments', (['M2'], {}), '(M2)\n', (1903, 1907), False, 'import cv2\n'), ((2138, 2184), 'cv2.circle', 'cv2.circle', (['image', '(x, y)', '(25)', '(255, 0, 0)', '(-1)'], {}), '(image, (x, y), 25, (255, 0, 0), -1)\n', (2148, 2184), False, 'import cv2\n'), ((2185, 2233), 'cv2.circle', 'cv2.circle', (['image', '(x2, y2)', '(25)', '(0, 255, 0)', '(-1)'], {}), '(image, (x2, y2), 25, (0, 255, 0), -1)\n', (2195, 2233), False, 'import cv2\n'), ((2436, 2446), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2444, 2446), True, 'from matplotlib import pyplot as plt\n'), ((701, 723), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(1)', 'pos'], {}), '(1, 1, pos)\n', (712, 723), True, 'from matplotlib import pyplot as plt\n'), ((728, 747), 'matplotlib.pyplot.imshow', 'plt.imshow', (['img_RGB'], {}), '(img_RGB)\n', (738, 747), True, 'from matplotlib import pyplot as plt\n'), ((752, 768), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (761, 768), True, 'from matplotlib import pyplot as plt\n'), ((773, 788), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (781, 788), True, 'from matplotlib import pyplot as plt\n'), ((463, 512), 'cv2.drawContours', 'cv2.drawContours', (['img', '[cnt]', '(0)', 'color', 'thickness'], {}), '(img, [cnt], 0, color, thickness)\n', (479, 512), False, 'import cv2\n')] |
## 1. Interfering with the Built-in Functions ##
a_list = [1, 8, 10, 9, 7]
print(max(a_list))
def max(a_list):
return "No max value returned"
max_val_test_0 = max(a_list)
print(max_val_test_0)
del max
## 3. Default Arguments ##
# INITIAL CODE
def open_dataset(file_name):
opened_file = open(file_name)
from csv import reader
read_file = reader(opened_file)
data = list(read_file)
return data
# SOLUTION CODE
def open_dataset(file_name='AppleStore.csv'):
opened_file = open(file_name)
from csv import reader
read_file = reader(opened_file)
data = list(read_file)
return data
apps_data = open_dataset()
## 4. The Official Python Documentation ##
one_decimal = round(3.43, ndigits=1)
two_decimals = round(0.23321, 2) # using only positional arguments
five_decimals = round(921.2225227, 5)
## 5. Multiple Return Statements ##
# INITIAL CODE
def open_dataset(file_name='AppleStore.csv'):
opened_file = open(file_name)
from csv import reader
read_file = reader(opened_file)
data = list(read_file)
return data
# SOLUTION CODE
def open_dataset(file_name='AppleStore.csv', header=True):
opened_file = open(file_name)
from csv import reader
read_file = reader(opened_file)
data = list(read_file)
if header:
return data[1:]
else:
return data
apps_data = open_dataset()
## 6. Returning Multiple Variables ##
# INITIAL CODE
def open_dataset(file_name='AppleStore.csv', header=True):
opened_file = open(file_name)
from csv import reader
read_file = reader(opened_file)
data = list(read_file)
if header:
return data[1:]
else:
return data
# SOLUTION CODE
def open_dataset(file_name='AppleStore.csv', header=True):
opened_file = open(file_name)
from csv import reader
read_file = reader(opened_file)
data = list(read_file)
if header:
return data[1:], data[0]
else:
return data
all_data = open_dataset()
header = all_data[1]
apps_data = all_data[0]
## 7. More About Tuples ##
def open_dataset(file_name='AppleStore.csv', header=True):
opened_file = open(file_name)
from csv import reader
read_file = reader(opened_file)
data = list(read_file)
if header:
return data[1:], data[0]
else:
return data
apps_data, header = open_dataset() | [
"csv.reader"
] | [((363, 382), 'csv.reader', 'reader', (['opened_file'], {}), '(opened_file)\n', (369, 382), False, 'from csv import reader\n'), ((575, 594), 'csv.reader', 'reader', (['opened_file'], {}), '(opened_file)\n', (581, 594), False, 'from csv import reader\n'), ((1034, 1053), 'csv.reader', 'reader', (['opened_file'], {}), '(opened_file)\n', (1040, 1053), False, 'from csv import reader\n'), ((1262, 1281), 'csv.reader', 'reader', (['opened_file'], {}), '(opened_file)\n', (1268, 1281), False, 'from csv import reader\n'), ((1614, 1633), 'csv.reader', 'reader', (['opened_file'], {}), '(opened_file)\n', (1620, 1633), False, 'from csv import reader\n'), ((1895, 1914), 'csv.reader', 'reader', (['opened_file'], {}), '(opened_file)\n', (1901, 1914), False, 'from csv import reader\n'), ((2274, 2293), 'csv.reader', 'reader', (['opened_file'], {}), '(opened_file)\n', (2280, 2293), False, 'from csv import reader\n')] |
#import sys
#!{sys.executable} -m pip install pyathena
from pyathena import connect
import pandas as pd
conn = connect(s3_staging_dir='s3://aws-athena-query-results-459817416023-us-east-1/', region_name='us-east-1')
df = pd.read_sql('SELECT * FROM "ticketdata"."nfl_stadium_data" order by stadium limit 10;', conn)
df | [
"pandas.read_sql",
"pyathena.connect"
] | [((113, 227), 'pyathena.connect', 'connect', ([], {'s3_staging_dir': '"""s3://aws-athena-query-results-459817416023-us-east-1/"""', 'region_name': '"""us-east-1"""'}), "(s3_staging_dir=\n 's3://aws-athena-query-results-459817416023-us-east-1/', region_name=\n 'us-east-1')\n", (120, 227), False, 'from pyathena import connect\n'), ((223, 325), 'pandas.read_sql', 'pd.read_sql', (['"""SELECT * FROM "ticketdata"."nfl_stadium_data" order by stadium limit 10;"""', 'conn'], {}), '(\n \'SELECT * FROM "ticketdata"."nfl_stadium_data" order by stadium limit 10;\',\n conn)\n', (234, 325), True, 'import pandas as pd\n')] |
import requests
import json
import api_informations as api_info # this is used to not expose the api key
def json_print(obj):
text = json.dumps(obj, sort_keys=True, indent=4)
print(text)
parameters = {
"api_key" : api_info.api_key,
"language" : "en-US",
}
response = requests.get("https://api.themoviedb.org/3/discover/movie", params=parameters)
json_print(response.json())
| [
"json.dumps",
"requests.get"
] | [((286, 364), 'requests.get', 'requests.get', (['"""https://api.themoviedb.org/3/discover/movie"""'], {'params': 'parameters'}), "('https://api.themoviedb.org/3/discover/movie', params=parameters)\n", (298, 364), False, 'import requests\n'), ((138, 179), 'json.dumps', 'json.dumps', (['obj'], {'sort_keys': '(True)', 'indent': '(4)'}), '(obj, sort_keys=True, indent=4)\n', (148, 179), False, 'import json\n')] |
import requests
import time
i = 0
while True:
response = requests.get(
"http://localhost:5000/send?idNode=ESP")
print(i)
i = i+1
print(response)
time.sleep(60)
| [
"time.sleep",
"requests.get"
] | [((62, 115), 'requests.get', 'requests.get', (['"""http://localhost:5000/send?idNode=ESP"""'], {}), "('http://localhost:5000/send?idNode=ESP')\n", (74, 115), False, 'import requests\n'), ((174, 188), 'time.sleep', 'time.sleep', (['(60)'], {}), '(60)\n', (184, 188), False, 'import time\n')] |
#
# 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.
#
# Copyright (c) 2018 by Delphix. All rights reserved.
#
# Author : <NAME>
# Date : April 2018
import logging
import time
import pytz
from tqdm import tqdm
from dxm.lib.DxLogging import print_error
from dxm.lib.DxLogging import print_message
from dxm.lib.DxTools.DxTools import paginator
from dxm.lib.masking_api.api.execution_api import ExecutionApi
from dxm.lib.masking_api.api.execution_component_api import ExecutionComponentApi
from dxm.lib.masking_api.rest import ApiException
from dxm.lib.masking_api.genericmodel import GenericModel
from dateutil.parser import parse
class DxExecutionComponent(object):
swagger_types = {
'execution_component_id': 'int',
'component_name': 'str',
'execution_id': 'int',
'status': 'str',
'rows_masked': 'int',
'rows_total': 'int',
'start_time': 'datetime',
'end_time': 'datetime'
}
swagger_map = {
'execution_component_id': 'executionComponentId',
'component_name': 'componentName',
'execution_id': 'executionId',
'status': 'status',
'rows_masked': 'rowsMasked',
'rows_total': 'rowsTotal',
'start_time': 'startTime',
'end_time': 'endTime'
}
def __init__(self):
self.__obj = GenericModel({ x:None for x in self.swagger_map.values()}, self.swagger_types, self.swagger_map)
def from_exec(self, exe):
self.__obj = exe
self.__obj.swagger_types = self.swagger_types
self.__obj.swagger_map = self.swagger_map
@property
def obj(self):
if self.__obj is not None:
return self.__obj
else:
return None
@property
def execution_id(self):
if self.obj is not None and hasattr(self.obj, 'execution_id'):
return self.obj.execution_id
else:
return None
@property
def execution_component_id(self):
if self.obj is not None and hasattr(self.obj, 'execution_component_id'):
return self.obj.execution_component_id
else:
return None
@property
def component_name(self):
if self.obj is not None and hasattr(self.obj, 'component_name'):
return self.obj.component_name
else:
return None
@property
def status(self):
if self.obj is not None and hasattr(self.obj, 'status'):
return self.obj.status
else:
return None
@property
def rows_masked(self):
if self.obj is not None and hasattr(self.obj, 'rows_masked'):
return self.obj.rows_masked
else:
return None
@property
def rows_total(self):
if self.obj is not None and hasattr(self.obj, 'rows_total'):
return self.obj.rows_total
else:
return None
@property
def start_time(self):
if self.obj is not None and hasattr(self.obj, 'start_time'):
try:
if self.obj.start_time is None:
return None
return parse(self.obj.start_time)
except ValueError:
raise ApiException(
status=0,
reason=(
"Failed to parse `{0}` as datetime object"
.format(self.obj.start_time)
)
)
else:
return None
@property
def end_time(self):
if self.obj is not None and hasattr(self.obj, 'end_time'):
try:
if self.obj.end_time is None:
return None
return parse(self.obj.end_time)
except ValueError:
raise ApiException(
status=0,
reason=(
"Failed to parse `{0}` as datetime object"
.format(self.obj.end_time)
)
)
else:
return None | [
"dateutil.parser.parse"
] | [((3623, 3649), 'dateutil.parser.parse', 'parse', (['self.obj.start_time'], {}), '(self.obj.start_time)\n', (3628, 3649), False, 'from dateutil.parser import parse\n'), ((4202, 4226), 'dateutil.parser.parse', 'parse', (['self.obj.end_time'], {}), '(self.obj.end_time)\n', (4207, 4226), False, 'from dateutil.parser import parse\n')] |
import mosspy
userid = 223762299
m = mosspy.Moss(userid, "javascript")
# Submission Files
m.addFile("files/d3.js")
m.addFilesByWildcard("files/map.js")
url = m.send() # Submission Report URL
print ("Report Url: " + url)
# Save report file
m.saveWebPage(url, "report/report.html")
# Download whole report locally including code diff links
mosspy.download_report(url, "report/src/", connections=8)
| [
"mosspy.Moss",
"mosspy.download_report"
] | [((39, 72), 'mosspy.Moss', 'mosspy.Moss', (['userid', '"""javascript"""'], {}), "(userid, 'javascript')\n", (50, 72), False, 'import mosspy\n'), ((345, 402), 'mosspy.download_report', 'mosspy.download_report', (['url', '"""report/src/"""'], {'connections': '(8)'}), "(url, 'report/src/', connections=8)\n", (367, 402), False, 'import mosspy\n')] |
import imp
ID = "newload"
permission = 3
def execute(self, name, params, channel, userdata, rank):
files = self.__ListDir__("commands")
currentlyLoaded = [self.commands[cmd][1] for cmd in self.commands]
for item in currentlyLoaded:
filename = item.partition("/")[2]
files.remove(filename)
if len(files) == 0:
self.sendMessage(channel, "No new commands found.")
else:
if len(files) == 1:
self.sendMessage(channel, "1 new command found.")
else:
self.sendMessage(channel, "{0} new commands found.".format(len(files)))
for filename in files:
path = "commands/"+filename
module = imp.load_source("RenolIRC_"+filename[0:-3], path)
cmd = module.ID
self.commands[cmd] = (module, path)
try:
if not callable(module.__initialize__):
module.__initialize__ = False
self.__CMDHandler_log__.debug("File {0} does not use an initialize function".format(filename))
except AttributeError:
module.__initialize__ = False
self.__CMDHandler_log__.debug("File {0} does not use an initialize function".format(filename))
if module.__initialize__ != False:
module.__initialize__(self, True)
self.sendMessage(channel, "{0} has been loaded.".format(path))
self.__CMDHandler_log__.info("File {0} has been newly loaded.".format(filename))
def __initialize__(self, Startup):
entry = self.helper.newHelp(ID)
entry.addDescription("The 'newload' command will load any newly added plugins that have not been loaded yet without reloading other plugins.")
entry.rank = permission
self.helper.registerHelp(entry, overwrite = True) | [
"imp.load_source"
] | [((712, 763), 'imp.load_source', 'imp.load_source', (["('RenolIRC_' + filename[0:-3])", 'path'], {}), "('RenolIRC_' + filename[0:-3], path)\n", (727, 763), False, 'import imp\n')] |
# -*- coding utf-8 -*-#
# ------------------------------------------------------------------
# Name: middlewire
# Author: liangbaikai
# Date: 2020/12/28
# Desc: there is a python file description
# ------------------------------------------------------------------
from copy import copy
from functools import wraps
from typing import Union, Callable
class Middleware:
def __init__(self):
# request middleware
self.request_middleware = []
# response middleware
self.response_middleware = []
def request(self, order_or_func: Union[int, Callable]):
def outWrap(func):
"""
Define a Decorate to be called before a request.
eg: @middleware.request
"""
middleware = func
@wraps(func)
def register_middleware(*args, **kwargs):
self.request_middleware.append((order_or_func, middleware))
self.request_middleware = sorted(self.request_middleware, key=lambda key: key[0])
return middleware
return register_middleware()
if callable(order_or_func):
cp_order = copy(order_or_func)
order_or_func = 0
return outWrap(cp_order)
return outWrap
def response(self, order_or_func: Union[int, Callable]):
def outWrap(func):
"""
Define a Decorate to be called before a request.
eg: @middleware.request
"""
middleware = func
@wraps(middleware)
def register_middleware(*args, **kwargs):
self.response_middleware.append((order_or_func, middleware))
self.response_middleware = sorted(self.response_middleware, key=lambda key: key[0], reverse=True)
return middleware
return register_middleware()
if callable(order_or_func):
cp_order = copy(order_or_func)
order_or_func = 0
return outWrap(cp_order)
return outWrap
def __add__(self, other):
new_middleware = Middleware()
# asc
new_middleware.request_middleware.extend(self.request_middleware)
new_middleware.request_middleware.extend(other.request_middleware)
new_middleware.request_middleware = sorted(new_middleware.request_middleware, key=lambda key: key[0])
# desc
new_middleware.response_middleware.extend(other.response_middleware)
new_middleware.response_middleware.extend(self.response_middleware)
new_middleware.response_middleware = sorted(new_middleware.response_middleware,
key=lambda key: key[0],
reverse=True)
return new_middleware
| [
"copy.copy",
"functools.wraps"
] | [((807, 818), 'functools.wraps', 'wraps', (['func'], {}), '(func)\n', (812, 818), False, 'from functools import wraps\n'), ((1183, 1202), 'copy.copy', 'copy', (['order_or_func'], {}), '(order_or_func)\n', (1187, 1202), False, 'from copy import copy\n'), ((1555, 1572), 'functools.wraps', 'wraps', (['middleware'], {}), '(middleware)\n', (1560, 1572), False, 'from functools import wraps\n'), ((1954, 1973), 'copy.copy', 'copy', (['order_or_func'], {}), '(order_or_func)\n', (1958, 1973), False, 'from copy import copy\n')] |
import os
import unittest
this_dir = os.path.dirname(os.path.realpath(__file__))
class TestPageXML(unittest.TestCase):
def run_dataset_viewer(self, add_args):
from calamari_ocr.scripts.dataset_viewer import main
main(add_args + ["--no_plot"])
def test_cut_modes(self):
images = os.path.join(this_dir, "data", "avicanon_pagexml", "*.nrm.png")
self.run_dataset_viewer(["--gen", "PageXML", "--gen.images", images, "--gen.cut_mode", "BOX"])
self.run_dataset_viewer(["--gen", "PageXML", "--gen.images", images, "--gen.cut_mode", "MBR"])
| [
"os.path.realpath",
"calamari_ocr.scripts.dataset_viewer.main",
"os.path.join"
] | [((54, 80), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (70, 80), False, 'import os\n'), ((236, 266), 'calamari_ocr.scripts.dataset_viewer.main', 'main', (["(add_args + ['--no_plot'])"], {}), "(add_args + ['--no_plot'])\n", (240, 266), False, 'from calamari_ocr.scripts.dataset_viewer import main\n'), ((315, 378), 'os.path.join', 'os.path.join', (['this_dir', '"""data"""', '"""avicanon_pagexml"""', '"""*.nrm.png"""'], {}), "(this_dir, 'data', 'avicanon_pagexml', '*.nrm.png')\n", (327, 378), False, 'import os\n')] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# preproc_BrainSpan_link.py
# made by <NAME>
# 2020-04-20 16:21:05
#########################
import sys
import os
SVRNAME = os.uname()[1]
if "MBI" in SVRNAME.upper():
sys_path = "/Users/pcaso/bin/python_lib"
elif SVRNAME == "T7":
sys_path = "/ms1/bin/python_lib"
else:
sys_path = "/home/mk446/bin/python_lib"
sys.path.append(sys_path)
import time
import csv
sys.path.append("..")
def load_probe_file(genemap, probe_file, k1, tidx):
with open(probe_file, newline='') as csvfile:
for row in csv.reader(csvfile, delimiter=',', quotechar='"'):
ensembl_gene_id = row[2]
if ensembl_gene_id != "ensembl_gene_id":
gene_symbol = row[3]
try:
genemap[ensembl_gene_id][k1] = row[tidx]
except KeyError:
genemap[ensembl_gene_id] = {}
genemap[ensembl_gene_id][k1] = row[tidx]
return genemap
def preproc_BrainSpan_link(out, ma_probe_file, rnaseq_probe_file):
genemap = {}
genemap = load_probe_file(genemap, ma_probe_file, "ma", 3)
genemap = load_probe_file(genemap, rnaseq_probe_file, "rs", 2)
f = open(out, 'w')
cont = ['#ensgid', 'brainspan_microarray', 'brainspan_rnaseq']
f.write('\t'.join(cont) + '\n')
for ensgid in genemap.keys():
try:
ma = genemap[ensgid]['ma']
except KeyError:
ma = ""
try:
rs = genemap[ensgid]['rs']
except KeyError:
rs = ""
cont = [ensgid, ma, rs]
f.write('\t'.join(cont) + '\n')
f.close()
time.sleep(3)
proc_util.run_cmd('gz ' + out, True)
if __name__ == "__main__":
import proc_util
import file_util
import preproc_util
path = preproc_util.DATASOURCEPATH + "/EXPRESSION/BRAINSPAN/"
ma_probe_file = path + "Developmental_Transcriptome_Dataset/Exon_microarray_summarized_to_genes_gene_array_matrix/rows_metadata.csv"
rnaseq_probe_file = path + "Developmental_Transcriptome_Dataset/RNA-Seq_Gencode_v10_summarized_to_genes_genes_matrix/rows_metadata.csv"
out = path + "BRAINSPAN_link.tsv"
preproc_BrainSpan_link(out, ma_probe_file, rnaseq_probe_file)
| [
"proc_util.run_cmd",
"time.sleep",
"sys.path.append",
"csv.reader",
"os.uname"
] | [((367, 392), 'sys.path.append', 'sys.path.append', (['sys_path'], {}), '(sys_path)\n', (382, 392), False, 'import sys\n'), ((416, 437), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (431, 437), False, 'import sys\n'), ((170, 180), 'os.uname', 'os.uname', ([], {}), '()\n', (178, 180), False, 'import os\n'), ((1651, 1664), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (1661, 1664), False, 'import time\n'), ((1669, 1705), 'proc_util.run_cmd', 'proc_util.run_cmd', (["('gz ' + out)", '(True)'], {}), "('gz ' + out, True)\n", (1686, 1705), False, 'import proc_util\n'), ((560, 609), 'csv.reader', 'csv.reader', (['csvfile'], {'delimiter': '""","""', 'quotechar': '"""\\""""'}), '(csvfile, delimiter=\',\', quotechar=\'"\')\n', (570, 609), False, 'import csv\n')] |
# encoding: utf-8
from nose.tools import (
eq_,
set_trace,
)
from util.cdn import cdnify
class TestCDN(object):
def unchanged(self, url, cdns):
self.ceq(url, url, cdns)
def ceq(self, expect, url, cdns):
eq_(expect, cdnify(url, cdns))
def test_no_cdns(self):
url = "http://foo/"
self.unchanged(url, None)
def test_non_matching_cdn(self):
url = "http://foo.com/bar"
self.unchanged(url, {"bar.com" : "cdn.com"})
def test_matching_cdn(self):
url = "http://foo.com/bar#baz"
self.ceq("https://cdn.org/bar#baz", url,
{"foo.com" : "https://cdn.org",
"bar.com" : "http://cdn2.net/"}
)
def test_s3_bucket(self):
# Instead of the foo.com URL we accidentally used the full S3
# address for the bucket that hosts S3. cdnify() handles this
# with no problem.
url = "http://s3.amazonaws.com/foo.com/bar#baz"
self.ceq("https://cdn.org/bar#baz", url,
{"foo.com" : "https://cdn.org/"})
def test_relative_url(self):
# By default, relative URLs are untouched.
url = "/groups/"
self.unchanged(url, {"bar.com" : "cdn.com"})
# But if the CDN list has an entry for the empty string, that
# URL is used for relative URLs.
self.ceq("https://cdn.org/groups/", url,
{"" : "https://cdn.org/"})
| [
"util.cdn.cdnify"
] | [((252, 269), 'util.cdn.cdnify', 'cdnify', (['url', 'cdns'], {}), '(url, cdns)\n', (258, 269), False, 'from util.cdn import cdnify\n')] |
""" Test for act helpers """
import pytest
import act.api
def test_add_uri_fqdn() -> None: # type: ignore
""" Test for extraction of facts from uri with fqdn """
api = act.api.Act("", None, "error")
uri = "http://www.mnemonic.no/home"
facts = act.api.helpers.uri_facts(api, uri)
assert len(facts) == 4
assert api.fact("componentOf").source("fqdn", "www.mnemonic.no").destination("uri", uri) \
in facts
assert api.fact("componentOf").source("path", "/home").destination("uri", uri) in facts
assert api.fact("scheme", "http").source("uri", uri) in facts
assert api.fact("basename", "home").source("path", "/home") in facts
def test_uri_should_fail() -> None: # type: ignore
""" Test for extraction of facts from uri with ipv4 """
api = act.api.Act("", None, "error")
with pytest.raises(act.api.base.ValidationError):
act.api.helpers.uri_facts(api, "http://")
with pytest.raises(act.api.base.ValidationError):
act.api.helpers.uri_facts(api, "www.mnemonic.no")
with pytest.raises(act.api.base.ValidationError):
act.api.helpers.uri_facts(api, "127.0.0.1")
def test_add_uri_ipv4() -> None: # type: ignore
""" Test for extraction of facts from uri with ipv4 """
api = act.api.Act("", None, "error")
uri = "http://127.0.0.1:8080/home"
facts = act.api.helpers.uri_facts(api, uri)
assert len(facts) == 5
assert api.fact("componentOf").source("ipv4", "127.0.0.1").destination("uri", uri) in facts
assert api.fact("componentOf").source("path", "/home").destination("uri", uri) in facts
assert api.fact("scheme", "http").source("uri", uri) in facts
assert api.fact("basename", "home").source("path", "/home") in facts
assert api.fact("port", "8080").source("uri", uri) in facts
def test_add_uri_ipv6() -> None: # type: ignore
""" Test for extraction of facts from uri with ipv4 """
api = act.api.Act("", None, "error")
uri = "http://[2001:fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b]"
facts = act.api.helpers.uri_facts(api, uri)
assert len(facts) == 2
assert api.fact("scheme", "http").source("uri", uri) in facts
assert api.fact("componentOf").source("ipv6", "fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b").destination("uri", uri) \
in facts
def test_add_uri_ipv6_with_port_path_query() -> None: # type: ignore
""" Test for extraction of facts from uri with ipv6, path and query """
api = act.api.Act("", None, "error")
uri = "http://[2001:fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b]:8080/path?q=a"
facts = act.api.helpers.uri_facts(api, uri)
assert len(facts) == 6
assert api.fact("scheme", "http").source("uri", uri) in facts
assert api.fact("componentOf").source("ipv6", "fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b").destination("uri", uri) \
in facts
assert api.fact("port", "8080").source("uri", uri) in facts
assert api.fact("componentOf").source("path", "/path").destination("uri", uri) in facts
assert api.fact("basename", "path").source("path", "/path") in facts
assert api.fact("componentOf").source("query", "q=a").destination("uri", uri) in facts
| [
"pytest.raises"
] | [((837, 880), 'pytest.raises', 'pytest.raises', (['act.api.base.ValidationError'], {}), '(act.api.base.ValidationError)\n', (850, 880), False, 'import pytest\n'), ((942, 985), 'pytest.raises', 'pytest.raises', (['act.api.base.ValidationError'], {}), '(act.api.base.ValidationError)\n', (955, 985), False, 'import pytest\n'), ((1055, 1098), 'pytest.raises', 'pytest.raises', (['act.api.base.ValidationError'], {}), '(act.api.base.ValidationError)\n', (1068, 1098), False, 'import pytest\n')] |
import threading
class BaseEventHandler(object):
screen_lock = threading.Lock()
def __init__(self, browser, tab, directory='./'):
self.browser = browser
self.tab = tab
self.start_frame = None
self.directory = directory
def frame_started_loading(self, frameId):
if not self.start_frame:
self.start_frame = frameId
def frame_stopped_loading(self, frameId):
pass
| [
"threading.Lock"
] | [((69, 85), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (83, 85), False, 'import threading\n')] |
import numpy as np
import requests
import talib
class stock_ins:
BASE_URL = "https://paper-api.alpaca.markets"
DATA_URL = "https://data.alpaca.markets"
def __init__(self, stock_name, save_len, api_key, secret_key):
self.stock_name = stock_name
self.save_len = save_len
self.ask_data = []
self.bid_data = []
self.HEADERS = {'APCA-API-KEY-ID': api_key, 'APCA-API-SECRET-KEY': secret_key}
def __get_bid(self):
return requests.get("{}/v1/last/stocks/{}".format(self.DATA_URL, self.stock_name), headers=self.HEADERS).json()["last"]["price"]
def __get_ask(self):
return requests.get("{}/v1/last_quote/stocks/{}".format(self.DATA_URL, self.stock_name), headers=self.HEADERS).json()["last"]["askprice"]
def update(self):
# this will get new bid and ask data and resize it
bid = self.__get_bid()
ask = self.__get_ask()
if len(self.ask_data) >= self.save_len:
self.ask_data.pop(self.save_len-1)
self.bid_data.pop(self.save_len-1)
self.bid_data.insert(0, bid)
self.ask_data.insert(0, ask)
def get_indicator(self, ind, *, period_len=None, data=None):
# this will return any indicator available in talib in right format
data = self.ask_data if data is None else data
data = np.array(data, dtype="double")[::-1]
if period_len is None:
ind = getattr(talib, ind)(data)
else:
ind = getattr(talib, ind)(data, period_len)
return ind[::-1]
def order(self, data):
return requests.post("{}/v2/orders".format(self.BASE_URL), json=data, headers=self.HEADERS)
if __name__ == "__main__":
# test run, if everything is working
import config
import time
import market
stocks = ["DB", "TSLA", "MSFT"]
interval = 60 # interval time in seconds: minute data=60
save_len = 200 # length of saved prices
Key = config.key
sKey = config.sKey
stock_list = []
for stock in stocks:
stock_list.append(stock_ins(stock, save_len, Key, sKey))
while True:
if market.is_open():
start_timer = time.time()
for stock in stock_list:
stock.update() # this will update the bid and ask price
print(stock.get_indicator("EMA", period_len=2, data=[1, 2, 3, 4, 5]))
data = {
"side": "buy",
"symbol": stock.stock_name,
"type": "market",
"qty": "1",
"time_in_force": "gtc",
} # settings for order: order type etc.
# print(stock.order(data)) # this will order a stock with json=data
print(stock.ask_data[0], stock.ask_data[0], len(stock.ask_data))
sleep_time = interval - (time.time()-start_timer)
print("Waiting {:.2f}".format(sleep_time))
time.sleep(sleep_time)
| [
"numpy.array",
"market.is_open",
"time.sleep",
"time.time"
] | [((2142, 2158), 'market.is_open', 'market.is_open', ([], {}), '()\n', (2156, 2158), False, 'import market\n'), ((1350, 1380), 'numpy.array', 'np.array', (['data'], {'dtype': '"""double"""'}), "(data, dtype='double')\n", (1358, 1380), True, 'import numpy as np\n'), ((2186, 2197), 'time.time', 'time.time', ([], {}), '()\n', (2195, 2197), False, 'import time\n'), ((2985, 3007), 'time.sleep', 'time.sleep', (['sleep_time'], {}), '(sleep_time)\n', (2995, 3007), False, 'import time\n'), ((2893, 2904), 'time.time', 'time.time', ([], {}), '()\n', (2902, 2904), False, 'import time\n')] |
import json
import warnings
from pathlib import Path
import sys
from bilby.core.utils import logger
from bilby.core.result import BilbyJsonEncoder
from memestr.injection import create_injection
warnings.filterwarnings("ignore")
if len(sys.argv) > 1:
minimum_id = int(sys.argv[1])
maximum_id = int(sys.argv[2])
else:
minimum_id = 0
maximum_id = 100
for i in range(minimum_id, maximum_id):
logger.info(f'Injection ID: {i}')
params = create_injection()
Path('injection_parameter_sets').mkdir(parents=True, exist_ok=True)
with open(f'injection_parameter_sets/{str(i).zfill(3)}.json', 'w') as f:
out = dict(injections=params)
json.dump(out, f, indent=2, cls=BilbyJsonEncoder)
| [
"pathlib.Path",
"bilby.core.utils.logger.info",
"memestr.injection.create_injection",
"warnings.filterwarnings",
"json.dump"
] | [((197, 230), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (220, 230), False, 'import warnings\n'), ((413, 446), 'bilby.core.utils.logger.info', 'logger.info', (['f"""Injection ID: {i}"""'], {}), "(f'Injection ID: {i}')\n", (424, 446), False, 'from bilby.core.utils import logger\n'), ((460, 478), 'memestr.injection.create_injection', 'create_injection', ([], {}), '()\n', (476, 478), False, 'from memestr.injection import create_injection\n'), ((674, 723), 'json.dump', 'json.dump', (['out', 'f'], {'indent': '(2)', 'cls': 'BilbyJsonEncoder'}), '(out, f, indent=2, cls=BilbyJsonEncoder)\n', (683, 723), False, 'import json\n'), ((483, 515), 'pathlib.Path', 'Path', (['"""injection_parameter_sets"""'], {}), "('injection_parameter_sets')\n", (487, 515), False, 'from pathlib import Path\n')] |
"""This module contains various decorators.
There are two kinds of decorators defined in this module which consists of either two or
three nested functions. The former are decorators without and the latter with arguments.
For more information on decorators, see this `guide`_ on https://realpython.com which
provides a comprehensive overview.
.. _guide:
https://realpython.com/primer-on-python-decorators/
"""
import functools
import warnings
from typing import NamedTuple
import numpy as np
import pandas as pd
from estimagic.exceptions import get_traceback
from estimagic.parameters.process_constraints import process_constraints
from estimagic.parameters.reparametrize import reparametrize_from_internal
def numpy_interface(func=None, *, params=None, constraints=None, numpy_output=False):
"""Convert x to params.
This decorated function receives a NumPy array of parameters and converts it to a
:class:`pandas.DataFrame` which can be handled by the user's criterion function.
For convenience, the decorated function can also be called directly with a
params DataFrame. In that case, the decorator does nothing.
Args:
func (callable): The function to which the decorator is applied.
params (pandas.DataFrame): See :ref:`params`.
constraints (list of dict): Contains constraints.
numpy_output (bool): Whether pandas objects in the output should also be
converted to numpy arrays.
Returns:
callable
"""
constraints = [] if constraints is None else constraints
pc, pp = process_constraints(constraints, params)
fixed_values = pp["_internal_fixed_value"].to_numpy()
pre_replacements = pp["_pre_replacements"].to_numpy().astype(int)
post_replacements = pp["_post_replacements"].to_numpy().astype(int)
def decorator_numpy_interface(func):
@functools.wraps(func)
def wrapper_numpy_interface(x, *args, **kwargs):
if isinstance(x, pd.DataFrame):
p = x
elif isinstance(x, np.ndarray):
p = reparametrize_from_internal(
internal=x,
fixed_values=fixed_values,
pre_replacements=pre_replacements,
processed_constraints=pc,
post_replacements=post_replacements,
params=params,
return_numpy=False,
)
else:
raise ValueError(
"x must be a numpy array or DataFrame with 'value' column."
)
criterion_value = func(p, *args, **kwargs)
if isinstance(criterion_value, (pd.DataFrame, pd.Series)) and numpy_output:
criterion_value = criterion_value.to_numpy()
return criterion_value
return wrapper_numpy_interface
if callable(func):
return decorator_numpy_interface(func)
else:
return decorator_numpy_interface
def catch(
func=None,
*,
exception=Exception,
exclude=(KeyboardInterrupt, SystemExit),
onerror=None,
default=None,
warn=True,
reraise=False,
):
"""Catch and handle exceptions.
This decorator can be used with and without additional arguments.
Args:
exception (Exception or tuple): One or several exceptions that
are caught and handled. By default all Exceptions are
caught and handled.
exclude (Exception or tuple): One or several exceptionts that
are not caught. By default those are KeyboardInterrupt and
SystemExit.
onerror (None or Callable): Callable that takes an Exception
as only argument. This is called when an exception occurs.
default: Value that is returned when as the output of func when
an exception occurs. Can be one of the following:
- a constant
- "__traceback__", in this case a string with a traceback is returned.
- callable with the same signature as func.
warn (bool): If True, the exception is converted to a warning.
reraise (bool): If True, the exception is raised after handling it.
"""
def decorator_catch(func):
@functools.wraps(func)
def wrapper_catch(*args, **kwargs):
try:
res = func(*args, **kwargs)
except exclude:
raise
except exception as e:
if onerror is not None:
onerror(e)
if reraise:
raise e
tb = get_traceback()
if warn:
msg = f"The following exception was caught:\n\n{tb}"
warnings.warn(msg)
if default == "__traceback__":
res = tb
elif callable(default):
res = default(*args, **kwargs)
else:
res = default
return res
return wrapper_catch
if callable(func):
return decorator_catch(func)
else:
return decorator_catch
def unpack(func=None, symbol=None):
def decorator_unpack(func):
if symbol is None:
@functools.wraps(func)
def wrapper_unpack(arg):
return func(arg)
elif symbol == "*":
@functools.wraps(func)
def wrapper_unpack(arg):
return func(*arg)
elif symbol == "**":
@functools.wraps(func)
def wrapper_unpack(arg):
return func(**arg)
return wrapper_unpack
if callable(func):
return decorator_unpack(func)
else:
return decorator_unpack
def switch_sign(func):
"""Switch sign of all outputs of a function."""
@functools.wraps(func)
def wrapper(*args, **kwargs):
unswitched = func(*args, **kwargs)
if isinstance(unswitched, dict):
switched = {key: -val for key, val in unswitched.items()}
elif isinstance(unswitched, (tuple, list)):
switched = []
for entry in unswitched:
if isinstance(entry, dict):
switched.append({key: -val for key, val in entry.items()})
else:
switched.append(-entry)
if isinstance(unswitched, tuple):
switched = tuple(switched)
else:
switched = -unswitched
return switched
return wrapper
class AlgoInfo(NamedTuple):
primary_criterion_entry: str
name: str
parallelizes: bool
disable_cache: bool
needs_scaling: bool
is_available: bool
def mark_minimizer(
func=None,
*,
primary_criterion_entry="value",
name=None,
parallelizes=False,
disable_cache=False,
needs_scaling=False,
is_available=True,
):
"""Decorator to mark a function as internal estimagic minimizer and add information.
Args:
func (callable): The function to be decorated
primary_criterion_entry (str): One of "value", "contributions",
"root_contributions" or "dict". Default: "value". This decides
which part of the output of the user provided criterion function
is needed by the internal optimizer.
name (str): The name of the internal algorithm.
parallelizes (bool): Must be True if an algorithm evaluates the criterion,
derivative or criterion_and_derivative in parallel.
disable_cache (bool): If True, no caching for the criterion function
or its derivatives are used.
needs_scaling (bool): Must be True if the algorithm is not reasonable
independent of the scaling of the parameters.
is_available (bool): Whether the algorithm is available. This is needed for
algorithms that require optional dependencies.
"""
if name is None:
raise TypeError(
"mark_minimizer() missing 1 required keyword-only argument: 'name'"
)
elif not isinstance(name, str):
raise TypeError("name must be a string.")
valid_entries = ["value", "dict", "contributions", "root_contributions"]
if primary_criterion_entry not in valid_entries:
raise ValueError(
f"primary_criterion_entry must be one of {valid_entries} not "
f"{primary_criterion_entry}."
)
if not isinstance(parallelizes, bool):
raise TypeError("parallelizes must be a bool.")
if not isinstance(disable_cache, bool):
raise TypeError("disable_cache must be a bool.")
if not isinstance(needs_scaling, bool):
raise TypeError("needs_scaling must be a bool.")
if not isinstance(is_available, bool):
raise TypeError("is_available must be a bool.")
algo_info = AlgoInfo(
primary_criterion_entry=primary_criterion_entry,
name=name,
parallelizes=parallelizes,
disable_cache=disable_cache,
needs_scaling=needs_scaling,
is_available=is_available,
)
def decorator_mark_minimizer(func):
@functools.wraps(func)
def wrapper_mark_minimizer(*args, **kwargs):
return func(*args, **kwargs)
wrapper_mark_minimizer._algorithm_info = algo_info
return wrapper_mark_minimizer
if callable(func):
return decorator_mark_minimizer(func)
else:
return decorator_mark_minimizer
| [
"estimagic.parameters.process_constraints.process_constraints",
"estimagic.parameters.reparametrize.reparametrize_from_internal",
"functools.wraps",
"warnings.warn",
"estimagic.exceptions.get_traceback"
] | [((1579, 1619), 'estimagic.parameters.process_constraints.process_constraints', 'process_constraints', (['constraints', 'params'], {}), '(constraints, params)\n', (1598, 1619), False, 'from estimagic.parameters.process_constraints import process_constraints\n'), ((5850, 5871), 'functools.wraps', 'functools.wraps', (['func'], {}), '(func)\n', (5865, 5871), False, 'import functools\n'), ((1872, 1893), 'functools.wraps', 'functools.wraps', (['func'], {}), '(func)\n', (1887, 1893), False, 'import functools\n'), ((4259, 4280), 'functools.wraps', 'functools.wraps', (['func'], {}), '(func)\n', (4274, 4280), False, 'import functools\n'), ((9162, 9183), 'functools.wraps', 'functools.wraps', (['func'], {}), '(func)\n', (9177, 9183), False, 'import functools\n'), ((5266, 5287), 'functools.wraps', 'functools.wraps', (['func'], {}), '(func)\n', (5281, 5287), False, 'import functools\n'), ((5401, 5422), 'functools.wraps', 'functools.wraps', (['func'], {}), '(func)\n', (5416, 5422), False, 'import functools\n'), ((2081, 2288), 'estimagic.parameters.reparametrize.reparametrize_from_internal', 'reparametrize_from_internal', ([], {'internal': 'x', 'fixed_values': 'fixed_values', 'pre_replacements': 'pre_replacements', 'processed_constraints': 'pc', 'post_replacements': 'post_replacements', 'params': 'params', 'return_numpy': '(False)'}), '(internal=x, fixed_values=fixed_values,\n pre_replacements=pre_replacements, processed_constraints=pc,\n post_replacements=post_replacements, params=params, return_numpy=False)\n', (2108, 2288), False, 'from estimagic.parameters.reparametrize import reparametrize_from_internal\n'), ((4622, 4637), 'estimagic.exceptions.get_traceback', 'get_traceback', ([], {}), '()\n', (4635, 4637), False, 'from estimagic.exceptions import get_traceback\n'), ((5538, 5559), 'functools.wraps', 'functools.wraps', (['func'], {}), '(func)\n', (5553, 5559), False, 'import functools\n'), ((4757, 4775), 'warnings.warn', 'warnings.warn', (['msg'], {}), '(msg)\n', (4770, 4775), False, 'import warnings\n')] |
import pandas as pd
df = pd.DataFrame()
files = pd.read_csv('grandtlinks.csv')
try:
files['status'] = files['status'].astype(str)
header=False
except KeyError:
files['status'] = ''
header=True
for index, row in files.iterrows():
if row['status'] == 'parsed':
continue
filename = row['filename']
data = pd.read_csv(f'data/{filename}')
data = data.iloc[:-2]
fecha = data.fecha[0]
data = data.rename(columns={f'F{fecha}':'Puntaje'})
data['Cotizacion'] = data['Cotización'].str.replace(r'\.', '')
if 'GC.1' in data.columns:
data.rename(columns={'GC':'G', 'POS':'Puesto', 'GC.1':'GC'}, inplace=True)
data.drop(data.filter(regex=r'F\d+').columns, axis=1, inplace=True)
data.drop(columns=['PcG', 'PCG', 'AcG', 'PrG', 'PCT', 'CG', 'CT', 'PcG', 'AcT', 'Cotización'], axis=1, inplace=True, errors='ignore')
df = df.append(data)
files.at[index, 'status'] = 'parsed'
df.to_csv('grandtdata.csv', mode='a', header=header, index=False)
files.to_csv('grandtlinks.csv', index=False)
| [
"pandas.DataFrame",
"pandas.read_csv"
] | [((26, 40), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (38, 40), True, 'import pandas as pd\n'), ((50, 80), 'pandas.read_csv', 'pd.read_csv', (['"""grandtlinks.csv"""'], {}), "('grandtlinks.csv')\n", (61, 80), True, 'import pandas as pd\n'), ((341, 372), 'pandas.read_csv', 'pd.read_csv', (['f"""data/{filename}"""'], {}), "(f'data/{filename}')\n", (352, 372), True, 'import pandas as pd\n')] |
import os
class PathUtil:
@staticmethod
def filter_hidden_inplace(item_list):
if(not len(item_list)):
return
wanted = filter(
lambda item:
not ((item.startswith('.') and item != ".htaccess") or item.endswith('~')), item_list)
count = len(item_list)
good_item_count = len(wanted)
if(count == good_item_count):
return
item_list[:good_item_count] = wanted
for i in range(good_item_count, count):
item_list.pop()
@staticmethod
def get_path_fragment(root_dir, a_dir):
current_dir = a_dir
current_fragment = ''
while not current_dir == root_dir:
(current_dir, current_fragment_part) = os.path.split(current_dir)
current_fragment = os.path.join(
current_fragment_part, current_fragment)
return current_fragment
@staticmethod
def get_mirror_dir(directory,
source_root, mirror_root, ignore_root = False):
current_fragment = PathUtil.get_path_fragment(
source_root, directory)
if not current_fragment:
return mirror_root
mirror_directory = mirror_root
if not ignore_root:
mirror_directory = os.path.join(
mirror_root,
os.path.basename(source_root))
mirror_directory = os.path.join(
mirror_directory, current_fragment)
return mirror_directory
@staticmethod
def mirror_dir_tree(directory,
source_root, mirror_root, ignore_root = False):
mirror_directory = PathUtil.get_mirror_dir(
directory, source_root,
mirror_root, ignore_root)
try:
os.makedirs(mirror_directory)
except:
pass
return mirror_directory | [
"os.path.join",
"os.path.basename",
"os.makedirs",
"os.path.split"
] | [((1584, 1632), 'os.path.join', 'os.path.join', (['mirror_directory', 'current_fragment'], {}), '(mirror_directory, current_fragment)\n', (1596, 1632), False, 'import os\n'), ((793, 819), 'os.path.split', 'os.path.split', (['current_dir'], {}), '(current_dir)\n', (806, 819), False, 'import os\n'), ((851, 904), 'os.path.join', 'os.path.join', (['current_fragment_part', 'current_fragment'], {}), '(current_fragment_part, current_fragment)\n', (863, 904), False, 'import os\n'), ((1998, 2027), 'os.makedirs', 'os.makedirs', (['mirror_directory'], {}), '(mirror_directory)\n', (2009, 2027), False, 'import os\n'), ((1493, 1522), 'os.path.basename', 'os.path.basename', (['source_root'], {}), '(source_root)\n', (1509, 1522), False, 'import os\n')] |
from __future__ import annotations
from argparse import ArgumentParser
from pathlib import Path
from .._colors import get_colors
from ..linter import TransformationType, Transformer
from ._base import Command
from ._common import get_paths
class DecorateCommand(Command):
"""Add decorators to your code.
```bash
python3 -m deal decorate project/
```
Options:
+ `--types`: types of decorators to apply. All are enabled by default.
+ `--double-quotes`: use double quotes. Single quotes are used by default.
+ `--nocolor`: do not use colors in the console output.
The exit code is always 0. If you want to test the code for missed decorators,
use the `lint` command instead.
"""
@staticmethod
def init_parser(parser: ArgumentParser) -> None:
parser.add_argument(
'--types',
nargs='*',
choices=[tt.value for tt in TransformationType],
default=sorted(tt.value for tt in TransformationType),
help='types of decorators to apply',
)
parser.add_argument(
'--double-quotes',
action='store_true',
help='use double quotes',
)
parser.add_argument('--nocolor', action='store_true', help='colorless output')
parser.add_argument('paths', nargs='*', default='.')
def __call__(self, args) -> int:
types = {TransformationType(t) for t in args.types}
colors = get_colors(args)
for arg in args.paths:
for path in get_paths(Path(arg)):
self.print('{magenta}{path}{end}'.format(path=path, **colors))
original_code = path.read_text(encoding='utf8')
tr = Transformer(
content=original_code,
path=path,
types=types,
)
if args.double_quotes:
tr = tr._replace(quote='"')
modified_code = tr.transform()
if original_code == modified_code:
self.print(' {blue}no changes{end}'.format(**colors))
else:
path.write_text(modified_code)
self.print(' {green}decorated{end}'.format(**colors))
return 0
| [
"pathlib.Path"
] | [((1547, 1556), 'pathlib.Path', 'Path', (['arg'], {}), '(arg)\n', (1551, 1556), False, 'from pathlib import Path\n')] |
import os,sys,inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, currentdir+'/../../data-structures/stacks_and_queues')
p = currentdir+'/../../data-structures/linked_list'
sys.path.insert(0,p)
from stacks_and_queues import Stack
class PseudoQueue(object):
# internal stack obj
_data = None
def __init__(self):
# create Stack for internal data-struct
self._data = Stack()
def count(self):
# pass through method to underlying data struct
# BigO == O(n)
return self._data.count()
def enqueue(self, val: str) -> bool:
# enqeue a value at the end queue
# BigO == O(1)
self._data.push(val)
return True
def dequeue(self) -> (str, bool):
# dequeue from head of queue
# BigO == O(n)
# Algo: use a second stack, as we need the bottom element on the first stack
# so we are going to unload the first stack, into a temp stack, in order to
# get at the bottom element of the first, then rebuild it from temp to first-stack
retStr = ''
retBool = False
# Empty List? Early return!
b, s = self._data.peek()
if not b:
return retStr, retBool
# reverse the primary stack into temp stack
tempStack = Stack()
while True:
b, s = self._data.peek()
if b == False:
break
val = self._data.pop()
tempStack.push(val)
# top element on tempstack is the bottom of the primary data stack
retStr = tempStack.pop()
# reverse the temp stack back to the primary stack
while True:
b, s = tempStack.peek()
if b == False:
break
val = tempStack.pop()
self._data.push(val)
return retStr, True
| [
"stacks_and_queues.Stack",
"os.path.dirname",
"sys.path.insert",
"inspect.currentframe"
] | [((125, 152), 'os.path.dirname', 'os.path.dirname', (['currentdir'], {}), '(currentdir)\n', (140, 152), False, 'import os, sys, inspect\n'), ((156, 231), 'sys.path.insert', 'sys.path.insert', (['(0)', "(currentdir + '/../../data-structures/stacks_and_queues')"], {}), "(0, currentdir + '/../../data-structures/stacks_and_queues')\n", (171, 231), False, 'import os, sys, inspect\n'), ((286, 307), 'sys.path.insert', 'sys.path.insert', (['(0)', 'p'], {}), '(0, p)\n', (301, 307), False, 'import os, sys, inspect\n'), ((522, 529), 'stacks_and_queues.Stack', 'Stack', ([], {}), '()\n', (527, 529), False, 'from stacks_and_queues import Stack\n'), ((1452, 1459), 'stacks_and_queues.Stack', 'Stack', ([], {}), '()\n', (1457, 1459), False, 'from stacks_and_queues import Stack\n'), ((86, 108), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (106, 108), False, 'import os, sys, inspect\n')] |
import os
import git
from shutil import move
from printing import *
from config import get_config
#########
# GLOBALS
#########
COMMIT_MSG = {
"fonts": "Back up fonts.",
"packages": "Back up packages.",
"configs": "Back up configs.",
"all": "Full back up.",
"dotfiles": "Back up dotfiles."
}
###########
# FUNCTIONS
###########
def git_set_remote(repo, remote_url):
"""
Sets git repo upstream URL and fast-forwards history.
"""
print_path_yellow("Setting remote URL to:", "{}...".format(remote_url))
try:
origin = repo.create_remote('origin', remote_url)
origin.fetch()
except git.CommandError:
print_yellow_bold("Updating existing remote URL...")
repo.delete_remote(repo.remotes.origin)
origin = repo.create_remote('origin', remote_url)
origin.fetch()
def safe_create_gitignore(dir_path):
"""
Creates a .gitignore file that ignores all files listed in config.
"""
gitignore_path = os.path.join(dir_path, ".gitignore")
if os.path.exists(gitignore_path):
print_yellow_bold("Detected .gitignore file.")
pass
else:
print_yellow_bold("Creating default .gitignore...")
files_to_ignore = get_config()["default-gitignore"]
with open(gitignore_path, "w+") as f:
for ignore in files_to_ignore:
f.write("{}\n".format(ignore))
def safe_git_init(dir_path):
"""
If there is no git repo inside the dir_path, intialize one.
Returns tuple of (git.Repo, bool new_git_repo_created)
"""
if not os.path.isdir(os.path.join(dir_path, ".git")):
print_yellow_bold("Initializing new git repo...")
repo = git.Repo.init(dir_path)
return repo, True
else:
print_yellow_bold("Detected git repo.")
repo = git.Repo(dir_path)
return repo, False
def git_add_all_commit_push(repo, message):
"""
Stages all changed files in dir_path and its children folders for commit,
commits them and pushes to a remote if it's configured.
"""
if repo.index.diff(None) or repo.untracked_files:
print_yellow_bold("Making new commit...")
repo.git.add(A=True)
repo.git.commit(m=COMMIT_MSG[message])
print_yellow_bold("Successful commit.")
if "origin" in [remote.name for remote in repo.remotes]:
print_path_yellow("Pushing to master:", "{}...".format(repo.remotes.origin.url))
repo.git.fetch()
repo.git.push("--set-upstream", "origin", "master")
else:
print_yellow_bold("No changes to commit...")
def move_git_repo(source_path, new_path):
"""
Moves git folder and .gitignore to the new backup directory.
"""
git_dir = os.path.join(source_path, '.git')
git_ignore_file = os.path.join(source_path, '.gitignore')
try:
move(git_dir, new_path)
move(git_ignore_file, new_path)
print_blue_bold("Moving git repo to new location.")
except FileNotFoundError:
pass
| [
"os.path.exists",
"shutil.move",
"git.Repo.init",
"os.path.join",
"config.get_config",
"git.Repo"
] | [((917, 953), 'os.path.join', 'os.path.join', (['dir_path', '""".gitignore"""'], {}), "(dir_path, '.gitignore')\n", (929, 953), False, 'import os\n'), ((958, 988), 'os.path.exists', 'os.path.exists', (['gitignore_path'], {}), '(gitignore_path)\n', (972, 988), False, 'import os\n'), ((2476, 2509), 'os.path.join', 'os.path.join', (['source_path', '""".git"""'], {}), "(source_path, '.git')\n", (2488, 2509), False, 'import os\n'), ((2529, 2568), 'os.path.join', 'os.path.join', (['source_path', '""".gitignore"""'], {}), "(source_path, '.gitignore')\n", (2541, 2568), False, 'import os\n'), ((1544, 1567), 'git.Repo.init', 'git.Repo.init', (['dir_path'], {}), '(dir_path)\n', (1557, 1567), False, 'import git\n'), ((1646, 1664), 'git.Repo', 'git.Repo', (['dir_path'], {}), '(dir_path)\n', (1654, 1664), False, 'import git\n'), ((2578, 2601), 'shutil.move', 'move', (['git_dir', 'new_path'], {}), '(git_dir, new_path)\n', (2582, 2601), False, 'from shutil import move\n'), ((2604, 2635), 'shutil.move', 'move', (['git_ignore_file', 'new_path'], {}), '(git_ignore_file, new_path)\n', (2608, 2635), False, 'from shutil import move\n'), ((1127, 1139), 'config.get_config', 'get_config', ([], {}), '()\n', (1137, 1139), False, 'from config import get_config\n'), ((1450, 1480), 'os.path.join', 'os.path.join', (['dir_path', '""".git"""'], {}), "(dir_path, '.git')\n", (1462, 1480), False, 'import os\n')] |
"""Client software that receives the data.
Author: <NAME>
Email : <EMAIL>
"""
from __future__ import print_function, absolute_import
import socket
try:
import cPickle as pickle
except:
import pickle
import zlib
import cv2
buffer_size = 2**17
IP_address = "172.19.11.178"
port = 8080
address = (IP_address, port)
data_receiver = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
data_receiver.bind(address)
while True:
try:
data, address = data_receiver.recvfrom(buffer_size)
frame_data, event_data = pickle.loads(zlib.decompress(data))
if frame_data is not None:
cv2.imshow("frame", frame_data)
if event_data is not None:
cv2.imshow("event", event_data)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
except KeyboardInterrupt:
data_receiver.close()
break
| [
"zlib.decompress",
"cv2.waitKey",
"socket.socket",
"cv2.imshow"
] | [((341, 389), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_DGRAM'], {}), '(socket.AF_INET, socket.SOCK_DGRAM)\n', (354, 389), False, 'import socket\n'), ((546, 567), 'zlib.decompress', 'zlib.decompress', (['data'], {}), '(data)\n', (561, 567), False, 'import zlib\n'), ((617, 648), 'cv2.imshow', 'cv2.imshow', (['"""frame"""', 'frame_data'], {}), "('frame', frame_data)\n", (627, 648), False, 'import cv2\n'), ((697, 728), 'cv2.imshow', 'cv2.imshow', (['"""event"""', 'event_data'], {}), "('event', event_data)\n", (707, 728), False, 'import cv2\n'), ((741, 755), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (752, 755), False, 'import cv2\n')] |
from bs4 import BeautifulSoup as Bs4
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import pandas as pd
def scroll(driver, timeout):
scroll_pause_time = timeout
# Get scroll height
last_height = driver.execute_script("return document.body.scrollHeight")
while True:
# Scroll down to bottom
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
# Wait to load page
sleep(scroll_pause_time)
# Calculate new scroll height and compare with last scroll height
new_height = driver.execute_script("return document.body.scrollHeight")
if new_height == last_height:
# If heights are the same it will exit the function
break
last_height = new_height
driver = webdriver.Chrome(executable_path='C:/WebDrivers/chromedriver.exe')
url = 'https://www.facebook.com/login'
driver.get(url)
driver.implicitly_wait(10)
email = 'Your Email'
email_xpath = """//*[@id="email"]"""
find_email_element = driver.find_element_by_xpath(email_xpath)
find_email_element.send_keys(email)
driver.implicitly_wait(10)
password = '<PASSWORD>'
password_xpath = """//*[@id="pass"]"""
find_password_element = driver.find_element_by_xpath(password_xpath)
find_password_element.send_keys(password)
find_password_element.send_keys(Keys.ENTER)
sleep(6)
group_url = "https://www.facebook.com/groups/group-name/members"
driver.get(group_url)
driver.implicitly_wait(10)
scroll(driver, 2)
names = []
final_names = []
src = driver.page_source
html_soup = Bs4(src, 'lxml')
html_soup.prettify()
for name in html_soup.find_all('a', {'class': "oajrlxb2 g5ia77u1 qu0x051f esr5mh6w e9989ue4 r7d6kgcz rq0escxv nhd2j8a9 nc684nl6 p7hjln8o kvgmc6g5 cxmmr5t8 oygrvhab hcukyx3x jb3vyjys rz4wbd8a qt6c0cv9 a8nywdso i1ao9s8h esuyzwwr f1sip0of lzcic4wl oo9gr5id gpro0wi8 lrazzd5p"}):
text = name.get_text()
list_0 = names.append(text)
for final_name in names[1:]:
final_names.append(final_name)
df = pd.DataFrame(final_names)
df.to_csv('Group_Members.csv', index=True)
driver.quit()
| [
"bs4.BeautifulSoup",
"selenium.webdriver.Chrome",
"pandas.DataFrame",
"time.sleep"
] | [((861, 927), 'selenium.webdriver.Chrome', 'webdriver.Chrome', ([], {'executable_path': '"""C:/WebDrivers/chromedriver.exe"""'}), "(executable_path='C:/WebDrivers/chromedriver.exe')\n", (877, 927), False, 'from selenium import webdriver\n'), ((1438, 1446), 'time.sleep', 'sleep', (['(6)'], {}), '(6)\n', (1443, 1446), False, 'from time import sleep\n'), ((1662, 1678), 'bs4.BeautifulSoup', 'Bs4', (['src', '"""lxml"""'], {}), "(src, 'lxml')\n", (1665, 1678), True, 'from bs4 import BeautifulSoup as Bs4\n'), ((2121, 2146), 'pandas.DataFrame', 'pd.DataFrame', (['final_names'], {}), '(final_names)\n', (2133, 2146), True, 'import pandas as pd\n'), ((507, 531), 'time.sleep', 'sleep', (['scroll_pause_time'], {}), '(scroll_pause_time)\n', (512, 531), False, 'from time import sleep\n')] |
import logging
import pickle
from datetime import datetime
import munch
from rocketgram import Bot, Dispatcher, DefaultValuesMiddleware, ParseModeType
logger = logging.getLogger('mybot')
router = Dispatcher()
def get_bot(token: str):
bot = Bot(token, router=router, globals_class=munch.Munch, context_data_class=munch.Munch)
bot.middleware(DefaultValuesMiddleware(parse_mode=ParseModeType.html))
return bot
| [
"logging.getLogger",
"rocketgram.DefaultValuesMiddleware",
"rocketgram.Bot",
"rocketgram.Dispatcher"
] | [((163, 189), 'logging.getLogger', 'logging.getLogger', (['"""mybot"""'], {}), "('mybot')\n", (180, 189), False, 'import logging\n'), ((200, 212), 'rocketgram.Dispatcher', 'Dispatcher', ([], {}), '()\n', (210, 212), False, 'from rocketgram import Bot, Dispatcher, DefaultValuesMiddleware, ParseModeType\n'), ((250, 339), 'rocketgram.Bot', 'Bot', (['token'], {'router': 'router', 'globals_class': 'munch.Munch', 'context_data_class': 'munch.Munch'}), '(token, router=router, globals_class=munch.Munch, context_data_class=\n munch.Munch)\n', (253, 339), False, 'from rocketgram import Bot, Dispatcher, DefaultValuesMiddleware, ParseModeType\n'), ((354, 408), 'rocketgram.DefaultValuesMiddleware', 'DefaultValuesMiddleware', ([], {'parse_mode': 'ParseModeType.html'}), '(parse_mode=ParseModeType.html)\n', (377, 408), False, 'from rocketgram import Bot, Dispatcher, DefaultValuesMiddleware, ParseModeType\n')] |
import numpy as np
from rotations import rot2, rot3
import mavsim_python_parameters_aerosonde_parameters as P
class Gravity:
def __init__(self, state):
self.mass = P.mass
self.gravity = P.gravity
self.state = state
# Aero quantities
@property
def force(self):
R_ib = self.state.rot
R_bi = R_ib.T
W_i = np.array([0, 0, P.mass*P.gravity])
F = R_bi @ W_i
return F.flatten()
| [
"numpy.array"
] | [((385, 421), 'numpy.array', 'np.array', (['[0, 0, P.mass * P.gravity]'], {}), '([0, 0, P.mass * P.gravity])\n', (393, 421), True, 'import numpy as np\n')] |
from tensorflow.python.framework import ops
import tensorflow as tf
from utilities import model as md
import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
import os
import time
import cv2
def model(photos_train, Y_train, photos_test, Y_test, learning_rate=0.0005,
num_epochs=1500, minibatch_size=128, print_cost=True):
"""
Implements a three-layer tensorflow neural network:
LINEAR->RELU->LINEAR->RELU->LINEAR->SOFTMAX.
Arguments:
X_train -- training set
Y_train -- training set labels
X_test -- test set
Y_test -- test set labels
learning_rate -- learning rate of the optimization
num_epochs -- number of epochs of the optimization loop
minibatch_size -- size of a minibatch
print_cost -- True to print the cost every 100 epochs
Returns:
parameters -- parameters learnt by the model. They can then be used to predict.
"""
im_size = 64
ops.reset_default_graph() # to be able to rerun the model without overwriting tf variables
tf.set_random_seed(1) # to keep consistent results
seed = 3 # to keep consistent results
(n_x, m) = (im_size * im_size * 3, len(photos_train)) # (n_x: input size, m : number of examples in the train set)
n_y = 6 # n_y : output size
costs = [] # To keep track of the cost
# Create Placeholders of shape (n_x, n_y)
X, Y = md.create_placeholders(n_x, n_y)
# Initialize parameters
parameters = md.initialize_parameters()
# Forward propagation: Build the forward propagation in the tensorflow graph
Z3 = md.forward_propagation(X, parameters)
# Cost function: Add cost function to tensorflow graph
cost = md.compute_cost(Z3, Y)
# Backpropagation: Define the tensorflow optimizer
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
# Initialize all the variables
init = tf.global_variables_initializer()
# Start the session to compute the tensorflow graph
with tf.Session() as sess:
# Run the initialization
sess.run(init)
path = os.path.dirname(__file__)
# Do the training loop
for epoch in range(num_epochs):
epoch_cost = 0. # Defines a cost related to an epoch
num_minibatches = int(m / minibatch_size) # number of minibatches of size minibatch_size in the train set
seed = seed + 1
minibatches = md.random_mini_batches_chunk(photos_train, Y_train, minibatch_size, seed)
for minibatch in minibatches:
# Select a minibatch
(minibatch_X, minibatch_Y) = minibatch
x_train_temp = np.array([cv2.imread(os.path.join(path, '../yelpData/resized64/') + i + '.png')
.reshape((1, im_size * im_size * 3)).T
for i in minibatch_X['photo_id']]).T[0]
# Flatten the training and test images
x_train_flatten = x_train_temp
# Normalize image vectors
x_train = x_train_flatten / 255.
# Convert training and test labels to one hot matrices
y_train = md.convert_to_one_hot(minibatch_Y.T, 6)
# IMPORTANT: The line that runs the graph on a minibatch.
# Run the session to execute the "optimizer" and the "cost",
# the feedict should contain a minibatch for (X,Y).
_, minibatch_cost = sess.run([optimizer, cost], feed_dict={X: x_train, Y: y_train})
epoch_cost += minibatch_cost / num_minibatches
# Print the cost every epoch
if print_cost == True and epoch % 5 == 0:
print("Cost after epoch %i: %f" % (epoch, epoch_cost))
if print_cost == True and epoch % 5 == 0:
costs.append(epoch_cost)
# plot the cost
plt.plot(np.squeeze(costs))
plt.ylabel('cost')
plt.xlabel('iterations (per tens)')
plt.title("Learning rate =" + str(learning_rate))
plt.show()
# lets save the parameters in a variable
parameters = sess.run(parameters)
print("Parameters have been trained!")
# Calculate the correct predictions
correct_prediction = tf.equal(tf.argmax(Z3), tf.argmax(Y))
# Calculate accuracy on the test set
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
length = int(len(photos_train))
Y_train = md.convert_to_one_hot(Y_train.T, 6)
acc = 0
for i in range(0, 3):
X_train_temp = np.array([cv2.imread(os.path.join(path, '../yelpData/resized64/') + i + '.png')
.reshape((1, im_size * im_size * 3)).T
for i in photos_train['photo_id']
[int(i * length / 3):int((i+1) * length / 3)]]).T[0]
accuracy_temp = accuracy.eval(
{X: X_train_temp / 255, Y: Y_train[:, int(i * length / 3):int((i+1) * length / 3)]})
acc += accuracy_temp
print("Train Accuracy: ", acc / 3)
X_test = np.array([cv2.imread(os.path.join(path, '../yelpData/resized64/') + i + '.png')
.reshape((1, im_size * im_size * 3)).T
for i in photos_test['photo_id']]).T[0]
X_test = X_test / 255.
Y_test = md.convert_to_one_hot(Y_test.T, 6)
print("Test Accuracy:", accuracy.eval({X: X_test, Y: Y_test}))
return parameters
if __name__ == '__main__':
x, y = md.get_data_chunk()
x_train, x_test, y_train, y_test = train_test_split(x, y,
test_size=.05,
random_state=42,
shuffle=True, stratify=y)
start = time.time()
parameters = model(x_train, y_train, x_test, y_test, num_epochs=500, learning_rate=0.001)
stop = time.time()
print("Time elapsed: " + str(stop - start))
path = os.path.dirname(__file__)
param_path = os.path.join(path, '../yelpData/') + 'parameters_5.npy'
np.save(param_path, parameters)
| [
"tensorflow.python.framework.ops.reset_default_graph",
"matplotlib.pyplot.ylabel",
"utilities.model.forward_propagation",
"utilities.model.get_data_chunk",
"tensorflow.set_random_seed",
"tensorflow.cast",
"numpy.save",
"utilities.model.compute_cost",
"utilities.model.initialize_parameters",
"tenso... | [((969, 994), 'tensorflow.python.framework.ops.reset_default_graph', 'ops.reset_default_graph', ([], {}), '()\n', (992, 994), False, 'from tensorflow.python.framework import ops\n'), ((1065, 1086), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['(1)'], {}), '(1)\n', (1083, 1086), True, 'import tensorflow as tf\n'), ((1415, 1447), 'utilities.model.create_placeholders', 'md.create_placeholders', (['n_x', 'n_y'], {}), '(n_x, n_y)\n', (1437, 1447), True, 'from utilities import model as md\n'), ((1494, 1520), 'utilities.model.initialize_parameters', 'md.initialize_parameters', ([], {}), '()\n', (1518, 1520), True, 'from utilities import model as md\n'), ((1612, 1649), 'utilities.model.forward_propagation', 'md.forward_propagation', (['X', 'parameters'], {}), '(X, parameters)\n', (1634, 1649), True, 'from utilities import model as md\n'), ((1721, 1743), 'utilities.model.compute_cost', 'md.compute_cost', (['Z3', 'Y'], {}), '(Z3, Y)\n', (1736, 1743), True, 'from utilities import model as md\n'), ((1930, 1963), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (1961, 1963), True, 'import tensorflow as tf\n'), ((5647, 5666), 'utilities.model.get_data_chunk', 'md.get_data_chunk', ([], {}), '()\n', (5664, 5666), True, 'from utilities import model as md\n'), ((5706, 5791), 'sklearn.model_selection.train_test_split', 'train_test_split', (['x', 'y'], {'test_size': '(0.05)', 'random_state': '(42)', 'shuffle': '(True)', 'stratify': 'y'}), '(x, y, test_size=0.05, random_state=42, shuffle=True,\n stratify=y)\n', (5722, 5791), False, 'from sklearn.model_selection import train_test_split\n'), ((5968, 5979), 'time.time', 'time.time', ([], {}), '()\n', (5977, 5979), False, 'import time\n'), ((6085, 6096), 'time.time', 'time.time', ([], {}), '()\n', (6094, 6096), False, 'import time\n'), ((6156, 6181), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (6171, 6181), False, 'import os\n'), ((6259, 6290), 'numpy.save', 'np.save', (['param_path', 'parameters'], {}), '(param_path, parameters)\n', (6266, 6290), True, 'import numpy as np\n'), ((2030, 2042), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (2040, 2042), True, 'import tensorflow as tf\n'), ((2124, 2149), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (2139, 2149), False, 'import os\n'), ((3987, 4005), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""cost"""'], {}), "('cost')\n", (3997, 4005), True, 'import matplotlib.pyplot as plt\n'), ((4014, 4049), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""iterations (per tens)"""'], {}), "('iterations (per tens)')\n", (4024, 4049), True, 'import matplotlib.pyplot as plt\n'), ((4116, 4126), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4124, 4126), True, 'import matplotlib.pyplot as plt\n'), ((4555, 4590), 'utilities.model.convert_to_one_hot', 'md.convert_to_one_hot', (['Y_train.T', '(6)'], {}), '(Y_train.T, 6)\n', (4576, 4590), True, 'from utilities import model as md\n'), ((5474, 5508), 'utilities.model.convert_to_one_hot', 'md.convert_to_one_hot', (['Y_test.T', '(6)'], {}), '(Y_test.T, 6)\n', (5495, 5508), True, 'from utilities import model as md\n'), ((6199, 6233), 'os.path.join', 'os.path.join', (['path', '"""../yelpData/"""'], {}), "(path, '../yelpData/')\n", (6211, 6233), False, 'import os\n'), ((1816, 1867), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': 'learning_rate'}), '(learning_rate=learning_rate)\n', (1838, 1867), True, 'import tensorflow as tf\n'), ((2462, 2535), 'utilities.model.random_mini_batches_chunk', 'md.random_mini_batches_chunk', (['photos_train', 'Y_train', 'minibatch_size', 'seed'], {}), '(photos_train, Y_train, minibatch_size, seed)\n', (2490, 2535), True, 'from utilities import model as md\n'), ((3960, 3977), 'numpy.squeeze', 'np.squeeze', (['costs'], {}), '(costs)\n', (3970, 3977), True, 'import numpy as np\n'), ((4349, 4362), 'tensorflow.argmax', 'tf.argmax', (['Z3'], {}), '(Z3)\n', (4358, 4362), True, 'import tensorflow as tf\n'), ((4364, 4376), 'tensorflow.argmax', 'tf.argmax', (['Y'], {}), '(Y)\n', (4373, 4376), True, 'import tensorflow as tf\n'), ((4458, 4494), 'tensorflow.cast', 'tf.cast', (['correct_prediction', '"""float"""'], {}), "(correct_prediction, 'float')\n", (4465, 4494), True, 'import tensorflow as tf\n'), ((3233, 3272), 'utilities.model.convert_to_one_hot', 'md.convert_to_one_hot', (['minibatch_Y.T', '(6)'], {}), '(minibatch_Y.T, 6)\n', (3254, 3272), True, 'from utilities import model as md\n'), ((5234, 5278), 'os.path.join', 'os.path.join', (['path', '"""../yelpData/resized64/"""'], {}), "(path, '../yelpData/resized64/')\n", (5246, 5278), False, 'import os\n'), ((4686, 4730), 'os.path.join', 'os.path.join', (['path', '"""../yelpData/resized64/"""'], {}), "(path, '../yelpData/resized64/')\n", (4698, 4730), False, 'import os\n'), ((2723, 2767), 'os.path.join', 'os.path.join', (['path', '"""../yelpData/resized64/"""'], {}), "(path, '../yelpData/resized64/')\n", (2735, 2767), False, 'import os\n')] |
import FreeCAD
import FPEventDispatcher
from FPInitialPlacement import InitialPlacements
import FPSimServer
import FPUtils
pressEventLocationXY = dict()
rotationAngleAtPress = dict()
class FPSimRotaryPotentiometer(InitialPlacements):
def __init__(self, obj):
InitialPlacements.__init__(self, obj)
obj.addProperty('App::PropertyPythonObject', 'RotationAngleDeg').RotationAngleDeg = 0
obj.addProperty('App::PropertyInteger', 'IncrementsOnWholeArc').IncrementsOnWholeArc = 64
obj.addProperty('App::PropertyFloat', 'MouseSensitivity').MouseSensitivity = 1.0
obj.addProperty('App::PropertyVector', 'RotationAxis').RotationAxis = (0,0,0)
obj.addProperty('App::PropertyVector', 'RotationCenter').RotationCenter = (0,0,0)
obj.addProperty('App::PropertyFloat', 'PositiveRotLimitDeg').PositiveRotLimitDeg = 10.0
obj.addProperty('App::PropertyFloat', 'NegativeRotLimitDeg').NegativeRotLimitDeg = 10.0
obj.addProperty('App::PropertyInteger', 'NumSnapInPositions').NumSnapInPositions = 0
obj.addProperty('App::PropertyBool', 'Motorized').Motorized = False
obj.addProperty('App::PropertyBool', 'TouchSensitive').TouchSensitive = False
obj.Proxy = self
def _registerEventCallbacks(self, objName):
FPEventDispatcher.eventDispatcher.registerForButtonEvent(objName, self.onButtonEvent)
def _unregisterEventCallbacks(self, objName):
FPEventDispatcher.eventDispatcher.unregisterForButtonEvent(objName)
def onChanged(self, obj, prop):
#FreeCAD.Console.PrintMessage("in onChanged obj.Name: " + str(obj.Name) + " obj.Label: " + str(obj.Label) + " prop: " + str(prop) + "\n")
if prop == 'Proxy':
# Called at loading existing object on first place(Placement is not valid yet )
# Called at creation on first place(ToCheck: I think Placement is not valid here yet)
self._registerEventCallbacks(obj.Name)
FPSimServer.dataAquisitionCBHolder.setPotentiometerCB(obj.Name, self.getValue)
elif prop == 'Group':
# Always called when the group changes(new group member inserted or removed)
# or gets created :
# - called after 'proxy'-cb
# - Placement is valid
# - strange thing is at this point there is no child object inside
if not obj.Group:
# Called when Removing all objects from group or when group-obj gets deleted
#FreeCAD.Console.PrintMessage(str(obj.Label) + " Obj has no Group attribute\n")
FPSimServer.dataAquisitionCBHolder.clearPotentiometerCB(obj.Name)
self._unregisterEventCallbacks(obj.Name)
elif self.hasNoChilds(obj):
# Called at object creation
#FreeCAD.Console.PrintMessage(str(obj.Label) + " Obj has Group attribute but no childs\n")
FPSimServer.dataAquisitionCBHolder.setPotentiometerCB(obj.Name, self.getValue)
self._registerEventCallbacks(obj.Name)
else:
# Called When object gets added to a group that already has at least one child
#FreeCAD.Console.PrintMessage(str(obj.Label) + " Obj has Group attribute and childs\n")
pass
self.saveInitialPlacements(obj)
elif prop == 'ExpressionEngine':
# Called at loading existing object at last cb(Placement is valid now)
try:
obj.RotationAngleDeg = 0
self.moveToInitialPlacement(obj)
except KeyError:
self.saveInitialPlacements(obj)
elif prop == 'NumSnapInPositions':
if obj.NumSnapInPositions == 1:
obj.NumSnapInPositions = 2
if obj.NumSnapInPositions < 0:
obj.NumSnapInPositions = 0
# Called on parameter change (followed by execute-cb when it gets applied)
def execute(self, fp):
#FreeCAD.Console.PrintMessage("in execute fp: " + str(fp.Label) + "\n")
# Called when group-obj parameter change or child-objects parameter change gets applied
pass
def onButtonEvent(self, objName, state, pointerPos):
if state == FPEventDispatcher.FPEventDispatcher.PRESSED:
obj = FreeCAD.ActiveDocument.getObject(objName)
pressEventLocationXY[objName] = pointerPos
rotationAngleAtPress[objName] = obj.RotationAngleDeg
FPEventDispatcher.eventDispatcher.registerForLocation(objName, self.onDragged)
else:
FPEventDispatcher.eventDispatcher.unregisterForLocation(objName, self.onDragged)
def onDragged(self, objName, pointerPos):
obj = FreeCAD.ActiveDocument.getObject(objName)
self.setRotation(obj, rotationAngleAtPress[objName] + (pointerPos[1] - pressEventLocationXY[objName][1]) * obj.MouseSensitivity)
def getValue(self, objName):
obj = FreeCAD.ActiveDocument.getObject(objName)
wholeArcDeg = obj.NegativeRotLimitDeg + obj.PositiveRotLimitDeg
rotDeg = obj.RotationAngleDeg + obj.NegativeRotLimitDeg
return int( (rotDeg / wholeArcDeg) * float(obj.IncrementsOnWholeArc - 1) )
def moveToValue(self, objName, value):
obj = FreeCAD.ActiveDocument.getObject(objName)
fullRangeDeg = obj.NegativeRotLimitDeg + obj.PositiveRotLimitDeg
destDeg = value * float(fullRangeDeg) / float(obj.IncrementsOnWholeArc) - obj.NegativeRotLimitDeg
self.setRotation(obj, destDeg)
def setRotation(self, obj, degree):
clampedDeg = FPUtils.clamp(degree, -obj.PositiveRotLimitDeg, obj.NegativeRotLimitDeg)
if obj.NumSnapInPositions:
partDeg = float(obj.NegativeRotLimitDeg + obj.PositiveRotLimitDeg) / float(obj.NumSnapInPositions - 1)
obj.RotationAngleDeg = int((obj.NegativeRotLimitDeg + clampedDeg) / partDeg) * partDeg - obj.NegativeRotLimitDeg
else:
obj.RotationAngleDeg = clampedDeg
rot = FreeCAD.Rotation(obj.RotationAxis, obj.RotationAngleDeg)
for child in obj.Group:
initPlc = self.getInitialPlacement(obj, child.Name)
rotPlacement = FreeCAD.Placement(initPlc.Base, rot, obj.RotationCenter - initPlc.Base)
newRot = rotPlacement.Rotation.multiply( initPlc.Rotation )
newBase = rotPlacement.Base
child.Placement.Base = newBase
child.Placement.Rotation = newRot
class FPSimRotaryPotentiometerViewProvider:
def __init__(self, obj):
obj.Proxy = self
def getIcon(self):
import FPSimDir
return FPSimDir.__dir__ + '/icons/RotPotentiometer.svg'
def createFPSimRotaryPotentiometer():
obj = FreeCAD.ActiveDocument.addObject('App::DocumentObjectGroupPython', 'FPSimRotaryPotentiometer')
FPSimRotaryPotentiometer(obj)
FPSimRotaryPotentiometerViewProvider(obj.ViewObject)
selection = FreeCAD.Gui.Selection.getSelectionEx()
try:
obj.RotationAxis = selection[-1].SubObjects[-1].normalAt(0,0)
obj.RotationCenter = selection[-1].SubObjects[-1].CenterOfMass
for sel_obj in selection:
obj.addObject(sel_obj.Object)
except IndexError:
FreeCAD.Console.PrintError("Usage Error, select objects and a rotation surface\n")
| [
"FreeCAD.ActiveDocument.addObject",
"FPEventDispatcher.eventDispatcher.registerForButtonEvent",
"FreeCAD.ActiveDocument.getObject",
"FreeCAD.Rotation",
"FPUtils.clamp",
"FreeCAD.Console.PrintError",
"FPSimServer.dataAquisitionCBHolder.setPotentiometerCB",
"FreeCAD.Gui.Selection.getSelectionEx",
"FPE... | [((6755, 6853), 'FreeCAD.ActiveDocument.addObject', 'FreeCAD.ActiveDocument.addObject', (['"""App::DocumentObjectGroupPython"""', '"""FPSimRotaryPotentiometer"""'], {}), "('App::DocumentObjectGroupPython',\n 'FPSimRotaryPotentiometer')\n", (6787, 6853), False, 'import FreeCAD\n'), ((6958, 6996), 'FreeCAD.Gui.Selection.getSelectionEx', 'FreeCAD.Gui.Selection.getSelectionEx', ([], {}), '()\n', (6994, 6996), False, 'import FreeCAD\n'), ((273, 310), 'FPInitialPlacement.InitialPlacements.__init__', 'InitialPlacements.__init__', (['self', 'obj'], {}), '(self, obj)\n', (299, 310), False, 'from FPInitialPlacement import InitialPlacements\n'), ((1298, 1388), 'FPEventDispatcher.eventDispatcher.registerForButtonEvent', 'FPEventDispatcher.eventDispatcher.registerForButtonEvent', (['objName', 'self.onButtonEvent'], {}), '(objName, self.\n onButtonEvent)\n', (1354, 1388), False, 'import FPEventDispatcher\n'), ((1443, 1510), 'FPEventDispatcher.eventDispatcher.unregisterForButtonEvent', 'FPEventDispatcher.eventDispatcher.unregisterForButtonEvent', (['objName'], {}), '(objName)\n', (1501, 1510), False, 'import FPEventDispatcher\n'), ((4742, 4783), 'FreeCAD.ActiveDocument.getObject', 'FreeCAD.ActiveDocument.getObject', (['objName'], {}), '(objName)\n', (4774, 4783), False, 'import FreeCAD\n'), ((4969, 5010), 'FreeCAD.ActiveDocument.getObject', 'FreeCAD.ActiveDocument.getObject', (['objName'], {}), '(objName)\n', (5001, 5010), False, 'import FreeCAD\n'), ((5288, 5329), 'FreeCAD.ActiveDocument.getObject', 'FreeCAD.ActiveDocument.getObject', (['objName'], {}), '(objName)\n', (5320, 5329), False, 'import FreeCAD\n'), ((5610, 5682), 'FPUtils.clamp', 'FPUtils.clamp', (['degree', '(-obj.PositiveRotLimitDeg)', 'obj.NegativeRotLimitDeg'], {}), '(degree, -obj.PositiveRotLimitDeg, obj.NegativeRotLimitDeg)\n', (5623, 5682), False, 'import FPUtils\n'), ((6032, 6088), 'FreeCAD.Rotation', 'FreeCAD.Rotation', (['obj.RotationAxis', 'obj.RotationAngleDeg'], {}), '(obj.RotationAxis, obj.RotationAngleDeg)\n', (6048, 6088), False, 'import FreeCAD\n'), ((1975, 2053), 'FPSimServer.dataAquisitionCBHolder.setPotentiometerCB', 'FPSimServer.dataAquisitionCBHolder.setPotentiometerCB', (['obj.Name', 'self.getValue'], {}), '(obj.Name, self.getValue)\n', (2028, 2053), False, 'import FPSimServer\n'), ((4321, 4362), 'FreeCAD.ActiveDocument.getObject', 'FreeCAD.ActiveDocument.getObject', (['objName'], {}), '(objName)\n', (4353, 4362), False, 'import FreeCAD\n'), ((4495, 4573), 'FPEventDispatcher.eventDispatcher.registerForLocation', 'FPEventDispatcher.eventDispatcher.registerForLocation', (['objName', 'self.onDragged'], {}), '(objName, self.onDragged)\n', (4548, 4573), False, 'import FPEventDispatcher\n'), ((4600, 4685), 'FPEventDispatcher.eventDispatcher.unregisterForLocation', 'FPEventDispatcher.eventDispatcher.unregisterForLocation', (['objName', 'self.onDragged'], {}), '(objName, self.onDragged\n )\n', (4655, 4685), False, 'import FPEventDispatcher\n'), ((6212, 6283), 'FreeCAD.Placement', 'FreeCAD.Placement', (['initPlc.Base', 'rot', '(obj.RotationCenter - initPlc.Base)'], {}), '(initPlc.Base, rot, obj.RotationCenter - initPlc.Base)\n', (6229, 6283), False, 'import FreeCAD\n'), ((7254, 7341), 'FreeCAD.Console.PrintError', 'FreeCAD.Console.PrintError', (['"""Usage Error, select objects and a rotation surface\n"""'], {}), "(\n 'Usage Error, select objects and a rotation surface\\n')\n", (7280, 7341), False, 'import FreeCAD\n'), ((2604, 2669), 'FPSimServer.dataAquisitionCBHolder.clearPotentiometerCB', 'FPSimServer.dataAquisitionCBHolder.clearPotentiometerCB', (['obj.Name'], {}), '(obj.Name)\n', (2659, 2669), False, 'import FPSimServer\n'), ((2934, 3012), 'FPSimServer.dataAquisitionCBHolder.setPotentiometerCB', 'FPSimServer.dataAquisitionCBHolder.setPotentiometerCB', (['obj.Name', 'self.getValue'], {}), '(obj.Name, self.getValue)\n', (2987, 3012), False, 'import FPSimServer\n')] |
import os
import scipy
import numpy as np
from ImageStatistics import UsefulImDirectory
import scipy as sp
import ast
from bokeh.charts import Histogram, show
import pandas as pd
class Game(object):
def __init__(self, gamefolder):
self.gamefolder = os.path.abspath(gamefolder)
file = open(os.path.join(gamefolder, "sales"))
self.releaseplayers = int(file.readline().rstrip("\n").split(": ")[1])
file.close()
file = open(os.path.join(gamefolder, "imagelinks"))
self.gameid = int(file.readline().rstrip("\n"))
file.close()
self.images = UsefulImDirectory.ImAggregate(os.path.join(gamefolder, "imgs"))
self.stats = ["means", "variances", "medians", "iqrs", "stddevs", "contrast"]
self.data = None
def getdata(self):
if self.data is None:
self.data = [self.images.getdata("reds"), self.images.getdata("greens"), self.images.getdata("blues")]
return self.data
else:
return self.data
def getcontrast(self):
return self.images.getdata("contrast")
def getplayers(self):
return self.releaseplayers
def calcstat(self, stat):
if stat not in self.stats:
raise AssertionError("Please choose a valid stat")
if stat == "means":
return [np.mean(x) for x in self.getdata()]
elif stat == "variances":
return [np.var(x) for x in self.getdata()]
elif stat == "medians":
return [np.median(x) for x in self.getdata()]
elif stat == "iqrs":
return [sp.stats.iqr(x) for x in self.getdata()]
elif stat == "stddevs":
return [np.std(x) for x in self.getdata()]
elif stat == "contrast":
return self.getcontrast()
def storestats(self):
file = open(os.path.join(self.gamefolder, "stats"), 'w+')
for x in self.stats:
towrite = self.calcstat(x)
file.write(x + ": " + str(towrite) + "\n")
file.close()
def readstats(self):
file = open(os.path.join(self.gamefolder, "stats"))
means = ast.literal_eval(file.readline().rstrip("\n").split(": ")[1])
variances = ast.literal_eval(file.readline().rstrip("\n").split(": ")[1])
medians = ast.literal_eval(file.readline().rstrip("\n").split(": ")[1])
iqrs = ast.literal_eval(file.readline().rstrip("\n").split(": ")[1])
stddevs = ast.literal_eval(file.readline().rstrip("\n").split(": ")[1])
line = file.readline().rstrip("\n").split(": ")[1]
try:
contrast = ast.literal_eval(line)
except ValueError:
tocont = line.replace("nan, ", "")
contrast = ast.literal_eval(tocont)
file.close()
return {"means": means, "variances": variances, "medians": medians, "iqrs": iqrs, "stddevs": stddevs, "contrast": contrast}
def colorhistogram(self, color):
colors = ["red", "green", "blue"]
if color.lower() not in colors:
raise AssertionError("Please pick a valid color")
self.histograms = {}
tohist = {"red": 0, "green": 1, "blue": 2}
self.histograms[color.lower()] = Histogram(pd.DataFrame(self.getdata()[tohist[color.lower()]], columns=[color.lower()]),values=color.lower(),color=color.capitalize(),bins=255)
show(self.histograms[color.lower()]) | [
"numpy.mean",
"numpy.median",
"scipy.stats.iqr",
"os.path.join",
"ast.literal_eval",
"numpy.std",
"os.path.abspath",
"numpy.var"
] | [((262, 289), 'os.path.abspath', 'os.path.abspath', (['gamefolder'], {}), '(gamefolder)\n', (277, 289), False, 'import os\n'), ((310, 343), 'os.path.join', 'os.path.join', (['gamefolder', '"""sales"""'], {}), "(gamefolder, 'sales')\n", (322, 343), False, 'import os\n'), ((465, 503), 'os.path.join', 'os.path.join', (['gamefolder', '"""imagelinks"""'], {}), "(gamefolder, 'imagelinks')\n", (477, 503), False, 'import os\n'), ((634, 666), 'os.path.join', 'os.path.join', (['gamefolder', '"""imgs"""'], {}), "(gamefolder, 'imgs')\n", (646, 666), False, 'import os\n'), ((1885, 1923), 'os.path.join', 'os.path.join', (['self.gamefolder', '"""stats"""'], {}), "(self.gamefolder, 'stats')\n", (1897, 1923), False, 'import os\n'), ((2129, 2167), 'os.path.join', 'os.path.join', (['self.gamefolder', '"""stats"""'], {}), "(self.gamefolder, 'stats')\n", (2141, 2167), False, 'import os\n'), ((2661, 2683), 'ast.literal_eval', 'ast.literal_eval', (['line'], {}), '(line)\n', (2677, 2683), False, 'import ast\n'), ((1354, 1364), 'numpy.mean', 'np.mean', (['x'], {}), '(x)\n', (1361, 1364), True, 'import numpy as np\n'), ((2781, 2805), 'ast.literal_eval', 'ast.literal_eval', (['tocont'], {}), '(tocont)\n', (2797, 2805), False, 'import ast\n'), ((1444, 1453), 'numpy.var', 'np.var', (['x'], {}), '(x)\n', (1450, 1453), True, 'import numpy as np\n'), ((1531, 1543), 'numpy.median', 'np.median', (['x'], {}), '(x)\n', (1540, 1543), True, 'import numpy as np\n'), ((1618, 1633), 'scipy.stats.iqr', 'sp.stats.iqr', (['x'], {}), '(x)\n', (1630, 1633), True, 'import scipy as sp\n'), ((1711, 1720), 'numpy.std', 'np.std', (['x'], {}), '(x)\n', (1717, 1720), True, 'import numpy as np\n')] |
import argparse
import compile_sandbox
import default_nemesis_proto
import logging
import nemesis_pb2
import os
import runner
import shutil
import tempfile
class Judger(object):
def __init__(self, conf, logger):
self.conf = conf
self.logger = logger
self.checker_path = None
self.working_dir = None
self.exe_path = None
self.source_path = None
self.solution_path = None
def __return_custom_failure(self, conf):
self.logger.error('Judger.__return_custom_failure()')
result = default_nemesis_proto.default_CustomInvocationStatus()
result.user_id = conf.user_id
result.time = -1
result.memory = -1
result.compiled = False
result.compile_log = b'internal Nemesis error'
result.status = nemesis_pb2.SYS
result.out = b'internal Nemesis error'
job = default_nemesis_proto.default_JobReturn()
job.custom = True
job.custom_status.CopyFrom(result)
job.system_error = True
return job
def __run__custom(self):
self.logger.info('Judger.__run_custom()')
try:
self.working_dir = tempfile.mkdtemp()
self.logger.info('Judger.__run__custom(): create')
self.source_path = os.path.join(self.working_dir, 'source')
self.exe_path = os.path.join(self.working_dir, 'bin')
except:
self.logger.error('Judger.__run__custom(): create working directory error')
try:
shutil.rmtree(self.working_dir)
except:
pass
return self.__return_custom_failure(self.conf.custom_job)
self.logger.info('Judger.__run__custom(): write source')
try:
with open(self.source_path, 'wb') as source_file:
source_file.write(self.conf.custom_job.source)
except:
shutil.rmtree(self.working_dir)
self.logger.error('Judger.__run__custom(): write source failure')
return self.__return_custom_failure(self.conf.custom_job)
compiler = compile_sandbox.Compiler(
lang = self.conf.custom_job.lang,
src_file = self.source_path,
exe_file = self.exe_path,
logger = self.logger)
self.logger.info('Judger.__run__custom(): compilation started')
try:
compiler_exit_code, compiler_log = compiler.run()
except:
shutil.rmtree(self.working_dir)
self.logger.error('Judger.__run__custom(): compilation sandbox failure')
return self.__return_custom_failure(self.conf.custom_job)
if compiler_exit_code != 0:
self.logger.info('Judger.__run__custom(): compilation failure')
result = default_nemesis_proto.default_CustomInvocationStatus()
result.id = self.conf.custom_job.id
result.user_id = self.conf.custom_job.user_id
result.time = -1
result.memory = -1
result.compiled = False
result.compile_log = compiler_log
result.status = nemesis_pb2.OK
result.out = b'0'
status = default_nemesis_proto.default_JobReturn()
status.custom_status.CopyFrom(result)
status.custom = True
status.system_error = False
return status
self.logger.info('Judger.__run__custom(): compilation success')
try:
self.logger.info('Judger.__run__custom(): run sandbox')
proc = runner.Runner(
logger = self.logger,
exe_path = self.exe_path,
conf = self.conf.custom_job.test,
custom = True)
status, time, memory, out = proc.run()
self.logger.info('Judger.__run__custom(): sandbox exited')
result = default_nemesis_proto.default_CustomInvocationStatus()
result.id = self.conf.custom_job.id
result.user_id = self.conf.custom_job.user_id
result.time = time
result.memory = memory
result.compiled = True
result.compile_log = compiler_log
result.status = status
result.out = out
shutil.rmtree(self.working_dir)
status = default_nemesis_proto.default_JobReturn()
status.custom_status.CopyFrom(result)
status.custom = True
status.system_error = False
return status
except:
shutil.rmtree(self.working_dir)
self.logger.error('Judger.__run__custom(): run sandbox failure')
return self.__return_custom_failure(self.conf.custom_job)
def __return_failure(self, conf):
self.logger.error('Judger.__return_failure()')
result = default_nemesis_proto.default_Status()
result.id = conf.submit.id
result.task_id = conf.submit.task.task_id
result.user_id = conf.submit.user_id
result.lang = conf.submit.lang
result.number_of_groups = 0
result.points = 0
result.acm = False
result.compiled = False
result.compile_log = b'Internal Nemesis error'
result.status = nemesis_pb2.SYS
result.rejudge = conf.submit.rejudge
job = default_nemesis_proto.default_JobReturn()
job.custom = False
job.status.CopyFrom(result)
job.system_error = True
return job
def __generate_outs(self):
self.logger.info('Judger.__generate_outs()')
compiler = compile_sandbox.Compiler(
lang = nemesis_pb2.CXX,
src_file = self.solution_source,
exe_file = self.solution_path,
logger = self.logger)
self.logger.info('Judger.__generate_outs(): compile solution')
try:
compiler_exit_code, compiler_log = compiler.run()
except:
shutil.rmtree(self.working_dir)
self.logger.error('Judger.__generate_outs(): solution compilation failure')
return False
if compiler_exit_code != 0:
shutil.rmtree(self.working_dir)
self.logger.error('Judger.__generate_outs(): solution compilation failure')
self.logger.error(compiler_log)
return False
copy_of_task = nemesis_pb2.Task()
copy_of_task.CopyFrom(self.conf.submit.task)
for grp in self.conf.submit.task.groups:
for test in grp.tests:
self.logger.info('Judger.__generate_outs(): generate ({}, {})'.format(grp.id, test.id))
conf = test
run = runner.Runner(
exe_path = self.solution_path,
conf = conf,
custom = True,
logger = self.logger,
generator = True)
status = run.run()
if status[0] != nemesis_pb2.OK:
return False
out = status[3]
copy_of_task.groups[grp.id - 1].tests[test.id - 1].output = out
self.conf.submit.task.CopyFrom(copy_of_task)
return True
def run(self):
if self.conf.IsInitialized() == False:
self.logger.error('Judger.run(): self.conf.IsInitialized() == False')
raise RuntimeError('self.conf.IsInitialized() == False')
if self.conf.custom:
self.logger.info('Judger.run(): execute custom invocation')
return self.__run__custom()
self.logger.info('Judger.run(): run normal submit')
try:
self.working_dir = tempfile.mkdtemp()
self.logger.info('Judger.run(): create {}'.format(self.working_dir))
self.source_path = os.path.join(self.working_dir, 'source')
self.exe_path = os.path.join(self.working_dir, 'bin')
self.checker_path = os.path.join(self.working_dir, 'checker')
self.checker_source = os.path.join(self.working_dir, 'checker.source')
self.solution_path = os.path.join(self.working_dir, 'solution')
self.solution_source = os.path.join(self.working_dir, 'solution.source')
except:
self.logger.error('Judger.run(): create working directory error')
try:
shutil.rmtree(self.working_dir)
except:
pass
return self.__return_failure(self.conf)
self.logger.info('Judger.run(): write source')
try:
with open(self.source_path, 'wb') as source_file:
source_file.write(self.conf.submit.code)
with open(self.checker_source, 'wb') as checker_file:
checker_file.write(self.conf.submit.task.checker)
self.logger.info('Judger.run(): write solution source')
with open(self.solution_source, 'wb') as solution_file:
solution_file.write(self.conf.submit.task.solution)
except:
shutil.rmtree(self.working_dir)
self.logger.error('Judger.run(): write source failure')
return self.__return_failure(self.conf)
compiler = compile_sandbox.Compiler(
lang=nemesis_pb2.CXX,
src_file=self.checker_source,
exe_file=self.checker_path,
logger=self.logger)
self.logger.info('Judger.run(): compile checker')
try:
compiler_exit_code, compiler_log = compiler.run()
except:
shutil.rmtree(self.working_dir)
self.logger.error('Judger.run(): checker compilation failure')
return self.__return_failure(self.conf)
if compiler_exit_code != 0:
shutil.rmtree(self.working_dir)
self.logger.error('Judger.run(): checker compilation failure')
self.logger.error(compiler_log)
return self.__return_failure(self.conf)
if self.__generate_outs() == False:
self.logger.error('Judger.run(): outs generator failure')
try:
shutil.rmtree(self.working_dir)
except:
pass
return self.__return_failure(self.conf)
compiler = compile_sandbox.Compiler(
lang=self.conf.submit.lang,
src_file=self.source_path,
exe_file=self.exe_path,
logger=self.logger)
self.logger.info('Judger.run(): compilation started')
try:
compiler_exit_code, compiler_log = compiler.run()
except:
shutil.rmtree(self.working_dir)
self.logger.error('Judger.run(): compilation sandbox failure')
return self.__return_failure(self.conf)
if compiler_exit_code != 0:
self.logger.info('Judger.run(): compilation failure')
result = default_nemesis_proto.default_Status()
result.id = self.conf.submit.id
result.task_id = self.conf.submit.task.task_id
result.user_id = self.conf.submit.user_id
result.lang = self.conf.submit.lang
result.number_of_groups = 0
result.points = 0
result.acm = False
result.compiled = False
result.compile_log = compiler_log
result.status = nemesis_pb2.OK
result.rejudge = self.conf.submit.rejudge
shutil.rmtree(self.working_dir)
job = default_nemesis_proto.default_JobReturn()
job.custom = False
job.status.CopyFrom(result)
job.system_error = False
return job
self.logger.info('Judger.run(): compilation success')
result = default_nemesis_proto.default_Status()
result.id = self.conf.submit.id
result.task_id = self.conf.submit.task.task_id
result.user_id = self.conf.submit.user_id
result.lang = self.conf.submit.lang
result.number_of_groups = self.conf.submit.task.number_of_groups
result.points = 0
result.acm = False
result.compiled = True
result.compile_log = compiler_log
result.status = nemesis_pb2.OK
result.rejudge = self.conf.submit.rejudge
correct_grp = 0
for grp in self.conf.submit.task.groups:
grp_status = default_nemesis_proto.default_Status_Group()
grp_status.id = grp.id
grp_status.number_of_tests = grp.number_of_tests
verdict = True
self.logger.info('Judger.run(): group number {}'.format(grp.id))
for test in grp.tests:
self.logger.info('Judger.run(): test number {}'.format(test.id))
proc = runner.Runner(
logger = self.logger,
exe_path = self.exe_path,
conf = test,
src_path = self.source_path,
check_path = self.checker_path,
custom = False)
try:
status = proc.run()
except:
self.logger.error('Judgeer.run(): internal Nemesis error')
shutil.rmtree(self.working_dir)
return self.__return_failure(self.conf)
if status.verdict == False:
verdict = False
grp_status.status = status.status
if status.status != nemesis_pb2.OK:
grp_status.status = status.status
grp_status.tests.extend([status])
grp_status.verdict = verdict
if verdict == True:
correct_grp += 1
if grp_status.status != nemesis_pb2.OK:
result.status = grp_status.status
result.groups.extend([grp_status])
result.points = int(100 / result.number_of_groups * correct_grp)
if correct_grp == result.number_of_groups:
result.acm = True
result.points = 100
shutil.rmtree(self.working_dir)
status = default_nemesis_proto.default_JobReturn()
status.custom = False
status.status.CopyFrom(result)
return status
def main():
parser = argparse.ArgumentParser(description="Nemesis Judger")
parser.add_argument('--submit', dest="submit", required=True, help="submit file")
args = parser.parse_args()
logging.basicConfig(level=logging.INFO)
conf = nemesis_pb2.Job()
try:
with open(args.submit, 'rb') as config_file:
conf.ParseFromString(config_file.read())
except:
raise RuntimeError('read submit error')
judge = Judger(conf=conf, logger=logging.getLogger('WORKER_LOCALHOST_01'))
print(judge.run())
if __name__ == "__main__":
main()
| [
"logging.basicConfig",
"logging.getLogger",
"argparse.ArgumentParser",
"nemesis_pb2.Job",
"os.path.join",
"compile_sandbox.Compiler",
"shutil.rmtree",
"default_nemesis_proto.default_Status",
"runner.Runner",
"default_nemesis_proto.default_CustomInvocationStatus",
"tempfile.mkdtemp",
"default_n... | [((14203, 14256), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Nemesis Judger"""'}), "(description='Nemesis Judger')\n", (14226, 14256), False, 'import argparse\n'), ((14380, 14419), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (14399, 14419), False, 'import logging\n'), ((14431, 14448), 'nemesis_pb2.Job', 'nemesis_pb2.Job', ([], {}), '()\n', (14446, 14448), False, 'import nemesis_pb2\n'), ((559, 613), 'default_nemesis_proto.default_CustomInvocationStatus', 'default_nemesis_proto.default_CustomInvocationStatus', ([], {}), '()\n', (611, 613), False, 'import default_nemesis_proto\n'), ((901, 942), 'default_nemesis_proto.default_JobReturn', 'default_nemesis_proto.default_JobReturn', ([], {}), '()\n', (940, 942), False, 'import default_nemesis_proto\n'), ((2119, 2251), 'compile_sandbox.Compiler', 'compile_sandbox.Compiler', ([], {'lang': 'self.conf.custom_job.lang', 'src_file': 'self.source_path', 'exe_file': 'self.exe_path', 'logger': 'self.logger'}), '(lang=self.conf.custom_job.lang, src_file=self.\n source_path, exe_file=self.exe_path, logger=self.logger)\n', (2143, 2251), False, 'import compile_sandbox\n'), ((4837, 4875), 'default_nemesis_proto.default_Status', 'default_nemesis_proto.default_Status', ([], {}), '()\n', (4873, 4875), False, 'import default_nemesis_proto\n'), ((5321, 5362), 'default_nemesis_proto.default_JobReturn', 'default_nemesis_proto.default_JobReturn', ([], {}), '()\n', (5360, 5362), False, 'import default_nemesis_proto\n'), ((5582, 5713), 'compile_sandbox.Compiler', 'compile_sandbox.Compiler', ([], {'lang': 'nemesis_pb2.CXX', 'src_file': 'self.solution_source', 'exe_file': 'self.solution_path', 'logger': 'self.logger'}), '(lang=nemesis_pb2.CXX, src_file=self.\n solution_source, exe_file=self.solution_path, logger=self.logger)\n', (5606, 5713), False, 'import compile_sandbox\n'), ((6349, 6367), 'nemesis_pb2.Task', 'nemesis_pb2.Task', ([], {}), '()\n', (6365, 6367), False, 'import nemesis_pb2\n'), ((9186, 9314), 'compile_sandbox.Compiler', 'compile_sandbox.Compiler', ([], {'lang': 'nemesis_pb2.CXX', 'src_file': 'self.checker_source', 'exe_file': 'self.checker_path', 'logger': 'self.logger'}), '(lang=nemesis_pb2.CXX, src_file=self.checker_source,\n exe_file=self.checker_path, logger=self.logger)\n', (9210, 9314), False, 'import compile_sandbox\n'), ((10227, 10355), 'compile_sandbox.Compiler', 'compile_sandbox.Compiler', ([], {'lang': 'self.conf.submit.lang', 'src_file': 'self.source_path', 'exe_file': 'self.exe_path', 'logger': 'self.logger'}), '(lang=self.conf.submit.lang, src_file=self.\n source_path, exe_file=self.exe_path, logger=self.logger)\n', (10251, 10355), False, 'import compile_sandbox\n'), ((11692, 11730), 'default_nemesis_proto.default_Status', 'default_nemesis_proto.default_Status', ([], {}), '()\n', (11728, 11730), False, 'import default_nemesis_proto\n'), ((13985, 14016), 'shutil.rmtree', 'shutil.rmtree', (['self.working_dir'], {}), '(self.working_dir)\n', (13998, 14016), False, 'import shutil\n'), ((14043, 14084), 'default_nemesis_proto.default_JobReturn', 'default_nemesis_proto.default_JobReturn', ([], {}), '()\n', (14082, 14084), False, 'import default_nemesis_proto\n'), ((1187, 1205), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (1203, 1205), False, 'import tempfile\n'), ((1300, 1340), 'os.path.join', 'os.path.join', (['self.working_dir', '"""source"""'], {}), "(self.working_dir, 'source')\n", (1312, 1340), False, 'import os\n'), ((1369, 1406), 'os.path.join', 'os.path.join', (['self.working_dir', '"""bin"""'], {}), "(self.working_dir, 'bin')\n", (1381, 1406), False, 'import os\n'), ((2802, 2856), 'default_nemesis_proto.default_CustomInvocationStatus', 'default_nemesis_proto.default_CustomInvocationStatus', ([], {}), '()\n', (2854, 2856), False, 'import default_nemesis_proto\n'), ((3200, 3241), 'default_nemesis_proto.default_JobReturn', 'default_nemesis_proto.default_JobReturn', ([], {}), '()\n', (3239, 3241), False, 'import default_nemesis_proto\n'), ((3566, 3673), 'runner.Runner', 'runner.Runner', ([], {'logger': 'self.logger', 'exe_path': 'self.exe_path', 'conf': 'self.conf.custom_job.test', 'custom': '(True)'}), '(logger=self.logger, exe_path=self.exe_path, conf=self.conf.\n custom_job.test, custom=True)\n', (3579, 3673), False, 'import runner\n'), ((3888, 3942), 'default_nemesis_proto.default_CustomInvocationStatus', 'default_nemesis_proto.default_CustomInvocationStatus', ([], {}), '()\n', (3940, 3942), False, 'import default_nemesis_proto\n'), ((4273, 4304), 'shutil.rmtree', 'shutil.rmtree', (['self.working_dir'], {}), '(self.working_dir)\n', (4286, 4304), False, 'import shutil\n'), ((4327, 4368), 'default_nemesis_proto.default_JobReturn', 'default_nemesis_proto.default_JobReturn', ([], {}), '()\n', (4366, 4368), False, 'import default_nemesis_proto\n'), ((6136, 6167), 'shutil.rmtree', 'shutil.rmtree', (['self.working_dir'], {}), '(self.working_dir)\n', (6149, 6167), False, 'import shutil\n'), ((7654, 7672), 'tempfile.mkdtemp', 'tempfile.mkdtemp', ([], {}), '()\n', (7670, 7672), False, 'import tempfile\n'), ((7785, 7825), 'os.path.join', 'os.path.join', (['self.working_dir', '"""source"""'], {}), "(self.working_dir, 'source')\n", (7797, 7825), False, 'import os\n'), ((7854, 7891), 'os.path.join', 'os.path.join', (['self.working_dir', '"""bin"""'], {}), "(self.working_dir, 'bin')\n", (7866, 7891), False, 'import os\n'), ((7924, 7965), 'os.path.join', 'os.path.join', (['self.working_dir', '"""checker"""'], {}), "(self.working_dir, 'checker')\n", (7936, 7965), False, 'import os\n'), ((8000, 8048), 'os.path.join', 'os.path.join', (['self.working_dir', '"""checker.source"""'], {}), "(self.working_dir, 'checker.source')\n", (8012, 8048), False, 'import os\n'), ((8082, 8124), 'os.path.join', 'os.path.join', (['self.working_dir', '"""solution"""'], {}), "(self.working_dir, 'solution')\n", (8094, 8124), False, 'import os\n'), ((8160, 8209), 'os.path.join', 'os.path.join', (['self.working_dir', '"""solution.source"""'], {}), "(self.working_dir, 'solution.source')\n", (8172, 8209), False, 'import os\n'), ((9731, 9762), 'shutil.rmtree', 'shutil.rmtree', (['self.working_dir'], {}), '(self.working_dir)\n', (9744, 9762), False, 'import shutil\n'), ((10850, 10888), 'default_nemesis_proto.default_Status', 'default_nemesis_proto.default_Status', ([], {}), '()\n', (10886, 10888), False, 'import default_nemesis_proto\n'), ((11386, 11417), 'shutil.rmtree', 'shutil.rmtree', (['self.working_dir'], {}), '(self.working_dir)\n', (11399, 11417), False, 'import shutil\n'), ((11437, 11478), 'default_nemesis_proto.default_JobReturn', 'default_nemesis_proto.default_JobReturn', ([], {}), '()\n', (11476, 11478), False, 'import default_nemesis_proto\n'), ((12308, 12352), 'default_nemesis_proto.default_Status_Group', 'default_nemesis_proto.default_Status_Group', ([], {}), '()\n', (12350, 12352), False, 'import default_nemesis_proto\n'), ((14662, 14702), 'logging.getLogger', 'logging.getLogger', (['"""WORKER_LOCALHOST_01"""'], {}), "('WORKER_LOCALHOST_01')\n", (14679, 14702), False, 'import logging\n'), ((1919, 1950), 'shutil.rmtree', 'shutil.rmtree', (['self.working_dir'], {}), '(self.working_dir)\n', (1932, 1950), False, 'import shutil\n'), ((2481, 2512), 'shutil.rmtree', 'shutil.rmtree', (['self.working_dir'], {}), '(self.working_dir)\n', (2494, 2512), False, 'import shutil\n'), ((4547, 4578), 'shutil.rmtree', 'shutil.rmtree', (['self.working_dir'], {}), '(self.working_dir)\n', (4560, 4578), False, 'import shutil\n'), ((5942, 5973), 'shutil.rmtree', 'shutil.rmtree', (['self.working_dir'], {}), '(self.working_dir)\n', (5955, 5973), False, 'import shutil\n'), ((6660, 6767), 'runner.Runner', 'runner.Runner', ([], {'exe_path': 'self.solution_path', 'conf': 'conf', 'custom': '(True)', 'logger': 'self.logger', 'generator': '(True)'}), '(exe_path=self.solution_path, conf=conf, custom=True, logger=\n self.logger, generator=True)\n', (6673, 6767), False, 'import runner\n'), ((9014, 9045), 'shutil.rmtree', 'shutil.rmtree', (['self.working_dir'], {}), '(self.working_dir)\n', (9027, 9045), False, 'import shutil\n'), ((9523, 9554), 'shutil.rmtree', 'shutil.rmtree', (['self.working_dir'], {}), '(self.working_dir)\n', (9536, 9554), False, 'import shutil\n'), ((10082, 10113), 'shutil.rmtree', 'shutil.rmtree', (['self.working_dir'], {}), '(self.working_dir)\n', (10095, 10113), False, 'import shutil\n'), ((10567, 10598), 'shutil.rmtree', 'shutil.rmtree', (['self.working_dir'], {}), '(self.working_dir)\n', (10580, 10598), False, 'import shutil\n'), ((12693, 12836), 'runner.Runner', 'runner.Runner', ([], {'logger': 'self.logger', 'exe_path': 'self.exe_path', 'conf': 'test', 'src_path': 'self.source_path', 'check_path': 'self.checker_path', 'custom': '(False)'}), '(logger=self.logger, exe_path=self.exe_path, conf=test,\n src_path=self.source_path, check_path=self.checker_path, custom=False)\n', (12706, 12836), False, 'import runner\n'), ((1544, 1575), 'shutil.rmtree', 'shutil.rmtree', (['self.working_dir'], {}), '(self.working_dir)\n', (1557, 1575), False, 'import shutil\n'), ((8337, 8368), 'shutil.rmtree', 'shutil.rmtree', (['self.working_dir'], {}), '(self.working_dir)\n', (8350, 8368), False, 'import shutil\n'), ((13150, 13181), 'shutil.rmtree', 'shutil.rmtree', (['self.working_dir'], {}), '(self.working_dir)\n', (13163, 13181), False, 'import shutil\n')] |
# -*- coding: utf-8 -*-
# ========================================================================
#
# Copyright © <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.
#
# ========================================================================
import argparse
# import csv
import io
import os
import requests
import sys
from datetime import datetime, timedelta
from monthdelta import monthdelta
# from pprint import pprint
from time import sleep
# handle incoming parameters,
# pushing their values into the
# args dictionary for later usage
arg_parser = argparse.ArgumentParser(description='Obtain earthquakes via ReSTful interface')
arg_parser.add_argument('--bgn_date',
type=str,
default='2020-01-01',
help='starting date')
arg_parser.add_argument('--end_date',
type=str,
default='2020-12-31',
help='ending date')
arg_parser.add_argument('--iteration_type',
type=str,
default='months',
choices=('days', 'weeks', 'months', 'years'),
help='iteration type (e.g. days, weeks, months, years)')
arg_parser.add_argument('--how_many_iterations',
type=int,
default=0,
help='how many iterations')
arg_parser.add_argument('--method',
type=str,
default='query',
choices=('count', 'query'),
help='method to use')
arg_parser.add_argument('--format',
type=str,
default='csv',
choices=('csv', 'geojson', 'kml', 'quakeml', 'text', 'xml'),
help='format of output')
arg_parser.add_argument('--min_magnitude',
default=0.0,
type=float,
help='minimum magnitude (0 or greater)')
arg_parser.add_argument('--max_magnitude',
default=10.0,
type=float,
help='maximum magnitude (0 or greater)')
arg_parser.add_argument('--min_depth',
type=float,
default=-100,
help='minimum depth in kilometers (-100 to 1000)')
arg_parser.add_argument('--max_depth',
type=float,
default=1000,
help='maximum depth in kilometers (-100 to 1000)')
arg_parser.add_argument('--sleep_seconds',
type=int,
default=1,
help='sleep seconds')
arg_parser.add_argument('--tgt_path',
type=str,
default='~/Desktop/Quakes/',
help='target file path')
arg_parser.add_argument('--tgt_file_basename',
type=str,
default='ANSS_ComCat_Quakes_20200101_20201231',
help='target file base name')
arg_parser.add_argument('--tgt_file_append',
type=str,
default=False,
help='target file append')
arg_parser.add_argument('--tgt_file_extension',
type=str,
default='.csv',
help='target file extension')
arg_parser.add_argument('--tgt_col_delimiter',
type=str,
default=',',
help='target column delimiter')
arg_parser.add_argument('--tgt_col_quotechar',
type=str,
default='"',
help='target column quote character')
args = arg_parser.parse_args()
def get_next_dates_list(bgn_date,
end_date,
iteration_type,
how_many_iterations):
iteration = 0
bgn_end_dates = []
date_time = bgn_date
max_date = date_time
while date_time <= end_date:
iteration += 1
# print('date_time: %s, end_date: %s, max_date: %s, how_many_iterations: %s, iteration: %s, iteration_type: %s' %(date_time, end_date, max_date, iteration, how_many_iterations, iteration_type))
if how_many_iterations == 0 or iteration <= how_many_iterations:
bgn_date = date_time.strftime('%Y-%m-%d')
try:
if iteration_type == 'days':
date_time += timedelta(days=1)
max_date = (date_time + timedelta(days=1)).strftime('%Y-%m-%d')
elif iteration_type == 'weeks':
date_time += timedelta(weeks=1)
max_date = date_time.strftime('%Y-%m-%d')
elif iteration_type == 'months':
date_time += monthdelta(months=1)
max_date = date_time.strftime('%Y-%m-%d')
elif iteration_type == 'years':
date_time += monthdelta(months=12)
max_date = date_time.strftime('%Y-%m-%d')
else:
date_time += timedelta(days=1)
max_date = (date_time + timedelta(days=1)).strftime('%Y-%m-%d')
print('bgn_date: %s, max_date: %s' % (bgn_date, max_date))
if datetime.strptime(max_date, '%Y-%m-%d') < end_date:
bgn_end_dates.append((bgn_date, max_date))
else:
bgn_end_dates.append((bgn_date, max_date))
break
except Exception as e:
sys.stderr.write('Exception: %s' % e)
else:
break
return bgn_end_dates
if args.tgt_path.startswith('~'):
args.tgt_path = os.path.expanduser(args.tgt_path)
tgt_file_name = os.path.join(args.tgt_path, args.tgt_file_basename + args.tgt_file_extension)
print('tgt_file_name: %s' % tgt_file_name)
# open the target file for write
with io.open(tgt_file_name, 'w', newline='', encoding="utf8") as tgt_file:
first_pass = True
base_url = 'https://earthquake.usgs.gov/fdsnws/event/1/'
base_url += 'count?' if args.method == 'count' else 'query?'
base_url += 'format=%s' % args.format
base_url += '&mindepth=%d' % args.min_depth
base_url += '&maxdepth=%d' % args.max_depth
base_url += '&minmagnitude=%d' % args.min_magnitude if args.min_magnitude is not None else ''
base_url += '&maxmagnitude=%d' % args.max_magnitude if args.max_magnitude is not None else ''
bgn_date = datetime.strptime(args.bgn_date, '%Y-%m-%d')
end_date = datetime.strptime(args.end_date, '%Y-%m-%d')
bgn_end_dates = get_next_dates_list(bgn_date,
end_date,
args.iteration_type,
args.how_many_iterations)
# pprint(bgn_end_dates)
for bgn_end_date in bgn_end_dates:
url = '%s&starttime=%s&endtime=%s' % (base_url, bgn_end_date[0], bgn_end_date[1])
print(url)
try:
response = requests.get(url)
content_decoded = response.content.decode('utf-8')
print(content_decoded)
if first_pass:
if content_decoded.strip() != '':
tgt_file.write(content_decoded.strip() + '\n')
tgt_file.flush()
first_pass = False
else:
if content_decoded[content_decoded.find('\n') + 1:].strip() != '':
tgt_file.write(content_decoded[content_decoded.find('\n') + 1:].strip() + '\n')
tgt_file.flush()
except Exception as e:
print('Bad response. Got an error code:', e)
sleep(args.sleep_seconds)
tgt_file.close()
print('Processing finished!')
| [
"argparse.ArgumentParser",
"datetime.datetime.strptime",
"monthdelta.monthdelta",
"os.path.join",
"io.open",
"time.sleep",
"requests.get",
"sys.stderr.write",
"datetime.timedelta",
"os.path.expanduser"
] | [((1062, 1141), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Obtain earthquakes via ReSTful interface"""'}), "(description='Obtain earthquakes via ReSTful interface')\n", (1085, 1141), False, 'import argparse\n'), ((6423, 6500), 'os.path.join', 'os.path.join', (['args.tgt_path', '(args.tgt_file_basename + args.tgt_file_extension)'], {}), '(args.tgt_path, args.tgt_file_basename + args.tgt_file_extension)\n', (6435, 6500), False, 'import os\n'), ((6373, 6406), 'os.path.expanduser', 'os.path.expanduser', (['args.tgt_path'], {}), '(args.tgt_path)\n', (6391, 6406), False, 'import os\n'), ((6583, 6639), 'io.open', 'io.open', (['tgt_file_name', '"""w"""'], {'newline': '""""""', 'encoding': '"""utf8"""'}), "(tgt_file_name, 'w', newline='', encoding='utf8')\n", (6590, 6639), False, 'import io\n'), ((7152, 7196), 'datetime.datetime.strptime', 'datetime.strptime', (['args.bgn_date', '"""%Y-%m-%d"""'], {}), "(args.bgn_date, '%Y-%m-%d')\n", (7169, 7196), False, 'from datetime import datetime, timedelta\n'), ((7212, 7256), 'datetime.datetime.strptime', 'datetime.strptime', (['args.end_date', '"""%Y-%m-%d"""'], {}), "(args.end_date, '%Y-%m-%d')\n", (7229, 7256), False, 'from datetime import datetime, timedelta\n'), ((8369, 8394), 'time.sleep', 'sleep', (['args.sleep_seconds'], {}), '(args.sleep_seconds)\n', (8374, 8394), False, 'from time import sleep\n'), ((7698, 7715), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (7710, 7715), False, 'import requests\n'), ((5100, 5117), 'datetime.timedelta', 'timedelta', ([], {'days': '(1)'}), '(days=1)\n', (5109, 5117), False, 'from datetime import datetime, timedelta\n'), ((5945, 5984), 'datetime.datetime.strptime', 'datetime.strptime', (['max_date', '"""%Y-%m-%d"""'], {}), "(max_date, '%Y-%m-%d')\n", (5962, 5984), False, 'from datetime import datetime, timedelta\n'), ((6222, 6259), 'sys.stderr.write', 'sys.stderr.write', (["('Exception: %s' % e)"], {}), "('Exception: %s' % e)\n", (6238, 6259), False, 'import sys\n'), ((5283, 5301), 'datetime.timedelta', 'timedelta', ([], {'weeks': '(1)'}), '(weeks=1)\n', (5292, 5301), False, 'from datetime import datetime, timedelta\n'), ((5446, 5466), 'monthdelta.monthdelta', 'monthdelta', ([], {'months': '(1)'}), '(months=1)\n', (5456, 5466), False, 'from monthdelta import monthdelta\n'), ((5162, 5179), 'datetime.timedelta', 'timedelta', ([], {'days': '(1)'}), '(days=1)\n', (5171, 5179), False, 'from datetime import datetime, timedelta\n'), ((5610, 5631), 'monthdelta.monthdelta', 'monthdelta', ([], {'months': '(12)'}), '(months=12)\n', (5620, 5631), False, 'from monthdelta import monthdelta\n'), ((5749, 5766), 'datetime.timedelta', 'timedelta', ([], {'days': '(1)'}), '(days=1)\n', (5758, 5766), False, 'from datetime import datetime, timedelta\n'), ((5811, 5828), 'datetime.timedelta', 'timedelta', ([], {'days': '(1)'}), '(days=1)\n', (5820, 5828), False, 'from datetime import datetime, timedelta\n')] |
from .ranking import CreditRanking
from .interleaving_method import InterleavingMethod
import numpy as np
from scipy.optimize import linprog
class Optimized(InterleavingMethod):
'''
Optimized Interleaving
Args:
lists: lists of document IDs
max_length: the maximum length of resultant interleaving.
If this is None (default), it is set to the minimum length
of the given lists.
sample_num: If this is None (default), an interleaved ranking is
generated every time when `interleave` is called.
Otherwise, `sample_num` rankings are sampled in the
initialization, one of which is returned when `interleave`
is called.
credit_func: either 'inverse' (1/rank) or 'negative' (-rank)
'''
def __init__(self, lists, max_length=None, sample_num=None,
credit_func='inverse', secure_sampling=False):
'''
lists: lists of document IDs
max_length: the maximum length of resultant interleaving.
If this is None (default), it is set to the minimum length
of the given lists.
sample_num: If this is None (default), an interleaved ranking is
generated every time when `interleave` is called.
Otherwise, `sample_num` rankings are sampled in the
initialization, one of which is returned when `interleave`
is called.
credit_func: either 'inverse' (1/rank) or 'negative' (-rank)
'''
if sample_num is None:
raise ValueError('sample_num cannot be None, '
+ 'i.e. the initial sampling is necessary')
if credit_func == 'inverse':
self._credit_func = lambda x: 1.0 / x
elif credit_func == 'negative':
self._credit_func = lambda x: -x
else:
raise ValueError('credit_func should be either inverse or negative')
self._secure_sampling = secure_sampling
super(Optimized, self).__init__(lists,
max_length=max_length, sample_num=sample_num)
# self._rankings (sampled rankings) is obtained here
res = self._compute_probabilities(lists, self._rankings)
is_success, self._probabilities, _ = res
self._probabilities /= np.sum(self._probabilities)
if not is_success:
raise ValueError('Optimization failed')
def _sample_rankings(self):
'''
Sample `sample_num` rankings
'''
distribution = {}
if self._secure_sampling:
rankings = set()
for _ in range(self.sample_num):
rankings.add(self._sample(self.max_length, self.lists))
for ranking in rankings:
distribution[ranking] = 1.0 / len(rankings)
else:
while len(distribution) < self.sample_num:
ranking = self._sample(self.max_length, self.lists)
distribution[ranking] = 1.0 / self.sample_num
self._rankings, self._probabilities = zip(*distribution.items())
def _sample(self, max_length, lists):
'''
Prefix constraint sampling
(Multileaved Comparisons for Fast Online Evaluation, CIKM'14)
max_length: the maximum length of resultant interleaving
lists: lists of document IDs
Return an instance of Ranking
'''
num_rankers = len(lists)
result = CreditRanking(num_rankers)
teams = set(range(num_rankers))
while len(result) < max_length:
if len(teams) == 0:
break
selected_team = np.random.choice(list(teams))
docs = [x for x in lists[selected_team] if not x in result]
if len(docs) > 0:
selected_doc = docs[0]
result.append(selected_doc)
else:
teams.remove(selected_team)
# assign credits
for docid in result:
for team in result.credits:
if docid in lists[team]:
rank = lists[team].index(docid) + 1
else:
rank = len(lists[team]) + 1
result.credits[team][docid] = self._credit_func(rank)
return result
def _compute_probabilities(self, lists, rankings):
'''
Solve the optimization problem in
(Multileaved Comparisons for Fast Online Evaluation, CIKM'14)
lists: lists of document IDs
rankings: a list of Ranking instances
Return a list of probabilities for input rankings
'''
# probability constraints
A_p_sum = np.array([1]*len(rankings))
# unbiasedness constraints
ub_cons = self._unbiasedness_constraints(lists, rankings)
# sensitivity
sensitivity = self._sensitivity(lists, rankings)
# constraints
A_eq = np.vstack((A_p_sum, ub_cons))
b_eq = np.array([1.0] + [0.0]*ub_cons.shape[0])
# solving the optimization problem
res = linprog(sensitivity, # objective function
A_eq=A_eq, b_eq=b_eq, # constraints
bounds=[(0, 1)]*len(rankings) # 0 <= p <= 1
)
return res.success, res.x, res.fun
def _unbiasedness_constraints(self, lists, rankings):
'''
for each k and team x, for a certain c_k:
sum_{L_i} {p_i} * sum^k_{j=1} ranking.credits[x][d_j] = c_k
In other words,
sum_{L_i} {p_i} * sum^k_{j=1}
(ranking.credits[x][d_j] - ranking.credits[x+1][d_j]) = 0
'''
result = []
credits = np.zeros((self.max_length, len(rankings), len(lists)))
for rid, ranking in enumerate(rankings):
for idx, docid in enumerate(ranking):
for team in ranking.credits:
credits[idx, rid, team] = ranking.credits[team][docid]
if idx > 0:
credits[idx, rid, team] += credits[idx-1, rid, team]
for i in range(len(lists) - 1):
result.append(credits[:, :, i] - credits[:, :, i+1])
result = np.vstack(result)
return result
def _sensitivity(self, lists, rankings):
'''
Expected variance
'''
# compute the mean of each ranking
mu = np.zeros(len(rankings))
for rid, ranking in enumerate(rankings):
for idx, docid in enumerate(ranking):
click_prob = 1.0 / (idx + 1)
credit = np.sum(
[ranking.credits[x][docid] for x in ranking.credits])
mu[rid] += click_prob * credit
mu /= len(lists)
# compute the variance
var = np.zeros(len(rankings))
for rid, ranking in enumerate(rankings):
for x in ranking.credits:
v = 0.0
for idx, docid in enumerate(ranking):
click_prob = 1.0 / (idx + 1)
if docid in ranking.credits[x]:
v += click_prob * ranking.credits[x][docid]
v -= mu[rid]
var[rid] += v ** 2
return var
@classmethod
def compute_scores(cls, ranking, clicks):
'''
ranking: an instance of Ranking
clicks: a list of indices clicked by a user
Return a list of scores of each ranker.
'''
return {i: sum([ranking.credits[i][ranking[c]] for c in clicks])
for i in ranking.credits}
| [
"numpy.sum",
"numpy.array",
"numpy.vstack"
] | [((2386, 2413), 'numpy.sum', 'np.sum', (['self._probabilities'], {}), '(self._probabilities)\n', (2392, 2413), True, 'import numpy as np\n'), ((4982, 5011), 'numpy.vstack', 'np.vstack', (['(A_p_sum, ub_cons)'], {}), '((A_p_sum, ub_cons))\n', (4991, 5011), True, 'import numpy as np\n'), ((5027, 5069), 'numpy.array', 'np.array', (['([1.0] + [0.0] * ub_cons.shape[0])'], {}), '([1.0] + [0.0] * ub_cons.shape[0])\n', (5035, 5069), True, 'import numpy as np\n'), ((6217, 6234), 'numpy.vstack', 'np.vstack', (['result'], {}), '(result)\n', (6226, 6234), True, 'import numpy as np\n'), ((6602, 6662), 'numpy.sum', 'np.sum', (['[ranking.credits[x][docid] for x in ranking.credits]'], {}), '([ranking.credits[x][docid] for x in ranking.credits])\n', (6608, 6662), True, 'import numpy as np\n')] |
from collections import defaultdict
class HashTable(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
#initialize a hash table object
hash_table = defaultdict(int)
#for each num in list nums
for num in nums:
#add value to key if duplicate is met
hash_table[num] += 1
#for each key in hash table
for key in hash_table:
#if key has 1 value
if hash_table[key] == 1:
#return key
return key
| [
"collections.defaultdict"
] | [((230, 246), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (241, 246), False, 'from collections import defaultdict\n')] |